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 /// \brief 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 "Utils/AMDGPUBaseInfo.h" 30 #include "llvm/ADT/APFloat.h" 31 #include "llvm/ADT/APInt.h" 32 #include "llvm/ADT/ArrayRef.h" 33 #include "llvm/ADT/BitVector.h" 34 #include "llvm/ADT/SmallVector.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/ADT/Twine.h" 38 #include "llvm/CodeGen/Analysis.h" 39 #include "llvm/CodeGen/CallingConvLower.h" 40 #include "llvm/CodeGen/DAGCombine.h" 41 #include "llvm/CodeGen/ISDOpcodes.h" 42 #include "llvm/CodeGen/MachineBasicBlock.h" 43 #include "llvm/CodeGen/MachineFrameInfo.h" 44 #include "llvm/CodeGen/MachineFunction.h" 45 #include "llvm/CodeGen/MachineInstr.h" 46 #include "llvm/CodeGen/MachineInstrBuilder.h" 47 #include "llvm/CodeGen/MachineMemOperand.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/MachineValueType.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGNodes.h" 53 #include "llvm/CodeGen/ValueTypes.h" 54 #include "llvm/IR/Constants.h" 55 #include "llvm/IR/DataLayout.h" 56 #include "llvm/IR/DebugLoc.h" 57 #include "llvm/IR/DerivedTypes.h" 58 #include "llvm/IR/DiagnosticInfo.h" 59 #include "llvm/IR/Function.h" 60 #include "llvm/IR/GlobalValue.h" 61 #include "llvm/IR/InstrTypes.h" 62 #include "llvm/IR/Instruction.h" 63 #include "llvm/IR/Instructions.h" 64 #include "llvm/IR/IntrinsicInst.h" 65 #include "llvm/IR/Type.h" 66 #include "llvm/Support/Casting.h" 67 #include "llvm/Support/CodeGen.h" 68 #include "llvm/Support/CommandLine.h" 69 #include "llvm/Support/Compiler.h" 70 #include "llvm/Support/ErrorHandling.h" 71 #include "llvm/Support/KnownBits.h" 72 #include "llvm/Support/MathExtras.h" 73 #include "llvm/Target/TargetCallingConv.h" 74 #include "llvm/Target/TargetOptions.h" 75 #include "llvm/Target/TargetRegisterInfo.h" 76 #include <cassert> 77 #include <cmath> 78 #include <cstdint> 79 #include <iterator> 80 #include <tuple> 81 #include <utility> 82 #include <vector> 83 84 using namespace llvm; 85 86 static cl::opt<bool> EnableVGPRIndexMode( 87 "amdgpu-vgpr-index-mode", 88 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"), 89 cl::init(false)); 90 91 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 92 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 93 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 94 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 95 return AMDGPU::SGPR0 + Reg; 96 } 97 } 98 llvm_unreachable("Cannot allocate sgpr"); 99 } 100 101 SITargetLowering::SITargetLowering(const TargetMachine &TM, 102 const SISubtarget &STI) 103 : AMDGPUTargetLowering(TM, STI) { 104 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 105 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 106 107 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass); 108 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 109 110 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 111 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 112 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 113 114 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass); 115 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass); 116 117 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass); 118 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 119 120 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass); 121 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 122 123 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass); 124 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 125 126 if (Subtarget->has16BitInsts()) { 127 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass); 128 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass); 129 } 130 131 if (Subtarget->hasVOP3PInsts()) { 132 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass); 133 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass); 134 } 135 136 computeRegisterProperties(STI.getRegisterInfo()); 137 138 // We need to custom lower vector stores from local memory 139 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 140 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 141 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 142 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 143 setOperationAction(ISD::LOAD, MVT::i1, Custom); 144 145 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 146 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 147 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 148 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 149 setOperationAction(ISD::STORE, MVT::i1, Custom); 150 151 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 152 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 153 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 154 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 155 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 156 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 157 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 158 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 159 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 160 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 161 162 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 163 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 164 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand); 165 166 setOperationAction(ISD::SELECT, MVT::i1, Promote); 167 setOperationAction(ISD::SELECT, MVT::i64, Custom); 168 setOperationAction(ISD::SELECT, MVT::f64, Promote); 169 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 170 171 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 172 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 173 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 174 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 175 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 176 177 setOperationAction(ISD::SETCC, MVT::i1, Promote); 178 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 179 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 180 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 181 182 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 183 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 184 185 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 186 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 187 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 188 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 189 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 190 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 191 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 192 193 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 194 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 195 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 196 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 197 198 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 199 200 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 201 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 202 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 203 204 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 205 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 206 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 207 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 208 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 209 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 210 211 setOperationAction(ISD::UADDO, MVT::i32, Legal); 212 setOperationAction(ISD::USUBO, MVT::i32, Legal); 213 214 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 215 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 216 217 // We only support LOAD/STORE and vector manipulation ops for vectors 218 // with > 4 elements. 219 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 220 MVT::v2i64, MVT::v2f64}) { 221 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 222 switch (Op) { 223 case ISD::LOAD: 224 case ISD::STORE: 225 case ISD::BUILD_VECTOR: 226 case ISD::BITCAST: 227 case ISD::EXTRACT_VECTOR_ELT: 228 case ISD::INSERT_VECTOR_ELT: 229 case ISD::INSERT_SUBVECTOR: 230 case ISD::EXTRACT_SUBVECTOR: 231 case ISD::SCALAR_TO_VECTOR: 232 break; 233 case ISD::CONCAT_VECTORS: 234 setOperationAction(Op, VT, Custom); 235 break; 236 default: 237 setOperationAction(Op, VT, Expand); 238 break; 239 } 240 } 241 } 242 243 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 244 // is expanded to avoid having two separate loops in case the index is a VGPR. 245 246 // Most operations are naturally 32-bit vector operations. We only support 247 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 248 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 249 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 250 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 251 252 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 253 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 254 255 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 256 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 257 258 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 259 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 260 } 261 262 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 263 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 264 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 265 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 266 267 // Avoid stack access for these. 268 // TODO: Generalize to more vector types. 269 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 270 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 271 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 272 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 273 274 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 275 // and output demarshalling 276 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 277 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 278 279 // We can't return success/failure, only the old value, 280 // let LLVM add the comparison 281 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 282 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 283 284 if (getSubtarget()->hasFlatAddressSpace()) { 285 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 286 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 287 } 288 289 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 290 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 291 292 // On SI this is s_memtime and s_memrealtime on VI. 293 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 294 setOperationAction(ISD::TRAP, MVT::Other, Custom); 295 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 296 297 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 298 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 299 300 if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) { 301 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 302 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 303 setOperationAction(ISD::FRINT, MVT::f64, Legal); 304 } 305 306 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 307 308 setOperationAction(ISD::FSIN, MVT::f32, Custom); 309 setOperationAction(ISD::FCOS, MVT::f32, Custom); 310 setOperationAction(ISD::FDIV, MVT::f32, Custom); 311 setOperationAction(ISD::FDIV, MVT::f64, Custom); 312 313 if (Subtarget->has16BitInsts()) { 314 setOperationAction(ISD::Constant, MVT::i16, Legal); 315 316 setOperationAction(ISD::SMIN, MVT::i16, Legal); 317 setOperationAction(ISD::SMAX, MVT::i16, Legal); 318 319 setOperationAction(ISD::UMIN, MVT::i16, Legal); 320 setOperationAction(ISD::UMAX, MVT::i16, Legal); 321 322 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 323 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 324 325 setOperationAction(ISD::ROTR, MVT::i16, Promote); 326 setOperationAction(ISD::ROTL, MVT::i16, Promote); 327 328 setOperationAction(ISD::SDIV, MVT::i16, Promote); 329 setOperationAction(ISD::UDIV, MVT::i16, Promote); 330 setOperationAction(ISD::SREM, MVT::i16, Promote); 331 setOperationAction(ISD::UREM, MVT::i16, Promote); 332 333 setOperationAction(ISD::BSWAP, MVT::i16, Promote); 334 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 335 336 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 337 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 338 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 339 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 340 341 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 342 343 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 344 345 setOperationAction(ISD::LOAD, MVT::i16, Custom); 346 347 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 348 349 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 350 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 351 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 352 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 353 354 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 355 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 356 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote); 357 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote); 358 359 // F16 - Constant Actions. 360 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 361 362 // F16 - Load/Store Actions. 363 setOperationAction(ISD::LOAD, MVT::f16, Promote); 364 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 365 setOperationAction(ISD::STORE, MVT::f16, Promote); 366 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 367 368 // F16 - VOP1 Actions. 369 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 370 setOperationAction(ISD::FCOS, MVT::f16, Promote); 371 setOperationAction(ISD::FSIN, MVT::f16, Promote); 372 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 373 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 374 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 375 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 376 setOperationAction(ISD::FROUND, MVT::f16, Custom); 377 378 // F16 - VOP2 Actions. 379 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 380 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 381 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 382 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 383 setOperationAction(ISD::FDIV, MVT::f16, Custom); 384 385 // F16 - VOP3 Actions. 386 setOperationAction(ISD::FMA, MVT::f16, Legal); 387 if (!Subtarget->hasFP16Denormals()) 388 setOperationAction(ISD::FMAD, MVT::f16, Legal); 389 } 390 391 if (Subtarget->hasVOP3PInsts()) { 392 for (MVT VT : {MVT::v2i16, MVT::v2f16}) { 393 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 394 switch (Op) { 395 case ISD::LOAD: 396 case ISD::STORE: 397 case ISD::BUILD_VECTOR: 398 case ISD::BITCAST: 399 case ISD::EXTRACT_VECTOR_ELT: 400 case ISD::INSERT_VECTOR_ELT: 401 case ISD::INSERT_SUBVECTOR: 402 case ISD::EXTRACT_SUBVECTOR: 403 case ISD::SCALAR_TO_VECTOR: 404 break; 405 case ISD::CONCAT_VECTORS: 406 setOperationAction(Op, VT, Custom); 407 break; 408 default: 409 setOperationAction(Op, VT, Expand); 410 break; 411 } 412 } 413 } 414 415 // XXX - Do these do anything? Vector constants turn into build_vector. 416 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 417 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 418 419 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 420 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 421 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 422 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 423 424 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 425 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 426 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 427 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 428 429 setOperationAction(ISD::AND, MVT::v2i16, Promote); 430 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 431 setOperationAction(ISD::OR, MVT::v2i16, Promote); 432 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 433 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 434 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 435 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 436 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 437 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 438 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 439 440 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 441 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 442 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 443 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 444 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 445 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 446 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 447 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 448 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 449 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 450 451 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 452 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 453 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 454 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 455 setOperationAction(ISD::FMINNUM, MVT::v2f16, Legal); 456 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Legal); 457 458 // This isn't really legal, but this avoids the legalizer unrolling it (and 459 // allows matching fneg (fabs x) patterns) 460 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 461 462 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 463 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 464 465 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 466 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 467 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 468 } else { 469 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 470 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 471 } 472 473 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 474 setOperationAction(ISD::SELECT, VT, Custom); 475 } 476 477 setTargetDAGCombine(ISD::ADD); 478 setTargetDAGCombine(ISD::ADDCARRY); 479 setTargetDAGCombine(ISD::SUB); 480 setTargetDAGCombine(ISD::SUBCARRY); 481 setTargetDAGCombine(ISD::FADD); 482 setTargetDAGCombine(ISD::FSUB); 483 setTargetDAGCombine(ISD::FMINNUM); 484 setTargetDAGCombine(ISD::FMAXNUM); 485 setTargetDAGCombine(ISD::SMIN); 486 setTargetDAGCombine(ISD::SMAX); 487 setTargetDAGCombine(ISD::UMIN); 488 setTargetDAGCombine(ISD::UMAX); 489 setTargetDAGCombine(ISD::SETCC); 490 setTargetDAGCombine(ISD::AND); 491 setTargetDAGCombine(ISD::OR); 492 setTargetDAGCombine(ISD::XOR); 493 setTargetDAGCombine(ISD::SINT_TO_FP); 494 setTargetDAGCombine(ISD::UINT_TO_FP); 495 setTargetDAGCombine(ISD::FCANONICALIZE); 496 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 497 setTargetDAGCombine(ISD::ZERO_EXTEND); 498 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 499 500 // All memory operations. Some folding on the pointer operand is done to help 501 // matching the constant offsets in the addressing modes. 502 setTargetDAGCombine(ISD::LOAD); 503 setTargetDAGCombine(ISD::STORE); 504 setTargetDAGCombine(ISD::ATOMIC_LOAD); 505 setTargetDAGCombine(ISD::ATOMIC_STORE); 506 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 507 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 508 setTargetDAGCombine(ISD::ATOMIC_SWAP); 509 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 510 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 511 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 512 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 513 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 514 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 515 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 516 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 517 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 518 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 519 520 setSchedulingPreference(Sched::RegPressure); 521 } 522 523 const SISubtarget *SITargetLowering::getSubtarget() const { 524 return static_cast<const SISubtarget *>(Subtarget); 525 } 526 527 //===----------------------------------------------------------------------===// 528 // TargetLowering queries 529 //===----------------------------------------------------------------------===// 530 531 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &, 532 EVT) const { 533 // SI has some legal vector types, but no legal vector operations. Say no 534 // shuffles are legal in order to prefer scalarizing some vector operations. 535 return false; 536 } 537 538 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 539 const CallInst &CI, 540 unsigned IntrID) const { 541 switch (IntrID) { 542 case Intrinsic::amdgcn_atomic_inc: 543 case Intrinsic::amdgcn_atomic_dec: { 544 Info.opc = ISD::INTRINSIC_W_CHAIN; 545 Info.memVT = MVT::getVT(CI.getType()); 546 Info.ptrVal = CI.getOperand(0); 547 Info.align = 0; 548 549 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 550 Info.vol = !Vol || !Vol->isZero(); 551 Info.readMem = true; 552 Info.writeMem = true; 553 return true; 554 } 555 default: 556 return false; 557 } 558 } 559 560 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 561 SmallVectorImpl<Value*> &Ops, 562 Type *&AccessTy) const { 563 switch (II->getIntrinsicID()) { 564 case Intrinsic::amdgcn_atomic_inc: 565 case Intrinsic::amdgcn_atomic_dec: { 566 Value *Ptr = II->getArgOperand(0); 567 AccessTy = II->getType(); 568 Ops.push_back(Ptr); 569 return true; 570 } 571 default: 572 return false; 573 } 574 } 575 576 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 577 if (!Subtarget->hasFlatInstOffsets()) { 578 // Flat instructions do not have offsets, and only have the register 579 // address. 580 return AM.BaseOffs == 0 && AM.Scale == 0; 581 } 582 583 // GFX9 added a 13-bit signed offset. When using regular flat instructions, 584 // the sign bit is ignored and is treated as a 12-bit unsigned offset. 585 586 // Just r + i 587 return isUInt<12>(AM.BaseOffs) && AM.Scale == 0; 588 } 589 590 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 591 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 592 // additionally can do r + r + i with addr64. 32-bit has more addressing 593 // mode options. Depending on the resource constant, it can also do 594 // (i64 r0) + (i32 r1) * (i14 i). 595 // 596 // Private arrays end up using a scratch buffer most of the time, so also 597 // assume those use MUBUF instructions. Scratch loads / stores are currently 598 // implemented as mubuf instructions with offen bit set, so slightly 599 // different than the normal addr64. 600 if (!isUInt<12>(AM.BaseOffs)) 601 return false; 602 603 // FIXME: Since we can split immediate into soffset and immediate offset, 604 // would it make sense to allow any immediate? 605 606 switch (AM.Scale) { 607 case 0: // r + i or just i, depending on HasBaseReg. 608 return true; 609 case 1: 610 return true; // We have r + r or r + i. 611 case 2: 612 if (AM.HasBaseReg) { 613 // Reject 2 * r + r. 614 return false; 615 } 616 617 // Allow 2 * r as r + r 618 // Or 2 * r + i is allowed as r + r + i. 619 return true; 620 default: // Don't allow n * r 621 return false; 622 } 623 } 624 625 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 626 const AddrMode &AM, Type *Ty, 627 unsigned AS) const { 628 // No global is ever allowed as a base. 629 if (AM.BaseGV) 630 return false; 631 632 if (AS == AMDGPUASI.GLOBAL_ADDRESS) { 633 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) { 634 // Assume the we will use FLAT for all global memory accesses 635 // on VI. 636 // FIXME: This assumption is currently wrong. On VI we still use 637 // MUBUF instructions for the r + i addressing mode. As currently 638 // implemented, the MUBUF instructions only work on buffer < 4GB. 639 // It may be possible to support > 4GB buffers with MUBUF instructions, 640 // by setting the stride value in the resource descriptor which would 641 // increase the size limit to (stride * 4GB). However, this is risky, 642 // because it has never been validated. 643 return isLegalFlatAddressingMode(AM); 644 } 645 646 return isLegalMUBUFAddressingMode(AM); 647 } else if (AS == AMDGPUASI.CONSTANT_ADDRESS) { 648 // If the offset isn't a multiple of 4, it probably isn't going to be 649 // correctly aligned. 650 // FIXME: Can we get the real alignment here? 651 if (AM.BaseOffs % 4 != 0) 652 return isLegalMUBUFAddressingMode(AM); 653 654 // There are no SMRD extloads, so if we have to do a small type access we 655 // will use a MUBUF load. 656 // FIXME?: We also need to do this if unaligned, but we don't know the 657 // alignment here. 658 if (DL.getTypeStoreSize(Ty) < 4) 659 return isLegalMUBUFAddressingMode(AM); 660 661 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) { 662 // SMRD instructions have an 8-bit, dword offset on SI. 663 if (!isUInt<8>(AM.BaseOffs / 4)) 664 return false; 665 } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) { 666 // On CI+, this can also be a 32-bit literal constant offset. If it fits 667 // in 8-bits, it can use a smaller encoding. 668 if (!isUInt<32>(AM.BaseOffs / 4)) 669 return false; 670 } else if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) { 671 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 672 if (!isUInt<20>(AM.BaseOffs)) 673 return false; 674 } else 675 llvm_unreachable("unhandled generation"); 676 677 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 678 return true; 679 680 if (AM.Scale == 1 && AM.HasBaseReg) 681 return true; 682 683 return false; 684 685 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 686 return isLegalMUBUFAddressingMode(AM); 687 } else if (AS == AMDGPUASI.LOCAL_ADDRESS || 688 AS == AMDGPUASI.REGION_ADDRESS) { 689 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 690 // field. 691 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 692 // an 8-bit dword offset but we don't know the alignment here. 693 if (!isUInt<16>(AM.BaseOffs)) 694 return false; 695 696 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 697 return true; 698 699 if (AM.Scale == 1 && AM.HasBaseReg) 700 return true; 701 702 return false; 703 } else if (AS == AMDGPUASI.FLAT_ADDRESS || 704 AS == AMDGPUASI.UNKNOWN_ADDRESS_SPACE) { 705 // For an unknown address space, this usually means that this is for some 706 // reason being used for pure arithmetic, and not based on some addressing 707 // computation. We don't have instructions that compute pointers with any 708 // addressing modes, so treat them as having no offset like flat 709 // instructions. 710 return isLegalFlatAddressingMode(AM); 711 } else { 712 llvm_unreachable("unhandled address space"); 713 } 714 } 715 716 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT) const { 717 if (AS == AMDGPUASI.GLOBAL_ADDRESS || AS == AMDGPUASI.FLAT_ADDRESS) { 718 return (MemVT.getSizeInBits() <= 4 * 32); 719 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 720 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 721 return (MemVT.getSizeInBits() <= MaxPrivateBits); 722 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 723 return (MemVT.getSizeInBits() <= 2 * 32); 724 } 725 return true; 726 } 727 728 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 729 unsigned AddrSpace, 730 unsigned Align, 731 bool *IsFast) const { 732 if (IsFast) 733 *IsFast = false; 734 735 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 736 // which isn't a simple VT. 737 // Until MVT is extended to handle this, simply check for the size and 738 // rely on the condition below: allow accesses if the size is a multiple of 4. 739 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 740 VT.getStoreSize() > 16)) { 741 return false; 742 } 743 744 if (AddrSpace == AMDGPUASI.LOCAL_ADDRESS || 745 AddrSpace == AMDGPUASI.REGION_ADDRESS) { 746 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 747 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 748 // with adjacent offsets. 749 bool AlignedBy4 = (Align % 4 == 0); 750 if (IsFast) 751 *IsFast = AlignedBy4; 752 753 return AlignedBy4; 754 } 755 756 // FIXME: We have to be conservative here and assume that flat operations 757 // will access scratch. If we had access to the IR function, then we 758 // could determine if any private memory was used in the function. 759 if (!Subtarget->hasUnalignedScratchAccess() && 760 (AddrSpace == AMDGPUASI.PRIVATE_ADDRESS || 761 AddrSpace == AMDGPUASI.FLAT_ADDRESS)) { 762 return false; 763 } 764 765 if (Subtarget->hasUnalignedBufferAccess()) { 766 // If we have an uniform constant load, it still requires using a slow 767 // buffer instruction if unaligned. 768 if (IsFast) { 769 *IsFast = (AddrSpace == AMDGPUASI.CONSTANT_ADDRESS) ? 770 (Align % 4 == 0) : true; 771 } 772 773 return true; 774 } 775 776 // Smaller than dword value must be aligned. 777 if (VT.bitsLT(MVT::i32)) 778 return false; 779 780 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 781 // byte-address are ignored, thus forcing Dword alignment. 782 // This applies to private, global, and constant memory. 783 if (IsFast) 784 *IsFast = true; 785 786 return VT.bitsGT(MVT::i32) && Align % 4 == 0; 787 } 788 789 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign, 790 unsigned SrcAlign, bool IsMemset, 791 bool ZeroMemset, 792 bool MemcpyStrSrc, 793 MachineFunction &MF) const { 794 // FIXME: Should account for address space here. 795 796 // The default fallback uses the private pointer size as a guess for a type to 797 // use. Make sure we switch these to 64-bit accesses. 798 799 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global 800 return MVT::v4i32; 801 802 if (Size >= 8 && DstAlign >= 4) 803 return MVT::v2i32; 804 805 // Use the default. 806 return MVT::Other; 807 } 808 809 static bool isFlatGlobalAddrSpace(unsigned AS, AMDGPUAS AMDGPUASI) { 810 return AS == AMDGPUASI.GLOBAL_ADDRESS || 811 AS == AMDGPUASI.FLAT_ADDRESS || 812 AS == AMDGPUASI.CONSTANT_ADDRESS; 813 } 814 815 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 816 unsigned DestAS) const { 817 return isFlatGlobalAddrSpace(SrcAS, AMDGPUASI) && 818 isFlatGlobalAddrSpace(DestAS, AMDGPUASI); 819 } 820 821 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 822 const MemSDNode *MemNode = cast<MemSDNode>(N); 823 const Value *Ptr = MemNode->getMemOperand()->getValue(); 824 const Instruction *I = dyn_cast<Instruction>(Ptr); 825 return I && I->getMetadata("amdgpu.noclobber"); 826 } 827 828 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS, 829 unsigned DestAS) const { 830 // Flat -> private/local is a simple truncate. 831 // Flat -> global is no-op 832 if (SrcAS == AMDGPUASI.FLAT_ADDRESS) 833 return true; 834 835 return isNoopAddrSpaceCast(SrcAS, DestAS); 836 } 837 838 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 839 const MemSDNode *MemNode = cast<MemSDNode>(N); 840 841 return AMDGPU::isUniformMMO(MemNode->getMemOperand()); 842 } 843 844 TargetLoweringBase::LegalizeTypeAction 845 SITargetLowering::getPreferredVectorAction(EVT VT) const { 846 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16)) 847 return TypeSplitVector; 848 849 return TargetLoweringBase::getPreferredVectorAction(VT); 850 } 851 852 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 853 Type *Ty) const { 854 // FIXME: Could be smarter if called for vector constants. 855 return true; 856 } 857 858 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 859 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 860 switch (Op) { 861 case ISD::LOAD: 862 case ISD::STORE: 863 864 // These operations are done with 32-bit instructions anyway. 865 case ISD::AND: 866 case ISD::OR: 867 case ISD::XOR: 868 case ISD::SELECT: 869 // TODO: Extensions? 870 return true; 871 default: 872 return false; 873 } 874 } 875 876 // SimplifySetCC uses this function to determine whether or not it should 877 // create setcc with i1 operands. We don't have instructions for i1 setcc. 878 if (VT == MVT::i1 && Op == ISD::SETCC) 879 return false; 880 881 return TargetLowering::isTypeDesirableForOp(Op, VT); 882 } 883 884 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 885 const SDLoc &SL, 886 SDValue Chain, 887 uint64_t Offset) const { 888 const DataLayout &DL = DAG.getDataLayout(); 889 MachineFunction &MF = DAG.getMachineFunction(); 890 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 891 unsigned InputPtrReg = TRI->getPreloadedValue(MF, 892 SIRegisterInfo::KERNARG_SEGMENT_PTR); 893 894 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 895 MVT PtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS); 896 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 897 MRI.getLiveInVirtReg(InputPtrReg), PtrVT); 898 return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr, 899 DAG.getConstant(Offset, SL, PtrVT)); 900 } 901 902 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 903 const SDLoc &SL, SDValue Val, 904 bool Signed, 905 const ISD::InputArg *Arg) const { 906 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 907 VT.bitsLT(MemVT)) { 908 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 909 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 910 } 911 912 if (MemVT.isFloatingPoint()) 913 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT); 914 else if (Signed) 915 Val = DAG.getSExtOrTrunc(Val, SL, VT); 916 else 917 Val = DAG.getZExtOrTrunc(Val, SL, VT); 918 919 return Val; 920 } 921 922 SDValue SITargetLowering::lowerKernargMemParameter( 923 SelectionDAG &DAG, EVT VT, EVT MemVT, 924 const SDLoc &SL, SDValue Chain, 925 uint64_t Offset, bool Signed, 926 const ISD::InputArg *Arg) const { 927 const DataLayout &DL = DAG.getDataLayout(); 928 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 929 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS); 930 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 931 932 unsigned Align = DL.getABITypeAlignment(Ty); 933 934 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 935 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 936 MachineMemOperand::MONonTemporal | 937 MachineMemOperand::MODereferenceable | 938 MachineMemOperand::MOInvariant); 939 940 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 941 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 942 } 943 944 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 945 const SDLoc &SL, SDValue Chain, 946 const ISD::InputArg &Arg) const { 947 MachineFunction &MF = DAG.getMachineFunction(); 948 MachineFrameInfo &MFI = MF.getFrameInfo(); 949 950 if (Arg.Flags.isByVal()) { 951 unsigned Size = Arg.Flags.getByValSize(); 952 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 953 return DAG.getFrameIndex(FrameIdx, MVT::i32); 954 } 955 956 unsigned ArgOffset = VA.getLocMemOffset(); 957 unsigned ArgSize = VA.getValVT().getStoreSize(); 958 959 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 960 961 // Create load nodes to retrieve arguments from the stack. 962 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 963 SDValue ArgValue; 964 965 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 966 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 967 MVT MemVT = VA.getValVT(); 968 969 switch (VA.getLocInfo()) { 970 default: 971 break; 972 case CCValAssign::BCvt: 973 MemVT = VA.getLocVT(); 974 break; 975 case CCValAssign::SExt: 976 ExtType = ISD::SEXTLOAD; 977 break; 978 case CCValAssign::ZExt: 979 ExtType = ISD::ZEXTLOAD; 980 break; 981 case CCValAssign::AExt: 982 ExtType = ISD::EXTLOAD; 983 break; 984 } 985 986 ArgValue = DAG.getExtLoad( 987 ExtType, SL, VA.getLocVT(), Chain, FIN, 988 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 989 MemVT); 990 return ArgValue; 991 } 992 993 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 994 CallingConv::ID CallConv, 995 ArrayRef<ISD::InputArg> Ins, 996 BitVector &Skipped, 997 FunctionType *FType, 998 SIMachineFunctionInfo *Info) { 999 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1000 const ISD::InputArg &Arg = Ins[I]; 1001 1002 // First check if it's a PS input addr. 1003 if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() && 1004 !Arg.Flags.isByVal() && PSInputNum <= 15) { 1005 1006 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) { 1007 // We can safely skip PS inputs. 1008 Skipped.set(I); 1009 ++PSInputNum; 1010 continue; 1011 } 1012 1013 Info->markPSInputAllocated(PSInputNum); 1014 if (Arg.Used) 1015 Info->markPSInputEnabled(PSInputNum); 1016 1017 ++PSInputNum; 1018 } 1019 1020 // Second split vertices into their elements. 1021 if (Arg.VT.isVector()) { 1022 ISD::InputArg NewArg = Arg; 1023 NewArg.Flags.setSplit(); 1024 NewArg.VT = Arg.VT.getVectorElementType(); 1025 1026 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a 1027 // three or five element vertex only needs three or five registers, 1028 // NOT four or eight. 1029 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 1030 unsigned NumElements = ParamType->getVectorNumElements(); 1031 1032 for (unsigned J = 0; J != NumElements; ++J) { 1033 Splits.push_back(NewArg); 1034 NewArg.PartOffset += NewArg.VT.getStoreSize(); 1035 } 1036 } else { 1037 Splits.push_back(Arg); 1038 } 1039 } 1040 } 1041 1042 // Allocate special inputs passed in VGPRs. 1043 static void allocateSpecialInputVGPRs(CCState &CCInfo, 1044 MachineFunction &MF, 1045 const SIRegisterInfo &TRI, 1046 SIMachineFunctionInfo &Info) { 1047 if (Info.hasWorkItemIDX()) { 1048 unsigned Reg = TRI.getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X); 1049 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1050 CCInfo.AllocateReg(Reg); 1051 } 1052 1053 if (Info.hasWorkItemIDY()) { 1054 unsigned Reg = TRI.getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y); 1055 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1056 CCInfo.AllocateReg(Reg); 1057 } 1058 1059 if (Info.hasWorkItemIDZ()) { 1060 unsigned Reg = TRI.getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z); 1061 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1062 CCInfo.AllocateReg(Reg); 1063 } 1064 } 1065 1066 // Allocate special inputs passed in user SGPRs. 1067 static void allocateHSAUserSGPRs(CCState &CCInfo, 1068 MachineFunction &MF, 1069 const SIRegisterInfo &TRI, 1070 SIMachineFunctionInfo &Info) { 1071 if (Info.hasImplicitBufferPtr()) { 1072 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1073 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1074 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1075 } 1076 1077 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1078 if (Info.hasPrivateSegmentBuffer()) { 1079 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1080 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1081 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1082 } 1083 1084 if (Info.hasDispatchPtr()) { 1085 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1086 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1087 CCInfo.AllocateReg(DispatchPtrReg); 1088 } 1089 1090 if (Info.hasQueuePtr()) { 1091 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1092 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1093 CCInfo.AllocateReg(QueuePtrReg); 1094 } 1095 1096 if (Info.hasKernargSegmentPtr()) { 1097 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI); 1098 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1099 CCInfo.AllocateReg(InputPtrReg); 1100 } 1101 1102 if (Info.hasDispatchID()) { 1103 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1104 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1105 CCInfo.AllocateReg(DispatchIDReg); 1106 } 1107 1108 if (Info.hasFlatScratchInit()) { 1109 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1110 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1111 CCInfo.AllocateReg(FlatScratchInitReg); 1112 } 1113 1114 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1115 // these from the dispatch pointer. 1116 } 1117 1118 // Allocate special input registers that are initialized per-wave. 1119 static void allocateSystemSGPRs(CCState &CCInfo, 1120 MachineFunction &MF, 1121 SIMachineFunctionInfo &Info, 1122 CallingConv::ID CallConv, 1123 bool IsShader) { 1124 if (Info.hasWorkGroupIDX()) { 1125 unsigned Reg = Info.addWorkGroupIDX(); 1126 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1127 CCInfo.AllocateReg(Reg); 1128 } 1129 1130 if (Info.hasWorkGroupIDY()) { 1131 unsigned Reg = Info.addWorkGroupIDY(); 1132 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1133 CCInfo.AllocateReg(Reg); 1134 } 1135 1136 if (Info.hasWorkGroupIDZ()) { 1137 unsigned Reg = Info.addWorkGroupIDZ(); 1138 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1139 CCInfo.AllocateReg(Reg); 1140 } 1141 1142 if (Info.hasWorkGroupInfo()) { 1143 unsigned Reg = Info.addWorkGroupInfo(); 1144 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1145 CCInfo.AllocateReg(Reg); 1146 } 1147 1148 if (Info.hasPrivateSegmentWaveByteOffset()) { 1149 // Scratch wave offset passed in system SGPR. 1150 unsigned PrivateSegmentWaveByteOffsetReg; 1151 1152 if (IsShader) { 1153 PrivateSegmentWaveByteOffsetReg = 1154 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1155 1156 // This is true if the scratch wave byte offset doesn't have a fixed 1157 // location. 1158 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1159 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1160 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1161 } 1162 } else 1163 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1164 1165 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1166 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1167 } 1168 } 1169 1170 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1171 MachineFunction &MF, 1172 const SIRegisterInfo &TRI, 1173 SIMachineFunctionInfo &Info, 1174 bool NeedSP) { 1175 // Now that we've figured out where the scratch register inputs are, see if 1176 // should reserve the arguments and use them directly. 1177 MachineFrameInfo &MFI = MF.getFrameInfo(); 1178 bool HasStackObjects = MFI.hasStackObjects(); 1179 1180 // Record that we know we have non-spill stack objects so we don't need to 1181 // check all stack objects later. 1182 if (HasStackObjects) 1183 Info.setHasNonSpillStackObjects(true); 1184 1185 // Everything live out of a block is spilled with fast regalloc, so it's 1186 // almost certain that spilling will be required. 1187 if (TM.getOptLevel() == CodeGenOpt::None) 1188 HasStackObjects = true; 1189 1190 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 1191 if (ST.isAmdCodeObjectV2(MF)) { 1192 if (HasStackObjects) { 1193 // If we have stack objects, we unquestionably need the private buffer 1194 // resource. For the Code Object V2 ABI, this will be the first 4 user 1195 // SGPR inputs. We can reserve those and use them directly. 1196 1197 unsigned PrivateSegmentBufferReg = TRI.getPreloadedValue( 1198 MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER); 1199 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1200 1201 unsigned PrivateSegmentWaveByteOffsetReg = TRI.getPreloadedValue( 1202 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1203 Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg); 1204 } else { 1205 unsigned ReservedBufferReg 1206 = TRI.reservedPrivateSegmentBufferReg(MF); 1207 unsigned ReservedOffsetReg 1208 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1209 1210 // We tentatively reserve the last registers (skipping the last two 1211 // which may contain VCC). After register allocation, we'll replace 1212 // these with the ones immediately after those which were really 1213 // allocated. In the prologue copies will be inserted from the argument 1214 // to these reserved registers. 1215 Info.setScratchRSrcReg(ReservedBufferReg); 1216 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1217 } 1218 } else { 1219 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1220 1221 // Without HSA, relocations are used for the scratch pointer and the 1222 // buffer resource setup is always inserted in the prologue. Scratch wave 1223 // offset is still in an input SGPR. 1224 Info.setScratchRSrcReg(ReservedBufferReg); 1225 1226 if (HasStackObjects) { 1227 unsigned ScratchWaveOffsetReg = TRI.getPreloadedValue( 1228 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1229 Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg); 1230 } else { 1231 unsigned ReservedOffsetReg 1232 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1233 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1234 } 1235 } 1236 1237 if (NeedSP) { 1238 unsigned ReservedStackPtrOffsetReg = TRI.reservedStackPtrOffsetReg(MF); 1239 Info.setStackPtrOffsetReg(ReservedStackPtrOffsetReg); 1240 1241 assert(Info.getStackPtrOffsetReg() != Info.getFrameOffsetReg()); 1242 assert(!TRI.isSubRegister(Info.getScratchRSrcReg(), 1243 Info.getStackPtrOffsetReg())); 1244 } 1245 } 1246 1247 SDValue SITargetLowering::LowerFormalArguments( 1248 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 1249 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 1250 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 1251 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1252 1253 MachineFunction &MF = DAG.getMachineFunction(); 1254 FunctionType *FType = MF.getFunction()->getFunctionType(); 1255 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1256 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 1257 1258 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 1259 const Function *Fn = MF.getFunction(); 1260 DiagnosticInfoUnsupported NoGraphicsHSA( 1261 *Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 1262 DAG.getContext()->diagnose(NoGraphicsHSA); 1263 return DAG.getEntryNode(); 1264 } 1265 1266 // Create stack objects that are used for emitting debugger prologue if 1267 // "amdgpu-debugger-emit-prologue" attribute was specified. 1268 if (ST.debuggerEmitPrologue()) 1269 createDebuggerPrologueStackObjects(MF); 1270 1271 SmallVector<ISD::InputArg, 16> Splits; 1272 SmallVector<CCValAssign, 16> ArgLocs; 1273 BitVector Skipped(Ins.size()); 1274 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1275 *DAG.getContext()); 1276 1277 bool IsShader = AMDGPU::isShader(CallConv); 1278 bool IsKernel = AMDGPU::isKernel(CallConv); 1279 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 1280 1281 if (IsShader) { 1282 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 1283 1284 // At least one interpolation mode must be enabled or else the GPU will 1285 // hang. 1286 // 1287 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 1288 // set PSInputAddr, the user wants to enable some bits after the compilation 1289 // based on run-time states. Since we can't know what the final PSInputEna 1290 // will look like, so we shouldn't do anything here and the user should take 1291 // responsibility for the correct programming. 1292 // 1293 // Otherwise, the following restrictions apply: 1294 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 1295 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 1296 // enabled too. 1297 if (CallConv == CallingConv::AMDGPU_PS && 1298 ((Info->getPSInputAddr() & 0x7F) == 0 || 1299 ((Info->getPSInputAddr() & 0xF) == 0 && 1300 Info->isPSInputAllocated(11)))) { 1301 CCInfo.AllocateReg(AMDGPU::VGPR0); 1302 CCInfo.AllocateReg(AMDGPU::VGPR1); 1303 Info->markPSInputAllocated(0); 1304 Info->markPSInputEnabled(0); 1305 } 1306 1307 assert(!Info->hasDispatchPtr() && 1308 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 1309 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 1310 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 1311 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 1312 !Info->hasWorkItemIDZ()); 1313 } else if (IsKernel) { 1314 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 1315 } else { 1316 Splits.append(Ins.begin(), Ins.end()); 1317 } 1318 1319 if (IsEntryFunc) { 1320 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 1321 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 1322 } 1323 1324 if (IsKernel) { 1325 analyzeFormalArgumentsCompute(CCInfo, Ins); 1326 } else { 1327 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 1328 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 1329 } 1330 1331 SmallVector<SDValue, 16> Chains; 1332 1333 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 1334 const ISD::InputArg &Arg = Ins[i]; 1335 if (Skipped[i]) { 1336 InVals.push_back(DAG.getUNDEF(Arg.VT)); 1337 continue; 1338 } 1339 1340 CCValAssign &VA = ArgLocs[ArgIdx++]; 1341 MVT VT = VA.getLocVT(); 1342 1343 if (IsEntryFunc && VA.isMemLoc()) { 1344 VT = Ins[i].VT; 1345 EVT MemVT = VA.getLocVT(); 1346 1347 const uint64_t Offset = Subtarget->getExplicitKernelArgOffset(MF) + 1348 VA.getLocMemOffset(); 1349 Info->setABIArgOffset(Offset + MemVT.getStoreSize()); 1350 1351 // The first 36 bytes of the input buffer contains information about 1352 // thread group and global sizes. 1353 SDValue Arg = lowerKernargMemParameter( 1354 DAG, VT, MemVT, DL, Chain, Offset, Ins[i].Flags.isSExt(), &Ins[i]); 1355 Chains.push_back(Arg.getValue(1)); 1356 1357 auto *ParamTy = 1358 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 1359 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS && 1360 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 1361 // On SI local pointers are just offsets into LDS, so they are always 1362 // less than 16-bits. On CI and newer they could potentially be 1363 // real pointers, so we can't guarantee their size. 1364 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 1365 DAG.getValueType(MVT::i16)); 1366 } 1367 1368 InVals.push_back(Arg); 1369 continue; 1370 } else if (!IsEntryFunc && VA.isMemLoc()) { 1371 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 1372 InVals.push_back(Val); 1373 if (!Arg.Flags.isByVal()) 1374 Chains.push_back(Val.getValue(1)); 1375 continue; 1376 } 1377 1378 assert(VA.isRegLoc() && "Parameter must be in a register!"); 1379 1380 unsigned Reg = VA.getLocReg(); 1381 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 1382 1383 Reg = MF.addLiveIn(Reg, RC); 1384 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 1385 1386 if (IsShader && Arg.VT.isVector()) { 1387 // Build a vector from the registers 1388 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 1389 unsigned NumElements = ParamType->getVectorNumElements(); 1390 1391 SmallVector<SDValue, 4> Regs; 1392 Regs.push_back(Val); 1393 for (unsigned j = 1; j != NumElements; ++j) { 1394 Reg = ArgLocs[ArgIdx++].getLocReg(); 1395 Reg = MF.addLiveIn(Reg, RC); 1396 1397 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT); 1398 Regs.push_back(Copy); 1399 } 1400 1401 // Fill up the missing vector elements 1402 NumElements = Arg.VT.getVectorNumElements() - NumElements; 1403 Regs.append(NumElements, DAG.getUNDEF(VT)); 1404 1405 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs)); 1406 continue; 1407 } 1408 1409 InVals.push_back(Val); 1410 } 1411 1412 const MachineFrameInfo &FrameInfo = MF.getFrameInfo(); 1413 1414 // TODO: Could maybe omit SP if only tail calls? 1415 bool NeedSP = FrameInfo.hasCalls() || FrameInfo.hasVarSizedObjects(); 1416 1417 // Start adding system SGPRs. 1418 if (IsEntryFunc) { 1419 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 1420 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info, NeedSP); 1421 } else { 1422 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 1423 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg()); 1424 CCInfo.AllocateReg(Info->getFrameOffsetReg()); 1425 1426 if (NeedSP) { 1427 unsigned StackPtrReg = findFirstFreeSGPR(CCInfo); 1428 CCInfo.AllocateReg(StackPtrReg); 1429 Info->setStackPtrOffsetReg(StackPtrReg); 1430 } 1431 } 1432 1433 return Chains.empty() ? Chain : 1434 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 1435 } 1436 1437 // TODO: If return values can't fit in registers, we should return as many as 1438 // possible in registers before passing on stack. 1439 bool SITargetLowering::CanLowerReturn( 1440 CallingConv::ID CallConv, 1441 MachineFunction &MF, bool IsVarArg, 1442 const SmallVectorImpl<ISD::OutputArg> &Outs, 1443 LLVMContext &Context) const { 1444 // Replacing returns with sret/stack usage doesn't make sense for shaders. 1445 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 1446 // for shaders. Vector types should be explicitly handled by CC. 1447 if (AMDGPU::isEntryFunctionCC(CallConv)) 1448 return true; 1449 1450 SmallVector<CCValAssign, 16> RVLocs; 1451 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 1452 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 1453 } 1454 1455 SDValue 1456 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 1457 bool isVarArg, 1458 const SmallVectorImpl<ISD::OutputArg> &Outs, 1459 const SmallVectorImpl<SDValue> &OutVals, 1460 const SDLoc &DL, SelectionDAG &DAG) const { 1461 MachineFunction &MF = DAG.getMachineFunction(); 1462 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1463 1464 if (AMDGPU::isKernel(CallConv)) { 1465 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 1466 OutVals, DL, DAG); 1467 } 1468 1469 bool IsShader = AMDGPU::isShader(CallConv); 1470 1471 Info->setIfReturnsVoid(Outs.size() == 0); 1472 bool IsWaveEnd = Info->returnsVoid() && IsShader; 1473 1474 SmallVector<ISD::OutputArg, 48> Splits; 1475 SmallVector<SDValue, 48> SplitVals; 1476 1477 // Split vectors into their elements. 1478 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 1479 const ISD::OutputArg &Out = Outs[i]; 1480 1481 if (IsShader && Out.VT.isVector()) { 1482 MVT VT = Out.VT.getVectorElementType(); 1483 ISD::OutputArg NewOut = Out; 1484 NewOut.Flags.setSplit(); 1485 NewOut.VT = VT; 1486 1487 // We want the original number of vector elements here, e.g. 1488 // three or five, not four or eight. 1489 unsigned NumElements = Out.ArgVT.getVectorNumElements(); 1490 1491 for (unsigned j = 0; j != NumElements; ++j) { 1492 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i], 1493 DAG.getConstant(j, DL, MVT::i32)); 1494 SplitVals.push_back(Elem); 1495 Splits.push_back(NewOut); 1496 NewOut.PartOffset += NewOut.VT.getStoreSize(); 1497 } 1498 } else { 1499 SplitVals.push_back(OutVals[i]); 1500 Splits.push_back(Out); 1501 } 1502 } 1503 1504 // CCValAssign - represent the assignment of the return value to a location. 1505 SmallVector<CCValAssign, 48> RVLocs; 1506 1507 // CCState - Info about the registers and stack slots. 1508 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1509 *DAG.getContext()); 1510 1511 // Analyze outgoing return values. 1512 CCInfo.AnalyzeReturn(Splits, CCAssignFnForReturn(CallConv, isVarArg)); 1513 1514 SDValue Flag; 1515 SmallVector<SDValue, 48> RetOps; 1516 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 1517 1518 // Add return address for callable functions. 1519 if (!Info->isEntryFunction()) { 1520 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1521 SDValue ReturnAddrReg = CreateLiveInRegister( 1522 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 1523 1524 // FIXME: Should be able to use a vreg here, but need a way to prevent it 1525 // from being allcoated to a CSR. 1526 1527 SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 1528 MVT::i64); 1529 1530 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag); 1531 Flag = Chain.getValue(1); 1532 1533 RetOps.push_back(PhysReturnAddrReg); 1534 } 1535 1536 // Copy the result values into the output registers. 1537 for (unsigned i = 0, realRVLocIdx = 0; 1538 i != RVLocs.size(); 1539 ++i, ++realRVLocIdx) { 1540 CCValAssign &VA = RVLocs[i]; 1541 assert(VA.isRegLoc() && "Can only return in registers!"); 1542 // TODO: Partially return in registers if return values don't fit. 1543 1544 SDValue Arg = SplitVals[realRVLocIdx]; 1545 1546 // Copied from other backends. 1547 switch (VA.getLocInfo()) { 1548 case CCValAssign::Full: 1549 break; 1550 case CCValAssign::BCvt: 1551 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 1552 break; 1553 case CCValAssign::SExt: 1554 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 1555 break; 1556 case CCValAssign::ZExt: 1557 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 1558 break; 1559 case CCValAssign::AExt: 1560 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 1561 break; 1562 default: 1563 llvm_unreachable("Unknown loc info!"); 1564 } 1565 1566 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 1567 Flag = Chain.getValue(1); 1568 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 1569 } 1570 1571 // FIXME: Does sret work properly? 1572 1573 // Update chain and glue. 1574 RetOps[0] = Chain; 1575 if (Flag.getNode()) 1576 RetOps.push_back(Flag); 1577 1578 unsigned Opc = AMDGPUISD::ENDPGM; 1579 if (!IsWaveEnd) 1580 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 1581 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 1582 } 1583 1584 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT, 1585 SelectionDAG &DAG) const { 1586 unsigned Reg = StringSwitch<unsigned>(RegName) 1587 .Case("m0", AMDGPU::M0) 1588 .Case("exec", AMDGPU::EXEC) 1589 .Case("exec_lo", AMDGPU::EXEC_LO) 1590 .Case("exec_hi", AMDGPU::EXEC_HI) 1591 .Case("flat_scratch", AMDGPU::FLAT_SCR) 1592 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 1593 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 1594 .Default(AMDGPU::NoRegister); 1595 1596 if (Reg == AMDGPU::NoRegister) { 1597 report_fatal_error(Twine("invalid register name \"" 1598 + StringRef(RegName) + "\".")); 1599 1600 } 1601 1602 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS && 1603 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 1604 report_fatal_error(Twine("invalid register \"" 1605 + StringRef(RegName) + "\" for subtarget.")); 1606 } 1607 1608 switch (Reg) { 1609 case AMDGPU::M0: 1610 case AMDGPU::EXEC_LO: 1611 case AMDGPU::EXEC_HI: 1612 case AMDGPU::FLAT_SCR_LO: 1613 case AMDGPU::FLAT_SCR_HI: 1614 if (VT.getSizeInBits() == 32) 1615 return Reg; 1616 break; 1617 case AMDGPU::EXEC: 1618 case AMDGPU::FLAT_SCR: 1619 if (VT.getSizeInBits() == 64) 1620 return Reg; 1621 break; 1622 default: 1623 llvm_unreachable("missing register type checking"); 1624 } 1625 1626 report_fatal_error(Twine("invalid type for register \"" 1627 + StringRef(RegName) + "\".")); 1628 } 1629 1630 // If kill is not the last instruction, split the block so kill is always a 1631 // proper terminator. 1632 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 1633 MachineBasicBlock *BB) const { 1634 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 1635 1636 MachineBasicBlock::iterator SplitPoint(&MI); 1637 ++SplitPoint; 1638 1639 if (SplitPoint == BB->end()) { 1640 // Don't bother with a new block. 1641 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR)); 1642 return BB; 1643 } 1644 1645 MachineFunction *MF = BB->getParent(); 1646 MachineBasicBlock *SplitBB 1647 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 1648 1649 MF->insert(++MachineFunction::iterator(BB), SplitBB); 1650 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 1651 1652 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 1653 BB->addSuccessor(SplitBB); 1654 1655 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR)); 1656 return SplitBB; 1657 } 1658 1659 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 1660 // wavefront. If the value is uniform and just happens to be in a VGPR, this 1661 // will only do one iteration. In the worst case, this will loop 64 times. 1662 // 1663 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 1664 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 1665 const SIInstrInfo *TII, 1666 MachineRegisterInfo &MRI, 1667 MachineBasicBlock &OrigBB, 1668 MachineBasicBlock &LoopBB, 1669 const DebugLoc &DL, 1670 const MachineOperand &IdxReg, 1671 unsigned InitReg, 1672 unsigned ResultReg, 1673 unsigned PhiReg, 1674 unsigned InitSaveExecReg, 1675 int Offset, 1676 bool UseGPRIdxMode) { 1677 MachineBasicBlock::iterator I = LoopBB.begin(); 1678 1679 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 1680 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 1681 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 1682 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 1683 1684 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 1685 .addReg(InitReg) 1686 .addMBB(&OrigBB) 1687 .addReg(ResultReg) 1688 .addMBB(&LoopBB); 1689 1690 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 1691 .addReg(InitSaveExecReg) 1692 .addMBB(&OrigBB) 1693 .addReg(NewExec) 1694 .addMBB(&LoopBB); 1695 1696 // Read the next variant <- also loop target. 1697 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 1698 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 1699 1700 // Compare the just read M0 value to all possible Idx values. 1701 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 1702 .addReg(CurrentIdxReg) 1703 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 1704 1705 if (UseGPRIdxMode) { 1706 unsigned IdxReg; 1707 if (Offset == 0) { 1708 IdxReg = CurrentIdxReg; 1709 } else { 1710 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 1711 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 1712 .addReg(CurrentIdxReg, RegState::Kill) 1713 .addImm(Offset); 1714 } 1715 1716 MachineInstr *SetIdx = 1717 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_IDX)) 1718 .addReg(IdxReg, RegState::Kill); 1719 SetIdx->getOperand(2).setIsUndef(); 1720 } else { 1721 // Move index from VCC into M0 1722 if (Offset == 0) { 1723 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 1724 .addReg(CurrentIdxReg, RegState::Kill); 1725 } else { 1726 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 1727 .addReg(CurrentIdxReg, RegState::Kill) 1728 .addImm(Offset); 1729 } 1730 } 1731 1732 // Update EXEC, save the original EXEC value to VCC. 1733 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec) 1734 .addReg(CondReg, RegState::Kill); 1735 1736 MRI.setSimpleHint(NewExec, CondReg); 1737 1738 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 1739 MachineInstr *InsertPt = 1740 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC) 1741 .addReg(AMDGPU::EXEC) 1742 .addReg(NewExec); 1743 1744 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 1745 // s_cbranch_scc0? 1746 1747 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 1748 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 1749 .addMBB(&LoopBB); 1750 1751 return InsertPt->getIterator(); 1752 } 1753 1754 // This has slightly sub-optimal regalloc when the source vector is killed by 1755 // the read. The register allocator does not understand that the kill is 1756 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 1757 // subregister from it, using 1 more VGPR than necessary. This was saved when 1758 // this was expanded after register allocation. 1759 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 1760 MachineBasicBlock &MBB, 1761 MachineInstr &MI, 1762 unsigned InitResultReg, 1763 unsigned PhiReg, 1764 int Offset, 1765 bool UseGPRIdxMode) { 1766 MachineFunction *MF = MBB.getParent(); 1767 MachineRegisterInfo &MRI = MF->getRegInfo(); 1768 const DebugLoc &DL = MI.getDebugLoc(); 1769 MachineBasicBlock::iterator I(&MI); 1770 1771 unsigned DstReg = MI.getOperand(0).getReg(); 1772 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 1773 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 1774 1775 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 1776 1777 // Save the EXEC mask 1778 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec) 1779 .addReg(AMDGPU::EXEC); 1780 1781 // To insert the loop we need to split the block. Move everything after this 1782 // point to a new block, and insert a new empty block between the two. 1783 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 1784 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 1785 MachineFunction::iterator MBBI(MBB); 1786 ++MBBI; 1787 1788 MF->insert(MBBI, LoopBB); 1789 MF->insert(MBBI, RemainderBB); 1790 1791 LoopBB->addSuccessor(LoopBB); 1792 LoopBB->addSuccessor(RemainderBB); 1793 1794 // Move the rest of the block into a new block. 1795 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 1796 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 1797 1798 MBB.addSuccessor(LoopBB); 1799 1800 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 1801 1802 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 1803 InitResultReg, DstReg, PhiReg, TmpExec, 1804 Offset, UseGPRIdxMode); 1805 1806 MachineBasicBlock::iterator First = RemainderBB->begin(); 1807 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC) 1808 .addReg(SaveExec); 1809 1810 return InsPt; 1811 } 1812 1813 // Returns subreg index, offset 1814 static std::pair<unsigned, int> 1815 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 1816 const TargetRegisterClass *SuperRC, 1817 unsigned VecReg, 1818 int Offset) { 1819 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 1820 1821 // Skip out of bounds offsets, or else we would end up using an undefined 1822 // register. 1823 if (Offset >= NumElts || Offset < 0) 1824 return std::make_pair(AMDGPU::sub0, Offset); 1825 1826 return std::make_pair(AMDGPU::sub0 + Offset, 0); 1827 } 1828 1829 // Return true if the index is an SGPR and was set. 1830 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 1831 MachineRegisterInfo &MRI, 1832 MachineInstr &MI, 1833 int Offset, 1834 bool UseGPRIdxMode, 1835 bool IsIndirectSrc) { 1836 MachineBasicBlock *MBB = MI.getParent(); 1837 const DebugLoc &DL = MI.getDebugLoc(); 1838 MachineBasicBlock::iterator I(&MI); 1839 1840 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 1841 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 1842 1843 assert(Idx->getReg() != AMDGPU::NoRegister); 1844 1845 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 1846 return false; 1847 1848 if (UseGPRIdxMode) { 1849 unsigned IdxMode = IsIndirectSrc ? 1850 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE; 1851 if (Offset == 0) { 1852 MachineInstr *SetOn = 1853 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 1854 .add(*Idx) 1855 .addImm(IdxMode); 1856 1857 SetOn->getOperand(3).setIsUndef(); 1858 } else { 1859 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 1860 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 1861 .add(*Idx) 1862 .addImm(Offset); 1863 MachineInstr *SetOn = 1864 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 1865 .addReg(Tmp, RegState::Kill) 1866 .addImm(IdxMode); 1867 1868 SetOn->getOperand(3).setIsUndef(); 1869 } 1870 1871 return true; 1872 } 1873 1874 if (Offset == 0) { 1875 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 1876 .add(*Idx); 1877 } else { 1878 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 1879 .add(*Idx) 1880 .addImm(Offset); 1881 } 1882 1883 return true; 1884 } 1885 1886 // Control flow needs to be inserted if indexing with a VGPR. 1887 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 1888 MachineBasicBlock &MBB, 1889 const SISubtarget &ST) { 1890 const SIInstrInfo *TII = ST.getInstrInfo(); 1891 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 1892 MachineFunction *MF = MBB.getParent(); 1893 MachineRegisterInfo &MRI = MF->getRegInfo(); 1894 1895 unsigned Dst = MI.getOperand(0).getReg(); 1896 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 1897 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 1898 1899 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 1900 1901 unsigned SubReg; 1902 std::tie(SubReg, Offset) 1903 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 1904 1905 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 1906 1907 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 1908 MachineBasicBlock::iterator I(&MI); 1909 const DebugLoc &DL = MI.getDebugLoc(); 1910 1911 if (UseGPRIdxMode) { 1912 // TODO: Look at the uses to avoid the copy. This may require rescheduling 1913 // to avoid interfering with other uses, so probably requires a new 1914 // optimization pass. 1915 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 1916 .addReg(SrcReg, RegState::Undef, SubReg) 1917 .addReg(SrcReg, RegState::Implicit) 1918 .addReg(AMDGPU::M0, RegState::Implicit); 1919 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 1920 } else { 1921 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 1922 .addReg(SrcReg, RegState::Undef, SubReg) 1923 .addReg(SrcReg, RegState::Implicit); 1924 } 1925 1926 MI.eraseFromParent(); 1927 1928 return &MBB; 1929 } 1930 1931 const DebugLoc &DL = MI.getDebugLoc(); 1932 MachineBasicBlock::iterator I(&MI); 1933 1934 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 1935 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 1936 1937 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 1938 1939 if (UseGPRIdxMode) { 1940 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 1941 .addImm(0) // Reset inside loop. 1942 .addImm(VGPRIndexMode::SRC0_ENABLE); 1943 SetOn->getOperand(3).setIsUndef(); 1944 1945 // Disable again after the loop. 1946 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 1947 } 1948 1949 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, UseGPRIdxMode); 1950 MachineBasicBlock *LoopBB = InsPt->getParent(); 1951 1952 if (UseGPRIdxMode) { 1953 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 1954 .addReg(SrcReg, RegState::Undef, SubReg) 1955 .addReg(SrcReg, RegState::Implicit) 1956 .addReg(AMDGPU::M0, RegState::Implicit); 1957 } else { 1958 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 1959 .addReg(SrcReg, RegState::Undef, SubReg) 1960 .addReg(SrcReg, RegState::Implicit); 1961 } 1962 1963 MI.eraseFromParent(); 1964 1965 return LoopBB; 1966 } 1967 1968 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI, 1969 const TargetRegisterClass *VecRC) { 1970 switch (TRI.getRegSizeInBits(*VecRC)) { 1971 case 32: // 4 bytes 1972 return AMDGPU::V_MOVRELD_B32_V1; 1973 case 64: // 8 bytes 1974 return AMDGPU::V_MOVRELD_B32_V2; 1975 case 128: // 16 bytes 1976 return AMDGPU::V_MOVRELD_B32_V4; 1977 case 256: // 32 bytes 1978 return AMDGPU::V_MOVRELD_B32_V8; 1979 case 512: // 64 bytes 1980 return AMDGPU::V_MOVRELD_B32_V16; 1981 default: 1982 llvm_unreachable("unsupported size for MOVRELD pseudos"); 1983 } 1984 } 1985 1986 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 1987 MachineBasicBlock &MBB, 1988 const SISubtarget &ST) { 1989 const SIInstrInfo *TII = ST.getInstrInfo(); 1990 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 1991 MachineFunction *MF = MBB.getParent(); 1992 MachineRegisterInfo &MRI = MF->getRegInfo(); 1993 1994 unsigned Dst = MI.getOperand(0).getReg(); 1995 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 1996 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 1997 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 1998 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 1999 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 2000 2001 // This can be an immediate, but will be folded later. 2002 assert(Val->getReg()); 2003 2004 unsigned SubReg; 2005 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 2006 SrcVec->getReg(), 2007 Offset); 2008 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 2009 2010 if (Idx->getReg() == AMDGPU::NoRegister) { 2011 MachineBasicBlock::iterator I(&MI); 2012 const DebugLoc &DL = MI.getDebugLoc(); 2013 2014 assert(Offset == 0); 2015 2016 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 2017 .add(*SrcVec) 2018 .add(*Val) 2019 .addImm(SubReg); 2020 2021 MI.eraseFromParent(); 2022 return &MBB; 2023 } 2024 2025 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 2026 MachineBasicBlock::iterator I(&MI); 2027 const DebugLoc &DL = MI.getDebugLoc(); 2028 2029 if (UseGPRIdxMode) { 2030 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 2031 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst 2032 .add(*Val) 2033 .addReg(Dst, RegState::ImplicitDefine) 2034 .addReg(SrcVec->getReg(), RegState::Implicit) 2035 .addReg(AMDGPU::M0, RegState::Implicit); 2036 2037 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2038 } else { 2039 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 2040 2041 BuildMI(MBB, I, DL, MovRelDesc) 2042 .addReg(Dst, RegState::Define) 2043 .addReg(SrcVec->getReg()) 2044 .add(*Val) 2045 .addImm(SubReg - AMDGPU::sub0); 2046 } 2047 2048 MI.eraseFromParent(); 2049 return &MBB; 2050 } 2051 2052 if (Val->isReg()) 2053 MRI.clearKillFlags(Val->getReg()); 2054 2055 const DebugLoc &DL = MI.getDebugLoc(); 2056 2057 if (UseGPRIdxMode) { 2058 MachineBasicBlock::iterator I(&MI); 2059 2060 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2061 .addImm(0) // Reset inside loop. 2062 .addImm(VGPRIndexMode::DST_ENABLE); 2063 SetOn->getOperand(3).setIsUndef(); 2064 2065 // Disable again after the loop. 2066 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2067 } 2068 2069 unsigned PhiReg = MRI.createVirtualRegister(VecRC); 2070 2071 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 2072 Offset, UseGPRIdxMode); 2073 MachineBasicBlock *LoopBB = InsPt->getParent(); 2074 2075 if (UseGPRIdxMode) { 2076 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 2077 .addReg(PhiReg, RegState::Undef, SubReg) // vdst 2078 .add(*Val) // src0 2079 .addReg(Dst, RegState::ImplicitDefine) 2080 .addReg(PhiReg, RegState::Implicit) 2081 .addReg(AMDGPU::M0, RegState::Implicit); 2082 } else { 2083 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 2084 2085 BuildMI(*LoopBB, InsPt, DL, MovRelDesc) 2086 .addReg(Dst, RegState::Define) 2087 .addReg(PhiReg) 2088 .add(*Val) 2089 .addImm(SubReg - AMDGPU::sub0); 2090 } 2091 2092 MI.eraseFromParent(); 2093 2094 return LoopBB; 2095 } 2096 2097 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 2098 MachineInstr &MI, MachineBasicBlock *BB) const { 2099 2100 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 2101 MachineFunction *MF = BB->getParent(); 2102 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 2103 2104 if (TII->isMIMG(MI)) { 2105 if (!MI.memoperands_empty()) 2106 return BB; 2107 // Add a memoperand for mimg instructions so that they aren't assumed to 2108 // be ordered memory instuctions. 2109 2110 MachinePointerInfo PtrInfo(MFI->getImagePSV()); 2111 MachineMemOperand::Flags Flags = MachineMemOperand::MODereferenceable; 2112 if (MI.mayStore()) 2113 Flags |= MachineMemOperand::MOStore; 2114 2115 if (MI.mayLoad()) 2116 Flags |= MachineMemOperand::MOLoad; 2117 2118 auto MMO = MF->getMachineMemOperand(PtrInfo, Flags, 0, 0); 2119 MI.addMemOperand(*MF, MMO); 2120 return BB; 2121 } 2122 2123 switch (MI.getOpcode()) { 2124 case AMDGPU::SI_INIT_M0: 2125 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 2126 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 2127 .add(MI.getOperand(0)); 2128 MI.eraseFromParent(); 2129 return BB; 2130 2131 case AMDGPU::SI_INIT_EXEC: 2132 // This should be before all vector instructions. 2133 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 2134 AMDGPU::EXEC) 2135 .addImm(MI.getOperand(0).getImm()); 2136 MI.eraseFromParent(); 2137 return BB; 2138 2139 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 2140 // Extract the thread count from an SGPR input and set EXEC accordingly. 2141 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 2142 // 2143 // S_BFE_U32 count, input, {shift, 7} 2144 // S_BFM_B64 exec, count, 0 2145 // S_CMP_EQ_U32 count, 64 2146 // S_CMOV_B64 exec, -1 2147 MachineInstr *FirstMI = &*BB->begin(); 2148 MachineRegisterInfo &MRI = MF->getRegInfo(); 2149 unsigned InputReg = MI.getOperand(0).getReg(); 2150 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 2151 bool Found = false; 2152 2153 // Move the COPY of the input reg to the beginning, so that we can use it. 2154 for (auto I = BB->begin(); I != &MI; I++) { 2155 if (I->getOpcode() != TargetOpcode::COPY || 2156 I->getOperand(0).getReg() != InputReg) 2157 continue; 2158 2159 if (I == FirstMI) { 2160 FirstMI = &*++BB->begin(); 2161 } else { 2162 I->removeFromParent(); 2163 BB->insert(FirstMI, &*I); 2164 } 2165 Found = true; 2166 break; 2167 } 2168 assert(Found); 2169 (void)Found; 2170 2171 // This should be before all vector instructions. 2172 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 2173 .addReg(InputReg) 2174 .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000); 2175 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64), 2176 AMDGPU::EXEC) 2177 .addReg(CountReg) 2178 .addImm(0); 2179 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 2180 .addReg(CountReg, RegState::Kill) 2181 .addImm(64); 2182 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64), 2183 AMDGPU::EXEC) 2184 .addImm(-1); 2185 MI.eraseFromParent(); 2186 return BB; 2187 } 2188 2189 case AMDGPU::GET_GROUPSTATICSIZE: { 2190 DebugLoc DL = MI.getDebugLoc(); 2191 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 2192 .add(MI.getOperand(0)) 2193 .addImm(MFI->getLDSSize()); 2194 MI.eraseFromParent(); 2195 return BB; 2196 } 2197 case AMDGPU::SI_INDIRECT_SRC_V1: 2198 case AMDGPU::SI_INDIRECT_SRC_V2: 2199 case AMDGPU::SI_INDIRECT_SRC_V4: 2200 case AMDGPU::SI_INDIRECT_SRC_V8: 2201 case AMDGPU::SI_INDIRECT_SRC_V16: 2202 return emitIndirectSrc(MI, *BB, *getSubtarget()); 2203 case AMDGPU::SI_INDIRECT_DST_V1: 2204 case AMDGPU::SI_INDIRECT_DST_V2: 2205 case AMDGPU::SI_INDIRECT_DST_V4: 2206 case AMDGPU::SI_INDIRECT_DST_V8: 2207 case AMDGPU::SI_INDIRECT_DST_V16: 2208 return emitIndirectDst(MI, *BB, *getSubtarget()); 2209 case AMDGPU::SI_KILL: 2210 return splitKillBlock(MI, BB); 2211 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 2212 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 2213 2214 unsigned Dst = MI.getOperand(0).getReg(); 2215 unsigned Src0 = MI.getOperand(1).getReg(); 2216 unsigned Src1 = MI.getOperand(2).getReg(); 2217 const DebugLoc &DL = MI.getDebugLoc(); 2218 unsigned SrcCond = MI.getOperand(3).getReg(); 2219 2220 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 2221 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 2222 2223 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 2224 .addReg(Src0, 0, AMDGPU::sub0) 2225 .addReg(Src1, 0, AMDGPU::sub0) 2226 .addReg(SrcCond); 2227 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 2228 .addReg(Src0, 0, AMDGPU::sub1) 2229 .addReg(Src1, 0, AMDGPU::sub1) 2230 .addReg(SrcCond); 2231 2232 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 2233 .addReg(DstLo) 2234 .addImm(AMDGPU::sub0) 2235 .addReg(DstHi) 2236 .addImm(AMDGPU::sub1); 2237 MI.eraseFromParent(); 2238 return BB; 2239 } 2240 case AMDGPU::SI_BR_UNDEF: { 2241 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 2242 const DebugLoc &DL = MI.getDebugLoc(); 2243 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 2244 .add(MI.getOperand(0)); 2245 Br->getOperand(1).setIsUndef(true); // read undef SCC 2246 MI.eraseFromParent(); 2247 return BB; 2248 } 2249 default: 2250 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 2251 } 2252 } 2253 2254 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 2255 // This currently forces unfolding various combinations of fsub into fma with 2256 // free fneg'd operands. As long as we have fast FMA (controlled by 2257 // isFMAFasterThanFMulAndFAdd), we should perform these. 2258 2259 // When fma is quarter rate, for f64 where add / sub are at best half rate, 2260 // most of these combines appear to be cycle neutral but save on instruction 2261 // count / code size. 2262 return true; 2263 } 2264 2265 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 2266 EVT VT) const { 2267 if (!VT.isVector()) { 2268 return MVT::i1; 2269 } 2270 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 2271 } 2272 2273 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 2274 // TODO: Should i16 be used always if legal? For now it would force VALU 2275 // shifts. 2276 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 2277 } 2278 2279 // Answering this is somewhat tricky and depends on the specific device which 2280 // have different rates for fma or all f64 operations. 2281 // 2282 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 2283 // regardless of which device (although the number of cycles differs between 2284 // devices), so it is always profitable for f64. 2285 // 2286 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 2287 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 2288 // which we can always do even without fused FP ops since it returns the same 2289 // result as the separate operations and since it is always full 2290 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 2291 // however does not support denormals, so we do report fma as faster if we have 2292 // a fast fma device and require denormals. 2293 // 2294 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 2295 VT = VT.getScalarType(); 2296 2297 switch (VT.getSimpleVT().SimpleTy) { 2298 case MVT::f32: 2299 // This is as fast on some subtargets. However, we always have full rate f32 2300 // mad available which returns the same result as the separate operations 2301 // which we should prefer over fma. We can't use this if we want to support 2302 // denormals, so only report this in these cases. 2303 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32(); 2304 case MVT::f64: 2305 return true; 2306 case MVT::f16: 2307 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals(); 2308 default: 2309 break; 2310 } 2311 2312 return false; 2313 } 2314 2315 //===----------------------------------------------------------------------===// 2316 // Custom DAG Lowering Operations 2317 //===----------------------------------------------------------------------===// 2318 2319 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 2320 switch (Op.getOpcode()) { 2321 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 2322 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 2323 case ISD::LOAD: { 2324 SDValue Result = LowerLOAD(Op, DAG); 2325 assert((!Result.getNode() || 2326 Result.getNode()->getNumValues() == 2) && 2327 "Load should return a value and a chain"); 2328 return Result; 2329 } 2330 2331 case ISD::FSIN: 2332 case ISD::FCOS: 2333 return LowerTrig(Op, DAG); 2334 case ISD::SELECT: return LowerSELECT(Op, DAG); 2335 case ISD::FDIV: return LowerFDIV(Op, DAG); 2336 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 2337 case ISD::STORE: return LowerSTORE(Op, DAG); 2338 case ISD::GlobalAddress: { 2339 MachineFunction &MF = DAG.getMachineFunction(); 2340 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 2341 return LowerGlobalAddress(MFI, Op, DAG); 2342 } 2343 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2344 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 2345 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 2346 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 2347 case ISD::INSERT_VECTOR_ELT: 2348 return lowerINSERT_VECTOR_ELT(Op, DAG); 2349 case ISD::EXTRACT_VECTOR_ELT: 2350 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 2351 case ISD::FP_ROUND: 2352 return lowerFP_ROUND(Op, DAG); 2353 2354 case ISD::TRAP: 2355 case ISD::DEBUGTRAP: 2356 return lowerTRAP(Op, DAG); 2357 } 2358 return SDValue(); 2359 } 2360 2361 void SITargetLowering::ReplaceNodeResults(SDNode *N, 2362 SmallVectorImpl<SDValue> &Results, 2363 SelectionDAG &DAG) const { 2364 switch (N->getOpcode()) { 2365 case ISD::INSERT_VECTOR_ELT: { 2366 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 2367 Results.push_back(Res); 2368 return; 2369 } 2370 case ISD::EXTRACT_VECTOR_ELT: { 2371 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 2372 Results.push_back(Res); 2373 return; 2374 } 2375 case ISD::INTRINSIC_WO_CHAIN: { 2376 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 2377 if (IID == Intrinsic::amdgcn_cvt_pkrtz) { 2378 SDValue Src0 = N->getOperand(1); 2379 SDValue Src1 = N->getOperand(2); 2380 SDLoc SL(N); 2381 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 2382 Src0, Src1); 2383 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 2384 return; 2385 } 2386 break; 2387 } 2388 case ISD::SELECT: { 2389 SDLoc SL(N); 2390 EVT VT = N->getValueType(0); 2391 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 2392 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 2393 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 2394 2395 EVT SelectVT = NewVT; 2396 if (NewVT.bitsLT(MVT::i32)) { 2397 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 2398 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 2399 SelectVT = MVT::i32; 2400 } 2401 2402 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 2403 N->getOperand(0), LHS, RHS); 2404 2405 if (NewVT != SelectVT) 2406 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 2407 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 2408 return; 2409 } 2410 default: 2411 break; 2412 } 2413 } 2414 2415 /// \brief Helper function for LowerBRCOND 2416 static SDNode *findUser(SDValue Value, unsigned Opcode) { 2417 2418 SDNode *Parent = Value.getNode(); 2419 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 2420 I != E; ++I) { 2421 2422 if (I.getUse().get() != Value) 2423 continue; 2424 2425 if (I->getOpcode() == Opcode) 2426 return *I; 2427 } 2428 return nullptr; 2429 } 2430 2431 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 2432 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 2433 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 2434 case Intrinsic::amdgcn_if: 2435 return AMDGPUISD::IF; 2436 case Intrinsic::amdgcn_else: 2437 return AMDGPUISD::ELSE; 2438 case Intrinsic::amdgcn_loop: 2439 return AMDGPUISD::LOOP; 2440 case Intrinsic::amdgcn_end_cf: 2441 llvm_unreachable("should not occur"); 2442 default: 2443 return 0; 2444 } 2445 } 2446 2447 // break, if_break, else_break are all only used as inputs to loop, not 2448 // directly as branch conditions. 2449 return 0; 2450 } 2451 2452 void SITargetLowering::createDebuggerPrologueStackObjects( 2453 MachineFunction &MF) const { 2454 // Create stack objects that are used for emitting debugger prologue. 2455 // 2456 // Debugger prologue writes work group IDs and work item IDs to scratch memory 2457 // at fixed location in the following format: 2458 // offset 0: work group ID x 2459 // offset 4: work group ID y 2460 // offset 8: work group ID z 2461 // offset 16: work item ID x 2462 // offset 20: work item ID y 2463 // offset 24: work item ID z 2464 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2465 int ObjectIdx = 0; 2466 2467 // For each dimension: 2468 for (unsigned i = 0; i < 3; ++i) { 2469 // Create fixed stack object for work group ID. 2470 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true); 2471 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx); 2472 // Create fixed stack object for work item ID. 2473 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true); 2474 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx); 2475 } 2476 } 2477 2478 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 2479 const Triple &TT = getTargetMachine().getTargetTriple(); 2480 return GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS && 2481 AMDGPU::shouldEmitConstantsToTextSection(TT); 2482 } 2483 2484 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 2485 return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS || 2486 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) && 2487 !shouldEmitFixup(GV) && 2488 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 2489 } 2490 2491 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 2492 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 2493 } 2494 2495 /// This transforms the control flow intrinsics to get the branch destination as 2496 /// last parameter, also switches branch target with BR if the need arise 2497 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 2498 SelectionDAG &DAG) const { 2499 SDLoc DL(BRCOND); 2500 2501 SDNode *Intr = BRCOND.getOperand(1).getNode(); 2502 SDValue Target = BRCOND.getOperand(2); 2503 SDNode *BR = nullptr; 2504 SDNode *SetCC = nullptr; 2505 2506 if (Intr->getOpcode() == ISD::SETCC) { 2507 // As long as we negate the condition everything is fine 2508 SetCC = Intr; 2509 Intr = SetCC->getOperand(0).getNode(); 2510 2511 } else { 2512 // Get the target from BR if we don't negate the condition 2513 BR = findUser(BRCOND, ISD::BR); 2514 Target = BR->getOperand(1); 2515 } 2516 2517 // FIXME: This changes the types of the intrinsics instead of introducing new 2518 // nodes with the correct types. 2519 // e.g. llvm.amdgcn.loop 2520 2521 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 2522 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 2523 2524 unsigned CFNode = isCFIntrinsic(Intr); 2525 if (CFNode == 0) { 2526 // This is a uniform branch so we don't need to legalize. 2527 return BRCOND; 2528 } 2529 2530 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 2531 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 2532 2533 assert(!SetCC || 2534 (SetCC->getConstantOperandVal(1) == 1 && 2535 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 2536 ISD::SETNE)); 2537 2538 // operands of the new intrinsic call 2539 SmallVector<SDValue, 4> Ops; 2540 if (HaveChain) 2541 Ops.push_back(BRCOND.getOperand(0)); 2542 2543 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 2544 Ops.push_back(Target); 2545 2546 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 2547 2548 // build the new intrinsic call 2549 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 2550 2551 if (!HaveChain) { 2552 SDValue Ops[] = { 2553 SDValue(Result, 0), 2554 BRCOND.getOperand(0) 2555 }; 2556 2557 Result = DAG.getMergeValues(Ops, DL).getNode(); 2558 } 2559 2560 if (BR) { 2561 // Give the branch instruction our target 2562 SDValue Ops[] = { 2563 BR->getOperand(0), 2564 BRCOND.getOperand(2) 2565 }; 2566 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 2567 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 2568 BR = NewBR.getNode(); 2569 } 2570 2571 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 2572 2573 // Copy the intrinsic results to registers 2574 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 2575 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 2576 if (!CopyToReg) 2577 continue; 2578 2579 Chain = DAG.getCopyToReg( 2580 Chain, DL, 2581 CopyToReg->getOperand(1), 2582 SDValue(Result, i - 1), 2583 SDValue()); 2584 2585 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 2586 } 2587 2588 // Remove the old intrinsic from the chain 2589 DAG.ReplaceAllUsesOfValueWith( 2590 SDValue(Intr, Intr->getNumValues() - 1), 2591 Intr->getOperand(0)); 2592 2593 return Chain; 2594 } 2595 2596 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 2597 SDValue Op, 2598 const SDLoc &DL, 2599 EVT VT) const { 2600 return Op.getValueType().bitsLE(VT) ? 2601 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 2602 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 2603 } 2604 2605 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 2606 assert(Op.getValueType() == MVT::f16 && 2607 "Do not know how to custom lower FP_ROUND for non-f16 type"); 2608 2609 SDValue Src = Op.getOperand(0); 2610 EVT SrcVT = Src.getValueType(); 2611 if (SrcVT != MVT::f64) 2612 return Op; 2613 2614 SDLoc DL(Op); 2615 2616 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 2617 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 2618 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 2619 } 2620 2621 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 2622 SDLoc SL(Op); 2623 MachineFunction &MF = DAG.getMachineFunction(); 2624 SDValue Chain = Op.getOperand(0); 2625 2626 unsigned TrapID = Op.getOpcode() == ISD::DEBUGTRAP ? 2627 SISubtarget::TrapIDLLVMDebugTrap : SISubtarget::TrapIDLLVMTrap; 2628 2629 if (Subtarget->getTrapHandlerAbi() == SISubtarget::TrapHandlerAbiHsa && 2630 Subtarget->isTrapHandlerEnabled()) { 2631 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2632 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 2633 assert(UserSGPR != AMDGPU::NoRegister); 2634 2635 SDValue QueuePtr = CreateLiveInRegister( 2636 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 2637 2638 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 2639 2640 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 2641 QueuePtr, SDValue()); 2642 2643 SDValue Ops[] = { 2644 ToReg, 2645 DAG.getTargetConstant(TrapID, SL, MVT::i16), 2646 SGPR01, 2647 ToReg.getValue(1) 2648 }; 2649 2650 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 2651 } 2652 2653 switch (TrapID) { 2654 case SISubtarget::TrapIDLLVMTrap: 2655 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 2656 case SISubtarget::TrapIDLLVMDebugTrap: { 2657 DiagnosticInfoUnsupported NoTrap(*MF.getFunction(), 2658 "debugtrap handler not supported", 2659 Op.getDebugLoc(), 2660 DS_Warning); 2661 LLVMContext &Ctx = MF.getFunction()->getContext(); 2662 Ctx.diagnose(NoTrap); 2663 return Chain; 2664 } 2665 default: 2666 llvm_unreachable("unsupported trap handler type!"); 2667 } 2668 2669 return Chain; 2670 } 2671 2672 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 2673 SelectionDAG &DAG) const { 2674 // FIXME: Use inline constants (src_{shared, private}_base) instead. 2675 if (Subtarget->hasApertureRegs()) { 2676 unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ? 2677 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 2678 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 2679 unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ? 2680 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 2681 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 2682 unsigned Encoding = 2683 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 2684 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 2685 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 2686 2687 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 2688 SDValue ApertureReg = SDValue( 2689 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 2690 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 2691 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 2692 } 2693 2694 MachineFunction &MF = DAG.getMachineFunction(); 2695 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2696 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 2697 assert(UserSGPR != AMDGPU::NoRegister); 2698 2699 SDValue QueuePtr = CreateLiveInRegister( 2700 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 2701 2702 // Offset into amd_queue_t for group_segment_aperture_base_hi / 2703 // private_segment_aperture_base_hi. 2704 uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44; 2705 2706 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, QueuePtr, 2707 DAG.getConstant(StructOffset, DL, MVT::i64)); 2708 2709 // TODO: Use custom target PseudoSourceValue. 2710 // TODO: We should use the value from the IR intrinsic call, but it might not 2711 // be available and how do we get it? 2712 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()), 2713 AMDGPUASI.CONSTANT_ADDRESS)); 2714 2715 MachinePointerInfo PtrInfo(V, StructOffset); 2716 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 2717 MinAlign(64, StructOffset), 2718 MachineMemOperand::MODereferenceable | 2719 MachineMemOperand::MOInvariant); 2720 } 2721 2722 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 2723 SelectionDAG &DAG) const { 2724 SDLoc SL(Op); 2725 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 2726 2727 SDValue Src = ASC->getOperand(0); 2728 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 2729 2730 const AMDGPUTargetMachine &TM = 2731 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 2732 2733 // flat -> local/private 2734 if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) { 2735 unsigned DestAS = ASC->getDestAddressSpace(); 2736 2737 if (DestAS == AMDGPUASI.LOCAL_ADDRESS || 2738 DestAS == AMDGPUASI.PRIVATE_ADDRESS) { 2739 unsigned NullVal = TM.getNullPointerValue(DestAS); 2740 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 2741 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 2742 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 2743 2744 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 2745 NonNull, Ptr, SegmentNullPtr); 2746 } 2747 } 2748 2749 // local/private -> flat 2750 if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) { 2751 unsigned SrcAS = ASC->getSrcAddressSpace(); 2752 2753 if (SrcAS == AMDGPUASI.LOCAL_ADDRESS || 2754 SrcAS == AMDGPUASI.PRIVATE_ADDRESS) { 2755 unsigned NullVal = TM.getNullPointerValue(SrcAS); 2756 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 2757 2758 SDValue NonNull 2759 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 2760 2761 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 2762 SDValue CvtPtr 2763 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 2764 2765 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 2766 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 2767 FlatNullPtr); 2768 } 2769 } 2770 2771 // global <-> flat are no-ops and never emitted. 2772 2773 const MachineFunction &MF = DAG.getMachineFunction(); 2774 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 2775 *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 2776 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 2777 2778 return DAG.getUNDEF(ASC->getValueType(0)); 2779 } 2780 2781 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 2782 SelectionDAG &DAG) const { 2783 SDValue Idx = Op.getOperand(2); 2784 if (isa<ConstantSDNode>(Idx)) 2785 return SDValue(); 2786 2787 // Avoid stack access for dynamic indexing. 2788 SDLoc SL(Op); 2789 SDValue Vec = Op.getOperand(0); 2790 SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1)); 2791 2792 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 2793 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val); 2794 2795 // Convert vector index to bit-index. 2796 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, 2797 DAG.getConstant(16, SL, MVT::i32)); 2798 2799 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 2800 2801 SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32, 2802 DAG.getConstant(0xffff, SL, MVT::i32), 2803 ScaledIdx); 2804 2805 SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal); 2806 SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32, 2807 DAG.getNOT(SL, BFM, MVT::i32), BCVec); 2808 2809 SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS); 2810 return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI); 2811 } 2812 2813 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 2814 SelectionDAG &DAG) const { 2815 SDLoc SL(Op); 2816 2817 EVT ResultVT = Op.getValueType(); 2818 SDValue Vec = Op.getOperand(0); 2819 SDValue Idx = Op.getOperand(1); 2820 2821 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 2822 2823 // Make sure we we do any optimizations that will make it easier to fold 2824 // source modifiers before obscuring it with bit operations. 2825 2826 // XXX - Why doesn't this get called when vector_shuffle is expanded? 2827 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 2828 return Combined; 2829 2830 if (const ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) { 2831 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 2832 2833 if (CIdx->getZExtValue() == 1) { 2834 Result = DAG.getNode(ISD::SRL, SL, MVT::i32, Result, 2835 DAG.getConstant(16, SL, MVT::i32)); 2836 } else { 2837 assert(CIdx->getZExtValue() == 0); 2838 } 2839 2840 if (ResultVT.bitsLT(MVT::i32)) 2841 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result); 2842 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 2843 } 2844 2845 SDValue Sixteen = DAG.getConstant(16, SL, MVT::i32); 2846 2847 // Convert vector index to bit-index. 2848 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Sixteen); 2849 2850 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 2851 SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx); 2852 2853 SDValue Result = Elt; 2854 if (ResultVT.bitsLT(MVT::i32)) 2855 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result); 2856 2857 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 2858 } 2859 2860 bool 2861 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 2862 // We can fold offsets for anything that doesn't require a GOT relocation. 2863 return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS || 2864 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) && 2865 !shouldEmitGOTReloc(GA->getGlobal()); 2866 } 2867 2868 static SDValue 2869 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 2870 const SDLoc &DL, unsigned Offset, EVT PtrVT, 2871 unsigned GAFlags = SIInstrInfo::MO_NONE) { 2872 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 2873 // lowered to the following code sequence: 2874 // 2875 // For constant address space: 2876 // s_getpc_b64 s[0:1] 2877 // s_add_u32 s0, s0, $symbol 2878 // s_addc_u32 s1, s1, 0 2879 // 2880 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 2881 // a fixup or relocation is emitted to replace $symbol with a literal 2882 // constant, which is a pc-relative offset from the encoding of the $symbol 2883 // operand to the global variable. 2884 // 2885 // For global address space: 2886 // s_getpc_b64 s[0:1] 2887 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 2888 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 2889 // 2890 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 2891 // fixups or relocations are emitted to replace $symbol@*@lo and 2892 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 2893 // which is a 64-bit pc-relative offset from the encoding of the $symbol 2894 // operand to the global variable. 2895 // 2896 // What we want here is an offset from the value returned by s_getpc 2897 // (which is the address of the s_add_u32 instruction) to the global 2898 // variable, but since the encoding of $symbol starts 4 bytes after the start 2899 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 2900 // small. This requires us to add 4 to the global variable offset in order to 2901 // compute the correct address. 2902 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 2903 GAFlags); 2904 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 2905 GAFlags == SIInstrInfo::MO_NONE ? 2906 GAFlags : GAFlags + 1); 2907 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 2908 } 2909 2910 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 2911 SDValue Op, 2912 SelectionDAG &DAG) const { 2913 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 2914 2915 if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS && 2916 GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS) 2917 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 2918 2919 SDLoc DL(GSD); 2920 const GlobalValue *GV = GSD->getGlobal(); 2921 EVT PtrVT = Op.getValueType(); 2922 2923 if (shouldEmitFixup(GV)) 2924 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 2925 else if (shouldEmitPCReloc(GV)) 2926 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 2927 SIInstrInfo::MO_REL32); 2928 2929 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 2930 SIInstrInfo::MO_GOTPCREL32); 2931 2932 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 2933 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS); 2934 const DataLayout &DataLayout = DAG.getDataLayout(); 2935 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 2936 // FIXME: Use a PseudoSourceValue once those can be assigned an address space. 2937 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 2938 2939 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 2940 MachineMemOperand::MODereferenceable | 2941 MachineMemOperand::MOInvariant); 2942 } 2943 2944 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 2945 const SDLoc &DL, SDValue V) const { 2946 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 2947 // the destination register. 2948 // 2949 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 2950 // so we will end up with redundant moves to m0. 2951 // 2952 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 2953 2954 // A Null SDValue creates a glue result. 2955 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 2956 V, Chain); 2957 return SDValue(M0, 0); 2958 } 2959 2960 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 2961 SDValue Op, 2962 MVT VT, 2963 unsigned Offset) const { 2964 SDLoc SL(Op); 2965 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 2966 DAG.getEntryNode(), Offset, false); 2967 // The local size values will have the hi 16-bits as zero. 2968 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 2969 DAG.getValueType(VT)); 2970 } 2971 2972 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 2973 EVT VT) { 2974 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(), 2975 "non-hsa intrinsic with hsa target", 2976 DL.getDebugLoc()); 2977 DAG.getContext()->diagnose(BadIntrin); 2978 return DAG.getUNDEF(VT); 2979 } 2980 2981 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 2982 EVT VT) { 2983 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(), 2984 "intrinsic not supported on subtarget", 2985 DL.getDebugLoc()); 2986 DAG.getContext()->diagnose(BadIntrin); 2987 return DAG.getUNDEF(VT); 2988 } 2989 2990 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 2991 SelectionDAG &DAG) const { 2992 MachineFunction &MF = DAG.getMachineFunction(); 2993 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 2994 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2995 2996 EVT VT = Op.getValueType(); 2997 SDLoc DL(Op); 2998 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2999 3000 // TODO: Should this propagate fast-math-flags? 3001 3002 switch (IntrinsicID) { 3003 case Intrinsic::amdgcn_implicit_buffer_ptr: { 3004 if (getSubtarget()->isAmdCodeObjectV2(MF)) 3005 return emitNonHSAIntrinsicError(DAG, DL, VT); 3006 3007 unsigned Reg = TRI->getPreloadedValue(MF, 3008 SIRegisterInfo::IMPLICIT_BUFFER_PTR); 3009 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT); 3010 } 3011 case Intrinsic::amdgcn_dispatch_ptr: 3012 case Intrinsic::amdgcn_queue_ptr: { 3013 if (!Subtarget->isAmdCodeObjectV2(MF)) { 3014 DiagnosticInfoUnsupported BadIntrin( 3015 *MF.getFunction(), "unsupported hsa intrinsic without hsa target", 3016 DL.getDebugLoc()); 3017 DAG.getContext()->diagnose(BadIntrin); 3018 return DAG.getUNDEF(VT); 3019 } 3020 3021 auto Reg = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 3022 SIRegisterInfo::DISPATCH_PTR : SIRegisterInfo::QUEUE_PTR; 3023 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, 3024 TRI->getPreloadedValue(MF, Reg), VT); 3025 } 3026 case Intrinsic::amdgcn_implicitarg_ptr: { 3027 unsigned offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT); 3028 return lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), offset); 3029 } 3030 case Intrinsic::amdgcn_kernarg_segment_ptr: { 3031 unsigned Reg 3032 = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR); 3033 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT); 3034 } 3035 case Intrinsic::amdgcn_dispatch_id: { 3036 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_ID); 3037 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT); 3038 } 3039 case Intrinsic::amdgcn_rcp: 3040 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 3041 case Intrinsic::amdgcn_rsq: 3042 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 3043 case Intrinsic::amdgcn_rsq_legacy: 3044 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 3045 return emitRemovedIntrinsicError(DAG, DL, VT); 3046 3047 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 3048 case Intrinsic::amdgcn_rcp_legacy: 3049 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 3050 return emitRemovedIntrinsicError(DAG, DL, VT); 3051 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 3052 case Intrinsic::amdgcn_rsq_clamp: { 3053 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 3054 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 3055 3056 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 3057 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 3058 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 3059 3060 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 3061 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 3062 DAG.getConstantFP(Max, DL, VT)); 3063 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 3064 DAG.getConstantFP(Min, DL, VT)); 3065 } 3066 case Intrinsic::r600_read_ngroups_x: 3067 if (Subtarget->isAmdHsaOS()) 3068 return emitNonHSAIntrinsicError(DAG, DL, VT); 3069 3070 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3071 SI::KernelInputOffsets::NGROUPS_X, false); 3072 case Intrinsic::r600_read_ngroups_y: 3073 if (Subtarget->isAmdHsaOS()) 3074 return emitNonHSAIntrinsicError(DAG, DL, VT); 3075 3076 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3077 SI::KernelInputOffsets::NGROUPS_Y, false); 3078 case Intrinsic::r600_read_ngroups_z: 3079 if (Subtarget->isAmdHsaOS()) 3080 return emitNonHSAIntrinsicError(DAG, DL, VT); 3081 3082 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3083 SI::KernelInputOffsets::NGROUPS_Z, false); 3084 case Intrinsic::r600_read_global_size_x: 3085 if (Subtarget->isAmdHsaOS()) 3086 return emitNonHSAIntrinsicError(DAG, DL, VT); 3087 3088 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3089 SI::KernelInputOffsets::GLOBAL_SIZE_X, false); 3090 case Intrinsic::r600_read_global_size_y: 3091 if (Subtarget->isAmdHsaOS()) 3092 return emitNonHSAIntrinsicError(DAG, DL, VT); 3093 3094 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3095 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false); 3096 case Intrinsic::r600_read_global_size_z: 3097 if (Subtarget->isAmdHsaOS()) 3098 return emitNonHSAIntrinsicError(DAG, DL, VT); 3099 3100 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3101 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false); 3102 case Intrinsic::r600_read_local_size_x: 3103 if (Subtarget->isAmdHsaOS()) 3104 return emitNonHSAIntrinsicError(DAG, DL, VT); 3105 3106 return lowerImplicitZextParam(DAG, Op, MVT::i16, 3107 SI::KernelInputOffsets::LOCAL_SIZE_X); 3108 case Intrinsic::r600_read_local_size_y: 3109 if (Subtarget->isAmdHsaOS()) 3110 return emitNonHSAIntrinsicError(DAG, DL, VT); 3111 3112 return lowerImplicitZextParam(DAG, Op, MVT::i16, 3113 SI::KernelInputOffsets::LOCAL_SIZE_Y); 3114 case Intrinsic::r600_read_local_size_z: 3115 if (Subtarget->isAmdHsaOS()) 3116 return emitNonHSAIntrinsicError(DAG, DL, VT); 3117 3118 return lowerImplicitZextParam(DAG, Op, MVT::i16, 3119 SI::KernelInputOffsets::LOCAL_SIZE_Z); 3120 case Intrinsic::amdgcn_workgroup_id_x: 3121 case Intrinsic::r600_read_tgid_x: 3122 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass, 3123 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT); 3124 case Intrinsic::amdgcn_workgroup_id_y: 3125 case Intrinsic::r600_read_tgid_y: 3126 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass, 3127 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT); 3128 case Intrinsic::amdgcn_workgroup_id_z: 3129 case Intrinsic::r600_read_tgid_z: 3130 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass, 3131 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT); 3132 case Intrinsic::amdgcn_workitem_id_x: 3133 case Intrinsic::r600_read_tidig_x: 3134 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass, 3135 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT); 3136 case Intrinsic::amdgcn_workitem_id_y: 3137 case Intrinsic::r600_read_tidig_y: 3138 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass, 3139 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT); 3140 case Intrinsic::amdgcn_workitem_id_z: 3141 case Intrinsic::r600_read_tidig_z: 3142 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass, 3143 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT); 3144 case AMDGPUIntrinsic::SI_load_const: { 3145 SDValue Ops[] = { 3146 Op.getOperand(1), 3147 Op.getOperand(2) 3148 }; 3149 3150 MachineMemOperand *MMO = MF.getMachineMemOperand( 3151 MachinePointerInfo(), 3152 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3153 MachineMemOperand::MOInvariant, 3154 VT.getStoreSize(), 4); 3155 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL, 3156 Op->getVTList(), Ops, VT, MMO); 3157 } 3158 case Intrinsic::amdgcn_fdiv_fast: 3159 return lowerFDIV_FAST(Op, DAG); 3160 case Intrinsic::amdgcn_interp_mov: { 3161 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 3162 SDValue Glue = M0.getValue(1); 3163 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1), 3164 Op.getOperand(2), Op.getOperand(3), Glue); 3165 } 3166 case Intrinsic::amdgcn_interp_p1: { 3167 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 3168 SDValue Glue = M0.getValue(1); 3169 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1), 3170 Op.getOperand(2), Op.getOperand(3), Glue); 3171 } 3172 case Intrinsic::amdgcn_interp_p2: { 3173 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 3174 SDValue Glue = SDValue(M0.getNode(), 1); 3175 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1), 3176 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4), 3177 Glue); 3178 } 3179 case Intrinsic::amdgcn_sin: 3180 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 3181 3182 case Intrinsic::amdgcn_cos: 3183 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 3184 3185 case Intrinsic::amdgcn_log_clamp: { 3186 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 3187 return SDValue(); 3188 3189 DiagnosticInfoUnsupported BadIntrin( 3190 *MF.getFunction(), "intrinsic not supported on subtarget", 3191 DL.getDebugLoc()); 3192 DAG.getContext()->diagnose(BadIntrin); 3193 return DAG.getUNDEF(VT); 3194 } 3195 case Intrinsic::amdgcn_ldexp: 3196 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 3197 Op.getOperand(1), Op.getOperand(2)); 3198 3199 case Intrinsic::amdgcn_fract: 3200 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 3201 3202 case Intrinsic::amdgcn_class: 3203 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 3204 Op.getOperand(1), Op.getOperand(2)); 3205 case Intrinsic::amdgcn_div_fmas: 3206 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 3207 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 3208 Op.getOperand(4)); 3209 3210 case Intrinsic::amdgcn_div_fixup: 3211 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 3212 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3213 3214 case Intrinsic::amdgcn_trig_preop: 3215 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 3216 Op.getOperand(1), Op.getOperand(2)); 3217 case Intrinsic::amdgcn_div_scale: { 3218 // 3rd parameter required to be a constant. 3219 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 3220 if (!Param) 3221 return DAG.getUNDEF(VT); 3222 3223 // Translate to the operands expected by the machine instruction. The 3224 // first parameter must be the same as the first instruction. 3225 SDValue Numerator = Op.getOperand(1); 3226 SDValue Denominator = Op.getOperand(2); 3227 3228 // Note this order is opposite of the machine instruction's operations, 3229 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 3230 // intrinsic has the numerator as the first operand to match a normal 3231 // division operation. 3232 3233 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 3234 3235 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 3236 Denominator, Numerator); 3237 } 3238 case Intrinsic::amdgcn_icmp: { 3239 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 3240 if (!CD) 3241 return DAG.getUNDEF(VT); 3242 3243 int CondCode = CD->getSExtValue(); 3244 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 3245 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 3246 return DAG.getUNDEF(VT); 3247 3248 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 3249 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 3250 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 3251 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 3252 } 3253 case Intrinsic::amdgcn_fcmp: { 3254 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 3255 if (!CD) 3256 return DAG.getUNDEF(VT); 3257 3258 int CondCode = CD->getSExtValue(); 3259 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 3260 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) 3261 return DAG.getUNDEF(VT); 3262 3263 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 3264 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 3265 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 3266 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 3267 } 3268 case Intrinsic::amdgcn_fmed3: 3269 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 3270 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3271 case Intrinsic::amdgcn_fmul_legacy: 3272 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 3273 Op.getOperand(1), Op.getOperand(2)); 3274 case Intrinsic::amdgcn_sffbh: 3275 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 3276 case Intrinsic::amdgcn_sbfe: 3277 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 3278 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3279 case Intrinsic::amdgcn_ubfe: 3280 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 3281 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3282 case Intrinsic::amdgcn_cvt_pkrtz: { 3283 // FIXME: Stop adding cast if v2f16 legal. 3284 EVT VT = Op.getValueType(); 3285 SDValue Node = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, DL, MVT::i32, 3286 Op.getOperand(1), Op.getOperand(2)); 3287 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 3288 } 3289 default: 3290 return Op; 3291 } 3292 } 3293 3294 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 3295 SelectionDAG &DAG) const { 3296 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 3297 SDLoc DL(Op); 3298 MachineFunction &MF = DAG.getMachineFunction(); 3299 3300 switch (IntrID) { 3301 case Intrinsic::amdgcn_atomic_inc: 3302 case Intrinsic::amdgcn_atomic_dec: { 3303 MemSDNode *M = cast<MemSDNode>(Op); 3304 unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ? 3305 AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC; 3306 SDValue Ops[] = { 3307 M->getOperand(0), // Chain 3308 M->getOperand(2), // Ptr 3309 M->getOperand(3) // Value 3310 }; 3311 3312 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 3313 M->getMemoryVT(), M->getMemOperand()); 3314 } 3315 case Intrinsic::amdgcn_buffer_load: 3316 case Intrinsic::amdgcn_buffer_load_format: { 3317 SDValue Ops[] = { 3318 Op.getOperand(0), // Chain 3319 Op.getOperand(2), // rsrc 3320 Op.getOperand(3), // vindex 3321 Op.getOperand(4), // offset 3322 Op.getOperand(5), // glc 3323 Op.getOperand(6) // slc 3324 }; 3325 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 3326 3327 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 3328 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 3329 EVT VT = Op.getValueType(); 3330 EVT IntVT = VT.changeTypeToInteger(); 3331 3332 MachineMemOperand *MMO = MF.getMachineMemOperand( 3333 MachinePointerInfo(MFI->getBufferPSV()), 3334 MachineMemOperand::MOLoad, 3335 VT.getStoreSize(), VT.getStoreSize()); 3336 3337 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, MMO); 3338 } 3339 case Intrinsic::amdgcn_tbuffer_load: { 3340 SDValue Ops[] = { 3341 Op.getOperand(0), // Chain 3342 Op.getOperand(2), // rsrc 3343 Op.getOperand(3), // vindex 3344 Op.getOperand(4), // voffset 3345 Op.getOperand(5), // soffset 3346 Op.getOperand(6), // offset 3347 Op.getOperand(7), // dfmt 3348 Op.getOperand(8), // nfmt 3349 Op.getOperand(9), // glc 3350 Op.getOperand(10) // slc 3351 }; 3352 3353 EVT VT = Op.getOperand(2).getValueType(); 3354 3355 MachineMemOperand *MMO = MF.getMachineMemOperand( 3356 MachinePointerInfo(), 3357 MachineMemOperand::MOLoad, 3358 VT.getStoreSize(), VT.getStoreSize()); 3359 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 3360 Op->getVTList(), Ops, VT, MMO); 3361 } 3362 // Basic sample. 3363 case Intrinsic::amdgcn_image_sample: 3364 case Intrinsic::amdgcn_image_sample_cl: 3365 case Intrinsic::amdgcn_image_sample_d: 3366 case Intrinsic::amdgcn_image_sample_d_cl: 3367 case Intrinsic::amdgcn_image_sample_l: 3368 case Intrinsic::amdgcn_image_sample_b: 3369 case Intrinsic::amdgcn_image_sample_b_cl: 3370 case Intrinsic::amdgcn_image_sample_lz: 3371 case Intrinsic::amdgcn_image_sample_cd: 3372 case Intrinsic::amdgcn_image_sample_cd_cl: 3373 3374 // Sample with comparison. 3375 case Intrinsic::amdgcn_image_sample_c: 3376 case Intrinsic::amdgcn_image_sample_c_cl: 3377 case Intrinsic::amdgcn_image_sample_c_d: 3378 case Intrinsic::amdgcn_image_sample_c_d_cl: 3379 case Intrinsic::amdgcn_image_sample_c_l: 3380 case Intrinsic::amdgcn_image_sample_c_b: 3381 case Intrinsic::amdgcn_image_sample_c_b_cl: 3382 case Intrinsic::amdgcn_image_sample_c_lz: 3383 case Intrinsic::amdgcn_image_sample_c_cd: 3384 case Intrinsic::amdgcn_image_sample_c_cd_cl: 3385 3386 // Sample with offsets. 3387 case Intrinsic::amdgcn_image_sample_o: 3388 case Intrinsic::amdgcn_image_sample_cl_o: 3389 case Intrinsic::amdgcn_image_sample_d_o: 3390 case Intrinsic::amdgcn_image_sample_d_cl_o: 3391 case Intrinsic::amdgcn_image_sample_l_o: 3392 case Intrinsic::amdgcn_image_sample_b_o: 3393 case Intrinsic::amdgcn_image_sample_b_cl_o: 3394 case Intrinsic::amdgcn_image_sample_lz_o: 3395 case Intrinsic::amdgcn_image_sample_cd_o: 3396 case Intrinsic::amdgcn_image_sample_cd_cl_o: 3397 3398 // Sample with comparison and offsets. 3399 case Intrinsic::amdgcn_image_sample_c_o: 3400 case Intrinsic::amdgcn_image_sample_c_cl_o: 3401 case Intrinsic::amdgcn_image_sample_c_d_o: 3402 case Intrinsic::amdgcn_image_sample_c_d_cl_o: 3403 case Intrinsic::amdgcn_image_sample_c_l_o: 3404 case Intrinsic::amdgcn_image_sample_c_b_o: 3405 case Intrinsic::amdgcn_image_sample_c_b_cl_o: 3406 case Intrinsic::amdgcn_image_sample_c_lz_o: 3407 case Intrinsic::amdgcn_image_sample_c_cd_o: 3408 case Intrinsic::amdgcn_image_sample_c_cd_cl_o: 3409 3410 case Intrinsic::amdgcn_image_getlod: { 3411 // Replace dmask with everything disabled with undef. 3412 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(5)); 3413 if (!DMask || DMask->isNullValue()) { 3414 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 3415 return DAG.getMergeValues({ Undef, Op.getOperand(0) }, SDLoc(Op)); 3416 } 3417 3418 return SDValue(); 3419 } 3420 default: 3421 return SDValue(); 3422 } 3423 } 3424 3425 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 3426 SelectionDAG &DAG) const { 3427 SDLoc DL(Op); 3428 SDValue Chain = Op.getOperand(0); 3429 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 3430 MachineFunction &MF = DAG.getMachineFunction(); 3431 3432 switch (IntrinsicID) { 3433 case Intrinsic::amdgcn_exp: { 3434 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 3435 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 3436 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8)); 3437 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9)); 3438 3439 const SDValue Ops[] = { 3440 Chain, 3441 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 3442 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 3443 Op.getOperand(4), // src0 3444 Op.getOperand(5), // src1 3445 Op.getOperand(6), // src2 3446 Op.getOperand(7), // src3 3447 DAG.getTargetConstant(0, DL, MVT::i1), // compr 3448 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 3449 }; 3450 3451 unsigned Opc = Done->isNullValue() ? 3452 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 3453 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 3454 } 3455 case Intrinsic::amdgcn_exp_compr: { 3456 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 3457 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 3458 SDValue Src0 = Op.getOperand(4); 3459 SDValue Src1 = Op.getOperand(5); 3460 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 3461 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7)); 3462 3463 SDValue Undef = DAG.getUNDEF(MVT::f32); 3464 const SDValue Ops[] = { 3465 Chain, 3466 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 3467 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 3468 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), 3469 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), 3470 Undef, // src2 3471 Undef, // src3 3472 DAG.getTargetConstant(1, DL, MVT::i1), // compr 3473 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 3474 }; 3475 3476 unsigned Opc = Done->isNullValue() ? 3477 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 3478 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 3479 } 3480 case Intrinsic::amdgcn_s_sendmsg: 3481 case Intrinsic::amdgcn_s_sendmsghalt: { 3482 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ? 3483 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT; 3484 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 3485 SDValue Glue = Chain.getValue(1); 3486 return DAG.getNode(NodeOp, DL, MVT::Other, Chain, 3487 Op.getOperand(2), Glue); 3488 } 3489 case Intrinsic::amdgcn_init_exec: { 3490 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain, 3491 Op.getOperand(2)); 3492 } 3493 case Intrinsic::amdgcn_init_exec_from_input: { 3494 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain, 3495 Op.getOperand(2), Op.getOperand(3)); 3496 } 3497 case AMDGPUIntrinsic::AMDGPU_kill: { 3498 SDValue Src = Op.getOperand(2); 3499 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) { 3500 if (!K->isNegative()) 3501 return Chain; 3502 3503 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32); 3504 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne); 3505 } 3506 3507 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src); 3508 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast); 3509 } 3510 case Intrinsic::amdgcn_s_barrier: { 3511 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 3512 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 3513 unsigned WGSize = ST.getFlatWorkGroupSizes(*MF.getFunction()).second; 3514 if (WGSize <= ST.getWavefrontSize()) 3515 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 3516 Op.getOperand(0)), 0); 3517 } 3518 return SDValue(); 3519 }; 3520 case AMDGPUIntrinsic::SI_tbuffer_store: { 3521 3522 // Extract vindex and voffset from vaddr as appropriate 3523 const ConstantSDNode *OffEn = cast<ConstantSDNode>(Op.getOperand(10)); 3524 const ConstantSDNode *IdxEn = cast<ConstantSDNode>(Op.getOperand(11)); 3525 SDValue VAddr = Op.getOperand(5); 3526 3527 SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32); 3528 3529 assert(!(OffEn->isOne() && IdxEn->isOne()) && 3530 "Legacy intrinsic doesn't support both offset and index - use new version"); 3531 3532 SDValue VIndex = IdxEn->isOne() ? VAddr : Zero; 3533 SDValue VOffset = OffEn->isOne() ? VAddr : Zero; 3534 3535 // Deal with the vec-3 case 3536 const ConstantSDNode *NumChannels = cast<ConstantSDNode>(Op.getOperand(4)); 3537 auto Opcode = NumChannels->getZExtValue() == 3 ? 3538 AMDGPUISD::TBUFFER_STORE_FORMAT_X3 : AMDGPUISD::TBUFFER_STORE_FORMAT; 3539 3540 SDValue Ops[] = { 3541 Chain, 3542 Op.getOperand(3), // vdata 3543 Op.getOperand(2), // rsrc 3544 VIndex, 3545 VOffset, 3546 Op.getOperand(6), // soffset 3547 Op.getOperand(7), // inst_offset 3548 Op.getOperand(8), // dfmt 3549 Op.getOperand(9), // nfmt 3550 Op.getOperand(12), // glc 3551 Op.getOperand(13), // slc 3552 }; 3553 3554 assert((cast<ConstantSDNode>(Op.getOperand(14)))->getZExtValue() == 0 && 3555 "Value of tfe other than zero is unsupported"); 3556 3557 EVT VT = Op.getOperand(3).getValueType(); 3558 MachineMemOperand *MMO = MF.getMachineMemOperand( 3559 MachinePointerInfo(), 3560 MachineMemOperand::MOStore, 3561 VT.getStoreSize(), 4); 3562 return DAG.getMemIntrinsicNode(Opcode, DL, 3563 Op->getVTList(), Ops, VT, MMO); 3564 } 3565 3566 case Intrinsic::amdgcn_tbuffer_store: { 3567 SDValue Ops[] = { 3568 Chain, 3569 Op.getOperand(2), // vdata 3570 Op.getOperand(3), // rsrc 3571 Op.getOperand(4), // vindex 3572 Op.getOperand(5), // voffset 3573 Op.getOperand(6), // soffset 3574 Op.getOperand(7), // offset 3575 Op.getOperand(8), // dfmt 3576 Op.getOperand(9), // nfmt 3577 Op.getOperand(10), // glc 3578 Op.getOperand(11) // slc 3579 }; 3580 EVT VT = Op.getOperand(3).getValueType(); 3581 MachineMemOperand *MMO = MF.getMachineMemOperand( 3582 MachinePointerInfo(), 3583 MachineMemOperand::MOStore, 3584 VT.getStoreSize(), 4); 3585 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL, 3586 Op->getVTList(), Ops, VT, MMO); 3587 } 3588 3589 default: 3590 return Op; 3591 } 3592 } 3593 3594 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 3595 SDLoc DL(Op); 3596 LoadSDNode *Load = cast<LoadSDNode>(Op); 3597 ISD::LoadExtType ExtType = Load->getExtensionType(); 3598 EVT MemVT = Load->getMemoryVT(); 3599 3600 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 3601 // FIXME: Copied from PPC 3602 // First, load into 32 bits, then truncate to 1 bit. 3603 3604 SDValue Chain = Load->getChain(); 3605 SDValue BasePtr = Load->getBasePtr(); 3606 MachineMemOperand *MMO = Load->getMemOperand(); 3607 3608 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 3609 3610 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 3611 BasePtr, RealMemVT, MMO); 3612 3613 SDValue Ops[] = { 3614 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 3615 NewLD.getValue(1) 3616 }; 3617 3618 return DAG.getMergeValues(Ops, DL); 3619 } 3620 3621 if (!MemVT.isVector()) 3622 return SDValue(); 3623 3624 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 3625 "Custom lowering for non-i32 vectors hasn't been implemented."); 3626 3627 unsigned AS = Load->getAddressSpace(); 3628 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 3629 AS, Load->getAlignment())) { 3630 SDValue Ops[2]; 3631 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 3632 return DAG.getMergeValues(Ops, DL); 3633 } 3634 3635 MachineFunction &MF = DAG.getMachineFunction(); 3636 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 3637 // If there is a possibilty that flat instruction access scratch memory 3638 // then we need to use the same legalization rules we use for private. 3639 if (AS == AMDGPUASI.FLAT_ADDRESS) 3640 AS = MFI->hasFlatScratchInit() ? 3641 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS; 3642 3643 unsigned NumElements = MemVT.getVectorNumElements(); 3644 if (AS == AMDGPUASI.CONSTANT_ADDRESS) { 3645 if (isMemOpUniform(Load)) 3646 return SDValue(); 3647 // Non-uniform loads will be selected to MUBUF instructions, so they 3648 // have the same legalization requirements as global and private 3649 // loads. 3650 // 3651 } 3652 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS) { 3653 if (Subtarget->getScalarizeGlobalBehavior() && isMemOpUniform(Load) && 3654 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load)) 3655 return SDValue(); 3656 // Non-uniform loads will be selected to MUBUF instructions, so they 3657 // have the same legalization requirements as global and private 3658 // loads. 3659 // 3660 } 3661 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS || 3662 AS == AMDGPUASI.FLAT_ADDRESS) { 3663 if (NumElements > 4) 3664 return SplitVectorLoad(Op, DAG); 3665 // v4 loads are supported for private and global memory. 3666 return SDValue(); 3667 } 3668 if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 3669 // Depending on the setting of the private_element_size field in the 3670 // resource descriptor, we can only make private accesses up to a certain 3671 // size. 3672 switch (Subtarget->getMaxPrivateElementSize()) { 3673 case 4: 3674 return scalarizeVectorLoad(Load, DAG); 3675 case 8: 3676 if (NumElements > 2) 3677 return SplitVectorLoad(Op, DAG); 3678 return SDValue(); 3679 case 16: 3680 // Same as global/flat 3681 if (NumElements > 4) 3682 return SplitVectorLoad(Op, DAG); 3683 return SDValue(); 3684 default: 3685 llvm_unreachable("unsupported private_element_size"); 3686 } 3687 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 3688 if (NumElements > 2) 3689 return SplitVectorLoad(Op, DAG); 3690 3691 if (NumElements == 2) 3692 return SDValue(); 3693 3694 // If properly aligned, if we split we might be able to use ds_read_b64. 3695 return SplitVectorLoad(Op, DAG); 3696 } 3697 return SDValue(); 3698 } 3699 3700 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3701 if (Op.getValueType() != MVT::i64) 3702 return SDValue(); 3703 3704 SDLoc DL(Op); 3705 SDValue Cond = Op.getOperand(0); 3706 3707 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 3708 SDValue One = DAG.getConstant(1, DL, MVT::i32); 3709 3710 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 3711 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 3712 3713 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 3714 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 3715 3716 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 3717 3718 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 3719 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 3720 3721 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 3722 3723 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 3724 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res); 3725 } 3726 3727 // Catch division cases where we can use shortcuts with rcp and rsq 3728 // instructions. 3729 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 3730 SelectionDAG &DAG) const { 3731 SDLoc SL(Op); 3732 SDValue LHS = Op.getOperand(0); 3733 SDValue RHS = Op.getOperand(1); 3734 EVT VT = Op.getValueType(); 3735 const SDNodeFlags Flags = Op->getFlags(); 3736 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || 3737 Flags.hasUnsafeAlgebra() || Flags.hasAllowReciprocal(); 3738 3739 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals()) 3740 return SDValue(); 3741 3742 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 3743 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) { 3744 if (CLHS->isExactlyValue(1.0)) { 3745 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 3746 // the CI documentation has a worst case error of 1 ulp. 3747 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 3748 // use it as long as we aren't trying to use denormals. 3749 // 3750 // v_rcp_f16 and v_rsq_f16 DO support denormals. 3751 3752 // 1.0 / sqrt(x) -> rsq(x) 3753 3754 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 3755 // error seems really high at 2^29 ULP. 3756 if (RHS.getOpcode() == ISD::FSQRT) 3757 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 3758 3759 // 1.0 / x -> rcp(x) 3760 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 3761 } 3762 3763 // Same as for 1.0, but expand the sign out of the constant. 3764 if (CLHS->isExactlyValue(-1.0)) { 3765 // -1.0 / x -> rcp (fneg x) 3766 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 3767 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 3768 } 3769 } 3770 } 3771 3772 if (Unsafe) { 3773 // Turn into multiply by the reciprocal. 3774 // x / y -> x * (1.0 / y) 3775 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 3776 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 3777 } 3778 3779 return SDValue(); 3780 } 3781 3782 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 3783 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 3784 if (GlueChain->getNumValues() <= 1) { 3785 return DAG.getNode(Opcode, SL, VT, A, B); 3786 } 3787 3788 assert(GlueChain->getNumValues() == 3); 3789 3790 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 3791 switch (Opcode) { 3792 default: llvm_unreachable("no chain equivalent for opcode"); 3793 case ISD::FMUL: 3794 Opcode = AMDGPUISD::FMUL_W_CHAIN; 3795 break; 3796 } 3797 3798 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 3799 GlueChain.getValue(2)); 3800 } 3801 3802 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 3803 EVT VT, SDValue A, SDValue B, SDValue C, 3804 SDValue GlueChain) { 3805 if (GlueChain->getNumValues() <= 1) { 3806 return DAG.getNode(Opcode, SL, VT, A, B, C); 3807 } 3808 3809 assert(GlueChain->getNumValues() == 3); 3810 3811 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 3812 switch (Opcode) { 3813 default: llvm_unreachable("no chain equivalent for opcode"); 3814 case ISD::FMA: 3815 Opcode = AMDGPUISD::FMA_W_CHAIN; 3816 break; 3817 } 3818 3819 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 3820 GlueChain.getValue(2)); 3821 } 3822 3823 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 3824 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 3825 return FastLowered; 3826 3827 SDLoc SL(Op); 3828 SDValue Src0 = Op.getOperand(0); 3829 SDValue Src1 = Op.getOperand(1); 3830 3831 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 3832 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 3833 3834 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 3835 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 3836 3837 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 3838 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 3839 3840 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 3841 } 3842 3843 // Faster 2.5 ULP division that does not support denormals. 3844 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 3845 SDLoc SL(Op); 3846 SDValue LHS = Op.getOperand(1); 3847 SDValue RHS = Op.getOperand(2); 3848 3849 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 3850 3851 const APFloat K0Val(BitsToFloat(0x6f800000)); 3852 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 3853 3854 const APFloat K1Val(BitsToFloat(0x2f800000)); 3855 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 3856 3857 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 3858 3859 EVT SetCCVT = 3860 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 3861 3862 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 3863 3864 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 3865 3866 // TODO: Should this propagate fast-math-flags? 3867 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 3868 3869 // rcp does not support denormals. 3870 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 3871 3872 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 3873 3874 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 3875 } 3876 3877 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 3878 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 3879 return FastLowered; 3880 3881 SDLoc SL(Op); 3882 SDValue LHS = Op.getOperand(0); 3883 SDValue RHS = Op.getOperand(1); 3884 3885 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 3886 3887 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 3888 3889 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 3890 RHS, RHS, LHS); 3891 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 3892 LHS, RHS, LHS); 3893 3894 // Denominator is scaled to not be denormal, so using rcp is ok. 3895 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 3896 DenominatorScaled); 3897 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 3898 DenominatorScaled); 3899 3900 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 3901 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 3902 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 3903 3904 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 3905 3906 if (!Subtarget->hasFP32Denormals()) { 3907 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 3908 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 3909 SL, MVT::i32); 3910 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 3911 DAG.getEntryNode(), 3912 EnableDenormValue, BitField); 3913 SDValue Ops[3] = { 3914 NegDivScale0, 3915 EnableDenorm.getValue(0), 3916 EnableDenorm.getValue(1) 3917 }; 3918 3919 NegDivScale0 = DAG.getMergeValues(Ops, SL); 3920 } 3921 3922 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 3923 ApproxRcp, One, NegDivScale0); 3924 3925 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 3926 ApproxRcp, Fma0); 3927 3928 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 3929 Fma1, Fma1); 3930 3931 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 3932 NumeratorScaled, Mul); 3933 3934 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 3935 3936 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 3937 NumeratorScaled, Fma3); 3938 3939 if (!Subtarget->hasFP32Denormals()) { 3940 const SDValue DisableDenormValue = 3941 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 3942 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 3943 Fma4.getValue(1), 3944 DisableDenormValue, 3945 BitField, 3946 Fma4.getValue(2)); 3947 3948 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 3949 DisableDenorm, DAG.getRoot()); 3950 DAG.setRoot(OutputChain); 3951 } 3952 3953 SDValue Scale = NumeratorScaled.getValue(1); 3954 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 3955 Fma4, Fma1, Fma3, Scale); 3956 3957 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 3958 } 3959 3960 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 3961 if (DAG.getTarget().Options.UnsafeFPMath) 3962 return lowerFastUnsafeFDIV(Op, DAG); 3963 3964 SDLoc SL(Op); 3965 SDValue X = Op.getOperand(0); 3966 SDValue Y = Op.getOperand(1); 3967 3968 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 3969 3970 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 3971 3972 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 3973 3974 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 3975 3976 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 3977 3978 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 3979 3980 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 3981 3982 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 3983 3984 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 3985 3986 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 3987 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 3988 3989 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 3990 NegDivScale0, Mul, DivScale1); 3991 3992 SDValue Scale; 3993 3994 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) { 3995 // Workaround a hardware bug on SI where the condition output from div_scale 3996 // is not usable. 3997 3998 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 3999 4000 // Figure out if the scale to use for div_fmas. 4001 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 4002 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 4003 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 4004 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 4005 4006 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 4007 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 4008 4009 SDValue Scale0Hi 4010 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 4011 SDValue Scale1Hi 4012 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 4013 4014 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 4015 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 4016 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 4017 } else { 4018 Scale = DivScale1.getValue(1); 4019 } 4020 4021 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 4022 Fma4, Fma3, Mul, Scale); 4023 4024 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 4025 } 4026 4027 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 4028 EVT VT = Op.getValueType(); 4029 4030 if (VT == MVT::f32) 4031 return LowerFDIV32(Op, DAG); 4032 4033 if (VT == MVT::f64) 4034 return LowerFDIV64(Op, DAG); 4035 4036 if (VT == MVT::f16) 4037 return LowerFDIV16(Op, DAG); 4038 4039 llvm_unreachable("Unexpected type for fdiv"); 4040 } 4041 4042 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 4043 SDLoc DL(Op); 4044 StoreSDNode *Store = cast<StoreSDNode>(Op); 4045 EVT VT = Store->getMemoryVT(); 4046 4047 if (VT == MVT::i1) { 4048 return DAG.getTruncStore(Store->getChain(), DL, 4049 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 4050 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 4051 } 4052 4053 assert(VT.isVector() && 4054 Store->getValue().getValueType().getScalarType() == MVT::i32); 4055 4056 unsigned AS = Store->getAddressSpace(); 4057 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 4058 AS, Store->getAlignment())) { 4059 return expandUnalignedStore(Store, DAG); 4060 } 4061 4062 MachineFunction &MF = DAG.getMachineFunction(); 4063 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4064 // If there is a possibilty that flat instruction access scratch memory 4065 // then we need to use the same legalization rules we use for private. 4066 if (AS == AMDGPUASI.FLAT_ADDRESS) 4067 AS = MFI->hasFlatScratchInit() ? 4068 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS; 4069 4070 unsigned NumElements = VT.getVectorNumElements(); 4071 if (AS == AMDGPUASI.GLOBAL_ADDRESS || 4072 AS == AMDGPUASI.FLAT_ADDRESS) { 4073 if (NumElements > 4) 4074 return SplitVectorStore(Op, DAG); 4075 return SDValue(); 4076 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 4077 switch (Subtarget->getMaxPrivateElementSize()) { 4078 case 4: 4079 return scalarizeVectorStore(Store, DAG); 4080 case 8: 4081 if (NumElements > 2) 4082 return SplitVectorStore(Op, DAG); 4083 return SDValue(); 4084 case 16: 4085 if (NumElements > 4) 4086 return SplitVectorStore(Op, DAG); 4087 return SDValue(); 4088 default: 4089 llvm_unreachable("unsupported private_element_size"); 4090 } 4091 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 4092 if (NumElements > 2) 4093 return SplitVectorStore(Op, DAG); 4094 4095 if (NumElements == 2) 4096 return Op; 4097 4098 // If properly aligned, if we split we might be able to use ds_write_b64. 4099 return SplitVectorStore(Op, DAG); 4100 } else { 4101 llvm_unreachable("unhandled address space"); 4102 } 4103 } 4104 4105 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 4106 SDLoc DL(Op); 4107 EVT VT = Op.getValueType(); 4108 SDValue Arg = Op.getOperand(0); 4109 // TODO: Should this propagate fast-math-flags? 4110 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT, 4111 DAG.getNode(ISD::FMUL, DL, VT, Arg, 4112 DAG.getConstantFP(0.5/M_PI, DL, 4113 VT))); 4114 4115 switch (Op.getOpcode()) { 4116 case ISD::FCOS: 4117 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart); 4118 case ISD::FSIN: 4119 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart); 4120 default: 4121 llvm_unreachable("Wrong trig opcode"); 4122 } 4123 } 4124 4125 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 4126 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 4127 assert(AtomicNode->isCompareAndSwap()); 4128 unsigned AS = AtomicNode->getAddressSpace(); 4129 4130 // No custom lowering required for local address space 4131 if (!isFlatGlobalAddrSpace(AS, AMDGPUASI)) 4132 return Op; 4133 4134 // Non-local address space requires custom lowering for atomic compare 4135 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 4136 SDLoc DL(Op); 4137 SDValue ChainIn = Op.getOperand(0); 4138 SDValue Addr = Op.getOperand(1); 4139 SDValue Old = Op.getOperand(2); 4140 SDValue New = Op.getOperand(3); 4141 EVT VT = Op.getValueType(); 4142 MVT SimpleVT = VT.getSimpleVT(); 4143 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 4144 4145 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 4146 SDValue Ops[] = { ChainIn, Addr, NewOld }; 4147 4148 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 4149 Ops, VT, AtomicNode->getMemOperand()); 4150 } 4151 4152 //===----------------------------------------------------------------------===// 4153 // Custom DAG optimizations 4154 //===----------------------------------------------------------------------===// 4155 4156 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 4157 DAGCombinerInfo &DCI) const { 4158 EVT VT = N->getValueType(0); 4159 EVT ScalarVT = VT.getScalarType(); 4160 if (ScalarVT != MVT::f32) 4161 return SDValue(); 4162 4163 SelectionDAG &DAG = DCI.DAG; 4164 SDLoc DL(N); 4165 4166 SDValue Src = N->getOperand(0); 4167 EVT SrcVT = Src.getValueType(); 4168 4169 // TODO: We could try to match extracting the higher bytes, which would be 4170 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 4171 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 4172 // about in practice. 4173 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) { 4174 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 4175 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 4176 DCI.AddToWorklist(Cvt.getNode()); 4177 return Cvt; 4178 } 4179 } 4180 4181 return SDValue(); 4182 } 4183 4184 /// \brief Return true if the given offset Size in bytes can be folded into 4185 /// the immediate offsets of a memory instruction for the given address space. 4186 static bool canFoldOffset(unsigned OffsetSize, unsigned AS, 4187 const SISubtarget &STI) { 4188 auto AMDGPUASI = STI.getAMDGPUAS(); 4189 if (AS == AMDGPUASI.GLOBAL_ADDRESS) { 4190 // MUBUF instructions a 12-bit offset in bytes. 4191 return isUInt<12>(OffsetSize); 4192 } 4193 if (AS == AMDGPUASI.CONSTANT_ADDRESS) { 4194 // SMRD instructions have an 8-bit offset in dwords on SI and 4195 // a 20-bit offset in bytes on VI. 4196 if (STI.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 4197 return isUInt<20>(OffsetSize); 4198 else 4199 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4); 4200 } 4201 if (AS == AMDGPUASI.LOCAL_ADDRESS || 4202 AS == AMDGPUASI.REGION_ADDRESS) { 4203 // The single offset versions have a 16-bit offset in bytes. 4204 return isUInt<16>(OffsetSize); 4205 } 4206 // Indirect register addressing does not use any offsets. 4207 return false; 4208 } 4209 4210 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 4211 4212 // This is a variant of 4213 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 4214 // 4215 // The normal DAG combiner will do this, but only if the add has one use since 4216 // that would increase the number of instructions. 4217 // 4218 // This prevents us from seeing a constant offset that can be folded into a 4219 // memory instruction's addressing mode. If we know the resulting add offset of 4220 // a pointer can be folded into an addressing offset, we can replace the pointer 4221 // operand with the add of new constant offset. This eliminates one of the uses, 4222 // and may allow the remaining use to also be simplified. 4223 // 4224 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 4225 unsigned AddrSpace, 4226 DAGCombinerInfo &DCI) const { 4227 SDValue N0 = N->getOperand(0); 4228 SDValue N1 = N->getOperand(1); 4229 4230 if (N0.getOpcode() != ISD::ADD) 4231 return SDValue(); 4232 4233 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 4234 if (!CN1) 4235 return SDValue(); 4236 4237 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4238 if (!CAdd) 4239 return SDValue(); 4240 4241 // If the resulting offset is too large, we can't fold it into the addressing 4242 // mode offset. 4243 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 4244 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *getSubtarget())) 4245 return SDValue(); 4246 4247 SelectionDAG &DAG = DCI.DAG; 4248 SDLoc SL(N); 4249 EVT VT = N->getValueType(0); 4250 4251 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 4252 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 4253 4254 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset); 4255 } 4256 4257 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 4258 DAGCombinerInfo &DCI) const { 4259 SDValue Ptr = N->getBasePtr(); 4260 SelectionDAG &DAG = DCI.DAG; 4261 SDLoc SL(N); 4262 4263 // TODO: We could also do this for multiplies. 4264 unsigned AS = N->getAddressSpace(); 4265 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUASI.PRIVATE_ADDRESS) { 4266 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI); 4267 if (NewPtr) { 4268 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 4269 4270 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 4271 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 4272 } 4273 } 4274 4275 return SDValue(); 4276 } 4277 4278 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 4279 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 4280 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 4281 (Opc == ISD::XOR && Val == 0); 4282 } 4283 4284 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 4285 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 4286 // integer combine opportunities since most 64-bit operations are decomposed 4287 // this way. TODO: We won't want this for SALU especially if it is an inline 4288 // immediate. 4289 SDValue SITargetLowering::splitBinaryBitConstantOp( 4290 DAGCombinerInfo &DCI, 4291 const SDLoc &SL, 4292 unsigned Opc, SDValue LHS, 4293 const ConstantSDNode *CRHS) const { 4294 uint64_t Val = CRHS->getZExtValue(); 4295 uint32_t ValLo = Lo_32(Val); 4296 uint32_t ValHi = Hi_32(Val); 4297 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4298 4299 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 4300 bitOpWithConstantIsReducible(Opc, ValHi)) || 4301 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 4302 // If we need to materialize a 64-bit immediate, it will be split up later 4303 // anyway. Avoid creating the harder to understand 64-bit immediate 4304 // materialization. 4305 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 4306 } 4307 4308 return SDValue(); 4309 } 4310 4311 // Returns true if argument is a boolean value which is not serialized into 4312 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 4313 static bool isBoolSGPR(SDValue V) { 4314 if (V.getValueType() != MVT::i1) 4315 return false; 4316 switch (V.getOpcode()) { 4317 default: break; 4318 case ISD::SETCC: 4319 case ISD::AND: 4320 case ISD::OR: 4321 case ISD::XOR: 4322 case AMDGPUISD::FP_CLASS: 4323 return true; 4324 } 4325 return false; 4326 } 4327 4328 SDValue SITargetLowering::performAndCombine(SDNode *N, 4329 DAGCombinerInfo &DCI) const { 4330 if (DCI.isBeforeLegalize()) 4331 return SDValue(); 4332 4333 SelectionDAG &DAG = DCI.DAG; 4334 EVT VT = N->getValueType(0); 4335 SDValue LHS = N->getOperand(0); 4336 SDValue RHS = N->getOperand(1); 4337 4338 4339 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 4340 if (VT == MVT::i64 && CRHS) { 4341 if (SDValue Split 4342 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 4343 return Split; 4344 } 4345 4346 if (CRHS && VT == MVT::i32) { 4347 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 4348 // nb = number of trailing zeroes in mask 4349 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 4350 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 4351 uint64_t Mask = CRHS->getZExtValue(); 4352 unsigned Bits = countPopulation(Mask); 4353 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 4354 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 4355 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 4356 unsigned Shift = CShift->getZExtValue(); 4357 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 4358 unsigned Offset = NB + Shift; 4359 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 4360 SDLoc SL(N); 4361 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 4362 LHS->getOperand(0), 4363 DAG.getConstant(Offset, SL, MVT::i32), 4364 DAG.getConstant(Bits, SL, MVT::i32)); 4365 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 4366 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 4367 DAG.getValueType(NarrowVT)); 4368 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 4369 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 4370 return Shl; 4371 } 4372 } 4373 } 4374 } 4375 4376 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 4377 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 4378 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 4379 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 4380 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 4381 4382 SDValue X = LHS.getOperand(0); 4383 SDValue Y = RHS.getOperand(0); 4384 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 4385 return SDValue(); 4386 4387 if (LCC == ISD::SETO) { 4388 if (X != LHS.getOperand(1)) 4389 return SDValue(); 4390 4391 if (RCC == ISD::SETUNE) { 4392 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 4393 if (!C1 || !C1->isInfinity() || C1->isNegative()) 4394 return SDValue(); 4395 4396 const uint32_t Mask = SIInstrFlags::N_NORMAL | 4397 SIInstrFlags::N_SUBNORMAL | 4398 SIInstrFlags::N_ZERO | 4399 SIInstrFlags::P_ZERO | 4400 SIInstrFlags::P_SUBNORMAL | 4401 SIInstrFlags::P_NORMAL; 4402 4403 static_assert(((~(SIInstrFlags::S_NAN | 4404 SIInstrFlags::Q_NAN | 4405 SIInstrFlags::N_INFINITY | 4406 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 4407 "mask not equal"); 4408 4409 SDLoc DL(N); 4410 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 4411 X, DAG.getConstant(Mask, DL, MVT::i32)); 4412 } 4413 } 4414 } 4415 4416 if (VT == MVT::i32 && 4417 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 4418 // and x, (sext cc from i1) => select cc, x, 0 4419 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 4420 std::swap(LHS, RHS); 4421 if (isBoolSGPR(RHS.getOperand(0))) 4422 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 4423 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 4424 } 4425 4426 return SDValue(); 4427 } 4428 4429 SDValue SITargetLowering::performOrCombine(SDNode *N, 4430 DAGCombinerInfo &DCI) const { 4431 SelectionDAG &DAG = DCI.DAG; 4432 SDValue LHS = N->getOperand(0); 4433 SDValue RHS = N->getOperand(1); 4434 4435 EVT VT = N->getValueType(0); 4436 if (VT == MVT::i1) { 4437 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 4438 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 4439 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 4440 SDValue Src = LHS.getOperand(0); 4441 if (Src != RHS.getOperand(0)) 4442 return SDValue(); 4443 4444 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 4445 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 4446 if (!CLHS || !CRHS) 4447 return SDValue(); 4448 4449 // Only 10 bits are used. 4450 static const uint32_t MaxMask = 0x3ff; 4451 4452 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 4453 SDLoc DL(N); 4454 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 4455 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 4456 } 4457 4458 return SDValue(); 4459 } 4460 4461 if (VT != MVT::i64) 4462 return SDValue(); 4463 4464 // TODO: This could be a generic combine with a predicate for extracting the 4465 // high half of an integer being free. 4466 4467 // (or i64:x, (zero_extend i32:y)) -> 4468 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 4469 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 4470 RHS.getOpcode() != ISD::ZERO_EXTEND) 4471 std::swap(LHS, RHS); 4472 4473 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 4474 SDValue ExtSrc = RHS.getOperand(0); 4475 EVT SrcVT = ExtSrc.getValueType(); 4476 if (SrcVT == MVT::i32) { 4477 SDLoc SL(N); 4478 SDValue LowLHS, HiBits; 4479 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 4480 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 4481 4482 DCI.AddToWorklist(LowOr.getNode()); 4483 DCI.AddToWorklist(HiBits.getNode()); 4484 4485 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 4486 LowOr, HiBits); 4487 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 4488 } 4489 } 4490 4491 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 4492 if (CRHS) { 4493 if (SDValue Split 4494 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 4495 return Split; 4496 } 4497 4498 return SDValue(); 4499 } 4500 4501 SDValue SITargetLowering::performXorCombine(SDNode *N, 4502 DAGCombinerInfo &DCI) const { 4503 EVT VT = N->getValueType(0); 4504 if (VT != MVT::i64) 4505 return SDValue(); 4506 4507 SDValue LHS = N->getOperand(0); 4508 SDValue RHS = N->getOperand(1); 4509 4510 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 4511 if (CRHS) { 4512 if (SDValue Split 4513 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 4514 return Split; 4515 } 4516 4517 return SDValue(); 4518 } 4519 4520 // Instructions that will be lowered with a final instruction that zeros the 4521 // high result bits. 4522 // XXX - probably only need to list legal operations. 4523 static bool fp16SrcZerosHighBits(unsigned Opc) { 4524 switch (Opc) { 4525 case ISD::FADD: 4526 case ISD::FSUB: 4527 case ISD::FMUL: 4528 case ISD::FDIV: 4529 case ISD::FREM: 4530 case ISD::FMA: 4531 case ISD::FMAD: 4532 case ISD::FCANONICALIZE: 4533 case ISD::FP_ROUND: 4534 case ISD::UINT_TO_FP: 4535 case ISD::SINT_TO_FP: 4536 case ISD::FABS: 4537 // Fabs is lowered to a bit operation, but it's an and which will clear the 4538 // high bits anyway. 4539 case ISD::FSQRT: 4540 case ISD::FSIN: 4541 case ISD::FCOS: 4542 case ISD::FPOWI: 4543 case ISD::FPOW: 4544 case ISD::FLOG: 4545 case ISD::FLOG2: 4546 case ISD::FLOG10: 4547 case ISD::FEXP: 4548 case ISD::FEXP2: 4549 case ISD::FCEIL: 4550 case ISD::FTRUNC: 4551 case ISD::FRINT: 4552 case ISD::FNEARBYINT: 4553 case ISD::FROUND: 4554 case ISD::FFLOOR: 4555 case ISD::FMINNUM: 4556 case ISD::FMAXNUM: 4557 case AMDGPUISD::FRACT: 4558 case AMDGPUISD::CLAMP: 4559 case AMDGPUISD::COS_HW: 4560 case AMDGPUISD::SIN_HW: 4561 case AMDGPUISD::FMIN3: 4562 case AMDGPUISD::FMAX3: 4563 case AMDGPUISD::FMED3: 4564 case AMDGPUISD::FMAD_FTZ: 4565 case AMDGPUISD::RCP: 4566 case AMDGPUISD::RSQ: 4567 case AMDGPUISD::LDEXP: 4568 return true; 4569 default: 4570 // fcopysign, select and others may be lowered to 32-bit bit operations 4571 // which don't zero the high bits. 4572 return false; 4573 } 4574 } 4575 4576 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 4577 DAGCombinerInfo &DCI) const { 4578 if (!Subtarget->has16BitInsts() || 4579 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 4580 return SDValue(); 4581 4582 EVT VT = N->getValueType(0); 4583 if (VT != MVT::i32) 4584 return SDValue(); 4585 4586 SDValue Src = N->getOperand(0); 4587 if (Src.getValueType() != MVT::i16) 4588 return SDValue(); 4589 4590 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 4591 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 4592 if (Src.getOpcode() == ISD::BITCAST) { 4593 SDValue BCSrc = Src.getOperand(0); 4594 if (BCSrc.getValueType() == MVT::f16 && 4595 fp16SrcZerosHighBits(BCSrc.getOpcode())) 4596 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 4597 } 4598 4599 return SDValue(); 4600 } 4601 4602 SDValue SITargetLowering::performClassCombine(SDNode *N, 4603 DAGCombinerInfo &DCI) const { 4604 SelectionDAG &DAG = DCI.DAG; 4605 SDValue Mask = N->getOperand(1); 4606 4607 // fp_class x, 0 -> false 4608 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 4609 if (CMask->isNullValue()) 4610 return DAG.getConstant(0, SDLoc(N), MVT::i1); 4611 } 4612 4613 if (N->getOperand(0).isUndef()) 4614 return DAG.getUNDEF(MVT::i1); 4615 4616 return SDValue(); 4617 } 4618 4619 // Constant fold canonicalize. 4620 SDValue SITargetLowering::performFCanonicalizeCombine( 4621 SDNode *N, 4622 DAGCombinerInfo &DCI) const { 4623 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0)); 4624 if (!CFP) 4625 return SDValue(); 4626 4627 SelectionDAG &DAG = DCI.DAG; 4628 const APFloat &C = CFP->getValueAPF(); 4629 4630 // Flush denormals to 0 if not enabled. 4631 if (C.isDenormal()) { 4632 EVT VT = N->getValueType(0); 4633 EVT SVT = VT.getScalarType(); 4634 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals()) 4635 return DAG.getConstantFP(0.0, SDLoc(N), VT); 4636 4637 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals()) 4638 return DAG.getConstantFP(0.0, SDLoc(N), VT); 4639 4640 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals()) 4641 return DAG.getConstantFP(0.0, SDLoc(N), VT); 4642 } 4643 4644 if (C.isNaN()) { 4645 EVT VT = N->getValueType(0); 4646 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 4647 if (C.isSignaling()) { 4648 // Quiet a signaling NaN. 4649 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 4650 } 4651 4652 // Make sure it is the canonical NaN bitpattern. 4653 // 4654 // TODO: Can we use -1 as the canonical NaN value since it's an inline 4655 // immediate? 4656 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 4657 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 4658 } 4659 4660 return N->getOperand(0); 4661 } 4662 4663 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 4664 switch (Opc) { 4665 case ISD::FMAXNUM: 4666 return AMDGPUISD::FMAX3; 4667 case ISD::SMAX: 4668 return AMDGPUISD::SMAX3; 4669 case ISD::UMAX: 4670 return AMDGPUISD::UMAX3; 4671 case ISD::FMINNUM: 4672 return AMDGPUISD::FMIN3; 4673 case ISD::SMIN: 4674 return AMDGPUISD::SMIN3; 4675 case ISD::UMIN: 4676 return AMDGPUISD::UMIN3; 4677 default: 4678 llvm_unreachable("Not a min/max opcode"); 4679 } 4680 } 4681 4682 SDValue SITargetLowering::performIntMed3ImmCombine( 4683 SelectionDAG &DAG, const SDLoc &SL, 4684 SDValue Op0, SDValue Op1, bool Signed) const { 4685 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 4686 if (!K1) 4687 return SDValue(); 4688 4689 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 4690 if (!K0) 4691 return SDValue(); 4692 4693 if (Signed) { 4694 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 4695 return SDValue(); 4696 } else { 4697 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 4698 return SDValue(); 4699 } 4700 4701 EVT VT = K0->getValueType(0); 4702 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 4703 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 4704 return DAG.getNode(Med3Opc, SL, VT, 4705 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 4706 } 4707 4708 // If there isn't a 16-bit med3 operation, convert to 32-bit. 4709 MVT NVT = MVT::i32; 4710 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4711 4712 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 4713 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 4714 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 4715 4716 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 4717 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 4718 } 4719 4720 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) { 4721 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions()) 4722 return true; 4723 4724 return DAG.isKnownNeverNaN(Op); 4725 } 4726 4727 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 4728 const SDLoc &SL, 4729 SDValue Op0, 4730 SDValue Op1) const { 4731 ConstantFPSDNode *K1 = dyn_cast<ConstantFPSDNode>(Op1); 4732 if (!K1) 4733 return SDValue(); 4734 4735 ConstantFPSDNode *K0 = dyn_cast<ConstantFPSDNode>(Op0.getOperand(1)); 4736 if (!K0) 4737 return SDValue(); 4738 4739 // Ordered >= (although NaN inputs should have folded away by now). 4740 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 4741 if (Cmp == APFloat::cmpGreaterThan) 4742 return SDValue(); 4743 4744 // TODO: Check IEEE bit enabled? 4745 EVT VT = K0->getValueType(0); 4746 if (Subtarget->enableDX10Clamp()) { 4747 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 4748 // hardware fmed3 behavior converting to a min. 4749 // FIXME: Should this be allowing -0.0? 4750 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 4751 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 4752 } 4753 4754 // med3 for f16 is only available on gfx9+. 4755 if (VT == MVT::f64 || (VT == MVT::f16 && !Subtarget->hasMed3_16())) 4756 return SDValue(); 4757 4758 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 4759 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would then 4760 // give the other result, which is different from med3 with a NaN input. 4761 SDValue Var = Op0.getOperand(0); 4762 if (!isKnownNeverSNan(DAG, Var)) 4763 return SDValue(); 4764 4765 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 4766 Var, SDValue(K0, 0), SDValue(K1, 0)); 4767 } 4768 4769 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 4770 DAGCombinerInfo &DCI) const { 4771 SelectionDAG &DAG = DCI.DAG; 4772 4773 EVT VT = N->getValueType(0); 4774 unsigned Opc = N->getOpcode(); 4775 SDValue Op0 = N->getOperand(0); 4776 SDValue Op1 = N->getOperand(1); 4777 4778 // Only do this if the inner op has one use since this will just increases 4779 // register pressure for no benefit. 4780 4781 4782 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 4783 VT != MVT::f64 && 4784 ((VT != MVT::f16 && VT != MVT::i16) || Subtarget->hasMin3Max3_16())) { 4785 // max(max(a, b), c) -> max3(a, b, c) 4786 // min(min(a, b), c) -> min3(a, b, c) 4787 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 4788 SDLoc DL(N); 4789 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 4790 DL, 4791 N->getValueType(0), 4792 Op0.getOperand(0), 4793 Op0.getOperand(1), 4794 Op1); 4795 } 4796 4797 // Try commuted. 4798 // max(a, max(b, c)) -> max3(a, b, c) 4799 // min(a, min(b, c)) -> min3(a, b, c) 4800 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 4801 SDLoc DL(N); 4802 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 4803 DL, 4804 N->getValueType(0), 4805 Op0, 4806 Op1.getOperand(0), 4807 Op1.getOperand(1)); 4808 } 4809 } 4810 4811 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 4812 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 4813 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 4814 return Med3; 4815 } 4816 4817 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 4818 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 4819 return Med3; 4820 } 4821 4822 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 4823 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 4824 (Opc == AMDGPUISD::FMIN_LEGACY && 4825 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 4826 (VT == MVT::f32 || VT == MVT::f64 || 4827 (VT == MVT::f16 && Subtarget->has16BitInsts())) && 4828 Op0.hasOneUse()) { 4829 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 4830 return Res; 4831 } 4832 4833 return SDValue(); 4834 } 4835 4836 static bool isClampZeroToOne(SDValue A, SDValue B) { 4837 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 4838 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 4839 // FIXME: Should this be allowing -0.0? 4840 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 4841 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 4842 } 4843 } 4844 4845 return false; 4846 } 4847 4848 // FIXME: Should only worry about snans for version with chain. 4849 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 4850 DAGCombinerInfo &DCI) const { 4851 EVT VT = N->getValueType(0); 4852 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 4853 // NaNs. With a NaN input, the order of the operands may change the result. 4854 4855 SelectionDAG &DAG = DCI.DAG; 4856 SDLoc SL(N); 4857 4858 SDValue Src0 = N->getOperand(0); 4859 SDValue Src1 = N->getOperand(1); 4860 SDValue Src2 = N->getOperand(2); 4861 4862 if (isClampZeroToOne(Src0, Src1)) { 4863 // const_a, const_b, x -> clamp is safe in all cases including signaling 4864 // nans. 4865 // FIXME: Should this be allowing -0.0? 4866 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 4867 } 4868 4869 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 4870 // handling no dx10-clamp? 4871 if (Subtarget->enableDX10Clamp()) { 4872 // If NaNs is clamped to 0, we are free to reorder the inputs. 4873 4874 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 4875 std::swap(Src0, Src1); 4876 4877 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 4878 std::swap(Src1, Src2); 4879 4880 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 4881 std::swap(Src0, Src1); 4882 4883 if (isClampZeroToOne(Src1, Src2)) 4884 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 4885 } 4886 4887 return SDValue(); 4888 } 4889 4890 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 4891 DAGCombinerInfo &DCI) const { 4892 SDValue Src0 = N->getOperand(0); 4893 SDValue Src1 = N->getOperand(1); 4894 if (Src0.isUndef() && Src1.isUndef()) 4895 return DCI.DAG.getUNDEF(N->getValueType(0)); 4896 return SDValue(); 4897 } 4898 4899 SDValue SITargetLowering::performExtractVectorEltCombine( 4900 SDNode *N, DAGCombinerInfo &DCI) const { 4901 SDValue Vec = N->getOperand(0); 4902 4903 SelectionDAG &DAG= DCI.DAG; 4904 if (Vec.getOpcode() == ISD::FNEG && allUsesHaveSourceMods(N)) { 4905 SDLoc SL(N); 4906 EVT EltVT = N->getValueType(0); 4907 SDValue Idx = N->getOperand(1); 4908 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4909 Vec.getOperand(0), Idx); 4910 return DAG.getNode(ISD::FNEG, SL, EltVT, Elt); 4911 } 4912 4913 return SDValue(); 4914 } 4915 4916 4917 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 4918 const SDNode *N0, 4919 const SDNode *N1) const { 4920 EVT VT = N0->getValueType(0); 4921 4922 // Only do this if we are not trying to support denormals. v_mad_f32 does not 4923 // support denormals ever. 4924 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) || 4925 (VT == MVT::f16 && !Subtarget->hasFP16Denormals())) 4926 return ISD::FMAD; 4927 4928 const TargetOptions &Options = DAG.getTarget().Options; 4929 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 4930 (N0->getFlags().hasUnsafeAlgebra() && 4931 N1->getFlags().hasUnsafeAlgebra())) && 4932 isFMAFasterThanFMulAndFAdd(VT)) { 4933 return ISD::FMA; 4934 } 4935 4936 return 0; 4937 } 4938 4939 SDValue SITargetLowering::performAddCombine(SDNode *N, 4940 DAGCombinerInfo &DCI) const { 4941 SelectionDAG &DAG = DCI.DAG; 4942 EVT VT = N->getValueType(0); 4943 4944 if (VT != MVT::i32) 4945 return SDValue(); 4946 4947 SDLoc SL(N); 4948 SDValue LHS = N->getOperand(0); 4949 SDValue RHS = N->getOperand(1); 4950 4951 // add x, zext (setcc) => addcarry x, 0, setcc 4952 // add x, sext (setcc) => subcarry x, 0, setcc 4953 unsigned Opc = LHS.getOpcode(); 4954 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 4955 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 4956 std::swap(RHS, LHS); 4957 4958 Opc = RHS.getOpcode(); 4959 switch (Opc) { 4960 default: break; 4961 case ISD::ZERO_EXTEND: 4962 case ISD::SIGN_EXTEND: 4963 case ISD::ANY_EXTEND: { 4964 auto Cond = RHS.getOperand(0); 4965 if (!isBoolSGPR(Cond)) 4966 break; 4967 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 4968 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 4969 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 4970 return DAG.getNode(Opc, SL, VTList, Args); 4971 } 4972 case ISD::ADDCARRY: { 4973 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 4974 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 4975 if (!C || C->getZExtValue() != 0) break; 4976 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 4977 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 4978 } 4979 } 4980 return SDValue(); 4981 } 4982 4983 SDValue SITargetLowering::performSubCombine(SDNode *N, 4984 DAGCombinerInfo &DCI) const { 4985 SelectionDAG &DAG = DCI.DAG; 4986 EVT VT = N->getValueType(0); 4987 4988 if (VT != MVT::i32) 4989 return SDValue(); 4990 4991 SDLoc SL(N); 4992 SDValue LHS = N->getOperand(0); 4993 SDValue RHS = N->getOperand(1); 4994 4995 unsigned Opc = LHS.getOpcode(); 4996 if (Opc != ISD::SUBCARRY) 4997 std::swap(RHS, LHS); 4998 4999 if (LHS.getOpcode() == ISD::SUBCARRY) { 5000 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 5001 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 5002 if (!C || C->getZExtValue() != 0) 5003 return SDValue(); 5004 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 5005 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 5006 } 5007 return SDValue(); 5008 } 5009 5010 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 5011 DAGCombinerInfo &DCI) const { 5012 5013 if (N->getValueType(0) != MVT::i32) 5014 return SDValue(); 5015 5016 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 5017 if (!C || C->getZExtValue() != 0) 5018 return SDValue(); 5019 5020 SelectionDAG &DAG = DCI.DAG; 5021 SDValue LHS = N->getOperand(0); 5022 5023 // addcarry (add x, y), 0, cc => addcarry x, y, cc 5024 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 5025 unsigned LHSOpc = LHS.getOpcode(); 5026 unsigned Opc = N->getOpcode(); 5027 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 5028 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 5029 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 5030 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 5031 } 5032 return SDValue(); 5033 } 5034 5035 SDValue SITargetLowering::performFAddCombine(SDNode *N, 5036 DAGCombinerInfo &DCI) const { 5037 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 5038 return SDValue(); 5039 5040 SelectionDAG &DAG = DCI.DAG; 5041 EVT VT = N->getValueType(0); 5042 5043 SDLoc SL(N); 5044 SDValue LHS = N->getOperand(0); 5045 SDValue RHS = N->getOperand(1); 5046 5047 // These should really be instruction patterns, but writing patterns with 5048 // source modiifiers is a pain. 5049 5050 // fadd (fadd (a, a), b) -> mad 2.0, a, b 5051 if (LHS.getOpcode() == ISD::FADD) { 5052 SDValue A = LHS.getOperand(0); 5053 if (A == LHS.getOperand(1)) { 5054 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 5055 if (FusedOp != 0) { 5056 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 5057 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 5058 } 5059 } 5060 } 5061 5062 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 5063 if (RHS.getOpcode() == ISD::FADD) { 5064 SDValue A = RHS.getOperand(0); 5065 if (A == RHS.getOperand(1)) { 5066 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 5067 if (FusedOp != 0) { 5068 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 5069 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 5070 } 5071 } 5072 } 5073 5074 return SDValue(); 5075 } 5076 5077 SDValue SITargetLowering::performFSubCombine(SDNode *N, 5078 DAGCombinerInfo &DCI) const { 5079 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 5080 return SDValue(); 5081 5082 SelectionDAG &DAG = DCI.DAG; 5083 SDLoc SL(N); 5084 EVT VT = N->getValueType(0); 5085 assert(!VT.isVector()); 5086 5087 // Try to get the fneg to fold into the source modifier. This undoes generic 5088 // DAG combines and folds them into the mad. 5089 // 5090 // Only do this if we are not trying to support denormals. v_mad_f32 does 5091 // not support denormals ever. 5092 SDValue LHS = N->getOperand(0); 5093 SDValue RHS = N->getOperand(1); 5094 if (LHS.getOpcode() == ISD::FADD) { 5095 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 5096 SDValue A = LHS.getOperand(0); 5097 if (A == LHS.getOperand(1)) { 5098 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 5099 if (FusedOp != 0){ 5100 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 5101 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 5102 5103 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 5104 } 5105 } 5106 } 5107 5108 if (RHS.getOpcode() == ISD::FADD) { 5109 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 5110 5111 SDValue A = RHS.getOperand(0); 5112 if (A == RHS.getOperand(1)) { 5113 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 5114 if (FusedOp != 0){ 5115 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 5116 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 5117 } 5118 } 5119 } 5120 5121 return SDValue(); 5122 } 5123 5124 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 5125 DAGCombinerInfo &DCI) const { 5126 SelectionDAG &DAG = DCI.DAG; 5127 SDLoc SL(N); 5128 5129 SDValue LHS = N->getOperand(0); 5130 SDValue RHS = N->getOperand(1); 5131 EVT VT = LHS.getValueType(); 5132 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 5133 5134 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 5135 if (!CRHS) { 5136 CRHS = dyn_cast<ConstantSDNode>(LHS); 5137 if (CRHS) { 5138 std::swap(LHS, RHS); 5139 CC = getSetCCSwappedOperands(CC); 5140 } 5141 } 5142 5143 if (CRHS && VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 5144 isBoolSGPR(LHS.getOperand(0))) { 5145 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 5146 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 5147 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 5148 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 5149 if ((CRHS->isAllOnesValue() && 5150 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 5151 (CRHS->isNullValue() && 5152 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 5153 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 5154 DAG.getConstant(-1, SL, MVT::i1)); 5155 if ((CRHS->isAllOnesValue() && 5156 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 5157 (CRHS->isNullValue() && 5158 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 5159 return LHS.getOperand(0); 5160 } 5161 5162 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 5163 VT != MVT::f16)) 5164 return SDValue(); 5165 5166 // Match isinf pattern 5167 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 5168 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) { 5169 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 5170 if (!CRHS) 5171 return SDValue(); 5172 5173 const APFloat &APF = CRHS->getValueAPF(); 5174 if (APF.isInfinity() && !APF.isNegative()) { 5175 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY; 5176 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 5177 DAG.getConstant(Mask, SL, MVT::i32)); 5178 } 5179 } 5180 5181 return SDValue(); 5182 } 5183 5184 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 5185 DAGCombinerInfo &DCI) const { 5186 SelectionDAG &DAG = DCI.DAG; 5187 SDLoc SL(N); 5188 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 5189 5190 SDValue Src = N->getOperand(0); 5191 SDValue Srl = N->getOperand(0); 5192 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 5193 Srl = Srl.getOperand(0); 5194 5195 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 5196 if (Srl.getOpcode() == ISD::SRL) { 5197 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 5198 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 5199 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 5200 5201 if (const ConstantSDNode *C = 5202 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 5203 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 5204 EVT(MVT::i32)); 5205 5206 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 5207 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 5208 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 5209 MVT::f32, Srl); 5210 } 5211 } 5212 } 5213 5214 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 5215 5216 KnownBits Known; 5217 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 5218 !DCI.isBeforeLegalizeOps()); 5219 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5220 if (TLI.ShrinkDemandedConstant(Src, Demanded, TLO) || 5221 TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) { 5222 DCI.CommitTargetLoweringOpt(TLO); 5223 } 5224 5225 return SDValue(); 5226 } 5227 5228 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 5229 DAGCombinerInfo &DCI) const { 5230 switch (N->getOpcode()) { 5231 default: 5232 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 5233 case ISD::ADD: 5234 return performAddCombine(N, DCI); 5235 case ISD::SUB: 5236 return performSubCombine(N, DCI); 5237 case ISD::ADDCARRY: 5238 case ISD::SUBCARRY: 5239 return performAddCarrySubCarryCombine(N, DCI); 5240 case ISD::FADD: 5241 return performFAddCombine(N, DCI); 5242 case ISD::FSUB: 5243 return performFSubCombine(N, DCI); 5244 case ISD::SETCC: 5245 return performSetCCCombine(N, DCI); 5246 case ISD::FMAXNUM: 5247 case ISD::FMINNUM: 5248 case ISD::SMAX: 5249 case ISD::SMIN: 5250 case ISD::UMAX: 5251 case ISD::UMIN: 5252 case AMDGPUISD::FMIN_LEGACY: 5253 case AMDGPUISD::FMAX_LEGACY: { 5254 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG && 5255 getTargetMachine().getOptLevel() > CodeGenOpt::None) 5256 return performMinMaxCombine(N, DCI); 5257 break; 5258 } 5259 case ISD::LOAD: 5260 case ISD::STORE: 5261 case ISD::ATOMIC_LOAD: 5262 case ISD::ATOMIC_STORE: 5263 case ISD::ATOMIC_CMP_SWAP: 5264 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 5265 case ISD::ATOMIC_SWAP: 5266 case ISD::ATOMIC_LOAD_ADD: 5267 case ISD::ATOMIC_LOAD_SUB: 5268 case ISD::ATOMIC_LOAD_AND: 5269 case ISD::ATOMIC_LOAD_OR: 5270 case ISD::ATOMIC_LOAD_XOR: 5271 case ISD::ATOMIC_LOAD_NAND: 5272 case ISD::ATOMIC_LOAD_MIN: 5273 case ISD::ATOMIC_LOAD_MAX: 5274 case ISD::ATOMIC_LOAD_UMIN: 5275 case ISD::ATOMIC_LOAD_UMAX: 5276 case AMDGPUISD::ATOMIC_INC: 5277 case AMDGPUISD::ATOMIC_DEC: // TODO: Target mem intrinsics. 5278 if (DCI.isBeforeLegalize()) 5279 break; 5280 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 5281 case ISD::AND: 5282 return performAndCombine(N, DCI); 5283 case ISD::OR: 5284 return performOrCombine(N, DCI); 5285 case ISD::XOR: 5286 return performXorCombine(N, DCI); 5287 case ISD::ZERO_EXTEND: 5288 return performZeroExtendCombine(N, DCI); 5289 case AMDGPUISD::FP_CLASS: 5290 return performClassCombine(N, DCI); 5291 case ISD::FCANONICALIZE: 5292 return performFCanonicalizeCombine(N, DCI); 5293 case AMDGPUISD::FRACT: 5294 case AMDGPUISD::RCP: 5295 case AMDGPUISD::RSQ: 5296 case AMDGPUISD::RCP_LEGACY: 5297 case AMDGPUISD::RSQ_LEGACY: 5298 case AMDGPUISD::RSQ_CLAMP: 5299 case AMDGPUISD::LDEXP: { 5300 SDValue Src = N->getOperand(0); 5301 if (Src.isUndef()) 5302 return Src; 5303 break; 5304 } 5305 case ISD::SINT_TO_FP: 5306 case ISD::UINT_TO_FP: 5307 return performUCharToFloatCombine(N, DCI); 5308 case AMDGPUISD::CVT_F32_UBYTE0: 5309 case AMDGPUISD::CVT_F32_UBYTE1: 5310 case AMDGPUISD::CVT_F32_UBYTE2: 5311 case AMDGPUISD::CVT_F32_UBYTE3: 5312 return performCvtF32UByteNCombine(N, DCI); 5313 case AMDGPUISD::FMED3: 5314 return performFMed3Combine(N, DCI); 5315 case AMDGPUISD::CVT_PKRTZ_F16_F32: 5316 return performCvtPkRTZCombine(N, DCI); 5317 case ISD::SCALAR_TO_VECTOR: { 5318 SelectionDAG &DAG = DCI.DAG; 5319 EVT VT = N->getValueType(0); 5320 5321 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 5322 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 5323 SDLoc SL(N); 5324 SDValue Src = N->getOperand(0); 5325 EVT EltVT = Src.getValueType(); 5326 if (EltVT == MVT::f16) 5327 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 5328 5329 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 5330 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 5331 } 5332 5333 break; 5334 } 5335 case ISD::EXTRACT_VECTOR_ELT: 5336 return performExtractVectorEltCombine(N, DCI); 5337 } 5338 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 5339 } 5340 5341 /// \brief Helper function for adjustWritemask 5342 static unsigned SubIdx2Lane(unsigned Idx) { 5343 switch (Idx) { 5344 default: return 0; 5345 case AMDGPU::sub0: return 0; 5346 case AMDGPU::sub1: return 1; 5347 case AMDGPU::sub2: return 2; 5348 case AMDGPU::sub3: return 3; 5349 } 5350 } 5351 5352 /// \brief Adjust the writemask of MIMG instructions 5353 void SITargetLowering::adjustWritemask(MachineSDNode *&Node, 5354 SelectionDAG &DAG) const { 5355 SDNode *Users[4] = { }; 5356 unsigned Lane = 0; 5357 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3; 5358 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 5359 unsigned NewDmask = 0; 5360 5361 // Try to figure out the used register components 5362 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 5363 I != E; ++I) { 5364 5365 // Don't look at users of the chain. 5366 if (I.getUse().getResNo() != 0) 5367 continue; 5368 5369 // Abort if we can't understand the usage 5370 if (!I->isMachineOpcode() || 5371 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 5372 return; 5373 5374 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used. 5375 // Note that subregs are packed, i.e. Lane==0 is the first bit set 5376 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 5377 // set, etc. 5378 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 5379 5380 // Set which texture component corresponds to the lane. 5381 unsigned Comp; 5382 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) { 5383 assert(Dmask); 5384 Comp = countTrailingZeros(Dmask); 5385 Dmask &= ~(1 << Comp); 5386 } 5387 5388 // Abort if we have more than one user per component 5389 if (Users[Lane]) 5390 return; 5391 5392 Users[Lane] = *I; 5393 NewDmask |= 1 << Comp; 5394 } 5395 5396 // Abort if there's no change 5397 if (NewDmask == OldDmask) 5398 return; 5399 5400 // Adjust the writemask in the node 5401 std::vector<SDValue> Ops; 5402 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 5403 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 5404 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 5405 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops); 5406 5407 // If we only got one lane, replace it with a copy 5408 // (if NewDmask has only one bit set...) 5409 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) { 5410 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(), 5411 MVT::i32); 5412 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, 5413 SDLoc(), Users[Lane]->getValueType(0), 5414 SDValue(Node, 0), RC); 5415 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 5416 return; 5417 } 5418 5419 // Update the users of the node with the new indices 5420 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) { 5421 SDNode *User = Users[i]; 5422 if (!User) 5423 continue; 5424 5425 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 5426 DAG.UpdateNodeOperands(User, User->getOperand(0), Op); 5427 5428 switch (Idx) { 5429 default: break; 5430 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 5431 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 5432 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 5433 } 5434 } 5435 } 5436 5437 static bool isFrameIndexOp(SDValue Op) { 5438 if (Op.getOpcode() == ISD::AssertZext) 5439 Op = Op.getOperand(0); 5440 5441 return isa<FrameIndexSDNode>(Op); 5442 } 5443 5444 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG) 5445 /// with frame index operands. 5446 /// LLVM assumes that inputs are to these instructions are registers. 5447 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 5448 SelectionDAG &DAG) const { 5449 if (Node->getOpcode() == ISD::CopyToReg) { 5450 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 5451 SDValue SrcVal = Node->getOperand(2); 5452 5453 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 5454 // to try understanding copies to physical registers. 5455 if (SrcVal.getValueType() == MVT::i1 && 5456 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) { 5457 SDLoc SL(Node); 5458 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 5459 SDValue VReg = DAG.getRegister( 5460 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 5461 5462 SDNode *Glued = Node->getGluedNode(); 5463 SDValue ToVReg 5464 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 5465 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 5466 SDValue ToResultReg 5467 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 5468 VReg, ToVReg.getValue(1)); 5469 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 5470 DAG.RemoveDeadNode(Node); 5471 return ToResultReg.getNode(); 5472 } 5473 } 5474 5475 SmallVector<SDValue, 8> Ops; 5476 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 5477 if (!isFrameIndexOp(Node->getOperand(i))) { 5478 Ops.push_back(Node->getOperand(i)); 5479 continue; 5480 } 5481 5482 SDLoc DL(Node); 5483 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 5484 Node->getOperand(i).getValueType(), 5485 Node->getOperand(i)), 0)); 5486 } 5487 5488 DAG.UpdateNodeOperands(Node, Ops); 5489 return Node; 5490 } 5491 5492 /// \brief Fold the instructions after selecting them. 5493 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 5494 SelectionDAG &DAG) const { 5495 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 5496 unsigned Opcode = Node->getMachineOpcode(); 5497 5498 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 5499 !TII->isGather4(Opcode)) 5500 adjustWritemask(Node, DAG); 5501 5502 if (Opcode == AMDGPU::INSERT_SUBREG || 5503 Opcode == AMDGPU::REG_SEQUENCE) { 5504 legalizeTargetIndependentNode(Node, DAG); 5505 return Node; 5506 } 5507 return Node; 5508 } 5509 5510 /// \brief Assign the register class depending on the number of 5511 /// bits set in the writemask 5512 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 5513 SDNode *Node) const { 5514 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 5515 5516 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 5517 5518 if (TII->isVOP3(MI.getOpcode())) { 5519 // Make sure constant bus requirements are respected. 5520 TII->legalizeOperandsVOP3(MRI, MI); 5521 return; 5522 } 5523 5524 if (TII->isMIMG(MI)) { 5525 unsigned VReg = MI.getOperand(0).getReg(); 5526 const TargetRegisterClass *RC = MRI.getRegClass(VReg); 5527 // TODO: Need mapping tables to handle other cases (register classes). 5528 if (RC != &AMDGPU::VReg_128RegClass) 5529 return; 5530 5531 unsigned DmaskIdx = MI.getNumOperands() == 12 ? 3 : 4; 5532 unsigned Writemask = MI.getOperand(DmaskIdx).getImm(); 5533 unsigned BitsSet = 0; 5534 for (unsigned i = 0; i < 4; ++i) 5535 BitsSet += Writemask & (1 << i) ? 1 : 0; 5536 switch (BitsSet) { 5537 default: return; 5538 case 1: RC = &AMDGPU::VGPR_32RegClass; break; 5539 case 2: RC = &AMDGPU::VReg_64RegClass; break; 5540 case 3: RC = &AMDGPU::VReg_96RegClass; break; 5541 } 5542 5543 unsigned NewOpcode = TII->getMaskedMIMGOp(MI.getOpcode(), BitsSet); 5544 MI.setDesc(TII->get(NewOpcode)); 5545 MRI.setRegClass(VReg, RC); 5546 return; 5547 } 5548 5549 // Replace unused atomics with the no return version. 5550 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 5551 if (NoRetAtomicOp != -1) { 5552 if (!Node->hasAnyUseOfValue(0)) { 5553 MI.setDesc(TII->get(NoRetAtomicOp)); 5554 MI.RemoveOperand(0); 5555 return; 5556 } 5557 5558 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 5559 // instruction, because the return type of these instructions is a vec2 of 5560 // the memory type, so it can be tied to the input operand. 5561 // This means these instructions always have a use, so we need to add a 5562 // special case to check if the atomic has only one extract_subreg use, 5563 // which itself has no uses. 5564 if ((Node->hasNUsesOfValue(1, 0) && 5565 Node->use_begin()->isMachineOpcode() && 5566 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 5567 !Node->use_begin()->hasAnyUseOfValue(0))) { 5568 unsigned Def = MI.getOperand(0).getReg(); 5569 5570 // Change this into a noret atomic. 5571 MI.setDesc(TII->get(NoRetAtomicOp)); 5572 MI.RemoveOperand(0); 5573 5574 // If we only remove the def operand from the atomic instruction, the 5575 // extract_subreg will be left with a use of a vreg without a def. 5576 // So we need to insert an implicit_def to avoid machine verifier 5577 // errors. 5578 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 5579 TII->get(AMDGPU::IMPLICIT_DEF), Def); 5580 } 5581 return; 5582 } 5583 } 5584 5585 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 5586 uint64_t Val) { 5587 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 5588 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 5589 } 5590 5591 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 5592 const SDLoc &DL, 5593 SDValue Ptr) const { 5594 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 5595 5596 // Build the half of the subregister with the constants before building the 5597 // full 128-bit register. If we are building multiple resource descriptors, 5598 // this will allow CSEing of the 2-component register. 5599 const SDValue Ops0[] = { 5600 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 5601 buildSMovImm32(DAG, DL, 0), 5602 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 5603 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 5604 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 5605 }; 5606 5607 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 5608 MVT::v2i32, Ops0), 0); 5609 5610 // Combine the constants and the pointer. 5611 const SDValue Ops1[] = { 5612 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 5613 Ptr, 5614 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 5615 SubRegHi, 5616 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 5617 }; 5618 5619 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 5620 } 5621 5622 /// \brief Return a resource descriptor with the 'Add TID' bit enabled 5623 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 5624 /// of the resource descriptor) to create an offset, which is added to 5625 /// the resource pointer. 5626 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 5627 SDValue Ptr, uint32_t RsrcDword1, 5628 uint64_t RsrcDword2And3) const { 5629 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 5630 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 5631 if (RsrcDword1) { 5632 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 5633 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 5634 0); 5635 } 5636 5637 SDValue DataLo = buildSMovImm32(DAG, DL, 5638 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 5639 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 5640 5641 const SDValue Ops[] = { 5642 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 5643 PtrLo, 5644 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 5645 PtrHi, 5646 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 5647 DataLo, 5648 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 5649 DataHi, 5650 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 5651 }; 5652 5653 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 5654 } 5655 5656 //===----------------------------------------------------------------------===// 5657 // SI Inline Assembly Support 5658 //===----------------------------------------------------------------------===// 5659 5660 std::pair<unsigned, const TargetRegisterClass *> 5661 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 5662 StringRef Constraint, 5663 MVT VT) const { 5664 if (!isTypeLegal(VT)) 5665 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 5666 5667 if (Constraint.size() == 1) { 5668 switch (Constraint[0]) { 5669 case 's': 5670 case 'r': 5671 switch (VT.getSizeInBits()) { 5672 default: 5673 return std::make_pair(0U, nullptr); 5674 case 32: 5675 case 16: 5676 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass); 5677 case 64: 5678 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass); 5679 case 128: 5680 return std::make_pair(0U, &AMDGPU::SReg_128RegClass); 5681 case 256: 5682 return std::make_pair(0U, &AMDGPU::SReg_256RegClass); 5683 case 512: 5684 return std::make_pair(0U, &AMDGPU::SReg_512RegClass); 5685 } 5686 5687 case 'v': 5688 switch (VT.getSizeInBits()) { 5689 default: 5690 return std::make_pair(0U, nullptr); 5691 case 32: 5692 case 16: 5693 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass); 5694 case 64: 5695 return std::make_pair(0U, &AMDGPU::VReg_64RegClass); 5696 case 96: 5697 return std::make_pair(0U, &AMDGPU::VReg_96RegClass); 5698 case 128: 5699 return std::make_pair(0U, &AMDGPU::VReg_128RegClass); 5700 case 256: 5701 return std::make_pair(0U, &AMDGPU::VReg_256RegClass); 5702 case 512: 5703 return std::make_pair(0U, &AMDGPU::VReg_512RegClass); 5704 } 5705 } 5706 } 5707 5708 if (Constraint.size() > 1) { 5709 const TargetRegisterClass *RC = nullptr; 5710 if (Constraint[1] == 'v') { 5711 RC = &AMDGPU::VGPR_32RegClass; 5712 } else if (Constraint[1] == 's') { 5713 RC = &AMDGPU::SGPR_32RegClass; 5714 } 5715 5716 if (RC) { 5717 uint32_t Idx; 5718 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 5719 if (!Failed && Idx < RC->getNumRegs()) 5720 return std::make_pair(RC->getRegister(Idx), RC); 5721 } 5722 } 5723 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 5724 } 5725 5726 SITargetLowering::ConstraintType 5727 SITargetLowering::getConstraintType(StringRef Constraint) const { 5728 if (Constraint.size() == 1) { 5729 switch (Constraint[0]) { 5730 default: break; 5731 case 's': 5732 case 'v': 5733 return C_RegisterClass; 5734 } 5735 } 5736 return TargetLowering::getConstraintType(Constraint); 5737 } 5738