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