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