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