1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 /// \file 11 /// \brief Custom DAG lowering for SI 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifdef _MSC_VER 16 // Provide M_PI. 17 #define _USE_MATH_DEFINES 18 #endif 19 20 #include "SIISelLowering.h" 21 #include "AMDGPU.h" 22 #include "AMDGPUIntrinsicInfo.h" 23 #include "AMDGPUSubtarget.h" 24 #include "AMDGPUTargetMachine.h" 25 #include "SIDefines.h" 26 #include "SIInstrInfo.h" 27 #include "SIMachineFunctionInfo.h" 28 #include "SIRegisterInfo.h" 29 #include "Utils/AMDGPUBaseInfo.h" 30 #include "llvm/ADT/APFloat.h" 31 #include "llvm/ADT/APInt.h" 32 #include "llvm/ADT/ArrayRef.h" 33 #include "llvm/ADT/BitVector.h" 34 #include "llvm/ADT/SmallVector.h" 35 #include "llvm/ADT/Statistic.h" 36 #include "llvm/ADT/StringRef.h" 37 #include "llvm/ADT/StringSwitch.h" 38 #include "llvm/ADT/Twine.h" 39 #include "llvm/CodeGen/Analysis.h" 40 #include "llvm/CodeGen/CallingConvLower.h" 41 #include "llvm/CodeGen/DAGCombine.h" 42 #include "llvm/CodeGen/ISDOpcodes.h" 43 #include "llvm/CodeGen/MachineBasicBlock.h" 44 #include "llvm/CodeGen/MachineFrameInfo.h" 45 #include "llvm/CodeGen/MachineFunction.h" 46 #include "llvm/CodeGen/MachineInstr.h" 47 #include "llvm/CodeGen/MachineInstrBuilder.h" 48 #include "llvm/CodeGen/MachineMemOperand.h" 49 #include "llvm/CodeGen/MachineModuleInfo.h" 50 #include "llvm/CodeGen/MachineOperand.h" 51 #include "llvm/CodeGen/MachineRegisterInfo.h" 52 #include "llvm/CodeGen/MachineValueType.h" 53 #include "llvm/CodeGen/SelectionDAG.h" 54 #include "llvm/CodeGen/SelectionDAGNodes.h" 55 #include "llvm/CodeGen/TargetCallingConv.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/Constants.h" 59 #include "llvm/IR/DataLayout.h" 60 #include "llvm/IR/DebugLoc.h" 61 #include "llvm/IR/DerivedTypes.h" 62 #include "llvm/IR/DiagnosticInfo.h" 63 #include "llvm/IR/Function.h" 64 #include "llvm/IR/GlobalValue.h" 65 #include "llvm/IR/InstrTypes.h" 66 #include "llvm/IR/Instruction.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/IntrinsicInst.h" 69 #include "llvm/IR/Type.h" 70 #include "llvm/Support/Casting.h" 71 #include "llvm/Support/CodeGen.h" 72 #include "llvm/Support/CommandLine.h" 73 #include "llvm/Support/Compiler.h" 74 #include "llvm/Support/ErrorHandling.h" 75 #include "llvm/Support/KnownBits.h" 76 #include "llvm/Support/MathExtras.h" 77 #include "llvm/Target/TargetOptions.h" 78 #include <cassert> 79 #include <cmath> 80 #include <cstdint> 81 #include <iterator> 82 #include <tuple> 83 #include <utility> 84 #include <vector> 85 86 using namespace llvm; 87 88 #define DEBUG_TYPE "si-lower" 89 90 STATISTIC(NumTailCalls, "Number of tail calls"); 91 92 static cl::opt<bool> EnableVGPRIndexMode( 93 "amdgpu-vgpr-index-mode", 94 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"), 95 cl::init(false)); 96 97 static cl::opt<unsigned> AssumeFrameIndexHighZeroBits( 98 "amdgpu-frame-index-zero-bits", 99 cl::desc("High bits of frame index assumed to be zero"), 100 cl::init(5), 101 cl::ReallyHidden); 102 103 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 104 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 105 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 106 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 107 return AMDGPU::SGPR0 + Reg; 108 } 109 } 110 llvm_unreachable("Cannot allocate sgpr"); 111 } 112 113 SITargetLowering::SITargetLowering(const TargetMachine &TM, 114 const SISubtarget &STI) 115 : AMDGPUTargetLowering(TM, STI) { 116 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 117 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 118 119 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass); 120 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 121 122 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 123 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 124 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 125 126 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass); 127 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass); 128 129 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass); 130 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 131 132 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass); 133 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 134 135 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass); 136 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 137 138 if (Subtarget->has16BitInsts()) { 139 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass); 140 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass); 141 } 142 143 if (Subtarget->hasVOP3PInsts()) { 144 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass); 145 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass); 146 } 147 148 computeRegisterProperties(STI.getRegisterInfo()); 149 150 // We need to custom lower vector stores from local memory 151 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 152 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 153 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 154 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 155 setOperationAction(ISD::LOAD, MVT::i1, Custom); 156 157 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 158 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 159 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 160 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 161 setOperationAction(ISD::STORE, MVT::i1, Custom); 162 163 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 164 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 165 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 166 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 167 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 168 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 169 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 170 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 171 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 172 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 173 174 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 175 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 176 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand); 177 178 setOperationAction(ISD::SELECT, MVT::i1, Promote); 179 setOperationAction(ISD::SELECT, MVT::i64, Custom); 180 setOperationAction(ISD::SELECT, MVT::f64, Promote); 181 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 182 183 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 184 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 185 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 186 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 187 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 188 189 setOperationAction(ISD::SETCC, MVT::i1, Promote); 190 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 191 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 192 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 193 194 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 195 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 196 197 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 198 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 199 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 200 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 201 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 202 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 203 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 204 205 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 206 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 207 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 208 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 209 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 210 211 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 212 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 213 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 214 215 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 216 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 217 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 218 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 219 220 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 221 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 222 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 223 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 224 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 225 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 226 227 setOperationAction(ISD::UADDO, MVT::i32, Legal); 228 setOperationAction(ISD::USUBO, MVT::i32, Legal); 229 230 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 231 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 232 233 #if 0 234 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 235 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 236 #endif 237 238 //setOperationAction(ISD::ADDC, MVT::i64, Expand); 239 //setOperationAction(ISD::SUBC, MVT::i64, Expand); 240 241 // We only support LOAD/STORE and vector manipulation ops for vectors 242 // with > 4 elements. 243 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 244 MVT::v2i64, MVT::v2f64}) { 245 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 246 switch (Op) { 247 case ISD::LOAD: 248 case ISD::STORE: 249 case ISD::BUILD_VECTOR: 250 case ISD::BITCAST: 251 case ISD::EXTRACT_VECTOR_ELT: 252 case ISD::INSERT_VECTOR_ELT: 253 case ISD::INSERT_SUBVECTOR: 254 case ISD::EXTRACT_SUBVECTOR: 255 case ISD::SCALAR_TO_VECTOR: 256 break; 257 case ISD::CONCAT_VECTORS: 258 setOperationAction(Op, VT, Custom); 259 break; 260 default: 261 setOperationAction(Op, VT, Expand); 262 break; 263 } 264 } 265 } 266 267 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 268 // is expanded to avoid having two separate loops in case the index is a VGPR. 269 270 // Most operations are naturally 32-bit vector operations. We only support 271 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 272 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 273 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 274 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 275 276 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 277 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 278 279 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 280 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 281 282 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 283 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 284 } 285 286 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 287 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 288 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 289 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 290 291 // Avoid stack access for these. 292 // TODO: Generalize to more vector types. 293 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 294 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 295 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 296 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 297 298 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 299 // and output demarshalling 300 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 301 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 302 303 // We can't return success/failure, only the old value, 304 // let LLVM add the comparison 305 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 306 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 307 308 if (getSubtarget()->hasFlatAddressSpace()) { 309 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 310 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 311 } 312 313 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 314 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 315 316 // On SI this is s_memtime and s_memrealtime on VI. 317 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 318 setOperationAction(ISD::TRAP, MVT::Other, Custom); 319 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 320 321 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 322 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 323 324 if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) { 325 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 326 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 327 setOperationAction(ISD::FRINT, MVT::f64, Legal); 328 } 329 330 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 331 332 setOperationAction(ISD::FSIN, MVT::f32, Custom); 333 setOperationAction(ISD::FCOS, MVT::f32, Custom); 334 setOperationAction(ISD::FDIV, MVT::f32, Custom); 335 setOperationAction(ISD::FDIV, MVT::f64, Custom); 336 337 if (Subtarget->has16BitInsts()) { 338 setOperationAction(ISD::Constant, MVT::i16, Legal); 339 340 setOperationAction(ISD::SMIN, MVT::i16, Legal); 341 setOperationAction(ISD::SMAX, MVT::i16, Legal); 342 343 setOperationAction(ISD::UMIN, MVT::i16, Legal); 344 setOperationAction(ISD::UMAX, MVT::i16, Legal); 345 346 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 347 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 348 349 setOperationAction(ISD::ROTR, MVT::i16, Promote); 350 setOperationAction(ISD::ROTL, MVT::i16, Promote); 351 352 setOperationAction(ISD::SDIV, MVT::i16, Promote); 353 setOperationAction(ISD::UDIV, MVT::i16, Promote); 354 setOperationAction(ISD::SREM, MVT::i16, Promote); 355 setOperationAction(ISD::UREM, MVT::i16, Promote); 356 357 setOperationAction(ISD::BSWAP, MVT::i16, Promote); 358 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 359 360 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 361 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 362 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 363 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 364 365 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 366 367 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 368 369 setOperationAction(ISD::LOAD, MVT::i16, Custom); 370 371 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 372 373 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 374 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 375 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 376 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 377 378 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 379 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 380 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote); 381 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote); 382 383 // F16 - Constant Actions. 384 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 385 386 // F16 - Load/Store Actions. 387 setOperationAction(ISD::LOAD, MVT::f16, Promote); 388 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 389 setOperationAction(ISD::STORE, MVT::f16, Promote); 390 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 391 392 // F16 - VOP1 Actions. 393 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 394 setOperationAction(ISD::FCOS, MVT::f16, Promote); 395 setOperationAction(ISD::FSIN, MVT::f16, Promote); 396 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 397 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 398 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 399 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 400 setOperationAction(ISD::FROUND, MVT::f16, Custom); 401 402 // F16 - VOP2 Actions. 403 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 404 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 405 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 406 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 407 setOperationAction(ISD::FDIV, MVT::f16, Custom); 408 409 // F16 - VOP3 Actions. 410 setOperationAction(ISD::FMA, MVT::f16, Legal); 411 if (!Subtarget->hasFP16Denormals()) 412 setOperationAction(ISD::FMAD, MVT::f16, Legal); 413 } 414 415 if (Subtarget->hasVOP3PInsts()) { 416 for (MVT VT : {MVT::v2i16, MVT::v2f16}) { 417 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 418 switch (Op) { 419 case ISD::LOAD: 420 case ISD::STORE: 421 case ISD::BUILD_VECTOR: 422 case ISD::BITCAST: 423 case ISD::EXTRACT_VECTOR_ELT: 424 case ISD::INSERT_VECTOR_ELT: 425 case ISD::INSERT_SUBVECTOR: 426 case ISD::EXTRACT_SUBVECTOR: 427 case ISD::SCALAR_TO_VECTOR: 428 break; 429 case ISD::CONCAT_VECTORS: 430 setOperationAction(Op, VT, Custom); 431 break; 432 default: 433 setOperationAction(Op, VT, Expand); 434 break; 435 } 436 } 437 } 438 439 // XXX - Do these do anything? Vector constants turn into build_vector. 440 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 441 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 442 443 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 444 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 445 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 446 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 447 448 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 449 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 450 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 451 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 452 453 setOperationAction(ISD::AND, MVT::v2i16, Promote); 454 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 455 setOperationAction(ISD::OR, MVT::v2i16, Promote); 456 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 457 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 458 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 459 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 460 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 461 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 462 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 463 464 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 465 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 466 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 467 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 468 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 469 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 470 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 471 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 472 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 473 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 474 475 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 476 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 477 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 478 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 479 setOperationAction(ISD::FMINNUM, MVT::v2f16, Legal); 480 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Legal); 481 482 // This isn't really legal, but this avoids the legalizer unrolling it (and 483 // allows matching fneg (fabs x) patterns) 484 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 485 486 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 487 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 488 489 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 490 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 491 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 492 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 493 } else { 494 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 495 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 496 } 497 498 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 499 setOperationAction(ISD::SELECT, VT, Custom); 500 } 501 502 setTargetDAGCombine(ISD::ADD); 503 setTargetDAGCombine(ISD::ADDCARRY); 504 setTargetDAGCombine(ISD::SUB); 505 setTargetDAGCombine(ISD::SUBCARRY); 506 setTargetDAGCombine(ISD::FADD); 507 setTargetDAGCombine(ISD::FSUB); 508 setTargetDAGCombine(ISD::FMINNUM); 509 setTargetDAGCombine(ISD::FMAXNUM); 510 setTargetDAGCombine(ISD::SMIN); 511 setTargetDAGCombine(ISD::SMAX); 512 setTargetDAGCombine(ISD::UMIN); 513 setTargetDAGCombine(ISD::UMAX); 514 setTargetDAGCombine(ISD::SETCC); 515 setTargetDAGCombine(ISD::AND); 516 setTargetDAGCombine(ISD::OR); 517 setTargetDAGCombine(ISD::XOR); 518 setTargetDAGCombine(ISD::SINT_TO_FP); 519 setTargetDAGCombine(ISD::UINT_TO_FP); 520 setTargetDAGCombine(ISD::FCANONICALIZE); 521 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 522 setTargetDAGCombine(ISD::ZERO_EXTEND); 523 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 524 setTargetDAGCombine(ISD::BUILD_VECTOR); 525 526 // All memory operations. Some folding on the pointer operand is done to help 527 // matching the constant offsets in the addressing modes. 528 setTargetDAGCombine(ISD::LOAD); 529 setTargetDAGCombine(ISD::STORE); 530 setTargetDAGCombine(ISD::ATOMIC_LOAD); 531 setTargetDAGCombine(ISD::ATOMIC_STORE); 532 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 533 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 534 setTargetDAGCombine(ISD::ATOMIC_SWAP); 535 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 536 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 537 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 538 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 539 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 540 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 541 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 542 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 543 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 544 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 545 546 setSchedulingPreference(Sched::RegPressure); 547 } 548 549 const SISubtarget *SITargetLowering::getSubtarget() const { 550 return static_cast<const SISubtarget *>(Subtarget); 551 } 552 553 //===----------------------------------------------------------------------===// 554 // TargetLowering queries 555 //===----------------------------------------------------------------------===// 556 557 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 558 // SI has some legal vector types, but no legal vector operations. Say no 559 // shuffles are legal in order to prefer scalarizing some vector operations. 560 return false; 561 } 562 563 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 564 const CallInst &CI, 565 MachineFunction &MF, 566 unsigned IntrID) const { 567 switch (IntrID) { 568 case Intrinsic::amdgcn_atomic_inc: 569 case Intrinsic::amdgcn_atomic_dec: 570 case Intrinsic::amdgcn_ds_fadd: 571 case Intrinsic::amdgcn_ds_fmin: 572 case Intrinsic::amdgcn_ds_fmax: { 573 Info.opc = ISD::INTRINSIC_W_CHAIN; 574 Info.memVT = MVT::getVT(CI.getType()); 575 Info.ptrVal = CI.getOperand(0); 576 Info.align = 0; 577 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 578 579 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 580 if (!Vol || !Vol->isZero()) 581 Info.flags |= MachineMemOperand::MOVolatile; 582 583 return true; 584 } 585 586 // Image load. 587 case Intrinsic::amdgcn_image_load: 588 case Intrinsic::amdgcn_image_load_mip: 589 590 // Sample. 591 case Intrinsic::amdgcn_image_sample: 592 case Intrinsic::amdgcn_image_sample_cl: 593 case Intrinsic::amdgcn_image_sample_d: 594 case Intrinsic::amdgcn_image_sample_d_cl: 595 case Intrinsic::amdgcn_image_sample_l: 596 case Intrinsic::amdgcn_image_sample_b: 597 case Intrinsic::amdgcn_image_sample_b_cl: 598 case Intrinsic::amdgcn_image_sample_lz: 599 case Intrinsic::amdgcn_image_sample_cd: 600 case Intrinsic::amdgcn_image_sample_cd_cl: 601 602 // Sample with comparison. 603 case Intrinsic::amdgcn_image_sample_c: 604 case Intrinsic::amdgcn_image_sample_c_cl: 605 case Intrinsic::amdgcn_image_sample_c_d: 606 case Intrinsic::amdgcn_image_sample_c_d_cl: 607 case Intrinsic::amdgcn_image_sample_c_l: 608 case Intrinsic::amdgcn_image_sample_c_b: 609 case Intrinsic::amdgcn_image_sample_c_b_cl: 610 case Intrinsic::amdgcn_image_sample_c_lz: 611 case Intrinsic::amdgcn_image_sample_c_cd: 612 case Intrinsic::amdgcn_image_sample_c_cd_cl: 613 614 // Sample with offsets. 615 case Intrinsic::amdgcn_image_sample_o: 616 case Intrinsic::amdgcn_image_sample_cl_o: 617 case Intrinsic::amdgcn_image_sample_d_o: 618 case Intrinsic::amdgcn_image_sample_d_cl_o: 619 case Intrinsic::amdgcn_image_sample_l_o: 620 case Intrinsic::amdgcn_image_sample_b_o: 621 case Intrinsic::amdgcn_image_sample_b_cl_o: 622 case Intrinsic::amdgcn_image_sample_lz_o: 623 case Intrinsic::amdgcn_image_sample_cd_o: 624 case Intrinsic::amdgcn_image_sample_cd_cl_o: 625 626 // Sample with comparison and offsets. 627 case Intrinsic::amdgcn_image_sample_c_o: 628 case Intrinsic::amdgcn_image_sample_c_cl_o: 629 case Intrinsic::amdgcn_image_sample_c_d_o: 630 case Intrinsic::amdgcn_image_sample_c_d_cl_o: 631 case Intrinsic::amdgcn_image_sample_c_l_o: 632 case Intrinsic::amdgcn_image_sample_c_b_o: 633 case Intrinsic::amdgcn_image_sample_c_b_cl_o: 634 case Intrinsic::amdgcn_image_sample_c_lz_o: 635 case Intrinsic::amdgcn_image_sample_c_cd_o: 636 case Intrinsic::amdgcn_image_sample_c_cd_cl_o: 637 638 // Basic gather4 639 case Intrinsic::amdgcn_image_gather4: 640 case Intrinsic::amdgcn_image_gather4_cl: 641 case Intrinsic::amdgcn_image_gather4_l: 642 case Intrinsic::amdgcn_image_gather4_b: 643 case Intrinsic::amdgcn_image_gather4_b_cl: 644 case Intrinsic::amdgcn_image_gather4_lz: 645 646 // Gather4 with comparison 647 case Intrinsic::amdgcn_image_gather4_c: 648 case Intrinsic::amdgcn_image_gather4_c_cl: 649 case Intrinsic::amdgcn_image_gather4_c_l: 650 case Intrinsic::amdgcn_image_gather4_c_b: 651 case Intrinsic::amdgcn_image_gather4_c_b_cl: 652 case Intrinsic::amdgcn_image_gather4_c_lz: 653 654 // Gather4 with offsets 655 case Intrinsic::amdgcn_image_gather4_o: 656 case Intrinsic::amdgcn_image_gather4_cl_o: 657 case Intrinsic::amdgcn_image_gather4_l_o: 658 case Intrinsic::amdgcn_image_gather4_b_o: 659 case Intrinsic::amdgcn_image_gather4_b_cl_o: 660 case Intrinsic::amdgcn_image_gather4_lz_o: 661 662 // Gather4 with comparison and offsets 663 case Intrinsic::amdgcn_image_gather4_c_o: 664 case Intrinsic::amdgcn_image_gather4_c_cl_o: 665 case Intrinsic::amdgcn_image_gather4_c_l_o: 666 case Intrinsic::amdgcn_image_gather4_c_b_o: 667 case Intrinsic::amdgcn_image_gather4_c_b_cl_o: 668 case Intrinsic::amdgcn_image_gather4_c_lz_o: { 669 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 670 Info.opc = ISD::INTRINSIC_W_CHAIN; 671 Info.memVT = MVT::getVT(CI.getType()); 672 Info.ptrVal = MFI->getImagePSV( 673 *MF.getSubtarget<SISubtarget>().getInstrInfo(), 674 CI.getArgOperand(1)); 675 Info.align = 0; 676 Info.flags = MachineMemOperand::MOLoad | 677 MachineMemOperand::MODereferenceable; 678 return true; 679 } 680 case Intrinsic::amdgcn_image_store: 681 case Intrinsic::amdgcn_image_store_mip: { 682 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 683 Info.opc = ISD::INTRINSIC_VOID; 684 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 685 Info.ptrVal = MFI->getImagePSV( 686 *MF.getSubtarget<SISubtarget>().getInstrInfo(), 687 CI.getArgOperand(2)); 688 Info.flags = MachineMemOperand::MOStore | 689 MachineMemOperand::MODereferenceable; 690 Info.align = 0; 691 return true; 692 } 693 case Intrinsic::amdgcn_image_atomic_swap: 694 case Intrinsic::amdgcn_image_atomic_add: 695 case Intrinsic::amdgcn_image_atomic_sub: 696 case Intrinsic::amdgcn_image_atomic_smin: 697 case Intrinsic::amdgcn_image_atomic_umin: 698 case Intrinsic::amdgcn_image_atomic_smax: 699 case Intrinsic::amdgcn_image_atomic_umax: 700 case Intrinsic::amdgcn_image_atomic_and: 701 case Intrinsic::amdgcn_image_atomic_or: 702 case Intrinsic::amdgcn_image_atomic_xor: 703 case Intrinsic::amdgcn_image_atomic_inc: 704 case Intrinsic::amdgcn_image_atomic_dec: { 705 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 706 Info.opc = ISD::INTRINSIC_W_CHAIN; 707 Info.memVT = MVT::getVT(CI.getType()); 708 Info.ptrVal = MFI->getImagePSV( 709 *MF.getSubtarget<SISubtarget>().getInstrInfo(), 710 CI.getArgOperand(2)); 711 712 Info.flags = MachineMemOperand::MOLoad | 713 MachineMemOperand::MOStore | 714 MachineMemOperand::MODereferenceable; 715 716 // XXX - Should this be volatile without known ordering? 717 Info.flags |= MachineMemOperand::MOVolatile; 718 return true; 719 } 720 case Intrinsic::amdgcn_image_atomic_cmpswap: { 721 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 722 Info.opc = ISD::INTRINSIC_W_CHAIN; 723 Info.memVT = MVT::getVT(CI.getType()); 724 Info.ptrVal = MFI->getImagePSV( 725 *MF.getSubtarget<SISubtarget>().getInstrInfo(), 726 CI.getArgOperand(3)); 727 728 Info.flags = MachineMemOperand::MOLoad | 729 MachineMemOperand::MOStore | 730 MachineMemOperand::MODereferenceable; 731 732 // XXX - Should this be volatile without known ordering? 733 Info.flags |= MachineMemOperand::MOVolatile; 734 return true; 735 } 736 case Intrinsic::amdgcn_tbuffer_load: 737 case Intrinsic::amdgcn_buffer_load: 738 case Intrinsic::amdgcn_buffer_load_format: { 739 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 740 Info.opc = ISD::INTRINSIC_W_CHAIN; 741 Info.ptrVal = MFI->getBufferPSV( 742 *MF.getSubtarget<SISubtarget>().getInstrInfo(), 743 CI.getArgOperand(0)); 744 Info.memVT = MVT::getVT(CI.getType()); 745 Info.flags = MachineMemOperand::MOLoad | 746 MachineMemOperand::MODereferenceable; 747 748 // There is a constant offset component, but there are additional register 749 // offsets which could break AA if we set the offset to anything non-0. 750 return true; 751 } 752 case Intrinsic::amdgcn_tbuffer_store: 753 case Intrinsic::amdgcn_buffer_store: 754 case Intrinsic::amdgcn_buffer_store_format: { 755 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 756 Info.opc = ISD::INTRINSIC_VOID; 757 Info.ptrVal = MFI->getBufferPSV( 758 *MF.getSubtarget<SISubtarget>().getInstrInfo(), 759 CI.getArgOperand(1)); 760 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 761 Info.flags = MachineMemOperand::MOStore | 762 MachineMemOperand::MODereferenceable; 763 return true; 764 } 765 case Intrinsic::amdgcn_buffer_atomic_swap: 766 case Intrinsic::amdgcn_buffer_atomic_add: 767 case Intrinsic::amdgcn_buffer_atomic_sub: 768 case Intrinsic::amdgcn_buffer_atomic_smin: 769 case Intrinsic::amdgcn_buffer_atomic_umin: 770 case Intrinsic::amdgcn_buffer_atomic_smax: 771 case Intrinsic::amdgcn_buffer_atomic_umax: 772 case Intrinsic::amdgcn_buffer_atomic_and: 773 case Intrinsic::amdgcn_buffer_atomic_or: 774 case Intrinsic::amdgcn_buffer_atomic_xor: { 775 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 776 Info.opc = ISD::INTRINSIC_W_CHAIN; 777 Info.ptrVal = MFI->getBufferPSV( 778 *MF.getSubtarget<SISubtarget>().getInstrInfo(), 779 CI.getArgOperand(1)); 780 Info.memVT = MVT::getVT(CI.getType()); 781 Info.flags = MachineMemOperand::MOLoad | 782 MachineMemOperand::MOStore | 783 MachineMemOperand::MODereferenceable | 784 MachineMemOperand::MOVolatile; 785 return true; 786 } 787 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 788 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 789 Info.opc = ISD::INTRINSIC_W_CHAIN; 790 Info.ptrVal = MFI->getBufferPSV( 791 *MF.getSubtarget<SISubtarget>().getInstrInfo(), 792 CI.getArgOperand(2)); 793 Info.memVT = MVT::getVT(CI.getType()); 794 Info.flags = MachineMemOperand::MOLoad | 795 MachineMemOperand::MOStore | 796 MachineMemOperand::MODereferenceable | 797 MachineMemOperand::MOVolatile; 798 return true; 799 } 800 default: 801 return false; 802 } 803 } 804 805 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 806 SmallVectorImpl<Value*> &Ops, 807 Type *&AccessTy) const { 808 switch (II->getIntrinsicID()) { 809 case Intrinsic::amdgcn_atomic_inc: 810 case Intrinsic::amdgcn_atomic_dec: 811 case Intrinsic::amdgcn_ds_fadd: 812 case Intrinsic::amdgcn_ds_fmin: 813 case Intrinsic::amdgcn_ds_fmax: { 814 Value *Ptr = II->getArgOperand(0); 815 AccessTy = II->getType(); 816 Ops.push_back(Ptr); 817 return true; 818 } 819 default: 820 return false; 821 } 822 } 823 824 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 825 if (!Subtarget->hasFlatInstOffsets()) { 826 // Flat instructions do not have offsets, and only have the register 827 // address. 828 return AM.BaseOffs == 0 && AM.Scale == 0; 829 } 830 831 // GFX9 added a 13-bit signed offset. When using regular flat instructions, 832 // the sign bit is ignored and is treated as a 12-bit unsigned offset. 833 834 // Just r + i 835 return isUInt<12>(AM.BaseOffs) && AM.Scale == 0; 836 } 837 838 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 839 if (Subtarget->hasFlatGlobalInsts()) 840 return isInt<13>(AM.BaseOffs) && AM.Scale == 0; 841 842 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 843 // Assume the we will use FLAT for all global memory accesses 844 // on VI. 845 // FIXME: This assumption is currently wrong. On VI we still use 846 // MUBUF instructions for the r + i addressing mode. As currently 847 // implemented, the MUBUF instructions only work on buffer < 4GB. 848 // It may be possible to support > 4GB buffers with MUBUF instructions, 849 // by setting the stride value in the resource descriptor which would 850 // increase the size limit to (stride * 4GB). However, this is risky, 851 // because it has never been validated. 852 return isLegalFlatAddressingMode(AM); 853 } 854 855 return isLegalMUBUFAddressingMode(AM); 856 } 857 858 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 859 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 860 // additionally can do r + r + i with addr64. 32-bit has more addressing 861 // mode options. Depending on the resource constant, it can also do 862 // (i64 r0) + (i32 r1) * (i14 i). 863 // 864 // Private arrays end up using a scratch buffer most of the time, so also 865 // assume those use MUBUF instructions. Scratch loads / stores are currently 866 // implemented as mubuf instructions with offen bit set, so slightly 867 // different than the normal addr64. 868 if (!isUInt<12>(AM.BaseOffs)) 869 return false; 870 871 // FIXME: Since we can split immediate into soffset and immediate offset, 872 // would it make sense to allow any immediate? 873 874 switch (AM.Scale) { 875 case 0: // r + i or just i, depending on HasBaseReg. 876 return true; 877 case 1: 878 return true; // We have r + r or r + i. 879 case 2: 880 if (AM.HasBaseReg) { 881 // Reject 2 * r + r. 882 return false; 883 } 884 885 // Allow 2 * r as r + r 886 // Or 2 * r + i is allowed as r + r + i. 887 return true; 888 default: // Don't allow n * r 889 return false; 890 } 891 } 892 893 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 894 const AddrMode &AM, Type *Ty, 895 unsigned AS, Instruction *I) const { 896 // No global is ever allowed as a base. 897 if (AM.BaseGV) 898 return false; 899 900 if (AS == AMDGPUASI.GLOBAL_ADDRESS) 901 return isLegalGlobalAddressingMode(AM); 902 903 if (AS == AMDGPUASI.CONSTANT_ADDRESS) { 904 // If the offset isn't a multiple of 4, it probably isn't going to be 905 // correctly aligned. 906 // FIXME: Can we get the real alignment here? 907 if (AM.BaseOffs % 4 != 0) 908 return isLegalMUBUFAddressingMode(AM); 909 910 // There are no SMRD extloads, so if we have to do a small type access we 911 // will use a MUBUF load. 912 // FIXME?: We also need to do this if unaligned, but we don't know the 913 // alignment here. 914 if (DL.getTypeStoreSize(Ty) < 4) 915 return isLegalGlobalAddressingMode(AM); 916 917 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) { 918 // SMRD instructions have an 8-bit, dword offset on SI. 919 if (!isUInt<8>(AM.BaseOffs / 4)) 920 return false; 921 } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) { 922 // On CI+, this can also be a 32-bit literal constant offset. If it fits 923 // in 8-bits, it can use a smaller encoding. 924 if (!isUInt<32>(AM.BaseOffs / 4)) 925 return false; 926 } else if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) { 927 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 928 if (!isUInt<20>(AM.BaseOffs)) 929 return false; 930 } else 931 llvm_unreachable("unhandled generation"); 932 933 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 934 return true; 935 936 if (AM.Scale == 1 && AM.HasBaseReg) 937 return true; 938 939 return false; 940 941 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 942 return isLegalMUBUFAddressingMode(AM); 943 } else if (AS == AMDGPUASI.LOCAL_ADDRESS || 944 AS == AMDGPUASI.REGION_ADDRESS) { 945 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 946 // field. 947 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 948 // an 8-bit dword offset but we don't know the alignment here. 949 if (!isUInt<16>(AM.BaseOffs)) 950 return false; 951 952 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 953 return true; 954 955 if (AM.Scale == 1 && AM.HasBaseReg) 956 return true; 957 958 return false; 959 } else if (AS == AMDGPUASI.FLAT_ADDRESS || 960 AS == AMDGPUASI.UNKNOWN_ADDRESS_SPACE) { 961 // For an unknown address space, this usually means that this is for some 962 // reason being used for pure arithmetic, and not based on some addressing 963 // computation. We don't have instructions that compute pointers with any 964 // addressing modes, so treat them as having no offset like flat 965 // instructions. 966 return isLegalFlatAddressingMode(AM); 967 } else { 968 llvm_unreachable("unhandled address space"); 969 } 970 } 971 972 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 973 const SelectionDAG &DAG) const { 974 if (AS == AMDGPUASI.GLOBAL_ADDRESS || AS == AMDGPUASI.FLAT_ADDRESS) { 975 return (MemVT.getSizeInBits() <= 4 * 32); 976 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 977 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 978 return (MemVT.getSizeInBits() <= MaxPrivateBits); 979 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 980 return (MemVT.getSizeInBits() <= 2 * 32); 981 } 982 return true; 983 } 984 985 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 986 unsigned AddrSpace, 987 unsigned Align, 988 bool *IsFast) const { 989 if (IsFast) 990 *IsFast = false; 991 992 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 993 // which isn't a simple VT. 994 // Until MVT is extended to handle this, simply check for the size and 995 // rely on the condition below: allow accesses if the size is a multiple of 4. 996 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 997 VT.getStoreSize() > 16)) { 998 return false; 999 } 1000 1001 if (AddrSpace == AMDGPUASI.LOCAL_ADDRESS || 1002 AddrSpace == AMDGPUASI.REGION_ADDRESS) { 1003 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1004 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1005 // with adjacent offsets. 1006 bool AlignedBy4 = (Align % 4 == 0); 1007 if (IsFast) 1008 *IsFast = AlignedBy4; 1009 1010 return AlignedBy4; 1011 } 1012 1013 // FIXME: We have to be conservative here and assume that flat operations 1014 // will access scratch. If we had access to the IR function, then we 1015 // could determine if any private memory was used in the function. 1016 if (!Subtarget->hasUnalignedScratchAccess() && 1017 (AddrSpace == AMDGPUASI.PRIVATE_ADDRESS || 1018 AddrSpace == AMDGPUASI.FLAT_ADDRESS)) { 1019 return false; 1020 } 1021 1022 if (Subtarget->hasUnalignedBufferAccess()) { 1023 // If we have an uniform constant load, it still requires using a slow 1024 // buffer instruction if unaligned. 1025 if (IsFast) { 1026 *IsFast = (AddrSpace == AMDGPUASI.CONSTANT_ADDRESS) ? 1027 (Align % 4 == 0) : true; 1028 } 1029 1030 return true; 1031 } 1032 1033 // Smaller than dword value must be aligned. 1034 if (VT.bitsLT(MVT::i32)) 1035 return false; 1036 1037 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1038 // byte-address are ignored, thus forcing Dword alignment. 1039 // This applies to private, global, and constant memory. 1040 if (IsFast) 1041 *IsFast = true; 1042 1043 return VT.bitsGT(MVT::i32) && Align % 4 == 0; 1044 } 1045 1046 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign, 1047 unsigned SrcAlign, bool IsMemset, 1048 bool ZeroMemset, 1049 bool MemcpyStrSrc, 1050 MachineFunction &MF) const { 1051 // FIXME: Should account for address space here. 1052 1053 // The default fallback uses the private pointer size as a guess for a type to 1054 // use. Make sure we switch these to 64-bit accesses. 1055 1056 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global 1057 return MVT::v4i32; 1058 1059 if (Size >= 8 && DstAlign >= 4) 1060 return MVT::v2i32; 1061 1062 // Use the default. 1063 return MVT::Other; 1064 } 1065 1066 static bool isFlatGlobalAddrSpace(unsigned AS, AMDGPUAS AMDGPUASI) { 1067 return AS == AMDGPUASI.GLOBAL_ADDRESS || 1068 AS == AMDGPUASI.FLAT_ADDRESS || 1069 AS == AMDGPUASI.CONSTANT_ADDRESS; 1070 } 1071 1072 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1073 unsigned DestAS) const { 1074 return isFlatGlobalAddrSpace(SrcAS, AMDGPUASI) && 1075 isFlatGlobalAddrSpace(DestAS, AMDGPUASI); 1076 } 1077 1078 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1079 const MemSDNode *MemNode = cast<MemSDNode>(N); 1080 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1081 const Instruction *I = dyn_cast<Instruction>(Ptr); 1082 return I && I->getMetadata("amdgpu.noclobber"); 1083 } 1084 1085 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS, 1086 unsigned DestAS) const { 1087 // Flat -> private/local is a simple truncate. 1088 // Flat -> global is no-op 1089 if (SrcAS == AMDGPUASI.FLAT_ADDRESS) 1090 return true; 1091 1092 return isNoopAddrSpaceCast(SrcAS, DestAS); 1093 } 1094 1095 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1096 const MemSDNode *MemNode = cast<MemSDNode>(N); 1097 1098 return AMDGPU::isUniformMMO(MemNode->getMemOperand()); 1099 } 1100 1101 TargetLoweringBase::LegalizeTypeAction 1102 SITargetLowering::getPreferredVectorAction(EVT VT) const { 1103 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1104 return TypeSplitVector; 1105 1106 return TargetLoweringBase::getPreferredVectorAction(VT); 1107 } 1108 1109 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1110 Type *Ty) const { 1111 // FIXME: Could be smarter if called for vector constants. 1112 return true; 1113 } 1114 1115 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1116 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1117 switch (Op) { 1118 case ISD::LOAD: 1119 case ISD::STORE: 1120 1121 // These operations are done with 32-bit instructions anyway. 1122 case ISD::AND: 1123 case ISD::OR: 1124 case ISD::XOR: 1125 case ISD::SELECT: 1126 // TODO: Extensions? 1127 return true; 1128 default: 1129 return false; 1130 } 1131 } 1132 1133 // SimplifySetCC uses this function to determine whether or not it should 1134 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1135 if (VT == MVT::i1 && Op == ISD::SETCC) 1136 return false; 1137 1138 return TargetLowering::isTypeDesirableForOp(Op, VT); 1139 } 1140 1141 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1142 const SDLoc &SL, 1143 SDValue Chain, 1144 uint64_t Offset) const { 1145 const DataLayout &DL = DAG.getDataLayout(); 1146 MachineFunction &MF = DAG.getMachineFunction(); 1147 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1148 1149 const ArgDescriptor *InputPtrReg; 1150 const TargetRegisterClass *RC; 1151 1152 std::tie(InputPtrReg, RC) 1153 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1154 1155 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1156 MVT PtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS); 1157 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1158 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1159 1160 return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr, 1161 DAG.getConstant(Offset, SL, PtrVT)); 1162 } 1163 1164 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1165 const SDLoc &SL) const { 1166 auto MFI = DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>(); 1167 uint64_t Offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT); 1168 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1169 } 1170 1171 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1172 const SDLoc &SL, SDValue Val, 1173 bool Signed, 1174 const ISD::InputArg *Arg) const { 1175 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1176 VT.bitsLT(MemVT)) { 1177 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1178 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1179 } 1180 1181 if (MemVT.isFloatingPoint()) 1182 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT); 1183 else if (Signed) 1184 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1185 else 1186 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1187 1188 return Val; 1189 } 1190 1191 SDValue SITargetLowering::lowerKernargMemParameter( 1192 SelectionDAG &DAG, EVT VT, EVT MemVT, 1193 const SDLoc &SL, SDValue Chain, 1194 uint64_t Offset, bool Signed, 1195 const ISD::InputArg *Arg) const { 1196 const DataLayout &DL = DAG.getDataLayout(); 1197 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 1198 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS); 1199 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 1200 1201 unsigned Align = DL.getABITypeAlignment(Ty); 1202 1203 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1204 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1205 MachineMemOperand::MONonTemporal | 1206 MachineMemOperand::MODereferenceable | 1207 MachineMemOperand::MOInvariant); 1208 1209 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1210 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1211 } 1212 1213 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1214 const SDLoc &SL, SDValue Chain, 1215 const ISD::InputArg &Arg) const { 1216 MachineFunction &MF = DAG.getMachineFunction(); 1217 MachineFrameInfo &MFI = MF.getFrameInfo(); 1218 1219 if (Arg.Flags.isByVal()) { 1220 unsigned Size = Arg.Flags.getByValSize(); 1221 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1222 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1223 } 1224 1225 unsigned ArgOffset = VA.getLocMemOffset(); 1226 unsigned ArgSize = VA.getValVT().getStoreSize(); 1227 1228 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1229 1230 // Create load nodes to retrieve arguments from the stack. 1231 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1232 SDValue ArgValue; 1233 1234 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1235 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1236 MVT MemVT = VA.getValVT(); 1237 1238 switch (VA.getLocInfo()) { 1239 default: 1240 break; 1241 case CCValAssign::BCvt: 1242 MemVT = VA.getLocVT(); 1243 break; 1244 case CCValAssign::SExt: 1245 ExtType = ISD::SEXTLOAD; 1246 break; 1247 case CCValAssign::ZExt: 1248 ExtType = ISD::ZEXTLOAD; 1249 break; 1250 case CCValAssign::AExt: 1251 ExtType = ISD::EXTLOAD; 1252 break; 1253 } 1254 1255 ArgValue = DAG.getExtLoad( 1256 ExtType, SL, VA.getLocVT(), Chain, FIN, 1257 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1258 MemVT); 1259 return ArgValue; 1260 } 1261 1262 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1263 const SIMachineFunctionInfo &MFI, 1264 EVT VT, 1265 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1266 const ArgDescriptor *Reg; 1267 const TargetRegisterClass *RC; 1268 1269 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1270 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1271 } 1272 1273 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1274 CallingConv::ID CallConv, 1275 ArrayRef<ISD::InputArg> Ins, 1276 BitVector &Skipped, 1277 FunctionType *FType, 1278 SIMachineFunctionInfo *Info) { 1279 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1280 const ISD::InputArg &Arg = Ins[I]; 1281 1282 // First check if it's a PS input addr. 1283 if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() && 1284 !Arg.Flags.isByVal() && PSInputNum <= 15) { 1285 1286 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) { 1287 // We can safely skip PS inputs. 1288 Skipped.set(I); 1289 ++PSInputNum; 1290 continue; 1291 } 1292 1293 Info->markPSInputAllocated(PSInputNum); 1294 if (Arg.Used) 1295 Info->markPSInputEnabled(PSInputNum); 1296 1297 ++PSInputNum; 1298 } 1299 1300 // Second split vertices into their elements. 1301 if (Arg.VT.isVector()) { 1302 ISD::InputArg NewArg = Arg; 1303 NewArg.Flags.setSplit(); 1304 NewArg.VT = Arg.VT.getVectorElementType(); 1305 1306 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a 1307 // three or five element vertex only needs three or five registers, 1308 // NOT four or eight. 1309 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 1310 unsigned NumElements = ParamType->getVectorNumElements(); 1311 1312 for (unsigned J = 0; J != NumElements; ++J) { 1313 Splits.push_back(NewArg); 1314 NewArg.PartOffset += NewArg.VT.getStoreSize(); 1315 } 1316 } else { 1317 Splits.push_back(Arg); 1318 } 1319 } 1320 } 1321 1322 // Allocate special inputs passed in VGPRs. 1323 static void allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1324 MachineFunction &MF, 1325 const SIRegisterInfo &TRI, 1326 SIMachineFunctionInfo &Info) { 1327 if (Info.hasWorkItemIDX()) { 1328 unsigned Reg = AMDGPU::VGPR0; 1329 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1330 1331 CCInfo.AllocateReg(Reg); 1332 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1333 } 1334 1335 if (Info.hasWorkItemIDY()) { 1336 unsigned Reg = AMDGPU::VGPR1; 1337 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1338 1339 CCInfo.AllocateReg(Reg); 1340 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1341 } 1342 1343 if (Info.hasWorkItemIDZ()) { 1344 unsigned Reg = AMDGPU::VGPR2; 1345 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1346 1347 CCInfo.AllocateReg(Reg); 1348 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1349 } 1350 } 1351 1352 // Try to allocate a VGPR at the end of the argument list, or if no argument 1353 // VGPRs are left allocating a stack slot. 1354 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo) { 1355 ArrayRef<MCPhysReg> ArgVGPRs 1356 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1357 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1358 if (RegIdx == ArgVGPRs.size()) { 1359 // Spill to stack required. 1360 int64_t Offset = CCInfo.AllocateStack(4, 4); 1361 1362 return ArgDescriptor::createStack(Offset); 1363 } 1364 1365 unsigned Reg = ArgVGPRs[RegIdx]; 1366 Reg = CCInfo.AllocateReg(Reg); 1367 assert(Reg != AMDGPU::NoRegister); 1368 1369 MachineFunction &MF = CCInfo.getMachineFunction(); 1370 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1371 return ArgDescriptor::createRegister(Reg); 1372 } 1373 1374 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1375 const TargetRegisterClass *RC, 1376 unsigned NumArgRegs) { 1377 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1378 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1379 if (RegIdx == ArgSGPRs.size()) 1380 report_fatal_error("ran out of SGPRs for arguments"); 1381 1382 unsigned Reg = ArgSGPRs[RegIdx]; 1383 Reg = CCInfo.AllocateReg(Reg); 1384 assert(Reg != AMDGPU::NoRegister); 1385 1386 MachineFunction &MF = CCInfo.getMachineFunction(); 1387 MF.addLiveIn(Reg, RC); 1388 return ArgDescriptor::createRegister(Reg); 1389 } 1390 1391 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1392 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1393 } 1394 1395 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1396 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1397 } 1398 1399 static void allocateSpecialInputVGPRs(CCState &CCInfo, 1400 MachineFunction &MF, 1401 const SIRegisterInfo &TRI, 1402 SIMachineFunctionInfo &Info) { 1403 if (Info.hasWorkItemIDX()) 1404 Info.setWorkItemIDX(allocateVGPR32Input(CCInfo)); 1405 1406 if (Info.hasWorkItemIDY()) 1407 Info.setWorkItemIDY(allocateVGPR32Input(CCInfo)); 1408 1409 if (Info.hasWorkItemIDZ()) 1410 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo)); 1411 } 1412 1413 static void allocateSpecialInputSGPRs(CCState &CCInfo, 1414 MachineFunction &MF, 1415 const SIRegisterInfo &TRI, 1416 SIMachineFunctionInfo &Info) { 1417 auto &ArgInfo = Info.getArgInfo(); 1418 1419 // TODO: Unify handling with private memory pointers. 1420 1421 if (Info.hasDispatchPtr()) 1422 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1423 1424 if (Info.hasQueuePtr()) 1425 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1426 1427 if (Info.hasKernargSegmentPtr()) 1428 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo); 1429 1430 if (Info.hasDispatchID()) 1431 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1432 1433 // flat_scratch_init is not applicable for non-kernel functions. 1434 1435 if (Info.hasWorkGroupIDX()) 1436 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1437 1438 if (Info.hasWorkGroupIDY()) 1439 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1440 1441 if (Info.hasWorkGroupIDZ()) 1442 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1443 1444 if (Info.hasImplicitArgPtr()) 1445 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1446 } 1447 1448 // Allocate special inputs passed in user SGPRs. 1449 static void allocateHSAUserSGPRs(CCState &CCInfo, 1450 MachineFunction &MF, 1451 const SIRegisterInfo &TRI, 1452 SIMachineFunctionInfo &Info) { 1453 if (Info.hasImplicitBufferPtr()) { 1454 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1455 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1456 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1457 } 1458 1459 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1460 if (Info.hasPrivateSegmentBuffer()) { 1461 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1462 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1463 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1464 } 1465 1466 if (Info.hasDispatchPtr()) { 1467 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1468 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1469 CCInfo.AllocateReg(DispatchPtrReg); 1470 } 1471 1472 if (Info.hasQueuePtr()) { 1473 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1474 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1475 CCInfo.AllocateReg(QueuePtrReg); 1476 } 1477 1478 if (Info.hasKernargSegmentPtr()) { 1479 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI); 1480 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1481 CCInfo.AllocateReg(InputPtrReg); 1482 } 1483 1484 if (Info.hasDispatchID()) { 1485 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1486 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1487 CCInfo.AllocateReg(DispatchIDReg); 1488 } 1489 1490 if (Info.hasFlatScratchInit()) { 1491 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1492 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1493 CCInfo.AllocateReg(FlatScratchInitReg); 1494 } 1495 1496 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1497 // these from the dispatch pointer. 1498 } 1499 1500 // Allocate special input registers that are initialized per-wave. 1501 static void allocateSystemSGPRs(CCState &CCInfo, 1502 MachineFunction &MF, 1503 SIMachineFunctionInfo &Info, 1504 CallingConv::ID CallConv, 1505 bool IsShader) { 1506 if (Info.hasWorkGroupIDX()) { 1507 unsigned Reg = Info.addWorkGroupIDX(); 1508 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1509 CCInfo.AllocateReg(Reg); 1510 } 1511 1512 if (Info.hasWorkGroupIDY()) { 1513 unsigned Reg = Info.addWorkGroupIDY(); 1514 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1515 CCInfo.AllocateReg(Reg); 1516 } 1517 1518 if (Info.hasWorkGroupIDZ()) { 1519 unsigned Reg = Info.addWorkGroupIDZ(); 1520 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1521 CCInfo.AllocateReg(Reg); 1522 } 1523 1524 if (Info.hasWorkGroupInfo()) { 1525 unsigned Reg = Info.addWorkGroupInfo(); 1526 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1527 CCInfo.AllocateReg(Reg); 1528 } 1529 1530 if (Info.hasPrivateSegmentWaveByteOffset()) { 1531 // Scratch wave offset passed in system SGPR. 1532 unsigned PrivateSegmentWaveByteOffsetReg; 1533 1534 if (IsShader) { 1535 PrivateSegmentWaveByteOffsetReg = 1536 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1537 1538 // This is true if the scratch wave byte offset doesn't have a fixed 1539 // location. 1540 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1541 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1542 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1543 } 1544 } else 1545 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1546 1547 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1548 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1549 } 1550 } 1551 1552 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1553 MachineFunction &MF, 1554 const SIRegisterInfo &TRI, 1555 SIMachineFunctionInfo &Info) { 1556 // Now that we've figured out where the scratch register inputs are, see if 1557 // should reserve the arguments and use them directly. 1558 MachineFrameInfo &MFI = MF.getFrameInfo(); 1559 bool HasStackObjects = MFI.hasStackObjects(); 1560 1561 // Record that we know we have non-spill stack objects so we don't need to 1562 // check all stack objects later. 1563 if (HasStackObjects) 1564 Info.setHasNonSpillStackObjects(true); 1565 1566 // Everything live out of a block is spilled with fast regalloc, so it's 1567 // almost certain that spilling will be required. 1568 if (TM.getOptLevel() == CodeGenOpt::None) 1569 HasStackObjects = true; 1570 1571 // For now assume stack access is needed in any callee functions, so we need 1572 // the scratch registers to pass in. 1573 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1574 1575 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 1576 if (ST.isAmdCodeObjectV2(MF)) { 1577 if (RequiresStackAccess) { 1578 // If we have stack objects, we unquestionably need the private buffer 1579 // resource. For the Code Object V2 ABI, this will be the first 4 user 1580 // SGPR inputs. We can reserve those and use them directly. 1581 1582 unsigned PrivateSegmentBufferReg = Info.getPreloadedReg( 1583 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 1584 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1585 1586 if (MFI.hasCalls()) { 1587 // If we have calls, we need to keep the frame register in a register 1588 // that won't be clobbered by a call, so ensure it is copied somewhere. 1589 1590 // This is not a problem for the scratch wave offset, because the same 1591 // registers are reserved in all functions. 1592 1593 // FIXME: Nothing is really ensuring this is a call preserved register, 1594 // it's just selected from the end so it happens to be. 1595 unsigned ReservedOffsetReg 1596 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1597 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1598 } else { 1599 unsigned PrivateSegmentWaveByteOffsetReg = Info.getPreloadedReg( 1600 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1601 Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg); 1602 } 1603 } else { 1604 unsigned ReservedBufferReg 1605 = TRI.reservedPrivateSegmentBufferReg(MF); 1606 unsigned ReservedOffsetReg 1607 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1608 1609 // We tentatively reserve the last registers (skipping the last two 1610 // which may contain VCC). After register allocation, we'll replace 1611 // these with the ones immediately after those which were really 1612 // allocated. In the prologue copies will be inserted from the argument 1613 // to these reserved registers. 1614 Info.setScratchRSrcReg(ReservedBufferReg); 1615 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1616 } 1617 } else { 1618 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1619 1620 // Without HSA, relocations are used for the scratch pointer and the 1621 // buffer resource setup is always inserted in the prologue. Scratch wave 1622 // offset is still in an input SGPR. 1623 Info.setScratchRSrcReg(ReservedBufferReg); 1624 1625 if (HasStackObjects && !MFI.hasCalls()) { 1626 unsigned ScratchWaveOffsetReg = Info.getPreloadedReg( 1627 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1628 Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg); 1629 } else { 1630 unsigned ReservedOffsetReg 1631 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1632 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1633 } 1634 } 1635 } 1636 1637 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 1638 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 1639 return !Info->isEntryFunction(); 1640 } 1641 1642 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 1643 1644 } 1645 1646 void SITargetLowering::insertCopiesSplitCSR( 1647 MachineBasicBlock *Entry, 1648 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 1649 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1650 1651 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 1652 if (!IStart) 1653 return; 1654 1655 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1656 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 1657 MachineBasicBlock::iterator MBBI = Entry->begin(); 1658 for (const MCPhysReg *I = IStart; *I; ++I) { 1659 const TargetRegisterClass *RC = nullptr; 1660 if (AMDGPU::SReg_64RegClass.contains(*I)) 1661 RC = &AMDGPU::SGPR_64RegClass; 1662 else if (AMDGPU::SReg_32RegClass.contains(*I)) 1663 RC = &AMDGPU::SGPR_32RegClass; 1664 else 1665 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 1666 1667 unsigned NewVR = MRI->createVirtualRegister(RC); 1668 // Create copy from CSR to a virtual register. 1669 Entry->addLiveIn(*I); 1670 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 1671 .addReg(*I); 1672 1673 // Insert the copy-back instructions right before the terminator. 1674 for (auto *Exit : Exits) 1675 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 1676 TII->get(TargetOpcode::COPY), *I) 1677 .addReg(NewVR); 1678 } 1679 } 1680 1681 SDValue SITargetLowering::LowerFormalArguments( 1682 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 1683 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 1684 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 1685 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1686 1687 MachineFunction &MF = DAG.getMachineFunction(); 1688 FunctionType *FType = MF.getFunction().getFunctionType(); 1689 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1690 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 1691 1692 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 1693 const Function &Fn = MF.getFunction(); 1694 DiagnosticInfoUnsupported NoGraphicsHSA( 1695 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 1696 DAG.getContext()->diagnose(NoGraphicsHSA); 1697 return DAG.getEntryNode(); 1698 } 1699 1700 // Create stack objects that are used for emitting debugger prologue if 1701 // "amdgpu-debugger-emit-prologue" attribute was specified. 1702 if (ST.debuggerEmitPrologue()) 1703 createDebuggerPrologueStackObjects(MF); 1704 1705 SmallVector<ISD::InputArg, 16> Splits; 1706 SmallVector<CCValAssign, 16> ArgLocs; 1707 BitVector Skipped(Ins.size()); 1708 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1709 *DAG.getContext()); 1710 1711 bool IsShader = AMDGPU::isShader(CallConv); 1712 bool IsKernel = AMDGPU::isKernel(CallConv); 1713 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 1714 1715 if (!IsEntryFunc) { 1716 // 4 bytes are reserved at offset 0 for the emergency stack slot. Skip over 1717 // this when allocating argument fixed offsets. 1718 CCInfo.AllocateStack(4, 4); 1719 } 1720 1721 if (IsShader) { 1722 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 1723 1724 // At least one interpolation mode must be enabled or else the GPU will 1725 // hang. 1726 // 1727 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 1728 // set PSInputAddr, the user wants to enable some bits after the compilation 1729 // based on run-time states. Since we can't know what the final PSInputEna 1730 // will look like, so we shouldn't do anything here and the user should take 1731 // responsibility for the correct programming. 1732 // 1733 // Otherwise, the following restrictions apply: 1734 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 1735 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 1736 // enabled too. 1737 if (CallConv == CallingConv::AMDGPU_PS) { 1738 if ((Info->getPSInputAddr() & 0x7F) == 0 || 1739 ((Info->getPSInputAddr() & 0xF) == 0 && 1740 Info->isPSInputAllocated(11))) { 1741 CCInfo.AllocateReg(AMDGPU::VGPR0); 1742 CCInfo.AllocateReg(AMDGPU::VGPR1); 1743 Info->markPSInputAllocated(0); 1744 Info->markPSInputEnabled(0); 1745 } 1746 if (Subtarget->isAmdPalOS()) { 1747 // For isAmdPalOS, the user does not enable some bits after compilation 1748 // based on run-time states; the register values being generated here are 1749 // the final ones set in hardware. Therefore we need to apply the 1750 // workaround to PSInputAddr and PSInputEnable together. (The case where 1751 // a bit is set in PSInputAddr but not PSInputEnable is where the 1752 // frontend set up an input arg for a particular interpolation mode, but 1753 // nothing uses that input arg. Really we should have an earlier pass 1754 // that removes such an arg.) 1755 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 1756 if ((PsInputBits & 0x7F) == 0 || 1757 ((PsInputBits & 0xF) == 0 && 1758 (PsInputBits >> 11 & 1))) 1759 Info->markPSInputEnabled( 1760 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 1761 } 1762 } 1763 1764 assert(!Info->hasDispatchPtr() && 1765 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 1766 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 1767 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 1768 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 1769 !Info->hasWorkItemIDZ()); 1770 } else if (IsKernel) { 1771 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 1772 } else { 1773 Splits.append(Ins.begin(), Ins.end()); 1774 } 1775 1776 if (IsEntryFunc) { 1777 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 1778 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 1779 } 1780 1781 if (IsKernel) { 1782 analyzeFormalArgumentsCompute(CCInfo, Ins); 1783 } else { 1784 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 1785 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 1786 } 1787 1788 SmallVector<SDValue, 16> Chains; 1789 1790 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 1791 const ISD::InputArg &Arg = Ins[i]; 1792 if (Skipped[i]) { 1793 InVals.push_back(DAG.getUNDEF(Arg.VT)); 1794 continue; 1795 } 1796 1797 CCValAssign &VA = ArgLocs[ArgIdx++]; 1798 MVT VT = VA.getLocVT(); 1799 1800 if (IsEntryFunc && VA.isMemLoc()) { 1801 VT = Ins[i].VT; 1802 EVT MemVT = VA.getLocVT(); 1803 1804 const uint64_t Offset = Subtarget->getExplicitKernelArgOffset(MF) + 1805 VA.getLocMemOffset(); 1806 Info->setABIArgOffset(Offset + MemVT.getStoreSize()); 1807 1808 // The first 36 bytes of the input buffer contains information about 1809 // thread group and global sizes. 1810 SDValue Arg = lowerKernargMemParameter( 1811 DAG, VT, MemVT, DL, Chain, Offset, Ins[i].Flags.isSExt(), &Ins[i]); 1812 Chains.push_back(Arg.getValue(1)); 1813 1814 auto *ParamTy = 1815 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 1816 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS && 1817 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 1818 // On SI local pointers are just offsets into LDS, so they are always 1819 // less than 16-bits. On CI and newer they could potentially be 1820 // real pointers, so we can't guarantee their size. 1821 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 1822 DAG.getValueType(MVT::i16)); 1823 } 1824 1825 InVals.push_back(Arg); 1826 continue; 1827 } else if (!IsEntryFunc && VA.isMemLoc()) { 1828 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 1829 InVals.push_back(Val); 1830 if (!Arg.Flags.isByVal()) 1831 Chains.push_back(Val.getValue(1)); 1832 continue; 1833 } 1834 1835 assert(VA.isRegLoc() && "Parameter must be in a register!"); 1836 1837 unsigned Reg = VA.getLocReg(); 1838 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 1839 EVT ValVT = VA.getValVT(); 1840 1841 Reg = MF.addLiveIn(Reg, RC); 1842 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 1843 1844 if (Arg.Flags.isSRet() && !getSubtarget()->enableHugePrivateBuffer()) { 1845 // The return object should be reasonably addressable. 1846 1847 // FIXME: This helps when the return is a real sret. If it is a 1848 // automatically inserted sret (i.e. CanLowerReturn returns false), an 1849 // extra copy is inserted in SelectionDAGBuilder which obscures this. 1850 unsigned NumBits = 32 - AssumeFrameIndexHighZeroBits; 1851 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 1852 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 1853 } 1854 1855 // If this is an 8 or 16-bit value, it is really passed promoted 1856 // to 32 bits. Insert an assert[sz]ext to capture this, then 1857 // truncate to the right size. 1858 switch (VA.getLocInfo()) { 1859 case CCValAssign::Full: 1860 break; 1861 case CCValAssign::BCvt: 1862 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 1863 break; 1864 case CCValAssign::SExt: 1865 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 1866 DAG.getValueType(ValVT)); 1867 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 1868 break; 1869 case CCValAssign::ZExt: 1870 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 1871 DAG.getValueType(ValVT)); 1872 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 1873 break; 1874 case CCValAssign::AExt: 1875 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 1876 break; 1877 default: 1878 llvm_unreachable("Unknown loc info!"); 1879 } 1880 1881 if (IsShader && Arg.VT.isVector()) { 1882 // Build a vector from the registers 1883 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 1884 unsigned NumElements = ParamType->getVectorNumElements(); 1885 1886 SmallVector<SDValue, 4> Regs; 1887 Regs.push_back(Val); 1888 for (unsigned j = 1; j != NumElements; ++j) { 1889 Reg = ArgLocs[ArgIdx++].getLocReg(); 1890 Reg = MF.addLiveIn(Reg, RC); 1891 1892 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT); 1893 Regs.push_back(Copy); 1894 } 1895 1896 // Fill up the missing vector elements 1897 NumElements = Arg.VT.getVectorNumElements() - NumElements; 1898 Regs.append(NumElements, DAG.getUNDEF(VT)); 1899 1900 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs)); 1901 continue; 1902 } 1903 1904 InVals.push_back(Val); 1905 } 1906 1907 if (!IsEntryFunc) { 1908 // Special inputs come after user arguments. 1909 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 1910 } 1911 1912 // Start adding system SGPRs. 1913 if (IsEntryFunc) { 1914 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 1915 } else { 1916 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 1917 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg()); 1918 CCInfo.AllocateReg(Info->getFrameOffsetReg()); 1919 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 1920 } 1921 1922 auto &ArgUsageInfo = 1923 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 1924 ArgUsageInfo.setFuncArgInfo(MF.getFunction(), Info->getArgInfo()); 1925 1926 unsigned StackArgSize = CCInfo.getNextStackOffset(); 1927 Info->setBytesInStackArgArea(StackArgSize); 1928 1929 return Chains.empty() ? Chain : 1930 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 1931 } 1932 1933 // TODO: If return values can't fit in registers, we should return as many as 1934 // possible in registers before passing on stack. 1935 bool SITargetLowering::CanLowerReturn( 1936 CallingConv::ID CallConv, 1937 MachineFunction &MF, bool IsVarArg, 1938 const SmallVectorImpl<ISD::OutputArg> &Outs, 1939 LLVMContext &Context) const { 1940 // Replacing returns with sret/stack usage doesn't make sense for shaders. 1941 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 1942 // for shaders. Vector types should be explicitly handled by CC. 1943 if (AMDGPU::isEntryFunctionCC(CallConv)) 1944 return true; 1945 1946 SmallVector<CCValAssign, 16> RVLocs; 1947 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 1948 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 1949 } 1950 1951 SDValue 1952 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 1953 bool isVarArg, 1954 const SmallVectorImpl<ISD::OutputArg> &Outs, 1955 const SmallVectorImpl<SDValue> &OutVals, 1956 const SDLoc &DL, SelectionDAG &DAG) const { 1957 MachineFunction &MF = DAG.getMachineFunction(); 1958 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1959 1960 if (AMDGPU::isKernel(CallConv)) { 1961 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 1962 OutVals, DL, DAG); 1963 } 1964 1965 bool IsShader = AMDGPU::isShader(CallConv); 1966 1967 Info->setIfReturnsVoid(Outs.size() == 0); 1968 bool IsWaveEnd = Info->returnsVoid() && IsShader; 1969 1970 SmallVector<ISD::OutputArg, 48> Splits; 1971 SmallVector<SDValue, 48> SplitVals; 1972 1973 // Split vectors into their elements. 1974 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 1975 const ISD::OutputArg &Out = Outs[i]; 1976 1977 if (IsShader && Out.VT.isVector()) { 1978 MVT VT = Out.VT.getVectorElementType(); 1979 ISD::OutputArg NewOut = Out; 1980 NewOut.Flags.setSplit(); 1981 NewOut.VT = VT; 1982 1983 // We want the original number of vector elements here, e.g. 1984 // three or five, not four or eight. 1985 unsigned NumElements = Out.ArgVT.getVectorNumElements(); 1986 1987 for (unsigned j = 0; j != NumElements; ++j) { 1988 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i], 1989 DAG.getConstant(j, DL, MVT::i32)); 1990 SplitVals.push_back(Elem); 1991 Splits.push_back(NewOut); 1992 NewOut.PartOffset += NewOut.VT.getStoreSize(); 1993 } 1994 } else { 1995 SplitVals.push_back(OutVals[i]); 1996 Splits.push_back(Out); 1997 } 1998 } 1999 2000 // CCValAssign - represent the assignment of the return value to a location. 2001 SmallVector<CCValAssign, 48> RVLocs; 2002 2003 // CCState - Info about the registers and stack slots. 2004 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2005 *DAG.getContext()); 2006 2007 // Analyze outgoing return values. 2008 CCInfo.AnalyzeReturn(Splits, CCAssignFnForReturn(CallConv, isVarArg)); 2009 2010 SDValue Flag; 2011 SmallVector<SDValue, 48> RetOps; 2012 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2013 2014 // Add return address for callable functions. 2015 if (!Info->isEntryFunction()) { 2016 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2017 SDValue ReturnAddrReg = CreateLiveInRegister( 2018 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2019 2020 // FIXME: Should be able to use a vreg here, but need a way to prevent it 2021 // from being allcoated to a CSR. 2022 2023 SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2024 MVT::i64); 2025 2026 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag); 2027 Flag = Chain.getValue(1); 2028 2029 RetOps.push_back(PhysReturnAddrReg); 2030 } 2031 2032 // Copy the result values into the output registers. 2033 for (unsigned i = 0, realRVLocIdx = 0; 2034 i != RVLocs.size(); 2035 ++i, ++realRVLocIdx) { 2036 CCValAssign &VA = RVLocs[i]; 2037 assert(VA.isRegLoc() && "Can only return in registers!"); 2038 // TODO: Partially return in registers if return values don't fit. 2039 2040 SDValue Arg = SplitVals[realRVLocIdx]; 2041 2042 // Copied from other backends. 2043 switch (VA.getLocInfo()) { 2044 case CCValAssign::Full: 2045 break; 2046 case CCValAssign::BCvt: 2047 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2048 break; 2049 case CCValAssign::SExt: 2050 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2051 break; 2052 case CCValAssign::ZExt: 2053 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2054 break; 2055 case CCValAssign::AExt: 2056 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2057 break; 2058 default: 2059 llvm_unreachable("Unknown loc info!"); 2060 } 2061 2062 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2063 Flag = Chain.getValue(1); 2064 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2065 } 2066 2067 // FIXME: Does sret work properly? 2068 if (!Info->isEntryFunction()) { 2069 const SIRegisterInfo *TRI 2070 = static_cast<const SISubtarget *>(Subtarget)->getRegisterInfo(); 2071 const MCPhysReg *I = 2072 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2073 if (I) { 2074 for (; *I; ++I) { 2075 if (AMDGPU::SReg_64RegClass.contains(*I)) 2076 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2077 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2078 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2079 else 2080 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2081 } 2082 } 2083 } 2084 2085 // Update chain and glue. 2086 RetOps[0] = Chain; 2087 if (Flag.getNode()) 2088 RetOps.push_back(Flag); 2089 2090 unsigned Opc = AMDGPUISD::ENDPGM; 2091 if (!IsWaveEnd) 2092 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2093 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2094 } 2095 2096 SDValue SITargetLowering::LowerCallResult( 2097 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2098 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2099 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2100 SDValue ThisVal) const { 2101 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2102 2103 // Assign locations to each value returned by this call. 2104 SmallVector<CCValAssign, 16> RVLocs; 2105 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2106 *DAG.getContext()); 2107 CCInfo.AnalyzeCallResult(Ins, RetCC); 2108 2109 // Copy all of the result registers out of their specified physreg. 2110 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2111 CCValAssign VA = RVLocs[i]; 2112 SDValue Val; 2113 2114 if (VA.isRegLoc()) { 2115 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2116 Chain = Val.getValue(1); 2117 InFlag = Val.getValue(2); 2118 } else if (VA.isMemLoc()) { 2119 report_fatal_error("TODO: return values in memory"); 2120 } else 2121 llvm_unreachable("unknown argument location type"); 2122 2123 switch (VA.getLocInfo()) { 2124 case CCValAssign::Full: 2125 break; 2126 case CCValAssign::BCvt: 2127 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2128 break; 2129 case CCValAssign::ZExt: 2130 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2131 DAG.getValueType(VA.getValVT())); 2132 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2133 break; 2134 case CCValAssign::SExt: 2135 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2136 DAG.getValueType(VA.getValVT())); 2137 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2138 break; 2139 case CCValAssign::AExt: 2140 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2141 break; 2142 default: 2143 llvm_unreachable("Unknown loc info!"); 2144 } 2145 2146 InVals.push_back(Val); 2147 } 2148 2149 return Chain; 2150 } 2151 2152 // Add code to pass special inputs required depending on used features separate 2153 // from the explicit user arguments present in the IR. 2154 void SITargetLowering::passSpecialInputs( 2155 CallLoweringInfo &CLI, 2156 const SIMachineFunctionInfo &Info, 2157 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2158 SmallVectorImpl<SDValue> &MemOpChains, 2159 SDValue Chain, 2160 SDValue StackPtr) const { 2161 // If we don't have a call site, this was a call inserted by 2162 // legalization. These can never use special inputs. 2163 if (!CLI.CS) 2164 return; 2165 2166 const Function *CalleeFunc = CLI.CS.getCalledFunction(); 2167 assert(CalleeFunc); 2168 2169 SelectionDAG &DAG = CLI.DAG; 2170 const SDLoc &DL = CLI.DL; 2171 2172 const SISubtarget *ST = getSubtarget(); 2173 const SIRegisterInfo *TRI = ST->getRegisterInfo(); 2174 2175 auto &ArgUsageInfo = 2176 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2177 const AMDGPUFunctionArgInfo &CalleeArgInfo 2178 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2179 2180 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2181 2182 // TODO: Unify with private memory register handling. This is complicated by 2183 // the fact that at least in kernels, the input argument is not necessarily 2184 // in the same location as the input. 2185 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2186 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2187 AMDGPUFunctionArgInfo::QUEUE_PTR, 2188 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR, 2189 AMDGPUFunctionArgInfo::DISPATCH_ID, 2190 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2191 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2192 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z, 2193 AMDGPUFunctionArgInfo::WORKITEM_ID_X, 2194 AMDGPUFunctionArgInfo::WORKITEM_ID_Y, 2195 AMDGPUFunctionArgInfo::WORKITEM_ID_Z, 2196 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR 2197 }; 2198 2199 for (auto InputID : InputRegs) { 2200 const ArgDescriptor *OutgoingArg; 2201 const TargetRegisterClass *ArgRC; 2202 2203 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID); 2204 if (!OutgoingArg) 2205 continue; 2206 2207 const ArgDescriptor *IncomingArg; 2208 const TargetRegisterClass *IncomingArgRC; 2209 std::tie(IncomingArg, IncomingArgRC) 2210 = CallerArgInfo.getPreloadedValue(InputID); 2211 assert(IncomingArgRC == ArgRC); 2212 2213 // All special arguments are ints for now. 2214 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2215 SDValue InputReg; 2216 2217 if (IncomingArg) { 2218 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2219 } else { 2220 // The implicit arg ptr is special because it doesn't have a corresponding 2221 // input for kernels, and is computed from the kernarg segment pointer. 2222 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2223 InputReg = getImplicitArgPtr(DAG, DL); 2224 } 2225 2226 if (OutgoingArg->isRegister()) { 2227 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2228 } else { 2229 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, StackPtr, 2230 InputReg, 2231 OutgoingArg->getStackOffset()); 2232 MemOpChains.push_back(ArgStore); 2233 } 2234 } 2235 } 2236 2237 static bool canGuaranteeTCO(CallingConv::ID CC) { 2238 return CC == CallingConv::Fast; 2239 } 2240 2241 /// Return true if we might ever do TCO for calls with this calling convention. 2242 static bool mayTailCallThisCC(CallingConv::ID CC) { 2243 switch (CC) { 2244 case CallingConv::C: 2245 return true; 2246 default: 2247 return canGuaranteeTCO(CC); 2248 } 2249 } 2250 2251 bool SITargetLowering::isEligibleForTailCallOptimization( 2252 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2253 const SmallVectorImpl<ISD::OutputArg> &Outs, 2254 const SmallVectorImpl<SDValue> &OutVals, 2255 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2256 if (!mayTailCallThisCC(CalleeCC)) 2257 return false; 2258 2259 MachineFunction &MF = DAG.getMachineFunction(); 2260 const Function &CallerF = MF.getFunction(); 2261 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2262 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2263 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2264 2265 // Kernels aren't callable, and don't have a live in return address so it 2266 // doesn't make sense to do a tail call with entry functions. 2267 if (!CallerPreserved) 2268 return false; 2269 2270 bool CCMatch = CallerCC == CalleeCC; 2271 2272 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2273 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2274 return true; 2275 return false; 2276 } 2277 2278 // TODO: Can we handle var args? 2279 if (IsVarArg) 2280 return false; 2281 2282 for (const Argument &Arg : CallerF.args()) { 2283 if (Arg.hasByValAttr()) 2284 return false; 2285 } 2286 2287 LLVMContext &Ctx = *DAG.getContext(); 2288 2289 // Check that the call results are passed in the same way. 2290 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2291 CCAssignFnForCall(CalleeCC, IsVarArg), 2292 CCAssignFnForCall(CallerCC, IsVarArg))) 2293 return false; 2294 2295 // The callee has to preserve all registers the caller needs to preserve. 2296 if (!CCMatch) { 2297 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2298 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2299 return false; 2300 } 2301 2302 // Nothing more to check if the callee is taking no arguments. 2303 if (Outs.empty()) 2304 return true; 2305 2306 SmallVector<CCValAssign, 16> ArgLocs; 2307 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2308 2309 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2310 2311 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2312 // If the stack arguments for this call do not fit into our own save area then 2313 // the call cannot be made tail. 2314 // TODO: Is this really necessary? 2315 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2316 return false; 2317 2318 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2319 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2320 } 2321 2322 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2323 if (!CI->isTailCall()) 2324 return false; 2325 2326 const Function *ParentFn = CI->getParent()->getParent(); 2327 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2328 return false; 2329 2330 auto Attr = ParentFn->getFnAttribute("disable-tail-calls"); 2331 return (Attr.getValueAsString() != "true"); 2332 } 2333 2334 // The wave scratch offset register is used as the global base pointer. 2335 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2336 SmallVectorImpl<SDValue> &InVals) const { 2337 SelectionDAG &DAG = CLI.DAG; 2338 const SDLoc &DL = CLI.DL; 2339 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2340 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2341 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2342 SDValue Chain = CLI.Chain; 2343 SDValue Callee = CLI.Callee; 2344 bool &IsTailCall = CLI.IsTailCall; 2345 CallingConv::ID CallConv = CLI.CallConv; 2346 bool IsVarArg = CLI.IsVarArg; 2347 bool IsSibCall = false; 2348 bool IsThisReturn = false; 2349 MachineFunction &MF = DAG.getMachineFunction(); 2350 2351 if (IsVarArg) { 2352 return lowerUnhandledCall(CLI, InVals, 2353 "unsupported call to variadic function "); 2354 } 2355 2356 if (!CLI.CS.getCalledFunction()) { 2357 return lowerUnhandledCall(CLI, InVals, 2358 "unsupported indirect call to function "); 2359 } 2360 2361 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2362 return lowerUnhandledCall(CLI, InVals, 2363 "unsupported required tail call to function "); 2364 } 2365 2366 // The first 4 bytes are reserved for the callee's emergency stack slot. 2367 const unsigned CalleeUsableStackOffset = 4; 2368 2369 if (IsTailCall) { 2370 IsTailCall = isEligibleForTailCallOptimization( 2371 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2372 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) { 2373 report_fatal_error("failed to perform tail call elimination on a call " 2374 "site marked musttail"); 2375 } 2376 2377 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2378 2379 // A sibling call is one where we're under the usual C ABI and not planning 2380 // to change that but can still do a tail call: 2381 if (!TailCallOpt && IsTailCall) 2382 IsSibCall = true; 2383 2384 if (IsTailCall) 2385 ++NumTailCalls; 2386 } 2387 2388 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Callee)) { 2389 // FIXME: Remove this hack for function pointer types after removing 2390 // support of old address space mapping. In the new address space 2391 // mapping the pointer in default address space is 64 bit, therefore 2392 // does not need this hack. 2393 if (Callee.getValueType() == MVT::i32) { 2394 const GlobalValue *GV = GA->getGlobal(); 2395 Callee = DAG.getGlobalAddress(GV, DL, MVT::i64, GA->getOffset(), false, 2396 GA->getTargetFlags()); 2397 } 2398 } 2399 assert(Callee.getValueType() == MVT::i64); 2400 2401 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2402 2403 // Analyze operands of the call, assigning locations to each operand. 2404 SmallVector<CCValAssign, 16> ArgLocs; 2405 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2406 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2407 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2408 2409 // Get a count of how many bytes are to be pushed on the stack. 2410 unsigned NumBytes = CCInfo.getNextStackOffset(); 2411 2412 if (IsSibCall) { 2413 // Since we're not changing the ABI to make this a tail call, the memory 2414 // operands are already available in the caller's incoming argument space. 2415 NumBytes = 0; 2416 } 2417 2418 // FPDiff is the byte offset of the call's argument area from the callee's. 2419 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2420 // by this amount for a tail call. In a sibling call it must be 0 because the 2421 // caller will deallocate the entire stack and the callee still expects its 2422 // arguments to begin at SP+0. Completely unused for non-tail calls. 2423 int32_t FPDiff = 0; 2424 MachineFrameInfo &MFI = MF.getFrameInfo(); 2425 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2426 2427 SDValue CallerSavedFP; 2428 2429 // Adjust the stack pointer for the new arguments... 2430 // These operations are automatically eliminated by the prolog/epilog pass 2431 if (!IsSibCall) { 2432 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2433 2434 unsigned OffsetReg = Info->getScratchWaveOffsetReg(); 2435 2436 // In the HSA case, this should be an identity copy. 2437 SDValue ScratchRSrcReg 2438 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2439 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2440 2441 // TODO: Don't hardcode these registers and get from the callee function. 2442 SDValue ScratchWaveOffsetReg 2443 = DAG.getCopyFromReg(Chain, DL, OffsetReg, MVT::i32); 2444 RegsToPass.emplace_back(AMDGPU::SGPR4, ScratchWaveOffsetReg); 2445 2446 if (!Info->isEntryFunction()) { 2447 // Avoid clobbering this function's FP value. In the current convention 2448 // callee will overwrite this, so do save/restore around the call site. 2449 CallerSavedFP = DAG.getCopyFromReg(Chain, DL, 2450 Info->getFrameOffsetReg(), MVT::i32); 2451 } 2452 } 2453 2454 // Stack pointer relative accesses are done by changing the offset SGPR. This 2455 // is just the VGPR offset component. 2456 SDValue StackPtr = DAG.getConstant(CalleeUsableStackOffset, DL, MVT::i32); 2457 2458 SmallVector<SDValue, 8> MemOpChains; 2459 MVT PtrVT = MVT::i32; 2460 2461 // Walk the register/memloc assignments, inserting copies/loads. 2462 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 2463 ++i, ++realArgIdx) { 2464 CCValAssign &VA = ArgLocs[i]; 2465 SDValue Arg = OutVals[realArgIdx]; 2466 2467 // Promote the value if needed. 2468 switch (VA.getLocInfo()) { 2469 case CCValAssign::Full: 2470 break; 2471 case CCValAssign::BCvt: 2472 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2473 break; 2474 case CCValAssign::ZExt: 2475 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2476 break; 2477 case CCValAssign::SExt: 2478 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2479 break; 2480 case CCValAssign::AExt: 2481 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2482 break; 2483 case CCValAssign::FPExt: 2484 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2485 break; 2486 default: 2487 llvm_unreachable("Unknown loc info!"); 2488 } 2489 2490 if (VA.isRegLoc()) { 2491 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2492 } else { 2493 assert(VA.isMemLoc()); 2494 2495 SDValue DstAddr; 2496 MachinePointerInfo DstInfo; 2497 2498 unsigned LocMemOffset = VA.getLocMemOffset(); 2499 int32_t Offset = LocMemOffset; 2500 2501 SDValue PtrOff = DAG.getObjectPtrOffset(DL, StackPtr, Offset); 2502 2503 if (IsTailCall) { 2504 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2505 unsigned OpSize = Flags.isByVal() ? 2506 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2507 2508 Offset = Offset + FPDiff; 2509 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2510 2511 DstAddr = DAG.getObjectPtrOffset(DL, DAG.getFrameIndex(FI, PtrVT), 2512 StackPtr); 2513 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2514 2515 // Make sure any stack arguments overlapping with where we're storing 2516 // are loaded before this eventual operation. Otherwise they'll be 2517 // clobbered. 2518 2519 // FIXME: Why is this really necessary? This seems to just result in a 2520 // lot of code to copy the stack and write them back to the same 2521 // locations, which are supposed to be immutable? 2522 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2523 } else { 2524 DstAddr = PtrOff; 2525 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2526 } 2527 2528 if (Outs[i].Flags.isByVal()) { 2529 SDValue SizeNode = 2530 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2531 SDValue Cpy = DAG.getMemcpy( 2532 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 2533 /*isVol = */ false, /*AlwaysInline = */ true, 2534 /*isTailCall = */ false, DstInfo, 2535 MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy( 2536 *DAG.getContext(), AMDGPUASI.PRIVATE_ADDRESS)))); 2537 2538 MemOpChains.push_back(Cpy); 2539 } else { 2540 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo); 2541 MemOpChains.push_back(Store); 2542 } 2543 } 2544 } 2545 2546 // Copy special input registers after user input arguments. 2547 passSpecialInputs(CLI, *Info, RegsToPass, MemOpChains, Chain, StackPtr); 2548 2549 if (!MemOpChains.empty()) 2550 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2551 2552 // Build a sequence of copy-to-reg nodes chained together with token chain 2553 // and flag operands which copy the outgoing args into the appropriate regs. 2554 SDValue InFlag; 2555 for (auto &RegToPass : RegsToPass) { 2556 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2557 RegToPass.second, InFlag); 2558 InFlag = Chain.getValue(1); 2559 } 2560 2561 2562 SDValue PhysReturnAddrReg; 2563 if (IsTailCall) { 2564 // Since the return is being combined with the call, we need to pass on the 2565 // return address. 2566 2567 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2568 SDValue ReturnAddrReg = CreateLiveInRegister( 2569 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2570 2571 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2572 MVT::i64); 2573 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2574 InFlag = Chain.getValue(1); 2575 } 2576 2577 // We don't usually want to end the call-sequence here because we would tidy 2578 // the frame up *after* the call, however in the ABI-changing tail-call case 2579 // we've carefully laid out the parameters so that when sp is reset they'll be 2580 // in the correct location. 2581 if (IsTailCall && !IsSibCall) { 2582 Chain = DAG.getCALLSEQ_END(Chain, 2583 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2584 DAG.getTargetConstant(0, DL, MVT::i32), 2585 InFlag, DL); 2586 InFlag = Chain.getValue(1); 2587 } 2588 2589 std::vector<SDValue> Ops; 2590 Ops.push_back(Chain); 2591 Ops.push_back(Callee); 2592 2593 if (IsTailCall) { 2594 // Each tail call may have to adjust the stack by a different amount, so 2595 // this information must travel along with the operation for eventual 2596 // consumption by emitEpilogue. 2597 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 2598 2599 Ops.push_back(PhysReturnAddrReg); 2600 } 2601 2602 // Add argument registers to the end of the list so that they are known live 2603 // into the call. 2604 for (auto &RegToPass : RegsToPass) { 2605 Ops.push_back(DAG.getRegister(RegToPass.first, 2606 RegToPass.second.getValueType())); 2607 } 2608 2609 // Add a register mask operand representing the call-preserved registers. 2610 2611 const AMDGPURegisterInfo *TRI = Subtarget->getRegisterInfo(); 2612 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2613 assert(Mask && "Missing call preserved mask for calling convention"); 2614 Ops.push_back(DAG.getRegisterMask(Mask)); 2615 2616 if (InFlag.getNode()) 2617 Ops.push_back(InFlag); 2618 2619 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2620 2621 // If we're doing a tall call, use a TC_RETURN here rather than an 2622 // actual call instruction. 2623 if (IsTailCall) { 2624 MFI.setHasTailCall(); 2625 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 2626 } 2627 2628 // Returns a chain and a flag for retval copy to use. 2629 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 2630 Chain = Call.getValue(0); 2631 InFlag = Call.getValue(1); 2632 2633 if (CallerSavedFP) { 2634 SDValue FPReg = DAG.getRegister(Info->getFrameOffsetReg(), MVT::i32); 2635 Chain = DAG.getCopyToReg(Chain, DL, FPReg, CallerSavedFP, InFlag); 2636 InFlag = Chain.getValue(1); 2637 } 2638 2639 uint64_t CalleePopBytes = NumBytes; 2640 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 2641 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 2642 InFlag, DL); 2643 if (!Ins.empty()) 2644 InFlag = Chain.getValue(1); 2645 2646 // Handle result values, copying them out of physregs into vregs that we 2647 // return. 2648 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 2649 InVals, IsThisReturn, 2650 IsThisReturn ? OutVals[0] : SDValue()); 2651 } 2652 2653 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT, 2654 SelectionDAG &DAG) const { 2655 unsigned Reg = StringSwitch<unsigned>(RegName) 2656 .Case("m0", AMDGPU::M0) 2657 .Case("exec", AMDGPU::EXEC) 2658 .Case("exec_lo", AMDGPU::EXEC_LO) 2659 .Case("exec_hi", AMDGPU::EXEC_HI) 2660 .Case("flat_scratch", AMDGPU::FLAT_SCR) 2661 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 2662 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 2663 .Default(AMDGPU::NoRegister); 2664 2665 if (Reg == AMDGPU::NoRegister) { 2666 report_fatal_error(Twine("invalid register name \"" 2667 + StringRef(RegName) + "\".")); 2668 2669 } 2670 2671 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS && 2672 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 2673 report_fatal_error(Twine("invalid register \"" 2674 + StringRef(RegName) + "\" for subtarget.")); 2675 } 2676 2677 switch (Reg) { 2678 case AMDGPU::M0: 2679 case AMDGPU::EXEC_LO: 2680 case AMDGPU::EXEC_HI: 2681 case AMDGPU::FLAT_SCR_LO: 2682 case AMDGPU::FLAT_SCR_HI: 2683 if (VT.getSizeInBits() == 32) 2684 return Reg; 2685 break; 2686 case AMDGPU::EXEC: 2687 case AMDGPU::FLAT_SCR: 2688 if (VT.getSizeInBits() == 64) 2689 return Reg; 2690 break; 2691 default: 2692 llvm_unreachable("missing register type checking"); 2693 } 2694 2695 report_fatal_error(Twine("invalid type for register \"" 2696 + StringRef(RegName) + "\".")); 2697 } 2698 2699 // If kill is not the last instruction, split the block so kill is always a 2700 // proper terminator. 2701 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 2702 MachineBasicBlock *BB) const { 2703 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 2704 2705 MachineBasicBlock::iterator SplitPoint(&MI); 2706 ++SplitPoint; 2707 2708 if (SplitPoint == BB->end()) { 2709 // Don't bother with a new block. 2710 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 2711 return BB; 2712 } 2713 2714 MachineFunction *MF = BB->getParent(); 2715 MachineBasicBlock *SplitBB 2716 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 2717 2718 MF->insert(++MachineFunction::iterator(BB), SplitBB); 2719 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 2720 2721 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 2722 BB->addSuccessor(SplitBB); 2723 2724 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 2725 return SplitBB; 2726 } 2727 2728 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 2729 // wavefront. If the value is uniform and just happens to be in a VGPR, this 2730 // will only do one iteration. In the worst case, this will loop 64 times. 2731 // 2732 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 2733 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 2734 const SIInstrInfo *TII, 2735 MachineRegisterInfo &MRI, 2736 MachineBasicBlock &OrigBB, 2737 MachineBasicBlock &LoopBB, 2738 const DebugLoc &DL, 2739 const MachineOperand &IdxReg, 2740 unsigned InitReg, 2741 unsigned ResultReg, 2742 unsigned PhiReg, 2743 unsigned InitSaveExecReg, 2744 int Offset, 2745 bool UseGPRIdxMode) { 2746 MachineBasicBlock::iterator I = LoopBB.begin(); 2747 2748 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2749 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2750 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 2751 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2752 2753 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 2754 .addReg(InitReg) 2755 .addMBB(&OrigBB) 2756 .addReg(ResultReg) 2757 .addMBB(&LoopBB); 2758 2759 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 2760 .addReg(InitSaveExecReg) 2761 .addMBB(&OrigBB) 2762 .addReg(NewExec) 2763 .addMBB(&LoopBB); 2764 2765 // Read the next variant <- also loop target. 2766 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 2767 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 2768 2769 // Compare the just read M0 value to all possible Idx values. 2770 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 2771 .addReg(CurrentIdxReg) 2772 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 2773 2774 if (UseGPRIdxMode) { 2775 unsigned IdxReg; 2776 if (Offset == 0) { 2777 IdxReg = CurrentIdxReg; 2778 } else { 2779 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 2780 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 2781 .addReg(CurrentIdxReg, RegState::Kill) 2782 .addImm(Offset); 2783 } 2784 2785 MachineInstr *SetIdx = 2786 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_IDX)) 2787 .addReg(IdxReg, RegState::Kill); 2788 SetIdx->getOperand(2).setIsUndef(); 2789 } else { 2790 // Move index from VCC into M0 2791 if (Offset == 0) { 2792 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 2793 .addReg(CurrentIdxReg, RegState::Kill); 2794 } else { 2795 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 2796 .addReg(CurrentIdxReg, RegState::Kill) 2797 .addImm(Offset); 2798 } 2799 } 2800 2801 // Update EXEC, save the original EXEC value to VCC. 2802 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec) 2803 .addReg(CondReg, RegState::Kill); 2804 2805 MRI.setSimpleHint(NewExec, CondReg); 2806 2807 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 2808 MachineInstr *InsertPt = 2809 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC) 2810 .addReg(AMDGPU::EXEC) 2811 .addReg(NewExec); 2812 2813 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 2814 // s_cbranch_scc0? 2815 2816 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 2817 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 2818 .addMBB(&LoopBB); 2819 2820 return InsertPt->getIterator(); 2821 } 2822 2823 // This has slightly sub-optimal regalloc when the source vector is killed by 2824 // the read. The register allocator does not understand that the kill is 2825 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 2826 // subregister from it, using 1 more VGPR than necessary. This was saved when 2827 // this was expanded after register allocation. 2828 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 2829 MachineBasicBlock &MBB, 2830 MachineInstr &MI, 2831 unsigned InitResultReg, 2832 unsigned PhiReg, 2833 int Offset, 2834 bool UseGPRIdxMode) { 2835 MachineFunction *MF = MBB.getParent(); 2836 MachineRegisterInfo &MRI = MF->getRegInfo(); 2837 const DebugLoc &DL = MI.getDebugLoc(); 2838 MachineBasicBlock::iterator I(&MI); 2839 2840 unsigned DstReg = MI.getOperand(0).getReg(); 2841 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass); 2842 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass); 2843 2844 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 2845 2846 // Save the EXEC mask 2847 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec) 2848 .addReg(AMDGPU::EXEC); 2849 2850 // To insert the loop we need to split the block. Move everything after this 2851 // point to a new block, and insert a new empty block between the two. 2852 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 2853 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 2854 MachineFunction::iterator MBBI(MBB); 2855 ++MBBI; 2856 2857 MF->insert(MBBI, LoopBB); 2858 MF->insert(MBBI, RemainderBB); 2859 2860 LoopBB->addSuccessor(LoopBB); 2861 LoopBB->addSuccessor(RemainderBB); 2862 2863 // Move the rest of the block into a new block. 2864 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 2865 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 2866 2867 MBB.addSuccessor(LoopBB); 2868 2869 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 2870 2871 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 2872 InitResultReg, DstReg, PhiReg, TmpExec, 2873 Offset, UseGPRIdxMode); 2874 2875 MachineBasicBlock::iterator First = RemainderBB->begin(); 2876 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC) 2877 .addReg(SaveExec); 2878 2879 return InsPt; 2880 } 2881 2882 // Returns subreg index, offset 2883 static std::pair<unsigned, int> 2884 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 2885 const TargetRegisterClass *SuperRC, 2886 unsigned VecReg, 2887 int Offset) { 2888 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 2889 2890 // Skip out of bounds offsets, or else we would end up using an undefined 2891 // register. 2892 if (Offset >= NumElts || Offset < 0) 2893 return std::make_pair(AMDGPU::sub0, Offset); 2894 2895 return std::make_pair(AMDGPU::sub0 + Offset, 0); 2896 } 2897 2898 // Return true if the index is an SGPR and was set. 2899 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 2900 MachineRegisterInfo &MRI, 2901 MachineInstr &MI, 2902 int Offset, 2903 bool UseGPRIdxMode, 2904 bool IsIndirectSrc) { 2905 MachineBasicBlock *MBB = MI.getParent(); 2906 const DebugLoc &DL = MI.getDebugLoc(); 2907 MachineBasicBlock::iterator I(&MI); 2908 2909 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 2910 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 2911 2912 assert(Idx->getReg() != AMDGPU::NoRegister); 2913 2914 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 2915 return false; 2916 2917 if (UseGPRIdxMode) { 2918 unsigned IdxMode = IsIndirectSrc ? 2919 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE; 2920 if (Offset == 0) { 2921 MachineInstr *SetOn = 2922 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2923 .add(*Idx) 2924 .addImm(IdxMode); 2925 2926 SetOn->getOperand(3).setIsUndef(); 2927 } else { 2928 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 2929 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 2930 .add(*Idx) 2931 .addImm(Offset); 2932 MachineInstr *SetOn = 2933 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2934 .addReg(Tmp, RegState::Kill) 2935 .addImm(IdxMode); 2936 2937 SetOn->getOperand(3).setIsUndef(); 2938 } 2939 2940 return true; 2941 } 2942 2943 if (Offset == 0) { 2944 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 2945 .add(*Idx); 2946 } else { 2947 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 2948 .add(*Idx) 2949 .addImm(Offset); 2950 } 2951 2952 return true; 2953 } 2954 2955 // Control flow needs to be inserted if indexing with a VGPR. 2956 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 2957 MachineBasicBlock &MBB, 2958 const SISubtarget &ST) { 2959 const SIInstrInfo *TII = ST.getInstrInfo(); 2960 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 2961 MachineFunction *MF = MBB.getParent(); 2962 MachineRegisterInfo &MRI = MF->getRegInfo(); 2963 2964 unsigned Dst = MI.getOperand(0).getReg(); 2965 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 2966 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 2967 2968 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 2969 2970 unsigned SubReg; 2971 std::tie(SubReg, Offset) 2972 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 2973 2974 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 2975 2976 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 2977 MachineBasicBlock::iterator I(&MI); 2978 const DebugLoc &DL = MI.getDebugLoc(); 2979 2980 if (UseGPRIdxMode) { 2981 // TODO: Look at the uses to avoid the copy. This may require rescheduling 2982 // to avoid interfering with other uses, so probably requires a new 2983 // optimization pass. 2984 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 2985 .addReg(SrcReg, RegState::Undef, SubReg) 2986 .addReg(SrcReg, RegState::Implicit) 2987 .addReg(AMDGPU::M0, RegState::Implicit); 2988 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2989 } else { 2990 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 2991 .addReg(SrcReg, RegState::Undef, SubReg) 2992 .addReg(SrcReg, RegState::Implicit); 2993 } 2994 2995 MI.eraseFromParent(); 2996 2997 return &MBB; 2998 } 2999 3000 const DebugLoc &DL = MI.getDebugLoc(); 3001 MachineBasicBlock::iterator I(&MI); 3002 3003 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3004 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3005 3006 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3007 3008 if (UseGPRIdxMode) { 3009 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3010 .addImm(0) // Reset inside loop. 3011 .addImm(VGPRIndexMode::SRC0_ENABLE); 3012 SetOn->getOperand(3).setIsUndef(); 3013 3014 // Disable again after the loop. 3015 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3016 } 3017 3018 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, UseGPRIdxMode); 3019 MachineBasicBlock *LoopBB = InsPt->getParent(); 3020 3021 if (UseGPRIdxMode) { 3022 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3023 .addReg(SrcReg, RegState::Undef, SubReg) 3024 .addReg(SrcReg, RegState::Implicit) 3025 .addReg(AMDGPU::M0, RegState::Implicit); 3026 } else { 3027 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3028 .addReg(SrcReg, RegState::Undef, SubReg) 3029 .addReg(SrcReg, RegState::Implicit); 3030 } 3031 3032 MI.eraseFromParent(); 3033 3034 return LoopBB; 3035 } 3036 3037 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI, 3038 const TargetRegisterClass *VecRC) { 3039 switch (TRI.getRegSizeInBits(*VecRC)) { 3040 case 32: // 4 bytes 3041 return AMDGPU::V_MOVRELD_B32_V1; 3042 case 64: // 8 bytes 3043 return AMDGPU::V_MOVRELD_B32_V2; 3044 case 128: // 16 bytes 3045 return AMDGPU::V_MOVRELD_B32_V4; 3046 case 256: // 32 bytes 3047 return AMDGPU::V_MOVRELD_B32_V8; 3048 case 512: // 64 bytes 3049 return AMDGPU::V_MOVRELD_B32_V16; 3050 default: 3051 llvm_unreachable("unsupported size for MOVRELD pseudos"); 3052 } 3053 } 3054 3055 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3056 MachineBasicBlock &MBB, 3057 const SISubtarget &ST) { 3058 const SIInstrInfo *TII = ST.getInstrInfo(); 3059 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3060 MachineFunction *MF = MBB.getParent(); 3061 MachineRegisterInfo &MRI = MF->getRegInfo(); 3062 3063 unsigned Dst = MI.getOperand(0).getReg(); 3064 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3065 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3066 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3067 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3068 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3069 3070 // This can be an immediate, but will be folded later. 3071 assert(Val->getReg()); 3072 3073 unsigned SubReg; 3074 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3075 SrcVec->getReg(), 3076 Offset); 3077 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 3078 3079 if (Idx->getReg() == AMDGPU::NoRegister) { 3080 MachineBasicBlock::iterator I(&MI); 3081 const DebugLoc &DL = MI.getDebugLoc(); 3082 3083 assert(Offset == 0); 3084 3085 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3086 .add(*SrcVec) 3087 .add(*Val) 3088 .addImm(SubReg); 3089 3090 MI.eraseFromParent(); 3091 return &MBB; 3092 } 3093 3094 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3095 MachineBasicBlock::iterator I(&MI); 3096 const DebugLoc &DL = MI.getDebugLoc(); 3097 3098 if (UseGPRIdxMode) { 3099 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 3100 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst 3101 .add(*Val) 3102 .addReg(Dst, RegState::ImplicitDefine) 3103 .addReg(SrcVec->getReg(), RegState::Implicit) 3104 .addReg(AMDGPU::M0, RegState::Implicit); 3105 3106 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3107 } else { 3108 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 3109 3110 BuildMI(MBB, I, DL, MovRelDesc) 3111 .addReg(Dst, RegState::Define) 3112 .addReg(SrcVec->getReg()) 3113 .add(*Val) 3114 .addImm(SubReg - AMDGPU::sub0); 3115 } 3116 3117 MI.eraseFromParent(); 3118 return &MBB; 3119 } 3120 3121 if (Val->isReg()) 3122 MRI.clearKillFlags(Val->getReg()); 3123 3124 const DebugLoc &DL = MI.getDebugLoc(); 3125 3126 if (UseGPRIdxMode) { 3127 MachineBasicBlock::iterator I(&MI); 3128 3129 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3130 .addImm(0) // Reset inside loop. 3131 .addImm(VGPRIndexMode::DST_ENABLE); 3132 SetOn->getOperand(3).setIsUndef(); 3133 3134 // Disable again after the loop. 3135 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3136 } 3137 3138 unsigned PhiReg = MRI.createVirtualRegister(VecRC); 3139 3140 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3141 Offset, UseGPRIdxMode); 3142 MachineBasicBlock *LoopBB = InsPt->getParent(); 3143 3144 if (UseGPRIdxMode) { 3145 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 3146 .addReg(PhiReg, RegState::Undef, SubReg) // vdst 3147 .add(*Val) // src0 3148 .addReg(Dst, RegState::ImplicitDefine) 3149 .addReg(PhiReg, RegState::Implicit) 3150 .addReg(AMDGPU::M0, RegState::Implicit); 3151 } else { 3152 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 3153 3154 BuildMI(*LoopBB, InsPt, DL, MovRelDesc) 3155 .addReg(Dst, RegState::Define) 3156 .addReg(PhiReg) 3157 .add(*Val) 3158 .addImm(SubReg - AMDGPU::sub0); 3159 } 3160 3161 MI.eraseFromParent(); 3162 3163 return LoopBB; 3164 } 3165 3166 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3167 MachineInstr &MI, MachineBasicBlock *BB) const { 3168 3169 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3170 MachineFunction *MF = BB->getParent(); 3171 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3172 3173 if (TII->isMIMG(MI)) { 3174 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 3175 report_fatal_error("missing mem operand from MIMG instruction"); 3176 } 3177 // Add a memoperand for mimg instructions so that they aren't assumed to 3178 // be ordered memory instuctions. 3179 3180 return BB; 3181 } 3182 3183 switch (MI.getOpcode()) { 3184 case AMDGPU::S_ADD_U64_PSEUDO: 3185 case AMDGPU::S_SUB_U64_PSEUDO: { 3186 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3187 const DebugLoc &DL = MI.getDebugLoc(); 3188 3189 MachineOperand &Dest = MI.getOperand(0); 3190 MachineOperand &Src0 = MI.getOperand(1); 3191 MachineOperand &Src1 = MI.getOperand(2); 3192 3193 unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3194 unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3195 3196 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3197 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub0, 3198 &AMDGPU::SReg_32_XM0RegClass); 3199 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3200 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub1, 3201 &AMDGPU::SReg_32_XM0RegClass); 3202 3203 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3204 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub0, 3205 &AMDGPU::SReg_32_XM0RegClass); 3206 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3207 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub1, 3208 &AMDGPU::SReg_32_XM0RegClass); 3209 3210 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3211 3212 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3213 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3214 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3215 .add(Src0Sub0) 3216 .add(Src1Sub0); 3217 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3218 .add(Src0Sub1) 3219 .add(Src1Sub1); 3220 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3221 .addReg(DestSub0) 3222 .addImm(AMDGPU::sub0) 3223 .addReg(DestSub1) 3224 .addImm(AMDGPU::sub1); 3225 MI.eraseFromParent(); 3226 return BB; 3227 } 3228 case AMDGPU::SI_INIT_M0: { 3229 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3230 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3231 .add(MI.getOperand(0)); 3232 MI.eraseFromParent(); 3233 return BB; 3234 } 3235 case AMDGPU::SI_INIT_EXEC: 3236 // This should be before all vector instructions. 3237 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3238 AMDGPU::EXEC) 3239 .addImm(MI.getOperand(0).getImm()); 3240 MI.eraseFromParent(); 3241 return BB; 3242 3243 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3244 // Extract the thread count from an SGPR input and set EXEC accordingly. 3245 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3246 // 3247 // S_BFE_U32 count, input, {shift, 7} 3248 // S_BFM_B64 exec, count, 0 3249 // S_CMP_EQ_U32 count, 64 3250 // S_CMOV_B64 exec, -1 3251 MachineInstr *FirstMI = &*BB->begin(); 3252 MachineRegisterInfo &MRI = MF->getRegInfo(); 3253 unsigned InputReg = MI.getOperand(0).getReg(); 3254 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3255 bool Found = false; 3256 3257 // Move the COPY of the input reg to the beginning, so that we can use it. 3258 for (auto I = BB->begin(); I != &MI; I++) { 3259 if (I->getOpcode() != TargetOpcode::COPY || 3260 I->getOperand(0).getReg() != InputReg) 3261 continue; 3262 3263 if (I == FirstMI) { 3264 FirstMI = &*++BB->begin(); 3265 } else { 3266 I->removeFromParent(); 3267 BB->insert(FirstMI, &*I); 3268 } 3269 Found = true; 3270 break; 3271 } 3272 assert(Found); 3273 (void)Found; 3274 3275 // This should be before all vector instructions. 3276 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3277 .addReg(InputReg) 3278 .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000); 3279 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64), 3280 AMDGPU::EXEC) 3281 .addReg(CountReg) 3282 .addImm(0); 3283 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3284 .addReg(CountReg, RegState::Kill) 3285 .addImm(64); 3286 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64), 3287 AMDGPU::EXEC) 3288 .addImm(-1); 3289 MI.eraseFromParent(); 3290 return BB; 3291 } 3292 3293 case AMDGPU::GET_GROUPSTATICSIZE: { 3294 DebugLoc DL = MI.getDebugLoc(); 3295 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3296 .add(MI.getOperand(0)) 3297 .addImm(MFI->getLDSSize()); 3298 MI.eraseFromParent(); 3299 return BB; 3300 } 3301 case AMDGPU::SI_INDIRECT_SRC_V1: 3302 case AMDGPU::SI_INDIRECT_SRC_V2: 3303 case AMDGPU::SI_INDIRECT_SRC_V4: 3304 case AMDGPU::SI_INDIRECT_SRC_V8: 3305 case AMDGPU::SI_INDIRECT_SRC_V16: 3306 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3307 case AMDGPU::SI_INDIRECT_DST_V1: 3308 case AMDGPU::SI_INDIRECT_DST_V2: 3309 case AMDGPU::SI_INDIRECT_DST_V4: 3310 case AMDGPU::SI_INDIRECT_DST_V8: 3311 case AMDGPU::SI_INDIRECT_DST_V16: 3312 return emitIndirectDst(MI, *BB, *getSubtarget()); 3313 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3314 case AMDGPU::SI_KILL_I1_PSEUDO: 3315 return splitKillBlock(MI, BB); 3316 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3317 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3318 3319 unsigned Dst = MI.getOperand(0).getReg(); 3320 unsigned Src0 = MI.getOperand(1).getReg(); 3321 unsigned Src1 = MI.getOperand(2).getReg(); 3322 const DebugLoc &DL = MI.getDebugLoc(); 3323 unsigned SrcCond = MI.getOperand(3).getReg(); 3324 3325 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3326 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3327 unsigned SrcCondCopy = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass); 3328 3329 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3330 .addReg(SrcCond); 3331 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3332 .addReg(Src0, 0, AMDGPU::sub0) 3333 .addReg(Src1, 0, AMDGPU::sub0) 3334 .addReg(SrcCondCopy); 3335 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3336 .addReg(Src0, 0, AMDGPU::sub1) 3337 .addReg(Src1, 0, AMDGPU::sub1) 3338 .addReg(SrcCondCopy); 3339 3340 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3341 .addReg(DstLo) 3342 .addImm(AMDGPU::sub0) 3343 .addReg(DstHi) 3344 .addImm(AMDGPU::sub1); 3345 MI.eraseFromParent(); 3346 return BB; 3347 } 3348 case AMDGPU::SI_BR_UNDEF: { 3349 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3350 const DebugLoc &DL = MI.getDebugLoc(); 3351 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3352 .add(MI.getOperand(0)); 3353 Br->getOperand(1).setIsUndef(true); // read undef SCC 3354 MI.eraseFromParent(); 3355 return BB; 3356 } 3357 case AMDGPU::ADJCALLSTACKUP: 3358 case AMDGPU::ADJCALLSTACKDOWN: { 3359 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3360 MachineInstrBuilder MIB(*MF, &MI); 3361 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3362 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 3363 return BB; 3364 } 3365 case AMDGPU::SI_CALL_ISEL: 3366 case AMDGPU::SI_TCRETURN_ISEL: { 3367 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3368 const DebugLoc &DL = MI.getDebugLoc(); 3369 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3370 3371 MachineRegisterInfo &MRI = MF->getRegInfo(); 3372 unsigned GlobalAddrReg = MI.getOperand(0).getReg(); 3373 MachineInstr *PCRel = MRI.getVRegDef(GlobalAddrReg); 3374 assert(PCRel->getOpcode() == AMDGPU::SI_PC_ADD_REL_OFFSET); 3375 3376 const GlobalValue *G = PCRel->getOperand(1).getGlobal(); 3377 3378 MachineInstrBuilder MIB; 3379 if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) { 3380 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg) 3381 .add(MI.getOperand(0)) 3382 .addGlobalAddress(G); 3383 } else { 3384 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_TCRETURN)) 3385 .add(MI.getOperand(0)) 3386 .addGlobalAddress(G); 3387 3388 // There is an additional imm operand for tcreturn, but it should be in the 3389 // right place already. 3390 } 3391 3392 for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I) 3393 MIB.add(MI.getOperand(I)); 3394 3395 MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end()); 3396 MI.eraseFromParent(); 3397 return BB; 3398 } 3399 default: 3400 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3401 } 3402 } 3403 3404 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 3405 return isTypeLegal(VT.getScalarType()); 3406 } 3407 3408 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3409 // This currently forces unfolding various combinations of fsub into fma with 3410 // free fneg'd operands. As long as we have fast FMA (controlled by 3411 // isFMAFasterThanFMulAndFAdd), we should perform these. 3412 3413 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3414 // most of these combines appear to be cycle neutral but save on instruction 3415 // count / code size. 3416 return true; 3417 } 3418 3419 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3420 EVT VT) const { 3421 if (!VT.isVector()) { 3422 return MVT::i1; 3423 } 3424 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3425 } 3426 3427 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3428 // TODO: Should i16 be used always if legal? For now it would force VALU 3429 // shifts. 3430 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3431 } 3432 3433 // Answering this is somewhat tricky and depends on the specific device which 3434 // have different rates for fma or all f64 operations. 3435 // 3436 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3437 // regardless of which device (although the number of cycles differs between 3438 // devices), so it is always profitable for f64. 3439 // 3440 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3441 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3442 // which we can always do even without fused FP ops since it returns the same 3443 // result as the separate operations and since it is always full 3444 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3445 // however does not support denormals, so we do report fma as faster if we have 3446 // a fast fma device and require denormals. 3447 // 3448 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 3449 VT = VT.getScalarType(); 3450 3451 switch (VT.getSimpleVT().SimpleTy) { 3452 case MVT::f32: 3453 // This is as fast on some subtargets. However, we always have full rate f32 3454 // mad available which returns the same result as the separate operations 3455 // which we should prefer over fma. We can't use this if we want to support 3456 // denormals, so only report this in these cases. 3457 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32(); 3458 case MVT::f64: 3459 return true; 3460 case MVT::f16: 3461 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals(); 3462 default: 3463 break; 3464 } 3465 3466 return false; 3467 } 3468 3469 //===----------------------------------------------------------------------===// 3470 // Custom DAG Lowering Operations 3471 //===----------------------------------------------------------------------===// 3472 3473 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 3474 switch (Op.getOpcode()) { 3475 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 3476 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 3477 case ISD::LOAD: { 3478 SDValue Result = LowerLOAD(Op, DAG); 3479 assert((!Result.getNode() || 3480 Result.getNode()->getNumValues() == 2) && 3481 "Load should return a value and a chain"); 3482 return Result; 3483 } 3484 3485 case ISD::FSIN: 3486 case ISD::FCOS: 3487 return LowerTrig(Op, DAG); 3488 case ISD::SELECT: return LowerSELECT(Op, DAG); 3489 case ISD::FDIV: return LowerFDIV(Op, DAG); 3490 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 3491 case ISD::STORE: return LowerSTORE(Op, DAG); 3492 case ISD::GlobalAddress: { 3493 MachineFunction &MF = DAG.getMachineFunction(); 3494 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 3495 return LowerGlobalAddress(MFI, Op, DAG); 3496 } 3497 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3498 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 3499 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 3500 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 3501 case ISD::INSERT_VECTOR_ELT: 3502 return lowerINSERT_VECTOR_ELT(Op, DAG); 3503 case ISD::EXTRACT_VECTOR_ELT: 3504 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3505 case ISD::FP_ROUND: 3506 return lowerFP_ROUND(Op, DAG); 3507 case ISD::TRAP: 3508 case ISD::DEBUGTRAP: 3509 return lowerTRAP(Op, DAG); 3510 } 3511 return SDValue(); 3512 } 3513 3514 static unsigned getImageOpcode(unsigned IID) { 3515 switch (IID) { 3516 case Intrinsic::amdgcn_image_load: 3517 return AMDGPUISD::IMAGE_LOAD; 3518 case Intrinsic::amdgcn_image_load_mip: 3519 return AMDGPUISD::IMAGE_LOAD_MIP; 3520 3521 // Basic sample. 3522 case Intrinsic::amdgcn_image_sample: 3523 return AMDGPUISD::IMAGE_SAMPLE; 3524 case Intrinsic::amdgcn_image_sample_cl: 3525 return AMDGPUISD::IMAGE_SAMPLE_CL; 3526 case Intrinsic::amdgcn_image_sample_d: 3527 return AMDGPUISD::IMAGE_SAMPLE_D; 3528 case Intrinsic::amdgcn_image_sample_d_cl: 3529 return AMDGPUISD::IMAGE_SAMPLE_D_CL; 3530 case Intrinsic::amdgcn_image_sample_l: 3531 return AMDGPUISD::IMAGE_SAMPLE_L; 3532 case Intrinsic::amdgcn_image_sample_b: 3533 return AMDGPUISD::IMAGE_SAMPLE_B; 3534 case Intrinsic::amdgcn_image_sample_b_cl: 3535 return AMDGPUISD::IMAGE_SAMPLE_B_CL; 3536 case Intrinsic::amdgcn_image_sample_lz: 3537 return AMDGPUISD::IMAGE_SAMPLE_LZ; 3538 case Intrinsic::amdgcn_image_sample_cd: 3539 return AMDGPUISD::IMAGE_SAMPLE_CD; 3540 case Intrinsic::amdgcn_image_sample_cd_cl: 3541 return AMDGPUISD::IMAGE_SAMPLE_CD_CL; 3542 3543 // Sample with comparison. 3544 case Intrinsic::amdgcn_image_sample_c: 3545 return AMDGPUISD::IMAGE_SAMPLE_C; 3546 case Intrinsic::amdgcn_image_sample_c_cl: 3547 return AMDGPUISD::IMAGE_SAMPLE_C_CL; 3548 case Intrinsic::amdgcn_image_sample_c_d: 3549 return AMDGPUISD::IMAGE_SAMPLE_C_D; 3550 case Intrinsic::amdgcn_image_sample_c_d_cl: 3551 return AMDGPUISD::IMAGE_SAMPLE_C_D_CL; 3552 case Intrinsic::amdgcn_image_sample_c_l: 3553 return AMDGPUISD::IMAGE_SAMPLE_C_L; 3554 case Intrinsic::amdgcn_image_sample_c_b: 3555 return AMDGPUISD::IMAGE_SAMPLE_C_B; 3556 case Intrinsic::amdgcn_image_sample_c_b_cl: 3557 return AMDGPUISD::IMAGE_SAMPLE_C_B_CL; 3558 case Intrinsic::amdgcn_image_sample_c_lz: 3559 return AMDGPUISD::IMAGE_SAMPLE_C_LZ; 3560 case Intrinsic::amdgcn_image_sample_c_cd: 3561 return AMDGPUISD::IMAGE_SAMPLE_C_CD; 3562 case Intrinsic::amdgcn_image_sample_c_cd_cl: 3563 return AMDGPUISD::IMAGE_SAMPLE_C_CD_CL; 3564 3565 // Sample with offsets. 3566 case Intrinsic::amdgcn_image_sample_o: 3567 return AMDGPUISD::IMAGE_SAMPLE_O; 3568 case Intrinsic::amdgcn_image_sample_cl_o: 3569 return AMDGPUISD::IMAGE_SAMPLE_CL_O; 3570 case Intrinsic::amdgcn_image_sample_d_o: 3571 return AMDGPUISD::IMAGE_SAMPLE_D_O; 3572 case Intrinsic::amdgcn_image_sample_d_cl_o: 3573 return AMDGPUISD::IMAGE_SAMPLE_D_CL_O; 3574 case Intrinsic::amdgcn_image_sample_l_o: 3575 return AMDGPUISD::IMAGE_SAMPLE_L_O; 3576 case Intrinsic::amdgcn_image_sample_b_o: 3577 return AMDGPUISD::IMAGE_SAMPLE_B_O; 3578 case Intrinsic::amdgcn_image_sample_b_cl_o: 3579 return AMDGPUISD::IMAGE_SAMPLE_B_CL_O; 3580 case Intrinsic::amdgcn_image_sample_lz_o: 3581 return AMDGPUISD::IMAGE_SAMPLE_LZ_O; 3582 case Intrinsic::amdgcn_image_sample_cd_o: 3583 return AMDGPUISD::IMAGE_SAMPLE_CD_O; 3584 case Intrinsic::amdgcn_image_sample_cd_cl_o: 3585 return AMDGPUISD::IMAGE_SAMPLE_CD_CL_O; 3586 3587 // Sample with comparison and offsets. 3588 case Intrinsic::amdgcn_image_sample_c_o: 3589 return AMDGPUISD::IMAGE_SAMPLE_C_O; 3590 case Intrinsic::amdgcn_image_sample_c_cl_o: 3591 return AMDGPUISD::IMAGE_SAMPLE_C_CL_O; 3592 case Intrinsic::amdgcn_image_sample_c_d_o: 3593 return AMDGPUISD::IMAGE_SAMPLE_C_D_O; 3594 case Intrinsic::amdgcn_image_sample_c_d_cl_o: 3595 return AMDGPUISD::IMAGE_SAMPLE_C_D_CL_O; 3596 case Intrinsic::amdgcn_image_sample_c_l_o: 3597 return AMDGPUISD::IMAGE_SAMPLE_C_L_O; 3598 case Intrinsic::amdgcn_image_sample_c_b_o: 3599 return AMDGPUISD::IMAGE_SAMPLE_C_B_O; 3600 case Intrinsic::amdgcn_image_sample_c_b_cl_o: 3601 return AMDGPUISD::IMAGE_SAMPLE_C_B_CL_O; 3602 case Intrinsic::amdgcn_image_sample_c_lz_o: 3603 return AMDGPUISD::IMAGE_SAMPLE_C_LZ_O; 3604 case Intrinsic::amdgcn_image_sample_c_cd_o: 3605 return AMDGPUISD::IMAGE_SAMPLE_C_CD_O; 3606 case Intrinsic::amdgcn_image_sample_c_cd_cl_o: 3607 return AMDGPUISD::IMAGE_SAMPLE_C_CD_CL_O; 3608 3609 // Basic gather4. 3610 case Intrinsic::amdgcn_image_gather4: 3611 return AMDGPUISD::IMAGE_GATHER4; 3612 case Intrinsic::amdgcn_image_gather4_cl: 3613 return AMDGPUISD::IMAGE_GATHER4_CL; 3614 case Intrinsic::amdgcn_image_gather4_l: 3615 return AMDGPUISD::IMAGE_GATHER4_L; 3616 case Intrinsic::amdgcn_image_gather4_b: 3617 return AMDGPUISD::IMAGE_GATHER4_B; 3618 case Intrinsic::amdgcn_image_gather4_b_cl: 3619 return AMDGPUISD::IMAGE_GATHER4_B_CL; 3620 case Intrinsic::amdgcn_image_gather4_lz: 3621 return AMDGPUISD::IMAGE_GATHER4_LZ; 3622 3623 // Gather4 with comparison. 3624 case Intrinsic::amdgcn_image_gather4_c: 3625 return AMDGPUISD::IMAGE_GATHER4_C; 3626 case Intrinsic::amdgcn_image_gather4_c_cl: 3627 return AMDGPUISD::IMAGE_GATHER4_C_CL; 3628 case Intrinsic::amdgcn_image_gather4_c_l: 3629 return AMDGPUISD::IMAGE_GATHER4_C_L; 3630 case Intrinsic::amdgcn_image_gather4_c_b: 3631 return AMDGPUISD::IMAGE_GATHER4_C_B; 3632 case Intrinsic::amdgcn_image_gather4_c_b_cl: 3633 return AMDGPUISD::IMAGE_GATHER4_C_B_CL; 3634 case Intrinsic::amdgcn_image_gather4_c_lz: 3635 return AMDGPUISD::IMAGE_GATHER4_C_LZ; 3636 3637 // Gather4 with offsets. 3638 case Intrinsic::amdgcn_image_gather4_o: 3639 return AMDGPUISD::IMAGE_GATHER4_O; 3640 case Intrinsic::amdgcn_image_gather4_cl_o: 3641 return AMDGPUISD::IMAGE_GATHER4_CL_O; 3642 case Intrinsic::amdgcn_image_gather4_l_o: 3643 return AMDGPUISD::IMAGE_GATHER4_L_O; 3644 case Intrinsic::amdgcn_image_gather4_b_o: 3645 return AMDGPUISD::IMAGE_GATHER4_B_O; 3646 case Intrinsic::amdgcn_image_gather4_b_cl_o: 3647 return AMDGPUISD::IMAGE_GATHER4_B_CL_O; 3648 case Intrinsic::amdgcn_image_gather4_lz_o: 3649 return AMDGPUISD::IMAGE_GATHER4_LZ_O; 3650 3651 // Gather4 with comparison and offsets. 3652 case Intrinsic::amdgcn_image_gather4_c_o: 3653 return AMDGPUISD::IMAGE_GATHER4_C_O; 3654 case Intrinsic::amdgcn_image_gather4_c_cl_o: 3655 return AMDGPUISD::IMAGE_GATHER4_C_CL_O; 3656 case Intrinsic::amdgcn_image_gather4_c_l_o: 3657 return AMDGPUISD::IMAGE_GATHER4_C_L_O; 3658 case Intrinsic::amdgcn_image_gather4_c_b_o: 3659 return AMDGPUISD::IMAGE_GATHER4_C_B_O; 3660 case Intrinsic::amdgcn_image_gather4_c_b_cl_o: 3661 return AMDGPUISD::IMAGE_GATHER4_C_B_CL_O; 3662 case Intrinsic::amdgcn_image_gather4_c_lz_o: 3663 return AMDGPUISD::IMAGE_GATHER4_C_LZ_O; 3664 3665 default: 3666 break; 3667 } 3668 return 0; 3669 } 3670 3671 static SDValue adjustLoadValueType(SDValue Result, EVT LoadVT, SDLoc DL, 3672 SelectionDAG &DAG, bool Unpacked) { 3673 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 3674 // Truncate to v2i16/v4i16. 3675 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 3676 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, IntLoadVT, Result); 3677 // Bitcast to original type (v2f16/v4f16). 3678 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Trunc); 3679 } 3680 // Cast back to the original packed type. 3681 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 3682 } 3683 3684 // This is to lower INTRINSIC_W_CHAIN with illegal result types. 3685 SDValue SITargetLowering::lowerIntrinsicWChain_IllegalReturnType(SDValue Op, 3686 SDValue &Chain, SelectionDAG &DAG) const { 3687 EVT LoadVT = Op.getValueType(); 3688 // TODO: handle v3f16. 3689 if (LoadVT != MVT::v2f16 && LoadVT != MVT::v4f16) 3690 return SDValue(); 3691 3692 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 3693 EVT UnpackedLoadVT = (LoadVT == MVT::v2f16) ? MVT::v2i32 : MVT::v4i32; 3694 EVT EquivLoadVT = Unpacked ? UnpackedLoadVT : 3695 getEquivalentMemType(*DAG.getContext(), LoadVT); 3696 // Change from v4f16/v2f16 to EquivLoadVT. 3697 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 3698 3699 SDValue Res; 3700 SDLoc DL(Op); 3701 MemSDNode *M = cast<MemSDNode>(Op); 3702 unsigned IID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 3703 switch (IID) { 3704 case Intrinsic::amdgcn_tbuffer_load: { 3705 SDValue Ops[] = { 3706 Op.getOperand(0), // Chain 3707 Op.getOperand(2), // rsrc 3708 Op.getOperand(3), // vindex 3709 Op.getOperand(4), // voffset 3710 Op.getOperand(5), // soffset 3711 Op.getOperand(6), // offset 3712 Op.getOperand(7), // dfmt 3713 Op.getOperand(8), // nfmt 3714 Op.getOperand(9), // glc 3715 Op.getOperand(10) // slc 3716 }; 3717 Res = DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, DL, 3718 VTList, Ops, M->getMemoryVT(), 3719 M->getMemOperand()); 3720 Chain = Res.getValue(1); 3721 return adjustLoadValueType(Res, LoadVT, DL, DAG, Unpacked); 3722 } 3723 case Intrinsic::amdgcn_buffer_load_format: { 3724 SDValue Ops[] = { 3725 Op.getOperand(0), // Chain 3726 Op.getOperand(2), // rsrc 3727 Op.getOperand(3), // vindex 3728 Op.getOperand(4), // offset 3729 Op.getOperand(5), // glc 3730 Op.getOperand(6) // slc 3731 }; 3732 Res = DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 3733 DL, VTList, Ops, M->getMemoryVT(), 3734 M->getMemOperand()); 3735 Chain = Res.getValue(1); 3736 return adjustLoadValueType(Res, LoadVT, DL, DAG, Unpacked); 3737 } 3738 case Intrinsic::amdgcn_image_load: 3739 case Intrinsic::amdgcn_image_load_mip: { 3740 SDValue Ops[] = { 3741 Op.getOperand(0), // Chain 3742 Op.getOperand(2), // vaddr 3743 Op.getOperand(3), // rsrc 3744 Op.getOperand(4), // dmask 3745 Op.getOperand(5), // glc 3746 Op.getOperand(6), // slc 3747 Op.getOperand(7), // lwe 3748 Op.getOperand(8) // da 3749 }; 3750 unsigned Opc = getImageOpcode(IID); 3751 Res = DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, M->getMemoryVT(), 3752 M->getMemOperand()); 3753 Chain = Res.getValue(1); 3754 return adjustLoadValueType(Res, LoadVT, DL, DAG, Unpacked); 3755 } 3756 // Basic sample. 3757 case Intrinsic::amdgcn_image_sample: 3758 case Intrinsic::amdgcn_image_sample_cl: 3759 case Intrinsic::amdgcn_image_sample_d: 3760 case Intrinsic::amdgcn_image_sample_d_cl: 3761 case Intrinsic::amdgcn_image_sample_l: 3762 case Intrinsic::amdgcn_image_sample_b: 3763 case Intrinsic::amdgcn_image_sample_b_cl: 3764 case Intrinsic::amdgcn_image_sample_lz: 3765 case Intrinsic::amdgcn_image_sample_cd: 3766 case Intrinsic::amdgcn_image_sample_cd_cl: 3767 3768 // Sample with comparison. 3769 case Intrinsic::amdgcn_image_sample_c: 3770 case Intrinsic::amdgcn_image_sample_c_cl: 3771 case Intrinsic::amdgcn_image_sample_c_d: 3772 case Intrinsic::amdgcn_image_sample_c_d_cl: 3773 case Intrinsic::amdgcn_image_sample_c_l: 3774 case Intrinsic::amdgcn_image_sample_c_b: 3775 case Intrinsic::amdgcn_image_sample_c_b_cl: 3776 case Intrinsic::amdgcn_image_sample_c_lz: 3777 case Intrinsic::amdgcn_image_sample_c_cd: 3778 case Intrinsic::amdgcn_image_sample_c_cd_cl: 3779 3780 // Sample with offsets. 3781 case Intrinsic::amdgcn_image_sample_o: 3782 case Intrinsic::amdgcn_image_sample_cl_o: 3783 case Intrinsic::amdgcn_image_sample_d_o: 3784 case Intrinsic::amdgcn_image_sample_d_cl_o: 3785 case Intrinsic::amdgcn_image_sample_l_o: 3786 case Intrinsic::amdgcn_image_sample_b_o: 3787 case Intrinsic::amdgcn_image_sample_b_cl_o: 3788 case Intrinsic::amdgcn_image_sample_lz_o: 3789 case Intrinsic::amdgcn_image_sample_cd_o: 3790 case Intrinsic::amdgcn_image_sample_cd_cl_o: 3791 3792 // Sample with comparison and offsets. 3793 case Intrinsic::amdgcn_image_sample_c_o: 3794 case Intrinsic::amdgcn_image_sample_c_cl_o: 3795 case Intrinsic::amdgcn_image_sample_c_d_o: 3796 case Intrinsic::amdgcn_image_sample_c_d_cl_o: 3797 case Intrinsic::amdgcn_image_sample_c_l_o: 3798 case Intrinsic::amdgcn_image_sample_c_b_o: 3799 case Intrinsic::amdgcn_image_sample_c_b_cl_o: 3800 case Intrinsic::amdgcn_image_sample_c_lz_o: 3801 case Intrinsic::amdgcn_image_sample_c_cd_o: 3802 case Intrinsic::amdgcn_image_sample_c_cd_cl_o: 3803 3804 // Basic gather4 3805 case Intrinsic::amdgcn_image_gather4: 3806 case Intrinsic::amdgcn_image_gather4_cl: 3807 case Intrinsic::amdgcn_image_gather4_l: 3808 case Intrinsic::amdgcn_image_gather4_b: 3809 case Intrinsic::amdgcn_image_gather4_b_cl: 3810 case Intrinsic::amdgcn_image_gather4_lz: 3811 3812 // Gather4 with comparison 3813 case Intrinsic::amdgcn_image_gather4_c: 3814 case Intrinsic::amdgcn_image_gather4_c_cl: 3815 case Intrinsic::amdgcn_image_gather4_c_l: 3816 case Intrinsic::amdgcn_image_gather4_c_b: 3817 case Intrinsic::amdgcn_image_gather4_c_b_cl: 3818 case Intrinsic::amdgcn_image_gather4_c_lz: 3819 3820 // Gather4 with offsets 3821 case Intrinsic::amdgcn_image_gather4_o: 3822 case Intrinsic::amdgcn_image_gather4_cl_o: 3823 case Intrinsic::amdgcn_image_gather4_l_o: 3824 case Intrinsic::amdgcn_image_gather4_b_o: 3825 case Intrinsic::amdgcn_image_gather4_b_cl_o: 3826 case Intrinsic::amdgcn_image_gather4_lz_o: 3827 3828 // Gather4 with comparison and offsets 3829 case Intrinsic::amdgcn_image_gather4_c_o: 3830 case Intrinsic::amdgcn_image_gather4_c_cl_o: 3831 case Intrinsic::amdgcn_image_gather4_c_l_o: 3832 case Intrinsic::amdgcn_image_gather4_c_b_o: 3833 case Intrinsic::amdgcn_image_gather4_c_b_cl_o: 3834 case Intrinsic::amdgcn_image_gather4_c_lz_o: { 3835 SDValue Ops[] = { 3836 Op.getOperand(0), // Chain 3837 Op.getOperand(2), // vaddr 3838 Op.getOperand(3), // rsrc 3839 Op.getOperand(4), // sampler 3840 Op.getOperand(5), // dmask 3841 Op.getOperand(6), // unorm 3842 Op.getOperand(7), // glc 3843 Op.getOperand(8), // slc 3844 Op.getOperand(9), // lwe 3845 Op.getOperand(10) // da 3846 }; 3847 unsigned Opc = getImageOpcode(IID); 3848 Res = DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, M->getMemoryVT(), 3849 M->getMemOperand()); 3850 Chain = Res.getValue(1); 3851 return adjustLoadValueType(Res, LoadVT, DL, DAG, Unpacked); 3852 } 3853 default: 3854 return SDValue(); 3855 } 3856 } 3857 3858 void SITargetLowering::ReplaceNodeResults(SDNode *N, 3859 SmallVectorImpl<SDValue> &Results, 3860 SelectionDAG &DAG) const { 3861 switch (N->getOpcode()) { 3862 case ISD::INSERT_VECTOR_ELT: { 3863 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 3864 Results.push_back(Res); 3865 return; 3866 } 3867 case ISD::EXTRACT_VECTOR_ELT: { 3868 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 3869 Results.push_back(Res); 3870 return; 3871 } 3872 case ISD::INTRINSIC_WO_CHAIN: { 3873 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 3874 switch (IID) { 3875 case Intrinsic::amdgcn_cvt_pkrtz: { 3876 SDValue Src0 = N->getOperand(1); 3877 SDValue Src1 = N->getOperand(2); 3878 SDLoc SL(N); 3879 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 3880 Src0, Src1); 3881 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 3882 return; 3883 } 3884 case Intrinsic::amdgcn_cvt_pknorm_i16: 3885 case Intrinsic::amdgcn_cvt_pknorm_u16: 3886 case Intrinsic::amdgcn_cvt_pk_i16: 3887 case Intrinsic::amdgcn_cvt_pk_u16: { 3888 SDValue Src0 = N->getOperand(1); 3889 SDValue Src1 = N->getOperand(2); 3890 SDLoc SL(N); 3891 unsigned Opcode; 3892 3893 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 3894 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 3895 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 3896 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 3897 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 3898 Opcode = AMDGPUISD::CVT_PK_I16_I32; 3899 else 3900 Opcode = AMDGPUISD::CVT_PK_U16_U32; 3901 3902 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 3903 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 3904 return; 3905 } 3906 } 3907 break; 3908 } 3909 case ISD::INTRINSIC_W_CHAIN: { 3910 SDValue Chain; 3911 if (SDValue Res = lowerIntrinsicWChain_IllegalReturnType(SDValue(N, 0), 3912 Chain, DAG)) { 3913 Results.push_back(Res); 3914 Results.push_back(Chain); 3915 return; 3916 } 3917 break; 3918 } 3919 case ISD::SELECT: { 3920 SDLoc SL(N); 3921 EVT VT = N->getValueType(0); 3922 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 3923 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 3924 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 3925 3926 EVT SelectVT = NewVT; 3927 if (NewVT.bitsLT(MVT::i32)) { 3928 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 3929 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 3930 SelectVT = MVT::i32; 3931 } 3932 3933 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 3934 N->getOperand(0), LHS, RHS); 3935 3936 if (NewVT != SelectVT) 3937 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 3938 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 3939 return; 3940 } 3941 default: 3942 break; 3943 } 3944 } 3945 3946 /// \brief Helper function for LowerBRCOND 3947 static SDNode *findUser(SDValue Value, unsigned Opcode) { 3948 3949 SDNode *Parent = Value.getNode(); 3950 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 3951 I != E; ++I) { 3952 3953 if (I.getUse().get() != Value) 3954 continue; 3955 3956 if (I->getOpcode() == Opcode) 3957 return *I; 3958 } 3959 return nullptr; 3960 } 3961 3962 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 3963 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 3964 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 3965 case Intrinsic::amdgcn_if: 3966 return AMDGPUISD::IF; 3967 case Intrinsic::amdgcn_else: 3968 return AMDGPUISD::ELSE; 3969 case Intrinsic::amdgcn_loop: 3970 return AMDGPUISD::LOOP; 3971 case Intrinsic::amdgcn_end_cf: 3972 llvm_unreachable("should not occur"); 3973 default: 3974 return 0; 3975 } 3976 } 3977 3978 // break, if_break, else_break are all only used as inputs to loop, not 3979 // directly as branch conditions. 3980 return 0; 3981 } 3982 3983 void SITargetLowering::createDebuggerPrologueStackObjects( 3984 MachineFunction &MF) const { 3985 // Create stack objects that are used for emitting debugger prologue. 3986 // 3987 // Debugger prologue writes work group IDs and work item IDs to scratch memory 3988 // at fixed location in the following format: 3989 // offset 0: work group ID x 3990 // offset 4: work group ID y 3991 // offset 8: work group ID z 3992 // offset 16: work item ID x 3993 // offset 20: work item ID y 3994 // offset 24: work item ID z 3995 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3996 int ObjectIdx = 0; 3997 3998 // For each dimension: 3999 for (unsigned i = 0; i < 3; ++i) { 4000 // Create fixed stack object for work group ID. 4001 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true); 4002 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx); 4003 // Create fixed stack object for work item ID. 4004 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true); 4005 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx); 4006 } 4007 } 4008 4009 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4010 const Triple &TT = getTargetMachine().getTargetTriple(); 4011 return GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS && 4012 AMDGPU::shouldEmitConstantsToTextSection(TT); 4013 } 4014 4015 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4016 return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS || 4017 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) && 4018 !shouldEmitFixup(GV) && 4019 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4020 } 4021 4022 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4023 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4024 } 4025 4026 /// This transforms the control flow intrinsics to get the branch destination as 4027 /// last parameter, also switches branch target with BR if the need arise 4028 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4029 SelectionDAG &DAG) const { 4030 SDLoc DL(BRCOND); 4031 4032 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4033 SDValue Target = BRCOND.getOperand(2); 4034 SDNode *BR = nullptr; 4035 SDNode *SetCC = nullptr; 4036 4037 if (Intr->getOpcode() == ISD::SETCC) { 4038 // As long as we negate the condition everything is fine 4039 SetCC = Intr; 4040 Intr = SetCC->getOperand(0).getNode(); 4041 4042 } else { 4043 // Get the target from BR if we don't negate the condition 4044 BR = findUser(BRCOND, ISD::BR); 4045 Target = BR->getOperand(1); 4046 } 4047 4048 // FIXME: This changes the types of the intrinsics instead of introducing new 4049 // nodes with the correct types. 4050 // e.g. llvm.amdgcn.loop 4051 4052 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 4053 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 4054 4055 unsigned CFNode = isCFIntrinsic(Intr); 4056 if (CFNode == 0) { 4057 // This is a uniform branch so we don't need to legalize. 4058 return BRCOND; 4059 } 4060 4061 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4062 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4063 4064 assert(!SetCC || 4065 (SetCC->getConstantOperandVal(1) == 1 && 4066 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4067 ISD::SETNE)); 4068 4069 // operands of the new intrinsic call 4070 SmallVector<SDValue, 4> Ops; 4071 if (HaveChain) 4072 Ops.push_back(BRCOND.getOperand(0)); 4073 4074 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4075 Ops.push_back(Target); 4076 4077 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4078 4079 // build the new intrinsic call 4080 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4081 4082 if (!HaveChain) { 4083 SDValue Ops[] = { 4084 SDValue(Result, 0), 4085 BRCOND.getOperand(0) 4086 }; 4087 4088 Result = DAG.getMergeValues(Ops, DL).getNode(); 4089 } 4090 4091 if (BR) { 4092 // Give the branch instruction our target 4093 SDValue Ops[] = { 4094 BR->getOperand(0), 4095 BRCOND.getOperand(2) 4096 }; 4097 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4098 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4099 BR = NewBR.getNode(); 4100 } 4101 4102 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4103 4104 // Copy the intrinsic results to registers 4105 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4106 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4107 if (!CopyToReg) 4108 continue; 4109 4110 Chain = DAG.getCopyToReg( 4111 Chain, DL, 4112 CopyToReg->getOperand(1), 4113 SDValue(Result, i - 1), 4114 SDValue()); 4115 4116 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4117 } 4118 4119 // Remove the old intrinsic from the chain 4120 DAG.ReplaceAllUsesOfValueWith( 4121 SDValue(Intr, Intr->getNumValues() - 1), 4122 Intr->getOperand(0)); 4123 4124 return Chain; 4125 } 4126 4127 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 4128 SDValue Op, 4129 const SDLoc &DL, 4130 EVT VT) const { 4131 return Op.getValueType().bitsLE(VT) ? 4132 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4133 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 4134 } 4135 4136 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4137 assert(Op.getValueType() == MVT::f16 && 4138 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4139 4140 SDValue Src = Op.getOperand(0); 4141 EVT SrcVT = Src.getValueType(); 4142 if (SrcVT != MVT::f64) 4143 return Op; 4144 4145 SDLoc DL(Op); 4146 4147 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4148 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4149 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4150 } 4151 4152 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4153 SDLoc SL(Op); 4154 MachineFunction &MF = DAG.getMachineFunction(); 4155 SDValue Chain = Op.getOperand(0); 4156 4157 unsigned TrapID = Op.getOpcode() == ISD::DEBUGTRAP ? 4158 SISubtarget::TrapIDLLVMDebugTrap : SISubtarget::TrapIDLLVMTrap; 4159 4160 if (Subtarget->getTrapHandlerAbi() == SISubtarget::TrapHandlerAbiHsa && 4161 Subtarget->isTrapHandlerEnabled()) { 4162 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4163 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4164 assert(UserSGPR != AMDGPU::NoRegister); 4165 4166 SDValue QueuePtr = CreateLiveInRegister( 4167 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4168 4169 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4170 4171 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4172 QueuePtr, SDValue()); 4173 4174 SDValue Ops[] = { 4175 ToReg, 4176 DAG.getTargetConstant(TrapID, SL, MVT::i16), 4177 SGPR01, 4178 ToReg.getValue(1) 4179 }; 4180 4181 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4182 } 4183 4184 switch (TrapID) { 4185 case SISubtarget::TrapIDLLVMTrap: 4186 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4187 case SISubtarget::TrapIDLLVMDebugTrap: { 4188 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4189 "debugtrap handler not supported", 4190 Op.getDebugLoc(), 4191 DS_Warning); 4192 LLVMContext &Ctx = MF.getFunction().getContext(); 4193 Ctx.diagnose(NoTrap); 4194 return Chain; 4195 } 4196 default: 4197 llvm_unreachable("unsupported trap handler type!"); 4198 } 4199 4200 return Chain; 4201 } 4202 4203 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4204 SelectionDAG &DAG) const { 4205 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4206 if (Subtarget->hasApertureRegs()) { 4207 unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ? 4208 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4209 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4210 unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ? 4211 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4212 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4213 unsigned Encoding = 4214 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4215 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4216 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4217 4218 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4219 SDValue ApertureReg = SDValue( 4220 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4221 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4222 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4223 } 4224 4225 MachineFunction &MF = DAG.getMachineFunction(); 4226 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4227 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4228 assert(UserSGPR != AMDGPU::NoRegister); 4229 4230 SDValue QueuePtr = CreateLiveInRegister( 4231 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4232 4233 // Offset into amd_queue_t for group_segment_aperture_base_hi / 4234 // private_segment_aperture_base_hi. 4235 uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44; 4236 4237 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 4238 4239 // TODO: Use custom target PseudoSourceValue. 4240 // TODO: We should use the value from the IR intrinsic call, but it might not 4241 // be available and how do we get it? 4242 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()), 4243 AMDGPUASI.CONSTANT_ADDRESS)); 4244 4245 MachinePointerInfo PtrInfo(V, StructOffset); 4246 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4247 MinAlign(64, StructOffset), 4248 MachineMemOperand::MODereferenceable | 4249 MachineMemOperand::MOInvariant); 4250 } 4251 4252 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4253 SelectionDAG &DAG) const { 4254 SDLoc SL(Op); 4255 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4256 4257 SDValue Src = ASC->getOperand(0); 4258 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4259 4260 const AMDGPUTargetMachine &TM = 4261 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4262 4263 // flat -> local/private 4264 if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) { 4265 unsigned DestAS = ASC->getDestAddressSpace(); 4266 4267 if (DestAS == AMDGPUASI.LOCAL_ADDRESS || 4268 DestAS == AMDGPUASI.PRIVATE_ADDRESS) { 4269 unsigned NullVal = TM.getNullPointerValue(DestAS); 4270 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4271 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4272 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4273 4274 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4275 NonNull, Ptr, SegmentNullPtr); 4276 } 4277 } 4278 4279 // local/private -> flat 4280 if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) { 4281 unsigned SrcAS = ASC->getSrcAddressSpace(); 4282 4283 if (SrcAS == AMDGPUASI.LOCAL_ADDRESS || 4284 SrcAS == AMDGPUASI.PRIVATE_ADDRESS) { 4285 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4286 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4287 4288 SDValue NonNull 4289 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4290 4291 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4292 SDValue CvtPtr 4293 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4294 4295 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4296 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4297 FlatNullPtr); 4298 } 4299 } 4300 4301 // global <-> flat are no-ops and never emitted. 4302 4303 const MachineFunction &MF = DAG.getMachineFunction(); 4304 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 4305 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 4306 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 4307 4308 return DAG.getUNDEF(ASC->getValueType(0)); 4309 } 4310 4311 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4312 SelectionDAG &DAG) const { 4313 SDValue Idx = Op.getOperand(2); 4314 if (isa<ConstantSDNode>(Idx)) 4315 return SDValue(); 4316 4317 // Avoid stack access for dynamic indexing. 4318 SDLoc SL(Op); 4319 SDValue Vec = Op.getOperand(0); 4320 SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1)); 4321 4322 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 4323 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val); 4324 4325 // Convert vector index to bit-index. 4326 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, 4327 DAG.getConstant(16, SL, MVT::i32)); 4328 4329 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 4330 4331 SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32, 4332 DAG.getConstant(0xffff, SL, MVT::i32), 4333 ScaledIdx); 4334 4335 SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal); 4336 SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32, 4337 DAG.getNOT(SL, BFM, MVT::i32), BCVec); 4338 4339 SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS); 4340 return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI); 4341 } 4342 4343 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4344 SelectionDAG &DAG) const { 4345 SDLoc SL(Op); 4346 4347 EVT ResultVT = Op.getValueType(); 4348 SDValue Vec = Op.getOperand(0); 4349 SDValue Idx = Op.getOperand(1); 4350 4351 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 4352 4353 // Make sure we we do any optimizations that will make it easier to fold 4354 // source modifiers before obscuring it with bit operations. 4355 4356 // XXX - Why doesn't this get called when vector_shuffle is expanded? 4357 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 4358 return Combined; 4359 4360 if (const ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) { 4361 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 4362 4363 if (CIdx->getZExtValue() == 1) { 4364 Result = DAG.getNode(ISD::SRL, SL, MVT::i32, Result, 4365 DAG.getConstant(16, SL, MVT::i32)); 4366 } else { 4367 assert(CIdx->getZExtValue() == 0); 4368 } 4369 4370 if (ResultVT.bitsLT(MVT::i32)) 4371 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result); 4372 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 4373 } 4374 4375 SDValue Sixteen = DAG.getConstant(16, SL, MVT::i32); 4376 4377 // Convert vector index to bit-index. 4378 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Sixteen); 4379 4380 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 4381 SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx); 4382 4383 SDValue Result = Elt; 4384 if (ResultVT.bitsLT(MVT::i32)) 4385 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result); 4386 4387 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 4388 } 4389 4390 bool 4391 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 4392 // We can fold offsets for anything that doesn't require a GOT relocation. 4393 return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS || 4394 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) && 4395 !shouldEmitGOTReloc(GA->getGlobal()); 4396 } 4397 4398 static SDValue 4399 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 4400 const SDLoc &DL, unsigned Offset, EVT PtrVT, 4401 unsigned GAFlags = SIInstrInfo::MO_NONE) { 4402 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 4403 // lowered to the following code sequence: 4404 // 4405 // For constant address space: 4406 // s_getpc_b64 s[0:1] 4407 // s_add_u32 s0, s0, $symbol 4408 // s_addc_u32 s1, s1, 0 4409 // 4410 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 4411 // a fixup or relocation is emitted to replace $symbol with a literal 4412 // constant, which is a pc-relative offset from the encoding of the $symbol 4413 // operand to the global variable. 4414 // 4415 // For global address space: 4416 // s_getpc_b64 s[0:1] 4417 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 4418 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 4419 // 4420 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 4421 // fixups or relocations are emitted to replace $symbol@*@lo and 4422 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 4423 // which is a 64-bit pc-relative offset from the encoding of the $symbol 4424 // operand to the global variable. 4425 // 4426 // What we want here is an offset from the value returned by s_getpc 4427 // (which is the address of the s_add_u32 instruction) to the global 4428 // variable, but since the encoding of $symbol starts 4 bytes after the start 4429 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 4430 // small. This requires us to add 4 to the global variable offset in order to 4431 // compute the correct address. 4432 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 4433 GAFlags); 4434 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 4435 GAFlags == SIInstrInfo::MO_NONE ? 4436 GAFlags : GAFlags + 1); 4437 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 4438 } 4439 4440 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 4441 SDValue Op, 4442 SelectionDAG &DAG) const { 4443 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 4444 const GlobalValue *GV = GSD->getGlobal(); 4445 4446 if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS && 4447 GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS && 4448 // FIXME: It isn't correct to rely on the type of the pointer. This should 4449 // be removed when address space 0 is 64-bit. 4450 !GV->getType()->getElementType()->isFunctionTy()) 4451 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 4452 4453 SDLoc DL(GSD); 4454 EVT PtrVT = Op.getValueType(); 4455 4456 if (shouldEmitFixup(GV)) 4457 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 4458 else if (shouldEmitPCReloc(GV)) 4459 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 4460 SIInstrInfo::MO_REL32); 4461 4462 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 4463 SIInstrInfo::MO_GOTPCREL32); 4464 4465 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 4466 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS); 4467 const DataLayout &DataLayout = DAG.getDataLayout(); 4468 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 4469 // FIXME: Use a PseudoSourceValue once those can be assigned an address space. 4470 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 4471 4472 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 4473 MachineMemOperand::MODereferenceable | 4474 MachineMemOperand::MOInvariant); 4475 } 4476 4477 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 4478 const SDLoc &DL, SDValue V) const { 4479 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 4480 // the destination register. 4481 // 4482 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 4483 // so we will end up with redundant moves to m0. 4484 // 4485 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 4486 4487 // A Null SDValue creates a glue result. 4488 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 4489 V, Chain); 4490 return SDValue(M0, 0); 4491 } 4492 4493 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 4494 SDValue Op, 4495 MVT VT, 4496 unsigned Offset) const { 4497 SDLoc SL(Op); 4498 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 4499 DAG.getEntryNode(), Offset, false); 4500 // The local size values will have the hi 16-bits as zero. 4501 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 4502 DAG.getValueType(VT)); 4503 } 4504 4505 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 4506 EVT VT) { 4507 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 4508 "non-hsa intrinsic with hsa target", 4509 DL.getDebugLoc()); 4510 DAG.getContext()->diagnose(BadIntrin); 4511 return DAG.getUNDEF(VT); 4512 } 4513 4514 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 4515 EVT VT) { 4516 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 4517 "intrinsic not supported on subtarget", 4518 DL.getDebugLoc()); 4519 DAG.getContext()->diagnose(BadIntrin); 4520 return DAG.getUNDEF(VT); 4521 } 4522 4523 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4524 SelectionDAG &DAG) const { 4525 MachineFunction &MF = DAG.getMachineFunction(); 4526 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 4527 4528 EVT VT = Op.getValueType(); 4529 SDLoc DL(Op); 4530 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4531 4532 // TODO: Should this propagate fast-math-flags? 4533 4534 switch (IntrinsicID) { 4535 case Intrinsic::amdgcn_implicit_buffer_ptr: { 4536 if (getSubtarget()->isAmdCodeObjectV2(MF)) 4537 return emitNonHSAIntrinsicError(DAG, DL, VT); 4538 return getPreloadedValue(DAG, *MFI, VT, 4539 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 4540 } 4541 case Intrinsic::amdgcn_dispatch_ptr: 4542 case Intrinsic::amdgcn_queue_ptr: { 4543 if (!Subtarget->isAmdCodeObjectV2(MF)) { 4544 DiagnosticInfoUnsupported BadIntrin( 4545 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 4546 DL.getDebugLoc()); 4547 DAG.getContext()->diagnose(BadIntrin); 4548 return DAG.getUNDEF(VT); 4549 } 4550 4551 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 4552 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 4553 return getPreloadedValue(DAG, *MFI, VT, RegID); 4554 } 4555 case Intrinsic::amdgcn_implicitarg_ptr: { 4556 if (MFI->isEntryFunction()) 4557 return getImplicitArgPtr(DAG, DL); 4558 return getPreloadedValue(DAG, *MFI, VT, 4559 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 4560 } 4561 case Intrinsic::amdgcn_kernarg_segment_ptr: { 4562 return getPreloadedValue(DAG, *MFI, VT, 4563 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 4564 } 4565 case Intrinsic::amdgcn_dispatch_id: { 4566 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 4567 } 4568 case Intrinsic::amdgcn_rcp: 4569 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 4570 case Intrinsic::amdgcn_rsq: 4571 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 4572 case Intrinsic::amdgcn_rsq_legacy: 4573 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 4574 return emitRemovedIntrinsicError(DAG, DL, VT); 4575 4576 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 4577 case Intrinsic::amdgcn_rcp_legacy: 4578 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 4579 return emitRemovedIntrinsicError(DAG, DL, VT); 4580 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 4581 case Intrinsic::amdgcn_rsq_clamp: { 4582 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 4583 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 4584 4585 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 4586 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 4587 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 4588 4589 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 4590 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 4591 DAG.getConstantFP(Max, DL, VT)); 4592 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 4593 DAG.getConstantFP(Min, DL, VT)); 4594 } 4595 case Intrinsic::r600_read_ngroups_x: 4596 if (Subtarget->isAmdHsaOS()) 4597 return emitNonHSAIntrinsicError(DAG, DL, VT); 4598 4599 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4600 SI::KernelInputOffsets::NGROUPS_X, false); 4601 case Intrinsic::r600_read_ngroups_y: 4602 if (Subtarget->isAmdHsaOS()) 4603 return emitNonHSAIntrinsicError(DAG, DL, VT); 4604 4605 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4606 SI::KernelInputOffsets::NGROUPS_Y, false); 4607 case Intrinsic::r600_read_ngroups_z: 4608 if (Subtarget->isAmdHsaOS()) 4609 return emitNonHSAIntrinsicError(DAG, DL, VT); 4610 4611 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4612 SI::KernelInputOffsets::NGROUPS_Z, false); 4613 case Intrinsic::r600_read_global_size_x: 4614 if (Subtarget->isAmdHsaOS()) 4615 return emitNonHSAIntrinsicError(DAG, DL, VT); 4616 4617 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4618 SI::KernelInputOffsets::GLOBAL_SIZE_X, false); 4619 case Intrinsic::r600_read_global_size_y: 4620 if (Subtarget->isAmdHsaOS()) 4621 return emitNonHSAIntrinsicError(DAG, DL, VT); 4622 4623 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4624 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false); 4625 case Intrinsic::r600_read_global_size_z: 4626 if (Subtarget->isAmdHsaOS()) 4627 return emitNonHSAIntrinsicError(DAG, DL, VT); 4628 4629 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4630 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false); 4631 case Intrinsic::r600_read_local_size_x: 4632 if (Subtarget->isAmdHsaOS()) 4633 return emitNonHSAIntrinsicError(DAG, DL, VT); 4634 4635 return lowerImplicitZextParam(DAG, Op, MVT::i16, 4636 SI::KernelInputOffsets::LOCAL_SIZE_X); 4637 case Intrinsic::r600_read_local_size_y: 4638 if (Subtarget->isAmdHsaOS()) 4639 return emitNonHSAIntrinsicError(DAG, DL, VT); 4640 4641 return lowerImplicitZextParam(DAG, Op, MVT::i16, 4642 SI::KernelInputOffsets::LOCAL_SIZE_Y); 4643 case Intrinsic::r600_read_local_size_z: 4644 if (Subtarget->isAmdHsaOS()) 4645 return emitNonHSAIntrinsicError(DAG, DL, VT); 4646 4647 return lowerImplicitZextParam(DAG, Op, MVT::i16, 4648 SI::KernelInputOffsets::LOCAL_SIZE_Z); 4649 case Intrinsic::amdgcn_workgroup_id_x: 4650 case Intrinsic::r600_read_tgid_x: 4651 return getPreloadedValue(DAG, *MFI, VT, 4652 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 4653 case Intrinsic::amdgcn_workgroup_id_y: 4654 case Intrinsic::r600_read_tgid_y: 4655 return getPreloadedValue(DAG, *MFI, VT, 4656 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 4657 case Intrinsic::amdgcn_workgroup_id_z: 4658 case Intrinsic::r600_read_tgid_z: 4659 return getPreloadedValue(DAG, *MFI, VT, 4660 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 4661 case Intrinsic::amdgcn_workitem_id_x: { 4662 case Intrinsic::r600_read_tidig_x: 4663 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 4664 SDLoc(DAG.getEntryNode()), 4665 MFI->getArgInfo().WorkItemIDX); 4666 } 4667 case Intrinsic::amdgcn_workitem_id_y: 4668 case Intrinsic::r600_read_tidig_y: 4669 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 4670 SDLoc(DAG.getEntryNode()), 4671 MFI->getArgInfo().WorkItemIDY); 4672 case Intrinsic::amdgcn_workitem_id_z: 4673 case Intrinsic::r600_read_tidig_z: 4674 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 4675 SDLoc(DAG.getEntryNode()), 4676 MFI->getArgInfo().WorkItemIDZ); 4677 case AMDGPUIntrinsic::SI_load_const: { 4678 SDValue Ops[] = { 4679 Op.getOperand(1), 4680 Op.getOperand(2) 4681 }; 4682 4683 MachineMemOperand *MMO = MF.getMachineMemOperand( 4684 MachinePointerInfo(), 4685 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 4686 MachineMemOperand::MOInvariant, 4687 VT.getStoreSize(), 4); 4688 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL, 4689 Op->getVTList(), Ops, VT, MMO); 4690 } 4691 case Intrinsic::amdgcn_fdiv_fast: 4692 return lowerFDIV_FAST(Op, DAG); 4693 case Intrinsic::amdgcn_interp_mov: { 4694 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 4695 SDValue Glue = M0.getValue(1); 4696 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1), 4697 Op.getOperand(2), Op.getOperand(3), Glue); 4698 } 4699 case Intrinsic::amdgcn_interp_p1: { 4700 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 4701 SDValue Glue = M0.getValue(1); 4702 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1), 4703 Op.getOperand(2), Op.getOperand(3), Glue); 4704 } 4705 case Intrinsic::amdgcn_interp_p2: { 4706 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 4707 SDValue Glue = SDValue(M0.getNode(), 1); 4708 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1), 4709 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4), 4710 Glue); 4711 } 4712 case Intrinsic::amdgcn_sin: 4713 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 4714 4715 case Intrinsic::amdgcn_cos: 4716 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 4717 4718 case Intrinsic::amdgcn_log_clamp: { 4719 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 4720 return SDValue(); 4721 4722 DiagnosticInfoUnsupported BadIntrin( 4723 MF.getFunction(), "intrinsic not supported on subtarget", 4724 DL.getDebugLoc()); 4725 DAG.getContext()->diagnose(BadIntrin); 4726 return DAG.getUNDEF(VT); 4727 } 4728 case Intrinsic::amdgcn_ldexp: 4729 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 4730 Op.getOperand(1), Op.getOperand(2)); 4731 4732 case Intrinsic::amdgcn_fract: 4733 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 4734 4735 case Intrinsic::amdgcn_class: 4736 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 4737 Op.getOperand(1), Op.getOperand(2)); 4738 case Intrinsic::amdgcn_div_fmas: 4739 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 4740 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 4741 Op.getOperand(4)); 4742 4743 case Intrinsic::amdgcn_div_fixup: 4744 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 4745 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4746 4747 case Intrinsic::amdgcn_trig_preop: 4748 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 4749 Op.getOperand(1), Op.getOperand(2)); 4750 case Intrinsic::amdgcn_div_scale: { 4751 // 3rd parameter required to be a constant. 4752 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 4753 if (!Param) 4754 return DAG.getMergeValues({ DAG.getUNDEF(VT), DAG.getUNDEF(MVT::i1) }, DL); 4755 4756 // Translate to the operands expected by the machine instruction. The 4757 // first parameter must be the same as the first instruction. 4758 SDValue Numerator = Op.getOperand(1); 4759 SDValue Denominator = Op.getOperand(2); 4760 4761 // Note this order is opposite of the machine instruction's operations, 4762 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 4763 // intrinsic has the numerator as the first operand to match a normal 4764 // division operation. 4765 4766 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 4767 4768 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 4769 Denominator, Numerator); 4770 } 4771 case Intrinsic::amdgcn_icmp: { 4772 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 4773 if (!CD) 4774 return DAG.getUNDEF(VT); 4775 4776 int CondCode = CD->getSExtValue(); 4777 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4778 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4779 return DAG.getUNDEF(VT); 4780 4781 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4782 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4783 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 4784 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 4785 } 4786 case Intrinsic::amdgcn_fcmp: { 4787 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 4788 if (!CD) 4789 return DAG.getUNDEF(VT); 4790 4791 int CondCode = CD->getSExtValue(); 4792 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4793 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) 4794 return DAG.getUNDEF(VT); 4795 4796 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4797 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4798 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 4799 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 4800 } 4801 case Intrinsic::amdgcn_fmed3: 4802 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 4803 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4804 case Intrinsic::amdgcn_fmul_legacy: 4805 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 4806 Op.getOperand(1), Op.getOperand(2)); 4807 case Intrinsic::amdgcn_sffbh: 4808 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 4809 case Intrinsic::amdgcn_sbfe: 4810 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 4811 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4812 case Intrinsic::amdgcn_ubfe: 4813 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 4814 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4815 case Intrinsic::amdgcn_cvt_pkrtz: 4816 case Intrinsic::amdgcn_cvt_pknorm_i16: 4817 case Intrinsic::amdgcn_cvt_pknorm_u16: 4818 case Intrinsic::amdgcn_cvt_pk_i16: 4819 case Intrinsic::amdgcn_cvt_pk_u16: { 4820 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 4821 EVT VT = Op.getValueType(); 4822 unsigned Opcode; 4823 4824 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 4825 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 4826 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 4827 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4828 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 4829 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4830 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 4831 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4832 else 4833 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4834 4835 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 4836 Op.getOperand(1), Op.getOperand(2)); 4837 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 4838 } 4839 case Intrinsic::amdgcn_wqm: { 4840 SDValue Src = Op.getOperand(1); 4841 return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src), 4842 0); 4843 } 4844 case Intrinsic::amdgcn_wwm: { 4845 SDValue Src = Op.getOperand(1); 4846 return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src), 4847 0); 4848 } 4849 case Intrinsic::amdgcn_image_getlod: 4850 case Intrinsic::amdgcn_image_getresinfo: { 4851 unsigned Idx = (IntrinsicID == Intrinsic::amdgcn_image_getresinfo) ? 3 : 4; 4852 4853 // Replace dmask with everything disabled with undef. 4854 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(Idx)); 4855 if (!DMask || DMask->isNullValue()) 4856 return DAG.getUNDEF(Op.getValueType()); 4857 return SDValue(); 4858 } 4859 default: 4860 return Op; 4861 } 4862 } 4863 4864 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4865 SelectionDAG &DAG) const { 4866 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4867 SDLoc DL(Op); 4868 4869 switch (IntrID) { 4870 case Intrinsic::amdgcn_atomic_inc: 4871 case Intrinsic::amdgcn_atomic_dec: 4872 case Intrinsic::amdgcn_ds_fadd: 4873 case Intrinsic::amdgcn_ds_fmin: 4874 case Intrinsic::amdgcn_ds_fmax: { 4875 MemSDNode *M = cast<MemSDNode>(Op); 4876 unsigned Opc; 4877 switch (IntrID) { 4878 case Intrinsic::amdgcn_atomic_inc: 4879 Opc = AMDGPUISD::ATOMIC_INC; 4880 break; 4881 case Intrinsic::amdgcn_atomic_dec: 4882 Opc = AMDGPUISD::ATOMIC_DEC; 4883 break; 4884 case Intrinsic::amdgcn_ds_fadd: 4885 Opc = AMDGPUISD::ATOMIC_LOAD_FADD; 4886 break; 4887 case Intrinsic::amdgcn_ds_fmin: 4888 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 4889 break; 4890 case Intrinsic::amdgcn_ds_fmax: 4891 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 4892 break; 4893 default: 4894 llvm_unreachable("Unknown intrinsic!"); 4895 } 4896 SDValue Ops[] = { 4897 M->getOperand(0), // Chain 4898 M->getOperand(2), // Ptr 4899 M->getOperand(3) // Value 4900 }; 4901 4902 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 4903 M->getMemoryVT(), M->getMemOperand()); 4904 } 4905 case Intrinsic::amdgcn_buffer_load: 4906 case Intrinsic::amdgcn_buffer_load_format: { 4907 SDValue Ops[] = { 4908 Op.getOperand(0), // Chain 4909 Op.getOperand(2), // rsrc 4910 Op.getOperand(3), // vindex 4911 Op.getOperand(4), // offset 4912 Op.getOperand(5), // glc 4913 Op.getOperand(6) // slc 4914 }; 4915 4916 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 4917 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 4918 EVT VT = Op.getValueType(); 4919 EVT IntVT = VT.changeTypeToInteger(); 4920 4921 auto *M = cast<MemSDNode>(Op); 4922 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 4923 M->getMemOperand()); 4924 } 4925 case Intrinsic::amdgcn_tbuffer_load: { 4926 MemSDNode *M = cast<MemSDNode>(Op); 4927 SDValue Ops[] = { 4928 Op.getOperand(0), // Chain 4929 Op.getOperand(2), // rsrc 4930 Op.getOperand(3), // vindex 4931 Op.getOperand(4), // voffset 4932 Op.getOperand(5), // soffset 4933 Op.getOperand(6), // offset 4934 Op.getOperand(7), // dfmt 4935 Op.getOperand(8), // nfmt 4936 Op.getOperand(9), // glc 4937 Op.getOperand(10) // slc 4938 }; 4939 4940 EVT VT = Op.getValueType(); 4941 4942 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 4943 Op->getVTList(), Ops, VT, M->getMemOperand()); 4944 } 4945 case Intrinsic::amdgcn_buffer_atomic_swap: 4946 case Intrinsic::amdgcn_buffer_atomic_add: 4947 case Intrinsic::amdgcn_buffer_atomic_sub: 4948 case Intrinsic::amdgcn_buffer_atomic_smin: 4949 case Intrinsic::amdgcn_buffer_atomic_umin: 4950 case Intrinsic::amdgcn_buffer_atomic_smax: 4951 case Intrinsic::amdgcn_buffer_atomic_umax: 4952 case Intrinsic::amdgcn_buffer_atomic_and: 4953 case Intrinsic::amdgcn_buffer_atomic_or: 4954 case Intrinsic::amdgcn_buffer_atomic_xor: { 4955 SDValue Ops[] = { 4956 Op.getOperand(0), // Chain 4957 Op.getOperand(2), // vdata 4958 Op.getOperand(3), // rsrc 4959 Op.getOperand(4), // vindex 4960 Op.getOperand(5), // offset 4961 Op.getOperand(6) // slc 4962 }; 4963 EVT VT = Op.getValueType(); 4964 4965 auto *M = cast<MemSDNode>(Op); 4966 unsigned Opcode = 0; 4967 4968 switch (IntrID) { 4969 case Intrinsic::amdgcn_buffer_atomic_swap: 4970 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 4971 break; 4972 case Intrinsic::amdgcn_buffer_atomic_add: 4973 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 4974 break; 4975 case Intrinsic::amdgcn_buffer_atomic_sub: 4976 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 4977 break; 4978 case Intrinsic::amdgcn_buffer_atomic_smin: 4979 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 4980 break; 4981 case Intrinsic::amdgcn_buffer_atomic_umin: 4982 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 4983 break; 4984 case Intrinsic::amdgcn_buffer_atomic_smax: 4985 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 4986 break; 4987 case Intrinsic::amdgcn_buffer_atomic_umax: 4988 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 4989 break; 4990 case Intrinsic::amdgcn_buffer_atomic_and: 4991 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 4992 break; 4993 case Intrinsic::amdgcn_buffer_atomic_or: 4994 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 4995 break; 4996 case Intrinsic::amdgcn_buffer_atomic_xor: 4997 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 4998 break; 4999 default: 5000 llvm_unreachable("unhandled atomic opcode"); 5001 } 5002 5003 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 5004 M->getMemOperand()); 5005 } 5006 5007 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 5008 SDValue Ops[] = { 5009 Op.getOperand(0), // Chain 5010 Op.getOperand(2), // src 5011 Op.getOperand(3), // cmp 5012 Op.getOperand(4), // rsrc 5013 Op.getOperand(5), // vindex 5014 Op.getOperand(6), // offset 5015 Op.getOperand(7) // slc 5016 }; 5017 EVT VT = Op.getValueType(); 5018 auto *M = cast<MemSDNode>(Op); 5019 5020 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 5021 Op->getVTList(), Ops, VT, M->getMemOperand()); 5022 } 5023 5024 // Basic sample. 5025 case Intrinsic::amdgcn_image_sample: 5026 case Intrinsic::amdgcn_image_sample_cl: 5027 case Intrinsic::amdgcn_image_sample_d: 5028 case Intrinsic::amdgcn_image_sample_d_cl: 5029 case Intrinsic::amdgcn_image_sample_l: 5030 case Intrinsic::amdgcn_image_sample_b: 5031 case Intrinsic::amdgcn_image_sample_b_cl: 5032 case Intrinsic::amdgcn_image_sample_lz: 5033 case Intrinsic::amdgcn_image_sample_cd: 5034 case Intrinsic::amdgcn_image_sample_cd_cl: 5035 5036 // Sample with comparison. 5037 case Intrinsic::amdgcn_image_sample_c: 5038 case Intrinsic::amdgcn_image_sample_c_cl: 5039 case Intrinsic::amdgcn_image_sample_c_d: 5040 case Intrinsic::amdgcn_image_sample_c_d_cl: 5041 case Intrinsic::amdgcn_image_sample_c_l: 5042 case Intrinsic::amdgcn_image_sample_c_b: 5043 case Intrinsic::amdgcn_image_sample_c_b_cl: 5044 case Intrinsic::amdgcn_image_sample_c_lz: 5045 case Intrinsic::amdgcn_image_sample_c_cd: 5046 case Intrinsic::amdgcn_image_sample_c_cd_cl: 5047 5048 // Sample with offsets. 5049 case Intrinsic::amdgcn_image_sample_o: 5050 case Intrinsic::amdgcn_image_sample_cl_o: 5051 case Intrinsic::amdgcn_image_sample_d_o: 5052 case Intrinsic::amdgcn_image_sample_d_cl_o: 5053 case Intrinsic::amdgcn_image_sample_l_o: 5054 case Intrinsic::amdgcn_image_sample_b_o: 5055 case Intrinsic::amdgcn_image_sample_b_cl_o: 5056 case Intrinsic::amdgcn_image_sample_lz_o: 5057 case Intrinsic::amdgcn_image_sample_cd_o: 5058 case Intrinsic::amdgcn_image_sample_cd_cl_o: 5059 5060 // Sample with comparison and offsets. 5061 case Intrinsic::amdgcn_image_sample_c_o: 5062 case Intrinsic::amdgcn_image_sample_c_cl_o: 5063 case Intrinsic::amdgcn_image_sample_c_d_o: 5064 case Intrinsic::amdgcn_image_sample_c_d_cl_o: 5065 case Intrinsic::amdgcn_image_sample_c_l_o: 5066 case Intrinsic::amdgcn_image_sample_c_b_o: 5067 case Intrinsic::amdgcn_image_sample_c_b_cl_o: 5068 case Intrinsic::amdgcn_image_sample_c_lz_o: 5069 case Intrinsic::amdgcn_image_sample_c_cd_o: 5070 case Intrinsic::amdgcn_image_sample_c_cd_cl_o: { 5071 // Replace dmask with everything disabled with undef. 5072 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(5)); 5073 if (!DMask || DMask->isNullValue()) { 5074 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 5075 return DAG.getMergeValues({ Undef, Op.getOperand(0) }, SDLoc(Op)); 5076 } 5077 5078 return SDValue(); 5079 } 5080 default: 5081 return SDValue(); 5082 } 5083 } 5084 5085 SDValue SITargetLowering::handleD16VData(SDValue VData, 5086 SelectionDAG &DAG) const { 5087 EVT StoreVT = VData.getValueType(); 5088 SDLoc DL(VData); 5089 5090 if (StoreVT.isVector()) { 5091 assert ((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 5092 if (!Subtarget->hasUnpackedD16VMem()) { 5093 if (!isTypeLegal(StoreVT)) { 5094 // If Target supports packed vmem, we just need to workaround 5095 // the illegal type by casting to an equivalent one. 5096 EVT EquivStoreVT = getEquivalentMemType(*DAG.getContext(), StoreVT); 5097 return DAG.getNode(ISD::BITCAST, DL, EquivStoreVT, VData); 5098 } 5099 } else { // We need to unpack the packed data to store. 5100 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 5101 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 5102 EVT EquivStoreVT = (StoreVT == MVT::v2f16) ? MVT::v2i32 : MVT::v4i32; 5103 return DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 5104 } 5105 } 5106 // No change for f16 and legal vector D16 types. 5107 return VData; 5108 } 5109 5110 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 5111 SelectionDAG &DAG) const { 5112 SDLoc DL(Op); 5113 SDValue Chain = Op.getOperand(0); 5114 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 5115 MachineFunction &MF = DAG.getMachineFunction(); 5116 5117 switch (IntrinsicID) { 5118 case Intrinsic::amdgcn_exp: { 5119 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 5120 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 5121 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8)); 5122 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9)); 5123 5124 const SDValue Ops[] = { 5125 Chain, 5126 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 5127 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 5128 Op.getOperand(4), // src0 5129 Op.getOperand(5), // src1 5130 Op.getOperand(6), // src2 5131 Op.getOperand(7), // src3 5132 DAG.getTargetConstant(0, DL, MVT::i1), // compr 5133 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 5134 }; 5135 5136 unsigned Opc = Done->isNullValue() ? 5137 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 5138 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 5139 } 5140 case Intrinsic::amdgcn_exp_compr: { 5141 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 5142 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 5143 SDValue Src0 = Op.getOperand(4); 5144 SDValue Src1 = Op.getOperand(5); 5145 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 5146 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7)); 5147 5148 SDValue Undef = DAG.getUNDEF(MVT::f32); 5149 const SDValue Ops[] = { 5150 Chain, 5151 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 5152 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 5153 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), 5154 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), 5155 Undef, // src2 5156 Undef, // src3 5157 DAG.getTargetConstant(1, DL, MVT::i1), // compr 5158 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 5159 }; 5160 5161 unsigned Opc = Done->isNullValue() ? 5162 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 5163 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 5164 } 5165 case Intrinsic::amdgcn_s_sendmsg: 5166 case Intrinsic::amdgcn_s_sendmsghalt: { 5167 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ? 5168 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT; 5169 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 5170 SDValue Glue = Chain.getValue(1); 5171 return DAG.getNode(NodeOp, DL, MVT::Other, Chain, 5172 Op.getOperand(2), Glue); 5173 } 5174 case Intrinsic::amdgcn_init_exec: { 5175 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain, 5176 Op.getOperand(2)); 5177 } 5178 case Intrinsic::amdgcn_init_exec_from_input: { 5179 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain, 5180 Op.getOperand(2), Op.getOperand(3)); 5181 } 5182 case AMDGPUIntrinsic::AMDGPU_kill: { 5183 SDValue Src = Op.getOperand(2); 5184 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) { 5185 if (!K->isNegative()) 5186 return Chain; 5187 5188 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32); 5189 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne); 5190 } 5191 5192 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src); 5193 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast); 5194 } 5195 case Intrinsic::amdgcn_s_barrier: { 5196 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 5197 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 5198 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 5199 if (WGSize <= ST.getWavefrontSize()) 5200 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 5201 Op.getOperand(0)), 0); 5202 } 5203 return SDValue(); 5204 }; 5205 case AMDGPUIntrinsic::SI_tbuffer_store: { 5206 5207 // Extract vindex and voffset from vaddr as appropriate 5208 const ConstantSDNode *OffEn = cast<ConstantSDNode>(Op.getOperand(10)); 5209 const ConstantSDNode *IdxEn = cast<ConstantSDNode>(Op.getOperand(11)); 5210 SDValue VAddr = Op.getOperand(5); 5211 5212 SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32); 5213 5214 assert(!(OffEn->isOne() && IdxEn->isOne()) && 5215 "Legacy intrinsic doesn't support both offset and index - use new version"); 5216 5217 SDValue VIndex = IdxEn->isOne() ? VAddr : Zero; 5218 SDValue VOffset = OffEn->isOne() ? VAddr : Zero; 5219 5220 // Deal with the vec-3 case 5221 const ConstantSDNode *NumChannels = cast<ConstantSDNode>(Op.getOperand(4)); 5222 auto Opcode = NumChannels->getZExtValue() == 3 ? 5223 AMDGPUISD::TBUFFER_STORE_FORMAT_X3 : AMDGPUISD::TBUFFER_STORE_FORMAT; 5224 5225 SDValue Ops[] = { 5226 Chain, 5227 Op.getOperand(3), // vdata 5228 Op.getOperand(2), // rsrc 5229 VIndex, 5230 VOffset, 5231 Op.getOperand(6), // soffset 5232 Op.getOperand(7), // inst_offset 5233 Op.getOperand(8), // dfmt 5234 Op.getOperand(9), // nfmt 5235 Op.getOperand(12), // glc 5236 Op.getOperand(13), // slc 5237 }; 5238 5239 assert((cast<ConstantSDNode>(Op.getOperand(14)))->getZExtValue() == 0 && 5240 "Value of tfe other than zero is unsupported"); 5241 5242 EVT VT = Op.getOperand(3).getValueType(); 5243 MachineMemOperand *MMO = MF.getMachineMemOperand( 5244 MachinePointerInfo(), 5245 MachineMemOperand::MOStore, 5246 VT.getStoreSize(), 4); 5247 return DAG.getMemIntrinsicNode(Opcode, DL, 5248 Op->getVTList(), Ops, VT, MMO); 5249 } 5250 5251 case Intrinsic::amdgcn_tbuffer_store: { 5252 SDValue VData = Op.getOperand(2); 5253 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 5254 if (IsD16) 5255 VData = handleD16VData(VData, DAG); 5256 SDValue Ops[] = { 5257 Chain, 5258 VData, // vdata 5259 Op.getOperand(3), // rsrc 5260 Op.getOperand(4), // vindex 5261 Op.getOperand(5), // voffset 5262 Op.getOperand(6), // soffset 5263 Op.getOperand(7), // offset 5264 Op.getOperand(8), // dfmt 5265 Op.getOperand(9), // nfmt 5266 Op.getOperand(10), // glc 5267 Op.getOperand(11) // slc 5268 }; 5269 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 5270 AMDGPUISD::TBUFFER_STORE_FORMAT; 5271 MemSDNode *M = cast<MemSDNode>(Op); 5272 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 5273 M->getMemoryVT(), M->getMemOperand()); 5274 } 5275 5276 case Intrinsic::amdgcn_buffer_store: 5277 case Intrinsic::amdgcn_buffer_store_format: { 5278 SDValue VData = Op.getOperand(2); 5279 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 5280 if (IsD16) 5281 VData = handleD16VData(VData, DAG); 5282 SDValue Ops[] = { 5283 Chain, 5284 VData, // vdata 5285 Op.getOperand(3), // rsrc 5286 Op.getOperand(4), // vindex 5287 Op.getOperand(5), // offset 5288 Op.getOperand(6), // glc 5289 Op.getOperand(7) // slc 5290 }; 5291 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 5292 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 5293 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 5294 MemSDNode *M = cast<MemSDNode>(Op); 5295 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 5296 M->getMemoryVT(), M->getMemOperand()); 5297 } 5298 5299 case Intrinsic::amdgcn_image_store: 5300 case Intrinsic::amdgcn_image_store_mip: { 5301 SDValue VData = Op.getOperand(2); 5302 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 5303 if (IsD16) 5304 VData = handleD16VData(VData, DAG); 5305 SDValue Ops[] = { 5306 Chain, // Chain 5307 VData, // vdata 5308 Op.getOperand(3), // vaddr 5309 Op.getOperand(4), // rsrc 5310 Op.getOperand(5), // dmask 5311 Op.getOperand(6), // glc 5312 Op.getOperand(7), // slc 5313 Op.getOperand(8), // lwe 5314 Op.getOperand(9) // da 5315 }; 5316 unsigned Opc = (IntrinsicID==Intrinsic::amdgcn_image_store) ? 5317 AMDGPUISD::IMAGE_STORE : AMDGPUISD::IMAGE_STORE_MIP; 5318 MemSDNode *M = cast<MemSDNode>(Op); 5319 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 5320 M->getMemoryVT(), M->getMemOperand()); 5321 } 5322 5323 default: 5324 return Op; 5325 } 5326 } 5327 5328 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 5329 SDLoc DL(Op); 5330 LoadSDNode *Load = cast<LoadSDNode>(Op); 5331 ISD::LoadExtType ExtType = Load->getExtensionType(); 5332 EVT MemVT = Load->getMemoryVT(); 5333 5334 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 5335 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 5336 return SDValue(); 5337 5338 // FIXME: Copied from PPC 5339 // First, load into 32 bits, then truncate to 1 bit. 5340 5341 SDValue Chain = Load->getChain(); 5342 SDValue BasePtr = Load->getBasePtr(); 5343 MachineMemOperand *MMO = Load->getMemOperand(); 5344 5345 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 5346 5347 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 5348 BasePtr, RealMemVT, MMO); 5349 5350 SDValue Ops[] = { 5351 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 5352 NewLD.getValue(1) 5353 }; 5354 5355 return DAG.getMergeValues(Ops, DL); 5356 } 5357 5358 if (!MemVT.isVector()) 5359 return SDValue(); 5360 5361 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 5362 "Custom lowering for non-i32 vectors hasn't been implemented."); 5363 5364 unsigned AS = Load->getAddressSpace(); 5365 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 5366 AS, Load->getAlignment())) { 5367 SDValue Ops[2]; 5368 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 5369 return DAG.getMergeValues(Ops, DL); 5370 } 5371 5372 MachineFunction &MF = DAG.getMachineFunction(); 5373 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 5374 // If there is a possibilty that flat instruction access scratch memory 5375 // then we need to use the same legalization rules we use for private. 5376 if (AS == AMDGPUASI.FLAT_ADDRESS) 5377 AS = MFI->hasFlatScratchInit() ? 5378 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS; 5379 5380 unsigned NumElements = MemVT.getVectorNumElements(); 5381 if (AS == AMDGPUASI.CONSTANT_ADDRESS) { 5382 if (isMemOpUniform(Load)) 5383 return SDValue(); 5384 // Non-uniform loads will be selected to MUBUF instructions, so they 5385 // have the same legalization requirements as global and private 5386 // loads. 5387 // 5388 } 5389 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS) { 5390 if (Subtarget->getScalarizeGlobalBehavior() && isMemOpUniform(Load) && 5391 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load)) 5392 return SDValue(); 5393 // Non-uniform loads will be selected to MUBUF instructions, so they 5394 // have the same legalization requirements as global and private 5395 // loads. 5396 // 5397 } 5398 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS || 5399 AS == AMDGPUASI.FLAT_ADDRESS) { 5400 if (NumElements > 4) 5401 return SplitVectorLoad(Op, DAG); 5402 // v4 loads are supported for private and global memory. 5403 return SDValue(); 5404 } 5405 if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 5406 // Depending on the setting of the private_element_size field in the 5407 // resource descriptor, we can only make private accesses up to a certain 5408 // size. 5409 switch (Subtarget->getMaxPrivateElementSize()) { 5410 case 4: 5411 return scalarizeVectorLoad(Load, DAG); 5412 case 8: 5413 if (NumElements > 2) 5414 return SplitVectorLoad(Op, DAG); 5415 return SDValue(); 5416 case 16: 5417 // Same as global/flat 5418 if (NumElements > 4) 5419 return SplitVectorLoad(Op, DAG); 5420 return SDValue(); 5421 default: 5422 llvm_unreachable("unsupported private_element_size"); 5423 } 5424 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 5425 if (NumElements > 2) 5426 return SplitVectorLoad(Op, DAG); 5427 5428 if (NumElements == 2) 5429 return SDValue(); 5430 5431 // If properly aligned, if we split we might be able to use ds_read_b64. 5432 return SplitVectorLoad(Op, DAG); 5433 } 5434 return SDValue(); 5435 } 5436 5437 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 5438 if (Op.getValueType() != MVT::i64) 5439 return SDValue(); 5440 5441 SDLoc DL(Op); 5442 SDValue Cond = Op.getOperand(0); 5443 5444 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 5445 SDValue One = DAG.getConstant(1, DL, MVT::i32); 5446 5447 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 5448 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 5449 5450 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 5451 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 5452 5453 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 5454 5455 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 5456 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 5457 5458 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 5459 5460 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 5461 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res); 5462 } 5463 5464 // Catch division cases where we can use shortcuts with rcp and rsq 5465 // instructions. 5466 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 5467 SelectionDAG &DAG) const { 5468 SDLoc SL(Op); 5469 SDValue LHS = Op.getOperand(0); 5470 SDValue RHS = Op.getOperand(1); 5471 EVT VT = Op.getValueType(); 5472 const SDNodeFlags Flags = Op->getFlags(); 5473 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || 5474 Flags.hasUnsafeAlgebra() || Flags.hasAllowReciprocal(); 5475 5476 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals()) 5477 return SDValue(); 5478 5479 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 5480 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) { 5481 if (CLHS->isExactlyValue(1.0)) { 5482 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 5483 // the CI documentation has a worst case error of 1 ulp. 5484 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 5485 // use it as long as we aren't trying to use denormals. 5486 // 5487 // v_rcp_f16 and v_rsq_f16 DO support denormals. 5488 5489 // 1.0 / sqrt(x) -> rsq(x) 5490 5491 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 5492 // error seems really high at 2^29 ULP. 5493 if (RHS.getOpcode() == ISD::FSQRT) 5494 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 5495 5496 // 1.0 / x -> rcp(x) 5497 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 5498 } 5499 5500 // Same as for 1.0, but expand the sign out of the constant. 5501 if (CLHS->isExactlyValue(-1.0)) { 5502 // -1.0 / x -> rcp (fneg x) 5503 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 5504 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 5505 } 5506 } 5507 } 5508 5509 if (Unsafe) { 5510 // Turn into multiply by the reciprocal. 5511 // x / y -> x * (1.0 / y) 5512 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 5513 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 5514 } 5515 5516 return SDValue(); 5517 } 5518 5519 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 5520 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 5521 if (GlueChain->getNumValues() <= 1) { 5522 return DAG.getNode(Opcode, SL, VT, A, B); 5523 } 5524 5525 assert(GlueChain->getNumValues() == 3); 5526 5527 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 5528 switch (Opcode) { 5529 default: llvm_unreachable("no chain equivalent for opcode"); 5530 case ISD::FMUL: 5531 Opcode = AMDGPUISD::FMUL_W_CHAIN; 5532 break; 5533 } 5534 5535 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 5536 GlueChain.getValue(2)); 5537 } 5538 5539 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 5540 EVT VT, SDValue A, SDValue B, SDValue C, 5541 SDValue GlueChain) { 5542 if (GlueChain->getNumValues() <= 1) { 5543 return DAG.getNode(Opcode, SL, VT, A, B, C); 5544 } 5545 5546 assert(GlueChain->getNumValues() == 3); 5547 5548 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 5549 switch (Opcode) { 5550 default: llvm_unreachable("no chain equivalent for opcode"); 5551 case ISD::FMA: 5552 Opcode = AMDGPUISD::FMA_W_CHAIN; 5553 break; 5554 } 5555 5556 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 5557 GlueChain.getValue(2)); 5558 } 5559 5560 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 5561 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 5562 return FastLowered; 5563 5564 SDLoc SL(Op); 5565 SDValue Src0 = Op.getOperand(0); 5566 SDValue Src1 = Op.getOperand(1); 5567 5568 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 5569 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 5570 5571 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 5572 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 5573 5574 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 5575 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 5576 5577 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 5578 } 5579 5580 // Faster 2.5 ULP division that does not support denormals. 5581 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 5582 SDLoc SL(Op); 5583 SDValue LHS = Op.getOperand(1); 5584 SDValue RHS = Op.getOperand(2); 5585 5586 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 5587 5588 const APFloat K0Val(BitsToFloat(0x6f800000)); 5589 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 5590 5591 const APFloat K1Val(BitsToFloat(0x2f800000)); 5592 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 5593 5594 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 5595 5596 EVT SetCCVT = 5597 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 5598 5599 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 5600 5601 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 5602 5603 // TODO: Should this propagate fast-math-flags? 5604 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 5605 5606 // rcp does not support denormals. 5607 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 5608 5609 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 5610 5611 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 5612 } 5613 5614 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 5615 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 5616 return FastLowered; 5617 5618 SDLoc SL(Op); 5619 SDValue LHS = Op.getOperand(0); 5620 SDValue RHS = Op.getOperand(1); 5621 5622 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 5623 5624 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 5625 5626 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 5627 RHS, RHS, LHS); 5628 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 5629 LHS, RHS, LHS); 5630 5631 // Denominator is scaled to not be denormal, so using rcp is ok. 5632 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 5633 DenominatorScaled); 5634 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 5635 DenominatorScaled); 5636 5637 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 5638 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 5639 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 5640 5641 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 5642 5643 if (!Subtarget->hasFP32Denormals()) { 5644 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 5645 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 5646 SL, MVT::i32); 5647 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 5648 DAG.getEntryNode(), 5649 EnableDenormValue, BitField); 5650 SDValue Ops[3] = { 5651 NegDivScale0, 5652 EnableDenorm.getValue(0), 5653 EnableDenorm.getValue(1) 5654 }; 5655 5656 NegDivScale0 = DAG.getMergeValues(Ops, SL); 5657 } 5658 5659 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 5660 ApproxRcp, One, NegDivScale0); 5661 5662 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 5663 ApproxRcp, Fma0); 5664 5665 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 5666 Fma1, Fma1); 5667 5668 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 5669 NumeratorScaled, Mul); 5670 5671 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 5672 5673 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 5674 NumeratorScaled, Fma3); 5675 5676 if (!Subtarget->hasFP32Denormals()) { 5677 const SDValue DisableDenormValue = 5678 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 5679 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 5680 Fma4.getValue(1), 5681 DisableDenormValue, 5682 BitField, 5683 Fma4.getValue(2)); 5684 5685 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 5686 DisableDenorm, DAG.getRoot()); 5687 DAG.setRoot(OutputChain); 5688 } 5689 5690 SDValue Scale = NumeratorScaled.getValue(1); 5691 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 5692 Fma4, Fma1, Fma3, Scale); 5693 5694 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 5695 } 5696 5697 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 5698 if (DAG.getTarget().Options.UnsafeFPMath) 5699 return lowerFastUnsafeFDIV(Op, DAG); 5700 5701 SDLoc SL(Op); 5702 SDValue X = Op.getOperand(0); 5703 SDValue Y = Op.getOperand(1); 5704 5705 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 5706 5707 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 5708 5709 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 5710 5711 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 5712 5713 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 5714 5715 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 5716 5717 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 5718 5719 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 5720 5721 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 5722 5723 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 5724 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 5725 5726 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 5727 NegDivScale0, Mul, DivScale1); 5728 5729 SDValue Scale; 5730 5731 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) { 5732 // Workaround a hardware bug on SI where the condition output from div_scale 5733 // is not usable. 5734 5735 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 5736 5737 // Figure out if the scale to use for div_fmas. 5738 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 5739 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 5740 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 5741 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 5742 5743 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 5744 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 5745 5746 SDValue Scale0Hi 5747 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 5748 SDValue Scale1Hi 5749 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 5750 5751 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 5752 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 5753 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 5754 } else { 5755 Scale = DivScale1.getValue(1); 5756 } 5757 5758 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 5759 Fma4, Fma3, Mul, Scale); 5760 5761 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 5762 } 5763 5764 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 5765 EVT VT = Op.getValueType(); 5766 5767 if (VT == MVT::f32) 5768 return LowerFDIV32(Op, DAG); 5769 5770 if (VT == MVT::f64) 5771 return LowerFDIV64(Op, DAG); 5772 5773 if (VT == MVT::f16) 5774 return LowerFDIV16(Op, DAG); 5775 5776 llvm_unreachable("Unexpected type for fdiv"); 5777 } 5778 5779 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 5780 SDLoc DL(Op); 5781 StoreSDNode *Store = cast<StoreSDNode>(Op); 5782 EVT VT = Store->getMemoryVT(); 5783 5784 if (VT == MVT::i1) { 5785 return DAG.getTruncStore(Store->getChain(), DL, 5786 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 5787 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 5788 } 5789 5790 assert(VT.isVector() && 5791 Store->getValue().getValueType().getScalarType() == MVT::i32); 5792 5793 unsigned AS = Store->getAddressSpace(); 5794 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 5795 AS, Store->getAlignment())) { 5796 return expandUnalignedStore(Store, DAG); 5797 } 5798 5799 MachineFunction &MF = DAG.getMachineFunction(); 5800 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 5801 // If there is a possibilty that flat instruction access scratch memory 5802 // then we need to use the same legalization rules we use for private. 5803 if (AS == AMDGPUASI.FLAT_ADDRESS) 5804 AS = MFI->hasFlatScratchInit() ? 5805 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS; 5806 5807 unsigned NumElements = VT.getVectorNumElements(); 5808 if (AS == AMDGPUASI.GLOBAL_ADDRESS || 5809 AS == AMDGPUASI.FLAT_ADDRESS) { 5810 if (NumElements > 4) 5811 return SplitVectorStore(Op, DAG); 5812 return SDValue(); 5813 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 5814 switch (Subtarget->getMaxPrivateElementSize()) { 5815 case 4: 5816 return scalarizeVectorStore(Store, DAG); 5817 case 8: 5818 if (NumElements > 2) 5819 return SplitVectorStore(Op, DAG); 5820 return SDValue(); 5821 case 16: 5822 if (NumElements > 4) 5823 return SplitVectorStore(Op, DAG); 5824 return SDValue(); 5825 default: 5826 llvm_unreachable("unsupported private_element_size"); 5827 } 5828 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 5829 if (NumElements > 2) 5830 return SplitVectorStore(Op, DAG); 5831 5832 if (NumElements == 2) 5833 return Op; 5834 5835 // If properly aligned, if we split we might be able to use ds_write_b64. 5836 return SplitVectorStore(Op, DAG); 5837 } else { 5838 llvm_unreachable("unhandled address space"); 5839 } 5840 } 5841 5842 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 5843 SDLoc DL(Op); 5844 EVT VT = Op.getValueType(); 5845 SDValue Arg = Op.getOperand(0); 5846 // TODO: Should this propagate fast-math-flags? 5847 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT, 5848 DAG.getNode(ISD::FMUL, DL, VT, Arg, 5849 DAG.getConstantFP(0.5/M_PI, DL, 5850 VT))); 5851 5852 switch (Op.getOpcode()) { 5853 case ISD::FCOS: 5854 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart); 5855 case ISD::FSIN: 5856 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart); 5857 default: 5858 llvm_unreachable("Wrong trig opcode"); 5859 } 5860 } 5861 5862 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 5863 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 5864 assert(AtomicNode->isCompareAndSwap()); 5865 unsigned AS = AtomicNode->getAddressSpace(); 5866 5867 // No custom lowering required for local address space 5868 if (!isFlatGlobalAddrSpace(AS, AMDGPUASI)) 5869 return Op; 5870 5871 // Non-local address space requires custom lowering for atomic compare 5872 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 5873 SDLoc DL(Op); 5874 SDValue ChainIn = Op.getOperand(0); 5875 SDValue Addr = Op.getOperand(1); 5876 SDValue Old = Op.getOperand(2); 5877 SDValue New = Op.getOperand(3); 5878 EVT VT = Op.getValueType(); 5879 MVT SimpleVT = VT.getSimpleVT(); 5880 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 5881 5882 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 5883 SDValue Ops[] = { ChainIn, Addr, NewOld }; 5884 5885 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 5886 Ops, VT, AtomicNode->getMemOperand()); 5887 } 5888 5889 //===----------------------------------------------------------------------===// 5890 // Custom DAG optimizations 5891 //===----------------------------------------------------------------------===// 5892 5893 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 5894 DAGCombinerInfo &DCI) const { 5895 EVT VT = N->getValueType(0); 5896 EVT ScalarVT = VT.getScalarType(); 5897 if (ScalarVT != MVT::f32) 5898 return SDValue(); 5899 5900 SelectionDAG &DAG = DCI.DAG; 5901 SDLoc DL(N); 5902 5903 SDValue Src = N->getOperand(0); 5904 EVT SrcVT = Src.getValueType(); 5905 5906 // TODO: We could try to match extracting the higher bytes, which would be 5907 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 5908 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 5909 // about in practice. 5910 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) { 5911 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 5912 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 5913 DCI.AddToWorklist(Cvt.getNode()); 5914 return Cvt; 5915 } 5916 } 5917 5918 return SDValue(); 5919 } 5920 5921 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 5922 5923 // This is a variant of 5924 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 5925 // 5926 // The normal DAG combiner will do this, but only if the add has one use since 5927 // that would increase the number of instructions. 5928 // 5929 // This prevents us from seeing a constant offset that can be folded into a 5930 // memory instruction's addressing mode. If we know the resulting add offset of 5931 // a pointer can be folded into an addressing offset, we can replace the pointer 5932 // operand with the add of new constant offset. This eliminates one of the uses, 5933 // and may allow the remaining use to also be simplified. 5934 // 5935 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 5936 unsigned AddrSpace, 5937 EVT MemVT, 5938 DAGCombinerInfo &DCI) const { 5939 SDValue N0 = N->getOperand(0); 5940 SDValue N1 = N->getOperand(1); 5941 5942 // We only do this to handle cases where it's profitable when there are 5943 // multiple uses of the add, so defer to the standard combine. 5944 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 5945 N0->hasOneUse()) 5946 return SDValue(); 5947 5948 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 5949 if (!CN1) 5950 return SDValue(); 5951 5952 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5953 if (!CAdd) 5954 return SDValue(); 5955 5956 // If the resulting offset is too large, we can't fold it into the addressing 5957 // mode offset. 5958 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 5959 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 5960 5961 AddrMode AM; 5962 AM.HasBaseReg = true; 5963 AM.BaseOffs = Offset.getSExtValue(); 5964 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 5965 return SDValue(); 5966 5967 SelectionDAG &DAG = DCI.DAG; 5968 SDLoc SL(N); 5969 EVT VT = N->getValueType(0); 5970 5971 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 5972 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 5973 5974 SDNodeFlags Flags; 5975 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 5976 (N0.getOpcode() == ISD::OR || 5977 N0->getFlags().hasNoUnsignedWrap())); 5978 5979 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 5980 } 5981 5982 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 5983 DAGCombinerInfo &DCI) const { 5984 SDValue Ptr = N->getBasePtr(); 5985 SelectionDAG &DAG = DCI.DAG; 5986 SDLoc SL(N); 5987 5988 // TODO: We could also do this for multiplies. 5989 if (Ptr.getOpcode() == ISD::SHL) { 5990 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 5991 N->getMemoryVT(), DCI); 5992 if (NewPtr) { 5993 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 5994 5995 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 5996 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 5997 } 5998 } 5999 6000 return SDValue(); 6001 } 6002 6003 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 6004 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 6005 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 6006 (Opc == ISD::XOR && Val == 0); 6007 } 6008 6009 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 6010 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 6011 // integer combine opportunities since most 64-bit operations are decomposed 6012 // this way. TODO: We won't want this for SALU especially if it is an inline 6013 // immediate. 6014 SDValue SITargetLowering::splitBinaryBitConstantOp( 6015 DAGCombinerInfo &DCI, 6016 const SDLoc &SL, 6017 unsigned Opc, SDValue LHS, 6018 const ConstantSDNode *CRHS) const { 6019 uint64_t Val = CRHS->getZExtValue(); 6020 uint32_t ValLo = Lo_32(Val); 6021 uint32_t ValHi = Hi_32(Val); 6022 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 6023 6024 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 6025 bitOpWithConstantIsReducible(Opc, ValHi)) || 6026 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 6027 // If we need to materialize a 64-bit immediate, it will be split up later 6028 // anyway. Avoid creating the harder to understand 64-bit immediate 6029 // materialization. 6030 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 6031 } 6032 6033 return SDValue(); 6034 } 6035 6036 // Returns true if argument is a boolean value which is not serialized into 6037 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 6038 static bool isBoolSGPR(SDValue V) { 6039 if (V.getValueType() != MVT::i1) 6040 return false; 6041 switch (V.getOpcode()) { 6042 default: break; 6043 case ISD::SETCC: 6044 case ISD::AND: 6045 case ISD::OR: 6046 case ISD::XOR: 6047 case AMDGPUISD::FP_CLASS: 6048 return true; 6049 } 6050 return false; 6051 } 6052 6053 SDValue SITargetLowering::performAndCombine(SDNode *N, 6054 DAGCombinerInfo &DCI) const { 6055 if (DCI.isBeforeLegalize()) 6056 return SDValue(); 6057 6058 SelectionDAG &DAG = DCI.DAG; 6059 EVT VT = N->getValueType(0); 6060 SDValue LHS = N->getOperand(0); 6061 SDValue RHS = N->getOperand(1); 6062 6063 6064 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 6065 if (VT == MVT::i64 && CRHS) { 6066 if (SDValue Split 6067 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 6068 return Split; 6069 } 6070 6071 if (CRHS && VT == MVT::i32) { 6072 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 6073 // nb = number of trailing zeroes in mask 6074 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 6075 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 6076 uint64_t Mask = CRHS->getZExtValue(); 6077 unsigned Bits = countPopulation(Mask); 6078 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 6079 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 6080 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 6081 unsigned Shift = CShift->getZExtValue(); 6082 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 6083 unsigned Offset = NB + Shift; 6084 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 6085 SDLoc SL(N); 6086 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 6087 LHS->getOperand(0), 6088 DAG.getConstant(Offset, SL, MVT::i32), 6089 DAG.getConstant(Bits, SL, MVT::i32)); 6090 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 6091 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 6092 DAG.getValueType(NarrowVT)); 6093 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 6094 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 6095 return Shl; 6096 } 6097 } 6098 } 6099 } 6100 6101 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 6102 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 6103 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 6104 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 6105 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 6106 6107 SDValue X = LHS.getOperand(0); 6108 SDValue Y = RHS.getOperand(0); 6109 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 6110 return SDValue(); 6111 6112 if (LCC == ISD::SETO) { 6113 if (X != LHS.getOperand(1)) 6114 return SDValue(); 6115 6116 if (RCC == ISD::SETUNE) { 6117 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 6118 if (!C1 || !C1->isInfinity() || C1->isNegative()) 6119 return SDValue(); 6120 6121 const uint32_t Mask = SIInstrFlags::N_NORMAL | 6122 SIInstrFlags::N_SUBNORMAL | 6123 SIInstrFlags::N_ZERO | 6124 SIInstrFlags::P_ZERO | 6125 SIInstrFlags::P_SUBNORMAL | 6126 SIInstrFlags::P_NORMAL; 6127 6128 static_assert(((~(SIInstrFlags::S_NAN | 6129 SIInstrFlags::Q_NAN | 6130 SIInstrFlags::N_INFINITY | 6131 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 6132 "mask not equal"); 6133 6134 SDLoc DL(N); 6135 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 6136 X, DAG.getConstant(Mask, DL, MVT::i32)); 6137 } 6138 } 6139 } 6140 6141 if (VT == MVT::i32 && 6142 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 6143 // and x, (sext cc from i1) => select cc, x, 0 6144 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 6145 std::swap(LHS, RHS); 6146 if (isBoolSGPR(RHS.getOperand(0))) 6147 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 6148 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 6149 } 6150 6151 return SDValue(); 6152 } 6153 6154 SDValue SITargetLowering::performOrCombine(SDNode *N, 6155 DAGCombinerInfo &DCI) const { 6156 SelectionDAG &DAG = DCI.DAG; 6157 SDValue LHS = N->getOperand(0); 6158 SDValue RHS = N->getOperand(1); 6159 6160 EVT VT = N->getValueType(0); 6161 if (VT == MVT::i1) { 6162 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 6163 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 6164 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 6165 SDValue Src = LHS.getOperand(0); 6166 if (Src != RHS.getOperand(0)) 6167 return SDValue(); 6168 6169 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 6170 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 6171 if (!CLHS || !CRHS) 6172 return SDValue(); 6173 6174 // Only 10 bits are used. 6175 static const uint32_t MaxMask = 0x3ff; 6176 6177 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 6178 SDLoc DL(N); 6179 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 6180 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 6181 } 6182 6183 return SDValue(); 6184 } 6185 6186 if (VT != MVT::i64) 6187 return SDValue(); 6188 6189 // TODO: This could be a generic combine with a predicate for extracting the 6190 // high half of an integer being free. 6191 6192 // (or i64:x, (zero_extend i32:y)) -> 6193 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 6194 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 6195 RHS.getOpcode() != ISD::ZERO_EXTEND) 6196 std::swap(LHS, RHS); 6197 6198 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 6199 SDValue ExtSrc = RHS.getOperand(0); 6200 EVT SrcVT = ExtSrc.getValueType(); 6201 if (SrcVT == MVT::i32) { 6202 SDLoc SL(N); 6203 SDValue LowLHS, HiBits; 6204 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 6205 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 6206 6207 DCI.AddToWorklist(LowOr.getNode()); 6208 DCI.AddToWorklist(HiBits.getNode()); 6209 6210 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 6211 LowOr, HiBits); 6212 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 6213 } 6214 } 6215 6216 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6217 if (CRHS) { 6218 if (SDValue Split 6219 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 6220 return Split; 6221 } 6222 6223 return SDValue(); 6224 } 6225 6226 SDValue SITargetLowering::performXorCombine(SDNode *N, 6227 DAGCombinerInfo &DCI) const { 6228 EVT VT = N->getValueType(0); 6229 if (VT != MVT::i64) 6230 return SDValue(); 6231 6232 SDValue LHS = N->getOperand(0); 6233 SDValue RHS = N->getOperand(1); 6234 6235 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 6236 if (CRHS) { 6237 if (SDValue Split 6238 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 6239 return Split; 6240 } 6241 6242 return SDValue(); 6243 } 6244 6245 // Instructions that will be lowered with a final instruction that zeros the 6246 // high result bits. 6247 // XXX - probably only need to list legal operations. 6248 static bool fp16SrcZerosHighBits(unsigned Opc) { 6249 switch (Opc) { 6250 case ISD::FADD: 6251 case ISD::FSUB: 6252 case ISD::FMUL: 6253 case ISD::FDIV: 6254 case ISD::FREM: 6255 case ISD::FMA: 6256 case ISD::FMAD: 6257 case ISD::FCANONICALIZE: 6258 case ISD::FP_ROUND: 6259 case ISD::UINT_TO_FP: 6260 case ISD::SINT_TO_FP: 6261 case ISD::FABS: 6262 // Fabs is lowered to a bit operation, but it's an and which will clear the 6263 // high bits anyway. 6264 case ISD::FSQRT: 6265 case ISD::FSIN: 6266 case ISD::FCOS: 6267 case ISD::FPOWI: 6268 case ISD::FPOW: 6269 case ISD::FLOG: 6270 case ISD::FLOG2: 6271 case ISD::FLOG10: 6272 case ISD::FEXP: 6273 case ISD::FEXP2: 6274 case ISD::FCEIL: 6275 case ISD::FTRUNC: 6276 case ISD::FRINT: 6277 case ISD::FNEARBYINT: 6278 case ISD::FROUND: 6279 case ISD::FFLOOR: 6280 case ISD::FMINNUM: 6281 case ISD::FMAXNUM: 6282 case AMDGPUISD::FRACT: 6283 case AMDGPUISD::CLAMP: 6284 case AMDGPUISD::COS_HW: 6285 case AMDGPUISD::SIN_HW: 6286 case AMDGPUISD::FMIN3: 6287 case AMDGPUISD::FMAX3: 6288 case AMDGPUISD::FMED3: 6289 case AMDGPUISD::FMAD_FTZ: 6290 case AMDGPUISD::RCP: 6291 case AMDGPUISD::RSQ: 6292 case AMDGPUISD::LDEXP: 6293 return true; 6294 default: 6295 // fcopysign, select and others may be lowered to 32-bit bit operations 6296 // which don't zero the high bits. 6297 return false; 6298 } 6299 } 6300 6301 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 6302 DAGCombinerInfo &DCI) const { 6303 if (!Subtarget->has16BitInsts() || 6304 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 6305 return SDValue(); 6306 6307 EVT VT = N->getValueType(0); 6308 if (VT != MVT::i32) 6309 return SDValue(); 6310 6311 SDValue Src = N->getOperand(0); 6312 if (Src.getValueType() != MVT::i16) 6313 return SDValue(); 6314 6315 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 6316 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 6317 if (Src.getOpcode() == ISD::BITCAST) { 6318 SDValue BCSrc = Src.getOperand(0); 6319 if (BCSrc.getValueType() == MVT::f16 && 6320 fp16SrcZerosHighBits(BCSrc.getOpcode())) 6321 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 6322 } 6323 6324 return SDValue(); 6325 } 6326 6327 SDValue SITargetLowering::performClassCombine(SDNode *N, 6328 DAGCombinerInfo &DCI) const { 6329 SelectionDAG &DAG = DCI.DAG; 6330 SDValue Mask = N->getOperand(1); 6331 6332 // fp_class x, 0 -> false 6333 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 6334 if (CMask->isNullValue()) 6335 return DAG.getConstant(0, SDLoc(N), MVT::i1); 6336 } 6337 6338 if (N->getOperand(0).isUndef()) 6339 return DAG.getUNDEF(MVT::i1); 6340 6341 return SDValue(); 6342 } 6343 6344 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) { 6345 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions()) 6346 return true; 6347 6348 return DAG.isKnownNeverNaN(Op); 6349 } 6350 6351 static bool isCanonicalized(SelectionDAG &DAG, SDValue Op, 6352 const SISubtarget *ST, unsigned MaxDepth=5) { 6353 // If source is a result of another standard FP operation it is already in 6354 // canonical form. 6355 6356 switch (Op.getOpcode()) { 6357 default: 6358 break; 6359 6360 // These will flush denorms if required. 6361 case ISD::FADD: 6362 case ISD::FSUB: 6363 case ISD::FMUL: 6364 case ISD::FSQRT: 6365 case ISD::FCEIL: 6366 case ISD::FFLOOR: 6367 case ISD::FMA: 6368 case ISD::FMAD: 6369 6370 case ISD::FCANONICALIZE: 6371 return true; 6372 6373 case ISD::FP_ROUND: 6374 return Op.getValueType().getScalarType() != MVT::f16 || 6375 ST->hasFP16Denormals(); 6376 6377 case ISD::FP_EXTEND: 6378 return Op.getOperand(0).getValueType().getScalarType() != MVT::f16 || 6379 ST->hasFP16Denormals(); 6380 6381 case ISD::FP16_TO_FP: 6382 case ISD::FP_TO_FP16: 6383 return ST->hasFP16Denormals(); 6384 6385 // It can/will be lowered or combined as a bit operation. 6386 // Need to check their input recursively to handle. 6387 case ISD::FNEG: 6388 case ISD::FABS: 6389 return (MaxDepth > 0) && 6390 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1); 6391 6392 case ISD::FSIN: 6393 case ISD::FCOS: 6394 case ISD::FSINCOS: 6395 return Op.getValueType().getScalarType() != MVT::f16; 6396 6397 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. 6398 // For such targets need to check their input recursively. 6399 case ISD::FMINNUM: 6400 case ISD::FMAXNUM: 6401 case ISD::FMINNAN: 6402 case ISD::FMAXNAN: 6403 6404 if (ST->supportsMinMaxDenormModes() && 6405 DAG.isKnownNeverNaN(Op.getOperand(0)) && 6406 DAG.isKnownNeverNaN(Op.getOperand(1))) 6407 return true; 6408 6409 return (MaxDepth > 0) && 6410 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1) && 6411 isCanonicalized(DAG, Op.getOperand(1), ST, MaxDepth - 1); 6412 6413 case ISD::ConstantFP: { 6414 auto F = cast<ConstantFPSDNode>(Op)->getValueAPF(); 6415 return !F.isDenormal() && !(F.isNaN() && F.isSignaling()); 6416 } 6417 } 6418 return false; 6419 } 6420 6421 // Constant fold canonicalize. 6422 SDValue SITargetLowering::performFCanonicalizeCombine( 6423 SDNode *N, 6424 DAGCombinerInfo &DCI) const { 6425 SelectionDAG &DAG = DCI.DAG; 6426 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0)); 6427 6428 if (!CFP) { 6429 SDValue N0 = N->getOperand(0); 6430 EVT VT = N0.getValueType().getScalarType(); 6431 auto ST = getSubtarget(); 6432 6433 if (((VT == MVT::f32 && ST->hasFP32Denormals()) || 6434 (VT == MVT::f64 && ST->hasFP64Denormals()) || 6435 (VT == MVT::f16 && ST->hasFP16Denormals())) && 6436 DAG.isKnownNeverNaN(N0)) 6437 return N0; 6438 6439 bool IsIEEEMode = Subtarget->enableIEEEBit(DAG.getMachineFunction()); 6440 6441 if ((IsIEEEMode || isKnownNeverSNan(DAG, N0)) && 6442 isCanonicalized(DAG, N0, ST)) 6443 return N0; 6444 6445 return SDValue(); 6446 } 6447 6448 const APFloat &C = CFP->getValueAPF(); 6449 6450 // Flush denormals to 0 if not enabled. 6451 if (C.isDenormal()) { 6452 EVT VT = N->getValueType(0); 6453 EVT SVT = VT.getScalarType(); 6454 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals()) 6455 return DAG.getConstantFP(0.0, SDLoc(N), VT); 6456 6457 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals()) 6458 return DAG.getConstantFP(0.0, SDLoc(N), VT); 6459 6460 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals()) 6461 return DAG.getConstantFP(0.0, SDLoc(N), VT); 6462 } 6463 6464 if (C.isNaN()) { 6465 EVT VT = N->getValueType(0); 6466 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 6467 if (C.isSignaling()) { 6468 // Quiet a signaling NaN. 6469 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 6470 } 6471 6472 // Make sure it is the canonical NaN bitpattern. 6473 // 6474 // TODO: Can we use -1 as the canonical NaN value since it's an inline 6475 // immediate? 6476 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 6477 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 6478 } 6479 6480 return N->getOperand(0); 6481 } 6482 6483 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 6484 switch (Opc) { 6485 case ISD::FMAXNUM: 6486 return AMDGPUISD::FMAX3; 6487 case ISD::SMAX: 6488 return AMDGPUISD::SMAX3; 6489 case ISD::UMAX: 6490 return AMDGPUISD::UMAX3; 6491 case ISD::FMINNUM: 6492 return AMDGPUISD::FMIN3; 6493 case ISD::SMIN: 6494 return AMDGPUISD::SMIN3; 6495 case ISD::UMIN: 6496 return AMDGPUISD::UMIN3; 6497 default: 6498 llvm_unreachable("Not a min/max opcode"); 6499 } 6500 } 6501 6502 SDValue SITargetLowering::performIntMed3ImmCombine( 6503 SelectionDAG &DAG, const SDLoc &SL, 6504 SDValue Op0, SDValue Op1, bool Signed) const { 6505 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 6506 if (!K1) 6507 return SDValue(); 6508 6509 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 6510 if (!K0) 6511 return SDValue(); 6512 6513 if (Signed) { 6514 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 6515 return SDValue(); 6516 } else { 6517 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 6518 return SDValue(); 6519 } 6520 6521 EVT VT = K0->getValueType(0); 6522 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 6523 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 6524 return DAG.getNode(Med3Opc, SL, VT, 6525 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 6526 } 6527 6528 // If there isn't a 16-bit med3 operation, convert to 32-bit. 6529 MVT NVT = MVT::i32; 6530 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6531 6532 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 6533 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 6534 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 6535 6536 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 6537 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 6538 } 6539 6540 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 6541 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 6542 return C; 6543 6544 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 6545 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 6546 return C; 6547 } 6548 6549 return nullptr; 6550 } 6551 6552 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 6553 const SDLoc &SL, 6554 SDValue Op0, 6555 SDValue Op1) const { 6556 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 6557 if (!K1) 6558 return SDValue(); 6559 6560 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 6561 if (!K0) 6562 return SDValue(); 6563 6564 // Ordered >= (although NaN inputs should have folded away by now). 6565 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 6566 if (Cmp == APFloat::cmpGreaterThan) 6567 return SDValue(); 6568 6569 // TODO: Check IEEE bit enabled? 6570 EVT VT = Op0.getValueType(); 6571 if (Subtarget->enableDX10Clamp()) { 6572 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 6573 // hardware fmed3 behavior converting to a min. 6574 // FIXME: Should this be allowing -0.0? 6575 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 6576 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 6577 } 6578 6579 // med3 for f16 is only available on gfx9+, and not available for v2f16. 6580 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 6581 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 6582 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 6583 // then give the other result, which is different from med3 with a NaN 6584 // input. 6585 SDValue Var = Op0.getOperand(0); 6586 if (!isKnownNeverSNan(DAG, Var)) 6587 return SDValue(); 6588 6589 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 6590 Var, SDValue(K0, 0), SDValue(K1, 0)); 6591 } 6592 6593 return SDValue(); 6594 } 6595 6596 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 6597 DAGCombinerInfo &DCI) const { 6598 SelectionDAG &DAG = DCI.DAG; 6599 6600 EVT VT = N->getValueType(0); 6601 unsigned Opc = N->getOpcode(); 6602 SDValue Op0 = N->getOperand(0); 6603 SDValue Op1 = N->getOperand(1); 6604 6605 // Only do this if the inner op has one use since this will just increases 6606 // register pressure for no benefit. 6607 6608 6609 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 6610 VT != MVT::f64 && 6611 ((VT != MVT::f16 && VT != MVT::i16) || Subtarget->hasMin3Max3_16())) { 6612 // max(max(a, b), c) -> max3(a, b, c) 6613 // min(min(a, b), c) -> min3(a, b, c) 6614 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 6615 SDLoc DL(N); 6616 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 6617 DL, 6618 N->getValueType(0), 6619 Op0.getOperand(0), 6620 Op0.getOperand(1), 6621 Op1); 6622 } 6623 6624 // Try commuted. 6625 // max(a, max(b, c)) -> max3(a, b, c) 6626 // min(a, min(b, c)) -> min3(a, b, c) 6627 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 6628 SDLoc DL(N); 6629 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 6630 DL, 6631 N->getValueType(0), 6632 Op0, 6633 Op1.getOperand(0), 6634 Op1.getOperand(1)); 6635 } 6636 } 6637 6638 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 6639 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 6640 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 6641 return Med3; 6642 } 6643 6644 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 6645 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 6646 return Med3; 6647 } 6648 6649 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 6650 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 6651 (Opc == AMDGPUISD::FMIN_LEGACY && 6652 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 6653 (VT == MVT::f32 || VT == MVT::f64 || 6654 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 6655 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 6656 Op0.hasOneUse()) { 6657 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 6658 return Res; 6659 } 6660 6661 return SDValue(); 6662 } 6663 6664 static bool isClampZeroToOne(SDValue A, SDValue B) { 6665 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 6666 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 6667 // FIXME: Should this be allowing -0.0? 6668 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 6669 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 6670 } 6671 } 6672 6673 return false; 6674 } 6675 6676 // FIXME: Should only worry about snans for version with chain. 6677 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 6678 DAGCombinerInfo &DCI) const { 6679 EVT VT = N->getValueType(0); 6680 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 6681 // NaNs. With a NaN input, the order of the operands may change the result. 6682 6683 SelectionDAG &DAG = DCI.DAG; 6684 SDLoc SL(N); 6685 6686 SDValue Src0 = N->getOperand(0); 6687 SDValue Src1 = N->getOperand(1); 6688 SDValue Src2 = N->getOperand(2); 6689 6690 if (isClampZeroToOne(Src0, Src1)) { 6691 // const_a, const_b, x -> clamp is safe in all cases including signaling 6692 // nans. 6693 // FIXME: Should this be allowing -0.0? 6694 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 6695 } 6696 6697 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 6698 // handling no dx10-clamp? 6699 if (Subtarget->enableDX10Clamp()) { 6700 // If NaNs is clamped to 0, we are free to reorder the inputs. 6701 6702 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 6703 std::swap(Src0, Src1); 6704 6705 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 6706 std::swap(Src1, Src2); 6707 6708 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 6709 std::swap(Src0, Src1); 6710 6711 if (isClampZeroToOne(Src1, Src2)) 6712 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 6713 } 6714 6715 return SDValue(); 6716 } 6717 6718 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 6719 DAGCombinerInfo &DCI) const { 6720 SDValue Src0 = N->getOperand(0); 6721 SDValue Src1 = N->getOperand(1); 6722 if (Src0.isUndef() && Src1.isUndef()) 6723 return DCI.DAG.getUNDEF(N->getValueType(0)); 6724 return SDValue(); 6725 } 6726 6727 SDValue SITargetLowering::performExtractVectorEltCombine( 6728 SDNode *N, DAGCombinerInfo &DCI) const { 6729 SDValue Vec = N->getOperand(0); 6730 6731 SelectionDAG &DAG = DCI.DAG; 6732 if (Vec.getOpcode() == ISD::FNEG && allUsesHaveSourceMods(N)) { 6733 SDLoc SL(N); 6734 EVT EltVT = N->getValueType(0); 6735 SDValue Idx = N->getOperand(1); 6736 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 6737 Vec.getOperand(0), Idx); 6738 return DAG.getNode(ISD::FNEG, SL, EltVT, Elt); 6739 } 6740 6741 return SDValue(); 6742 } 6743 6744 static bool convertBuildVectorCastElt(SelectionDAG &DAG, 6745 SDValue &Lo, SDValue &Hi) { 6746 if (Hi.getOpcode() == ISD::BITCAST && 6747 Hi.getOperand(0).getValueType() == MVT::f16 && 6748 (isa<ConstantSDNode>(Lo) || Lo.isUndef())) { 6749 Lo = DAG.getNode(ISD::BITCAST, SDLoc(Lo), MVT::f16, Lo); 6750 Hi = Hi.getOperand(0); 6751 return true; 6752 } 6753 6754 return false; 6755 } 6756 6757 SDValue SITargetLowering::performBuildVectorCombine( 6758 SDNode *N, DAGCombinerInfo &DCI) const { 6759 SDLoc SL(N); 6760 6761 if (!isTypeLegal(MVT::v2i16)) 6762 return SDValue(); 6763 SelectionDAG &DAG = DCI.DAG; 6764 EVT VT = N->getValueType(0); 6765 6766 if (VT == MVT::v2i16) { 6767 SDValue Lo = N->getOperand(0); 6768 SDValue Hi = N->getOperand(1); 6769 6770 // v2i16 build_vector (const|undef), (bitcast f16:$x) 6771 // -> bitcast (v2f16 build_vector const|undef, $x 6772 if (convertBuildVectorCastElt(DAG, Lo, Hi)) { 6773 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Lo, Hi }); 6774 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec); 6775 } 6776 6777 if (convertBuildVectorCastElt(DAG, Hi, Lo)) { 6778 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Hi, Lo }); 6779 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec); 6780 } 6781 } 6782 6783 return SDValue(); 6784 } 6785 6786 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 6787 const SDNode *N0, 6788 const SDNode *N1) const { 6789 EVT VT = N0->getValueType(0); 6790 6791 // Only do this if we are not trying to support denormals. v_mad_f32 does not 6792 // support denormals ever. 6793 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) || 6794 (VT == MVT::f16 && !Subtarget->hasFP16Denormals())) 6795 return ISD::FMAD; 6796 6797 const TargetOptions &Options = DAG.getTarget().Options; 6798 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 6799 (N0->getFlags().hasUnsafeAlgebra() && 6800 N1->getFlags().hasUnsafeAlgebra())) && 6801 isFMAFasterThanFMulAndFAdd(VT)) { 6802 return ISD::FMA; 6803 } 6804 6805 return 0; 6806 } 6807 6808 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 6809 EVT VT, 6810 SDValue N0, SDValue N1, SDValue N2, 6811 bool Signed) { 6812 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 6813 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 6814 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 6815 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 6816 } 6817 6818 SDValue SITargetLowering::performAddCombine(SDNode *N, 6819 DAGCombinerInfo &DCI) const { 6820 SelectionDAG &DAG = DCI.DAG; 6821 EVT VT = N->getValueType(0); 6822 SDLoc SL(N); 6823 SDValue LHS = N->getOperand(0); 6824 SDValue RHS = N->getOperand(1); 6825 6826 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 6827 && Subtarget->hasMad64_32() && 6828 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 6829 VT.getScalarSizeInBits() <= 64) { 6830 if (LHS.getOpcode() != ISD::MUL) 6831 std::swap(LHS, RHS); 6832 6833 SDValue MulLHS = LHS.getOperand(0); 6834 SDValue MulRHS = LHS.getOperand(1); 6835 SDValue AddRHS = RHS; 6836 6837 // TODO: Maybe restrict if SGPR inputs. 6838 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 6839 numBitsUnsigned(MulRHS, DAG) <= 32) { 6840 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 6841 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 6842 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 6843 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 6844 } 6845 6846 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 6847 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 6848 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 6849 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 6850 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 6851 } 6852 6853 return SDValue(); 6854 } 6855 6856 if (VT != MVT::i32) 6857 return SDValue(); 6858 6859 // add x, zext (setcc) => addcarry x, 0, setcc 6860 // add x, sext (setcc) => subcarry x, 0, setcc 6861 unsigned Opc = LHS.getOpcode(); 6862 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 6863 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 6864 std::swap(RHS, LHS); 6865 6866 Opc = RHS.getOpcode(); 6867 switch (Opc) { 6868 default: break; 6869 case ISD::ZERO_EXTEND: 6870 case ISD::SIGN_EXTEND: 6871 case ISD::ANY_EXTEND: { 6872 auto Cond = RHS.getOperand(0); 6873 if (!isBoolSGPR(Cond)) 6874 break; 6875 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 6876 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 6877 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 6878 return DAG.getNode(Opc, SL, VTList, Args); 6879 } 6880 case ISD::ADDCARRY: { 6881 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 6882 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 6883 if (!C || C->getZExtValue() != 0) break; 6884 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 6885 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 6886 } 6887 } 6888 return SDValue(); 6889 } 6890 6891 SDValue SITargetLowering::performSubCombine(SDNode *N, 6892 DAGCombinerInfo &DCI) const { 6893 SelectionDAG &DAG = DCI.DAG; 6894 EVT VT = N->getValueType(0); 6895 6896 if (VT != MVT::i32) 6897 return SDValue(); 6898 6899 SDLoc SL(N); 6900 SDValue LHS = N->getOperand(0); 6901 SDValue RHS = N->getOperand(1); 6902 6903 unsigned Opc = LHS.getOpcode(); 6904 if (Opc != ISD::SUBCARRY) 6905 std::swap(RHS, LHS); 6906 6907 if (LHS.getOpcode() == ISD::SUBCARRY) { 6908 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 6909 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 6910 if (!C || C->getZExtValue() != 0) 6911 return SDValue(); 6912 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 6913 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 6914 } 6915 return SDValue(); 6916 } 6917 6918 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 6919 DAGCombinerInfo &DCI) const { 6920 6921 if (N->getValueType(0) != MVT::i32) 6922 return SDValue(); 6923 6924 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6925 if (!C || C->getZExtValue() != 0) 6926 return SDValue(); 6927 6928 SelectionDAG &DAG = DCI.DAG; 6929 SDValue LHS = N->getOperand(0); 6930 6931 // addcarry (add x, y), 0, cc => addcarry x, y, cc 6932 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 6933 unsigned LHSOpc = LHS.getOpcode(); 6934 unsigned Opc = N->getOpcode(); 6935 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 6936 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 6937 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 6938 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 6939 } 6940 return SDValue(); 6941 } 6942 6943 SDValue SITargetLowering::performFAddCombine(SDNode *N, 6944 DAGCombinerInfo &DCI) const { 6945 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 6946 return SDValue(); 6947 6948 SelectionDAG &DAG = DCI.DAG; 6949 EVT VT = N->getValueType(0); 6950 6951 SDLoc SL(N); 6952 SDValue LHS = N->getOperand(0); 6953 SDValue RHS = N->getOperand(1); 6954 6955 // These should really be instruction patterns, but writing patterns with 6956 // source modiifiers is a pain. 6957 6958 // fadd (fadd (a, a), b) -> mad 2.0, a, b 6959 if (LHS.getOpcode() == ISD::FADD) { 6960 SDValue A = LHS.getOperand(0); 6961 if (A == LHS.getOperand(1)) { 6962 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 6963 if (FusedOp != 0) { 6964 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 6965 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 6966 } 6967 } 6968 } 6969 6970 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 6971 if (RHS.getOpcode() == ISD::FADD) { 6972 SDValue A = RHS.getOperand(0); 6973 if (A == RHS.getOperand(1)) { 6974 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 6975 if (FusedOp != 0) { 6976 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 6977 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 6978 } 6979 } 6980 } 6981 6982 return SDValue(); 6983 } 6984 6985 SDValue SITargetLowering::performFSubCombine(SDNode *N, 6986 DAGCombinerInfo &DCI) const { 6987 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 6988 return SDValue(); 6989 6990 SelectionDAG &DAG = DCI.DAG; 6991 SDLoc SL(N); 6992 EVT VT = N->getValueType(0); 6993 assert(!VT.isVector()); 6994 6995 // Try to get the fneg to fold into the source modifier. This undoes generic 6996 // DAG combines and folds them into the mad. 6997 // 6998 // Only do this if we are not trying to support denormals. v_mad_f32 does 6999 // not support denormals ever. 7000 SDValue LHS = N->getOperand(0); 7001 SDValue RHS = N->getOperand(1); 7002 if (LHS.getOpcode() == ISD::FADD) { 7003 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 7004 SDValue A = LHS.getOperand(0); 7005 if (A == LHS.getOperand(1)) { 7006 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 7007 if (FusedOp != 0){ 7008 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 7009 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7010 7011 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 7012 } 7013 } 7014 } 7015 7016 if (RHS.getOpcode() == ISD::FADD) { 7017 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 7018 7019 SDValue A = RHS.getOperand(0); 7020 if (A == RHS.getOperand(1)) { 7021 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 7022 if (FusedOp != 0){ 7023 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 7024 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 7025 } 7026 } 7027 } 7028 7029 return SDValue(); 7030 } 7031 7032 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 7033 DAGCombinerInfo &DCI) const { 7034 SelectionDAG &DAG = DCI.DAG; 7035 SDLoc SL(N); 7036 7037 SDValue LHS = N->getOperand(0); 7038 SDValue RHS = N->getOperand(1); 7039 EVT VT = LHS.getValueType(); 7040 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 7041 7042 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 7043 if (!CRHS) { 7044 CRHS = dyn_cast<ConstantSDNode>(LHS); 7045 if (CRHS) { 7046 std::swap(LHS, RHS); 7047 CC = getSetCCSwappedOperands(CC); 7048 } 7049 } 7050 7051 if (CRHS && VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 7052 isBoolSGPR(LHS.getOperand(0))) { 7053 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 7054 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 7055 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 7056 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 7057 if ((CRHS->isAllOnesValue() && 7058 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 7059 (CRHS->isNullValue() && 7060 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 7061 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 7062 DAG.getConstant(-1, SL, MVT::i1)); 7063 if ((CRHS->isAllOnesValue() && 7064 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 7065 (CRHS->isNullValue() && 7066 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 7067 return LHS.getOperand(0); 7068 } 7069 7070 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 7071 VT != MVT::f16)) 7072 return SDValue(); 7073 7074 // Match isinf pattern 7075 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 7076 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) { 7077 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 7078 if (!CRHS) 7079 return SDValue(); 7080 7081 const APFloat &APF = CRHS->getValueAPF(); 7082 if (APF.isInfinity() && !APF.isNegative()) { 7083 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY; 7084 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 7085 DAG.getConstant(Mask, SL, MVT::i32)); 7086 } 7087 } 7088 7089 return SDValue(); 7090 } 7091 7092 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 7093 DAGCombinerInfo &DCI) const { 7094 SelectionDAG &DAG = DCI.DAG; 7095 SDLoc SL(N); 7096 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 7097 7098 SDValue Src = N->getOperand(0); 7099 SDValue Srl = N->getOperand(0); 7100 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 7101 Srl = Srl.getOperand(0); 7102 7103 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 7104 if (Srl.getOpcode() == ISD::SRL) { 7105 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 7106 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 7107 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 7108 7109 if (const ConstantSDNode *C = 7110 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 7111 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 7112 EVT(MVT::i32)); 7113 7114 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 7115 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 7116 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 7117 MVT::f32, Srl); 7118 } 7119 } 7120 } 7121 7122 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 7123 7124 KnownBits Known; 7125 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 7126 !DCI.isBeforeLegalizeOps()); 7127 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7128 if (TLI.ShrinkDemandedConstant(Src, Demanded, TLO) || 7129 TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) { 7130 DCI.CommitTargetLoweringOpt(TLO); 7131 } 7132 7133 return SDValue(); 7134 } 7135 7136 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 7137 DAGCombinerInfo &DCI) const { 7138 switch (N->getOpcode()) { 7139 default: 7140 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 7141 case ISD::ADD: 7142 return performAddCombine(N, DCI); 7143 case ISD::SUB: 7144 return performSubCombine(N, DCI); 7145 case ISD::ADDCARRY: 7146 case ISD::SUBCARRY: 7147 return performAddCarrySubCarryCombine(N, DCI); 7148 case ISD::FADD: 7149 return performFAddCombine(N, DCI); 7150 case ISD::FSUB: 7151 return performFSubCombine(N, DCI); 7152 case ISD::SETCC: 7153 return performSetCCCombine(N, DCI); 7154 case ISD::FMAXNUM: 7155 case ISD::FMINNUM: 7156 case ISD::SMAX: 7157 case ISD::SMIN: 7158 case ISD::UMAX: 7159 case ISD::UMIN: 7160 case AMDGPUISD::FMIN_LEGACY: 7161 case AMDGPUISD::FMAX_LEGACY: { 7162 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG && 7163 getTargetMachine().getOptLevel() > CodeGenOpt::None) 7164 return performMinMaxCombine(N, DCI); 7165 break; 7166 } 7167 case ISD::LOAD: 7168 case ISD::STORE: 7169 case ISD::ATOMIC_LOAD: 7170 case ISD::ATOMIC_STORE: 7171 case ISD::ATOMIC_CMP_SWAP: 7172 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 7173 case ISD::ATOMIC_SWAP: 7174 case ISD::ATOMIC_LOAD_ADD: 7175 case ISD::ATOMIC_LOAD_SUB: 7176 case ISD::ATOMIC_LOAD_AND: 7177 case ISD::ATOMIC_LOAD_OR: 7178 case ISD::ATOMIC_LOAD_XOR: 7179 case ISD::ATOMIC_LOAD_NAND: 7180 case ISD::ATOMIC_LOAD_MIN: 7181 case ISD::ATOMIC_LOAD_MAX: 7182 case ISD::ATOMIC_LOAD_UMIN: 7183 case ISD::ATOMIC_LOAD_UMAX: 7184 case AMDGPUISD::ATOMIC_INC: 7185 case AMDGPUISD::ATOMIC_DEC: 7186 case AMDGPUISD::ATOMIC_LOAD_FADD: 7187 case AMDGPUISD::ATOMIC_LOAD_FMIN: 7188 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 7189 if (DCI.isBeforeLegalize()) 7190 break; 7191 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 7192 case ISD::AND: 7193 return performAndCombine(N, DCI); 7194 case ISD::OR: 7195 return performOrCombine(N, DCI); 7196 case ISD::XOR: 7197 return performXorCombine(N, DCI); 7198 case ISD::ZERO_EXTEND: 7199 return performZeroExtendCombine(N, DCI); 7200 case AMDGPUISD::FP_CLASS: 7201 return performClassCombine(N, DCI); 7202 case ISD::FCANONICALIZE: 7203 return performFCanonicalizeCombine(N, DCI); 7204 case AMDGPUISD::FRACT: 7205 case AMDGPUISD::RCP: 7206 case AMDGPUISD::RSQ: 7207 case AMDGPUISD::RCP_LEGACY: 7208 case AMDGPUISD::RSQ_LEGACY: 7209 case AMDGPUISD::RSQ_CLAMP: 7210 case AMDGPUISD::LDEXP: { 7211 SDValue Src = N->getOperand(0); 7212 if (Src.isUndef()) 7213 return Src; 7214 break; 7215 } 7216 case ISD::SINT_TO_FP: 7217 case ISD::UINT_TO_FP: 7218 return performUCharToFloatCombine(N, DCI); 7219 case AMDGPUISD::CVT_F32_UBYTE0: 7220 case AMDGPUISD::CVT_F32_UBYTE1: 7221 case AMDGPUISD::CVT_F32_UBYTE2: 7222 case AMDGPUISD::CVT_F32_UBYTE3: 7223 return performCvtF32UByteNCombine(N, DCI); 7224 case AMDGPUISD::FMED3: 7225 return performFMed3Combine(N, DCI); 7226 case AMDGPUISD::CVT_PKRTZ_F16_F32: 7227 return performCvtPkRTZCombine(N, DCI); 7228 case ISD::SCALAR_TO_VECTOR: { 7229 SelectionDAG &DAG = DCI.DAG; 7230 EVT VT = N->getValueType(0); 7231 7232 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 7233 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 7234 SDLoc SL(N); 7235 SDValue Src = N->getOperand(0); 7236 EVT EltVT = Src.getValueType(); 7237 if (EltVT == MVT::f16) 7238 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 7239 7240 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 7241 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 7242 } 7243 7244 break; 7245 } 7246 case ISD::EXTRACT_VECTOR_ELT: 7247 return performExtractVectorEltCombine(N, DCI); 7248 case ISD::BUILD_VECTOR: 7249 return performBuildVectorCombine(N, DCI); 7250 } 7251 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 7252 } 7253 7254 /// \brief Helper function for adjustWritemask 7255 static unsigned SubIdx2Lane(unsigned Idx) { 7256 switch (Idx) { 7257 default: return 0; 7258 case AMDGPU::sub0: return 0; 7259 case AMDGPU::sub1: return 1; 7260 case AMDGPU::sub2: return 2; 7261 case AMDGPU::sub3: return 3; 7262 } 7263 } 7264 7265 /// \brief Adjust the writemask of MIMG instructions 7266 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 7267 SelectionDAG &DAG) const { 7268 SDNode *Users[4] = { nullptr }; 7269 unsigned Lane = 0; 7270 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3; 7271 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 7272 unsigned NewDmask = 0; 7273 bool HasChain = Node->getNumValues() > 1; 7274 7275 if (OldDmask == 0) { 7276 // These are folded out, but on the chance it happens don't assert. 7277 return Node; 7278 } 7279 7280 // Try to figure out the used register components 7281 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 7282 I != E; ++I) { 7283 7284 // Don't look at users of the chain. 7285 if (I.getUse().getResNo() != 0) 7286 continue; 7287 7288 // Abort if we can't understand the usage 7289 if (!I->isMachineOpcode() || 7290 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 7291 return Node; 7292 7293 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 7294 // Note that subregs are packed, i.e. Lane==0 is the first bit set 7295 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 7296 // set, etc. 7297 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 7298 7299 // Set which texture component corresponds to the lane. 7300 unsigned Comp; 7301 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) { 7302 Comp = countTrailingZeros(Dmask); 7303 Dmask &= ~(1 << Comp); 7304 } 7305 7306 // Abort if we have more than one user per component 7307 if (Users[Lane]) 7308 return Node; 7309 7310 Users[Lane] = *I; 7311 NewDmask |= 1 << Comp; 7312 } 7313 7314 // Abort if there's no change 7315 if (NewDmask == OldDmask) 7316 return Node; 7317 7318 unsigned BitsSet = countPopulation(NewDmask); 7319 7320 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 7321 int NewOpcode = AMDGPU::getMaskedMIMGOp(*TII, 7322 Node->getMachineOpcode(), BitsSet); 7323 assert(NewOpcode != -1 && 7324 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 7325 "failed to find equivalent MIMG op"); 7326 7327 // Adjust the writemask in the node 7328 SmallVector<SDValue, 12> Ops; 7329 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 7330 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 7331 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 7332 7333 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 7334 7335 MVT ResultVT = BitsSet == 1 ? 7336 SVT : MVT::getVectorVT(SVT, BitsSet == 3 ? 4 : BitsSet); 7337 SDVTList NewVTList = HasChain ? 7338 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 7339 7340 7341 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 7342 NewVTList, Ops); 7343 7344 if (HasChain) { 7345 // Update chain. 7346 NewNode->setMemRefs(Node->memoperands_begin(), Node->memoperands_end()); 7347 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 7348 } 7349 7350 if (BitsSet == 1) { 7351 assert(Node->hasNUsesOfValue(1, 0)); 7352 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 7353 SDLoc(Node), Users[Lane]->getValueType(0), 7354 SDValue(NewNode, 0)); 7355 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 7356 return nullptr; 7357 } 7358 7359 // Update the users of the node with the new indices 7360 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) { 7361 SDNode *User = Users[i]; 7362 if (!User) 7363 continue; 7364 7365 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 7366 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 7367 7368 switch (Idx) { 7369 default: break; 7370 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 7371 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 7372 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 7373 } 7374 } 7375 7376 DAG.RemoveDeadNode(Node); 7377 return nullptr; 7378 } 7379 7380 static bool isFrameIndexOp(SDValue Op) { 7381 if (Op.getOpcode() == ISD::AssertZext) 7382 Op = Op.getOperand(0); 7383 7384 return isa<FrameIndexSDNode>(Op); 7385 } 7386 7387 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG) 7388 /// with frame index operands. 7389 /// LLVM assumes that inputs are to these instructions are registers. 7390 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 7391 SelectionDAG &DAG) const { 7392 if (Node->getOpcode() == ISD::CopyToReg) { 7393 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 7394 SDValue SrcVal = Node->getOperand(2); 7395 7396 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 7397 // to try understanding copies to physical registers. 7398 if (SrcVal.getValueType() == MVT::i1 && 7399 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) { 7400 SDLoc SL(Node); 7401 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 7402 SDValue VReg = DAG.getRegister( 7403 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 7404 7405 SDNode *Glued = Node->getGluedNode(); 7406 SDValue ToVReg 7407 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 7408 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 7409 SDValue ToResultReg 7410 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 7411 VReg, ToVReg.getValue(1)); 7412 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 7413 DAG.RemoveDeadNode(Node); 7414 return ToResultReg.getNode(); 7415 } 7416 } 7417 7418 SmallVector<SDValue, 8> Ops; 7419 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 7420 if (!isFrameIndexOp(Node->getOperand(i))) { 7421 Ops.push_back(Node->getOperand(i)); 7422 continue; 7423 } 7424 7425 SDLoc DL(Node); 7426 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 7427 Node->getOperand(i).getValueType(), 7428 Node->getOperand(i)), 0)); 7429 } 7430 7431 return DAG.UpdateNodeOperands(Node, Ops); 7432 } 7433 7434 /// \brief Fold the instructions after selecting them. 7435 /// Returns null if users were already updated. 7436 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 7437 SelectionDAG &DAG) const { 7438 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 7439 unsigned Opcode = Node->getMachineOpcode(); 7440 7441 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 7442 !TII->isGather4(Opcode) && !TII->isD16(Opcode)) { 7443 return adjustWritemask(Node, DAG); 7444 } 7445 7446 if (Opcode == AMDGPU::INSERT_SUBREG || 7447 Opcode == AMDGPU::REG_SEQUENCE) { 7448 legalizeTargetIndependentNode(Node, DAG); 7449 return Node; 7450 } 7451 7452 switch (Opcode) { 7453 case AMDGPU::V_DIV_SCALE_F32: 7454 case AMDGPU::V_DIV_SCALE_F64: { 7455 // Satisfy the operand register constraint when one of the inputs is 7456 // undefined. Ordinarily each undef value will have its own implicit_def of 7457 // a vreg, so force these to use a single register. 7458 SDValue Src0 = Node->getOperand(0); 7459 SDValue Src1 = Node->getOperand(1); 7460 SDValue Src2 = Node->getOperand(2); 7461 7462 if ((Src0.isMachineOpcode() && 7463 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 7464 (Src0 == Src1 || Src0 == Src2)) 7465 break; 7466 7467 MVT VT = Src0.getValueType().getSimpleVT(); 7468 const TargetRegisterClass *RC = getRegClassFor(VT); 7469 7470 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 7471 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 7472 7473 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 7474 UndefReg, Src0, SDValue()); 7475 7476 // src0 must be the same register as src1 or src2, even if the value is 7477 // undefined, so make sure we don't violate this constraint. 7478 if (Src0.isMachineOpcode() && 7479 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 7480 if (Src1.isMachineOpcode() && 7481 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 7482 Src0 = Src1; 7483 else if (Src2.isMachineOpcode() && 7484 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 7485 Src0 = Src2; 7486 else { 7487 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 7488 Src0 = UndefReg; 7489 Src1 = UndefReg; 7490 } 7491 } else 7492 break; 7493 7494 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 7495 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 7496 Ops.push_back(Node->getOperand(I)); 7497 7498 Ops.push_back(ImpDef.getValue(1)); 7499 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 7500 } 7501 default: 7502 break; 7503 } 7504 7505 return Node; 7506 } 7507 7508 /// \brief Assign the register class depending on the number of 7509 /// bits set in the writemask 7510 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 7511 SDNode *Node) const { 7512 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 7513 7514 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 7515 7516 if (TII->isVOP3(MI.getOpcode())) { 7517 // Make sure constant bus requirements are respected. 7518 TII->legalizeOperandsVOP3(MRI, MI); 7519 return; 7520 } 7521 7522 // Replace unused atomics with the no return version. 7523 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 7524 if (NoRetAtomicOp != -1) { 7525 if (!Node->hasAnyUseOfValue(0)) { 7526 MI.setDesc(TII->get(NoRetAtomicOp)); 7527 MI.RemoveOperand(0); 7528 return; 7529 } 7530 7531 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 7532 // instruction, because the return type of these instructions is a vec2 of 7533 // the memory type, so it can be tied to the input operand. 7534 // This means these instructions always have a use, so we need to add a 7535 // special case to check if the atomic has only one extract_subreg use, 7536 // which itself has no uses. 7537 if ((Node->hasNUsesOfValue(1, 0) && 7538 Node->use_begin()->isMachineOpcode() && 7539 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 7540 !Node->use_begin()->hasAnyUseOfValue(0))) { 7541 unsigned Def = MI.getOperand(0).getReg(); 7542 7543 // Change this into a noret atomic. 7544 MI.setDesc(TII->get(NoRetAtomicOp)); 7545 MI.RemoveOperand(0); 7546 7547 // If we only remove the def operand from the atomic instruction, the 7548 // extract_subreg will be left with a use of a vreg without a def. 7549 // So we need to insert an implicit_def to avoid machine verifier 7550 // errors. 7551 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 7552 TII->get(AMDGPU::IMPLICIT_DEF), Def); 7553 } 7554 return; 7555 } 7556 } 7557 7558 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 7559 uint64_t Val) { 7560 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 7561 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 7562 } 7563 7564 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 7565 const SDLoc &DL, 7566 SDValue Ptr) const { 7567 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 7568 7569 // Build the half of the subregister with the constants before building the 7570 // full 128-bit register. If we are building multiple resource descriptors, 7571 // this will allow CSEing of the 2-component register. 7572 const SDValue Ops0[] = { 7573 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 7574 buildSMovImm32(DAG, DL, 0), 7575 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 7576 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 7577 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 7578 }; 7579 7580 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 7581 MVT::v2i32, Ops0), 0); 7582 7583 // Combine the constants and the pointer. 7584 const SDValue Ops1[] = { 7585 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 7586 Ptr, 7587 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 7588 SubRegHi, 7589 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 7590 }; 7591 7592 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 7593 } 7594 7595 /// \brief Return a resource descriptor with the 'Add TID' bit enabled 7596 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 7597 /// of the resource descriptor) to create an offset, which is added to 7598 /// the resource pointer. 7599 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 7600 SDValue Ptr, uint32_t RsrcDword1, 7601 uint64_t RsrcDword2And3) const { 7602 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 7603 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 7604 if (RsrcDword1) { 7605 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 7606 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 7607 0); 7608 } 7609 7610 SDValue DataLo = buildSMovImm32(DAG, DL, 7611 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 7612 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 7613 7614 const SDValue Ops[] = { 7615 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 7616 PtrLo, 7617 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 7618 PtrHi, 7619 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 7620 DataLo, 7621 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 7622 DataHi, 7623 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 7624 }; 7625 7626 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 7627 } 7628 7629 //===----------------------------------------------------------------------===// 7630 // SI Inline Assembly Support 7631 //===----------------------------------------------------------------------===// 7632 7633 std::pair<unsigned, const TargetRegisterClass *> 7634 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 7635 StringRef Constraint, 7636 MVT VT) const { 7637 if (!isTypeLegal(VT)) 7638 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 7639 7640 if (Constraint.size() == 1) { 7641 switch (Constraint[0]) { 7642 case 's': 7643 case 'r': 7644 switch (VT.getSizeInBits()) { 7645 default: 7646 return std::make_pair(0U, nullptr); 7647 case 32: 7648 case 16: 7649 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass); 7650 case 64: 7651 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass); 7652 case 128: 7653 return std::make_pair(0U, &AMDGPU::SReg_128RegClass); 7654 case 256: 7655 return std::make_pair(0U, &AMDGPU::SReg_256RegClass); 7656 case 512: 7657 return std::make_pair(0U, &AMDGPU::SReg_512RegClass); 7658 } 7659 7660 case 'v': 7661 switch (VT.getSizeInBits()) { 7662 default: 7663 return std::make_pair(0U, nullptr); 7664 case 32: 7665 case 16: 7666 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass); 7667 case 64: 7668 return std::make_pair(0U, &AMDGPU::VReg_64RegClass); 7669 case 96: 7670 return std::make_pair(0U, &AMDGPU::VReg_96RegClass); 7671 case 128: 7672 return std::make_pair(0U, &AMDGPU::VReg_128RegClass); 7673 case 256: 7674 return std::make_pair(0U, &AMDGPU::VReg_256RegClass); 7675 case 512: 7676 return std::make_pair(0U, &AMDGPU::VReg_512RegClass); 7677 } 7678 } 7679 } 7680 7681 if (Constraint.size() > 1) { 7682 const TargetRegisterClass *RC = nullptr; 7683 if (Constraint[1] == 'v') { 7684 RC = &AMDGPU::VGPR_32RegClass; 7685 } else if (Constraint[1] == 's') { 7686 RC = &AMDGPU::SGPR_32RegClass; 7687 } 7688 7689 if (RC) { 7690 uint32_t Idx; 7691 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 7692 if (!Failed && Idx < RC->getNumRegs()) 7693 return std::make_pair(RC->getRegister(Idx), RC); 7694 } 7695 } 7696 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 7697 } 7698 7699 SITargetLowering::ConstraintType 7700 SITargetLowering::getConstraintType(StringRef Constraint) const { 7701 if (Constraint.size() == 1) { 7702 switch (Constraint[0]) { 7703 default: break; 7704 case 's': 7705 case 'v': 7706 return C_RegisterClass; 7707 } 7708 } 7709 return TargetLowering::getConstraintType(Constraint); 7710 } 7711 7712 // Figure out which registers should be reserved for stack access. Only after 7713 // the function is legalized do we know all of the non-spill stack objects or if 7714 // calls are present. 7715 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 7716 MachineRegisterInfo &MRI = MF.getRegInfo(); 7717 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 7718 const MachineFrameInfo &MFI = MF.getFrameInfo(); 7719 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 7720 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 7721 7722 if (Info->isEntryFunction()) { 7723 // Callable functions have fixed registers used for stack access. 7724 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 7725 } 7726 7727 // We have to assume the SP is needed in case there are calls in the function 7728 // during lowering. Calls are only detected after the function is 7729 // lowered. We're about to reserve registers, so don't bother using it if we 7730 // aren't really going to use it. 7731 bool NeedSP = !Info->isEntryFunction() || 7732 MFI.hasVarSizedObjects() || 7733 MFI.hasCalls(); 7734 7735 if (NeedSP) { 7736 unsigned ReservedStackPtrOffsetReg = TRI->reservedStackPtrOffsetReg(MF); 7737 Info->setStackPtrOffsetReg(ReservedStackPtrOffsetReg); 7738 7739 assert(Info->getStackPtrOffsetReg() != Info->getFrameOffsetReg()); 7740 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 7741 Info->getStackPtrOffsetReg())); 7742 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 7743 } 7744 7745 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 7746 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 7747 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG, 7748 Info->getScratchWaveOffsetReg()); 7749 7750 TargetLoweringBase::finalizeLowering(MF); 7751 } 7752 7753 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 7754 KnownBits &Known, 7755 const APInt &DemandedElts, 7756 const SelectionDAG &DAG, 7757 unsigned Depth) const { 7758 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 7759 DAG, Depth); 7760 7761 if (getSubtarget()->enableHugePrivateBuffer()) 7762 return; 7763 7764 // Technically it may be possible to have a dispatch with a single workitem 7765 // that uses the full private memory size, but that's not really useful. We 7766 // can't use vaddr in MUBUF instructions if we don't know the address 7767 // calculation won't overflow, so assume the sign bit is never set. 7768 Known.Zero.setHighBits(AssumeFrameIndexHighZeroBits); 7769 } 7770