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