1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 /// \file 11 /// Custom DAG lowering for SI 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifdef _MSC_VER 16 // Provide M_PI. 17 #define _USE_MATH_DEFINES 18 #endif 19 20 #include "SIISelLowering.h" 21 #include "AMDGPU.h" 22 #include "AMDGPUIntrinsicInfo.h" 23 #include "AMDGPUSubtarget.h" 24 #include "AMDGPUTargetMachine.h" 25 #include "SIDefines.h" 26 #include "SIInstrInfo.h" 27 #include "SIMachineFunctionInfo.h" 28 #include "SIRegisterInfo.h" 29 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 30 #include "Utils/AMDGPUBaseInfo.h" 31 #include "llvm/ADT/APFloat.h" 32 #include "llvm/ADT/APInt.h" 33 #include "llvm/ADT/ArrayRef.h" 34 #include "llvm/ADT/BitVector.h" 35 #include "llvm/ADT/SmallVector.h" 36 #include "llvm/ADT/Statistic.h" 37 #include "llvm/ADT/StringRef.h" 38 #include "llvm/ADT/StringSwitch.h" 39 #include "llvm/ADT/Twine.h" 40 #include "llvm/CodeGen/Analysis.h" 41 #include "llvm/CodeGen/CallingConvLower.h" 42 #include "llvm/CodeGen/DAGCombine.h" 43 #include "llvm/CodeGen/ISDOpcodes.h" 44 #include "llvm/CodeGen/MachineBasicBlock.h" 45 #include "llvm/CodeGen/MachineFrameInfo.h" 46 #include "llvm/CodeGen/MachineFunction.h" 47 #include "llvm/CodeGen/MachineInstr.h" 48 #include "llvm/CodeGen/MachineInstrBuilder.h" 49 #include "llvm/CodeGen/MachineMemOperand.h" 50 #include "llvm/CodeGen/MachineModuleInfo.h" 51 #include "llvm/CodeGen/MachineOperand.h" 52 #include "llvm/CodeGen/MachineRegisterInfo.h" 53 #include "llvm/CodeGen/SelectionDAG.h" 54 #include "llvm/CodeGen/SelectionDAGNodes.h" 55 #include "llvm/CodeGen/TargetCallingConv.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/Constants.h" 59 #include "llvm/IR/DataLayout.h" 60 #include "llvm/IR/DebugLoc.h" 61 #include "llvm/IR/DerivedTypes.h" 62 #include "llvm/IR/DiagnosticInfo.h" 63 #include "llvm/IR/Function.h" 64 #include "llvm/IR/GlobalValue.h" 65 #include "llvm/IR/InstrTypes.h" 66 #include "llvm/IR/Instruction.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/IntrinsicInst.h" 69 #include "llvm/IR/Type.h" 70 #include "llvm/Support/Casting.h" 71 #include "llvm/Support/CodeGen.h" 72 #include "llvm/Support/CommandLine.h" 73 #include "llvm/Support/Compiler.h" 74 #include "llvm/Support/ErrorHandling.h" 75 #include "llvm/Support/KnownBits.h" 76 #include "llvm/Support/MachineValueType.h" 77 #include "llvm/Support/MathExtras.h" 78 #include "llvm/Target/TargetOptions.h" 79 #include <cassert> 80 #include <cmath> 81 #include <cstdint> 82 #include <iterator> 83 #include <tuple> 84 #include <utility> 85 #include <vector> 86 87 using namespace llvm; 88 89 #define DEBUG_TYPE "si-lower" 90 91 STATISTIC(NumTailCalls, "Number of tail calls"); 92 93 static cl::opt<bool> EnableVGPRIndexMode( 94 "amdgpu-vgpr-index-mode", 95 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"), 96 cl::init(false)); 97 98 static cl::opt<unsigned> AssumeFrameIndexHighZeroBits( 99 "amdgpu-frame-index-zero-bits", 100 cl::desc("High bits of frame index assumed to be zero"), 101 cl::init(5), 102 cl::ReallyHidden); 103 104 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 105 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 106 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 107 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 108 return AMDGPU::SGPR0 + Reg; 109 } 110 } 111 llvm_unreachable("Cannot allocate sgpr"); 112 } 113 114 SITargetLowering::SITargetLowering(const TargetMachine &TM, 115 const SISubtarget &STI) 116 : AMDGPUTargetLowering(TM, STI) { 117 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 118 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 119 120 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass); 121 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 122 123 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 124 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 125 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 126 127 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass); 128 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass); 129 130 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass); 131 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 132 133 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass); 134 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 135 136 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass); 137 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 138 139 if (Subtarget->has16BitInsts()) { 140 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass); 141 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass); 142 143 // Unless there are also VOP3P operations, not operations are really legal. 144 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass); 145 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass); 146 } 147 148 computeRegisterProperties(STI.getRegisterInfo()); 149 150 // We need to custom lower vector stores from local memory 151 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 152 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 153 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 154 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 155 setOperationAction(ISD::LOAD, MVT::i1, Custom); 156 157 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 158 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 159 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 160 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 161 setOperationAction(ISD::STORE, MVT::i1, Custom); 162 163 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 164 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 165 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 166 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 167 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 168 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 169 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 170 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 171 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 172 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 173 174 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 175 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 176 177 setOperationAction(ISD::SELECT, MVT::i1, Promote); 178 setOperationAction(ISD::SELECT, MVT::i64, Custom); 179 setOperationAction(ISD::SELECT, MVT::f64, Promote); 180 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 181 182 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 183 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 184 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 185 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 186 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 187 188 setOperationAction(ISD::SETCC, MVT::i1, Promote); 189 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 190 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 191 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 192 193 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 194 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 195 196 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 197 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 198 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 199 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 200 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 201 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 202 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 203 204 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 205 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 206 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 207 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 208 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 209 210 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 211 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 212 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 213 214 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 215 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 216 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 217 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 218 219 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 220 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 221 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 222 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 223 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 224 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 225 226 setOperationAction(ISD::UADDO, MVT::i32, Legal); 227 setOperationAction(ISD::USUBO, MVT::i32, Legal); 228 229 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 230 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 231 232 #if 0 233 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 234 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 235 #endif 236 237 //setOperationAction(ISD::ADDC, MVT::i64, Expand); 238 //setOperationAction(ISD::SUBC, MVT::i64, Expand); 239 240 // We only support LOAD/STORE and vector manipulation ops for vectors 241 // with > 4 elements. 242 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 243 MVT::v2i64, MVT::v2f64}) { 244 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 245 switch (Op) { 246 case ISD::LOAD: 247 case ISD::STORE: 248 case ISD::BUILD_VECTOR: 249 case ISD::BITCAST: 250 case ISD::EXTRACT_VECTOR_ELT: 251 case ISD::INSERT_VECTOR_ELT: 252 case ISD::INSERT_SUBVECTOR: 253 case ISD::EXTRACT_SUBVECTOR: 254 case ISD::SCALAR_TO_VECTOR: 255 break; 256 case ISD::CONCAT_VECTORS: 257 setOperationAction(Op, VT, Custom); 258 break; 259 default: 260 setOperationAction(Op, VT, Expand); 261 break; 262 } 263 } 264 } 265 266 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 267 // is expanded to avoid having two separate loops in case the index is a VGPR. 268 269 // Most operations are naturally 32-bit vector operations. We only support 270 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 271 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 272 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 273 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 274 275 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 276 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 277 278 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 279 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 280 281 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 282 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 283 } 284 285 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 286 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 287 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 288 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 289 290 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 291 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 292 293 // Avoid stack access for these. 294 // TODO: Generalize to more vector types. 295 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 296 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 297 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 298 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 299 300 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 301 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 302 303 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 304 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 305 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 306 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 307 308 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 309 // and output demarshalling 310 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 311 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 312 313 // We can't return success/failure, only the old value, 314 // let LLVM add the comparison 315 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 316 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 317 318 if (getSubtarget()->hasFlatAddressSpace()) { 319 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 320 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 321 } 322 323 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 324 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 325 326 // On SI this is s_memtime and s_memrealtime on VI. 327 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 328 setOperationAction(ISD::TRAP, MVT::Other, Custom); 329 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 330 331 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 332 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 333 334 if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) { 335 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 336 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 337 setOperationAction(ISD::FRINT, MVT::f64, Legal); 338 } 339 340 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 341 342 setOperationAction(ISD::FSIN, MVT::f32, Custom); 343 setOperationAction(ISD::FCOS, MVT::f32, Custom); 344 setOperationAction(ISD::FDIV, MVT::f32, Custom); 345 setOperationAction(ISD::FDIV, MVT::f64, Custom); 346 347 if (Subtarget->has16BitInsts()) { 348 setOperationAction(ISD::Constant, MVT::i16, Legal); 349 350 setOperationAction(ISD::SMIN, MVT::i16, Legal); 351 setOperationAction(ISD::SMAX, MVT::i16, Legal); 352 353 setOperationAction(ISD::UMIN, MVT::i16, Legal); 354 setOperationAction(ISD::UMAX, MVT::i16, Legal); 355 356 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 357 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 358 359 setOperationAction(ISD::ROTR, MVT::i16, Promote); 360 setOperationAction(ISD::ROTL, MVT::i16, Promote); 361 362 setOperationAction(ISD::SDIV, MVT::i16, Promote); 363 setOperationAction(ISD::UDIV, MVT::i16, Promote); 364 setOperationAction(ISD::SREM, MVT::i16, Promote); 365 setOperationAction(ISD::UREM, MVT::i16, Promote); 366 367 setOperationAction(ISD::BSWAP, MVT::i16, Promote); 368 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 369 370 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 371 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 372 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 373 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 374 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 375 376 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 377 378 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 379 380 setOperationAction(ISD::LOAD, MVT::i16, Custom); 381 382 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 383 384 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 385 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 386 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 387 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 388 389 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 390 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 391 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote); 392 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote); 393 394 // F16 - Constant Actions. 395 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 396 397 // F16 - Load/Store Actions. 398 setOperationAction(ISD::LOAD, MVT::f16, Promote); 399 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 400 setOperationAction(ISD::STORE, MVT::f16, Promote); 401 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 402 403 // F16 - VOP1 Actions. 404 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 405 setOperationAction(ISD::FCOS, MVT::f16, Promote); 406 setOperationAction(ISD::FSIN, MVT::f16, Promote); 407 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 408 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 409 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 410 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 411 setOperationAction(ISD::FROUND, MVT::f16, Custom); 412 413 // F16 - VOP2 Actions. 414 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 415 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 416 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 417 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 418 setOperationAction(ISD::FDIV, MVT::f16, Custom); 419 420 // F16 - VOP3 Actions. 421 setOperationAction(ISD::FMA, MVT::f16, Legal); 422 if (!Subtarget->hasFP16Denormals()) 423 setOperationAction(ISD::FMAD, MVT::f16, Legal); 424 425 for (MVT VT : {MVT::v2i16, MVT::v2f16}) { 426 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 427 switch (Op) { 428 case ISD::LOAD: 429 case ISD::STORE: 430 case ISD::BUILD_VECTOR: 431 case ISD::BITCAST: 432 case ISD::EXTRACT_VECTOR_ELT: 433 case ISD::INSERT_VECTOR_ELT: 434 case ISD::INSERT_SUBVECTOR: 435 case ISD::EXTRACT_SUBVECTOR: 436 case ISD::SCALAR_TO_VECTOR: 437 break; 438 case ISD::CONCAT_VECTORS: 439 setOperationAction(Op, VT, Custom); 440 break; 441 default: 442 setOperationAction(Op, VT, Expand); 443 break; 444 } 445 } 446 } 447 448 // XXX - Do these do anything? Vector constants turn into build_vector. 449 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 450 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 451 452 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 453 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 454 455 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 456 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 457 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 458 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 459 460 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 461 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 462 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 463 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 464 465 setOperationAction(ISD::AND, MVT::v2i16, Promote); 466 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 467 setOperationAction(ISD::OR, MVT::v2i16, Promote); 468 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 469 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 470 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 471 472 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 473 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 474 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 475 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 476 477 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 478 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 479 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 480 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 481 482 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 483 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 484 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 485 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 486 487 if (!Subtarget->hasVOP3PInsts()) { 488 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 489 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 490 } 491 492 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 493 // This isn't really legal, but this avoids the legalizer unrolling it (and 494 // allows matching fneg (fabs x) patterns) 495 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 496 } 497 498 if (Subtarget->hasVOP3PInsts()) { 499 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 500 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 501 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 502 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 503 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 504 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 505 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 506 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 507 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 508 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 509 510 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 511 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 512 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 513 setOperationAction(ISD::FMINNUM, MVT::v2f16, Legal); 514 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Legal); 515 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 516 517 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 518 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 519 } 520 521 if (Subtarget->has16BitInsts()) { 522 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 523 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 524 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 525 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 526 } else { 527 // Legalization hack. 528 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 529 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 530 } 531 532 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 533 setOperationAction(ISD::SELECT, VT, Custom); 534 } 535 536 setTargetDAGCombine(ISD::ADD); 537 setTargetDAGCombine(ISD::ADDCARRY); 538 setTargetDAGCombine(ISD::SUB); 539 setTargetDAGCombine(ISD::SUBCARRY); 540 setTargetDAGCombine(ISD::FADD); 541 setTargetDAGCombine(ISD::FSUB); 542 setTargetDAGCombine(ISD::FMINNUM); 543 setTargetDAGCombine(ISD::FMAXNUM); 544 setTargetDAGCombine(ISD::SMIN); 545 setTargetDAGCombine(ISD::SMAX); 546 setTargetDAGCombine(ISD::UMIN); 547 setTargetDAGCombine(ISD::UMAX); 548 setTargetDAGCombine(ISD::SETCC); 549 setTargetDAGCombine(ISD::AND); 550 setTargetDAGCombine(ISD::OR); 551 setTargetDAGCombine(ISD::XOR); 552 setTargetDAGCombine(ISD::SINT_TO_FP); 553 setTargetDAGCombine(ISD::UINT_TO_FP); 554 setTargetDAGCombine(ISD::FCANONICALIZE); 555 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 556 setTargetDAGCombine(ISD::ZERO_EXTEND); 557 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 558 setTargetDAGCombine(ISD::BUILD_VECTOR); 559 560 // All memory operations. Some folding on the pointer operand is done to help 561 // matching the constant offsets in the addressing modes. 562 setTargetDAGCombine(ISD::LOAD); 563 setTargetDAGCombine(ISD::STORE); 564 setTargetDAGCombine(ISD::ATOMIC_LOAD); 565 setTargetDAGCombine(ISD::ATOMIC_STORE); 566 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 567 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 568 setTargetDAGCombine(ISD::ATOMIC_SWAP); 569 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 570 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 571 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 572 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 573 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 574 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 575 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 576 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 577 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 578 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 579 580 setSchedulingPreference(Sched::RegPressure); 581 } 582 583 const SISubtarget *SITargetLowering::getSubtarget() const { 584 return static_cast<const SISubtarget *>(Subtarget); 585 } 586 587 //===----------------------------------------------------------------------===// 588 // TargetLowering queries 589 //===----------------------------------------------------------------------===// 590 591 // v_mad_mix* support a conversion from f16 to f32. 592 // 593 // There is only one special case when denormals are enabled we don't currently, 594 // where this is OK to use. 595 bool SITargetLowering::isFPExtFoldable(unsigned Opcode, 596 EVT DestVT, EVT SrcVT) const { 597 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 598 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 599 DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() && 600 SrcVT.getScalarType() == MVT::f16; 601 } 602 603 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 604 // SI has some legal vector types, but no legal vector operations. Say no 605 // shuffles are legal in order to prefer scalarizing some vector operations. 606 return false; 607 } 608 609 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 610 const CallInst &CI, 611 MachineFunction &MF, 612 unsigned IntrID) const { 613 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 614 AMDGPU::lookupRsrcIntrinsicByIntr(IntrID)) { 615 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 616 (Intrinsic::ID)IntrID); 617 if (Attr.hasFnAttribute(Attribute::ReadNone)) 618 return false; 619 620 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 621 622 if (RsrcIntr->IsImage) { 623 Info.ptrVal = MFI->getImagePSV( 624 *MF.getSubtarget<SISubtarget>().getInstrInfo(), 625 CI.getArgOperand(RsrcIntr->RsrcArg)); 626 Info.align = 0; 627 } else { 628 Info.ptrVal = MFI->getBufferPSV( 629 *MF.getSubtarget<SISubtarget>().getInstrInfo(), 630 CI.getArgOperand(RsrcIntr->RsrcArg)); 631 } 632 633 Info.flags = MachineMemOperand::MODereferenceable; 634 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 635 Info.opc = ISD::INTRINSIC_W_CHAIN; 636 Info.memVT = MVT::getVT(CI.getType()); 637 Info.flags |= MachineMemOperand::MOLoad; 638 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 639 Info.opc = ISD::INTRINSIC_VOID; 640 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 641 Info.flags |= MachineMemOperand::MOStore; 642 } else { 643 // Atomic 644 Info.opc = ISD::INTRINSIC_W_CHAIN; 645 Info.memVT = MVT::getVT(CI.getType()); 646 Info.flags = MachineMemOperand::MOLoad | 647 MachineMemOperand::MOStore | 648 MachineMemOperand::MODereferenceable; 649 650 // XXX - Should this be volatile without known ordering? 651 Info.flags |= MachineMemOperand::MOVolatile; 652 } 653 return true; 654 } 655 656 switch (IntrID) { 657 case Intrinsic::amdgcn_atomic_inc: 658 case Intrinsic::amdgcn_atomic_dec: 659 case Intrinsic::amdgcn_ds_fadd: 660 case Intrinsic::amdgcn_ds_fmin: 661 case Intrinsic::amdgcn_ds_fmax: { 662 Info.opc = ISD::INTRINSIC_W_CHAIN; 663 Info.memVT = MVT::getVT(CI.getType()); 664 Info.ptrVal = CI.getOperand(0); 665 Info.align = 0; 666 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 667 668 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 669 if (!Vol || !Vol->isZero()) 670 Info.flags |= MachineMemOperand::MOVolatile; 671 672 return true; 673 } 674 675 default: 676 return false; 677 } 678 } 679 680 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 681 SmallVectorImpl<Value*> &Ops, 682 Type *&AccessTy) const { 683 switch (II->getIntrinsicID()) { 684 case Intrinsic::amdgcn_atomic_inc: 685 case Intrinsic::amdgcn_atomic_dec: 686 case Intrinsic::amdgcn_ds_fadd: 687 case Intrinsic::amdgcn_ds_fmin: 688 case Intrinsic::amdgcn_ds_fmax: { 689 Value *Ptr = II->getArgOperand(0); 690 AccessTy = II->getType(); 691 Ops.push_back(Ptr); 692 return true; 693 } 694 default: 695 return false; 696 } 697 } 698 699 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 700 if (!Subtarget->hasFlatInstOffsets()) { 701 // Flat instructions do not have offsets, and only have the register 702 // address. 703 return AM.BaseOffs == 0 && AM.Scale == 0; 704 } 705 706 // GFX9 added a 13-bit signed offset. When using regular flat instructions, 707 // the sign bit is ignored and is treated as a 12-bit unsigned offset. 708 709 // Just r + i 710 return isUInt<12>(AM.BaseOffs) && AM.Scale == 0; 711 } 712 713 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 714 if (Subtarget->hasFlatGlobalInsts()) 715 return isInt<13>(AM.BaseOffs) && AM.Scale == 0; 716 717 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 718 // Assume the we will use FLAT for all global memory accesses 719 // on VI. 720 // FIXME: This assumption is currently wrong. On VI we still use 721 // MUBUF instructions for the r + i addressing mode. As currently 722 // implemented, the MUBUF instructions only work on buffer < 4GB. 723 // It may be possible to support > 4GB buffers with MUBUF instructions, 724 // by setting the stride value in the resource descriptor which would 725 // increase the size limit to (stride * 4GB). However, this is risky, 726 // because it has never been validated. 727 return isLegalFlatAddressingMode(AM); 728 } 729 730 return isLegalMUBUFAddressingMode(AM); 731 } 732 733 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 734 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 735 // additionally can do r + r + i with addr64. 32-bit has more addressing 736 // mode options. Depending on the resource constant, it can also do 737 // (i64 r0) + (i32 r1) * (i14 i). 738 // 739 // Private arrays end up using a scratch buffer most of the time, so also 740 // assume those use MUBUF instructions. Scratch loads / stores are currently 741 // implemented as mubuf instructions with offen bit set, so slightly 742 // different than the normal addr64. 743 if (!isUInt<12>(AM.BaseOffs)) 744 return false; 745 746 // FIXME: Since we can split immediate into soffset and immediate offset, 747 // would it make sense to allow any immediate? 748 749 switch (AM.Scale) { 750 case 0: // r + i or just i, depending on HasBaseReg. 751 return true; 752 case 1: 753 return true; // We have r + r or r + i. 754 case 2: 755 if (AM.HasBaseReg) { 756 // Reject 2 * r + r. 757 return false; 758 } 759 760 // Allow 2 * r as r + r 761 // Or 2 * r + i is allowed as r + r + i. 762 return true; 763 default: // Don't allow n * r 764 return false; 765 } 766 } 767 768 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 769 const AddrMode &AM, Type *Ty, 770 unsigned AS, Instruction *I) const { 771 // No global is ever allowed as a base. 772 if (AM.BaseGV) 773 return false; 774 775 if (AS == AMDGPUASI.GLOBAL_ADDRESS) 776 return isLegalGlobalAddressingMode(AM); 777 778 if (AS == AMDGPUASI.CONSTANT_ADDRESS || 779 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT) { 780 // If the offset isn't a multiple of 4, it probably isn't going to be 781 // correctly aligned. 782 // FIXME: Can we get the real alignment here? 783 if (AM.BaseOffs % 4 != 0) 784 return isLegalMUBUFAddressingMode(AM); 785 786 // There are no SMRD extloads, so if we have to do a small type access we 787 // will use a MUBUF load. 788 // FIXME?: We also need to do this if unaligned, but we don't know the 789 // alignment here. 790 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 791 return isLegalGlobalAddressingMode(AM); 792 793 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) { 794 // SMRD instructions have an 8-bit, dword offset on SI. 795 if (!isUInt<8>(AM.BaseOffs / 4)) 796 return false; 797 } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) { 798 // On CI+, this can also be a 32-bit literal constant offset. If it fits 799 // in 8-bits, it can use a smaller encoding. 800 if (!isUInt<32>(AM.BaseOffs / 4)) 801 return false; 802 } else if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) { 803 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 804 if (!isUInt<20>(AM.BaseOffs)) 805 return false; 806 } else 807 llvm_unreachable("unhandled generation"); 808 809 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 810 return true; 811 812 if (AM.Scale == 1 && AM.HasBaseReg) 813 return true; 814 815 return false; 816 817 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 818 return isLegalMUBUFAddressingMode(AM); 819 } else if (AS == AMDGPUASI.LOCAL_ADDRESS || 820 AS == AMDGPUASI.REGION_ADDRESS) { 821 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 822 // field. 823 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 824 // an 8-bit dword offset but we don't know the alignment here. 825 if (!isUInt<16>(AM.BaseOffs)) 826 return false; 827 828 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 829 return true; 830 831 if (AM.Scale == 1 && AM.HasBaseReg) 832 return true; 833 834 return false; 835 } else if (AS == AMDGPUASI.FLAT_ADDRESS || 836 AS == AMDGPUASI.UNKNOWN_ADDRESS_SPACE) { 837 // For an unknown address space, this usually means that this is for some 838 // reason being used for pure arithmetic, and not based on some addressing 839 // computation. We don't have instructions that compute pointers with any 840 // addressing modes, so treat them as having no offset like flat 841 // instructions. 842 return isLegalFlatAddressingMode(AM); 843 } else { 844 llvm_unreachable("unhandled address space"); 845 } 846 } 847 848 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 849 const SelectionDAG &DAG) const { 850 if (AS == AMDGPUASI.GLOBAL_ADDRESS || AS == AMDGPUASI.FLAT_ADDRESS) { 851 return (MemVT.getSizeInBits() <= 4 * 32); 852 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 853 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 854 return (MemVT.getSizeInBits() <= MaxPrivateBits); 855 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 856 return (MemVT.getSizeInBits() <= 2 * 32); 857 } 858 return true; 859 } 860 861 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 862 unsigned AddrSpace, 863 unsigned Align, 864 bool *IsFast) const { 865 if (IsFast) 866 *IsFast = false; 867 868 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 869 // which isn't a simple VT. 870 // Until MVT is extended to handle this, simply check for the size and 871 // rely on the condition below: allow accesses if the size is a multiple of 4. 872 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 873 VT.getStoreSize() > 16)) { 874 return false; 875 } 876 877 if (AddrSpace == AMDGPUASI.LOCAL_ADDRESS || 878 AddrSpace == AMDGPUASI.REGION_ADDRESS) { 879 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 880 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 881 // with adjacent offsets. 882 bool AlignedBy4 = (Align % 4 == 0); 883 if (IsFast) 884 *IsFast = AlignedBy4; 885 886 return AlignedBy4; 887 } 888 889 // FIXME: We have to be conservative here and assume that flat operations 890 // will access scratch. If we had access to the IR function, then we 891 // could determine if any private memory was used in the function. 892 if (!Subtarget->hasUnalignedScratchAccess() && 893 (AddrSpace == AMDGPUASI.PRIVATE_ADDRESS || 894 AddrSpace == AMDGPUASI.FLAT_ADDRESS)) { 895 return false; 896 } 897 898 if (Subtarget->hasUnalignedBufferAccess()) { 899 // If we have an uniform constant load, it still requires using a slow 900 // buffer instruction if unaligned. 901 if (IsFast) { 902 *IsFast = (AddrSpace == AMDGPUASI.CONSTANT_ADDRESS || 903 AddrSpace == AMDGPUASI.CONSTANT_ADDRESS_32BIT) ? 904 (Align % 4 == 0) : true; 905 } 906 907 return true; 908 } 909 910 // Smaller than dword value must be aligned. 911 if (VT.bitsLT(MVT::i32)) 912 return false; 913 914 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 915 // byte-address are ignored, thus forcing Dword alignment. 916 // This applies to private, global, and constant memory. 917 if (IsFast) 918 *IsFast = true; 919 920 return VT.bitsGT(MVT::i32) && Align % 4 == 0; 921 } 922 923 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign, 924 unsigned SrcAlign, bool IsMemset, 925 bool ZeroMemset, 926 bool MemcpyStrSrc, 927 MachineFunction &MF) const { 928 // FIXME: Should account for address space here. 929 930 // The default fallback uses the private pointer size as a guess for a type to 931 // use. Make sure we switch these to 64-bit accesses. 932 933 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global 934 return MVT::v4i32; 935 936 if (Size >= 8 && DstAlign >= 4) 937 return MVT::v2i32; 938 939 // Use the default. 940 return MVT::Other; 941 } 942 943 static bool isFlatGlobalAddrSpace(unsigned AS, AMDGPUAS AMDGPUASI) { 944 return AS == AMDGPUASI.GLOBAL_ADDRESS || 945 AS == AMDGPUASI.FLAT_ADDRESS || 946 AS == AMDGPUASI.CONSTANT_ADDRESS || 947 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT; 948 } 949 950 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 951 unsigned DestAS) const { 952 return isFlatGlobalAddrSpace(SrcAS, AMDGPUASI) && 953 isFlatGlobalAddrSpace(DestAS, AMDGPUASI); 954 } 955 956 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 957 const MemSDNode *MemNode = cast<MemSDNode>(N); 958 const Value *Ptr = MemNode->getMemOperand()->getValue(); 959 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 960 return I && I->getMetadata("amdgpu.noclobber"); 961 } 962 963 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS, 964 unsigned DestAS) const { 965 // Flat -> private/local is a simple truncate. 966 // Flat -> global is no-op 967 if (SrcAS == AMDGPUASI.FLAT_ADDRESS) 968 return true; 969 970 return isNoopAddrSpaceCast(SrcAS, DestAS); 971 } 972 973 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 974 const MemSDNode *MemNode = cast<MemSDNode>(N); 975 976 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 977 } 978 979 TargetLoweringBase::LegalizeTypeAction 980 SITargetLowering::getPreferredVectorAction(EVT VT) const { 981 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16)) 982 return TypeSplitVector; 983 984 return TargetLoweringBase::getPreferredVectorAction(VT); 985 } 986 987 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 988 Type *Ty) const { 989 // FIXME: Could be smarter if called for vector constants. 990 return true; 991 } 992 993 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 994 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 995 switch (Op) { 996 case ISD::LOAD: 997 case ISD::STORE: 998 999 // These operations are done with 32-bit instructions anyway. 1000 case ISD::AND: 1001 case ISD::OR: 1002 case ISD::XOR: 1003 case ISD::SELECT: 1004 // TODO: Extensions? 1005 return true; 1006 default: 1007 return false; 1008 } 1009 } 1010 1011 // SimplifySetCC uses this function to determine whether or not it should 1012 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1013 if (VT == MVT::i1 && Op == ISD::SETCC) 1014 return false; 1015 1016 return TargetLowering::isTypeDesirableForOp(Op, VT); 1017 } 1018 1019 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1020 const SDLoc &SL, 1021 SDValue Chain, 1022 uint64_t Offset) const { 1023 const DataLayout &DL = DAG.getDataLayout(); 1024 MachineFunction &MF = DAG.getMachineFunction(); 1025 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1026 1027 const ArgDescriptor *InputPtrReg; 1028 const TargetRegisterClass *RC; 1029 1030 std::tie(InputPtrReg, RC) 1031 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1032 1033 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1034 MVT PtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS); 1035 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1036 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1037 1038 return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr, 1039 DAG.getConstant(Offset, SL, PtrVT)); 1040 } 1041 1042 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1043 const SDLoc &SL) const { 1044 auto MFI = DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>(); 1045 uint64_t Offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT); 1046 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1047 } 1048 1049 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1050 const SDLoc &SL, SDValue Val, 1051 bool Signed, 1052 const ISD::InputArg *Arg) const { 1053 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1054 VT.bitsLT(MemVT)) { 1055 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1056 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1057 } 1058 1059 if (MemVT.isFloatingPoint()) 1060 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT); 1061 else if (Signed) 1062 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1063 else 1064 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1065 1066 return Val; 1067 } 1068 1069 SDValue SITargetLowering::lowerKernargMemParameter( 1070 SelectionDAG &DAG, EVT VT, EVT MemVT, 1071 const SDLoc &SL, SDValue Chain, 1072 uint64_t Offset, bool Signed, 1073 const ISD::InputArg *Arg) const { 1074 const DataLayout &DL = DAG.getDataLayout(); 1075 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 1076 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS); 1077 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 1078 1079 unsigned Align = DL.getABITypeAlignment(Ty); 1080 1081 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1082 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1083 MachineMemOperand::MODereferenceable | 1084 MachineMemOperand::MOInvariant); 1085 1086 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1087 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1088 } 1089 1090 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1091 const SDLoc &SL, SDValue Chain, 1092 const ISD::InputArg &Arg) const { 1093 MachineFunction &MF = DAG.getMachineFunction(); 1094 MachineFrameInfo &MFI = MF.getFrameInfo(); 1095 1096 if (Arg.Flags.isByVal()) { 1097 unsigned Size = Arg.Flags.getByValSize(); 1098 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1099 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1100 } 1101 1102 unsigned ArgOffset = VA.getLocMemOffset(); 1103 unsigned ArgSize = VA.getValVT().getStoreSize(); 1104 1105 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1106 1107 // Create load nodes to retrieve arguments from the stack. 1108 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1109 SDValue ArgValue; 1110 1111 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1112 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1113 MVT MemVT = VA.getValVT(); 1114 1115 switch (VA.getLocInfo()) { 1116 default: 1117 break; 1118 case CCValAssign::BCvt: 1119 MemVT = VA.getLocVT(); 1120 break; 1121 case CCValAssign::SExt: 1122 ExtType = ISD::SEXTLOAD; 1123 break; 1124 case CCValAssign::ZExt: 1125 ExtType = ISD::ZEXTLOAD; 1126 break; 1127 case CCValAssign::AExt: 1128 ExtType = ISD::EXTLOAD; 1129 break; 1130 } 1131 1132 ArgValue = DAG.getExtLoad( 1133 ExtType, SL, VA.getLocVT(), Chain, FIN, 1134 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1135 MemVT); 1136 return ArgValue; 1137 } 1138 1139 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1140 const SIMachineFunctionInfo &MFI, 1141 EVT VT, 1142 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1143 const ArgDescriptor *Reg; 1144 const TargetRegisterClass *RC; 1145 1146 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1147 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1148 } 1149 1150 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1151 CallingConv::ID CallConv, 1152 ArrayRef<ISD::InputArg> Ins, 1153 BitVector &Skipped, 1154 FunctionType *FType, 1155 SIMachineFunctionInfo *Info) { 1156 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1157 const ISD::InputArg &Arg = Ins[I]; 1158 1159 // First check if it's a PS input addr. 1160 if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() && 1161 !Arg.Flags.isByVal() && PSInputNum <= 15) { 1162 1163 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) { 1164 // We can safely skip PS inputs. 1165 Skipped.set(I); 1166 ++PSInputNum; 1167 continue; 1168 } 1169 1170 Info->markPSInputAllocated(PSInputNum); 1171 if (Arg.Used) 1172 Info->markPSInputEnabled(PSInputNum); 1173 1174 ++PSInputNum; 1175 } 1176 1177 // Second split vertices into their elements. 1178 if (Arg.VT.isVector()) { 1179 ISD::InputArg NewArg = Arg; 1180 NewArg.Flags.setSplit(); 1181 NewArg.VT = Arg.VT.getVectorElementType(); 1182 1183 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a 1184 // three or five element vertex only needs three or five registers, 1185 // NOT four or eight. 1186 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 1187 unsigned NumElements = ParamType->getVectorNumElements(); 1188 1189 for (unsigned J = 0; J != NumElements; ++J) { 1190 Splits.push_back(NewArg); 1191 NewArg.PartOffset += NewArg.VT.getStoreSize(); 1192 } 1193 } else { 1194 Splits.push_back(Arg); 1195 } 1196 } 1197 } 1198 1199 // Allocate special inputs passed in VGPRs. 1200 static void allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1201 MachineFunction &MF, 1202 const SIRegisterInfo &TRI, 1203 SIMachineFunctionInfo &Info) { 1204 if (Info.hasWorkItemIDX()) { 1205 unsigned Reg = AMDGPU::VGPR0; 1206 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1207 1208 CCInfo.AllocateReg(Reg); 1209 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1210 } 1211 1212 if (Info.hasWorkItemIDY()) { 1213 unsigned Reg = AMDGPU::VGPR1; 1214 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1215 1216 CCInfo.AllocateReg(Reg); 1217 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1218 } 1219 1220 if (Info.hasWorkItemIDZ()) { 1221 unsigned Reg = AMDGPU::VGPR2; 1222 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1223 1224 CCInfo.AllocateReg(Reg); 1225 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1226 } 1227 } 1228 1229 // Try to allocate a VGPR at the end of the argument list, or if no argument 1230 // VGPRs are left allocating a stack slot. 1231 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo) { 1232 ArrayRef<MCPhysReg> ArgVGPRs 1233 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1234 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1235 if (RegIdx == ArgVGPRs.size()) { 1236 // Spill to stack required. 1237 int64_t Offset = CCInfo.AllocateStack(4, 4); 1238 1239 return ArgDescriptor::createStack(Offset); 1240 } 1241 1242 unsigned Reg = ArgVGPRs[RegIdx]; 1243 Reg = CCInfo.AllocateReg(Reg); 1244 assert(Reg != AMDGPU::NoRegister); 1245 1246 MachineFunction &MF = CCInfo.getMachineFunction(); 1247 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1248 return ArgDescriptor::createRegister(Reg); 1249 } 1250 1251 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1252 const TargetRegisterClass *RC, 1253 unsigned NumArgRegs) { 1254 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1255 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1256 if (RegIdx == ArgSGPRs.size()) 1257 report_fatal_error("ran out of SGPRs for arguments"); 1258 1259 unsigned Reg = ArgSGPRs[RegIdx]; 1260 Reg = CCInfo.AllocateReg(Reg); 1261 assert(Reg != AMDGPU::NoRegister); 1262 1263 MachineFunction &MF = CCInfo.getMachineFunction(); 1264 MF.addLiveIn(Reg, RC); 1265 return ArgDescriptor::createRegister(Reg); 1266 } 1267 1268 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1269 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1270 } 1271 1272 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1273 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1274 } 1275 1276 static void allocateSpecialInputVGPRs(CCState &CCInfo, 1277 MachineFunction &MF, 1278 const SIRegisterInfo &TRI, 1279 SIMachineFunctionInfo &Info) { 1280 if (Info.hasWorkItemIDX()) 1281 Info.setWorkItemIDX(allocateVGPR32Input(CCInfo)); 1282 1283 if (Info.hasWorkItemIDY()) 1284 Info.setWorkItemIDY(allocateVGPR32Input(CCInfo)); 1285 1286 if (Info.hasWorkItemIDZ()) 1287 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo)); 1288 } 1289 1290 static void allocateSpecialInputSGPRs(CCState &CCInfo, 1291 MachineFunction &MF, 1292 const SIRegisterInfo &TRI, 1293 SIMachineFunctionInfo &Info) { 1294 auto &ArgInfo = Info.getArgInfo(); 1295 1296 // TODO: Unify handling with private memory pointers. 1297 1298 if (Info.hasDispatchPtr()) 1299 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1300 1301 if (Info.hasQueuePtr()) 1302 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1303 1304 if (Info.hasKernargSegmentPtr()) 1305 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo); 1306 1307 if (Info.hasDispatchID()) 1308 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1309 1310 // flat_scratch_init is not applicable for non-kernel functions. 1311 1312 if (Info.hasWorkGroupIDX()) 1313 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1314 1315 if (Info.hasWorkGroupIDY()) 1316 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1317 1318 if (Info.hasWorkGroupIDZ()) 1319 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1320 1321 if (Info.hasImplicitArgPtr()) 1322 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1323 } 1324 1325 // Allocate special inputs passed in user SGPRs. 1326 static void allocateHSAUserSGPRs(CCState &CCInfo, 1327 MachineFunction &MF, 1328 const SIRegisterInfo &TRI, 1329 SIMachineFunctionInfo &Info) { 1330 if (Info.hasImplicitBufferPtr()) { 1331 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1332 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1333 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1334 } 1335 1336 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1337 if (Info.hasPrivateSegmentBuffer()) { 1338 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1339 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1340 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1341 } 1342 1343 if (Info.hasDispatchPtr()) { 1344 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1345 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1346 CCInfo.AllocateReg(DispatchPtrReg); 1347 } 1348 1349 if (Info.hasQueuePtr()) { 1350 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1351 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1352 CCInfo.AllocateReg(QueuePtrReg); 1353 } 1354 1355 if (Info.hasKernargSegmentPtr()) { 1356 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI); 1357 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1358 CCInfo.AllocateReg(InputPtrReg); 1359 } 1360 1361 if (Info.hasDispatchID()) { 1362 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1363 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1364 CCInfo.AllocateReg(DispatchIDReg); 1365 } 1366 1367 if (Info.hasFlatScratchInit()) { 1368 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1369 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1370 CCInfo.AllocateReg(FlatScratchInitReg); 1371 } 1372 1373 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1374 // these from the dispatch pointer. 1375 } 1376 1377 // Allocate special input registers that are initialized per-wave. 1378 static void allocateSystemSGPRs(CCState &CCInfo, 1379 MachineFunction &MF, 1380 SIMachineFunctionInfo &Info, 1381 CallingConv::ID CallConv, 1382 bool IsShader) { 1383 if (Info.hasWorkGroupIDX()) { 1384 unsigned Reg = Info.addWorkGroupIDX(); 1385 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1386 CCInfo.AllocateReg(Reg); 1387 } 1388 1389 if (Info.hasWorkGroupIDY()) { 1390 unsigned Reg = Info.addWorkGroupIDY(); 1391 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1392 CCInfo.AllocateReg(Reg); 1393 } 1394 1395 if (Info.hasWorkGroupIDZ()) { 1396 unsigned Reg = Info.addWorkGroupIDZ(); 1397 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1398 CCInfo.AllocateReg(Reg); 1399 } 1400 1401 if (Info.hasWorkGroupInfo()) { 1402 unsigned Reg = Info.addWorkGroupInfo(); 1403 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1404 CCInfo.AllocateReg(Reg); 1405 } 1406 1407 if (Info.hasPrivateSegmentWaveByteOffset()) { 1408 // Scratch wave offset passed in system SGPR. 1409 unsigned PrivateSegmentWaveByteOffsetReg; 1410 1411 if (IsShader) { 1412 PrivateSegmentWaveByteOffsetReg = 1413 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1414 1415 // This is true if the scratch wave byte offset doesn't have a fixed 1416 // location. 1417 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1418 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1419 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1420 } 1421 } else 1422 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1423 1424 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1425 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1426 } 1427 } 1428 1429 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1430 MachineFunction &MF, 1431 const SIRegisterInfo &TRI, 1432 SIMachineFunctionInfo &Info) { 1433 // Now that we've figured out where the scratch register inputs are, see if 1434 // should reserve the arguments and use them directly. 1435 MachineFrameInfo &MFI = MF.getFrameInfo(); 1436 bool HasStackObjects = MFI.hasStackObjects(); 1437 1438 // Record that we know we have non-spill stack objects so we don't need to 1439 // check all stack objects later. 1440 if (HasStackObjects) 1441 Info.setHasNonSpillStackObjects(true); 1442 1443 // Everything live out of a block is spilled with fast regalloc, so it's 1444 // almost certain that spilling will be required. 1445 if (TM.getOptLevel() == CodeGenOpt::None) 1446 HasStackObjects = true; 1447 1448 // For now assume stack access is needed in any callee functions, so we need 1449 // the scratch registers to pass in. 1450 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1451 1452 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 1453 if (ST.isAmdCodeObjectV2(MF)) { 1454 if (RequiresStackAccess) { 1455 // If we have stack objects, we unquestionably need the private buffer 1456 // resource. For the Code Object V2 ABI, this will be the first 4 user 1457 // SGPR inputs. We can reserve those and use them directly. 1458 1459 unsigned PrivateSegmentBufferReg = Info.getPreloadedReg( 1460 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 1461 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1462 1463 if (MFI.hasCalls()) { 1464 // If we have calls, we need to keep the frame register in a register 1465 // that won't be clobbered by a call, so ensure it is copied somewhere. 1466 1467 // This is not a problem for the scratch wave offset, because the same 1468 // registers are reserved in all functions. 1469 1470 // FIXME: Nothing is really ensuring this is a call preserved register, 1471 // it's just selected from the end so it happens to be. 1472 unsigned ReservedOffsetReg 1473 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1474 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1475 } else { 1476 unsigned PrivateSegmentWaveByteOffsetReg = Info.getPreloadedReg( 1477 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1478 Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg); 1479 } 1480 } else { 1481 unsigned ReservedBufferReg 1482 = TRI.reservedPrivateSegmentBufferReg(MF); 1483 unsigned ReservedOffsetReg 1484 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1485 1486 // We tentatively reserve the last registers (skipping the last two 1487 // which may contain VCC). After register allocation, we'll replace 1488 // these with the ones immediately after those which were really 1489 // allocated. In the prologue copies will be inserted from the argument 1490 // to these reserved registers. 1491 Info.setScratchRSrcReg(ReservedBufferReg); 1492 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1493 } 1494 } else { 1495 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1496 1497 // Without HSA, relocations are used for the scratch pointer and the 1498 // buffer resource setup is always inserted in the prologue. Scratch wave 1499 // offset is still in an input SGPR. 1500 Info.setScratchRSrcReg(ReservedBufferReg); 1501 1502 if (HasStackObjects && !MFI.hasCalls()) { 1503 unsigned ScratchWaveOffsetReg = Info.getPreloadedReg( 1504 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1505 Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg); 1506 } else { 1507 unsigned ReservedOffsetReg 1508 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1509 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1510 } 1511 } 1512 } 1513 1514 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 1515 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 1516 return !Info->isEntryFunction(); 1517 } 1518 1519 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 1520 1521 } 1522 1523 void SITargetLowering::insertCopiesSplitCSR( 1524 MachineBasicBlock *Entry, 1525 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 1526 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1527 1528 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 1529 if (!IStart) 1530 return; 1531 1532 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1533 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 1534 MachineBasicBlock::iterator MBBI = Entry->begin(); 1535 for (const MCPhysReg *I = IStart; *I; ++I) { 1536 const TargetRegisterClass *RC = nullptr; 1537 if (AMDGPU::SReg_64RegClass.contains(*I)) 1538 RC = &AMDGPU::SGPR_64RegClass; 1539 else if (AMDGPU::SReg_32RegClass.contains(*I)) 1540 RC = &AMDGPU::SGPR_32RegClass; 1541 else 1542 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 1543 1544 unsigned NewVR = MRI->createVirtualRegister(RC); 1545 // Create copy from CSR to a virtual register. 1546 Entry->addLiveIn(*I); 1547 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 1548 .addReg(*I); 1549 1550 // Insert the copy-back instructions right before the terminator. 1551 for (auto *Exit : Exits) 1552 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 1553 TII->get(TargetOpcode::COPY), *I) 1554 .addReg(NewVR); 1555 } 1556 } 1557 1558 SDValue SITargetLowering::LowerFormalArguments( 1559 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 1560 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 1561 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 1562 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1563 1564 MachineFunction &MF = DAG.getMachineFunction(); 1565 FunctionType *FType = MF.getFunction().getFunctionType(); 1566 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1567 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 1568 1569 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 1570 const Function &Fn = MF.getFunction(); 1571 DiagnosticInfoUnsupported NoGraphicsHSA( 1572 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 1573 DAG.getContext()->diagnose(NoGraphicsHSA); 1574 return DAG.getEntryNode(); 1575 } 1576 1577 // Create stack objects that are used for emitting debugger prologue if 1578 // "amdgpu-debugger-emit-prologue" attribute was specified. 1579 if (ST.debuggerEmitPrologue()) 1580 createDebuggerPrologueStackObjects(MF); 1581 1582 SmallVector<ISD::InputArg, 16> Splits; 1583 SmallVector<CCValAssign, 16> ArgLocs; 1584 BitVector Skipped(Ins.size()); 1585 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1586 *DAG.getContext()); 1587 1588 bool IsShader = AMDGPU::isShader(CallConv); 1589 bool IsKernel = AMDGPU::isKernel(CallConv); 1590 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 1591 1592 if (!IsEntryFunc) { 1593 // 4 bytes are reserved at offset 0 for the emergency stack slot. Skip over 1594 // this when allocating argument fixed offsets. 1595 CCInfo.AllocateStack(4, 4); 1596 } 1597 1598 if (IsShader) { 1599 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 1600 1601 // At least one interpolation mode must be enabled or else the GPU will 1602 // hang. 1603 // 1604 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 1605 // set PSInputAddr, the user wants to enable some bits after the compilation 1606 // based on run-time states. Since we can't know what the final PSInputEna 1607 // will look like, so we shouldn't do anything here and the user should take 1608 // responsibility for the correct programming. 1609 // 1610 // Otherwise, the following restrictions apply: 1611 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 1612 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 1613 // enabled too. 1614 if (CallConv == CallingConv::AMDGPU_PS) { 1615 if ((Info->getPSInputAddr() & 0x7F) == 0 || 1616 ((Info->getPSInputAddr() & 0xF) == 0 && 1617 Info->isPSInputAllocated(11))) { 1618 CCInfo.AllocateReg(AMDGPU::VGPR0); 1619 CCInfo.AllocateReg(AMDGPU::VGPR1); 1620 Info->markPSInputAllocated(0); 1621 Info->markPSInputEnabled(0); 1622 } 1623 if (Subtarget->isAmdPalOS()) { 1624 // For isAmdPalOS, the user does not enable some bits after compilation 1625 // based on run-time states; the register values being generated here are 1626 // the final ones set in hardware. Therefore we need to apply the 1627 // workaround to PSInputAddr and PSInputEnable together. (The case where 1628 // a bit is set in PSInputAddr but not PSInputEnable is where the 1629 // frontend set up an input arg for a particular interpolation mode, but 1630 // nothing uses that input arg. Really we should have an earlier pass 1631 // that removes such an arg.) 1632 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 1633 if ((PsInputBits & 0x7F) == 0 || 1634 ((PsInputBits & 0xF) == 0 && 1635 (PsInputBits >> 11 & 1))) 1636 Info->markPSInputEnabled( 1637 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 1638 } 1639 } 1640 1641 assert(!Info->hasDispatchPtr() && 1642 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 1643 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 1644 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 1645 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 1646 !Info->hasWorkItemIDZ()); 1647 } else if (IsKernel) { 1648 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 1649 } else { 1650 Splits.append(Ins.begin(), Ins.end()); 1651 } 1652 1653 if (IsEntryFunc) { 1654 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 1655 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 1656 } 1657 1658 if (IsKernel) { 1659 analyzeFormalArgumentsCompute(CCInfo, Ins); 1660 } else { 1661 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 1662 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 1663 } 1664 1665 SmallVector<SDValue, 16> Chains; 1666 1667 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 1668 const ISD::InputArg &Arg = Ins[i]; 1669 if (Skipped[i]) { 1670 InVals.push_back(DAG.getUNDEF(Arg.VT)); 1671 continue; 1672 } 1673 1674 CCValAssign &VA = ArgLocs[ArgIdx++]; 1675 MVT VT = VA.getLocVT(); 1676 1677 if (IsEntryFunc && VA.isMemLoc()) { 1678 VT = Ins[i].VT; 1679 EVT MemVT = VA.getLocVT(); 1680 1681 const uint64_t Offset = Subtarget->getExplicitKernelArgOffset(MF) + 1682 VA.getLocMemOffset(); 1683 Info->setABIArgOffset(Offset + MemVT.getStoreSize()); 1684 1685 // The first 36 bytes of the input buffer contains information about 1686 // thread group and global sizes. 1687 SDValue Arg = lowerKernargMemParameter( 1688 DAG, VT, MemVT, DL, Chain, Offset, Ins[i].Flags.isSExt(), &Ins[i]); 1689 Chains.push_back(Arg.getValue(1)); 1690 1691 auto *ParamTy = 1692 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 1693 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS && 1694 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 1695 // On SI local pointers are just offsets into LDS, so they are always 1696 // less than 16-bits. On CI and newer they could potentially be 1697 // real pointers, so we can't guarantee their size. 1698 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 1699 DAG.getValueType(MVT::i16)); 1700 } 1701 1702 InVals.push_back(Arg); 1703 continue; 1704 } else if (!IsEntryFunc && VA.isMemLoc()) { 1705 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 1706 InVals.push_back(Val); 1707 if (!Arg.Flags.isByVal()) 1708 Chains.push_back(Val.getValue(1)); 1709 continue; 1710 } 1711 1712 assert(VA.isRegLoc() && "Parameter must be in a register!"); 1713 1714 unsigned Reg = VA.getLocReg(); 1715 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 1716 EVT ValVT = VA.getValVT(); 1717 1718 Reg = MF.addLiveIn(Reg, RC); 1719 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 1720 1721 if (Arg.Flags.isSRet() && !getSubtarget()->enableHugePrivateBuffer()) { 1722 // The return object should be reasonably addressable. 1723 1724 // FIXME: This helps when the return is a real sret. If it is a 1725 // automatically inserted sret (i.e. CanLowerReturn returns false), an 1726 // extra copy is inserted in SelectionDAGBuilder which obscures this. 1727 unsigned NumBits = 32 - AssumeFrameIndexHighZeroBits; 1728 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 1729 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 1730 } 1731 1732 // If this is an 8 or 16-bit value, it is really passed promoted 1733 // to 32 bits. Insert an assert[sz]ext to capture this, then 1734 // truncate to the right size. 1735 switch (VA.getLocInfo()) { 1736 case CCValAssign::Full: 1737 break; 1738 case CCValAssign::BCvt: 1739 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 1740 break; 1741 case CCValAssign::SExt: 1742 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 1743 DAG.getValueType(ValVT)); 1744 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 1745 break; 1746 case CCValAssign::ZExt: 1747 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 1748 DAG.getValueType(ValVT)); 1749 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 1750 break; 1751 case CCValAssign::AExt: 1752 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 1753 break; 1754 default: 1755 llvm_unreachable("Unknown loc info!"); 1756 } 1757 1758 if (IsShader && Arg.VT.isVector()) { 1759 // Build a vector from the registers 1760 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 1761 unsigned NumElements = ParamType->getVectorNumElements(); 1762 1763 SmallVector<SDValue, 4> Regs; 1764 Regs.push_back(Val); 1765 for (unsigned j = 1; j != NumElements; ++j) { 1766 Reg = ArgLocs[ArgIdx++].getLocReg(); 1767 Reg = MF.addLiveIn(Reg, RC); 1768 1769 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT); 1770 Regs.push_back(Copy); 1771 } 1772 1773 // Fill up the missing vector elements 1774 NumElements = Arg.VT.getVectorNumElements() - NumElements; 1775 Regs.append(NumElements, DAG.getUNDEF(VT)); 1776 1777 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs)); 1778 continue; 1779 } 1780 1781 InVals.push_back(Val); 1782 } 1783 1784 if (!IsEntryFunc) { 1785 // Special inputs come after user arguments. 1786 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 1787 } 1788 1789 // Start adding system SGPRs. 1790 if (IsEntryFunc) { 1791 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 1792 } else { 1793 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 1794 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg()); 1795 CCInfo.AllocateReg(Info->getFrameOffsetReg()); 1796 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 1797 } 1798 1799 auto &ArgUsageInfo = 1800 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 1801 ArgUsageInfo.setFuncArgInfo(MF.getFunction(), Info->getArgInfo()); 1802 1803 unsigned StackArgSize = CCInfo.getNextStackOffset(); 1804 Info->setBytesInStackArgArea(StackArgSize); 1805 1806 return Chains.empty() ? Chain : 1807 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 1808 } 1809 1810 // TODO: If return values can't fit in registers, we should return as many as 1811 // possible in registers before passing on stack. 1812 bool SITargetLowering::CanLowerReturn( 1813 CallingConv::ID CallConv, 1814 MachineFunction &MF, bool IsVarArg, 1815 const SmallVectorImpl<ISD::OutputArg> &Outs, 1816 LLVMContext &Context) const { 1817 // Replacing returns with sret/stack usage doesn't make sense for shaders. 1818 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 1819 // for shaders. Vector types should be explicitly handled by CC. 1820 if (AMDGPU::isEntryFunctionCC(CallConv)) 1821 return true; 1822 1823 SmallVector<CCValAssign, 16> RVLocs; 1824 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 1825 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 1826 } 1827 1828 SDValue 1829 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 1830 bool isVarArg, 1831 const SmallVectorImpl<ISD::OutputArg> &Outs, 1832 const SmallVectorImpl<SDValue> &OutVals, 1833 const SDLoc &DL, SelectionDAG &DAG) const { 1834 MachineFunction &MF = DAG.getMachineFunction(); 1835 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1836 1837 if (AMDGPU::isKernel(CallConv)) { 1838 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 1839 OutVals, DL, DAG); 1840 } 1841 1842 bool IsShader = AMDGPU::isShader(CallConv); 1843 1844 Info->setIfReturnsVoid(Outs.size() == 0); 1845 bool IsWaveEnd = Info->returnsVoid() && IsShader; 1846 1847 SmallVector<ISD::OutputArg, 48> Splits; 1848 SmallVector<SDValue, 48> SplitVals; 1849 1850 // Split vectors into their elements. 1851 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 1852 const ISD::OutputArg &Out = Outs[i]; 1853 1854 if (IsShader && Out.VT.isVector()) { 1855 MVT VT = Out.VT.getVectorElementType(); 1856 ISD::OutputArg NewOut = Out; 1857 NewOut.Flags.setSplit(); 1858 NewOut.VT = VT; 1859 1860 // We want the original number of vector elements here, e.g. 1861 // three or five, not four or eight. 1862 unsigned NumElements = Out.ArgVT.getVectorNumElements(); 1863 1864 for (unsigned j = 0; j != NumElements; ++j) { 1865 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i], 1866 DAG.getConstant(j, DL, MVT::i32)); 1867 SplitVals.push_back(Elem); 1868 Splits.push_back(NewOut); 1869 NewOut.PartOffset += NewOut.VT.getStoreSize(); 1870 } 1871 } else { 1872 SplitVals.push_back(OutVals[i]); 1873 Splits.push_back(Out); 1874 } 1875 } 1876 1877 // CCValAssign - represent the assignment of the return value to a location. 1878 SmallVector<CCValAssign, 48> RVLocs; 1879 1880 // CCState - Info about the registers and stack slots. 1881 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1882 *DAG.getContext()); 1883 1884 // Analyze outgoing return values. 1885 CCInfo.AnalyzeReturn(Splits, CCAssignFnForReturn(CallConv, isVarArg)); 1886 1887 SDValue Flag; 1888 SmallVector<SDValue, 48> RetOps; 1889 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 1890 1891 // Add return address for callable functions. 1892 if (!Info->isEntryFunction()) { 1893 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1894 SDValue ReturnAddrReg = CreateLiveInRegister( 1895 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 1896 1897 // FIXME: Should be able to use a vreg here, but need a way to prevent it 1898 // from being allcoated to a CSR. 1899 1900 SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 1901 MVT::i64); 1902 1903 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag); 1904 Flag = Chain.getValue(1); 1905 1906 RetOps.push_back(PhysReturnAddrReg); 1907 } 1908 1909 // Copy the result values into the output registers. 1910 for (unsigned i = 0, realRVLocIdx = 0; 1911 i != RVLocs.size(); 1912 ++i, ++realRVLocIdx) { 1913 CCValAssign &VA = RVLocs[i]; 1914 assert(VA.isRegLoc() && "Can only return in registers!"); 1915 // TODO: Partially return in registers if return values don't fit. 1916 1917 SDValue Arg = SplitVals[realRVLocIdx]; 1918 1919 // Copied from other backends. 1920 switch (VA.getLocInfo()) { 1921 case CCValAssign::Full: 1922 break; 1923 case CCValAssign::BCvt: 1924 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 1925 break; 1926 case CCValAssign::SExt: 1927 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 1928 break; 1929 case CCValAssign::ZExt: 1930 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 1931 break; 1932 case CCValAssign::AExt: 1933 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 1934 break; 1935 default: 1936 llvm_unreachable("Unknown loc info!"); 1937 } 1938 1939 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 1940 Flag = Chain.getValue(1); 1941 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 1942 } 1943 1944 // FIXME: Does sret work properly? 1945 if (!Info->isEntryFunction()) { 1946 const SIRegisterInfo *TRI 1947 = static_cast<const SISubtarget *>(Subtarget)->getRegisterInfo(); 1948 const MCPhysReg *I = 1949 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 1950 if (I) { 1951 for (; *I; ++I) { 1952 if (AMDGPU::SReg_64RegClass.contains(*I)) 1953 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 1954 else if (AMDGPU::SReg_32RegClass.contains(*I)) 1955 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 1956 else 1957 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 1958 } 1959 } 1960 } 1961 1962 // Update chain and glue. 1963 RetOps[0] = Chain; 1964 if (Flag.getNode()) 1965 RetOps.push_back(Flag); 1966 1967 unsigned Opc = AMDGPUISD::ENDPGM; 1968 if (!IsWaveEnd) 1969 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 1970 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 1971 } 1972 1973 SDValue SITargetLowering::LowerCallResult( 1974 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 1975 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 1976 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 1977 SDValue ThisVal) const { 1978 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 1979 1980 // Assign locations to each value returned by this call. 1981 SmallVector<CCValAssign, 16> RVLocs; 1982 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 1983 *DAG.getContext()); 1984 CCInfo.AnalyzeCallResult(Ins, RetCC); 1985 1986 // Copy all of the result registers out of their specified physreg. 1987 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1988 CCValAssign VA = RVLocs[i]; 1989 SDValue Val; 1990 1991 if (VA.isRegLoc()) { 1992 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 1993 Chain = Val.getValue(1); 1994 InFlag = Val.getValue(2); 1995 } else if (VA.isMemLoc()) { 1996 report_fatal_error("TODO: return values in memory"); 1997 } else 1998 llvm_unreachable("unknown argument location type"); 1999 2000 switch (VA.getLocInfo()) { 2001 case CCValAssign::Full: 2002 break; 2003 case CCValAssign::BCvt: 2004 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2005 break; 2006 case CCValAssign::ZExt: 2007 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2008 DAG.getValueType(VA.getValVT())); 2009 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2010 break; 2011 case CCValAssign::SExt: 2012 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2013 DAG.getValueType(VA.getValVT())); 2014 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2015 break; 2016 case CCValAssign::AExt: 2017 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2018 break; 2019 default: 2020 llvm_unreachable("Unknown loc info!"); 2021 } 2022 2023 InVals.push_back(Val); 2024 } 2025 2026 return Chain; 2027 } 2028 2029 // Add code to pass special inputs required depending on used features separate 2030 // from the explicit user arguments present in the IR. 2031 void SITargetLowering::passSpecialInputs( 2032 CallLoweringInfo &CLI, 2033 const SIMachineFunctionInfo &Info, 2034 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2035 SmallVectorImpl<SDValue> &MemOpChains, 2036 SDValue Chain, 2037 SDValue StackPtr) const { 2038 // If we don't have a call site, this was a call inserted by 2039 // legalization. These can never use special inputs. 2040 if (!CLI.CS) 2041 return; 2042 2043 const Function *CalleeFunc = CLI.CS.getCalledFunction(); 2044 assert(CalleeFunc); 2045 2046 SelectionDAG &DAG = CLI.DAG; 2047 const SDLoc &DL = CLI.DL; 2048 2049 const SISubtarget *ST = getSubtarget(); 2050 const SIRegisterInfo *TRI = ST->getRegisterInfo(); 2051 2052 auto &ArgUsageInfo = 2053 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2054 const AMDGPUFunctionArgInfo &CalleeArgInfo 2055 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2056 2057 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2058 2059 // TODO: Unify with private memory register handling. This is complicated by 2060 // the fact that at least in kernels, the input argument is not necessarily 2061 // in the same location as the input. 2062 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2063 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2064 AMDGPUFunctionArgInfo::QUEUE_PTR, 2065 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR, 2066 AMDGPUFunctionArgInfo::DISPATCH_ID, 2067 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2068 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2069 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z, 2070 AMDGPUFunctionArgInfo::WORKITEM_ID_X, 2071 AMDGPUFunctionArgInfo::WORKITEM_ID_Y, 2072 AMDGPUFunctionArgInfo::WORKITEM_ID_Z, 2073 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR 2074 }; 2075 2076 for (auto InputID : InputRegs) { 2077 const ArgDescriptor *OutgoingArg; 2078 const TargetRegisterClass *ArgRC; 2079 2080 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID); 2081 if (!OutgoingArg) 2082 continue; 2083 2084 const ArgDescriptor *IncomingArg; 2085 const TargetRegisterClass *IncomingArgRC; 2086 std::tie(IncomingArg, IncomingArgRC) 2087 = CallerArgInfo.getPreloadedValue(InputID); 2088 assert(IncomingArgRC == ArgRC); 2089 2090 // All special arguments are ints for now. 2091 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2092 SDValue InputReg; 2093 2094 if (IncomingArg) { 2095 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2096 } else { 2097 // The implicit arg ptr is special because it doesn't have a corresponding 2098 // input for kernels, and is computed from the kernarg segment pointer. 2099 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2100 InputReg = getImplicitArgPtr(DAG, DL); 2101 } 2102 2103 if (OutgoingArg->isRegister()) { 2104 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2105 } else { 2106 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, StackPtr, 2107 InputReg, 2108 OutgoingArg->getStackOffset()); 2109 MemOpChains.push_back(ArgStore); 2110 } 2111 } 2112 } 2113 2114 static bool canGuaranteeTCO(CallingConv::ID CC) { 2115 return CC == CallingConv::Fast; 2116 } 2117 2118 /// Return true if we might ever do TCO for calls with this calling convention. 2119 static bool mayTailCallThisCC(CallingConv::ID CC) { 2120 switch (CC) { 2121 case CallingConv::C: 2122 return true; 2123 default: 2124 return canGuaranteeTCO(CC); 2125 } 2126 } 2127 2128 bool SITargetLowering::isEligibleForTailCallOptimization( 2129 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2130 const SmallVectorImpl<ISD::OutputArg> &Outs, 2131 const SmallVectorImpl<SDValue> &OutVals, 2132 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2133 if (!mayTailCallThisCC(CalleeCC)) 2134 return false; 2135 2136 MachineFunction &MF = DAG.getMachineFunction(); 2137 const Function &CallerF = MF.getFunction(); 2138 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2139 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2140 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2141 2142 // Kernels aren't callable, and don't have a live in return address so it 2143 // doesn't make sense to do a tail call with entry functions. 2144 if (!CallerPreserved) 2145 return false; 2146 2147 bool CCMatch = CallerCC == CalleeCC; 2148 2149 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2150 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2151 return true; 2152 return false; 2153 } 2154 2155 // TODO: Can we handle var args? 2156 if (IsVarArg) 2157 return false; 2158 2159 for (const Argument &Arg : CallerF.args()) { 2160 if (Arg.hasByValAttr()) 2161 return false; 2162 } 2163 2164 LLVMContext &Ctx = *DAG.getContext(); 2165 2166 // Check that the call results are passed in the same way. 2167 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2168 CCAssignFnForCall(CalleeCC, IsVarArg), 2169 CCAssignFnForCall(CallerCC, IsVarArg))) 2170 return false; 2171 2172 // The callee has to preserve all registers the caller needs to preserve. 2173 if (!CCMatch) { 2174 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2175 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2176 return false; 2177 } 2178 2179 // Nothing more to check if the callee is taking no arguments. 2180 if (Outs.empty()) 2181 return true; 2182 2183 SmallVector<CCValAssign, 16> ArgLocs; 2184 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2185 2186 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2187 2188 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2189 // If the stack arguments for this call do not fit into our own save area then 2190 // the call cannot be made tail. 2191 // TODO: Is this really necessary? 2192 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2193 return false; 2194 2195 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2196 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2197 } 2198 2199 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2200 if (!CI->isTailCall()) 2201 return false; 2202 2203 const Function *ParentFn = CI->getParent()->getParent(); 2204 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2205 return false; 2206 2207 auto Attr = ParentFn->getFnAttribute("disable-tail-calls"); 2208 return (Attr.getValueAsString() != "true"); 2209 } 2210 2211 // The wave scratch offset register is used as the global base pointer. 2212 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2213 SmallVectorImpl<SDValue> &InVals) const { 2214 SelectionDAG &DAG = CLI.DAG; 2215 const SDLoc &DL = CLI.DL; 2216 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2217 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2218 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2219 SDValue Chain = CLI.Chain; 2220 SDValue Callee = CLI.Callee; 2221 bool &IsTailCall = CLI.IsTailCall; 2222 CallingConv::ID CallConv = CLI.CallConv; 2223 bool IsVarArg = CLI.IsVarArg; 2224 bool IsSibCall = false; 2225 bool IsThisReturn = false; 2226 MachineFunction &MF = DAG.getMachineFunction(); 2227 2228 if (IsVarArg) { 2229 return lowerUnhandledCall(CLI, InVals, 2230 "unsupported call to variadic function "); 2231 } 2232 2233 if (!CLI.CS.getCalledFunction()) { 2234 return lowerUnhandledCall(CLI, InVals, 2235 "unsupported indirect call to function "); 2236 } 2237 2238 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2239 return lowerUnhandledCall(CLI, InVals, 2240 "unsupported required tail call to function "); 2241 } 2242 2243 // The first 4 bytes are reserved for the callee's emergency stack slot. 2244 const unsigned CalleeUsableStackOffset = 4; 2245 2246 if (IsTailCall) { 2247 IsTailCall = isEligibleForTailCallOptimization( 2248 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2249 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) { 2250 report_fatal_error("failed to perform tail call elimination on a call " 2251 "site marked musttail"); 2252 } 2253 2254 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2255 2256 // A sibling call is one where we're under the usual C ABI and not planning 2257 // to change that but can still do a tail call: 2258 if (!TailCallOpt && IsTailCall) 2259 IsSibCall = true; 2260 2261 if (IsTailCall) 2262 ++NumTailCalls; 2263 } 2264 2265 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Callee)) { 2266 // FIXME: Remove this hack for function pointer types after removing 2267 // support of old address space mapping. In the new address space 2268 // mapping the pointer in default address space is 64 bit, therefore 2269 // does not need this hack. 2270 if (Callee.getValueType() == MVT::i32) { 2271 const GlobalValue *GV = GA->getGlobal(); 2272 Callee = DAG.getGlobalAddress(GV, DL, MVT::i64, GA->getOffset(), false, 2273 GA->getTargetFlags()); 2274 } 2275 } 2276 assert(Callee.getValueType() == MVT::i64); 2277 2278 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2279 2280 // Analyze operands of the call, assigning locations to each operand. 2281 SmallVector<CCValAssign, 16> ArgLocs; 2282 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2283 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2284 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2285 2286 // Get a count of how many bytes are to be pushed on the stack. 2287 unsigned NumBytes = CCInfo.getNextStackOffset(); 2288 2289 if (IsSibCall) { 2290 // Since we're not changing the ABI to make this a tail call, the memory 2291 // operands are already available in the caller's incoming argument space. 2292 NumBytes = 0; 2293 } 2294 2295 // FPDiff is the byte offset of the call's argument area from the callee's. 2296 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2297 // by this amount for a tail call. In a sibling call it must be 0 because the 2298 // caller will deallocate the entire stack and the callee still expects its 2299 // arguments to begin at SP+0. Completely unused for non-tail calls. 2300 int32_t FPDiff = 0; 2301 MachineFrameInfo &MFI = MF.getFrameInfo(); 2302 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2303 2304 SDValue CallerSavedFP; 2305 2306 // Adjust the stack pointer for the new arguments... 2307 // These operations are automatically eliminated by the prolog/epilog pass 2308 if (!IsSibCall) { 2309 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2310 2311 unsigned OffsetReg = Info->getScratchWaveOffsetReg(); 2312 2313 // In the HSA case, this should be an identity copy. 2314 SDValue ScratchRSrcReg 2315 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2316 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2317 2318 // TODO: Don't hardcode these registers and get from the callee function. 2319 SDValue ScratchWaveOffsetReg 2320 = DAG.getCopyFromReg(Chain, DL, OffsetReg, MVT::i32); 2321 RegsToPass.emplace_back(AMDGPU::SGPR4, ScratchWaveOffsetReg); 2322 2323 if (!Info->isEntryFunction()) { 2324 // Avoid clobbering this function's FP value. In the current convention 2325 // callee will overwrite this, so do save/restore around the call site. 2326 CallerSavedFP = DAG.getCopyFromReg(Chain, DL, 2327 Info->getFrameOffsetReg(), MVT::i32); 2328 } 2329 } 2330 2331 // Stack pointer relative accesses are done by changing the offset SGPR. This 2332 // is just the VGPR offset component. 2333 SDValue StackPtr = DAG.getConstant(CalleeUsableStackOffset, DL, MVT::i32); 2334 2335 SmallVector<SDValue, 8> MemOpChains; 2336 MVT PtrVT = MVT::i32; 2337 2338 // Walk the register/memloc assignments, inserting copies/loads. 2339 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 2340 ++i, ++realArgIdx) { 2341 CCValAssign &VA = ArgLocs[i]; 2342 SDValue Arg = OutVals[realArgIdx]; 2343 2344 // Promote the value if needed. 2345 switch (VA.getLocInfo()) { 2346 case CCValAssign::Full: 2347 break; 2348 case CCValAssign::BCvt: 2349 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2350 break; 2351 case CCValAssign::ZExt: 2352 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2353 break; 2354 case CCValAssign::SExt: 2355 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2356 break; 2357 case CCValAssign::AExt: 2358 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2359 break; 2360 case CCValAssign::FPExt: 2361 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2362 break; 2363 default: 2364 llvm_unreachable("Unknown loc info!"); 2365 } 2366 2367 if (VA.isRegLoc()) { 2368 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2369 } else { 2370 assert(VA.isMemLoc()); 2371 2372 SDValue DstAddr; 2373 MachinePointerInfo DstInfo; 2374 2375 unsigned LocMemOffset = VA.getLocMemOffset(); 2376 int32_t Offset = LocMemOffset; 2377 2378 SDValue PtrOff = DAG.getObjectPtrOffset(DL, StackPtr, Offset); 2379 2380 if (IsTailCall) { 2381 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2382 unsigned OpSize = Flags.isByVal() ? 2383 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2384 2385 Offset = Offset + FPDiff; 2386 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2387 2388 DstAddr = DAG.getObjectPtrOffset(DL, DAG.getFrameIndex(FI, PtrVT), 2389 StackPtr); 2390 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2391 2392 // Make sure any stack arguments overlapping with where we're storing 2393 // are loaded before this eventual operation. Otherwise they'll be 2394 // clobbered. 2395 2396 // FIXME: Why is this really necessary? This seems to just result in a 2397 // lot of code to copy the stack and write them back to the same 2398 // locations, which are supposed to be immutable? 2399 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2400 } else { 2401 DstAddr = PtrOff; 2402 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2403 } 2404 2405 if (Outs[i].Flags.isByVal()) { 2406 SDValue SizeNode = 2407 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2408 SDValue Cpy = DAG.getMemcpy( 2409 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 2410 /*isVol = */ false, /*AlwaysInline = */ true, 2411 /*isTailCall = */ false, DstInfo, 2412 MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy( 2413 *DAG.getContext(), AMDGPUASI.PRIVATE_ADDRESS)))); 2414 2415 MemOpChains.push_back(Cpy); 2416 } else { 2417 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo); 2418 MemOpChains.push_back(Store); 2419 } 2420 } 2421 } 2422 2423 // Copy special input registers after user input arguments. 2424 passSpecialInputs(CLI, *Info, RegsToPass, MemOpChains, Chain, StackPtr); 2425 2426 if (!MemOpChains.empty()) 2427 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2428 2429 // Build a sequence of copy-to-reg nodes chained together with token chain 2430 // and flag operands which copy the outgoing args into the appropriate regs. 2431 SDValue InFlag; 2432 for (auto &RegToPass : RegsToPass) { 2433 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2434 RegToPass.second, InFlag); 2435 InFlag = Chain.getValue(1); 2436 } 2437 2438 2439 SDValue PhysReturnAddrReg; 2440 if (IsTailCall) { 2441 // Since the return is being combined with the call, we need to pass on the 2442 // return address. 2443 2444 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2445 SDValue ReturnAddrReg = CreateLiveInRegister( 2446 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2447 2448 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2449 MVT::i64); 2450 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2451 InFlag = Chain.getValue(1); 2452 } 2453 2454 // We don't usually want to end the call-sequence here because we would tidy 2455 // the frame up *after* the call, however in the ABI-changing tail-call case 2456 // we've carefully laid out the parameters so that when sp is reset they'll be 2457 // in the correct location. 2458 if (IsTailCall && !IsSibCall) { 2459 Chain = DAG.getCALLSEQ_END(Chain, 2460 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2461 DAG.getTargetConstant(0, DL, MVT::i32), 2462 InFlag, DL); 2463 InFlag = Chain.getValue(1); 2464 } 2465 2466 std::vector<SDValue> Ops; 2467 Ops.push_back(Chain); 2468 Ops.push_back(Callee); 2469 2470 if (IsTailCall) { 2471 // Each tail call may have to adjust the stack by a different amount, so 2472 // this information must travel along with the operation for eventual 2473 // consumption by emitEpilogue. 2474 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 2475 2476 Ops.push_back(PhysReturnAddrReg); 2477 } 2478 2479 // Add argument registers to the end of the list so that they are known live 2480 // into the call. 2481 for (auto &RegToPass : RegsToPass) { 2482 Ops.push_back(DAG.getRegister(RegToPass.first, 2483 RegToPass.second.getValueType())); 2484 } 2485 2486 // Add a register mask operand representing the call-preserved registers. 2487 2488 const AMDGPURegisterInfo *TRI = Subtarget->getRegisterInfo(); 2489 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2490 assert(Mask && "Missing call preserved mask for calling convention"); 2491 Ops.push_back(DAG.getRegisterMask(Mask)); 2492 2493 if (InFlag.getNode()) 2494 Ops.push_back(InFlag); 2495 2496 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2497 2498 // If we're doing a tall call, use a TC_RETURN here rather than an 2499 // actual call instruction. 2500 if (IsTailCall) { 2501 MFI.setHasTailCall(); 2502 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 2503 } 2504 2505 // Returns a chain and a flag for retval copy to use. 2506 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 2507 Chain = Call.getValue(0); 2508 InFlag = Call.getValue(1); 2509 2510 if (CallerSavedFP) { 2511 SDValue FPReg = DAG.getRegister(Info->getFrameOffsetReg(), MVT::i32); 2512 Chain = DAG.getCopyToReg(Chain, DL, FPReg, CallerSavedFP, InFlag); 2513 InFlag = Chain.getValue(1); 2514 } 2515 2516 uint64_t CalleePopBytes = NumBytes; 2517 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 2518 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 2519 InFlag, DL); 2520 if (!Ins.empty()) 2521 InFlag = Chain.getValue(1); 2522 2523 // Handle result values, copying them out of physregs into vregs that we 2524 // return. 2525 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 2526 InVals, IsThisReturn, 2527 IsThisReturn ? OutVals[0] : SDValue()); 2528 } 2529 2530 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT, 2531 SelectionDAG &DAG) const { 2532 unsigned Reg = StringSwitch<unsigned>(RegName) 2533 .Case("m0", AMDGPU::M0) 2534 .Case("exec", AMDGPU::EXEC) 2535 .Case("exec_lo", AMDGPU::EXEC_LO) 2536 .Case("exec_hi", AMDGPU::EXEC_HI) 2537 .Case("flat_scratch", AMDGPU::FLAT_SCR) 2538 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 2539 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 2540 .Default(AMDGPU::NoRegister); 2541 2542 if (Reg == AMDGPU::NoRegister) { 2543 report_fatal_error(Twine("invalid register name \"" 2544 + StringRef(RegName) + "\".")); 2545 2546 } 2547 2548 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS && 2549 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 2550 report_fatal_error(Twine("invalid register \"" 2551 + StringRef(RegName) + "\" for subtarget.")); 2552 } 2553 2554 switch (Reg) { 2555 case AMDGPU::M0: 2556 case AMDGPU::EXEC_LO: 2557 case AMDGPU::EXEC_HI: 2558 case AMDGPU::FLAT_SCR_LO: 2559 case AMDGPU::FLAT_SCR_HI: 2560 if (VT.getSizeInBits() == 32) 2561 return Reg; 2562 break; 2563 case AMDGPU::EXEC: 2564 case AMDGPU::FLAT_SCR: 2565 if (VT.getSizeInBits() == 64) 2566 return Reg; 2567 break; 2568 default: 2569 llvm_unreachable("missing register type checking"); 2570 } 2571 2572 report_fatal_error(Twine("invalid type for register \"" 2573 + StringRef(RegName) + "\".")); 2574 } 2575 2576 // If kill is not the last instruction, split the block so kill is always a 2577 // proper terminator. 2578 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 2579 MachineBasicBlock *BB) const { 2580 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 2581 2582 MachineBasicBlock::iterator SplitPoint(&MI); 2583 ++SplitPoint; 2584 2585 if (SplitPoint == BB->end()) { 2586 // Don't bother with a new block. 2587 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 2588 return BB; 2589 } 2590 2591 MachineFunction *MF = BB->getParent(); 2592 MachineBasicBlock *SplitBB 2593 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 2594 2595 MF->insert(++MachineFunction::iterator(BB), SplitBB); 2596 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 2597 2598 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 2599 BB->addSuccessor(SplitBB); 2600 2601 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 2602 return SplitBB; 2603 } 2604 2605 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 2606 // wavefront. If the value is uniform and just happens to be in a VGPR, this 2607 // will only do one iteration. In the worst case, this will loop 64 times. 2608 // 2609 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 2610 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 2611 const SIInstrInfo *TII, 2612 MachineRegisterInfo &MRI, 2613 MachineBasicBlock &OrigBB, 2614 MachineBasicBlock &LoopBB, 2615 const DebugLoc &DL, 2616 const MachineOperand &IdxReg, 2617 unsigned InitReg, 2618 unsigned ResultReg, 2619 unsigned PhiReg, 2620 unsigned InitSaveExecReg, 2621 int Offset, 2622 bool UseGPRIdxMode, 2623 bool IsIndirectSrc) { 2624 MachineBasicBlock::iterator I = LoopBB.begin(); 2625 2626 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2627 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2628 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 2629 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2630 2631 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 2632 .addReg(InitReg) 2633 .addMBB(&OrigBB) 2634 .addReg(ResultReg) 2635 .addMBB(&LoopBB); 2636 2637 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 2638 .addReg(InitSaveExecReg) 2639 .addMBB(&OrigBB) 2640 .addReg(NewExec) 2641 .addMBB(&LoopBB); 2642 2643 // Read the next variant <- also loop target. 2644 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 2645 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 2646 2647 // Compare the just read M0 value to all possible Idx values. 2648 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 2649 .addReg(CurrentIdxReg) 2650 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 2651 2652 // Update EXEC, save the original EXEC value to VCC. 2653 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec) 2654 .addReg(CondReg, RegState::Kill); 2655 2656 MRI.setSimpleHint(NewExec, CondReg); 2657 2658 if (UseGPRIdxMode) { 2659 unsigned IdxReg; 2660 if (Offset == 0) { 2661 IdxReg = CurrentIdxReg; 2662 } else { 2663 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 2664 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 2665 .addReg(CurrentIdxReg, RegState::Kill) 2666 .addImm(Offset); 2667 } 2668 unsigned IdxMode = IsIndirectSrc ? 2669 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE; 2670 MachineInstr *SetOn = 2671 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2672 .addReg(IdxReg, RegState::Kill) 2673 .addImm(IdxMode); 2674 SetOn->getOperand(3).setIsUndef(); 2675 } else { 2676 // Move index from VCC into M0 2677 if (Offset == 0) { 2678 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 2679 .addReg(CurrentIdxReg, RegState::Kill); 2680 } else { 2681 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 2682 .addReg(CurrentIdxReg, RegState::Kill) 2683 .addImm(Offset); 2684 } 2685 } 2686 2687 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 2688 MachineInstr *InsertPt = 2689 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC) 2690 .addReg(AMDGPU::EXEC) 2691 .addReg(NewExec); 2692 2693 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 2694 // s_cbranch_scc0? 2695 2696 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 2697 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 2698 .addMBB(&LoopBB); 2699 2700 return InsertPt->getIterator(); 2701 } 2702 2703 // This has slightly sub-optimal regalloc when the source vector is killed by 2704 // the read. The register allocator does not understand that the kill is 2705 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 2706 // subregister from it, using 1 more VGPR than necessary. This was saved when 2707 // this was expanded after register allocation. 2708 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 2709 MachineBasicBlock &MBB, 2710 MachineInstr &MI, 2711 unsigned InitResultReg, 2712 unsigned PhiReg, 2713 int Offset, 2714 bool UseGPRIdxMode, 2715 bool IsIndirectSrc) { 2716 MachineFunction *MF = MBB.getParent(); 2717 MachineRegisterInfo &MRI = MF->getRegInfo(); 2718 const DebugLoc &DL = MI.getDebugLoc(); 2719 MachineBasicBlock::iterator I(&MI); 2720 2721 unsigned DstReg = MI.getOperand(0).getReg(); 2722 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass); 2723 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass); 2724 2725 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 2726 2727 // Save the EXEC mask 2728 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec) 2729 .addReg(AMDGPU::EXEC); 2730 2731 // To insert the loop we need to split the block. Move everything after this 2732 // point to a new block, and insert a new empty block between the two. 2733 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 2734 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 2735 MachineFunction::iterator MBBI(MBB); 2736 ++MBBI; 2737 2738 MF->insert(MBBI, LoopBB); 2739 MF->insert(MBBI, RemainderBB); 2740 2741 LoopBB->addSuccessor(LoopBB); 2742 LoopBB->addSuccessor(RemainderBB); 2743 2744 // Move the rest of the block into a new block. 2745 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 2746 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 2747 2748 MBB.addSuccessor(LoopBB); 2749 2750 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 2751 2752 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 2753 InitResultReg, DstReg, PhiReg, TmpExec, 2754 Offset, UseGPRIdxMode, IsIndirectSrc); 2755 2756 MachineBasicBlock::iterator First = RemainderBB->begin(); 2757 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC) 2758 .addReg(SaveExec); 2759 2760 return InsPt; 2761 } 2762 2763 // Returns subreg index, offset 2764 static std::pair<unsigned, int> 2765 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 2766 const TargetRegisterClass *SuperRC, 2767 unsigned VecReg, 2768 int Offset) { 2769 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 2770 2771 // Skip out of bounds offsets, or else we would end up using an undefined 2772 // register. 2773 if (Offset >= NumElts || Offset < 0) 2774 return std::make_pair(AMDGPU::sub0, Offset); 2775 2776 return std::make_pair(AMDGPU::sub0 + Offset, 0); 2777 } 2778 2779 // Return true if the index is an SGPR and was set. 2780 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 2781 MachineRegisterInfo &MRI, 2782 MachineInstr &MI, 2783 int Offset, 2784 bool UseGPRIdxMode, 2785 bool IsIndirectSrc) { 2786 MachineBasicBlock *MBB = MI.getParent(); 2787 const DebugLoc &DL = MI.getDebugLoc(); 2788 MachineBasicBlock::iterator I(&MI); 2789 2790 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 2791 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 2792 2793 assert(Idx->getReg() != AMDGPU::NoRegister); 2794 2795 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 2796 return false; 2797 2798 if (UseGPRIdxMode) { 2799 unsigned IdxMode = IsIndirectSrc ? 2800 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE; 2801 if (Offset == 0) { 2802 MachineInstr *SetOn = 2803 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2804 .add(*Idx) 2805 .addImm(IdxMode); 2806 2807 SetOn->getOperand(3).setIsUndef(); 2808 } else { 2809 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 2810 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 2811 .add(*Idx) 2812 .addImm(Offset); 2813 MachineInstr *SetOn = 2814 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2815 .addReg(Tmp, RegState::Kill) 2816 .addImm(IdxMode); 2817 2818 SetOn->getOperand(3).setIsUndef(); 2819 } 2820 2821 return true; 2822 } 2823 2824 if (Offset == 0) { 2825 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 2826 .add(*Idx); 2827 } else { 2828 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 2829 .add(*Idx) 2830 .addImm(Offset); 2831 } 2832 2833 return true; 2834 } 2835 2836 // Control flow needs to be inserted if indexing with a VGPR. 2837 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 2838 MachineBasicBlock &MBB, 2839 const SISubtarget &ST) { 2840 const SIInstrInfo *TII = ST.getInstrInfo(); 2841 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 2842 MachineFunction *MF = MBB.getParent(); 2843 MachineRegisterInfo &MRI = MF->getRegInfo(); 2844 2845 unsigned Dst = MI.getOperand(0).getReg(); 2846 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 2847 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 2848 2849 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 2850 2851 unsigned SubReg; 2852 std::tie(SubReg, Offset) 2853 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 2854 2855 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 2856 2857 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 2858 MachineBasicBlock::iterator I(&MI); 2859 const DebugLoc &DL = MI.getDebugLoc(); 2860 2861 if (UseGPRIdxMode) { 2862 // TODO: Look at the uses to avoid the copy. This may require rescheduling 2863 // to avoid interfering with other uses, so probably requires a new 2864 // optimization pass. 2865 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 2866 .addReg(SrcReg, RegState::Undef, SubReg) 2867 .addReg(SrcReg, RegState::Implicit) 2868 .addReg(AMDGPU::M0, RegState::Implicit); 2869 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2870 } else { 2871 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 2872 .addReg(SrcReg, RegState::Undef, SubReg) 2873 .addReg(SrcReg, RegState::Implicit); 2874 } 2875 2876 MI.eraseFromParent(); 2877 2878 return &MBB; 2879 } 2880 2881 const DebugLoc &DL = MI.getDebugLoc(); 2882 MachineBasicBlock::iterator I(&MI); 2883 2884 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 2885 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 2886 2887 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 2888 2889 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 2890 Offset, UseGPRIdxMode, true); 2891 MachineBasicBlock *LoopBB = InsPt->getParent(); 2892 2893 if (UseGPRIdxMode) { 2894 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 2895 .addReg(SrcReg, RegState::Undef, SubReg) 2896 .addReg(SrcReg, RegState::Implicit) 2897 .addReg(AMDGPU::M0, RegState::Implicit); 2898 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2899 } else { 2900 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 2901 .addReg(SrcReg, RegState::Undef, SubReg) 2902 .addReg(SrcReg, RegState::Implicit); 2903 } 2904 2905 MI.eraseFromParent(); 2906 2907 return LoopBB; 2908 } 2909 2910 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI, 2911 const TargetRegisterClass *VecRC) { 2912 switch (TRI.getRegSizeInBits(*VecRC)) { 2913 case 32: // 4 bytes 2914 return AMDGPU::V_MOVRELD_B32_V1; 2915 case 64: // 8 bytes 2916 return AMDGPU::V_MOVRELD_B32_V2; 2917 case 128: // 16 bytes 2918 return AMDGPU::V_MOVRELD_B32_V4; 2919 case 256: // 32 bytes 2920 return AMDGPU::V_MOVRELD_B32_V8; 2921 case 512: // 64 bytes 2922 return AMDGPU::V_MOVRELD_B32_V16; 2923 default: 2924 llvm_unreachable("unsupported size for MOVRELD pseudos"); 2925 } 2926 } 2927 2928 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 2929 MachineBasicBlock &MBB, 2930 const SISubtarget &ST) { 2931 const SIInstrInfo *TII = ST.getInstrInfo(); 2932 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 2933 MachineFunction *MF = MBB.getParent(); 2934 MachineRegisterInfo &MRI = MF->getRegInfo(); 2935 2936 unsigned Dst = MI.getOperand(0).getReg(); 2937 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 2938 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 2939 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 2940 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 2941 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 2942 2943 // This can be an immediate, but will be folded later. 2944 assert(Val->getReg()); 2945 2946 unsigned SubReg; 2947 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 2948 SrcVec->getReg(), 2949 Offset); 2950 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 2951 2952 if (Idx->getReg() == AMDGPU::NoRegister) { 2953 MachineBasicBlock::iterator I(&MI); 2954 const DebugLoc &DL = MI.getDebugLoc(); 2955 2956 assert(Offset == 0); 2957 2958 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 2959 .add(*SrcVec) 2960 .add(*Val) 2961 .addImm(SubReg); 2962 2963 MI.eraseFromParent(); 2964 return &MBB; 2965 } 2966 2967 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 2968 MachineBasicBlock::iterator I(&MI); 2969 const DebugLoc &DL = MI.getDebugLoc(); 2970 2971 if (UseGPRIdxMode) { 2972 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 2973 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst 2974 .add(*Val) 2975 .addReg(Dst, RegState::ImplicitDefine) 2976 .addReg(SrcVec->getReg(), RegState::Implicit) 2977 .addReg(AMDGPU::M0, RegState::Implicit); 2978 2979 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2980 } else { 2981 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 2982 2983 BuildMI(MBB, I, DL, MovRelDesc) 2984 .addReg(Dst, RegState::Define) 2985 .addReg(SrcVec->getReg()) 2986 .add(*Val) 2987 .addImm(SubReg - AMDGPU::sub0); 2988 } 2989 2990 MI.eraseFromParent(); 2991 return &MBB; 2992 } 2993 2994 if (Val->isReg()) 2995 MRI.clearKillFlags(Val->getReg()); 2996 2997 const DebugLoc &DL = MI.getDebugLoc(); 2998 2999 unsigned PhiReg = MRI.createVirtualRegister(VecRC); 3000 3001 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3002 Offset, UseGPRIdxMode, false); 3003 MachineBasicBlock *LoopBB = InsPt->getParent(); 3004 3005 if (UseGPRIdxMode) { 3006 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 3007 .addReg(PhiReg, RegState::Undef, SubReg) // vdst 3008 .add(*Val) // src0 3009 .addReg(Dst, RegState::ImplicitDefine) 3010 .addReg(PhiReg, RegState::Implicit) 3011 .addReg(AMDGPU::M0, RegState::Implicit); 3012 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3013 } else { 3014 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 3015 3016 BuildMI(*LoopBB, InsPt, DL, MovRelDesc) 3017 .addReg(Dst, RegState::Define) 3018 .addReg(PhiReg) 3019 .add(*Val) 3020 .addImm(SubReg - AMDGPU::sub0); 3021 } 3022 3023 MI.eraseFromParent(); 3024 3025 return LoopBB; 3026 } 3027 3028 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3029 MachineInstr &MI, MachineBasicBlock *BB) const { 3030 3031 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3032 MachineFunction *MF = BB->getParent(); 3033 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3034 3035 if (TII->isMIMG(MI)) { 3036 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 3037 report_fatal_error("missing mem operand from MIMG instruction"); 3038 } 3039 // Add a memoperand for mimg instructions so that they aren't assumed to 3040 // be ordered memory instuctions. 3041 3042 return BB; 3043 } 3044 3045 switch (MI.getOpcode()) { 3046 case AMDGPU::S_ADD_U64_PSEUDO: 3047 case AMDGPU::S_SUB_U64_PSEUDO: { 3048 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3049 const DebugLoc &DL = MI.getDebugLoc(); 3050 3051 MachineOperand &Dest = MI.getOperand(0); 3052 MachineOperand &Src0 = MI.getOperand(1); 3053 MachineOperand &Src1 = MI.getOperand(2); 3054 3055 unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3056 unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3057 3058 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3059 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub0, 3060 &AMDGPU::SReg_32_XM0RegClass); 3061 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3062 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub1, 3063 &AMDGPU::SReg_32_XM0RegClass); 3064 3065 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3066 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub0, 3067 &AMDGPU::SReg_32_XM0RegClass); 3068 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3069 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub1, 3070 &AMDGPU::SReg_32_XM0RegClass); 3071 3072 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3073 3074 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3075 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3076 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3077 .add(Src0Sub0) 3078 .add(Src1Sub0); 3079 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3080 .add(Src0Sub1) 3081 .add(Src1Sub1); 3082 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3083 .addReg(DestSub0) 3084 .addImm(AMDGPU::sub0) 3085 .addReg(DestSub1) 3086 .addImm(AMDGPU::sub1); 3087 MI.eraseFromParent(); 3088 return BB; 3089 } 3090 case AMDGPU::SI_INIT_M0: { 3091 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3092 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3093 .add(MI.getOperand(0)); 3094 MI.eraseFromParent(); 3095 return BB; 3096 } 3097 case AMDGPU::SI_INIT_EXEC: 3098 // This should be before all vector instructions. 3099 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3100 AMDGPU::EXEC) 3101 .addImm(MI.getOperand(0).getImm()); 3102 MI.eraseFromParent(); 3103 return BB; 3104 3105 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3106 // Extract the thread count from an SGPR input and set EXEC accordingly. 3107 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3108 // 3109 // S_BFE_U32 count, input, {shift, 7} 3110 // S_BFM_B64 exec, count, 0 3111 // S_CMP_EQ_U32 count, 64 3112 // S_CMOV_B64 exec, -1 3113 MachineInstr *FirstMI = &*BB->begin(); 3114 MachineRegisterInfo &MRI = MF->getRegInfo(); 3115 unsigned InputReg = MI.getOperand(0).getReg(); 3116 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3117 bool Found = false; 3118 3119 // Move the COPY of the input reg to the beginning, so that we can use it. 3120 for (auto I = BB->begin(); I != &MI; I++) { 3121 if (I->getOpcode() != TargetOpcode::COPY || 3122 I->getOperand(0).getReg() != InputReg) 3123 continue; 3124 3125 if (I == FirstMI) { 3126 FirstMI = &*++BB->begin(); 3127 } else { 3128 I->removeFromParent(); 3129 BB->insert(FirstMI, &*I); 3130 } 3131 Found = true; 3132 break; 3133 } 3134 assert(Found); 3135 (void)Found; 3136 3137 // This should be before all vector instructions. 3138 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3139 .addReg(InputReg) 3140 .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000); 3141 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64), 3142 AMDGPU::EXEC) 3143 .addReg(CountReg) 3144 .addImm(0); 3145 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3146 .addReg(CountReg, RegState::Kill) 3147 .addImm(64); 3148 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64), 3149 AMDGPU::EXEC) 3150 .addImm(-1); 3151 MI.eraseFromParent(); 3152 return BB; 3153 } 3154 3155 case AMDGPU::GET_GROUPSTATICSIZE: { 3156 DebugLoc DL = MI.getDebugLoc(); 3157 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3158 .add(MI.getOperand(0)) 3159 .addImm(MFI->getLDSSize()); 3160 MI.eraseFromParent(); 3161 return BB; 3162 } 3163 case AMDGPU::SI_INDIRECT_SRC_V1: 3164 case AMDGPU::SI_INDIRECT_SRC_V2: 3165 case AMDGPU::SI_INDIRECT_SRC_V4: 3166 case AMDGPU::SI_INDIRECT_SRC_V8: 3167 case AMDGPU::SI_INDIRECT_SRC_V16: 3168 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3169 case AMDGPU::SI_INDIRECT_DST_V1: 3170 case AMDGPU::SI_INDIRECT_DST_V2: 3171 case AMDGPU::SI_INDIRECT_DST_V4: 3172 case AMDGPU::SI_INDIRECT_DST_V8: 3173 case AMDGPU::SI_INDIRECT_DST_V16: 3174 return emitIndirectDst(MI, *BB, *getSubtarget()); 3175 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3176 case AMDGPU::SI_KILL_I1_PSEUDO: 3177 return splitKillBlock(MI, BB); 3178 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3179 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3180 3181 unsigned Dst = MI.getOperand(0).getReg(); 3182 unsigned Src0 = MI.getOperand(1).getReg(); 3183 unsigned Src1 = MI.getOperand(2).getReg(); 3184 const DebugLoc &DL = MI.getDebugLoc(); 3185 unsigned SrcCond = MI.getOperand(3).getReg(); 3186 3187 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3188 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3189 unsigned SrcCondCopy = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass); 3190 3191 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3192 .addReg(SrcCond); 3193 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3194 .addReg(Src0, 0, AMDGPU::sub0) 3195 .addReg(Src1, 0, AMDGPU::sub0) 3196 .addReg(SrcCondCopy); 3197 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3198 .addReg(Src0, 0, AMDGPU::sub1) 3199 .addReg(Src1, 0, AMDGPU::sub1) 3200 .addReg(SrcCondCopy); 3201 3202 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3203 .addReg(DstLo) 3204 .addImm(AMDGPU::sub0) 3205 .addReg(DstHi) 3206 .addImm(AMDGPU::sub1); 3207 MI.eraseFromParent(); 3208 return BB; 3209 } 3210 case AMDGPU::SI_BR_UNDEF: { 3211 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3212 const DebugLoc &DL = MI.getDebugLoc(); 3213 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3214 .add(MI.getOperand(0)); 3215 Br->getOperand(1).setIsUndef(true); // read undef SCC 3216 MI.eraseFromParent(); 3217 return BB; 3218 } 3219 case AMDGPU::ADJCALLSTACKUP: 3220 case AMDGPU::ADJCALLSTACKDOWN: { 3221 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3222 MachineInstrBuilder MIB(*MF, &MI); 3223 3224 // Add an implicit use of the frame offset reg to prevent the restore copy 3225 // inserted after the call from being reorderd after stack operations in the 3226 // the caller's frame. 3227 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3228 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 3229 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 3230 return BB; 3231 } 3232 case AMDGPU::SI_CALL_ISEL: 3233 case AMDGPU::SI_TCRETURN_ISEL: { 3234 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3235 const DebugLoc &DL = MI.getDebugLoc(); 3236 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3237 3238 MachineRegisterInfo &MRI = MF->getRegInfo(); 3239 unsigned GlobalAddrReg = MI.getOperand(0).getReg(); 3240 MachineInstr *PCRel = MRI.getVRegDef(GlobalAddrReg); 3241 assert(PCRel->getOpcode() == AMDGPU::SI_PC_ADD_REL_OFFSET); 3242 3243 const GlobalValue *G = PCRel->getOperand(1).getGlobal(); 3244 3245 MachineInstrBuilder MIB; 3246 if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) { 3247 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg) 3248 .add(MI.getOperand(0)) 3249 .addGlobalAddress(G); 3250 } else { 3251 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_TCRETURN)) 3252 .add(MI.getOperand(0)) 3253 .addGlobalAddress(G); 3254 3255 // There is an additional imm operand for tcreturn, but it should be in the 3256 // right place already. 3257 } 3258 3259 for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I) 3260 MIB.add(MI.getOperand(I)); 3261 3262 MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end()); 3263 MI.eraseFromParent(); 3264 return BB; 3265 } 3266 default: 3267 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3268 } 3269 } 3270 3271 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 3272 return isTypeLegal(VT.getScalarType()); 3273 } 3274 3275 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3276 // This currently forces unfolding various combinations of fsub into fma with 3277 // free fneg'd operands. As long as we have fast FMA (controlled by 3278 // isFMAFasterThanFMulAndFAdd), we should perform these. 3279 3280 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3281 // most of these combines appear to be cycle neutral but save on instruction 3282 // count / code size. 3283 return true; 3284 } 3285 3286 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3287 EVT VT) const { 3288 if (!VT.isVector()) { 3289 return MVT::i1; 3290 } 3291 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3292 } 3293 3294 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3295 // TODO: Should i16 be used always if legal? For now it would force VALU 3296 // shifts. 3297 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3298 } 3299 3300 // Answering this is somewhat tricky and depends on the specific device which 3301 // have different rates for fma or all f64 operations. 3302 // 3303 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3304 // regardless of which device (although the number of cycles differs between 3305 // devices), so it is always profitable for f64. 3306 // 3307 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3308 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3309 // which we can always do even without fused FP ops since it returns the same 3310 // result as the separate operations and since it is always full 3311 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3312 // however does not support denormals, so we do report fma as faster if we have 3313 // a fast fma device and require denormals. 3314 // 3315 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 3316 VT = VT.getScalarType(); 3317 3318 switch (VT.getSimpleVT().SimpleTy) { 3319 case MVT::f32: { 3320 // This is as fast on some subtargets. However, we always have full rate f32 3321 // mad available which returns the same result as the separate operations 3322 // which we should prefer over fma. We can't use this if we want to support 3323 // denormals, so only report this in these cases. 3324 if (Subtarget->hasFP32Denormals()) 3325 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 3326 3327 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 3328 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 3329 } 3330 case MVT::f64: 3331 return true; 3332 case MVT::f16: 3333 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals(); 3334 default: 3335 break; 3336 } 3337 3338 return false; 3339 } 3340 3341 //===----------------------------------------------------------------------===// 3342 // Custom DAG Lowering Operations 3343 //===----------------------------------------------------------------------===// 3344 3345 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 3346 switch (Op.getOpcode()) { 3347 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 3348 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 3349 case ISD::LOAD: { 3350 SDValue Result = LowerLOAD(Op, DAG); 3351 assert((!Result.getNode() || 3352 Result.getNode()->getNumValues() == 2) && 3353 "Load should return a value and a chain"); 3354 return Result; 3355 } 3356 3357 case ISD::FSIN: 3358 case ISD::FCOS: 3359 return LowerTrig(Op, DAG); 3360 case ISD::SELECT: return LowerSELECT(Op, DAG); 3361 case ISD::FDIV: return LowerFDIV(Op, DAG); 3362 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 3363 case ISD::STORE: return LowerSTORE(Op, DAG); 3364 case ISD::GlobalAddress: { 3365 MachineFunction &MF = DAG.getMachineFunction(); 3366 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 3367 return LowerGlobalAddress(MFI, Op, DAG); 3368 } 3369 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3370 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 3371 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 3372 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 3373 case ISD::INSERT_VECTOR_ELT: 3374 return lowerINSERT_VECTOR_ELT(Op, DAG); 3375 case ISD::EXTRACT_VECTOR_ELT: 3376 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3377 case ISD::BUILD_VECTOR: 3378 return lowerBUILD_VECTOR(Op, DAG); 3379 case ISD::FP_ROUND: 3380 return lowerFP_ROUND(Op, DAG); 3381 case ISD::TRAP: 3382 return lowerTRAP(Op, DAG); 3383 case ISD::DEBUGTRAP: 3384 return lowerDEBUGTRAP(Op, DAG); 3385 } 3386 return SDValue(); 3387 } 3388 3389 static unsigned getImageOpcode(unsigned IID) { 3390 switch (IID) { 3391 case Intrinsic::amdgcn_image_load: 3392 return AMDGPUISD::IMAGE_LOAD; 3393 case Intrinsic::amdgcn_image_load_mip: 3394 return AMDGPUISD::IMAGE_LOAD_MIP; 3395 3396 // Basic sample. 3397 case Intrinsic::amdgcn_image_sample: 3398 return AMDGPUISD::IMAGE_SAMPLE; 3399 case Intrinsic::amdgcn_image_sample_cl: 3400 return AMDGPUISD::IMAGE_SAMPLE_CL; 3401 case Intrinsic::amdgcn_image_sample_d: 3402 return AMDGPUISD::IMAGE_SAMPLE_D; 3403 case Intrinsic::amdgcn_image_sample_d_cl: 3404 return AMDGPUISD::IMAGE_SAMPLE_D_CL; 3405 case Intrinsic::amdgcn_image_sample_l: 3406 return AMDGPUISD::IMAGE_SAMPLE_L; 3407 case Intrinsic::amdgcn_image_sample_b: 3408 return AMDGPUISD::IMAGE_SAMPLE_B; 3409 case Intrinsic::amdgcn_image_sample_b_cl: 3410 return AMDGPUISD::IMAGE_SAMPLE_B_CL; 3411 case Intrinsic::amdgcn_image_sample_lz: 3412 return AMDGPUISD::IMAGE_SAMPLE_LZ; 3413 case Intrinsic::amdgcn_image_sample_cd: 3414 return AMDGPUISD::IMAGE_SAMPLE_CD; 3415 case Intrinsic::amdgcn_image_sample_cd_cl: 3416 return AMDGPUISD::IMAGE_SAMPLE_CD_CL; 3417 3418 // Sample with comparison. 3419 case Intrinsic::amdgcn_image_sample_c: 3420 return AMDGPUISD::IMAGE_SAMPLE_C; 3421 case Intrinsic::amdgcn_image_sample_c_cl: 3422 return AMDGPUISD::IMAGE_SAMPLE_C_CL; 3423 case Intrinsic::amdgcn_image_sample_c_d: 3424 return AMDGPUISD::IMAGE_SAMPLE_C_D; 3425 case Intrinsic::amdgcn_image_sample_c_d_cl: 3426 return AMDGPUISD::IMAGE_SAMPLE_C_D_CL; 3427 case Intrinsic::amdgcn_image_sample_c_l: 3428 return AMDGPUISD::IMAGE_SAMPLE_C_L; 3429 case Intrinsic::amdgcn_image_sample_c_b: 3430 return AMDGPUISD::IMAGE_SAMPLE_C_B; 3431 case Intrinsic::amdgcn_image_sample_c_b_cl: 3432 return AMDGPUISD::IMAGE_SAMPLE_C_B_CL; 3433 case Intrinsic::amdgcn_image_sample_c_lz: 3434 return AMDGPUISD::IMAGE_SAMPLE_C_LZ; 3435 case Intrinsic::amdgcn_image_sample_c_cd: 3436 return AMDGPUISD::IMAGE_SAMPLE_C_CD; 3437 case Intrinsic::amdgcn_image_sample_c_cd_cl: 3438 return AMDGPUISD::IMAGE_SAMPLE_C_CD_CL; 3439 3440 // Sample with offsets. 3441 case Intrinsic::amdgcn_image_sample_o: 3442 return AMDGPUISD::IMAGE_SAMPLE_O; 3443 case Intrinsic::amdgcn_image_sample_cl_o: 3444 return AMDGPUISD::IMAGE_SAMPLE_CL_O; 3445 case Intrinsic::amdgcn_image_sample_d_o: 3446 return AMDGPUISD::IMAGE_SAMPLE_D_O; 3447 case Intrinsic::amdgcn_image_sample_d_cl_o: 3448 return AMDGPUISD::IMAGE_SAMPLE_D_CL_O; 3449 case Intrinsic::amdgcn_image_sample_l_o: 3450 return AMDGPUISD::IMAGE_SAMPLE_L_O; 3451 case Intrinsic::amdgcn_image_sample_b_o: 3452 return AMDGPUISD::IMAGE_SAMPLE_B_O; 3453 case Intrinsic::amdgcn_image_sample_b_cl_o: 3454 return AMDGPUISD::IMAGE_SAMPLE_B_CL_O; 3455 case Intrinsic::amdgcn_image_sample_lz_o: 3456 return AMDGPUISD::IMAGE_SAMPLE_LZ_O; 3457 case Intrinsic::amdgcn_image_sample_cd_o: 3458 return AMDGPUISD::IMAGE_SAMPLE_CD_O; 3459 case Intrinsic::amdgcn_image_sample_cd_cl_o: 3460 return AMDGPUISD::IMAGE_SAMPLE_CD_CL_O; 3461 3462 // Sample with comparison and offsets. 3463 case Intrinsic::amdgcn_image_sample_c_o: 3464 return AMDGPUISD::IMAGE_SAMPLE_C_O; 3465 case Intrinsic::amdgcn_image_sample_c_cl_o: 3466 return AMDGPUISD::IMAGE_SAMPLE_C_CL_O; 3467 case Intrinsic::amdgcn_image_sample_c_d_o: 3468 return AMDGPUISD::IMAGE_SAMPLE_C_D_O; 3469 case Intrinsic::amdgcn_image_sample_c_d_cl_o: 3470 return AMDGPUISD::IMAGE_SAMPLE_C_D_CL_O; 3471 case Intrinsic::amdgcn_image_sample_c_l_o: 3472 return AMDGPUISD::IMAGE_SAMPLE_C_L_O; 3473 case Intrinsic::amdgcn_image_sample_c_b_o: 3474 return AMDGPUISD::IMAGE_SAMPLE_C_B_O; 3475 case Intrinsic::amdgcn_image_sample_c_b_cl_o: 3476 return AMDGPUISD::IMAGE_SAMPLE_C_B_CL_O; 3477 case Intrinsic::amdgcn_image_sample_c_lz_o: 3478 return AMDGPUISD::IMAGE_SAMPLE_C_LZ_O; 3479 case Intrinsic::amdgcn_image_sample_c_cd_o: 3480 return AMDGPUISD::IMAGE_SAMPLE_C_CD_O; 3481 case Intrinsic::amdgcn_image_sample_c_cd_cl_o: 3482 return AMDGPUISD::IMAGE_SAMPLE_C_CD_CL_O; 3483 3484 // Basic gather4. 3485 case Intrinsic::amdgcn_image_gather4: 3486 return AMDGPUISD::IMAGE_GATHER4; 3487 case Intrinsic::amdgcn_image_gather4_cl: 3488 return AMDGPUISD::IMAGE_GATHER4_CL; 3489 case Intrinsic::amdgcn_image_gather4_l: 3490 return AMDGPUISD::IMAGE_GATHER4_L; 3491 case Intrinsic::amdgcn_image_gather4_b: 3492 return AMDGPUISD::IMAGE_GATHER4_B; 3493 case Intrinsic::amdgcn_image_gather4_b_cl: 3494 return AMDGPUISD::IMAGE_GATHER4_B_CL; 3495 case Intrinsic::amdgcn_image_gather4_lz: 3496 return AMDGPUISD::IMAGE_GATHER4_LZ; 3497 3498 // Gather4 with comparison. 3499 case Intrinsic::amdgcn_image_gather4_c: 3500 return AMDGPUISD::IMAGE_GATHER4_C; 3501 case Intrinsic::amdgcn_image_gather4_c_cl: 3502 return AMDGPUISD::IMAGE_GATHER4_C_CL; 3503 case Intrinsic::amdgcn_image_gather4_c_l: 3504 return AMDGPUISD::IMAGE_GATHER4_C_L; 3505 case Intrinsic::amdgcn_image_gather4_c_b: 3506 return AMDGPUISD::IMAGE_GATHER4_C_B; 3507 case Intrinsic::amdgcn_image_gather4_c_b_cl: 3508 return AMDGPUISD::IMAGE_GATHER4_C_B_CL; 3509 case Intrinsic::amdgcn_image_gather4_c_lz: 3510 return AMDGPUISD::IMAGE_GATHER4_C_LZ; 3511 3512 // Gather4 with offsets. 3513 case Intrinsic::amdgcn_image_gather4_o: 3514 return AMDGPUISD::IMAGE_GATHER4_O; 3515 case Intrinsic::amdgcn_image_gather4_cl_o: 3516 return AMDGPUISD::IMAGE_GATHER4_CL_O; 3517 case Intrinsic::amdgcn_image_gather4_l_o: 3518 return AMDGPUISD::IMAGE_GATHER4_L_O; 3519 case Intrinsic::amdgcn_image_gather4_b_o: 3520 return AMDGPUISD::IMAGE_GATHER4_B_O; 3521 case Intrinsic::amdgcn_image_gather4_b_cl_o: 3522 return AMDGPUISD::IMAGE_GATHER4_B_CL_O; 3523 case Intrinsic::amdgcn_image_gather4_lz_o: 3524 return AMDGPUISD::IMAGE_GATHER4_LZ_O; 3525 3526 // Gather4 with comparison and offsets. 3527 case Intrinsic::amdgcn_image_gather4_c_o: 3528 return AMDGPUISD::IMAGE_GATHER4_C_O; 3529 case Intrinsic::amdgcn_image_gather4_c_cl_o: 3530 return AMDGPUISD::IMAGE_GATHER4_C_CL_O; 3531 case Intrinsic::amdgcn_image_gather4_c_l_o: 3532 return AMDGPUISD::IMAGE_GATHER4_C_L_O; 3533 case Intrinsic::amdgcn_image_gather4_c_b_o: 3534 return AMDGPUISD::IMAGE_GATHER4_C_B_O; 3535 case Intrinsic::amdgcn_image_gather4_c_b_cl_o: 3536 return AMDGPUISD::IMAGE_GATHER4_C_B_CL_O; 3537 case Intrinsic::amdgcn_image_gather4_c_lz_o: 3538 return AMDGPUISD::IMAGE_GATHER4_C_LZ_O; 3539 3540 default: 3541 break; 3542 } 3543 return 0; 3544 } 3545 3546 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 3547 const SDLoc &DL, 3548 SelectionDAG &DAG, bool Unpacked) { 3549 if (!LoadVT.isVector()) 3550 return Result; 3551 3552 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 3553 // Truncate to v2i16/v4i16. 3554 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 3555 3556 // Workaround legalizer not scalarizing truncate after vector op 3557 // legalization byt not creating intermediate vector trunc. 3558 SmallVector<SDValue, 4> Elts; 3559 DAG.ExtractVectorElements(Result, Elts); 3560 for (SDValue &Elt : Elts) 3561 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 3562 3563 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 3564 3565 // Bitcast to original type (v2f16/v4f16). 3566 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 3567 } 3568 3569 // Cast back to the original packed type. 3570 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 3571 } 3572 3573 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 3574 MemSDNode *M, 3575 SelectionDAG &DAG, 3576 bool IsIntrinsic) const { 3577 SDLoc DL(M); 3578 SmallVector<SDValue, 10> Ops; 3579 Ops.reserve(M->getNumOperands()); 3580 3581 Ops.push_back(M->getOperand(0)); 3582 if (IsIntrinsic) 3583 Ops.push_back(DAG.getConstant(Opcode, DL, MVT::i32)); 3584 3585 // Skip 1, as it is the intrinsic ID. 3586 for (unsigned I = 2, E = M->getNumOperands(); I != E; ++I) 3587 Ops.push_back(M->getOperand(I)); 3588 3589 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 3590 EVT LoadVT = M->getValueType(0); 3591 3592 EVT UnpackedLoadVT = LoadVT.isVector() ? 3593 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 3594 LoadVT.getVectorNumElements()) : LoadVT; 3595 EVT EquivLoadVT = LoadVT; 3596 if (LoadVT.isVector()) { 3597 EquivLoadVT = Unpacked ? UnpackedLoadVT : 3598 getEquivalentMemType(*DAG.getContext(), LoadVT); 3599 } 3600 3601 // Change from v4f16/v2f16 to EquivLoadVT. 3602 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 3603 3604 SDValue Load 3605 = DAG.getMemIntrinsicNode(IsIntrinsic ? ISD::INTRINSIC_W_CHAIN : Opcode, DL, 3606 VTList, Ops, M->getMemoryVT(), 3607 M->getMemOperand()); 3608 3609 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 3610 3611 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 3612 } 3613 3614 void SITargetLowering::ReplaceNodeResults(SDNode *N, 3615 SmallVectorImpl<SDValue> &Results, 3616 SelectionDAG &DAG) const { 3617 switch (N->getOpcode()) { 3618 case ISD::INSERT_VECTOR_ELT: { 3619 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 3620 Results.push_back(Res); 3621 return; 3622 } 3623 case ISD::EXTRACT_VECTOR_ELT: { 3624 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 3625 Results.push_back(Res); 3626 return; 3627 } 3628 case ISD::INTRINSIC_WO_CHAIN: { 3629 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 3630 switch (IID) { 3631 case Intrinsic::amdgcn_cvt_pkrtz: { 3632 SDValue Src0 = N->getOperand(1); 3633 SDValue Src1 = N->getOperand(2); 3634 SDLoc SL(N); 3635 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 3636 Src0, Src1); 3637 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 3638 return; 3639 } 3640 case Intrinsic::amdgcn_cvt_pknorm_i16: 3641 case Intrinsic::amdgcn_cvt_pknorm_u16: 3642 case Intrinsic::amdgcn_cvt_pk_i16: 3643 case Intrinsic::amdgcn_cvt_pk_u16: { 3644 SDValue Src0 = N->getOperand(1); 3645 SDValue Src1 = N->getOperand(2); 3646 SDLoc SL(N); 3647 unsigned Opcode; 3648 3649 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 3650 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 3651 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 3652 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 3653 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 3654 Opcode = AMDGPUISD::CVT_PK_I16_I32; 3655 else 3656 Opcode = AMDGPUISD::CVT_PK_U16_U32; 3657 3658 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 3659 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 3660 return; 3661 } 3662 } 3663 break; 3664 } 3665 case ISD::INTRINSIC_W_CHAIN: { 3666 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 3667 Results.push_back(Res); 3668 Results.push_back(Res.getValue(1)); 3669 return; 3670 } 3671 3672 break; 3673 } 3674 case ISD::SELECT: { 3675 SDLoc SL(N); 3676 EVT VT = N->getValueType(0); 3677 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 3678 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 3679 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 3680 3681 EVT SelectVT = NewVT; 3682 if (NewVT.bitsLT(MVT::i32)) { 3683 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 3684 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 3685 SelectVT = MVT::i32; 3686 } 3687 3688 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 3689 N->getOperand(0), LHS, RHS); 3690 3691 if (NewVT != SelectVT) 3692 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 3693 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 3694 return; 3695 } 3696 default: 3697 break; 3698 } 3699 } 3700 3701 /// Helper function for LowerBRCOND 3702 static SDNode *findUser(SDValue Value, unsigned Opcode) { 3703 3704 SDNode *Parent = Value.getNode(); 3705 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 3706 I != E; ++I) { 3707 3708 if (I.getUse().get() != Value) 3709 continue; 3710 3711 if (I->getOpcode() == Opcode) 3712 return *I; 3713 } 3714 return nullptr; 3715 } 3716 3717 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 3718 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 3719 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 3720 case Intrinsic::amdgcn_if: 3721 return AMDGPUISD::IF; 3722 case Intrinsic::amdgcn_else: 3723 return AMDGPUISD::ELSE; 3724 case Intrinsic::amdgcn_loop: 3725 return AMDGPUISD::LOOP; 3726 case Intrinsic::amdgcn_end_cf: 3727 llvm_unreachable("should not occur"); 3728 default: 3729 return 0; 3730 } 3731 } 3732 3733 // break, if_break, else_break are all only used as inputs to loop, not 3734 // directly as branch conditions. 3735 return 0; 3736 } 3737 3738 void SITargetLowering::createDebuggerPrologueStackObjects( 3739 MachineFunction &MF) const { 3740 // Create stack objects that are used for emitting debugger prologue. 3741 // 3742 // Debugger prologue writes work group IDs and work item IDs to scratch memory 3743 // at fixed location in the following format: 3744 // offset 0: work group ID x 3745 // offset 4: work group ID y 3746 // offset 8: work group ID z 3747 // offset 16: work item ID x 3748 // offset 20: work item ID y 3749 // offset 24: work item ID z 3750 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3751 int ObjectIdx = 0; 3752 3753 // For each dimension: 3754 for (unsigned i = 0; i < 3; ++i) { 3755 // Create fixed stack object for work group ID. 3756 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true); 3757 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx); 3758 // Create fixed stack object for work item ID. 3759 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true); 3760 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx); 3761 } 3762 } 3763 3764 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 3765 const Triple &TT = getTargetMachine().getTargetTriple(); 3766 return (GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS || 3767 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) && 3768 AMDGPU::shouldEmitConstantsToTextSection(TT); 3769 } 3770 3771 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 3772 return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS || 3773 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS || 3774 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) && 3775 !shouldEmitFixup(GV) && 3776 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3777 } 3778 3779 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 3780 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 3781 } 3782 3783 /// This transforms the control flow intrinsics to get the branch destination as 3784 /// last parameter, also switches branch target with BR if the need arise 3785 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 3786 SelectionDAG &DAG) const { 3787 SDLoc DL(BRCOND); 3788 3789 SDNode *Intr = BRCOND.getOperand(1).getNode(); 3790 SDValue Target = BRCOND.getOperand(2); 3791 SDNode *BR = nullptr; 3792 SDNode *SetCC = nullptr; 3793 3794 if (Intr->getOpcode() == ISD::SETCC) { 3795 // As long as we negate the condition everything is fine 3796 SetCC = Intr; 3797 Intr = SetCC->getOperand(0).getNode(); 3798 3799 } else { 3800 // Get the target from BR if we don't negate the condition 3801 BR = findUser(BRCOND, ISD::BR); 3802 Target = BR->getOperand(1); 3803 } 3804 3805 // FIXME: This changes the types of the intrinsics instead of introducing new 3806 // nodes with the correct types. 3807 // e.g. llvm.amdgcn.loop 3808 3809 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 3810 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 3811 3812 unsigned CFNode = isCFIntrinsic(Intr); 3813 if (CFNode == 0) { 3814 // This is a uniform branch so we don't need to legalize. 3815 return BRCOND; 3816 } 3817 3818 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 3819 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 3820 3821 assert(!SetCC || 3822 (SetCC->getConstantOperandVal(1) == 1 && 3823 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 3824 ISD::SETNE)); 3825 3826 // operands of the new intrinsic call 3827 SmallVector<SDValue, 4> Ops; 3828 if (HaveChain) 3829 Ops.push_back(BRCOND.getOperand(0)); 3830 3831 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 3832 Ops.push_back(Target); 3833 3834 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 3835 3836 // build the new intrinsic call 3837 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 3838 3839 if (!HaveChain) { 3840 SDValue Ops[] = { 3841 SDValue(Result, 0), 3842 BRCOND.getOperand(0) 3843 }; 3844 3845 Result = DAG.getMergeValues(Ops, DL).getNode(); 3846 } 3847 3848 if (BR) { 3849 // Give the branch instruction our target 3850 SDValue Ops[] = { 3851 BR->getOperand(0), 3852 BRCOND.getOperand(2) 3853 }; 3854 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 3855 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 3856 BR = NewBR.getNode(); 3857 } 3858 3859 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 3860 3861 // Copy the intrinsic results to registers 3862 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 3863 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 3864 if (!CopyToReg) 3865 continue; 3866 3867 Chain = DAG.getCopyToReg( 3868 Chain, DL, 3869 CopyToReg->getOperand(1), 3870 SDValue(Result, i - 1), 3871 SDValue()); 3872 3873 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 3874 } 3875 3876 // Remove the old intrinsic from the chain 3877 DAG.ReplaceAllUsesOfValueWith( 3878 SDValue(Intr, Intr->getNumValues() - 1), 3879 Intr->getOperand(0)); 3880 3881 return Chain; 3882 } 3883 3884 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 3885 SDValue Op, 3886 const SDLoc &DL, 3887 EVT VT) const { 3888 return Op.getValueType().bitsLE(VT) ? 3889 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 3890 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 3891 } 3892 3893 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 3894 assert(Op.getValueType() == MVT::f16 && 3895 "Do not know how to custom lower FP_ROUND for non-f16 type"); 3896 3897 SDValue Src = Op.getOperand(0); 3898 EVT SrcVT = Src.getValueType(); 3899 if (SrcVT != MVT::f64) 3900 return Op; 3901 3902 SDLoc DL(Op); 3903 3904 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 3905 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 3906 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 3907 } 3908 3909 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 3910 SDLoc SL(Op); 3911 SDValue Chain = Op.getOperand(0); 3912 3913 if (Subtarget->getTrapHandlerAbi() != SISubtarget::TrapHandlerAbiHsa || 3914 !Subtarget->isTrapHandlerEnabled()) 3915 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 3916 3917 MachineFunction &MF = DAG.getMachineFunction(); 3918 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3919 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 3920 assert(UserSGPR != AMDGPU::NoRegister); 3921 SDValue QueuePtr = CreateLiveInRegister( 3922 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 3923 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 3924 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 3925 QueuePtr, SDValue()); 3926 SDValue Ops[] = { 3927 ToReg, 3928 DAG.getTargetConstant(SISubtarget::TrapIDLLVMTrap, SL, MVT::i16), 3929 SGPR01, 3930 ToReg.getValue(1) 3931 }; 3932 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 3933 } 3934 3935 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 3936 SDLoc SL(Op); 3937 SDValue Chain = Op.getOperand(0); 3938 MachineFunction &MF = DAG.getMachineFunction(); 3939 3940 if (Subtarget->getTrapHandlerAbi() != SISubtarget::TrapHandlerAbiHsa || 3941 !Subtarget->isTrapHandlerEnabled()) { 3942 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 3943 "debugtrap handler not supported", 3944 Op.getDebugLoc(), 3945 DS_Warning); 3946 LLVMContext &Ctx = MF.getFunction().getContext(); 3947 Ctx.diagnose(NoTrap); 3948 return Chain; 3949 } 3950 3951 SDValue Ops[] = { 3952 Chain, 3953 DAG.getTargetConstant(SISubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 3954 }; 3955 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 3956 } 3957 3958 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 3959 SelectionDAG &DAG) const { 3960 // FIXME: Use inline constants (src_{shared, private}_base) instead. 3961 if (Subtarget->hasApertureRegs()) { 3962 unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ? 3963 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 3964 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 3965 unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ? 3966 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 3967 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 3968 unsigned Encoding = 3969 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 3970 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 3971 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 3972 3973 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 3974 SDValue ApertureReg = SDValue( 3975 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 3976 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 3977 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 3978 } 3979 3980 MachineFunction &MF = DAG.getMachineFunction(); 3981 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3982 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 3983 assert(UserSGPR != AMDGPU::NoRegister); 3984 3985 SDValue QueuePtr = CreateLiveInRegister( 3986 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 3987 3988 // Offset into amd_queue_t for group_segment_aperture_base_hi / 3989 // private_segment_aperture_base_hi. 3990 uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44; 3991 3992 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 3993 3994 // TODO: Use custom target PseudoSourceValue. 3995 // TODO: We should use the value from the IR intrinsic call, but it might not 3996 // be available and how do we get it? 3997 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()), 3998 AMDGPUASI.CONSTANT_ADDRESS)); 3999 4000 MachinePointerInfo PtrInfo(V, StructOffset); 4001 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4002 MinAlign(64, StructOffset), 4003 MachineMemOperand::MODereferenceable | 4004 MachineMemOperand::MOInvariant); 4005 } 4006 4007 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4008 SelectionDAG &DAG) const { 4009 SDLoc SL(Op); 4010 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4011 4012 SDValue Src = ASC->getOperand(0); 4013 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4014 4015 const AMDGPUTargetMachine &TM = 4016 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4017 4018 // flat -> local/private 4019 if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) { 4020 unsigned DestAS = ASC->getDestAddressSpace(); 4021 4022 if (DestAS == AMDGPUASI.LOCAL_ADDRESS || 4023 DestAS == AMDGPUASI.PRIVATE_ADDRESS) { 4024 unsigned NullVal = TM.getNullPointerValue(DestAS); 4025 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4026 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4027 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4028 4029 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4030 NonNull, Ptr, SegmentNullPtr); 4031 } 4032 } 4033 4034 // local/private -> flat 4035 if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) { 4036 unsigned SrcAS = ASC->getSrcAddressSpace(); 4037 4038 if (SrcAS == AMDGPUASI.LOCAL_ADDRESS || 4039 SrcAS == AMDGPUASI.PRIVATE_ADDRESS) { 4040 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4041 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4042 4043 SDValue NonNull 4044 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4045 4046 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4047 SDValue CvtPtr 4048 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4049 4050 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4051 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4052 FlatNullPtr); 4053 } 4054 } 4055 4056 // global <-> flat are no-ops and never emitted. 4057 4058 const MachineFunction &MF = DAG.getMachineFunction(); 4059 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 4060 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 4061 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 4062 4063 return DAG.getUNDEF(ASC->getValueType(0)); 4064 } 4065 4066 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4067 SelectionDAG &DAG) const { 4068 SDValue Vec = Op.getOperand(0); 4069 SDValue InsVal = Op.getOperand(1); 4070 SDValue Idx = Op.getOperand(2); 4071 EVT VecVT = Vec.getValueType(); 4072 4073 assert(VecVT.getScalarSizeInBits() == 16); 4074 4075 unsigned NumElts = VecVT.getVectorNumElements(); 4076 SDLoc SL(Op); 4077 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 4078 4079 if (NumElts == 4 && KIdx) { 4080 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 4081 4082 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4083 DAG.getConstant(0, SL, MVT::i32)); 4084 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4085 DAG.getConstant(1, SL, MVT::i32)); 4086 4087 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 4088 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 4089 4090 unsigned Idx = KIdx->getZExtValue(); 4091 bool InsertLo = Idx < 2; 4092 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 4093 InsertLo ? LoVec : HiVec, 4094 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 4095 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 4096 4097 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 4098 4099 SDValue Concat = InsertLo ? 4100 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 4101 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 4102 4103 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 4104 } 4105 4106 assert(NumElts == 2 || NumElts == 4); 4107 4108 if (isa<ConstantSDNode>(Idx)) 4109 return SDValue(); 4110 4111 EVT IntVT = NumElts == 2 ? MVT::i32 : MVT::i64; 4112 4113 // Avoid stack access for dynamic indexing. 4114 SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal); 4115 4116 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 4117 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Val); 4118 4119 // Convert vector index to bit-index. 4120 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, 4121 DAG.getConstant(4, SL, MVT::i32)); 4122 4123 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4124 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 4125 DAG.getConstant(0xffff, SL, IntVT), 4126 ScaledIdx); 4127 4128 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 4129 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 4130 DAG.getNOT(SL, BFM, IntVT), BCVec); 4131 4132 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 4133 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 4134 } 4135 4136 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4137 SelectionDAG &DAG) const { 4138 SDLoc SL(Op); 4139 4140 EVT ResultVT = Op.getValueType(); 4141 SDValue Vec = Op.getOperand(0); 4142 SDValue Idx = Op.getOperand(1); 4143 EVT VecVT = Vec.getValueType(); 4144 unsigned NumElts = VecVT.getVectorNumElements(); 4145 assert(VecVT.getScalarSizeInBits() == 16 && (NumElts == 2 || NumElts == 4)); 4146 4147 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 4148 4149 // Make sure we do any optimizations that will make it easier to fold 4150 // source modifiers before obscuring it with bit operations. 4151 4152 // XXX - Why doesn't this get called when vector_shuffle is expanded? 4153 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 4154 return Combined; 4155 4156 EVT IntVT = NumElts == 2 ? MVT::i32 : MVT::i64; 4157 SDValue Four = DAG.getConstant(4, SL, MVT::i32); 4158 4159 // Convert vector index to bit-index (* 16) 4160 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Four); 4161 4162 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4163 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 4164 4165 if (ResultVT == MVT::f16) { 4166 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 4167 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 4168 } 4169 4170 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 4171 } 4172 4173 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 4174 SelectionDAG &DAG) const { 4175 SDLoc SL(Op); 4176 EVT VT = Op.getValueType(); 4177 4178 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 4179 4180 SDValue Lo = Op.getOperand(0); 4181 SDValue Hi = Op.getOperand(1); 4182 4183 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4184 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 4185 4186 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 4187 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 4188 4189 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 4190 DAG.getConstant(16, SL, MVT::i32)); 4191 4192 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 4193 4194 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 4195 } 4196 4197 bool 4198 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 4199 // We can fold offsets for anything that doesn't require a GOT relocation. 4200 return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS || 4201 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS || 4202 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) && 4203 !shouldEmitGOTReloc(GA->getGlobal()); 4204 } 4205 4206 static SDValue 4207 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 4208 const SDLoc &DL, unsigned Offset, EVT PtrVT, 4209 unsigned GAFlags = SIInstrInfo::MO_NONE) { 4210 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 4211 // lowered to the following code sequence: 4212 // 4213 // For constant address space: 4214 // s_getpc_b64 s[0:1] 4215 // s_add_u32 s0, s0, $symbol 4216 // s_addc_u32 s1, s1, 0 4217 // 4218 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 4219 // a fixup or relocation is emitted to replace $symbol with a literal 4220 // constant, which is a pc-relative offset from the encoding of the $symbol 4221 // operand to the global variable. 4222 // 4223 // For global address space: 4224 // s_getpc_b64 s[0:1] 4225 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 4226 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 4227 // 4228 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 4229 // fixups or relocations are emitted to replace $symbol@*@lo and 4230 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 4231 // which is a 64-bit pc-relative offset from the encoding of the $symbol 4232 // operand to the global variable. 4233 // 4234 // What we want here is an offset from the value returned by s_getpc 4235 // (which is the address of the s_add_u32 instruction) to the global 4236 // variable, but since the encoding of $symbol starts 4 bytes after the start 4237 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 4238 // small. This requires us to add 4 to the global variable offset in order to 4239 // compute the correct address. 4240 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 4241 GAFlags); 4242 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 4243 GAFlags == SIInstrInfo::MO_NONE ? 4244 GAFlags : GAFlags + 1); 4245 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 4246 } 4247 4248 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 4249 SDValue Op, 4250 SelectionDAG &DAG) const { 4251 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 4252 const GlobalValue *GV = GSD->getGlobal(); 4253 4254 if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS && 4255 GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS_32BIT && 4256 GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS && 4257 // FIXME: It isn't correct to rely on the type of the pointer. This should 4258 // be removed when address space 0 is 64-bit. 4259 !GV->getType()->getElementType()->isFunctionTy()) 4260 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 4261 4262 SDLoc DL(GSD); 4263 EVT PtrVT = Op.getValueType(); 4264 4265 if (shouldEmitFixup(GV)) 4266 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 4267 else if (shouldEmitPCReloc(GV)) 4268 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 4269 SIInstrInfo::MO_REL32); 4270 4271 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 4272 SIInstrInfo::MO_GOTPCREL32); 4273 4274 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 4275 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS); 4276 const DataLayout &DataLayout = DAG.getDataLayout(); 4277 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 4278 // FIXME: Use a PseudoSourceValue once those can be assigned an address space. 4279 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 4280 4281 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 4282 MachineMemOperand::MODereferenceable | 4283 MachineMemOperand::MOInvariant); 4284 } 4285 4286 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 4287 const SDLoc &DL, SDValue V) const { 4288 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 4289 // the destination register. 4290 // 4291 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 4292 // so we will end up with redundant moves to m0. 4293 // 4294 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 4295 4296 // A Null SDValue creates a glue result. 4297 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 4298 V, Chain); 4299 return SDValue(M0, 0); 4300 } 4301 4302 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 4303 SDValue Op, 4304 MVT VT, 4305 unsigned Offset) const { 4306 SDLoc SL(Op); 4307 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 4308 DAG.getEntryNode(), Offset, false); 4309 // The local size values will have the hi 16-bits as zero. 4310 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 4311 DAG.getValueType(VT)); 4312 } 4313 4314 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 4315 EVT VT) { 4316 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 4317 "non-hsa intrinsic with hsa target", 4318 DL.getDebugLoc()); 4319 DAG.getContext()->diagnose(BadIntrin); 4320 return DAG.getUNDEF(VT); 4321 } 4322 4323 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 4324 EVT VT) { 4325 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 4326 "intrinsic not supported on subtarget", 4327 DL.getDebugLoc()); 4328 DAG.getContext()->diagnose(BadIntrin); 4329 return DAG.getUNDEF(VT); 4330 } 4331 4332 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4333 SelectionDAG &DAG) const { 4334 MachineFunction &MF = DAG.getMachineFunction(); 4335 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 4336 4337 EVT VT = Op.getValueType(); 4338 SDLoc DL(Op); 4339 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4340 4341 // TODO: Should this propagate fast-math-flags? 4342 4343 switch (IntrinsicID) { 4344 case Intrinsic::amdgcn_implicit_buffer_ptr: { 4345 if (getSubtarget()->isAmdCodeObjectV2(MF)) 4346 return emitNonHSAIntrinsicError(DAG, DL, VT); 4347 return getPreloadedValue(DAG, *MFI, VT, 4348 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 4349 } 4350 case Intrinsic::amdgcn_dispatch_ptr: 4351 case Intrinsic::amdgcn_queue_ptr: { 4352 if (!Subtarget->isAmdCodeObjectV2(MF)) { 4353 DiagnosticInfoUnsupported BadIntrin( 4354 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 4355 DL.getDebugLoc()); 4356 DAG.getContext()->diagnose(BadIntrin); 4357 return DAG.getUNDEF(VT); 4358 } 4359 4360 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 4361 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 4362 return getPreloadedValue(DAG, *MFI, VT, RegID); 4363 } 4364 case Intrinsic::amdgcn_implicitarg_ptr: { 4365 if (MFI->isEntryFunction()) 4366 return getImplicitArgPtr(DAG, DL); 4367 return getPreloadedValue(DAG, *MFI, VT, 4368 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 4369 } 4370 case Intrinsic::amdgcn_kernarg_segment_ptr: { 4371 return getPreloadedValue(DAG, *MFI, VT, 4372 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 4373 } 4374 case Intrinsic::amdgcn_dispatch_id: { 4375 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 4376 } 4377 case Intrinsic::amdgcn_rcp: 4378 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 4379 case Intrinsic::amdgcn_rsq: 4380 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 4381 case Intrinsic::amdgcn_rsq_legacy: 4382 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 4383 return emitRemovedIntrinsicError(DAG, DL, VT); 4384 4385 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 4386 case Intrinsic::amdgcn_rcp_legacy: 4387 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 4388 return emitRemovedIntrinsicError(DAG, DL, VT); 4389 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 4390 case Intrinsic::amdgcn_rsq_clamp: { 4391 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 4392 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 4393 4394 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 4395 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 4396 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 4397 4398 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 4399 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 4400 DAG.getConstantFP(Max, DL, VT)); 4401 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 4402 DAG.getConstantFP(Min, DL, VT)); 4403 } 4404 case Intrinsic::r600_read_ngroups_x: 4405 if (Subtarget->isAmdHsaOS()) 4406 return emitNonHSAIntrinsicError(DAG, DL, VT); 4407 4408 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4409 SI::KernelInputOffsets::NGROUPS_X, false); 4410 case Intrinsic::r600_read_ngroups_y: 4411 if (Subtarget->isAmdHsaOS()) 4412 return emitNonHSAIntrinsicError(DAG, DL, VT); 4413 4414 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4415 SI::KernelInputOffsets::NGROUPS_Y, false); 4416 case Intrinsic::r600_read_ngroups_z: 4417 if (Subtarget->isAmdHsaOS()) 4418 return emitNonHSAIntrinsicError(DAG, DL, VT); 4419 4420 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4421 SI::KernelInputOffsets::NGROUPS_Z, false); 4422 case Intrinsic::r600_read_global_size_x: 4423 if (Subtarget->isAmdHsaOS()) 4424 return emitNonHSAIntrinsicError(DAG, DL, VT); 4425 4426 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4427 SI::KernelInputOffsets::GLOBAL_SIZE_X, false); 4428 case Intrinsic::r600_read_global_size_y: 4429 if (Subtarget->isAmdHsaOS()) 4430 return emitNonHSAIntrinsicError(DAG, DL, VT); 4431 4432 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4433 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false); 4434 case Intrinsic::r600_read_global_size_z: 4435 if (Subtarget->isAmdHsaOS()) 4436 return emitNonHSAIntrinsicError(DAG, DL, VT); 4437 4438 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4439 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false); 4440 case Intrinsic::r600_read_local_size_x: 4441 if (Subtarget->isAmdHsaOS()) 4442 return emitNonHSAIntrinsicError(DAG, DL, VT); 4443 4444 return lowerImplicitZextParam(DAG, Op, MVT::i16, 4445 SI::KernelInputOffsets::LOCAL_SIZE_X); 4446 case Intrinsic::r600_read_local_size_y: 4447 if (Subtarget->isAmdHsaOS()) 4448 return emitNonHSAIntrinsicError(DAG, DL, VT); 4449 4450 return lowerImplicitZextParam(DAG, Op, MVT::i16, 4451 SI::KernelInputOffsets::LOCAL_SIZE_Y); 4452 case Intrinsic::r600_read_local_size_z: 4453 if (Subtarget->isAmdHsaOS()) 4454 return emitNonHSAIntrinsicError(DAG, DL, VT); 4455 4456 return lowerImplicitZextParam(DAG, Op, MVT::i16, 4457 SI::KernelInputOffsets::LOCAL_SIZE_Z); 4458 case Intrinsic::amdgcn_workgroup_id_x: 4459 case Intrinsic::r600_read_tgid_x: 4460 return getPreloadedValue(DAG, *MFI, VT, 4461 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 4462 case Intrinsic::amdgcn_workgroup_id_y: 4463 case Intrinsic::r600_read_tgid_y: 4464 return getPreloadedValue(DAG, *MFI, VT, 4465 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 4466 case Intrinsic::amdgcn_workgroup_id_z: 4467 case Intrinsic::r600_read_tgid_z: 4468 return getPreloadedValue(DAG, *MFI, VT, 4469 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 4470 case Intrinsic::amdgcn_workitem_id_x: { 4471 case Intrinsic::r600_read_tidig_x: 4472 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 4473 SDLoc(DAG.getEntryNode()), 4474 MFI->getArgInfo().WorkItemIDX); 4475 } 4476 case Intrinsic::amdgcn_workitem_id_y: 4477 case Intrinsic::r600_read_tidig_y: 4478 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 4479 SDLoc(DAG.getEntryNode()), 4480 MFI->getArgInfo().WorkItemIDY); 4481 case Intrinsic::amdgcn_workitem_id_z: 4482 case Intrinsic::r600_read_tidig_z: 4483 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 4484 SDLoc(DAG.getEntryNode()), 4485 MFI->getArgInfo().WorkItemIDZ); 4486 case AMDGPUIntrinsic::SI_load_const: { 4487 SDValue Ops[] = { 4488 Op.getOperand(1), 4489 Op.getOperand(2) 4490 }; 4491 4492 MachineMemOperand *MMO = MF.getMachineMemOperand( 4493 MachinePointerInfo(), 4494 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 4495 MachineMemOperand::MOInvariant, 4496 VT.getStoreSize(), 4); 4497 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL, 4498 Op->getVTList(), Ops, VT, MMO); 4499 } 4500 case Intrinsic::amdgcn_fdiv_fast: 4501 return lowerFDIV_FAST(Op, DAG); 4502 case Intrinsic::amdgcn_interp_mov: { 4503 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 4504 SDValue Glue = M0.getValue(1); 4505 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1), 4506 Op.getOperand(2), Op.getOperand(3), Glue); 4507 } 4508 case Intrinsic::amdgcn_interp_p1: { 4509 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 4510 SDValue Glue = M0.getValue(1); 4511 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1), 4512 Op.getOperand(2), Op.getOperand(3), Glue); 4513 } 4514 case Intrinsic::amdgcn_interp_p2: { 4515 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 4516 SDValue Glue = SDValue(M0.getNode(), 1); 4517 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1), 4518 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4), 4519 Glue); 4520 } 4521 case Intrinsic::amdgcn_sin: 4522 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 4523 4524 case Intrinsic::amdgcn_cos: 4525 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 4526 4527 case Intrinsic::amdgcn_log_clamp: { 4528 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 4529 return SDValue(); 4530 4531 DiagnosticInfoUnsupported BadIntrin( 4532 MF.getFunction(), "intrinsic not supported on subtarget", 4533 DL.getDebugLoc()); 4534 DAG.getContext()->diagnose(BadIntrin); 4535 return DAG.getUNDEF(VT); 4536 } 4537 case Intrinsic::amdgcn_ldexp: 4538 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 4539 Op.getOperand(1), Op.getOperand(2)); 4540 4541 case Intrinsic::amdgcn_fract: 4542 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 4543 4544 case Intrinsic::amdgcn_class: 4545 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 4546 Op.getOperand(1), Op.getOperand(2)); 4547 case Intrinsic::amdgcn_div_fmas: 4548 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 4549 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 4550 Op.getOperand(4)); 4551 4552 case Intrinsic::amdgcn_div_fixup: 4553 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 4554 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4555 4556 case Intrinsic::amdgcn_trig_preop: 4557 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 4558 Op.getOperand(1), Op.getOperand(2)); 4559 case Intrinsic::amdgcn_div_scale: { 4560 // 3rd parameter required to be a constant. 4561 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 4562 if (!Param) 4563 return DAG.getMergeValues({ DAG.getUNDEF(VT), DAG.getUNDEF(MVT::i1) }, DL); 4564 4565 // Translate to the operands expected by the machine instruction. The 4566 // first parameter must be the same as the first instruction. 4567 SDValue Numerator = Op.getOperand(1); 4568 SDValue Denominator = Op.getOperand(2); 4569 4570 // Note this order is opposite of the machine instruction's operations, 4571 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 4572 // intrinsic has the numerator as the first operand to match a normal 4573 // division operation. 4574 4575 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 4576 4577 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 4578 Denominator, Numerator); 4579 } 4580 case Intrinsic::amdgcn_icmp: { 4581 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 4582 if (!CD) 4583 return DAG.getUNDEF(VT); 4584 4585 int CondCode = CD->getSExtValue(); 4586 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4587 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4588 return DAG.getUNDEF(VT); 4589 4590 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4591 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4592 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 4593 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 4594 } 4595 case Intrinsic::amdgcn_fcmp: { 4596 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 4597 if (!CD) 4598 return DAG.getUNDEF(VT); 4599 4600 int CondCode = CD->getSExtValue(); 4601 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4602 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) 4603 return DAG.getUNDEF(VT); 4604 4605 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4606 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4607 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 4608 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 4609 } 4610 case Intrinsic::amdgcn_fmed3: 4611 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 4612 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4613 case Intrinsic::amdgcn_fmul_legacy: 4614 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 4615 Op.getOperand(1), Op.getOperand(2)); 4616 case Intrinsic::amdgcn_sffbh: 4617 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 4618 case Intrinsic::amdgcn_sbfe: 4619 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 4620 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4621 case Intrinsic::amdgcn_ubfe: 4622 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 4623 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4624 case Intrinsic::amdgcn_cvt_pkrtz: 4625 case Intrinsic::amdgcn_cvt_pknorm_i16: 4626 case Intrinsic::amdgcn_cvt_pknorm_u16: 4627 case Intrinsic::amdgcn_cvt_pk_i16: 4628 case Intrinsic::amdgcn_cvt_pk_u16: { 4629 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 4630 EVT VT = Op.getValueType(); 4631 unsigned Opcode; 4632 4633 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 4634 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 4635 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 4636 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4637 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 4638 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4639 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 4640 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4641 else 4642 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4643 4644 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 4645 Op.getOperand(1), Op.getOperand(2)); 4646 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 4647 } 4648 case Intrinsic::amdgcn_wqm: { 4649 SDValue Src = Op.getOperand(1); 4650 return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src), 4651 0); 4652 } 4653 case Intrinsic::amdgcn_wwm: { 4654 SDValue Src = Op.getOperand(1); 4655 return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src), 4656 0); 4657 } 4658 case Intrinsic::amdgcn_image_getlod: 4659 case Intrinsic::amdgcn_image_getresinfo: { 4660 unsigned Idx = (IntrinsicID == Intrinsic::amdgcn_image_getresinfo) ? 3 : 4; 4661 4662 // Replace dmask with everything disabled with undef. 4663 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(Idx)); 4664 if (!DMask || DMask->isNullValue()) 4665 return DAG.getUNDEF(Op.getValueType()); 4666 return SDValue(); 4667 } 4668 default: 4669 return Op; 4670 } 4671 } 4672 4673 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4674 SelectionDAG &DAG) const { 4675 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4676 SDLoc DL(Op); 4677 4678 switch (IntrID) { 4679 case Intrinsic::amdgcn_atomic_inc: 4680 case Intrinsic::amdgcn_atomic_dec: 4681 case Intrinsic::amdgcn_ds_fadd: 4682 case Intrinsic::amdgcn_ds_fmin: 4683 case Intrinsic::amdgcn_ds_fmax: { 4684 MemSDNode *M = cast<MemSDNode>(Op); 4685 unsigned Opc; 4686 switch (IntrID) { 4687 case Intrinsic::amdgcn_atomic_inc: 4688 Opc = AMDGPUISD::ATOMIC_INC; 4689 break; 4690 case Intrinsic::amdgcn_atomic_dec: 4691 Opc = AMDGPUISD::ATOMIC_DEC; 4692 break; 4693 case Intrinsic::amdgcn_ds_fadd: 4694 Opc = AMDGPUISD::ATOMIC_LOAD_FADD; 4695 break; 4696 case Intrinsic::amdgcn_ds_fmin: 4697 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 4698 break; 4699 case Intrinsic::amdgcn_ds_fmax: 4700 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 4701 break; 4702 default: 4703 llvm_unreachable("Unknown intrinsic!"); 4704 } 4705 SDValue Ops[] = { 4706 M->getOperand(0), // Chain 4707 M->getOperand(2), // Ptr 4708 M->getOperand(3) // Value 4709 }; 4710 4711 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 4712 M->getMemoryVT(), M->getMemOperand()); 4713 } 4714 case Intrinsic::amdgcn_buffer_load: 4715 case Intrinsic::amdgcn_buffer_load_format: { 4716 SDValue Ops[] = { 4717 Op.getOperand(0), // Chain 4718 Op.getOperand(2), // rsrc 4719 Op.getOperand(3), // vindex 4720 Op.getOperand(4), // offset 4721 Op.getOperand(5), // glc 4722 Op.getOperand(6) // slc 4723 }; 4724 4725 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 4726 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 4727 EVT VT = Op.getValueType(); 4728 EVT IntVT = VT.changeTypeToInteger(); 4729 auto *M = cast<MemSDNode>(Op); 4730 EVT LoadVT = Op.getValueType(); 4731 bool IsD16 = LoadVT.getScalarType() == MVT::f16; 4732 if (IsD16) 4733 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG); 4734 4735 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 4736 M->getMemOperand()); 4737 } 4738 case Intrinsic::amdgcn_tbuffer_load: { 4739 MemSDNode *M = cast<MemSDNode>(Op); 4740 EVT LoadVT = Op.getValueType(); 4741 bool IsD16 = LoadVT.getScalarType() == MVT::f16; 4742 if (IsD16) { 4743 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, M, DAG); 4744 } 4745 4746 SDValue Ops[] = { 4747 Op.getOperand(0), // Chain 4748 Op.getOperand(2), // rsrc 4749 Op.getOperand(3), // vindex 4750 Op.getOperand(4), // voffset 4751 Op.getOperand(5), // soffset 4752 Op.getOperand(6), // offset 4753 Op.getOperand(7), // dfmt 4754 Op.getOperand(8), // nfmt 4755 Op.getOperand(9), // glc 4756 Op.getOperand(10) // slc 4757 }; 4758 4759 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 4760 Op->getVTList(), Ops, LoadVT, 4761 M->getMemOperand()); 4762 } 4763 case Intrinsic::amdgcn_buffer_atomic_swap: 4764 case Intrinsic::amdgcn_buffer_atomic_add: 4765 case Intrinsic::amdgcn_buffer_atomic_sub: 4766 case Intrinsic::amdgcn_buffer_atomic_smin: 4767 case Intrinsic::amdgcn_buffer_atomic_umin: 4768 case Intrinsic::amdgcn_buffer_atomic_smax: 4769 case Intrinsic::amdgcn_buffer_atomic_umax: 4770 case Intrinsic::amdgcn_buffer_atomic_and: 4771 case Intrinsic::amdgcn_buffer_atomic_or: 4772 case Intrinsic::amdgcn_buffer_atomic_xor: { 4773 SDValue Ops[] = { 4774 Op.getOperand(0), // Chain 4775 Op.getOperand(2), // vdata 4776 Op.getOperand(3), // rsrc 4777 Op.getOperand(4), // vindex 4778 Op.getOperand(5), // offset 4779 Op.getOperand(6) // slc 4780 }; 4781 EVT VT = Op.getValueType(); 4782 4783 auto *M = cast<MemSDNode>(Op); 4784 unsigned Opcode = 0; 4785 4786 switch (IntrID) { 4787 case Intrinsic::amdgcn_buffer_atomic_swap: 4788 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 4789 break; 4790 case Intrinsic::amdgcn_buffer_atomic_add: 4791 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 4792 break; 4793 case Intrinsic::amdgcn_buffer_atomic_sub: 4794 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 4795 break; 4796 case Intrinsic::amdgcn_buffer_atomic_smin: 4797 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 4798 break; 4799 case Intrinsic::amdgcn_buffer_atomic_umin: 4800 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 4801 break; 4802 case Intrinsic::amdgcn_buffer_atomic_smax: 4803 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 4804 break; 4805 case Intrinsic::amdgcn_buffer_atomic_umax: 4806 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 4807 break; 4808 case Intrinsic::amdgcn_buffer_atomic_and: 4809 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 4810 break; 4811 case Intrinsic::amdgcn_buffer_atomic_or: 4812 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 4813 break; 4814 case Intrinsic::amdgcn_buffer_atomic_xor: 4815 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 4816 break; 4817 default: 4818 llvm_unreachable("unhandled atomic opcode"); 4819 } 4820 4821 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 4822 M->getMemOperand()); 4823 } 4824 4825 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 4826 SDValue Ops[] = { 4827 Op.getOperand(0), // Chain 4828 Op.getOperand(2), // src 4829 Op.getOperand(3), // cmp 4830 Op.getOperand(4), // rsrc 4831 Op.getOperand(5), // vindex 4832 Op.getOperand(6), // offset 4833 Op.getOperand(7) // slc 4834 }; 4835 EVT VT = Op.getValueType(); 4836 auto *M = cast<MemSDNode>(Op); 4837 4838 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 4839 Op->getVTList(), Ops, VT, M->getMemOperand()); 4840 } 4841 4842 case Intrinsic::amdgcn_image_load: 4843 case Intrinsic::amdgcn_image_load_mip: { 4844 EVT LoadVT = Op.getValueType(); 4845 if ((Subtarget->hasUnpackedD16VMem() && LoadVT == MVT::v2f16) || 4846 LoadVT == MVT::v4f16) { 4847 MemSDNode *M = cast<MemSDNode>(Op); 4848 return adjustLoadValueType(getImageOpcode(IntrID), M, DAG); 4849 } 4850 4851 return SDValue(); 4852 } 4853 4854 // Basic sample. 4855 case Intrinsic::amdgcn_image_sample: 4856 case Intrinsic::amdgcn_image_sample_cl: 4857 case Intrinsic::amdgcn_image_sample_d: 4858 case Intrinsic::amdgcn_image_sample_d_cl: 4859 case Intrinsic::amdgcn_image_sample_l: 4860 case Intrinsic::amdgcn_image_sample_b: 4861 case Intrinsic::amdgcn_image_sample_b_cl: 4862 case Intrinsic::amdgcn_image_sample_lz: 4863 case Intrinsic::amdgcn_image_sample_cd: 4864 case Intrinsic::amdgcn_image_sample_cd_cl: 4865 4866 // Sample with comparison. 4867 case Intrinsic::amdgcn_image_sample_c: 4868 case Intrinsic::amdgcn_image_sample_c_cl: 4869 case Intrinsic::amdgcn_image_sample_c_d: 4870 case Intrinsic::amdgcn_image_sample_c_d_cl: 4871 case Intrinsic::amdgcn_image_sample_c_l: 4872 case Intrinsic::amdgcn_image_sample_c_b: 4873 case Intrinsic::amdgcn_image_sample_c_b_cl: 4874 case Intrinsic::amdgcn_image_sample_c_lz: 4875 case Intrinsic::amdgcn_image_sample_c_cd: 4876 case Intrinsic::amdgcn_image_sample_c_cd_cl: 4877 4878 // Sample with offsets. 4879 case Intrinsic::amdgcn_image_sample_o: 4880 case Intrinsic::amdgcn_image_sample_cl_o: 4881 case Intrinsic::amdgcn_image_sample_d_o: 4882 case Intrinsic::amdgcn_image_sample_d_cl_o: 4883 case Intrinsic::amdgcn_image_sample_l_o: 4884 case Intrinsic::amdgcn_image_sample_b_o: 4885 case Intrinsic::amdgcn_image_sample_b_cl_o: 4886 case Intrinsic::amdgcn_image_sample_lz_o: 4887 case Intrinsic::amdgcn_image_sample_cd_o: 4888 case Intrinsic::amdgcn_image_sample_cd_cl_o: 4889 4890 // Sample with comparison and offsets. 4891 case Intrinsic::amdgcn_image_sample_c_o: 4892 case Intrinsic::amdgcn_image_sample_c_cl_o: 4893 case Intrinsic::amdgcn_image_sample_c_d_o: 4894 case Intrinsic::amdgcn_image_sample_c_d_cl_o: 4895 case Intrinsic::amdgcn_image_sample_c_l_o: 4896 case Intrinsic::amdgcn_image_sample_c_b_o: 4897 case Intrinsic::amdgcn_image_sample_c_b_cl_o: 4898 case Intrinsic::amdgcn_image_sample_c_lz_o: 4899 case Intrinsic::amdgcn_image_sample_c_cd_o: 4900 case Intrinsic::amdgcn_image_sample_c_cd_cl_o: 4901 4902 // Basic gather4 4903 case Intrinsic::amdgcn_image_gather4: 4904 case Intrinsic::amdgcn_image_gather4_cl: 4905 case Intrinsic::amdgcn_image_gather4_l: 4906 case Intrinsic::amdgcn_image_gather4_b: 4907 case Intrinsic::amdgcn_image_gather4_b_cl: 4908 case Intrinsic::amdgcn_image_gather4_lz: 4909 4910 // Gather4 with comparison 4911 case Intrinsic::amdgcn_image_gather4_c: 4912 case Intrinsic::amdgcn_image_gather4_c_cl: 4913 case Intrinsic::amdgcn_image_gather4_c_l: 4914 case Intrinsic::amdgcn_image_gather4_c_b: 4915 case Intrinsic::amdgcn_image_gather4_c_b_cl: 4916 case Intrinsic::amdgcn_image_gather4_c_lz: 4917 4918 // Gather4 with offsets 4919 case Intrinsic::amdgcn_image_gather4_o: 4920 case Intrinsic::amdgcn_image_gather4_cl_o: 4921 case Intrinsic::amdgcn_image_gather4_l_o: 4922 case Intrinsic::amdgcn_image_gather4_b_o: 4923 case Intrinsic::amdgcn_image_gather4_b_cl_o: 4924 case Intrinsic::amdgcn_image_gather4_lz_o: 4925 4926 // Gather4 with comparison and offsets 4927 case Intrinsic::amdgcn_image_gather4_c_o: 4928 case Intrinsic::amdgcn_image_gather4_c_cl_o: 4929 case Intrinsic::amdgcn_image_gather4_c_l_o: 4930 case Intrinsic::amdgcn_image_gather4_c_b_o: 4931 case Intrinsic::amdgcn_image_gather4_c_b_cl_o: 4932 case Intrinsic::amdgcn_image_gather4_c_lz_o: { 4933 // Replace dmask with everything disabled with undef. 4934 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(5)); 4935 if (!DMask || DMask->isNullValue()) { 4936 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 4937 return DAG.getMergeValues({ Undef, Op.getOperand(0) }, SDLoc(Op)); 4938 } 4939 4940 if ((Subtarget->hasUnpackedD16VMem() && Op.getValueType() == MVT::v2f16) || 4941 Op.getValueType() == MVT::v4f16) { 4942 return adjustLoadValueType(getImageOpcode(IntrID), cast<MemSDNode>(Op), 4943 DAG); 4944 } 4945 4946 return SDValue(); 4947 } 4948 default: 4949 EVT LoadVT = Op.getValueType(); 4950 if (LoadVT.getScalarSizeInBits() != 16) 4951 return SDValue(); 4952 4953 const AMDGPU::D16ImageDimIntrinsic *D16ImageDimIntr = 4954 AMDGPU::lookupD16ImageDimIntrinsicByIntr(IntrID); 4955 if (D16ImageDimIntr) { 4956 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4957 MemSDNode *M = cast<MemSDNode>(Op); 4958 4959 if (isTypeLegal(LoadVT) && (!Unpacked || LoadVT == MVT::f16)) 4960 return SDValue(); 4961 4962 return adjustLoadValueType(D16ImageDimIntr->D16HelperIntr, 4963 M, DAG, true); 4964 } 4965 4966 return SDValue(); 4967 } 4968 } 4969 4970 SDValue SITargetLowering::handleD16VData(SDValue VData, 4971 SelectionDAG &DAG) const { 4972 EVT StoreVT = VData.getValueType(); 4973 4974 // No change for f16 and legal vector D16 types. 4975 if (!StoreVT.isVector()) 4976 return VData; 4977 4978 SDLoc DL(VData); 4979 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 4980 4981 if (Subtarget->hasUnpackedD16VMem()) { 4982 // We need to unpack the packed data to store. 4983 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 4984 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 4985 4986 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4987 StoreVT.getVectorNumElements()); 4988 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 4989 return DAG.UnrollVectorOp(ZExt.getNode()); 4990 } 4991 4992 if (isTypeLegal(StoreVT)) 4993 return VData; 4994 4995 // If target supports packed vmem, we just need to workaround 4996 // the illegal type by casting to an equivalent one. 4997 EVT EquivStoreVT = getEquivalentMemType(*DAG.getContext(), StoreVT); 4998 return DAG.getNode(ISD::BITCAST, DL, EquivStoreVT, VData); 4999 } 5000 5001 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 5002 SelectionDAG &DAG) const { 5003 SDLoc DL(Op); 5004 SDValue Chain = Op.getOperand(0); 5005 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 5006 MachineFunction &MF = DAG.getMachineFunction(); 5007 5008 switch (IntrinsicID) { 5009 case Intrinsic::amdgcn_exp: { 5010 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 5011 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 5012 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8)); 5013 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9)); 5014 5015 const SDValue Ops[] = { 5016 Chain, 5017 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 5018 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 5019 Op.getOperand(4), // src0 5020 Op.getOperand(5), // src1 5021 Op.getOperand(6), // src2 5022 Op.getOperand(7), // src3 5023 DAG.getTargetConstant(0, DL, MVT::i1), // compr 5024 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 5025 }; 5026 5027 unsigned Opc = Done->isNullValue() ? 5028 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 5029 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 5030 } 5031 case Intrinsic::amdgcn_exp_compr: { 5032 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 5033 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 5034 SDValue Src0 = Op.getOperand(4); 5035 SDValue Src1 = Op.getOperand(5); 5036 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 5037 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7)); 5038 5039 SDValue Undef = DAG.getUNDEF(MVT::f32); 5040 const SDValue Ops[] = { 5041 Chain, 5042 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 5043 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 5044 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), 5045 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), 5046 Undef, // src2 5047 Undef, // src3 5048 DAG.getTargetConstant(1, DL, MVT::i1), // compr 5049 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 5050 }; 5051 5052 unsigned Opc = Done->isNullValue() ? 5053 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 5054 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 5055 } 5056 case Intrinsic::amdgcn_s_sendmsg: 5057 case Intrinsic::amdgcn_s_sendmsghalt: { 5058 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ? 5059 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT; 5060 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 5061 SDValue Glue = Chain.getValue(1); 5062 return DAG.getNode(NodeOp, DL, MVT::Other, Chain, 5063 Op.getOperand(2), Glue); 5064 } 5065 case Intrinsic::amdgcn_init_exec: { 5066 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain, 5067 Op.getOperand(2)); 5068 } 5069 case Intrinsic::amdgcn_init_exec_from_input: { 5070 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain, 5071 Op.getOperand(2), Op.getOperand(3)); 5072 } 5073 case AMDGPUIntrinsic::AMDGPU_kill: { 5074 SDValue Src = Op.getOperand(2); 5075 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) { 5076 if (!K->isNegative()) 5077 return Chain; 5078 5079 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32); 5080 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne); 5081 } 5082 5083 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src); 5084 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast); 5085 } 5086 case Intrinsic::amdgcn_s_barrier: { 5087 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 5088 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 5089 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 5090 if (WGSize <= ST.getWavefrontSize()) 5091 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 5092 Op.getOperand(0)), 0); 5093 } 5094 return SDValue(); 5095 }; 5096 case AMDGPUIntrinsic::SI_tbuffer_store: { 5097 5098 // Extract vindex and voffset from vaddr as appropriate 5099 const ConstantSDNode *OffEn = cast<ConstantSDNode>(Op.getOperand(10)); 5100 const ConstantSDNode *IdxEn = cast<ConstantSDNode>(Op.getOperand(11)); 5101 SDValue VAddr = Op.getOperand(5); 5102 5103 SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32); 5104 5105 assert(!(OffEn->isOne() && IdxEn->isOne()) && 5106 "Legacy intrinsic doesn't support both offset and index - use new version"); 5107 5108 SDValue VIndex = IdxEn->isOne() ? VAddr : Zero; 5109 SDValue VOffset = OffEn->isOne() ? VAddr : Zero; 5110 5111 // Deal with the vec-3 case 5112 const ConstantSDNode *NumChannels = cast<ConstantSDNode>(Op.getOperand(4)); 5113 auto Opcode = NumChannels->getZExtValue() == 3 ? 5114 AMDGPUISD::TBUFFER_STORE_FORMAT_X3 : AMDGPUISD::TBUFFER_STORE_FORMAT; 5115 5116 SDValue Ops[] = { 5117 Chain, 5118 Op.getOperand(3), // vdata 5119 Op.getOperand(2), // rsrc 5120 VIndex, 5121 VOffset, 5122 Op.getOperand(6), // soffset 5123 Op.getOperand(7), // inst_offset 5124 Op.getOperand(8), // dfmt 5125 Op.getOperand(9), // nfmt 5126 Op.getOperand(12), // glc 5127 Op.getOperand(13), // slc 5128 }; 5129 5130 assert((cast<ConstantSDNode>(Op.getOperand(14)))->getZExtValue() == 0 && 5131 "Value of tfe other than zero is unsupported"); 5132 5133 EVT VT = Op.getOperand(3).getValueType(); 5134 MachineMemOperand *MMO = MF.getMachineMemOperand( 5135 MachinePointerInfo(), 5136 MachineMemOperand::MOStore, 5137 VT.getStoreSize(), 4); 5138 return DAG.getMemIntrinsicNode(Opcode, DL, 5139 Op->getVTList(), Ops, VT, MMO); 5140 } 5141 5142 case Intrinsic::amdgcn_tbuffer_store: { 5143 SDValue VData = Op.getOperand(2); 5144 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 5145 if (IsD16) 5146 VData = handleD16VData(VData, DAG); 5147 SDValue Ops[] = { 5148 Chain, 5149 VData, // vdata 5150 Op.getOperand(3), // rsrc 5151 Op.getOperand(4), // vindex 5152 Op.getOperand(5), // voffset 5153 Op.getOperand(6), // soffset 5154 Op.getOperand(7), // offset 5155 Op.getOperand(8), // dfmt 5156 Op.getOperand(9), // nfmt 5157 Op.getOperand(10), // glc 5158 Op.getOperand(11) // slc 5159 }; 5160 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 5161 AMDGPUISD::TBUFFER_STORE_FORMAT; 5162 MemSDNode *M = cast<MemSDNode>(Op); 5163 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 5164 M->getMemoryVT(), M->getMemOperand()); 5165 } 5166 5167 case Intrinsic::amdgcn_buffer_store: 5168 case Intrinsic::amdgcn_buffer_store_format: { 5169 SDValue VData = Op.getOperand(2); 5170 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 5171 if (IsD16) 5172 VData = handleD16VData(VData, DAG); 5173 SDValue Ops[] = { 5174 Chain, 5175 VData, // vdata 5176 Op.getOperand(3), // rsrc 5177 Op.getOperand(4), // vindex 5178 Op.getOperand(5), // offset 5179 Op.getOperand(6), // glc 5180 Op.getOperand(7) // slc 5181 }; 5182 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 5183 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 5184 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 5185 MemSDNode *M = cast<MemSDNode>(Op); 5186 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 5187 M->getMemoryVT(), M->getMemOperand()); 5188 } 5189 case Intrinsic::amdgcn_image_store: 5190 case Intrinsic::amdgcn_image_store_mip: { 5191 SDValue VData = Op.getOperand(2); 5192 if ((Subtarget->hasUnpackedD16VMem() && 5193 VData.getValueType() == MVT::v2f16) || 5194 VData.getValueType() == MVT::v4f16) { 5195 SDValue Chain = Op.getOperand(0); 5196 5197 VData = handleD16VData(VData, DAG); 5198 SDValue Ops[] = { 5199 Chain, // Chain 5200 VData, // vdata 5201 Op.getOperand(3), // vaddr 5202 Op.getOperand(4), // rsrc 5203 Op.getOperand(5), // dmask 5204 Op.getOperand(6), // glc 5205 Op.getOperand(7), // slc 5206 Op.getOperand(8), // lwe 5207 Op.getOperand(9) // da 5208 }; 5209 unsigned Opc = (IntrinsicID == Intrinsic::amdgcn_image_store) ? 5210 AMDGPUISD::IMAGE_STORE : AMDGPUISD::IMAGE_STORE_MIP; 5211 MemSDNode *M = cast<MemSDNode>(Op); 5212 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 5213 M->getMemoryVT(), M->getMemOperand()); 5214 } 5215 5216 return SDValue(); 5217 } 5218 default: { 5219 const AMDGPU::D16ImageDimIntrinsic *D16ImageDimIntr = 5220 AMDGPU::lookupD16ImageDimIntrinsicByIntr(IntrinsicID); 5221 if (D16ImageDimIntr) { 5222 SDValue VData = Op.getOperand(2); 5223 EVT StoreVT = VData.getValueType(); 5224 if (((StoreVT == MVT::v2f16 || StoreVT == MVT::v4f16) && 5225 Subtarget->hasUnpackedD16VMem()) || 5226 !isTypeLegal(StoreVT)) { 5227 SmallVector<SDValue, 12> Ops(Op.getNode()->op_values()); 5228 5229 Ops[1] = DAG.getConstant(D16ImageDimIntr->D16HelperIntr, DL, MVT::i32); 5230 Ops[2] = handleD16VData(VData, DAG); 5231 5232 MemSDNode *M = cast<MemSDNode>(Op); 5233 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Op->getVTList(), 5234 Ops, M->getMemoryVT(), 5235 M->getMemOperand()); 5236 } 5237 } 5238 5239 return Op; 5240 } 5241 } 5242 } 5243 5244 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 5245 SDLoc DL(Op); 5246 LoadSDNode *Load = cast<LoadSDNode>(Op); 5247 ISD::LoadExtType ExtType = Load->getExtensionType(); 5248 EVT MemVT = Load->getMemoryVT(); 5249 5250 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 5251 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 5252 return SDValue(); 5253 5254 // FIXME: Copied from PPC 5255 // First, load into 32 bits, then truncate to 1 bit. 5256 5257 SDValue Chain = Load->getChain(); 5258 SDValue BasePtr = Load->getBasePtr(); 5259 MachineMemOperand *MMO = Load->getMemOperand(); 5260 5261 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 5262 5263 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 5264 BasePtr, RealMemVT, MMO); 5265 5266 SDValue Ops[] = { 5267 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 5268 NewLD.getValue(1) 5269 }; 5270 5271 return DAG.getMergeValues(Ops, DL); 5272 } 5273 5274 if (!MemVT.isVector()) 5275 return SDValue(); 5276 5277 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 5278 "Custom lowering for non-i32 vectors hasn't been implemented."); 5279 5280 unsigned Alignment = Load->getAlignment(); 5281 unsigned AS = Load->getAddressSpace(); 5282 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 5283 AS, Alignment)) { 5284 SDValue Ops[2]; 5285 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 5286 return DAG.getMergeValues(Ops, DL); 5287 } 5288 5289 MachineFunction &MF = DAG.getMachineFunction(); 5290 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 5291 // If there is a possibilty that flat instruction access scratch memory 5292 // then we need to use the same legalization rules we use for private. 5293 if (AS == AMDGPUASI.FLAT_ADDRESS) 5294 AS = MFI->hasFlatScratchInit() ? 5295 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS; 5296 5297 unsigned NumElements = MemVT.getVectorNumElements(); 5298 5299 if (AS == AMDGPUASI.CONSTANT_ADDRESS || 5300 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT) { 5301 if (!Op->isDivergent() && Alignment >= 4) 5302 return SDValue(); 5303 // Non-uniform loads will be selected to MUBUF instructions, so they 5304 // have the same legalization requirements as global and private 5305 // loads. 5306 // 5307 } 5308 5309 if (AS == AMDGPUASI.CONSTANT_ADDRESS || 5310 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT || 5311 AS == AMDGPUASI.GLOBAL_ADDRESS) { 5312 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 5313 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 5314 Alignment >= 4) 5315 return SDValue(); 5316 // Non-uniform loads will be selected to MUBUF instructions, so they 5317 // have the same legalization requirements as global and private 5318 // loads. 5319 // 5320 } 5321 if (AS == AMDGPUASI.CONSTANT_ADDRESS || 5322 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT || 5323 AS == AMDGPUASI.GLOBAL_ADDRESS || 5324 AS == AMDGPUASI.FLAT_ADDRESS) { 5325 if (NumElements > 4) 5326 return SplitVectorLoad(Op, DAG); 5327 // v4 loads are supported for private and global memory. 5328 return SDValue(); 5329 } 5330 if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 5331 // Depending on the setting of the private_element_size field in the 5332 // resource descriptor, we can only make private accesses up to a certain 5333 // size. 5334 switch (Subtarget->getMaxPrivateElementSize()) { 5335 case 4: 5336 return scalarizeVectorLoad(Load, DAG); 5337 case 8: 5338 if (NumElements > 2) 5339 return SplitVectorLoad(Op, DAG); 5340 return SDValue(); 5341 case 16: 5342 // Same as global/flat 5343 if (NumElements > 4) 5344 return SplitVectorLoad(Op, DAG); 5345 return SDValue(); 5346 default: 5347 llvm_unreachable("unsupported private_element_size"); 5348 } 5349 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 5350 // Use ds_read_b128 if possible. 5351 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 5352 MemVT.getStoreSize() == 16) 5353 return SDValue(); 5354 5355 if (NumElements > 2) 5356 return SplitVectorLoad(Op, DAG); 5357 } 5358 return SDValue(); 5359 } 5360 5361 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 5362 if (Op.getValueType() != MVT::i64) 5363 return SDValue(); 5364 5365 SDLoc DL(Op); 5366 SDValue Cond = Op.getOperand(0); 5367 5368 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 5369 SDValue One = DAG.getConstant(1, DL, MVT::i32); 5370 5371 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 5372 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 5373 5374 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 5375 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 5376 5377 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 5378 5379 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 5380 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 5381 5382 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 5383 5384 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 5385 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res); 5386 } 5387 5388 // Catch division cases where we can use shortcuts with rcp and rsq 5389 // instructions. 5390 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 5391 SelectionDAG &DAG) const { 5392 SDLoc SL(Op); 5393 SDValue LHS = Op.getOperand(0); 5394 SDValue RHS = Op.getOperand(1); 5395 EVT VT = Op.getValueType(); 5396 const SDNodeFlags Flags = Op->getFlags(); 5397 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal(); 5398 5399 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals()) 5400 return SDValue(); 5401 5402 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 5403 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) { 5404 if (CLHS->isExactlyValue(1.0)) { 5405 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 5406 // the CI documentation has a worst case error of 1 ulp. 5407 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 5408 // use it as long as we aren't trying to use denormals. 5409 // 5410 // v_rcp_f16 and v_rsq_f16 DO support denormals. 5411 5412 // 1.0 / sqrt(x) -> rsq(x) 5413 5414 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 5415 // error seems really high at 2^29 ULP. 5416 if (RHS.getOpcode() == ISD::FSQRT) 5417 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 5418 5419 // 1.0 / x -> rcp(x) 5420 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 5421 } 5422 5423 // Same as for 1.0, but expand the sign out of the constant. 5424 if (CLHS->isExactlyValue(-1.0)) { 5425 // -1.0 / x -> rcp (fneg x) 5426 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 5427 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 5428 } 5429 } 5430 } 5431 5432 if (Unsafe) { 5433 // Turn into multiply by the reciprocal. 5434 // x / y -> x * (1.0 / y) 5435 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 5436 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 5437 } 5438 5439 return SDValue(); 5440 } 5441 5442 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 5443 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 5444 if (GlueChain->getNumValues() <= 1) { 5445 return DAG.getNode(Opcode, SL, VT, A, B); 5446 } 5447 5448 assert(GlueChain->getNumValues() == 3); 5449 5450 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 5451 switch (Opcode) { 5452 default: llvm_unreachable("no chain equivalent for opcode"); 5453 case ISD::FMUL: 5454 Opcode = AMDGPUISD::FMUL_W_CHAIN; 5455 break; 5456 } 5457 5458 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 5459 GlueChain.getValue(2)); 5460 } 5461 5462 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 5463 EVT VT, SDValue A, SDValue B, SDValue C, 5464 SDValue GlueChain) { 5465 if (GlueChain->getNumValues() <= 1) { 5466 return DAG.getNode(Opcode, SL, VT, A, B, C); 5467 } 5468 5469 assert(GlueChain->getNumValues() == 3); 5470 5471 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 5472 switch (Opcode) { 5473 default: llvm_unreachable("no chain equivalent for opcode"); 5474 case ISD::FMA: 5475 Opcode = AMDGPUISD::FMA_W_CHAIN; 5476 break; 5477 } 5478 5479 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 5480 GlueChain.getValue(2)); 5481 } 5482 5483 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 5484 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 5485 return FastLowered; 5486 5487 SDLoc SL(Op); 5488 SDValue Src0 = Op.getOperand(0); 5489 SDValue Src1 = Op.getOperand(1); 5490 5491 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 5492 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 5493 5494 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 5495 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 5496 5497 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 5498 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 5499 5500 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 5501 } 5502 5503 // Faster 2.5 ULP division that does not support denormals. 5504 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 5505 SDLoc SL(Op); 5506 SDValue LHS = Op.getOperand(1); 5507 SDValue RHS = Op.getOperand(2); 5508 5509 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 5510 5511 const APFloat K0Val(BitsToFloat(0x6f800000)); 5512 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 5513 5514 const APFloat K1Val(BitsToFloat(0x2f800000)); 5515 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 5516 5517 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 5518 5519 EVT SetCCVT = 5520 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 5521 5522 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 5523 5524 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 5525 5526 // TODO: Should this propagate fast-math-flags? 5527 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 5528 5529 // rcp does not support denormals. 5530 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 5531 5532 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 5533 5534 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 5535 } 5536 5537 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 5538 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 5539 return FastLowered; 5540 5541 SDLoc SL(Op); 5542 SDValue LHS = Op.getOperand(0); 5543 SDValue RHS = Op.getOperand(1); 5544 5545 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 5546 5547 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 5548 5549 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 5550 RHS, RHS, LHS); 5551 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 5552 LHS, RHS, LHS); 5553 5554 // Denominator is scaled to not be denormal, so using rcp is ok. 5555 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 5556 DenominatorScaled); 5557 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 5558 DenominatorScaled); 5559 5560 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 5561 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 5562 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 5563 5564 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 5565 5566 if (!Subtarget->hasFP32Denormals()) { 5567 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 5568 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 5569 SL, MVT::i32); 5570 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 5571 DAG.getEntryNode(), 5572 EnableDenormValue, BitField); 5573 SDValue Ops[3] = { 5574 NegDivScale0, 5575 EnableDenorm.getValue(0), 5576 EnableDenorm.getValue(1) 5577 }; 5578 5579 NegDivScale0 = DAG.getMergeValues(Ops, SL); 5580 } 5581 5582 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 5583 ApproxRcp, One, NegDivScale0); 5584 5585 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 5586 ApproxRcp, Fma0); 5587 5588 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 5589 Fma1, Fma1); 5590 5591 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 5592 NumeratorScaled, Mul); 5593 5594 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 5595 5596 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 5597 NumeratorScaled, Fma3); 5598 5599 if (!Subtarget->hasFP32Denormals()) { 5600 const SDValue DisableDenormValue = 5601 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 5602 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 5603 Fma4.getValue(1), 5604 DisableDenormValue, 5605 BitField, 5606 Fma4.getValue(2)); 5607 5608 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 5609 DisableDenorm, DAG.getRoot()); 5610 DAG.setRoot(OutputChain); 5611 } 5612 5613 SDValue Scale = NumeratorScaled.getValue(1); 5614 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 5615 Fma4, Fma1, Fma3, Scale); 5616 5617 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 5618 } 5619 5620 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 5621 if (DAG.getTarget().Options.UnsafeFPMath) 5622 return lowerFastUnsafeFDIV(Op, DAG); 5623 5624 SDLoc SL(Op); 5625 SDValue X = Op.getOperand(0); 5626 SDValue Y = Op.getOperand(1); 5627 5628 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 5629 5630 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 5631 5632 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 5633 5634 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 5635 5636 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 5637 5638 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 5639 5640 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 5641 5642 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 5643 5644 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 5645 5646 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 5647 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 5648 5649 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 5650 NegDivScale0, Mul, DivScale1); 5651 5652 SDValue Scale; 5653 5654 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) { 5655 // Workaround a hardware bug on SI where the condition output from div_scale 5656 // is not usable. 5657 5658 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 5659 5660 // Figure out if the scale to use for div_fmas. 5661 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 5662 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 5663 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 5664 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 5665 5666 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 5667 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 5668 5669 SDValue Scale0Hi 5670 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 5671 SDValue Scale1Hi 5672 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 5673 5674 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 5675 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 5676 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 5677 } else { 5678 Scale = DivScale1.getValue(1); 5679 } 5680 5681 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 5682 Fma4, Fma3, Mul, Scale); 5683 5684 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 5685 } 5686 5687 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 5688 EVT VT = Op.getValueType(); 5689 5690 if (VT == MVT::f32) 5691 return LowerFDIV32(Op, DAG); 5692 5693 if (VT == MVT::f64) 5694 return LowerFDIV64(Op, DAG); 5695 5696 if (VT == MVT::f16) 5697 return LowerFDIV16(Op, DAG); 5698 5699 llvm_unreachable("Unexpected type for fdiv"); 5700 } 5701 5702 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 5703 SDLoc DL(Op); 5704 StoreSDNode *Store = cast<StoreSDNode>(Op); 5705 EVT VT = Store->getMemoryVT(); 5706 5707 if (VT == MVT::i1) { 5708 return DAG.getTruncStore(Store->getChain(), DL, 5709 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 5710 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 5711 } 5712 5713 assert(VT.isVector() && 5714 Store->getValue().getValueType().getScalarType() == MVT::i32); 5715 5716 unsigned AS = Store->getAddressSpace(); 5717 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 5718 AS, Store->getAlignment())) { 5719 return expandUnalignedStore(Store, DAG); 5720 } 5721 5722 MachineFunction &MF = DAG.getMachineFunction(); 5723 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 5724 // If there is a possibilty that flat instruction access scratch memory 5725 // then we need to use the same legalization rules we use for private. 5726 if (AS == AMDGPUASI.FLAT_ADDRESS) 5727 AS = MFI->hasFlatScratchInit() ? 5728 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS; 5729 5730 unsigned NumElements = VT.getVectorNumElements(); 5731 if (AS == AMDGPUASI.GLOBAL_ADDRESS || 5732 AS == AMDGPUASI.FLAT_ADDRESS) { 5733 if (NumElements > 4) 5734 return SplitVectorStore(Op, DAG); 5735 return SDValue(); 5736 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 5737 switch (Subtarget->getMaxPrivateElementSize()) { 5738 case 4: 5739 return scalarizeVectorStore(Store, DAG); 5740 case 8: 5741 if (NumElements > 2) 5742 return SplitVectorStore(Op, DAG); 5743 return SDValue(); 5744 case 16: 5745 if (NumElements > 4) 5746 return SplitVectorStore(Op, DAG); 5747 return SDValue(); 5748 default: 5749 llvm_unreachable("unsupported private_element_size"); 5750 } 5751 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 5752 // Use ds_write_b128 if possible. 5753 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 5754 VT.getStoreSize() == 16) 5755 return SDValue(); 5756 5757 if (NumElements > 2) 5758 return SplitVectorStore(Op, DAG); 5759 return SDValue(); 5760 } else { 5761 llvm_unreachable("unhandled address space"); 5762 } 5763 } 5764 5765 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 5766 SDLoc DL(Op); 5767 EVT VT = Op.getValueType(); 5768 SDValue Arg = Op.getOperand(0); 5769 // TODO: Should this propagate fast-math-flags? 5770 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT, 5771 DAG.getNode(ISD::FMUL, DL, VT, Arg, 5772 DAG.getConstantFP(0.5/M_PI, DL, 5773 VT))); 5774 5775 switch (Op.getOpcode()) { 5776 case ISD::FCOS: 5777 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart); 5778 case ISD::FSIN: 5779 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart); 5780 default: 5781 llvm_unreachable("Wrong trig opcode"); 5782 } 5783 } 5784 5785 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 5786 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 5787 assert(AtomicNode->isCompareAndSwap()); 5788 unsigned AS = AtomicNode->getAddressSpace(); 5789 5790 // No custom lowering required for local address space 5791 if (!isFlatGlobalAddrSpace(AS, AMDGPUASI)) 5792 return Op; 5793 5794 // Non-local address space requires custom lowering for atomic compare 5795 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 5796 SDLoc DL(Op); 5797 SDValue ChainIn = Op.getOperand(0); 5798 SDValue Addr = Op.getOperand(1); 5799 SDValue Old = Op.getOperand(2); 5800 SDValue New = Op.getOperand(3); 5801 EVT VT = Op.getValueType(); 5802 MVT SimpleVT = VT.getSimpleVT(); 5803 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 5804 5805 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 5806 SDValue Ops[] = { ChainIn, Addr, NewOld }; 5807 5808 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 5809 Ops, VT, AtomicNode->getMemOperand()); 5810 } 5811 5812 //===----------------------------------------------------------------------===// 5813 // Custom DAG optimizations 5814 //===----------------------------------------------------------------------===// 5815 5816 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 5817 DAGCombinerInfo &DCI) const { 5818 EVT VT = N->getValueType(0); 5819 EVT ScalarVT = VT.getScalarType(); 5820 if (ScalarVT != MVT::f32) 5821 return SDValue(); 5822 5823 SelectionDAG &DAG = DCI.DAG; 5824 SDLoc DL(N); 5825 5826 SDValue Src = N->getOperand(0); 5827 EVT SrcVT = Src.getValueType(); 5828 5829 // TODO: We could try to match extracting the higher bytes, which would be 5830 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 5831 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 5832 // about in practice. 5833 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 5834 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 5835 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 5836 DCI.AddToWorklist(Cvt.getNode()); 5837 return Cvt; 5838 } 5839 } 5840 5841 return SDValue(); 5842 } 5843 5844 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 5845 5846 // This is a variant of 5847 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 5848 // 5849 // The normal DAG combiner will do this, but only if the add has one use since 5850 // that would increase the number of instructions. 5851 // 5852 // This prevents us from seeing a constant offset that can be folded into a 5853 // memory instruction's addressing mode. If we know the resulting add offset of 5854 // a pointer can be folded into an addressing offset, we can replace the pointer 5855 // operand with the add of new constant offset. This eliminates one of the uses, 5856 // and may allow the remaining use to also be simplified. 5857 // 5858 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 5859 unsigned AddrSpace, 5860 EVT MemVT, 5861 DAGCombinerInfo &DCI) const { 5862 SDValue N0 = N->getOperand(0); 5863 SDValue N1 = N->getOperand(1); 5864 5865 // We only do this to handle cases where it's profitable when there are 5866 // multiple uses of the add, so defer to the standard combine. 5867 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 5868 N0->hasOneUse()) 5869 return SDValue(); 5870 5871 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 5872 if (!CN1) 5873 return SDValue(); 5874 5875 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5876 if (!CAdd) 5877 return SDValue(); 5878 5879 // If the resulting offset is too large, we can't fold it into the addressing 5880 // mode offset. 5881 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 5882 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 5883 5884 AddrMode AM; 5885 AM.HasBaseReg = true; 5886 AM.BaseOffs = Offset.getSExtValue(); 5887 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 5888 return SDValue(); 5889 5890 SelectionDAG &DAG = DCI.DAG; 5891 SDLoc SL(N); 5892 EVT VT = N->getValueType(0); 5893 5894 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 5895 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 5896 5897 SDNodeFlags Flags; 5898 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 5899 (N0.getOpcode() == ISD::OR || 5900 N0->getFlags().hasNoUnsignedWrap())); 5901 5902 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 5903 } 5904 5905 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 5906 DAGCombinerInfo &DCI) const { 5907 SDValue Ptr = N->getBasePtr(); 5908 SelectionDAG &DAG = DCI.DAG; 5909 SDLoc SL(N); 5910 5911 // TODO: We could also do this for multiplies. 5912 if (Ptr.getOpcode() == ISD::SHL) { 5913 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 5914 N->getMemoryVT(), DCI); 5915 if (NewPtr) { 5916 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 5917 5918 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 5919 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 5920 } 5921 } 5922 5923 return SDValue(); 5924 } 5925 5926 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 5927 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 5928 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 5929 (Opc == ISD::XOR && Val == 0); 5930 } 5931 5932 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 5933 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 5934 // integer combine opportunities since most 64-bit operations are decomposed 5935 // this way. TODO: We won't want this for SALU especially if it is an inline 5936 // immediate. 5937 SDValue SITargetLowering::splitBinaryBitConstantOp( 5938 DAGCombinerInfo &DCI, 5939 const SDLoc &SL, 5940 unsigned Opc, SDValue LHS, 5941 const ConstantSDNode *CRHS) const { 5942 uint64_t Val = CRHS->getZExtValue(); 5943 uint32_t ValLo = Lo_32(Val); 5944 uint32_t ValHi = Hi_32(Val); 5945 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 5946 5947 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 5948 bitOpWithConstantIsReducible(Opc, ValHi)) || 5949 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 5950 // If we need to materialize a 64-bit immediate, it will be split up later 5951 // anyway. Avoid creating the harder to understand 64-bit immediate 5952 // materialization. 5953 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 5954 } 5955 5956 return SDValue(); 5957 } 5958 5959 // Returns true if argument is a boolean value which is not serialized into 5960 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 5961 static bool isBoolSGPR(SDValue V) { 5962 if (V.getValueType() != MVT::i1) 5963 return false; 5964 switch (V.getOpcode()) { 5965 default: break; 5966 case ISD::SETCC: 5967 case ISD::AND: 5968 case ISD::OR: 5969 case ISD::XOR: 5970 case AMDGPUISD::FP_CLASS: 5971 return true; 5972 } 5973 return false; 5974 } 5975 5976 SDValue SITargetLowering::performAndCombine(SDNode *N, 5977 DAGCombinerInfo &DCI) const { 5978 if (DCI.isBeforeLegalize()) 5979 return SDValue(); 5980 5981 SelectionDAG &DAG = DCI.DAG; 5982 EVT VT = N->getValueType(0); 5983 SDValue LHS = N->getOperand(0); 5984 SDValue RHS = N->getOperand(1); 5985 5986 5987 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 5988 if (VT == MVT::i64 && CRHS) { 5989 if (SDValue Split 5990 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 5991 return Split; 5992 } 5993 5994 if (CRHS && VT == MVT::i32) { 5995 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 5996 // nb = number of trailing zeroes in mask 5997 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 5998 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 5999 uint64_t Mask = CRHS->getZExtValue(); 6000 unsigned Bits = countPopulation(Mask); 6001 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 6002 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 6003 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 6004 unsigned Shift = CShift->getZExtValue(); 6005 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 6006 unsigned Offset = NB + Shift; 6007 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 6008 SDLoc SL(N); 6009 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 6010 LHS->getOperand(0), 6011 DAG.getConstant(Offset, SL, MVT::i32), 6012 DAG.getConstant(Bits, SL, MVT::i32)); 6013 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 6014 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 6015 DAG.getValueType(NarrowVT)); 6016 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 6017 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 6018 return Shl; 6019 } 6020 } 6021 } 6022 } 6023 6024 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 6025 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 6026 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 6027 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 6028 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 6029 6030 SDValue X = LHS.getOperand(0); 6031 SDValue Y = RHS.getOperand(0); 6032 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 6033 return SDValue(); 6034 6035 if (LCC == ISD::SETO) { 6036 if (X != LHS.getOperand(1)) 6037 return SDValue(); 6038 6039 if (RCC == ISD::SETUNE) { 6040 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 6041 if (!C1 || !C1->isInfinity() || C1->isNegative()) 6042 return SDValue(); 6043 6044 const uint32_t Mask = SIInstrFlags::N_NORMAL | 6045 SIInstrFlags::N_SUBNORMAL | 6046 SIInstrFlags::N_ZERO | 6047 SIInstrFlags::P_ZERO | 6048 SIInstrFlags::P_SUBNORMAL | 6049 SIInstrFlags::P_NORMAL; 6050 6051 static_assert(((~(SIInstrFlags::S_NAN | 6052 SIInstrFlags::Q_NAN | 6053 SIInstrFlags::N_INFINITY | 6054 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 6055 "mask not equal"); 6056 6057 SDLoc DL(N); 6058 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 6059 X, DAG.getConstant(Mask, DL, MVT::i32)); 6060 } 6061 } 6062 } 6063 6064 if (VT == MVT::i32 && 6065 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 6066 // and x, (sext cc from i1) => select cc, x, 0 6067 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 6068 std::swap(LHS, RHS); 6069 if (isBoolSGPR(RHS.getOperand(0))) 6070 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 6071 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 6072 } 6073 6074 return SDValue(); 6075 } 6076 6077 SDValue SITargetLowering::performOrCombine(SDNode *N, 6078 DAGCombinerInfo &DCI) const { 6079 SelectionDAG &DAG = DCI.DAG; 6080 SDValue LHS = N->getOperand(0); 6081 SDValue RHS = N->getOperand(1); 6082 6083 EVT VT = N->getValueType(0); 6084 if (VT == MVT::i1) { 6085 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 6086 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 6087 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 6088 SDValue Src = LHS.getOperand(0); 6089 if (Src != RHS.getOperand(0)) 6090 return SDValue(); 6091 6092 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 6093 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 6094 if (!CLHS || !CRHS) 6095 return SDValue(); 6096 6097 // Only 10 bits are used. 6098 static const uint32_t MaxMask = 0x3ff; 6099 6100 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 6101 SDLoc DL(N); 6102 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 6103 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 6104 } 6105 6106 return SDValue(); 6107 } 6108 6109 if (VT != MVT::i64) 6110 return SDValue(); 6111 6112 // TODO: This could be a generic combine with a predicate for extracting the 6113 // high half of an integer being free. 6114 6115 // (or i64:x, (zero_extend i32:y)) -> 6116 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 6117 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 6118 RHS.getOpcode() != ISD::ZERO_EXTEND) 6119 std::swap(LHS, RHS); 6120 6121 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 6122 SDValue ExtSrc = RHS.getOperand(0); 6123 EVT SrcVT = ExtSrc.getValueType(); 6124 if (SrcVT == MVT::i32) { 6125 SDLoc SL(N); 6126 SDValue LowLHS, HiBits; 6127 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 6128 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 6129 6130 DCI.AddToWorklist(LowOr.getNode()); 6131 DCI.AddToWorklist(HiBits.getNode()); 6132 6133 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 6134 LowOr, HiBits); 6135 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 6136 } 6137 } 6138 6139 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6140 if (CRHS) { 6141 if (SDValue Split 6142 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 6143 return Split; 6144 } 6145 6146 return SDValue(); 6147 } 6148 6149 SDValue SITargetLowering::performXorCombine(SDNode *N, 6150 DAGCombinerInfo &DCI) const { 6151 EVT VT = N->getValueType(0); 6152 if (VT != MVT::i64) 6153 return SDValue(); 6154 6155 SDValue LHS = N->getOperand(0); 6156 SDValue RHS = N->getOperand(1); 6157 6158 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 6159 if (CRHS) { 6160 if (SDValue Split 6161 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 6162 return Split; 6163 } 6164 6165 return SDValue(); 6166 } 6167 6168 // Instructions that will be lowered with a final instruction that zeros the 6169 // high result bits. 6170 // XXX - probably only need to list legal operations. 6171 static bool fp16SrcZerosHighBits(unsigned Opc) { 6172 switch (Opc) { 6173 case ISD::FADD: 6174 case ISD::FSUB: 6175 case ISD::FMUL: 6176 case ISD::FDIV: 6177 case ISD::FREM: 6178 case ISD::FMA: 6179 case ISD::FMAD: 6180 case ISD::FCANONICALIZE: 6181 case ISD::FP_ROUND: 6182 case ISD::UINT_TO_FP: 6183 case ISD::SINT_TO_FP: 6184 case ISD::FABS: 6185 // Fabs is lowered to a bit operation, but it's an and which will clear the 6186 // high bits anyway. 6187 case ISD::FSQRT: 6188 case ISD::FSIN: 6189 case ISD::FCOS: 6190 case ISD::FPOWI: 6191 case ISD::FPOW: 6192 case ISD::FLOG: 6193 case ISD::FLOG2: 6194 case ISD::FLOG10: 6195 case ISD::FEXP: 6196 case ISD::FEXP2: 6197 case ISD::FCEIL: 6198 case ISD::FTRUNC: 6199 case ISD::FRINT: 6200 case ISD::FNEARBYINT: 6201 case ISD::FROUND: 6202 case ISD::FFLOOR: 6203 case ISD::FMINNUM: 6204 case ISD::FMAXNUM: 6205 case AMDGPUISD::FRACT: 6206 case AMDGPUISD::CLAMP: 6207 case AMDGPUISD::COS_HW: 6208 case AMDGPUISD::SIN_HW: 6209 case AMDGPUISD::FMIN3: 6210 case AMDGPUISD::FMAX3: 6211 case AMDGPUISD::FMED3: 6212 case AMDGPUISD::FMAD_FTZ: 6213 case AMDGPUISD::RCP: 6214 case AMDGPUISD::RSQ: 6215 case AMDGPUISD::LDEXP: 6216 return true; 6217 default: 6218 // fcopysign, select and others may be lowered to 32-bit bit operations 6219 // which don't zero the high bits. 6220 return false; 6221 } 6222 } 6223 6224 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 6225 DAGCombinerInfo &DCI) const { 6226 if (!Subtarget->has16BitInsts() || 6227 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 6228 return SDValue(); 6229 6230 EVT VT = N->getValueType(0); 6231 if (VT != MVT::i32) 6232 return SDValue(); 6233 6234 SDValue Src = N->getOperand(0); 6235 if (Src.getValueType() != MVT::i16) 6236 return SDValue(); 6237 6238 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 6239 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 6240 if (Src.getOpcode() == ISD::BITCAST) { 6241 SDValue BCSrc = Src.getOperand(0); 6242 if (BCSrc.getValueType() == MVT::f16 && 6243 fp16SrcZerosHighBits(BCSrc.getOpcode())) 6244 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 6245 } 6246 6247 return SDValue(); 6248 } 6249 6250 SDValue SITargetLowering::performClassCombine(SDNode *N, 6251 DAGCombinerInfo &DCI) const { 6252 SelectionDAG &DAG = DCI.DAG; 6253 SDValue Mask = N->getOperand(1); 6254 6255 // fp_class x, 0 -> false 6256 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 6257 if (CMask->isNullValue()) 6258 return DAG.getConstant(0, SDLoc(N), MVT::i1); 6259 } 6260 6261 if (N->getOperand(0).isUndef()) 6262 return DAG.getUNDEF(MVT::i1); 6263 6264 return SDValue(); 6265 } 6266 6267 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) { 6268 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions()) 6269 return true; 6270 6271 return DAG.isKnownNeverNaN(Op); 6272 } 6273 6274 static bool isCanonicalized(SelectionDAG &DAG, SDValue Op, 6275 const SISubtarget *ST, unsigned MaxDepth=5) { 6276 // If source is a result of another standard FP operation it is already in 6277 // canonical form. 6278 6279 switch (Op.getOpcode()) { 6280 default: 6281 break; 6282 6283 // These will flush denorms if required. 6284 case ISD::FADD: 6285 case ISD::FSUB: 6286 case ISD::FMUL: 6287 case ISD::FSQRT: 6288 case ISD::FCEIL: 6289 case ISD::FFLOOR: 6290 case ISD::FMA: 6291 case ISD::FMAD: 6292 6293 case ISD::FCANONICALIZE: 6294 return true; 6295 6296 case ISD::FP_ROUND: 6297 return Op.getValueType().getScalarType() != MVT::f16 || 6298 ST->hasFP16Denormals(); 6299 6300 case ISD::FP_EXTEND: 6301 return Op.getOperand(0).getValueType().getScalarType() != MVT::f16 || 6302 ST->hasFP16Denormals(); 6303 6304 case ISD::FP16_TO_FP: 6305 case ISD::FP_TO_FP16: 6306 return ST->hasFP16Denormals(); 6307 6308 // It can/will be lowered or combined as a bit operation. 6309 // Need to check their input recursively to handle. 6310 case ISD::FNEG: 6311 case ISD::FABS: 6312 return (MaxDepth > 0) && 6313 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1); 6314 6315 case ISD::FSIN: 6316 case ISD::FCOS: 6317 case ISD::FSINCOS: 6318 return Op.getValueType().getScalarType() != MVT::f16; 6319 6320 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. 6321 // For such targets need to check their input recursively. 6322 case ISD::FMINNUM: 6323 case ISD::FMAXNUM: 6324 case ISD::FMINNAN: 6325 case ISD::FMAXNAN: 6326 6327 if (ST->supportsMinMaxDenormModes() && 6328 DAG.isKnownNeverNaN(Op.getOperand(0)) && 6329 DAG.isKnownNeverNaN(Op.getOperand(1))) 6330 return true; 6331 6332 return (MaxDepth > 0) && 6333 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1) && 6334 isCanonicalized(DAG, Op.getOperand(1), ST, MaxDepth - 1); 6335 6336 case ISD::ConstantFP: { 6337 auto F = cast<ConstantFPSDNode>(Op)->getValueAPF(); 6338 return !F.isDenormal() && !(F.isNaN() && F.isSignaling()); 6339 } 6340 } 6341 return false; 6342 } 6343 6344 // Constant fold canonicalize. 6345 SDValue SITargetLowering::performFCanonicalizeCombine( 6346 SDNode *N, 6347 DAGCombinerInfo &DCI) const { 6348 SelectionDAG &DAG = DCI.DAG; 6349 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0)); 6350 6351 if (!CFP) { 6352 SDValue N0 = N->getOperand(0); 6353 EVT VT = N0.getValueType().getScalarType(); 6354 auto ST = getSubtarget(); 6355 6356 if (((VT == MVT::f32 && ST->hasFP32Denormals()) || 6357 (VT == MVT::f64 && ST->hasFP64Denormals()) || 6358 (VT == MVT::f16 && ST->hasFP16Denormals())) && 6359 DAG.isKnownNeverNaN(N0)) 6360 return N0; 6361 6362 bool IsIEEEMode = Subtarget->enableIEEEBit(DAG.getMachineFunction()); 6363 6364 if ((IsIEEEMode || isKnownNeverSNan(DAG, N0)) && 6365 isCanonicalized(DAG, N0, ST)) 6366 return N0; 6367 6368 return SDValue(); 6369 } 6370 6371 const APFloat &C = CFP->getValueAPF(); 6372 6373 // Flush denormals to 0 if not enabled. 6374 if (C.isDenormal()) { 6375 EVT VT = N->getValueType(0); 6376 EVT SVT = VT.getScalarType(); 6377 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals()) 6378 return DAG.getConstantFP(0.0, SDLoc(N), VT); 6379 6380 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals()) 6381 return DAG.getConstantFP(0.0, SDLoc(N), VT); 6382 6383 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals()) 6384 return DAG.getConstantFP(0.0, SDLoc(N), VT); 6385 } 6386 6387 if (C.isNaN()) { 6388 EVT VT = N->getValueType(0); 6389 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 6390 if (C.isSignaling()) { 6391 // Quiet a signaling NaN. 6392 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 6393 } 6394 6395 // Make sure it is the canonical NaN bitpattern. 6396 // 6397 // TODO: Can we use -1 as the canonical NaN value since it's an inline 6398 // immediate? 6399 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 6400 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 6401 } 6402 6403 return N->getOperand(0); 6404 } 6405 6406 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 6407 switch (Opc) { 6408 case ISD::FMAXNUM: 6409 return AMDGPUISD::FMAX3; 6410 case ISD::SMAX: 6411 return AMDGPUISD::SMAX3; 6412 case ISD::UMAX: 6413 return AMDGPUISD::UMAX3; 6414 case ISD::FMINNUM: 6415 return AMDGPUISD::FMIN3; 6416 case ISD::SMIN: 6417 return AMDGPUISD::SMIN3; 6418 case ISD::UMIN: 6419 return AMDGPUISD::UMIN3; 6420 default: 6421 llvm_unreachable("Not a min/max opcode"); 6422 } 6423 } 6424 6425 SDValue SITargetLowering::performIntMed3ImmCombine( 6426 SelectionDAG &DAG, const SDLoc &SL, 6427 SDValue Op0, SDValue Op1, bool Signed) const { 6428 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 6429 if (!K1) 6430 return SDValue(); 6431 6432 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 6433 if (!K0) 6434 return SDValue(); 6435 6436 if (Signed) { 6437 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 6438 return SDValue(); 6439 } else { 6440 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 6441 return SDValue(); 6442 } 6443 6444 EVT VT = K0->getValueType(0); 6445 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 6446 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 6447 return DAG.getNode(Med3Opc, SL, VT, 6448 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 6449 } 6450 6451 // If there isn't a 16-bit med3 operation, convert to 32-bit. 6452 MVT NVT = MVT::i32; 6453 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6454 6455 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 6456 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 6457 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 6458 6459 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 6460 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 6461 } 6462 6463 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 6464 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 6465 return C; 6466 6467 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 6468 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 6469 return C; 6470 } 6471 6472 return nullptr; 6473 } 6474 6475 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 6476 const SDLoc &SL, 6477 SDValue Op0, 6478 SDValue Op1) const { 6479 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 6480 if (!K1) 6481 return SDValue(); 6482 6483 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 6484 if (!K0) 6485 return SDValue(); 6486 6487 // Ordered >= (although NaN inputs should have folded away by now). 6488 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 6489 if (Cmp == APFloat::cmpGreaterThan) 6490 return SDValue(); 6491 6492 // TODO: Check IEEE bit enabled? 6493 EVT VT = Op0.getValueType(); 6494 if (Subtarget->enableDX10Clamp()) { 6495 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 6496 // hardware fmed3 behavior converting to a min. 6497 // FIXME: Should this be allowing -0.0? 6498 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 6499 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 6500 } 6501 6502 // med3 for f16 is only available on gfx9+, and not available for v2f16. 6503 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 6504 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 6505 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 6506 // then give the other result, which is different from med3 with a NaN 6507 // input. 6508 SDValue Var = Op0.getOperand(0); 6509 if (!isKnownNeverSNan(DAG, Var)) 6510 return SDValue(); 6511 6512 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 6513 Var, SDValue(K0, 0), SDValue(K1, 0)); 6514 } 6515 6516 return SDValue(); 6517 } 6518 6519 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 6520 DAGCombinerInfo &DCI) const { 6521 SelectionDAG &DAG = DCI.DAG; 6522 6523 EVT VT = N->getValueType(0); 6524 unsigned Opc = N->getOpcode(); 6525 SDValue Op0 = N->getOperand(0); 6526 SDValue Op1 = N->getOperand(1); 6527 6528 // Only do this if the inner op has one use since this will just increases 6529 // register pressure for no benefit. 6530 6531 6532 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 6533 !VT.isVector() && VT != MVT::f64 && 6534 ((VT != MVT::f16 && VT != MVT::i16) || Subtarget->hasMin3Max3_16())) { 6535 // max(max(a, b), c) -> max3(a, b, c) 6536 // min(min(a, b), c) -> min3(a, b, c) 6537 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 6538 SDLoc DL(N); 6539 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 6540 DL, 6541 N->getValueType(0), 6542 Op0.getOperand(0), 6543 Op0.getOperand(1), 6544 Op1); 6545 } 6546 6547 // Try commuted. 6548 // max(a, max(b, c)) -> max3(a, b, c) 6549 // min(a, min(b, c)) -> min3(a, b, c) 6550 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 6551 SDLoc DL(N); 6552 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 6553 DL, 6554 N->getValueType(0), 6555 Op0, 6556 Op1.getOperand(0), 6557 Op1.getOperand(1)); 6558 } 6559 } 6560 6561 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 6562 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 6563 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 6564 return Med3; 6565 } 6566 6567 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 6568 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 6569 return Med3; 6570 } 6571 6572 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 6573 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 6574 (Opc == AMDGPUISD::FMIN_LEGACY && 6575 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 6576 (VT == MVT::f32 || VT == MVT::f64 || 6577 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 6578 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 6579 Op0.hasOneUse()) { 6580 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 6581 return Res; 6582 } 6583 6584 return SDValue(); 6585 } 6586 6587 static bool isClampZeroToOne(SDValue A, SDValue B) { 6588 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 6589 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 6590 // FIXME: Should this be allowing -0.0? 6591 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 6592 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 6593 } 6594 } 6595 6596 return false; 6597 } 6598 6599 // FIXME: Should only worry about snans for version with chain. 6600 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 6601 DAGCombinerInfo &DCI) const { 6602 EVT VT = N->getValueType(0); 6603 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 6604 // NaNs. With a NaN input, the order of the operands may change the result. 6605 6606 SelectionDAG &DAG = DCI.DAG; 6607 SDLoc SL(N); 6608 6609 SDValue Src0 = N->getOperand(0); 6610 SDValue Src1 = N->getOperand(1); 6611 SDValue Src2 = N->getOperand(2); 6612 6613 if (isClampZeroToOne(Src0, Src1)) { 6614 // const_a, const_b, x -> clamp is safe in all cases including signaling 6615 // nans. 6616 // FIXME: Should this be allowing -0.0? 6617 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 6618 } 6619 6620 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 6621 // handling no dx10-clamp? 6622 if (Subtarget->enableDX10Clamp()) { 6623 // If NaNs is clamped to 0, we are free to reorder the inputs. 6624 6625 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 6626 std::swap(Src0, Src1); 6627 6628 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 6629 std::swap(Src1, Src2); 6630 6631 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 6632 std::swap(Src0, Src1); 6633 6634 if (isClampZeroToOne(Src1, Src2)) 6635 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 6636 } 6637 6638 return SDValue(); 6639 } 6640 6641 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 6642 DAGCombinerInfo &DCI) const { 6643 SDValue Src0 = N->getOperand(0); 6644 SDValue Src1 = N->getOperand(1); 6645 if (Src0.isUndef() && Src1.isUndef()) 6646 return DCI.DAG.getUNDEF(N->getValueType(0)); 6647 return SDValue(); 6648 } 6649 6650 SDValue SITargetLowering::performExtractVectorEltCombine( 6651 SDNode *N, DAGCombinerInfo &DCI) const { 6652 SDValue Vec = N->getOperand(0); 6653 6654 SelectionDAG &DAG = DCI.DAG; 6655 if ((Vec.getOpcode() == ISD::FNEG || 6656 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 6657 SDLoc SL(N); 6658 EVT EltVT = N->getValueType(0); 6659 SDValue Idx = N->getOperand(1); 6660 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 6661 Vec.getOperand(0), Idx); 6662 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 6663 } 6664 6665 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 6666 // => 6667 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 6668 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 6669 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 6670 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 6671 SDLoc SL(N); 6672 EVT EltVT = N->getValueType(0); 6673 SDValue Idx = N->getOperand(1); 6674 unsigned Opc = Vec.getOpcode(); 6675 6676 switch(Opc) { 6677 default: 6678 return SDValue(); 6679 // TODO: Support other binary operations. 6680 case ISD::FADD: 6681 case ISD::ADD: 6682 case ISD::UMIN: 6683 case ISD::UMAX: 6684 case ISD::SMIN: 6685 case ISD::SMAX: 6686 case ISD::FMAXNUM: 6687 case ISD::FMINNUM: 6688 return DAG.getNode(Opc, SL, EltVT, 6689 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 6690 Vec.getOperand(0), Idx), 6691 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 6692 Vec.getOperand(1), Idx)); 6693 } 6694 } 6695 return SDValue(); 6696 } 6697 6698 static bool convertBuildVectorCastElt(SelectionDAG &DAG, 6699 SDValue &Lo, SDValue &Hi) { 6700 if (Hi.getOpcode() == ISD::BITCAST && 6701 Hi.getOperand(0).getValueType() == MVT::f16 && 6702 (isa<ConstantSDNode>(Lo) || Lo.isUndef())) { 6703 Lo = DAG.getNode(ISD::BITCAST, SDLoc(Lo), MVT::f16, Lo); 6704 Hi = Hi.getOperand(0); 6705 return true; 6706 } 6707 6708 return false; 6709 } 6710 6711 SDValue SITargetLowering::performBuildVectorCombine( 6712 SDNode *N, DAGCombinerInfo &DCI) const { 6713 SDLoc SL(N); 6714 6715 if (!isTypeLegal(MVT::v2i16)) 6716 return SDValue(); 6717 SelectionDAG &DAG = DCI.DAG; 6718 EVT VT = N->getValueType(0); 6719 6720 if (VT == MVT::v2i16) { 6721 SDValue Lo = N->getOperand(0); 6722 SDValue Hi = N->getOperand(1); 6723 6724 // v2i16 build_vector (const|undef), (bitcast f16:$x) 6725 // -> bitcast (v2f16 build_vector const|undef, $x 6726 if (convertBuildVectorCastElt(DAG, Lo, Hi)) { 6727 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Lo, Hi }); 6728 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec); 6729 } 6730 6731 if (convertBuildVectorCastElt(DAG, Hi, Lo)) { 6732 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Hi, Lo }); 6733 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec); 6734 } 6735 } 6736 6737 return SDValue(); 6738 } 6739 6740 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 6741 const SDNode *N0, 6742 const SDNode *N1) const { 6743 EVT VT = N0->getValueType(0); 6744 6745 // Only do this if we are not trying to support denormals. v_mad_f32 does not 6746 // support denormals ever. 6747 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) || 6748 (VT == MVT::f16 && !Subtarget->hasFP16Denormals())) 6749 return ISD::FMAD; 6750 6751 const TargetOptions &Options = DAG.getTarget().Options; 6752 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 6753 (N0->getFlags().hasAllowContract() && 6754 N1->getFlags().hasAllowContract())) && 6755 isFMAFasterThanFMulAndFAdd(VT)) { 6756 return ISD::FMA; 6757 } 6758 6759 return 0; 6760 } 6761 6762 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 6763 EVT VT, 6764 SDValue N0, SDValue N1, SDValue N2, 6765 bool Signed) { 6766 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 6767 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 6768 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 6769 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 6770 } 6771 6772 SDValue SITargetLowering::performAddCombine(SDNode *N, 6773 DAGCombinerInfo &DCI) const { 6774 SelectionDAG &DAG = DCI.DAG; 6775 EVT VT = N->getValueType(0); 6776 SDLoc SL(N); 6777 SDValue LHS = N->getOperand(0); 6778 SDValue RHS = N->getOperand(1); 6779 6780 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 6781 && Subtarget->hasMad64_32() && 6782 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 6783 VT.getScalarSizeInBits() <= 64) { 6784 if (LHS.getOpcode() != ISD::MUL) 6785 std::swap(LHS, RHS); 6786 6787 SDValue MulLHS = LHS.getOperand(0); 6788 SDValue MulRHS = LHS.getOperand(1); 6789 SDValue AddRHS = RHS; 6790 6791 // TODO: Maybe restrict if SGPR inputs. 6792 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 6793 numBitsUnsigned(MulRHS, DAG) <= 32) { 6794 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 6795 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 6796 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 6797 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 6798 } 6799 6800 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 6801 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 6802 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 6803 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 6804 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 6805 } 6806 6807 return SDValue(); 6808 } 6809 6810 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 6811 return SDValue(); 6812 6813 // add x, zext (setcc) => addcarry x, 0, setcc 6814 // add x, sext (setcc) => subcarry x, 0, setcc 6815 unsigned Opc = LHS.getOpcode(); 6816 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 6817 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 6818 std::swap(RHS, LHS); 6819 6820 Opc = RHS.getOpcode(); 6821 switch (Opc) { 6822 default: break; 6823 case ISD::ZERO_EXTEND: 6824 case ISD::SIGN_EXTEND: 6825 case ISD::ANY_EXTEND: { 6826 auto Cond = RHS.getOperand(0); 6827 if (!isBoolSGPR(Cond)) 6828 break; 6829 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 6830 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 6831 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 6832 return DAG.getNode(Opc, SL, VTList, Args); 6833 } 6834 case ISD::ADDCARRY: { 6835 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 6836 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 6837 if (!C || C->getZExtValue() != 0) break; 6838 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 6839 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 6840 } 6841 } 6842 return SDValue(); 6843 } 6844 6845 SDValue SITargetLowering::performSubCombine(SDNode *N, 6846 DAGCombinerInfo &DCI) const { 6847 SelectionDAG &DAG = DCI.DAG; 6848 EVT VT = N->getValueType(0); 6849 6850 if (VT != MVT::i32) 6851 return SDValue(); 6852 6853 SDLoc SL(N); 6854 SDValue LHS = N->getOperand(0); 6855 SDValue RHS = N->getOperand(1); 6856 6857 unsigned Opc = LHS.getOpcode(); 6858 if (Opc != ISD::SUBCARRY) 6859 std::swap(RHS, LHS); 6860 6861 if (LHS.getOpcode() == ISD::SUBCARRY) { 6862 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 6863 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 6864 if (!C || C->getZExtValue() != 0) 6865 return SDValue(); 6866 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 6867 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 6868 } 6869 return SDValue(); 6870 } 6871 6872 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 6873 DAGCombinerInfo &DCI) const { 6874 6875 if (N->getValueType(0) != MVT::i32) 6876 return SDValue(); 6877 6878 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6879 if (!C || C->getZExtValue() != 0) 6880 return SDValue(); 6881 6882 SelectionDAG &DAG = DCI.DAG; 6883 SDValue LHS = N->getOperand(0); 6884 6885 // addcarry (add x, y), 0, cc => addcarry x, y, cc 6886 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 6887 unsigned LHSOpc = LHS.getOpcode(); 6888 unsigned Opc = N->getOpcode(); 6889 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 6890 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 6891 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 6892 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 6893 } 6894 return SDValue(); 6895 } 6896 6897 SDValue SITargetLowering::performFAddCombine(SDNode *N, 6898 DAGCombinerInfo &DCI) const { 6899 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 6900 return SDValue(); 6901 6902 SelectionDAG &DAG = DCI.DAG; 6903 EVT VT = N->getValueType(0); 6904 6905 SDLoc SL(N); 6906 SDValue LHS = N->getOperand(0); 6907 SDValue RHS = N->getOperand(1); 6908 6909 // These should really be instruction patterns, but writing patterns with 6910 // source modiifiers is a pain. 6911 6912 // fadd (fadd (a, a), b) -> mad 2.0, a, b 6913 if (LHS.getOpcode() == ISD::FADD) { 6914 SDValue A = LHS.getOperand(0); 6915 if (A == LHS.getOperand(1)) { 6916 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 6917 if (FusedOp != 0) { 6918 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 6919 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 6920 } 6921 } 6922 } 6923 6924 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 6925 if (RHS.getOpcode() == ISD::FADD) { 6926 SDValue A = RHS.getOperand(0); 6927 if (A == RHS.getOperand(1)) { 6928 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 6929 if (FusedOp != 0) { 6930 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 6931 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 6932 } 6933 } 6934 } 6935 6936 return SDValue(); 6937 } 6938 6939 SDValue SITargetLowering::performFSubCombine(SDNode *N, 6940 DAGCombinerInfo &DCI) const { 6941 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 6942 return SDValue(); 6943 6944 SelectionDAG &DAG = DCI.DAG; 6945 SDLoc SL(N); 6946 EVT VT = N->getValueType(0); 6947 assert(!VT.isVector()); 6948 6949 // Try to get the fneg to fold into the source modifier. This undoes generic 6950 // DAG combines and folds them into the mad. 6951 // 6952 // Only do this if we are not trying to support denormals. v_mad_f32 does 6953 // not support denormals ever. 6954 SDValue LHS = N->getOperand(0); 6955 SDValue RHS = N->getOperand(1); 6956 if (LHS.getOpcode() == ISD::FADD) { 6957 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 6958 SDValue A = LHS.getOperand(0); 6959 if (A == LHS.getOperand(1)) { 6960 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 6961 if (FusedOp != 0){ 6962 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 6963 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 6964 6965 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 6966 } 6967 } 6968 } 6969 6970 if (RHS.getOpcode() == ISD::FADD) { 6971 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 6972 6973 SDValue A = RHS.getOperand(0); 6974 if (A == RHS.getOperand(1)) { 6975 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 6976 if (FusedOp != 0){ 6977 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 6978 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 6979 } 6980 } 6981 } 6982 6983 return SDValue(); 6984 } 6985 6986 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 6987 DAGCombinerInfo &DCI) const { 6988 SelectionDAG &DAG = DCI.DAG; 6989 SDLoc SL(N); 6990 6991 SDValue LHS = N->getOperand(0); 6992 SDValue RHS = N->getOperand(1); 6993 EVT VT = LHS.getValueType(); 6994 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 6995 6996 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 6997 if (!CRHS) { 6998 CRHS = dyn_cast<ConstantSDNode>(LHS); 6999 if (CRHS) { 7000 std::swap(LHS, RHS); 7001 CC = getSetCCSwappedOperands(CC); 7002 } 7003 } 7004 7005 if (CRHS && VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 7006 isBoolSGPR(LHS.getOperand(0))) { 7007 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 7008 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 7009 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 7010 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 7011 if ((CRHS->isAllOnesValue() && 7012 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 7013 (CRHS->isNullValue() && 7014 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 7015 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 7016 DAG.getConstant(-1, SL, MVT::i1)); 7017 if ((CRHS->isAllOnesValue() && 7018 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 7019 (CRHS->isNullValue() && 7020 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 7021 return LHS.getOperand(0); 7022 } 7023 7024 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 7025 VT != MVT::f16)) 7026 return SDValue(); 7027 7028 // Match isinf pattern 7029 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 7030 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) { 7031 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 7032 if (!CRHS) 7033 return SDValue(); 7034 7035 const APFloat &APF = CRHS->getValueAPF(); 7036 if (APF.isInfinity() && !APF.isNegative()) { 7037 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY; 7038 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 7039 DAG.getConstant(Mask, SL, MVT::i32)); 7040 } 7041 } 7042 7043 return SDValue(); 7044 } 7045 7046 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 7047 DAGCombinerInfo &DCI) const { 7048 SelectionDAG &DAG = DCI.DAG; 7049 SDLoc SL(N); 7050 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 7051 7052 SDValue Src = N->getOperand(0); 7053 SDValue Srl = N->getOperand(0); 7054 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 7055 Srl = Srl.getOperand(0); 7056 7057 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 7058 if (Srl.getOpcode() == ISD::SRL) { 7059 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 7060 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 7061 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 7062 7063 if (const ConstantSDNode *C = 7064 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 7065 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 7066 EVT(MVT::i32)); 7067 7068 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 7069 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 7070 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 7071 MVT::f32, Srl); 7072 } 7073 } 7074 } 7075 7076 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 7077 7078 KnownBits Known; 7079 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 7080 !DCI.isBeforeLegalizeOps()); 7081 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7082 if (TLI.ShrinkDemandedConstant(Src, Demanded, TLO) || 7083 TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) { 7084 DCI.CommitTargetLoweringOpt(TLO); 7085 } 7086 7087 return SDValue(); 7088 } 7089 7090 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 7091 DAGCombinerInfo &DCI) const { 7092 switch (N->getOpcode()) { 7093 default: 7094 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 7095 case ISD::ADD: 7096 return performAddCombine(N, DCI); 7097 case ISD::SUB: 7098 return performSubCombine(N, DCI); 7099 case ISD::ADDCARRY: 7100 case ISD::SUBCARRY: 7101 return performAddCarrySubCarryCombine(N, DCI); 7102 case ISD::FADD: 7103 return performFAddCombine(N, DCI); 7104 case ISD::FSUB: 7105 return performFSubCombine(N, DCI); 7106 case ISD::SETCC: 7107 return performSetCCCombine(N, DCI); 7108 case ISD::FMAXNUM: 7109 case ISD::FMINNUM: 7110 case ISD::SMAX: 7111 case ISD::SMIN: 7112 case ISD::UMAX: 7113 case ISD::UMIN: 7114 case AMDGPUISD::FMIN_LEGACY: 7115 case AMDGPUISD::FMAX_LEGACY: { 7116 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG && 7117 getTargetMachine().getOptLevel() > CodeGenOpt::None) 7118 return performMinMaxCombine(N, DCI); 7119 break; 7120 } 7121 case ISD::LOAD: 7122 case ISD::STORE: 7123 case ISD::ATOMIC_LOAD: 7124 case ISD::ATOMIC_STORE: 7125 case ISD::ATOMIC_CMP_SWAP: 7126 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 7127 case ISD::ATOMIC_SWAP: 7128 case ISD::ATOMIC_LOAD_ADD: 7129 case ISD::ATOMIC_LOAD_SUB: 7130 case ISD::ATOMIC_LOAD_AND: 7131 case ISD::ATOMIC_LOAD_OR: 7132 case ISD::ATOMIC_LOAD_XOR: 7133 case ISD::ATOMIC_LOAD_NAND: 7134 case ISD::ATOMIC_LOAD_MIN: 7135 case ISD::ATOMIC_LOAD_MAX: 7136 case ISD::ATOMIC_LOAD_UMIN: 7137 case ISD::ATOMIC_LOAD_UMAX: 7138 case AMDGPUISD::ATOMIC_INC: 7139 case AMDGPUISD::ATOMIC_DEC: 7140 case AMDGPUISD::ATOMIC_LOAD_FADD: 7141 case AMDGPUISD::ATOMIC_LOAD_FMIN: 7142 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 7143 if (DCI.isBeforeLegalize()) 7144 break; 7145 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 7146 case ISD::AND: 7147 return performAndCombine(N, DCI); 7148 case ISD::OR: 7149 return performOrCombine(N, DCI); 7150 case ISD::XOR: 7151 return performXorCombine(N, DCI); 7152 case ISD::ZERO_EXTEND: 7153 return performZeroExtendCombine(N, DCI); 7154 case AMDGPUISD::FP_CLASS: 7155 return performClassCombine(N, DCI); 7156 case ISD::FCANONICALIZE: 7157 return performFCanonicalizeCombine(N, DCI); 7158 case AMDGPUISD::FRACT: 7159 case AMDGPUISD::RCP: 7160 case AMDGPUISD::RSQ: 7161 case AMDGPUISD::RCP_LEGACY: 7162 case AMDGPUISD::RSQ_LEGACY: 7163 case AMDGPUISD::RSQ_CLAMP: 7164 case AMDGPUISD::LDEXP: { 7165 SDValue Src = N->getOperand(0); 7166 if (Src.isUndef()) 7167 return Src; 7168 break; 7169 } 7170 case ISD::SINT_TO_FP: 7171 case ISD::UINT_TO_FP: 7172 return performUCharToFloatCombine(N, DCI); 7173 case AMDGPUISD::CVT_F32_UBYTE0: 7174 case AMDGPUISD::CVT_F32_UBYTE1: 7175 case AMDGPUISD::CVT_F32_UBYTE2: 7176 case AMDGPUISD::CVT_F32_UBYTE3: 7177 return performCvtF32UByteNCombine(N, DCI); 7178 case AMDGPUISD::FMED3: 7179 return performFMed3Combine(N, DCI); 7180 case AMDGPUISD::CVT_PKRTZ_F16_F32: 7181 return performCvtPkRTZCombine(N, DCI); 7182 case ISD::SCALAR_TO_VECTOR: { 7183 SelectionDAG &DAG = DCI.DAG; 7184 EVT VT = N->getValueType(0); 7185 7186 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 7187 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 7188 SDLoc SL(N); 7189 SDValue Src = N->getOperand(0); 7190 EVT EltVT = Src.getValueType(); 7191 if (EltVT == MVT::f16) 7192 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 7193 7194 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 7195 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 7196 } 7197 7198 break; 7199 } 7200 case ISD::EXTRACT_VECTOR_ELT: 7201 return performExtractVectorEltCombine(N, DCI); 7202 case ISD::BUILD_VECTOR: 7203 return performBuildVectorCombine(N, DCI); 7204 } 7205 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 7206 } 7207 7208 /// Helper function for adjustWritemask 7209 static unsigned SubIdx2Lane(unsigned Idx) { 7210 switch (Idx) { 7211 default: return 0; 7212 case AMDGPU::sub0: return 0; 7213 case AMDGPU::sub1: return 1; 7214 case AMDGPU::sub2: return 2; 7215 case AMDGPU::sub3: return 3; 7216 } 7217 } 7218 7219 /// Adjust the writemask of MIMG instructions 7220 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 7221 SelectionDAG &DAG) const { 7222 SDNode *Users[4] = { nullptr }; 7223 unsigned Lane = 0; 7224 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3; 7225 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 7226 unsigned NewDmask = 0; 7227 bool HasChain = Node->getNumValues() > 1; 7228 7229 if (OldDmask == 0) { 7230 // These are folded out, but on the chance it happens don't assert. 7231 return Node; 7232 } 7233 7234 // Try to figure out the used register components 7235 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 7236 I != E; ++I) { 7237 7238 // Don't look at users of the chain. 7239 if (I.getUse().getResNo() != 0) 7240 continue; 7241 7242 // Abort if we can't understand the usage 7243 if (!I->isMachineOpcode() || 7244 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 7245 return Node; 7246 7247 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 7248 // Note that subregs are packed, i.e. Lane==0 is the first bit set 7249 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 7250 // set, etc. 7251 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 7252 7253 // Set which texture component corresponds to the lane. 7254 unsigned Comp; 7255 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) { 7256 Comp = countTrailingZeros(Dmask); 7257 Dmask &= ~(1 << Comp); 7258 } 7259 7260 // Abort if we have more than one user per component 7261 if (Users[Lane]) 7262 return Node; 7263 7264 Users[Lane] = *I; 7265 NewDmask |= 1 << Comp; 7266 } 7267 7268 // Abort if there's no change 7269 if (NewDmask == OldDmask) 7270 return Node; 7271 7272 unsigned BitsSet = countPopulation(NewDmask); 7273 7274 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 7275 int NewOpcode = AMDGPU::getMaskedMIMGOp(*TII, 7276 Node->getMachineOpcode(), BitsSet); 7277 assert(NewOpcode != -1 && 7278 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 7279 "failed to find equivalent MIMG op"); 7280 7281 // Adjust the writemask in the node 7282 SmallVector<SDValue, 12> Ops; 7283 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 7284 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 7285 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 7286 7287 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 7288 7289 MVT ResultVT = BitsSet == 1 ? 7290 SVT : MVT::getVectorVT(SVT, BitsSet == 3 ? 4 : BitsSet); 7291 SDVTList NewVTList = HasChain ? 7292 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 7293 7294 7295 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 7296 NewVTList, Ops); 7297 7298 if (HasChain) { 7299 // Update chain. 7300 NewNode->setMemRefs(Node->memoperands_begin(), Node->memoperands_end()); 7301 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 7302 } 7303 7304 if (BitsSet == 1) { 7305 assert(Node->hasNUsesOfValue(1, 0)); 7306 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 7307 SDLoc(Node), Users[Lane]->getValueType(0), 7308 SDValue(NewNode, 0)); 7309 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 7310 return nullptr; 7311 } 7312 7313 // Update the users of the node with the new indices 7314 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) { 7315 SDNode *User = Users[i]; 7316 if (!User) 7317 continue; 7318 7319 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 7320 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 7321 7322 switch (Idx) { 7323 default: break; 7324 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 7325 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 7326 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 7327 } 7328 } 7329 7330 DAG.RemoveDeadNode(Node); 7331 return nullptr; 7332 } 7333 7334 static bool isFrameIndexOp(SDValue Op) { 7335 if (Op.getOpcode() == ISD::AssertZext) 7336 Op = Op.getOperand(0); 7337 7338 return isa<FrameIndexSDNode>(Op); 7339 } 7340 7341 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 7342 /// with frame index operands. 7343 /// LLVM assumes that inputs are to these instructions are registers. 7344 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 7345 SelectionDAG &DAG) const { 7346 if (Node->getOpcode() == ISD::CopyToReg) { 7347 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 7348 SDValue SrcVal = Node->getOperand(2); 7349 7350 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 7351 // to try understanding copies to physical registers. 7352 if (SrcVal.getValueType() == MVT::i1 && 7353 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) { 7354 SDLoc SL(Node); 7355 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 7356 SDValue VReg = DAG.getRegister( 7357 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 7358 7359 SDNode *Glued = Node->getGluedNode(); 7360 SDValue ToVReg 7361 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 7362 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 7363 SDValue ToResultReg 7364 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 7365 VReg, ToVReg.getValue(1)); 7366 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 7367 DAG.RemoveDeadNode(Node); 7368 return ToResultReg.getNode(); 7369 } 7370 } 7371 7372 SmallVector<SDValue, 8> Ops; 7373 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 7374 if (!isFrameIndexOp(Node->getOperand(i))) { 7375 Ops.push_back(Node->getOperand(i)); 7376 continue; 7377 } 7378 7379 SDLoc DL(Node); 7380 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 7381 Node->getOperand(i).getValueType(), 7382 Node->getOperand(i)), 0)); 7383 } 7384 7385 return DAG.UpdateNodeOperands(Node, Ops); 7386 } 7387 7388 /// Fold the instructions after selecting them. 7389 /// Returns null if users were already updated. 7390 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 7391 SelectionDAG &DAG) const { 7392 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 7393 unsigned Opcode = Node->getMachineOpcode(); 7394 7395 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 7396 !TII->isGather4(Opcode) && !TII->isD16(Opcode)) { 7397 return adjustWritemask(Node, DAG); 7398 } 7399 7400 if (Opcode == AMDGPU::INSERT_SUBREG || 7401 Opcode == AMDGPU::REG_SEQUENCE) { 7402 legalizeTargetIndependentNode(Node, DAG); 7403 return Node; 7404 } 7405 7406 switch (Opcode) { 7407 case AMDGPU::V_DIV_SCALE_F32: 7408 case AMDGPU::V_DIV_SCALE_F64: { 7409 // Satisfy the operand register constraint when one of the inputs is 7410 // undefined. Ordinarily each undef value will have its own implicit_def of 7411 // a vreg, so force these to use a single register. 7412 SDValue Src0 = Node->getOperand(0); 7413 SDValue Src1 = Node->getOperand(1); 7414 SDValue Src2 = Node->getOperand(2); 7415 7416 if ((Src0.isMachineOpcode() && 7417 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 7418 (Src0 == Src1 || Src0 == Src2)) 7419 break; 7420 7421 MVT VT = Src0.getValueType().getSimpleVT(); 7422 const TargetRegisterClass *RC = getRegClassFor(VT); 7423 7424 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 7425 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 7426 7427 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 7428 UndefReg, Src0, SDValue()); 7429 7430 // src0 must be the same register as src1 or src2, even if the value is 7431 // undefined, so make sure we don't violate this constraint. 7432 if (Src0.isMachineOpcode() && 7433 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 7434 if (Src1.isMachineOpcode() && 7435 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 7436 Src0 = Src1; 7437 else if (Src2.isMachineOpcode() && 7438 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 7439 Src0 = Src2; 7440 else { 7441 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 7442 Src0 = UndefReg; 7443 Src1 = UndefReg; 7444 } 7445 } else 7446 break; 7447 7448 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 7449 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 7450 Ops.push_back(Node->getOperand(I)); 7451 7452 Ops.push_back(ImpDef.getValue(1)); 7453 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 7454 } 7455 default: 7456 break; 7457 } 7458 7459 return Node; 7460 } 7461 7462 /// Assign the register class depending on the number of 7463 /// bits set in the writemask 7464 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 7465 SDNode *Node) const { 7466 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 7467 7468 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 7469 7470 if (TII->isVOP3(MI.getOpcode())) { 7471 // Make sure constant bus requirements are respected. 7472 TII->legalizeOperandsVOP3(MRI, MI); 7473 return; 7474 } 7475 7476 // Replace unused atomics with the no return version. 7477 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 7478 if (NoRetAtomicOp != -1) { 7479 if (!Node->hasAnyUseOfValue(0)) { 7480 MI.setDesc(TII->get(NoRetAtomicOp)); 7481 MI.RemoveOperand(0); 7482 return; 7483 } 7484 7485 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 7486 // instruction, because the return type of these instructions is a vec2 of 7487 // the memory type, so it can be tied to the input operand. 7488 // This means these instructions always have a use, so we need to add a 7489 // special case to check if the atomic has only one extract_subreg use, 7490 // which itself has no uses. 7491 if ((Node->hasNUsesOfValue(1, 0) && 7492 Node->use_begin()->isMachineOpcode() && 7493 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 7494 !Node->use_begin()->hasAnyUseOfValue(0))) { 7495 unsigned Def = MI.getOperand(0).getReg(); 7496 7497 // Change this into a noret atomic. 7498 MI.setDesc(TII->get(NoRetAtomicOp)); 7499 MI.RemoveOperand(0); 7500 7501 // If we only remove the def operand from the atomic instruction, the 7502 // extract_subreg will be left with a use of a vreg without a def. 7503 // So we need to insert an implicit_def to avoid machine verifier 7504 // errors. 7505 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 7506 TII->get(AMDGPU::IMPLICIT_DEF), Def); 7507 } 7508 return; 7509 } 7510 } 7511 7512 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 7513 uint64_t Val) { 7514 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 7515 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 7516 } 7517 7518 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 7519 const SDLoc &DL, 7520 SDValue Ptr) const { 7521 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 7522 7523 // Build the half of the subregister with the constants before building the 7524 // full 128-bit register. If we are building multiple resource descriptors, 7525 // this will allow CSEing of the 2-component register. 7526 const SDValue Ops0[] = { 7527 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 7528 buildSMovImm32(DAG, DL, 0), 7529 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 7530 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 7531 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 7532 }; 7533 7534 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 7535 MVT::v2i32, Ops0), 0); 7536 7537 // Combine the constants and the pointer. 7538 const SDValue Ops1[] = { 7539 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 7540 Ptr, 7541 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 7542 SubRegHi, 7543 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 7544 }; 7545 7546 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 7547 } 7548 7549 /// Return a resource descriptor with the 'Add TID' bit enabled 7550 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 7551 /// of the resource descriptor) to create an offset, which is added to 7552 /// the resource pointer. 7553 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 7554 SDValue Ptr, uint32_t RsrcDword1, 7555 uint64_t RsrcDword2And3) const { 7556 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 7557 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 7558 if (RsrcDword1) { 7559 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 7560 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 7561 0); 7562 } 7563 7564 SDValue DataLo = buildSMovImm32(DAG, DL, 7565 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 7566 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 7567 7568 const SDValue Ops[] = { 7569 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 7570 PtrLo, 7571 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 7572 PtrHi, 7573 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 7574 DataLo, 7575 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 7576 DataHi, 7577 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 7578 }; 7579 7580 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 7581 } 7582 7583 //===----------------------------------------------------------------------===// 7584 // SI Inline Assembly Support 7585 //===----------------------------------------------------------------------===// 7586 7587 std::pair<unsigned, const TargetRegisterClass *> 7588 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 7589 StringRef Constraint, 7590 MVT VT) const { 7591 if (!isTypeLegal(VT)) 7592 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 7593 7594 if (Constraint.size() == 1) { 7595 switch (Constraint[0]) { 7596 case 's': 7597 case 'r': 7598 switch (VT.getSizeInBits()) { 7599 default: 7600 return std::make_pair(0U, nullptr); 7601 case 32: 7602 case 16: 7603 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass); 7604 case 64: 7605 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass); 7606 case 128: 7607 return std::make_pair(0U, &AMDGPU::SReg_128RegClass); 7608 case 256: 7609 return std::make_pair(0U, &AMDGPU::SReg_256RegClass); 7610 case 512: 7611 return std::make_pair(0U, &AMDGPU::SReg_512RegClass); 7612 } 7613 7614 case 'v': 7615 switch (VT.getSizeInBits()) { 7616 default: 7617 return std::make_pair(0U, nullptr); 7618 case 32: 7619 case 16: 7620 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass); 7621 case 64: 7622 return std::make_pair(0U, &AMDGPU::VReg_64RegClass); 7623 case 96: 7624 return std::make_pair(0U, &AMDGPU::VReg_96RegClass); 7625 case 128: 7626 return std::make_pair(0U, &AMDGPU::VReg_128RegClass); 7627 case 256: 7628 return std::make_pair(0U, &AMDGPU::VReg_256RegClass); 7629 case 512: 7630 return std::make_pair(0U, &AMDGPU::VReg_512RegClass); 7631 } 7632 } 7633 } 7634 7635 if (Constraint.size() > 1) { 7636 const TargetRegisterClass *RC = nullptr; 7637 if (Constraint[1] == 'v') { 7638 RC = &AMDGPU::VGPR_32RegClass; 7639 } else if (Constraint[1] == 's') { 7640 RC = &AMDGPU::SGPR_32RegClass; 7641 } 7642 7643 if (RC) { 7644 uint32_t Idx; 7645 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 7646 if (!Failed && Idx < RC->getNumRegs()) 7647 return std::make_pair(RC->getRegister(Idx), RC); 7648 } 7649 } 7650 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 7651 } 7652 7653 SITargetLowering::ConstraintType 7654 SITargetLowering::getConstraintType(StringRef Constraint) const { 7655 if (Constraint.size() == 1) { 7656 switch (Constraint[0]) { 7657 default: break; 7658 case 's': 7659 case 'v': 7660 return C_RegisterClass; 7661 } 7662 } 7663 return TargetLowering::getConstraintType(Constraint); 7664 } 7665 7666 // Figure out which registers should be reserved for stack access. Only after 7667 // the function is legalized do we know all of the non-spill stack objects or if 7668 // calls are present. 7669 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 7670 MachineRegisterInfo &MRI = MF.getRegInfo(); 7671 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 7672 const MachineFrameInfo &MFI = MF.getFrameInfo(); 7673 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 7674 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 7675 7676 if (Info->isEntryFunction()) { 7677 // Callable functions have fixed registers used for stack access. 7678 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 7679 } 7680 7681 // We have to assume the SP is needed in case there are calls in the function 7682 // during lowering. Calls are only detected after the function is 7683 // lowered. We're about to reserve registers, so don't bother using it if we 7684 // aren't really going to use it. 7685 bool NeedSP = !Info->isEntryFunction() || 7686 MFI.hasVarSizedObjects() || 7687 MFI.hasCalls(); 7688 7689 if (NeedSP) { 7690 unsigned ReservedStackPtrOffsetReg = TRI->reservedStackPtrOffsetReg(MF); 7691 Info->setStackPtrOffsetReg(ReservedStackPtrOffsetReg); 7692 7693 assert(Info->getStackPtrOffsetReg() != Info->getFrameOffsetReg()); 7694 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 7695 Info->getStackPtrOffsetReg())); 7696 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 7697 } 7698 7699 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 7700 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 7701 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG, 7702 Info->getScratchWaveOffsetReg()); 7703 7704 TargetLoweringBase::finalizeLowering(MF); 7705 } 7706 7707 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 7708 KnownBits &Known, 7709 const APInt &DemandedElts, 7710 const SelectionDAG &DAG, 7711 unsigned Depth) const { 7712 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 7713 DAG, Depth); 7714 7715 if (getSubtarget()->enableHugePrivateBuffer()) 7716 return; 7717 7718 // Technically it may be possible to have a dispatch with a single workitem 7719 // that uses the full private memory size, but that's not really useful. We 7720 // can't use vaddr in MUBUF instructions if we don't know the address 7721 // calculation won't overflow, so assume the sign bit is never set. 7722 Known.Zero.setHighBits(AssumeFrameIndexHighZeroBits); 7723 } 7724