1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// Custom DAG lowering for SI 11 // 12 //===----------------------------------------------------------------------===// 13 14 #if defined(_MSC_VER) || defined(__MINGW32__) 15 // Provide M_PI. 16 #define _USE_MATH_DEFINES 17 #endif 18 19 #include "SIISelLowering.h" 20 #include "AMDGPU.h" 21 #include "AMDGPUSubtarget.h" 22 #include "AMDGPUTargetMachine.h" 23 #include "SIDefines.h" 24 #include "SIInstrInfo.h" 25 #include "SIMachineFunctionInfo.h" 26 #include "SIRegisterInfo.h" 27 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 28 #include "Utils/AMDGPUBaseInfo.h" 29 #include "llvm/ADT/APFloat.h" 30 #include "llvm/ADT/APInt.h" 31 #include "llvm/ADT/ArrayRef.h" 32 #include "llvm/ADT/BitVector.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/ADT/Twine.h" 38 #include "llvm/CodeGen/Analysis.h" 39 #include "llvm/CodeGen/CallingConvLower.h" 40 #include "llvm/CodeGen/DAGCombine.h" 41 #include "llvm/CodeGen/ISDOpcodes.h" 42 #include "llvm/CodeGen/MachineBasicBlock.h" 43 #include "llvm/CodeGen/MachineFrameInfo.h" 44 #include "llvm/CodeGen/MachineFunction.h" 45 #include "llvm/CodeGen/MachineInstr.h" 46 #include "llvm/CodeGen/MachineInstrBuilder.h" 47 #include "llvm/CodeGen/MachineMemOperand.h" 48 #include "llvm/CodeGen/MachineModuleInfo.h" 49 #include "llvm/CodeGen/MachineOperand.h" 50 #include "llvm/CodeGen/MachineRegisterInfo.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGNodes.h" 53 #include "llvm/CodeGen/TargetCallingConv.h" 54 #include "llvm/CodeGen/TargetRegisterInfo.h" 55 #include "llvm/CodeGen/ValueTypes.h" 56 #include "llvm/IR/Constants.h" 57 #include "llvm/IR/DataLayout.h" 58 #include "llvm/IR/DebugLoc.h" 59 #include "llvm/IR/DerivedTypes.h" 60 #include "llvm/IR/DiagnosticInfo.h" 61 #include "llvm/IR/Function.h" 62 #include "llvm/IR/GlobalValue.h" 63 #include "llvm/IR/InstrTypes.h" 64 #include "llvm/IR/Instruction.h" 65 #include "llvm/IR/Instructions.h" 66 #include "llvm/IR/IntrinsicInst.h" 67 #include "llvm/IR/Type.h" 68 #include "llvm/Support/Casting.h" 69 #include "llvm/Support/CodeGen.h" 70 #include "llvm/Support/CommandLine.h" 71 #include "llvm/Support/Compiler.h" 72 #include "llvm/Support/ErrorHandling.h" 73 #include "llvm/Support/KnownBits.h" 74 #include "llvm/Support/MachineValueType.h" 75 #include "llvm/Support/MathExtras.h" 76 #include "llvm/Target/TargetOptions.h" 77 #include <cassert> 78 #include <cmath> 79 #include <cstdint> 80 #include <iterator> 81 #include <tuple> 82 #include <utility> 83 #include <vector> 84 85 using namespace llvm; 86 87 #define DEBUG_TYPE "si-lower" 88 89 STATISTIC(NumTailCalls, "Number of tail calls"); 90 91 static cl::opt<bool> EnableVGPRIndexMode( 92 "amdgpu-vgpr-index-mode", 93 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"), 94 cl::init(false)); 95 96 static cl::opt<unsigned> AssumeFrameIndexHighZeroBits( 97 "amdgpu-frame-index-zero-bits", 98 cl::desc("High bits of frame index assumed to be zero"), 99 cl::init(5), 100 cl::ReallyHidden); 101 102 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 103 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 104 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 105 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 106 return AMDGPU::SGPR0 + Reg; 107 } 108 } 109 llvm_unreachable("Cannot allocate sgpr"); 110 } 111 112 SITargetLowering::SITargetLowering(const TargetMachine &TM, 113 const GCNSubtarget &STI) 114 : AMDGPUTargetLowering(TM, STI), 115 Subtarget(&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::v3i32, &AMDGPU::SGPR_96RegClass); 127 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 128 129 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass); 130 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass); 131 132 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass); 133 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 134 135 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 136 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 137 138 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass); 139 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 140 141 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass); 142 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 143 144 if (Subtarget->has16BitInsts()) { 145 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass); 146 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass); 147 148 // Unless there are also VOP3P operations, not operations are really legal. 149 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass); 150 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass); 151 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 152 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 153 } 154 155 computeRegisterProperties(Subtarget->getRegisterInfo()); 156 157 // We need to custom lower vector stores from local memory 158 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 159 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 160 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 161 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 162 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 163 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 164 setOperationAction(ISD::LOAD, MVT::i1, Custom); 165 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 166 167 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 168 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 169 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 170 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 171 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 172 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 173 setOperationAction(ISD::STORE, MVT::i1, Custom); 174 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 175 176 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 177 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 178 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 179 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 180 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 181 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 182 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 183 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 184 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 185 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 186 187 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 188 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 189 190 setOperationAction(ISD::SELECT, MVT::i1, Promote); 191 setOperationAction(ISD::SELECT, MVT::i64, Custom); 192 setOperationAction(ISD::SELECT, MVT::f64, Promote); 193 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 194 195 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 196 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 197 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 198 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 199 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 200 201 setOperationAction(ISD::SETCC, MVT::i1, Promote); 202 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 203 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 204 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 205 206 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 207 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 208 209 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 210 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 211 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 212 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 213 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 215 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 216 217 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 218 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 219 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 220 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 221 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 222 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 223 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 224 225 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 226 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 227 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 228 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 229 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 230 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 231 232 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 233 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 234 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 235 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 236 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 237 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 238 239 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 240 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 241 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 242 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 243 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 244 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 245 246 setOperationAction(ISD::UADDO, MVT::i32, Legal); 247 setOperationAction(ISD::USUBO, MVT::i32, Legal); 248 249 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 250 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 251 252 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 253 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 254 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 255 256 #if 0 257 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 258 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 259 #endif 260 261 // We only support LOAD/STORE and vector manipulation ops for vectors 262 // with > 4 elements. 263 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 264 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, MVT::v32i32 }) { 265 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 266 switch (Op) { 267 case ISD::LOAD: 268 case ISD::STORE: 269 case ISD::BUILD_VECTOR: 270 case ISD::BITCAST: 271 case ISD::EXTRACT_VECTOR_ELT: 272 case ISD::INSERT_VECTOR_ELT: 273 case ISD::INSERT_SUBVECTOR: 274 case ISD::EXTRACT_SUBVECTOR: 275 case ISD::SCALAR_TO_VECTOR: 276 break; 277 case ISD::CONCAT_VECTORS: 278 setOperationAction(Op, VT, Custom); 279 break; 280 default: 281 setOperationAction(Op, VT, Expand); 282 break; 283 } 284 } 285 } 286 287 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 288 289 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 290 // is expanded to avoid having two separate loops in case the index is a VGPR. 291 292 // Most operations are naturally 32-bit vector operations. We only support 293 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 294 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 295 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 296 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 297 298 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 299 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 300 301 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 302 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 303 304 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 305 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 306 } 307 308 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 309 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 310 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 311 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 312 313 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 314 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 315 316 // Avoid stack access for these. 317 // TODO: Generalize to more vector types. 318 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 319 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 320 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 321 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 322 323 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 324 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 325 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 326 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 327 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 328 329 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 330 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 331 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 332 333 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 334 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 335 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 336 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 337 338 // Deal with vec3 vector operations when widened to vec4. 339 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Expand); 340 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Expand); 341 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Expand); 342 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Expand); 343 344 // Deal with vec5 vector operations when widened to vec8. 345 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Expand); 346 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Expand); 347 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Expand); 348 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Expand); 349 350 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 351 // and output demarshalling 352 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 353 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 354 355 // We can't return success/failure, only the old value, 356 // let LLVM add the comparison 357 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 358 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 359 360 if (Subtarget->hasFlatAddressSpace()) { 361 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 362 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 363 } 364 365 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 366 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 367 368 // On SI this is s_memtime and s_memrealtime on VI. 369 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 370 setOperationAction(ISD::TRAP, MVT::Other, Custom); 371 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 372 373 if (Subtarget->has16BitInsts()) { 374 setOperationAction(ISD::FLOG, MVT::f16, Custom); 375 setOperationAction(ISD::FEXP, MVT::f16, Custom); 376 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 377 } 378 379 // v_mad_f32 does not support denormals according to some sources. 380 if (!Subtarget->hasFP32Denormals()) 381 setOperationAction(ISD::FMAD, MVT::f32, Legal); 382 383 if (!Subtarget->hasBFI()) { 384 // fcopysign can be done in a single instruction with BFI. 385 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 386 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 387 } 388 389 if (!Subtarget->hasBCNT(32)) 390 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 391 392 if (!Subtarget->hasBCNT(64)) 393 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 394 395 if (Subtarget->hasFFBH()) 396 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 397 398 if (Subtarget->hasFFBL()) 399 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 400 401 // We only really have 32-bit BFE instructions (and 16-bit on VI). 402 // 403 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 404 // effort to match them now. We want this to be false for i64 cases when the 405 // extraction isn't restricted to the upper or lower half. Ideally we would 406 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 407 // span the midpoint are probably relatively rare, so don't worry about them 408 // for now. 409 if (Subtarget->hasBFE()) 410 setHasExtractBitsInsn(true); 411 412 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 413 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 414 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 415 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 416 417 418 // These are really only legal for ieee_mode functions. We should be avoiding 419 // them for functions that don't have ieee_mode enabled, so just say they are 420 // legal. 421 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 422 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 423 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 424 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 425 426 427 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) { 428 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 429 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 430 setOperationAction(ISD::FRINT, MVT::f64, Legal); 431 } else { 432 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 433 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 434 setOperationAction(ISD::FRINT, MVT::f64, Custom); 435 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 436 } 437 438 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 439 440 setOperationAction(ISD::FSIN, MVT::f32, Custom); 441 setOperationAction(ISD::FCOS, MVT::f32, Custom); 442 setOperationAction(ISD::FDIV, MVT::f32, Custom); 443 setOperationAction(ISD::FDIV, MVT::f64, Custom); 444 445 if (Subtarget->has16BitInsts()) { 446 setOperationAction(ISD::Constant, MVT::i16, Legal); 447 448 setOperationAction(ISD::SMIN, MVT::i16, Legal); 449 setOperationAction(ISD::SMAX, MVT::i16, Legal); 450 451 setOperationAction(ISD::UMIN, MVT::i16, Legal); 452 setOperationAction(ISD::UMAX, MVT::i16, Legal); 453 454 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 455 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 456 457 setOperationAction(ISD::ROTR, MVT::i16, Promote); 458 setOperationAction(ISD::ROTL, MVT::i16, Promote); 459 460 setOperationAction(ISD::SDIV, MVT::i16, Promote); 461 setOperationAction(ISD::UDIV, MVT::i16, Promote); 462 setOperationAction(ISD::SREM, MVT::i16, Promote); 463 setOperationAction(ISD::UREM, MVT::i16, Promote); 464 465 setOperationAction(ISD::BSWAP, MVT::i16, Promote); 466 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 467 468 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 469 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 470 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 471 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 472 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 473 474 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 475 476 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 477 478 setOperationAction(ISD::LOAD, MVT::i16, Custom); 479 480 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 481 482 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 483 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 484 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 485 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 486 487 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 488 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 489 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote); 490 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote); 491 492 // F16 - Constant Actions. 493 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 494 495 // F16 - Load/Store Actions. 496 setOperationAction(ISD::LOAD, MVT::f16, Promote); 497 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 498 setOperationAction(ISD::STORE, MVT::f16, Promote); 499 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 500 501 // F16 - VOP1 Actions. 502 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 503 setOperationAction(ISD::FCOS, MVT::f16, Promote); 504 setOperationAction(ISD::FSIN, MVT::f16, Promote); 505 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 506 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 507 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 508 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 509 setOperationAction(ISD::FROUND, MVT::f16, Custom); 510 511 // F16 - VOP2 Actions. 512 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 513 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 514 515 setOperationAction(ISD::FDIV, MVT::f16, Custom); 516 517 // F16 - VOP3 Actions. 518 setOperationAction(ISD::FMA, MVT::f16, Legal); 519 if (!Subtarget->hasFP16Denormals()) 520 setOperationAction(ISD::FMAD, MVT::f16, Legal); 521 522 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 523 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 524 switch (Op) { 525 case ISD::LOAD: 526 case ISD::STORE: 527 case ISD::BUILD_VECTOR: 528 case ISD::BITCAST: 529 case ISD::EXTRACT_VECTOR_ELT: 530 case ISD::INSERT_VECTOR_ELT: 531 case ISD::INSERT_SUBVECTOR: 532 case ISD::EXTRACT_SUBVECTOR: 533 case ISD::SCALAR_TO_VECTOR: 534 break; 535 case ISD::CONCAT_VECTORS: 536 setOperationAction(Op, VT, Custom); 537 break; 538 default: 539 setOperationAction(Op, VT, Expand); 540 break; 541 } 542 } 543 } 544 545 // XXX - Do these do anything? Vector constants turn into build_vector. 546 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 547 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 548 549 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 550 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 551 552 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 553 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 554 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 555 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 556 557 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 558 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 559 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 560 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 561 562 setOperationAction(ISD::AND, MVT::v2i16, Promote); 563 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 564 setOperationAction(ISD::OR, MVT::v2i16, Promote); 565 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 566 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 567 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 568 569 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 570 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 571 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 572 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 573 574 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 575 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 576 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 577 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 578 579 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 580 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 581 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 582 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 583 584 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 585 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 586 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 587 588 if (!Subtarget->hasVOP3PInsts()) { 589 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 590 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 591 } 592 593 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 594 // This isn't really legal, but this avoids the legalizer unrolling it (and 595 // allows matching fneg (fabs x) patterns) 596 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 597 598 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 599 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 600 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 601 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 602 603 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 604 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 605 606 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 607 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 608 } 609 610 if (Subtarget->hasVOP3PInsts()) { 611 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 612 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 613 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 614 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 615 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 616 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 617 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 618 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 619 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 620 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 621 622 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 623 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 624 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 625 626 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 627 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 628 629 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 630 631 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 632 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 633 634 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 635 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 636 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 637 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 638 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 639 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 640 641 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 642 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 643 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 644 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 645 646 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 647 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 648 649 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 650 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 651 652 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 653 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 654 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 655 656 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 657 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 658 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 659 } 660 661 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 662 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 663 664 if (Subtarget->has16BitInsts()) { 665 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 666 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 667 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 668 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 669 } else { 670 // Legalization hack. 671 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 672 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 673 674 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 675 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 676 } 677 678 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 679 setOperationAction(ISD::SELECT, VT, Custom); 680 } 681 682 setTargetDAGCombine(ISD::ADD); 683 setTargetDAGCombine(ISD::ADDCARRY); 684 setTargetDAGCombine(ISD::SUB); 685 setTargetDAGCombine(ISD::SUBCARRY); 686 setTargetDAGCombine(ISD::FADD); 687 setTargetDAGCombine(ISD::FSUB); 688 setTargetDAGCombine(ISD::FMINNUM); 689 setTargetDAGCombine(ISD::FMAXNUM); 690 setTargetDAGCombine(ISD::FMINNUM_IEEE); 691 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 692 setTargetDAGCombine(ISD::FMA); 693 setTargetDAGCombine(ISD::SMIN); 694 setTargetDAGCombine(ISD::SMAX); 695 setTargetDAGCombine(ISD::UMIN); 696 setTargetDAGCombine(ISD::UMAX); 697 setTargetDAGCombine(ISD::SETCC); 698 setTargetDAGCombine(ISD::AND); 699 setTargetDAGCombine(ISD::OR); 700 setTargetDAGCombine(ISD::XOR); 701 setTargetDAGCombine(ISD::SINT_TO_FP); 702 setTargetDAGCombine(ISD::UINT_TO_FP); 703 setTargetDAGCombine(ISD::FCANONICALIZE); 704 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 705 setTargetDAGCombine(ISD::ZERO_EXTEND); 706 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 707 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 708 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 709 710 // All memory operations. Some folding on the pointer operand is done to help 711 // matching the constant offsets in the addressing modes. 712 setTargetDAGCombine(ISD::LOAD); 713 setTargetDAGCombine(ISD::STORE); 714 setTargetDAGCombine(ISD::ATOMIC_LOAD); 715 setTargetDAGCombine(ISD::ATOMIC_STORE); 716 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 717 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 718 setTargetDAGCombine(ISD::ATOMIC_SWAP); 719 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 720 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 721 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 722 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 723 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 724 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 725 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 726 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 727 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 728 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 729 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 730 731 setSchedulingPreference(Sched::RegPressure); 732 733 // SI at least has hardware support for floating point exceptions, but no way 734 // of using or handling them is implemented. They are also optional in OpenCL 735 // (Section 7.3) 736 setHasFloatingPointExceptions(Subtarget->hasFPExceptions()); 737 } 738 739 const GCNSubtarget *SITargetLowering::getSubtarget() const { 740 return Subtarget; 741 } 742 743 //===----------------------------------------------------------------------===// 744 // TargetLowering queries 745 //===----------------------------------------------------------------------===// 746 747 // v_mad_mix* support a conversion from f16 to f32. 748 // 749 // There is only one special case when denormals are enabled we don't currently, 750 // where this is OK to use. 751 bool SITargetLowering::isFPExtFoldable(unsigned Opcode, 752 EVT DestVT, EVT SrcVT) const { 753 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 754 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 755 DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() && 756 SrcVT.getScalarType() == MVT::f16; 757 } 758 759 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 760 // SI has some legal vector types, but no legal vector operations. Say no 761 // shuffles are legal in order to prefer scalarizing some vector operations. 762 return false; 763 } 764 765 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 766 CallingConv::ID CC, 767 EVT VT) const { 768 // TODO: Consider splitting all arguments into 32-bit pieces. 769 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 770 EVT ScalarVT = VT.getScalarType(); 771 unsigned Size = ScalarVT.getSizeInBits(); 772 if (Size == 32) 773 return ScalarVT.getSimpleVT(); 774 775 if (Size == 64) 776 return MVT::i32; 777 778 if (Size == 16 && Subtarget->has16BitInsts()) 779 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 780 } 781 782 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 783 } 784 785 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 786 CallingConv::ID CC, 787 EVT VT) const { 788 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 789 unsigned NumElts = VT.getVectorNumElements(); 790 EVT ScalarVT = VT.getScalarType(); 791 unsigned Size = ScalarVT.getSizeInBits(); 792 793 if (Size == 32) 794 return NumElts; 795 796 if (Size == 64) 797 return 2 * NumElts; 798 799 if (Size == 16 && Subtarget->has16BitInsts()) 800 return (VT.getVectorNumElements() + 1) / 2; 801 } 802 803 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 804 } 805 806 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 807 LLVMContext &Context, CallingConv::ID CC, 808 EVT VT, EVT &IntermediateVT, 809 unsigned &NumIntermediates, MVT &RegisterVT) const { 810 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 811 unsigned NumElts = VT.getVectorNumElements(); 812 EVT ScalarVT = VT.getScalarType(); 813 unsigned Size = ScalarVT.getSizeInBits(); 814 if (Size == 32) { 815 RegisterVT = ScalarVT.getSimpleVT(); 816 IntermediateVT = RegisterVT; 817 NumIntermediates = NumElts; 818 return NumIntermediates; 819 } 820 821 if (Size == 64) { 822 RegisterVT = MVT::i32; 823 IntermediateVT = RegisterVT; 824 NumIntermediates = 2 * NumElts; 825 return NumIntermediates; 826 } 827 828 // FIXME: We should fix the ABI to be the same on targets without 16-bit 829 // support, but unless we can properly handle 3-vectors, it will be still be 830 // inconsistent. 831 if (Size == 16 && Subtarget->has16BitInsts()) { 832 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 833 IntermediateVT = RegisterVT; 834 NumIntermediates = (NumElts + 1) / 2; 835 return NumIntermediates; 836 } 837 } 838 839 return TargetLowering::getVectorTypeBreakdownForCallingConv( 840 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 841 } 842 843 static MVT memVTFromAggregate(Type *Ty) { 844 // Only limited forms of aggregate type currently expected. 845 assert(Ty->isStructTy() && "Expected struct type"); 846 847 848 Type *ElementType = nullptr; 849 unsigned NumElts; 850 if (Ty->getContainedType(0)->isVectorTy()) { 851 VectorType *VecComponent = cast<VectorType>(Ty->getContainedType(0)); 852 ElementType = VecComponent->getElementType(); 853 NumElts = VecComponent->getNumElements(); 854 } else { 855 ElementType = Ty->getContainedType(0); 856 NumElts = 1; 857 } 858 859 assert((Ty->getContainedType(1) && Ty->getContainedType(1)->isIntegerTy(32)) && "Expected int32 type"); 860 861 // Calculate the size of the memVT type from the aggregate 862 unsigned Pow2Elts = 0; 863 unsigned ElementSize; 864 switch (ElementType->getTypeID()) { 865 default: 866 llvm_unreachable("Unknown type!"); 867 case Type::IntegerTyID: 868 ElementSize = cast<IntegerType>(ElementType)->getBitWidth(); 869 break; 870 case Type::HalfTyID: 871 ElementSize = 16; 872 break; 873 case Type::FloatTyID: 874 ElementSize = 32; 875 break; 876 } 877 unsigned AdditionalElts = ElementSize == 16 ? 2 : 1; 878 Pow2Elts = 1 << Log2_32_Ceil(NumElts + AdditionalElts); 879 880 return MVT::getVectorVT(MVT::getVT(ElementType, false), 881 Pow2Elts); 882 } 883 884 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 885 const CallInst &CI, 886 MachineFunction &MF, 887 unsigned IntrID) const { 888 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 889 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 890 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 891 (Intrinsic::ID)IntrID); 892 if (Attr.hasFnAttribute(Attribute::ReadNone)) 893 return false; 894 895 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 896 897 if (RsrcIntr->IsImage) { 898 Info.ptrVal = MFI->getImagePSV( 899 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 900 CI.getArgOperand(RsrcIntr->RsrcArg)); 901 Info.align = 0; 902 } else { 903 Info.ptrVal = MFI->getBufferPSV( 904 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 905 CI.getArgOperand(RsrcIntr->RsrcArg)); 906 } 907 908 Info.flags = MachineMemOperand::MODereferenceable; 909 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 910 Info.opc = ISD::INTRINSIC_W_CHAIN; 911 Info.memVT = MVT::getVT(CI.getType(), true); 912 if (Info.memVT == MVT::Other) { 913 // Some intrinsics return an aggregate type - special case to work out 914 // the correct memVT 915 Info.memVT = memVTFromAggregate(CI.getType()); 916 } 917 Info.flags |= MachineMemOperand::MOLoad; 918 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 919 Info.opc = ISD::INTRINSIC_VOID; 920 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 921 Info.flags |= MachineMemOperand::MOStore; 922 } else { 923 // Atomic 924 Info.opc = ISD::INTRINSIC_W_CHAIN; 925 Info.memVT = MVT::getVT(CI.getType()); 926 Info.flags = MachineMemOperand::MOLoad | 927 MachineMemOperand::MOStore | 928 MachineMemOperand::MODereferenceable; 929 930 // XXX - Should this be volatile without known ordering? 931 Info.flags |= MachineMemOperand::MOVolatile; 932 } 933 return true; 934 } 935 936 switch (IntrID) { 937 case Intrinsic::amdgcn_atomic_inc: 938 case Intrinsic::amdgcn_atomic_dec: 939 case Intrinsic::amdgcn_ds_ordered_add: 940 case Intrinsic::amdgcn_ds_ordered_swap: 941 case Intrinsic::amdgcn_ds_fadd: 942 case Intrinsic::amdgcn_ds_fmin: 943 case Intrinsic::amdgcn_ds_fmax: { 944 Info.opc = ISD::INTRINSIC_W_CHAIN; 945 Info.memVT = MVT::getVT(CI.getType()); 946 Info.ptrVal = CI.getOperand(0); 947 Info.align = 0; 948 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 949 950 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 951 if (!Vol->isZero()) 952 Info.flags |= MachineMemOperand::MOVolatile; 953 954 return true; 955 } 956 case Intrinsic::amdgcn_ds_append: 957 case Intrinsic::amdgcn_ds_consume: { 958 Info.opc = ISD::INTRINSIC_W_CHAIN; 959 Info.memVT = MVT::getVT(CI.getType()); 960 Info.ptrVal = CI.getOperand(0); 961 Info.align = 0; 962 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 963 964 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 965 if (!Vol->isZero()) 966 Info.flags |= MachineMemOperand::MOVolatile; 967 968 return true; 969 } 970 default: 971 return false; 972 } 973 } 974 975 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 976 SmallVectorImpl<Value*> &Ops, 977 Type *&AccessTy) const { 978 switch (II->getIntrinsicID()) { 979 case Intrinsic::amdgcn_atomic_inc: 980 case Intrinsic::amdgcn_atomic_dec: 981 case Intrinsic::amdgcn_ds_ordered_add: 982 case Intrinsic::amdgcn_ds_ordered_swap: 983 case Intrinsic::amdgcn_ds_fadd: 984 case Intrinsic::amdgcn_ds_fmin: 985 case Intrinsic::amdgcn_ds_fmax: { 986 Value *Ptr = II->getArgOperand(0); 987 AccessTy = II->getType(); 988 Ops.push_back(Ptr); 989 return true; 990 } 991 default: 992 return false; 993 } 994 } 995 996 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 997 if (!Subtarget->hasFlatInstOffsets()) { 998 // Flat instructions do not have offsets, and only have the register 999 // address. 1000 return AM.BaseOffs == 0 && AM.Scale == 0; 1001 } 1002 1003 // GFX9 added a 13-bit signed offset. When using regular flat instructions, 1004 // the sign bit is ignored and is treated as a 12-bit unsigned offset. 1005 1006 // Just r + i 1007 return isUInt<12>(AM.BaseOffs) && AM.Scale == 0; 1008 } 1009 1010 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1011 if (Subtarget->hasFlatGlobalInsts()) 1012 return isInt<13>(AM.BaseOffs) && AM.Scale == 0; 1013 1014 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1015 // Assume the we will use FLAT for all global memory accesses 1016 // on VI. 1017 // FIXME: This assumption is currently wrong. On VI we still use 1018 // MUBUF instructions for the r + i addressing mode. As currently 1019 // implemented, the MUBUF instructions only work on buffer < 4GB. 1020 // It may be possible to support > 4GB buffers with MUBUF instructions, 1021 // by setting the stride value in the resource descriptor which would 1022 // increase the size limit to (stride * 4GB). However, this is risky, 1023 // because it has never been validated. 1024 return isLegalFlatAddressingMode(AM); 1025 } 1026 1027 return isLegalMUBUFAddressingMode(AM); 1028 } 1029 1030 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1031 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1032 // additionally can do r + r + i with addr64. 32-bit has more addressing 1033 // mode options. Depending on the resource constant, it can also do 1034 // (i64 r0) + (i32 r1) * (i14 i). 1035 // 1036 // Private arrays end up using a scratch buffer most of the time, so also 1037 // assume those use MUBUF instructions. Scratch loads / stores are currently 1038 // implemented as mubuf instructions with offen bit set, so slightly 1039 // different than the normal addr64. 1040 if (!isUInt<12>(AM.BaseOffs)) 1041 return false; 1042 1043 // FIXME: Since we can split immediate into soffset and immediate offset, 1044 // would it make sense to allow any immediate? 1045 1046 switch (AM.Scale) { 1047 case 0: // r + i or just i, depending on HasBaseReg. 1048 return true; 1049 case 1: 1050 return true; // We have r + r or r + i. 1051 case 2: 1052 if (AM.HasBaseReg) { 1053 // Reject 2 * r + r. 1054 return false; 1055 } 1056 1057 // Allow 2 * r as r + r 1058 // Or 2 * r + i is allowed as r + r + i. 1059 return true; 1060 default: // Don't allow n * r 1061 return false; 1062 } 1063 } 1064 1065 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1066 const AddrMode &AM, Type *Ty, 1067 unsigned AS, Instruction *I) const { 1068 // No global is ever allowed as a base. 1069 if (AM.BaseGV) 1070 return false; 1071 1072 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1073 return isLegalGlobalAddressingMode(AM); 1074 1075 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1076 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1077 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1078 // If the offset isn't a multiple of 4, it probably isn't going to be 1079 // correctly aligned. 1080 // FIXME: Can we get the real alignment here? 1081 if (AM.BaseOffs % 4 != 0) 1082 return isLegalMUBUFAddressingMode(AM); 1083 1084 // There are no SMRD extloads, so if we have to do a small type access we 1085 // will use a MUBUF load. 1086 // FIXME?: We also need to do this if unaligned, but we don't know the 1087 // alignment here. 1088 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1089 return isLegalGlobalAddressingMode(AM); 1090 1091 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1092 // SMRD instructions have an 8-bit, dword offset on SI. 1093 if (!isUInt<8>(AM.BaseOffs / 4)) 1094 return false; 1095 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1096 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1097 // in 8-bits, it can use a smaller encoding. 1098 if (!isUInt<32>(AM.BaseOffs / 4)) 1099 return false; 1100 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1101 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1102 if (!isUInt<20>(AM.BaseOffs)) 1103 return false; 1104 } else 1105 llvm_unreachable("unhandled generation"); 1106 1107 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1108 return true; 1109 1110 if (AM.Scale == 1 && AM.HasBaseReg) 1111 return true; 1112 1113 return false; 1114 1115 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1116 return isLegalMUBUFAddressingMode(AM); 1117 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1118 AS == AMDGPUAS::REGION_ADDRESS) { 1119 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1120 // field. 1121 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1122 // an 8-bit dword offset but we don't know the alignment here. 1123 if (!isUInt<16>(AM.BaseOffs)) 1124 return false; 1125 1126 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1127 return true; 1128 1129 if (AM.Scale == 1 && AM.HasBaseReg) 1130 return true; 1131 1132 return false; 1133 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1134 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1135 // For an unknown address space, this usually means that this is for some 1136 // reason being used for pure arithmetic, and not based on some addressing 1137 // computation. We don't have instructions that compute pointers with any 1138 // addressing modes, so treat them as having no offset like flat 1139 // instructions. 1140 return isLegalFlatAddressingMode(AM); 1141 } else { 1142 llvm_unreachable("unhandled address space"); 1143 } 1144 } 1145 1146 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1147 const SelectionDAG &DAG) const { 1148 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1149 return (MemVT.getSizeInBits() <= 4 * 32); 1150 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1151 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1152 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1153 } else if (AS == AMDGPUAS::LOCAL_ADDRESS) { 1154 return (MemVT.getSizeInBits() <= 2 * 32); 1155 } 1156 return true; 1157 } 1158 1159 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 1160 unsigned AddrSpace, 1161 unsigned Align, 1162 bool *IsFast) const { 1163 if (IsFast) 1164 *IsFast = false; 1165 1166 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1167 // which isn't a simple VT. 1168 // Until MVT is extended to handle this, simply check for the size and 1169 // rely on the condition below: allow accesses if the size is a multiple of 4. 1170 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1171 VT.getStoreSize() > 16)) { 1172 return false; 1173 } 1174 1175 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1176 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1177 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1178 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1179 // with adjacent offsets. 1180 bool AlignedBy4 = (Align % 4 == 0); 1181 if (IsFast) 1182 *IsFast = AlignedBy4; 1183 1184 return AlignedBy4; 1185 } 1186 1187 // FIXME: We have to be conservative here and assume that flat operations 1188 // will access scratch. If we had access to the IR function, then we 1189 // could determine if any private memory was used in the function. 1190 if (!Subtarget->hasUnalignedScratchAccess() && 1191 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1192 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1193 bool AlignedBy4 = Align >= 4; 1194 if (IsFast) 1195 *IsFast = AlignedBy4; 1196 1197 return AlignedBy4; 1198 } 1199 1200 if (Subtarget->hasUnalignedBufferAccess()) { 1201 // If we have an uniform constant load, it still requires using a slow 1202 // buffer instruction if unaligned. 1203 if (IsFast) { 1204 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1205 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1206 (Align % 4 == 0) : true; 1207 } 1208 1209 return true; 1210 } 1211 1212 // Smaller than dword value must be aligned. 1213 if (VT.bitsLT(MVT::i32)) 1214 return false; 1215 1216 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1217 // byte-address are ignored, thus forcing Dword alignment. 1218 // This applies to private, global, and constant memory. 1219 if (IsFast) 1220 *IsFast = true; 1221 1222 return VT.bitsGT(MVT::i32) && Align % 4 == 0; 1223 } 1224 1225 EVT SITargetLowering::getOptimalMemOpType( 1226 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 1227 bool ZeroMemset, bool MemcpyStrSrc, 1228 const AttributeList &FuncAttributes) const { 1229 // FIXME: Should account for address space here. 1230 1231 // The default fallback uses the private pointer size as a guess for a type to 1232 // use. Make sure we switch these to 64-bit accesses. 1233 1234 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global 1235 return MVT::v4i32; 1236 1237 if (Size >= 8 && DstAlign >= 4) 1238 return MVT::v2i32; 1239 1240 // Use the default. 1241 return MVT::Other; 1242 } 1243 1244 static bool isFlatGlobalAddrSpace(unsigned AS) { 1245 return AS == AMDGPUAS::GLOBAL_ADDRESS || 1246 AS == AMDGPUAS::FLAT_ADDRESS || 1247 AS == AMDGPUAS::CONSTANT_ADDRESS || 1248 AS > AMDGPUAS::MAX_AMDGPU_ADDRESS; 1249 } 1250 1251 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1252 unsigned DestAS) const { 1253 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1254 } 1255 1256 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1257 const MemSDNode *MemNode = cast<MemSDNode>(N); 1258 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1259 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1260 return I && I->getMetadata("amdgpu.noclobber"); 1261 } 1262 1263 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS, 1264 unsigned DestAS) const { 1265 // Flat -> private/local is a simple truncate. 1266 // Flat -> global is no-op 1267 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1268 return true; 1269 1270 return isNoopAddrSpaceCast(SrcAS, DestAS); 1271 } 1272 1273 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1274 const MemSDNode *MemNode = cast<MemSDNode>(N); 1275 1276 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1277 } 1278 1279 TargetLoweringBase::LegalizeTypeAction 1280 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1281 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1282 return TypeSplitVector; 1283 1284 return TargetLoweringBase::getPreferredVectorAction(VT); 1285 } 1286 1287 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1288 Type *Ty) const { 1289 // FIXME: Could be smarter if called for vector constants. 1290 return true; 1291 } 1292 1293 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1294 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1295 switch (Op) { 1296 case ISD::LOAD: 1297 case ISD::STORE: 1298 1299 // These operations are done with 32-bit instructions anyway. 1300 case ISD::AND: 1301 case ISD::OR: 1302 case ISD::XOR: 1303 case ISD::SELECT: 1304 // TODO: Extensions? 1305 return true; 1306 default: 1307 return false; 1308 } 1309 } 1310 1311 // SimplifySetCC uses this function to determine whether or not it should 1312 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1313 if (VT == MVT::i1 && Op == ISD::SETCC) 1314 return false; 1315 1316 return TargetLowering::isTypeDesirableForOp(Op, VT); 1317 } 1318 1319 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1320 const SDLoc &SL, 1321 SDValue Chain, 1322 uint64_t Offset) const { 1323 const DataLayout &DL = DAG.getDataLayout(); 1324 MachineFunction &MF = DAG.getMachineFunction(); 1325 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1326 1327 const ArgDescriptor *InputPtrReg; 1328 const TargetRegisterClass *RC; 1329 1330 std::tie(InputPtrReg, RC) 1331 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1332 1333 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1334 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1335 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1336 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1337 1338 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1339 } 1340 1341 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1342 const SDLoc &SL) const { 1343 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1344 FIRST_IMPLICIT); 1345 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1346 } 1347 1348 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1349 const SDLoc &SL, SDValue Val, 1350 bool Signed, 1351 const ISD::InputArg *Arg) const { 1352 // First, if it is a widened vector, narrow it. 1353 if (VT.isVector() && 1354 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1355 EVT NarrowedVT = 1356 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1357 VT.getVectorNumElements()); 1358 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1359 DAG.getConstant(0, SL, MVT::i32)); 1360 } 1361 1362 // Then convert the vector elements or scalar value. 1363 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1364 VT.bitsLT(MemVT)) { 1365 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1366 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1367 } 1368 1369 if (MemVT.isFloatingPoint()) 1370 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT); 1371 else if (Signed) 1372 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1373 else 1374 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1375 1376 return Val; 1377 } 1378 1379 SDValue SITargetLowering::lowerKernargMemParameter( 1380 SelectionDAG &DAG, EVT VT, EVT MemVT, 1381 const SDLoc &SL, SDValue Chain, 1382 uint64_t Offset, unsigned Align, bool Signed, 1383 const ISD::InputArg *Arg) const { 1384 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 1385 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 1386 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 1387 1388 // Try to avoid using an extload by loading earlier than the argument address, 1389 // and extracting the relevant bits. The load should hopefully be merged with 1390 // the previous argument. 1391 if (MemVT.getStoreSize() < 4 && Align < 4) { 1392 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1393 int64_t AlignDownOffset = alignDown(Offset, 4); 1394 int64_t OffsetDiff = Offset - AlignDownOffset; 1395 1396 EVT IntVT = MemVT.changeTypeToInteger(); 1397 1398 // TODO: If we passed in the base kernel offset we could have a better 1399 // alignment than 4, but we don't really need it. 1400 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1401 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1402 MachineMemOperand::MODereferenceable | 1403 MachineMemOperand::MOInvariant); 1404 1405 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1406 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1407 1408 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1409 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1410 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1411 1412 1413 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1414 } 1415 1416 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1417 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1418 MachineMemOperand::MODereferenceable | 1419 MachineMemOperand::MOInvariant); 1420 1421 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1422 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1423 } 1424 1425 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1426 const SDLoc &SL, SDValue Chain, 1427 const ISD::InputArg &Arg) const { 1428 MachineFunction &MF = DAG.getMachineFunction(); 1429 MachineFrameInfo &MFI = MF.getFrameInfo(); 1430 1431 if (Arg.Flags.isByVal()) { 1432 unsigned Size = Arg.Flags.getByValSize(); 1433 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1434 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1435 } 1436 1437 unsigned ArgOffset = VA.getLocMemOffset(); 1438 unsigned ArgSize = VA.getValVT().getStoreSize(); 1439 1440 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1441 1442 // Create load nodes to retrieve arguments from the stack. 1443 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1444 SDValue ArgValue; 1445 1446 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1447 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1448 MVT MemVT = VA.getValVT(); 1449 1450 switch (VA.getLocInfo()) { 1451 default: 1452 break; 1453 case CCValAssign::BCvt: 1454 MemVT = VA.getLocVT(); 1455 break; 1456 case CCValAssign::SExt: 1457 ExtType = ISD::SEXTLOAD; 1458 break; 1459 case CCValAssign::ZExt: 1460 ExtType = ISD::ZEXTLOAD; 1461 break; 1462 case CCValAssign::AExt: 1463 ExtType = ISD::EXTLOAD; 1464 break; 1465 } 1466 1467 ArgValue = DAG.getExtLoad( 1468 ExtType, SL, VA.getLocVT(), Chain, FIN, 1469 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1470 MemVT); 1471 return ArgValue; 1472 } 1473 1474 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1475 const SIMachineFunctionInfo &MFI, 1476 EVT VT, 1477 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1478 const ArgDescriptor *Reg; 1479 const TargetRegisterClass *RC; 1480 1481 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1482 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1483 } 1484 1485 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1486 CallingConv::ID CallConv, 1487 ArrayRef<ISD::InputArg> Ins, 1488 BitVector &Skipped, 1489 FunctionType *FType, 1490 SIMachineFunctionInfo *Info) { 1491 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1492 const ISD::InputArg *Arg = &Ins[I]; 1493 1494 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1495 "vector type argument should have been split"); 1496 1497 // First check if it's a PS input addr. 1498 if (CallConv == CallingConv::AMDGPU_PS && 1499 !Arg->Flags.isInReg() && !Arg->Flags.isByVal() && PSInputNum <= 15) { 1500 1501 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1502 1503 // Inconveniently only the first part of the split is marked as isSplit, 1504 // so skip to the end. We only want to increment PSInputNum once for the 1505 // entire split argument. 1506 if (Arg->Flags.isSplit()) { 1507 while (!Arg->Flags.isSplitEnd()) { 1508 assert(!Arg->VT.isVector() && 1509 "unexpected vector split in ps argument type"); 1510 if (!SkipArg) 1511 Splits.push_back(*Arg); 1512 Arg = &Ins[++I]; 1513 } 1514 } 1515 1516 if (SkipArg) { 1517 // We can safely skip PS inputs. 1518 Skipped.set(Arg->getOrigArgIndex()); 1519 ++PSInputNum; 1520 continue; 1521 } 1522 1523 Info->markPSInputAllocated(PSInputNum); 1524 if (Arg->Used) 1525 Info->markPSInputEnabled(PSInputNum); 1526 1527 ++PSInputNum; 1528 } 1529 1530 Splits.push_back(*Arg); 1531 } 1532 } 1533 1534 // Allocate special inputs passed in VGPRs. 1535 static void allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1536 MachineFunction &MF, 1537 const SIRegisterInfo &TRI, 1538 SIMachineFunctionInfo &Info) { 1539 if (Info.hasWorkItemIDX()) { 1540 unsigned Reg = AMDGPU::VGPR0; 1541 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1542 1543 CCInfo.AllocateReg(Reg); 1544 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1545 } 1546 1547 if (Info.hasWorkItemIDY()) { 1548 unsigned Reg = AMDGPU::VGPR1; 1549 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1550 1551 CCInfo.AllocateReg(Reg); 1552 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1553 } 1554 1555 if (Info.hasWorkItemIDZ()) { 1556 unsigned Reg = AMDGPU::VGPR2; 1557 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1558 1559 CCInfo.AllocateReg(Reg); 1560 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1561 } 1562 } 1563 1564 // Try to allocate a VGPR at the end of the argument list, or if no argument 1565 // VGPRs are left allocating a stack slot. 1566 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo) { 1567 ArrayRef<MCPhysReg> ArgVGPRs 1568 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1569 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1570 if (RegIdx == ArgVGPRs.size()) { 1571 // Spill to stack required. 1572 int64_t Offset = CCInfo.AllocateStack(4, 4); 1573 1574 return ArgDescriptor::createStack(Offset); 1575 } 1576 1577 unsigned Reg = ArgVGPRs[RegIdx]; 1578 Reg = CCInfo.AllocateReg(Reg); 1579 assert(Reg != AMDGPU::NoRegister); 1580 1581 MachineFunction &MF = CCInfo.getMachineFunction(); 1582 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1583 return ArgDescriptor::createRegister(Reg); 1584 } 1585 1586 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1587 const TargetRegisterClass *RC, 1588 unsigned NumArgRegs) { 1589 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1590 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1591 if (RegIdx == ArgSGPRs.size()) 1592 report_fatal_error("ran out of SGPRs for arguments"); 1593 1594 unsigned Reg = ArgSGPRs[RegIdx]; 1595 Reg = CCInfo.AllocateReg(Reg); 1596 assert(Reg != AMDGPU::NoRegister); 1597 1598 MachineFunction &MF = CCInfo.getMachineFunction(); 1599 MF.addLiveIn(Reg, RC); 1600 return ArgDescriptor::createRegister(Reg); 1601 } 1602 1603 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1604 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1605 } 1606 1607 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1608 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1609 } 1610 1611 static void allocateSpecialInputVGPRs(CCState &CCInfo, 1612 MachineFunction &MF, 1613 const SIRegisterInfo &TRI, 1614 SIMachineFunctionInfo &Info) { 1615 if (Info.hasWorkItemIDX()) 1616 Info.setWorkItemIDX(allocateVGPR32Input(CCInfo)); 1617 1618 if (Info.hasWorkItemIDY()) 1619 Info.setWorkItemIDY(allocateVGPR32Input(CCInfo)); 1620 1621 if (Info.hasWorkItemIDZ()) 1622 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo)); 1623 } 1624 1625 static void allocateSpecialInputSGPRs(CCState &CCInfo, 1626 MachineFunction &MF, 1627 const SIRegisterInfo &TRI, 1628 SIMachineFunctionInfo &Info) { 1629 auto &ArgInfo = Info.getArgInfo(); 1630 1631 // TODO: Unify handling with private memory pointers. 1632 1633 if (Info.hasDispatchPtr()) 1634 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1635 1636 if (Info.hasQueuePtr()) 1637 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1638 1639 if (Info.hasKernargSegmentPtr()) 1640 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo); 1641 1642 if (Info.hasDispatchID()) 1643 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1644 1645 // flat_scratch_init is not applicable for non-kernel functions. 1646 1647 if (Info.hasWorkGroupIDX()) 1648 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1649 1650 if (Info.hasWorkGroupIDY()) 1651 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1652 1653 if (Info.hasWorkGroupIDZ()) 1654 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1655 1656 if (Info.hasImplicitArgPtr()) 1657 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1658 } 1659 1660 // Allocate special inputs passed in user SGPRs. 1661 static void allocateHSAUserSGPRs(CCState &CCInfo, 1662 MachineFunction &MF, 1663 const SIRegisterInfo &TRI, 1664 SIMachineFunctionInfo &Info) { 1665 if (Info.hasImplicitBufferPtr()) { 1666 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1667 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1668 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1669 } 1670 1671 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1672 if (Info.hasPrivateSegmentBuffer()) { 1673 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1674 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1675 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1676 } 1677 1678 if (Info.hasDispatchPtr()) { 1679 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1680 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1681 CCInfo.AllocateReg(DispatchPtrReg); 1682 } 1683 1684 if (Info.hasQueuePtr()) { 1685 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1686 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1687 CCInfo.AllocateReg(QueuePtrReg); 1688 } 1689 1690 if (Info.hasKernargSegmentPtr()) { 1691 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI); 1692 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1693 CCInfo.AllocateReg(InputPtrReg); 1694 } 1695 1696 if (Info.hasDispatchID()) { 1697 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1698 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1699 CCInfo.AllocateReg(DispatchIDReg); 1700 } 1701 1702 if (Info.hasFlatScratchInit()) { 1703 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1704 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1705 CCInfo.AllocateReg(FlatScratchInitReg); 1706 } 1707 1708 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1709 // these from the dispatch pointer. 1710 } 1711 1712 // Allocate special input registers that are initialized per-wave. 1713 static void allocateSystemSGPRs(CCState &CCInfo, 1714 MachineFunction &MF, 1715 SIMachineFunctionInfo &Info, 1716 CallingConv::ID CallConv, 1717 bool IsShader) { 1718 if (Info.hasWorkGroupIDX()) { 1719 unsigned Reg = Info.addWorkGroupIDX(); 1720 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1721 CCInfo.AllocateReg(Reg); 1722 } 1723 1724 if (Info.hasWorkGroupIDY()) { 1725 unsigned Reg = Info.addWorkGroupIDY(); 1726 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1727 CCInfo.AllocateReg(Reg); 1728 } 1729 1730 if (Info.hasWorkGroupIDZ()) { 1731 unsigned Reg = Info.addWorkGroupIDZ(); 1732 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1733 CCInfo.AllocateReg(Reg); 1734 } 1735 1736 if (Info.hasWorkGroupInfo()) { 1737 unsigned Reg = Info.addWorkGroupInfo(); 1738 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1739 CCInfo.AllocateReg(Reg); 1740 } 1741 1742 if (Info.hasPrivateSegmentWaveByteOffset()) { 1743 // Scratch wave offset passed in system SGPR. 1744 unsigned PrivateSegmentWaveByteOffsetReg; 1745 1746 if (IsShader) { 1747 PrivateSegmentWaveByteOffsetReg = 1748 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1749 1750 // This is true if the scratch wave byte offset doesn't have a fixed 1751 // location. 1752 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1753 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1754 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1755 } 1756 } else 1757 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1758 1759 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1760 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1761 } 1762 } 1763 1764 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1765 MachineFunction &MF, 1766 const SIRegisterInfo &TRI, 1767 SIMachineFunctionInfo &Info) { 1768 // Now that we've figured out where the scratch register inputs are, see if 1769 // should reserve the arguments and use them directly. 1770 MachineFrameInfo &MFI = MF.getFrameInfo(); 1771 bool HasStackObjects = MFI.hasStackObjects(); 1772 1773 // Record that we know we have non-spill stack objects so we don't need to 1774 // check all stack objects later. 1775 if (HasStackObjects) 1776 Info.setHasNonSpillStackObjects(true); 1777 1778 // Everything live out of a block is spilled with fast regalloc, so it's 1779 // almost certain that spilling will be required. 1780 if (TM.getOptLevel() == CodeGenOpt::None) 1781 HasStackObjects = true; 1782 1783 // For now assume stack access is needed in any callee functions, so we need 1784 // the scratch registers to pass in. 1785 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1786 1787 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 1788 if (ST.isAmdHsaOrMesa(MF.getFunction())) { 1789 if (RequiresStackAccess) { 1790 // If we have stack objects, we unquestionably need the private buffer 1791 // resource. For the Code Object V2 ABI, this will be the first 4 user 1792 // SGPR inputs. We can reserve those and use them directly. 1793 1794 unsigned PrivateSegmentBufferReg = Info.getPreloadedReg( 1795 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 1796 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1797 1798 if (MFI.hasCalls()) { 1799 // If we have calls, we need to keep the frame register in a register 1800 // that won't be clobbered by a call, so ensure it is copied somewhere. 1801 1802 // This is not a problem for the scratch wave offset, because the same 1803 // registers are reserved in all functions. 1804 1805 // FIXME: Nothing is really ensuring this is a call preserved register, 1806 // it's just selected from the end so it happens to be. 1807 unsigned ReservedOffsetReg 1808 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1809 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1810 } else { 1811 unsigned PrivateSegmentWaveByteOffsetReg = Info.getPreloadedReg( 1812 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1813 Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg); 1814 } 1815 } else { 1816 unsigned ReservedBufferReg 1817 = TRI.reservedPrivateSegmentBufferReg(MF); 1818 unsigned ReservedOffsetReg 1819 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1820 1821 // We tentatively reserve the last registers (skipping the last two 1822 // which may contain VCC). After register allocation, we'll replace 1823 // these with the ones immediately after those which were really 1824 // allocated. In the prologue copies will be inserted from the argument 1825 // to these reserved registers. 1826 Info.setScratchRSrcReg(ReservedBufferReg); 1827 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1828 } 1829 } else { 1830 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1831 1832 // Without HSA, relocations are used for the scratch pointer and the 1833 // buffer resource setup is always inserted in the prologue. Scratch wave 1834 // offset is still in an input SGPR. 1835 Info.setScratchRSrcReg(ReservedBufferReg); 1836 1837 if (HasStackObjects && !MFI.hasCalls()) { 1838 unsigned ScratchWaveOffsetReg = Info.getPreloadedReg( 1839 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1840 Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg); 1841 } else { 1842 unsigned ReservedOffsetReg 1843 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1844 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1845 } 1846 } 1847 } 1848 1849 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 1850 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 1851 return !Info->isEntryFunction(); 1852 } 1853 1854 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 1855 1856 } 1857 1858 void SITargetLowering::insertCopiesSplitCSR( 1859 MachineBasicBlock *Entry, 1860 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 1861 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1862 1863 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 1864 if (!IStart) 1865 return; 1866 1867 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1868 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 1869 MachineBasicBlock::iterator MBBI = Entry->begin(); 1870 for (const MCPhysReg *I = IStart; *I; ++I) { 1871 const TargetRegisterClass *RC = nullptr; 1872 if (AMDGPU::SReg_64RegClass.contains(*I)) 1873 RC = &AMDGPU::SGPR_64RegClass; 1874 else if (AMDGPU::SReg_32RegClass.contains(*I)) 1875 RC = &AMDGPU::SGPR_32RegClass; 1876 else 1877 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 1878 1879 unsigned NewVR = MRI->createVirtualRegister(RC); 1880 // Create copy from CSR to a virtual register. 1881 Entry->addLiveIn(*I); 1882 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 1883 .addReg(*I); 1884 1885 // Insert the copy-back instructions right before the terminator. 1886 for (auto *Exit : Exits) 1887 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 1888 TII->get(TargetOpcode::COPY), *I) 1889 .addReg(NewVR); 1890 } 1891 } 1892 1893 SDValue SITargetLowering::LowerFormalArguments( 1894 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 1895 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 1896 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 1897 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1898 1899 MachineFunction &MF = DAG.getMachineFunction(); 1900 const Function &Fn = MF.getFunction(); 1901 FunctionType *FType = MF.getFunction().getFunctionType(); 1902 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1903 1904 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 1905 DiagnosticInfoUnsupported NoGraphicsHSA( 1906 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 1907 DAG.getContext()->diagnose(NoGraphicsHSA); 1908 return DAG.getEntryNode(); 1909 } 1910 1911 SmallVector<ISD::InputArg, 16> Splits; 1912 SmallVector<CCValAssign, 16> ArgLocs; 1913 BitVector Skipped(Ins.size()); 1914 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1915 *DAG.getContext()); 1916 1917 bool IsShader = AMDGPU::isShader(CallConv); 1918 bool IsKernel = AMDGPU::isKernel(CallConv); 1919 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 1920 1921 if (!IsEntryFunc) { 1922 // 4 bytes are reserved at offset 0 for the emergency stack slot. Skip over 1923 // this when allocating argument fixed offsets. 1924 CCInfo.AllocateStack(4, 4); 1925 } 1926 1927 if (IsShader) { 1928 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 1929 1930 // At least one interpolation mode must be enabled or else the GPU will 1931 // hang. 1932 // 1933 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 1934 // set PSInputAddr, the user wants to enable some bits after the compilation 1935 // based on run-time states. Since we can't know what the final PSInputEna 1936 // will look like, so we shouldn't do anything here and the user should take 1937 // responsibility for the correct programming. 1938 // 1939 // Otherwise, the following restrictions apply: 1940 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 1941 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 1942 // enabled too. 1943 if (CallConv == CallingConv::AMDGPU_PS) { 1944 if ((Info->getPSInputAddr() & 0x7F) == 0 || 1945 ((Info->getPSInputAddr() & 0xF) == 0 && 1946 Info->isPSInputAllocated(11))) { 1947 CCInfo.AllocateReg(AMDGPU::VGPR0); 1948 CCInfo.AllocateReg(AMDGPU::VGPR1); 1949 Info->markPSInputAllocated(0); 1950 Info->markPSInputEnabled(0); 1951 } 1952 if (Subtarget->isAmdPalOS()) { 1953 // For isAmdPalOS, the user does not enable some bits after compilation 1954 // based on run-time states; the register values being generated here are 1955 // the final ones set in hardware. Therefore we need to apply the 1956 // workaround to PSInputAddr and PSInputEnable together. (The case where 1957 // a bit is set in PSInputAddr but not PSInputEnable is where the 1958 // frontend set up an input arg for a particular interpolation mode, but 1959 // nothing uses that input arg. Really we should have an earlier pass 1960 // that removes such an arg.) 1961 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 1962 if ((PsInputBits & 0x7F) == 0 || 1963 ((PsInputBits & 0xF) == 0 && 1964 (PsInputBits >> 11 & 1))) 1965 Info->markPSInputEnabled( 1966 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 1967 } 1968 } 1969 1970 assert(!Info->hasDispatchPtr() && 1971 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 1972 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 1973 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 1974 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 1975 !Info->hasWorkItemIDZ()); 1976 } else if (IsKernel) { 1977 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 1978 } else { 1979 Splits.append(Ins.begin(), Ins.end()); 1980 } 1981 1982 if (IsEntryFunc) { 1983 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 1984 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 1985 } 1986 1987 if (IsKernel) { 1988 analyzeFormalArgumentsCompute(CCInfo, Ins); 1989 } else { 1990 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 1991 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 1992 } 1993 1994 SmallVector<SDValue, 16> Chains; 1995 1996 // FIXME: This is the minimum kernel argument alignment. We should improve 1997 // this to the maximum alignment of the arguments. 1998 // 1999 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2000 // kern arg offset. 2001 const unsigned KernelArgBaseAlign = 16; 2002 2003 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2004 const ISD::InputArg &Arg = Ins[i]; 2005 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2006 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2007 continue; 2008 } 2009 2010 CCValAssign &VA = ArgLocs[ArgIdx++]; 2011 MVT VT = VA.getLocVT(); 2012 2013 if (IsEntryFunc && VA.isMemLoc()) { 2014 VT = Ins[i].VT; 2015 EVT MemVT = VA.getLocVT(); 2016 2017 const uint64_t Offset = VA.getLocMemOffset(); 2018 unsigned Align = MinAlign(KernelArgBaseAlign, Offset); 2019 2020 SDValue Arg = lowerKernargMemParameter( 2021 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]); 2022 Chains.push_back(Arg.getValue(1)); 2023 2024 auto *ParamTy = 2025 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2026 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2027 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2028 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2029 // On SI local pointers are just offsets into LDS, so they are always 2030 // less than 16-bits. On CI and newer they could potentially be 2031 // real pointers, so we can't guarantee their size. 2032 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2033 DAG.getValueType(MVT::i16)); 2034 } 2035 2036 InVals.push_back(Arg); 2037 continue; 2038 } else if (!IsEntryFunc && VA.isMemLoc()) { 2039 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2040 InVals.push_back(Val); 2041 if (!Arg.Flags.isByVal()) 2042 Chains.push_back(Val.getValue(1)); 2043 continue; 2044 } 2045 2046 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2047 2048 unsigned Reg = VA.getLocReg(); 2049 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2050 EVT ValVT = VA.getValVT(); 2051 2052 Reg = MF.addLiveIn(Reg, RC); 2053 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2054 2055 if (Arg.Flags.isSRet() && !getSubtarget()->enableHugePrivateBuffer()) { 2056 // The return object should be reasonably addressable. 2057 2058 // FIXME: This helps when the return is a real sret. If it is a 2059 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2060 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2061 unsigned NumBits = 32 - AssumeFrameIndexHighZeroBits; 2062 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2063 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2064 } 2065 2066 // If this is an 8 or 16-bit value, it is really passed promoted 2067 // to 32 bits. Insert an assert[sz]ext to capture this, then 2068 // truncate to the right size. 2069 switch (VA.getLocInfo()) { 2070 case CCValAssign::Full: 2071 break; 2072 case CCValAssign::BCvt: 2073 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2074 break; 2075 case CCValAssign::SExt: 2076 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2077 DAG.getValueType(ValVT)); 2078 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2079 break; 2080 case CCValAssign::ZExt: 2081 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2082 DAG.getValueType(ValVT)); 2083 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2084 break; 2085 case CCValAssign::AExt: 2086 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2087 break; 2088 default: 2089 llvm_unreachable("Unknown loc info!"); 2090 } 2091 2092 InVals.push_back(Val); 2093 } 2094 2095 if (!IsEntryFunc) { 2096 // Special inputs come after user arguments. 2097 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2098 } 2099 2100 // Start adding system SGPRs. 2101 if (IsEntryFunc) { 2102 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2103 } else { 2104 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2105 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg()); 2106 CCInfo.AllocateReg(Info->getFrameOffsetReg()); 2107 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2108 } 2109 2110 auto &ArgUsageInfo = 2111 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2112 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2113 2114 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2115 Info->setBytesInStackArgArea(StackArgSize); 2116 2117 return Chains.empty() ? Chain : 2118 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2119 } 2120 2121 // TODO: If return values can't fit in registers, we should return as many as 2122 // possible in registers before passing on stack. 2123 bool SITargetLowering::CanLowerReturn( 2124 CallingConv::ID CallConv, 2125 MachineFunction &MF, bool IsVarArg, 2126 const SmallVectorImpl<ISD::OutputArg> &Outs, 2127 LLVMContext &Context) const { 2128 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2129 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2130 // for shaders. Vector types should be explicitly handled by CC. 2131 if (AMDGPU::isEntryFunctionCC(CallConv)) 2132 return true; 2133 2134 SmallVector<CCValAssign, 16> RVLocs; 2135 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2136 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2137 } 2138 2139 SDValue 2140 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2141 bool isVarArg, 2142 const SmallVectorImpl<ISD::OutputArg> &Outs, 2143 const SmallVectorImpl<SDValue> &OutVals, 2144 const SDLoc &DL, SelectionDAG &DAG) const { 2145 MachineFunction &MF = DAG.getMachineFunction(); 2146 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2147 2148 if (AMDGPU::isKernel(CallConv)) { 2149 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2150 OutVals, DL, DAG); 2151 } 2152 2153 bool IsShader = AMDGPU::isShader(CallConv); 2154 2155 Info->setIfReturnsVoid(Outs.empty()); 2156 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2157 2158 // CCValAssign - represent the assignment of the return value to a location. 2159 SmallVector<CCValAssign, 48> RVLocs; 2160 SmallVector<ISD::OutputArg, 48> Splits; 2161 2162 // CCState - Info about the registers and stack slots. 2163 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2164 *DAG.getContext()); 2165 2166 // Analyze outgoing return values. 2167 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2168 2169 SDValue Flag; 2170 SmallVector<SDValue, 48> RetOps; 2171 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2172 2173 // Add return address for callable functions. 2174 if (!Info->isEntryFunction()) { 2175 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2176 SDValue ReturnAddrReg = CreateLiveInRegister( 2177 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2178 2179 // FIXME: Should be able to use a vreg here, but need a way to prevent it 2180 // from being allcoated to a CSR. 2181 2182 SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2183 MVT::i64); 2184 2185 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag); 2186 Flag = Chain.getValue(1); 2187 2188 RetOps.push_back(PhysReturnAddrReg); 2189 } 2190 2191 // Copy the result values into the output registers. 2192 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2193 ++I, ++RealRVLocIdx) { 2194 CCValAssign &VA = RVLocs[I]; 2195 assert(VA.isRegLoc() && "Can only return in registers!"); 2196 // TODO: Partially return in registers if return values don't fit. 2197 SDValue Arg = OutVals[RealRVLocIdx]; 2198 2199 // Copied from other backends. 2200 switch (VA.getLocInfo()) { 2201 case CCValAssign::Full: 2202 break; 2203 case CCValAssign::BCvt: 2204 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2205 break; 2206 case CCValAssign::SExt: 2207 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2208 break; 2209 case CCValAssign::ZExt: 2210 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2211 break; 2212 case CCValAssign::AExt: 2213 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2214 break; 2215 default: 2216 llvm_unreachable("Unknown loc info!"); 2217 } 2218 2219 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2220 Flag = Chain.getValue(1); 2221 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2222 } 2223 2224 // FIXME: Does sret work properly? 2225 if (!Info->isEntryFunction()) { 2226 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2227 const MCPhysReg *I = 2228 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2229 if (I) { 2230 for (; *I; ++I) { 2231 if (AMDGPU::SReg_64RegClass.contains(*I)) 2232 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2233 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2234 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2235 else 2236 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2237 } 2238 } 2239 } 2240 2241 // Update chain and glue. 2242 RetOps[0] = Chain; 2243 if (Flag.getNode()) 2244 RetOps.push_back(Flag); 2245 2246 unsigned Opc = AMDGPUISD::ENDPGM; 2247 if (!IsWaveEnd) 2248 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2249 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2250 } 2251 2252 SDValue SITargetLowering::LowerCallResult( 2253 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2254 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2255 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2256 SDValue ThisVal) const { 2257 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2258 2259 // Assign locations to each value returned by this call. 2260 SmallVector<CCValAssign, 16> RVLocs; 2261 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2262 *DAG.getContext()); 2263 CCInfo.AnalyzeCallResult(Ins, RetCC); 2264 2265 // Copy all of the result registers out of their specified physreg. 2266 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2267 CCValAssign VA = RVLocs[i]; 2268 SDValue Val; 2269 2270 if (VA.isRegLoc()) { 2271 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2272 Chain = Val.getValue(1); 2273 InFlag = Val.getValue(2); 2274 } else if (VA.isMemLoc()) { 2275 report_fatal_error("TODO: return values in memory"); 2276 } else 2277 llvm_unreachable("unknown argument location type"); 2278 2279 switch (VA.getLocInfo()) { 2280 case CCValAssign::Full: 2281 break; 2282 case CCValAssign::BCvt: 2283 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2284 break; 2285 case CCValAssign::ZExt: 2286 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2287 DAG.getValueType(VA.getValVT())); 2288 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2289 break; 2290 case CCValAssign::SExt: 2291 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2292 DAG.getValueType(VA.getValVT())); 2293 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2294 break; 2295 case CCValAssign::AExt: 2296 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2297 break; 2298 default: 2299 llvm_unreachable("Unknown loc info!"); 2300 } 2301 2302 InVals.push_back(Val); 2303 } 2304 2305 return Chain; 2306 } 2307 2308 // Add code to pass special inputs required depending on used features separate 2309 // from the explicit user arguments present in the IR. 2310 void SITargetLowering::passSpecialInputs( 2311 CallLoweringInfo &CLI, 2312 CCState &CCInfo, 2313 const SIMachineFunctionInfo &Info, 2314 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2315 SmallVectorImpl<SDValue> &MemOpChains, 2316 SDValue Chain) const { 2317 // If we don't have a call site, this was a call inserted by 2318 // legalization. These can never use special inputs. 2319 if (!CLI.CS) 2320 return; 2321 2322 const Function *CalleeFunc = CLI.CS.getCalledFunction(); 2323 assert(CalleeFunc); 2324 2325 SelectionDAG &DAG = CLI.DAG; 2326 const SDLoc &DL = CLI.DL; 2327 2328 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2329 2330 auto &ArgUsageInfo = 2331 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2332 const AMDGPUFunctionArgInfo &CalleeArgInfo 2333 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2334 2335 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2336 2337 // TODO: Unify with private memory register handling. This is complicated by 2338 // the fact that at least in kernels, the input argument is not necessarily 2339 // in the same location as the input. 2340 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2341 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2342 AMDGPUFunctionArgInfo::QUEUE_PTR, 2343 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR, 2344 AMDGPUFunctionArgInfo::DISPATCH_ID, 2345 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2346 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2347 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z, 2348 AMDGPUFunctionArgInfo::WORKITEM_ID_X, 2349 AMDGPUFunctionArgInfo::WORKITEM_ID_Y, 2350 AMDGPUFunctionArgInfo::WORKITEM_ID_Z, 2351 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR 2352 }; 2353 2354 for (auto InputID : InputRegs) { 2355 const ArgDescriptor *OutgoingArg; 2356 const TargetRegisterClass *ArgRC; 2357 2358 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID); 2359 if (!OutgoingArg) 2360 continue; 2361 2362 const ArgDescriptor *IncomingArg; 2363 const TargetRegisterClass *IncomingArgRC; 2364 std::tie(IncomingArg, IncomingArgRC) 2365 = CallerArgInfo.getPreloadedValue(InputID); 2366 assert(IncomingArgRC == ArgRC); 2367 2368 // All special arguments are ints for now. 2369 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2370 SDValue InputReg; 2371 2372 if (IncomingArg) { 2373 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2374 } else { 2375 // The implicit arg ptr is special because it doesn't have a corresponding 2376 // input for kernels, and is computed from the kernarg segment pointer. 2377 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2378 InputReg = getImplicitArgPtr(DAG, DL); 2379 } 2380 2381 if (OutgoingArg->isRegister()) { 2382 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2383 } else { 2384 unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4); 2385 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2386 SpecialArgOffset); 2387 MemOpChains.push_back(ArgStore); 2388 } 2389 } 2390 } 2391 2392 static bool canGuaranteeTCO(CallingConv::ID CC) { 2393 return CC == CallingConv::Fast; 2394 } 2395 2396 /// Return true if we might ever do TCO for calls with this calling convention. 2397 static bool mayTailCallThisCC(CallingConv::ID CC) { 2398 switch (CC) { 2399 case CallingConv::C: 2400 return true; 2401 default: 2402 return canGuaranteeTCO(CC); 2403 } 2404 } 2405 2406 bool SITargetLowering::isEligibleForTailCallOptimization( 2407 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2408 const SmallVectorImpl<ISD::OutputArg> &Outs, 2409 const SmallVectorImpl<SDValue> &OutVals, 2410 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2411 if (!mayTailCallThisCC(CalleeCC)) 2412 return false; 2413 2414 MachineFunction &MF = DAG.getMachineFunction(); 2415 const Function &CallerF = MF.getFunction(); 2416 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2417 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2418 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2419 2420 // Kernels aren't callable, and don't have a live in return address so it 2421 // doesn't make sense to do a tail call with entry functions. 2422 if (!CallerPreserved) 2423 return false; 2424 2425 bool CCMatch = CallerCC == CalleeCC; 2426 2427 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2428 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2429 return true; 2430 return false; 2431 } 2432 2433 // TODO: Can we handle var args? 2434 if (IsVarArg) 2435 return false; 2436 2437 for (const Argument &Arg : CallerF.args()) { 2438 if (Arg.hasByValAttr()) 2439 return false; 2440 } 2441 2442 LLVMContext &Ctx = *DAG.getContext(); 2443 2444 // Check that the call results are passed in the same way. 2445 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2446 CCAssignFnForCall(CalleeCC, IsVarArg), 2447 CCAssignFnForCall(CallerCC, IsVarArg))) 2448 return false; 2449 2450 // The callee has to preserve all registers the caller needs to preserve. 2451 if (!CCMatch) { 2452 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2453 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2454 return false; 2455 } 2456 2457 // Nothing more to check if the callee is taking no arguments. 2458 if (Outs.empty()) 2459 return true; 2460 2461 SmallVector<CCValAssign, 16> ArgLocs; 2462 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2463 2464 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2465 2466 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2467 // If the stack arguments for this call do not fit into our own save area then 2468 // the call cannot be made tail. 2469 // TODO: Is this really necessary? 2470 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2471 return false; 2472 2473 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2474 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2475 } 2476 2477 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2478 if (!CI->isTailCall()) 2479 return false; 2480 2481 const Function *ParentFn = CI->getParent()->getParent(); 2482 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2483 return false; 2484 2485 auto Attr = ParentFn->getFnAttribute("disable-tail-calls"); 2486 return (Attr.getValueAsString() != "true"); 2487 } 2488 2489 // The wave scratch offset register is used as the global base pointer. 2490 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2491 SmallVectorImpl<SDValue> &InVals) const { 2492 SelectionDAG &DAG = CLI.DAG; 2493 const SDLoc &DL = CLI.DL; 2494 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2495 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2496 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2497 SDValue Chain = CLI.Chain; 2498 SDValue Callee = CLI.Callee; 2499 bool &IsTailCall = CLI.IsTailCall; 2500 CallingConv::ID CallConv = CLI.CallConv; 2501 bool IsVarArg = CLI.IsVarArg; 2502 bool IsSibCall = false; 2503 bool IsThisReturn = false; 2504 MachineFunction &MF = DAG.getMachineFunction(); 2505 2506 if (IsVarArg) { 2507 return lowerUnhandledCall(CLI, InVals, 2508 "unsupported call to variadic function "); 2509 } 2510 2511 if (!CLI.CS.getInstruction()) 2512 report_fatal_error("unsupported libcall legalization"); 2513 2514 if (!CLI.CS.getCalledFunction()) { 2515 return lowerUnhandledCall(CLI, InVals, 2516 "unsupported indirect call to function "); 2517 } 2518 2519 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2520 return lowerUnhandledCall(CLI, InVals, 2521 "unsupported required tail call to function "); 2522 } 2523 2524 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2525 // Note the issue is with the CC of the calling function, not of the call 2526 // itself. 2527 return lowerUnhandledCall(CLI, InVals, 2528 "unsupported call from graphics shader of function "); 2529 } 2530 2531 // The first 4 bytes are reserved for the callee's emergency stack slot. 2532 if (IsTailCall) { 2533 IsTailCall = isEligibleForTailCallOptimization( 2534 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2535 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) { 2536 report_fatal_error("failed to perform tail call elimination on a call " 2537 "site marked musttail"); 2538 } 2539 2540 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2541 2542 // A sibling call is one where we're under the usual C ABI and not planning 2543 // to change that but can still do a tail call: 2544 if (!TailCallOpt && IsTailCall) 2545 IsSibCall = true; 2546 2547 if (IsTailCall) 2548 ++NumTailCalls; 2549 } 2550 2551 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2552 2553 // Analyze operands of the call, assigning locations to each operand. 2554 SmallVector<CCValAssign, 16> ArgLocs; 2555 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2556 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2557 2558 // The first 4 bytes are reserved for the callee's emergency stack slot. 2559 CCInfo.AllocateStack(4, 4); 2560 2561 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2562 2563 // Get a count of how many bytes are to be pushed on the stack. 2564 unsigned NumBytes = CCInfo.getNextStackOffset(); 2565 2566 if (IsSibCall) { 2567 // Since we're not changing the ABI to make this a tail call, the memory 2568 // operands are already available in the caller's incoming argument space. 2569 NumBytes = 0; 2570 } 2571 2572 // FPDiff is the byte offset of the call's argument area from the callee's. 2573 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2574 // by this amount for a tail call. In a sibling call it must be 0 because the 2575 // caller will deallocate the entire stack and the callee still expects its 2576 // arguments to begin at SP+0. Completely unused for non-tail calls. 2577 int32_t FPDiff = 0; 2578 MachineFrameInfo &MFI = MF.getFrameInfo(); 2579 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2580 2581 SDValue CallerSavedFP; 2582 2583 // Adjust the stack pointer for the new arguments... 2584 // These operations are automatically eliminated by the prolog/epilog pass 2585 if (!IsSibCall) { 2586 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2587 2588 unsigned OffsetReg = Info->getScratchWaveOffsetReg(); 2589 2590 // In the HSA case, this should be an identity copy. 2591 SDValue ScratchRSrcReg 2592 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2593 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2594 2595 // TODO: Don't hardcode these registers and get from the callee function. 2596 SDValue ScratchWaveOffsetReg 2597 = DAG.getCopyFromReg(Chain, DL, OffsetReg, MVT::i32); 2598 RegsToPass.emplace_back(AMDGPU::SGPR4, ScratchWaveOffsetReg); 2599 2600 if (!Info->isEntryFunction()) { 2601 // Avoid clobbering this function's FP value. In the current convention 2602 // callee will overwrite this, so do save/restore around the call site. 2603 CallerSavedFP = DAG.getCopyFromReg(Chain, DL, 2604 Info->getFrameOffsetReg(), MVT::i32); 2605 } 2606 } 2607 2608 SmallVector<SDValue, 8> MemOpChains; 2609 MVT PtrVT = MVT::i32; 2610 2611 // Walk the register/memloc assignments, inserting copies/loads. 2612 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 2613 ++i, ++realArgIdx) { 2614 CCValAssign &VA = ArgLocs[i]; 2615 SDValue Arg = OutVals[realArgIdx]; 2616 2617 // Promote the value if needed. 2618 switch (VA.getLocInfo()) { 2619 case CCValAssign::Full: 2620 break; 2621 case CCValAssign::BCvt: 2622 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2623 break; 2624 case CCValAssign::ZExt: 2625 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2626 break; 2627 case CCValAssign::SExt: 2628 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2629 break; 2630 case CCValAssign::AExt: 2631 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2632 break; 2633 case CCValAssign::FPExt: 2634 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2635 break; 2636 default: 2637 llvm_unreachable("Unknown loc info!"); 2638 } 2639 2640 if (VA.isRegLoc()) { 2641 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2642 } else { 2643 assert(VA.isMemLoc()); 2644 2645 SDValue DstAddr; 2646 MachinePointerInfo DstInfo; 2647 2648 unsigned LocMemOffset = VA.getLocMemOffset(); 2649 int32_t Offset = LocMemOffset; 2650 2651 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2652 unsigned Align = 0; 2653 2654 if (IsTailCall) { 2655 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2656 unsigned OpSize = Flags.isByVal() ? 2657 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2658 2659 // FIXME: We can have better than the minimum byval required alignment. 2660 Align = Flags.isByVal() ? Flags.getByValAlign() : 2661 MinAlign(Subtarget->getStackAlignment(), Offset); 2662 2663 Offset = Offset + FPDiff; 2664 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2665 2666 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2667 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2668 2669 // Make sure any stack arguments overlapping with where we're storing 2670 // are loaded before this eventual operation. Otherwise they'll be 2671 // clobbered. 2672 2673 // FIXME: Why is this really necessary? This seems to just result in a 2674 // lot of code to copy the stack and write them back to the same 2675 // locations, which are supposed to be immutable? 2676 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2677 } else { 2678 DstAddr = PtrOff; 2679 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2680 Align = MinAlign(Subtarget->getStackAlignment(), LocMemOffset); 2681 } 2682 2683 if (Outs[i].Flags.isByVal()) { 2684 SDValue SizeNode = 2685 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2686 SDValue Cpy = DAG.getMemcpy( 2687 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 2688 /*isVol = */ false, /*AlwaysInline = */ true, 2689 /*isTailCall = */ false, DstInfo, 2690 MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy( 2691 *DAG.getContext(), AMDGPUAS::PRIVATE_ADDRESS)))); 2692 2693 MemOpChains.push_back(Cpy); 2694 } else { 2695 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Align); 2696 MemOpChains.push_back(Store); 2697 } 2698 } 2699 } 2700 2701 // Copy special input registers after user input arguments. 2702 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2703 2704 if (!MemOpChains.empty()) 2705 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2706 2707 // Build a sequence of copy-to-reg nodes chained together with token chain 2708 // and flag operands which copy the outgoing args into the appropriate regs. 2709 SDValue InFlag; 2710 for (auto &RegToPass : RegsToPass) { 2711 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2712 RegToPass.second, InFlag); 2713 InFlag = Chain.getValue(1); 2714 } 2715 2716 2717 SDValue PhysReturnAddrReg; 2718 if (IsTailCall) { 2719 // Since the return is being combined with the call, we need to pass on the 2720 // return address. 2721 2722 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2723 SDValue ReturnAddrReg = CreateLiveInRegister( 2724 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2725 2726 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2727 MVT::i64); 2728 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2729 InFlag = Chain.getValue(1); 2730 } 2731 2732 // We don't usually want to end the call-sequence here because we would tidy 2733 // the frame up *after* the call, however in the ABI-changing tail-call case 2734 // we've carefully laid out the parameters so that when sp is reset they'll be 2735 // in the correct location. 2736 if (IsTailCall && !IsSibCall) { 2737 Chain = DAG.getCALLSEQ_END(Chain, 2738 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2739 DAG.getTargetConstant(0, DL, MVT::i32), 2740 InFlag, DL); 2741 InFlag = Chain.getValue(1); 2742 } 2743 2744 std::vector<SDValue> Ops; 2745 Ops.push_back(Chain); 2746 Ops.push_back(Callee); 2747 // Add a redundant copy of the callee global which will not be legalized, as 2748 // we need direct access to the callee later. 2749 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee); 2750 const GlobalValue *GV = GSD->getGlobal(); 2751 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 2752 2753 if (IsTailCall) { 2754 // Each tail call may have to adjust the stack by a different amount, so 2755 // this information must travel along with the operation for eventual 2756 // consumption by emitEpilogue. 2757 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 2758 2759 Ops.push_back(PhysReturnAddrReg); 2760 } 2761 2762 // Add argument registers to the end of the list so that they are known live 2763 // into the call. 2764 for (auto &RegToPass : RegsToPass) { 2765 Ops.push_back(DAG.getRegister(RegToPass.first, 2766 RegToPass.second.getValueType())); 2767 } 2768 2769 // Add a register mask operand representing the call-preserved registers. 2770 2771 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 2772 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2773 assert(Mask && "Missing call preserved mask for calling convention"); 2774 Ops.push_back(DAG.getRegisterMask(Mask)); 2775 2776 if (InFlag.getNode()) 2777 Ops.push_back(InFlag); 2778 2779 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2780 2781 // If we're doing a tall call, use a TC_RETURN here rather than an 2782 // actual call instruction. 2783 if (IsTailCall) { 2784 MFI.setHasTailCall(); 2785 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 2786 } 2787 2788 // Returns a chain and a flag for retval copy to use. 2789 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 2790 Chain = Call.getValue(0); 2791 InFlag = Call.getValue(1); 2792 2793 if (CallerSavedFP) { 2794 SDValue FPReg = DAG.getRegister(Info->getFrameOffsetReg(), MVT::i32); 2795 Chain = DAG.getCopyToReg(Chain, DL, FPReg, CallerSavedFP, InFlag); 2796 InFlag = Chain.getValue(1); 2797 } 2798 2799 uint64_t CalleePopBytes = NumBytes; 2800 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 2801 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 2802 InFlag, DL); 2803 if (!Ins.empty()) 2804 InFlag = Chain.getValue(1); 2805 2806 // Handle result values, copying them out of physregs into vregs that we 2807 // return. 2808 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 2809 InVals, IsThisReturn, 2810 IsThisReturn ? OutVals[0] : SDValue()); 2811 } 2812 2813 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT, 2814 SelectionDAG &DAG) const { 2815 unsigned Reg = StringSwitch<unsigned>(RegName) 2816 .Case("m0", AMDGPU::M0) 2817 .Case("exec", AMDGPU::EXEC) 2818 .Case("exec_lo", AMDGPU::EXEC_LO) 2819 .Case("exec_hi", AMDGPU::EXEC_HI) 2820 .Case("flat_scratch", AMDGPU::FLAT_SCR) 2821 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 2822 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 2823 .Default(AMDGPU::NoRegister); 2824 2825 if (Reg == AMDGPU::NoRegister) { 2826 report_fatal_error(Twine("invalid register name \"" 2827 + StringRef(RegName) + "\".")); 2828 2829 } 2830 2831 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2832 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 2833 report_fatal_error(Twine("invalid register \"" 2834 + StringRef(RegName) + "\" for subtarget.")); 2835 } 2836 2837 switch (Reg) { 2838 case AMDGPU::M0: 2839 case AMDGPU::EXEC_LO: 2840 case AMDGPU::EXEC_HI: 2841 case AMDGPU::FLAT_SCR_LO: 2842 case AMDGPU::FLAT_SCR_HI: 2843 if (VT.getSizeInBits() == 32) 2844 return Reg; 2845 break; 2846 case AMDGPU::EXEC: 2847 case AMDGPU::FLAT_SCR: 2848 if (VT.getSizeInBits() == 64) 2849 return Reg; 2850 break; 2851 default: 2852 llvm_unreachable("missing register type checking"); 2853 } 2854 2855 report_fatal_error(Twine("invalid type for register \"" 2856 + StringRef(RegName) + "\".")); 2857 } 2858 2859 // If kill is not the last instruction, split the block so kill is always a 2860 // proper terminator. 2861 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 2862 MachineBasicBlock *BB) const { 2863 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 2864 2865 MachineBasicBlock::iterator SplitPoint(&MI); 2866 ++SplitPoint; 2867 2868 if (SplitPoint == BB->end()) { 2869 // Don't bother with a new block. 2870 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 2871 return BB; 2872 } 2873 2874 MachineFunction *MF = BB->getParent(); 2875 MachineBasicBlock *SplitBB 2876 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 2877 2878 MF->insert(++MachineFunction::iterator(BB), SplitBB); 2879 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 2880 2881 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 2882 BB->addSuccessor(SplitBB); 2883 2884 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 2885 return SplitBB; 2886 } 2887 2888 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 2889 // wavefront. If the value is uniform and just happens to be in a VGPR, this 2890 // will only do one iteration. In the worst case, this will loop 64 times. 2891 // 2892 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 2893 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 2894 const SIInstrInfo *TII, 2895 MachineRegisterInfo &MRI, 2896 MachineBasicBlock &OrigBB, 2897 MachineBasicBlock &LoopBB, 2898 const DebugLoc &DL, 2899 const MachineOperand &IdxReg, 2900 unsigned InitReg, 2901 unsigned ResultReg, 2902 unsigned PhiReg, 2903 unsigned InitSaveExecReg, 2904 int Offset, 2905 bool UseGPRIdxMode, 2906 bool IsIndirectSrc) { 2907 MachineBasicBlock::iterator I = LoopBB.begin(); 2908 2909 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2910 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2911 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 2912 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2913 2914 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 2915 .addReg(InitReg) 2916 .addMBB(&OrigBB) 2917 .addReg(ResultReg) 2918 .addMBB(&LoopBB); 2919 2920 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 2921 .addReg(InitSaveExecReg) 2922 .addMBB(&OrigBB) 2923 .addReg(NewExec) 2924 .addMBB(&LoopBB); 2925 2926 // Read the next variant <- also loop target. 2927 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 2928 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 2929 2930 // Compare the just read M0 value to all possible Idx values. 2931 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 2932 .addReg(CurrentIdxReg) 2933 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 2934 2935 // Update EXEC, save the original EXEC value to VCC. 2936 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec) 2937 .addReg(CondReg, RegState::Kill); 2938 2939 MRI.setSimpleHint(NewExec, CondReg); 2940 2941 if (UseGPRIdxMode) { 2942 unsigned IdxReg; 2943 if (Offset == 0) { 2944 IdxReg = CurrentIdxReg; 2945 } else { 2946 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 2947 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 2948 .addReg(CurrentIdxReg, RegState::Kill) 2949 .addImm(Offset); 2950 } 2951 unsigned IdxMode = IsIndirectSrc ? 2952 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 2953 MachineInstr *SetOn = 2954 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2955 .addReg(IdxReg, RegState::Kill) 2956 .addImm(IdxMode); 2957 SetOn->getOperand(3).setIsUndef(); 2958 } else { 2959 // Move index from VCC into M0 2960 if (Offset == 0) { 2961 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 2962 .addReg(CurrentIdxReg, RegState::Kill); 2963 } else { 2964 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 2965 .addReg(CurrentIdxReg, RegState::Kill) 2966 .addImm(Offset); 2967 } 2968 } 2969 2970 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 2971 MachineInstr *InsertPt = 2972 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64_term), AMDGPU::EXEC) 2973 .addReg(AMDGPU::EXEC) 2974 .addReg(NewExec); 2975 2976 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 2977 // s_cbranch_scc0? 2978 2979 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 2980 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 2981 .addMBB(&LoopBB); 2982 2983 return InsertPt->getIterator(); 2984 } 2985 2986 // This has slightly sub-optimal regalloc when the source vector is killed by 2987 // the read. The register allocator does not understand that the kill is 2988 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 2989 // subregister from it, using 1 more VGPR than necessary. This was saved when 2990 // this was expanded after register allocation. 2991 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 2992 MachineBasicBlock &MBB, 2993 MachineInstr &MI, 2994 unsigned InitResultReg, 2995 unsigned PhiReg, 2996 int Offset, 2997 bool UseGPRIdxMode, 2998 bool IsIndirectSrc) { 2999 MachineFunction *MF = MBB.getParent(); 3000 MachineRegisterInfo &MRI = MF->getRegInfo(); 3001 const DebugLoc &DL = MI.getDebugLoc(); 3002 MachineBasicBlock::iterator I(&MI); 3003 3004 unsigned DstReg = MI.getOperand(0).getReg(); 3005 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass); 3006 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass); 3007 3008 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3009 3010 // Save the EXEC mask 3011 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec) 3012 .addReg(AMDGPU::EXEC); 3013 3014 // To insert the loop we need to split the block. Move everything after this 3015 // point to a new block, and insert a new empty block between the two. 3016 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3017 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3018 MachineFunction::iterator MBBI(MBB); 3019 ++MBBI; 3020 3021 MF->insert(MBBI, LoopBB); 3022 MF->insert(MBBI, RemainderBB); 3023 3024 LoopBB->addSuccessor(LoopBB); 3025 LoopBB->addSuccessor(RemainderBB); 3026 3027 // Move the rest of the block into a new block. 3028 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3029 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3030 3031 MBB.addSuccessor(LoopBB); 3032 3033 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3034 3035 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3036 InitResultReg, DstReg, PhiReg, TmpExec, 3037 Offset, UseGPRIdxMode, IsIndirectSrc); 3038 3039 MachineBasicBlock::iterator First = RemainderBB->begin(); 3040 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC) 3041 .addReg(SaveExec); 3042 3043 return InsPt; 3044 } 3045 3046 // Returns subreg index, offset 3047 static std::pair<unsigned, int> 3048 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3049 const TargetRegisterClass *SuperRC, 3050 unsigned VecReg, 3051 int Offset) { 3052 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3053 3054 // Skip out of bounds offsets, or else we would end up using an undefined 3055 // register. 3056 if (Offset >= NumElts || Offset < 0) 3057 return std::make_pair(AMDGPU::sub0, Offset); 3058 3059 return std::make_pair(AMDGPU::sub0 + Offset, 0); 3060 } 3061 3062 // Return true if the index is an SGPR and was set. 3063 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3064 MachineRegisterInfo &MRI, 3065 MachineInstr &MI, 3066 int Offset, 3067 bool UseGPRIdxMode, 3068 bool IsIndirectSrc) { 3069 MachineBasicBlock *MBB = MI.getParent(); 3070 const DebugLoc &DL = MI.getDebugLoc(); 3071 MachineBasicBlock::iterator I(&MI); 3072 3073 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3074 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3075 3076 assert(Idx->getReg() != AMDGPU::NoRegister); 3077 3078 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3079 return false; 3080 3081 if (UseGPRIdxMode) { 3082 unsigned IdxMode = IsIndirectSrc ? 3083 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3084 if (Offset == 0) { 3085 MachineInstr *SetOn = 3086 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3087 .add(*Idx) 3088 .addImm(IdxMode); 3089 3090 SetOn->getOperand(3).setIsUndef(); 3091 } else { 3092 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3093 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3094 .add(*Idx) 3095 .addImm(Offset); 3096 MachineInstr *SetOn = 3097 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3098 .addReg(Tmp, RegState::Kill) 3099 .addImm(IdxMode); 3100 3101 SetOn->getOperand(3).setIsUndef(); 3102 } 3103 3104 return true; 3105 } 3106 3107 if (Offset == 0) { 3108 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3109 .add(*Idx); 3110 } else { 3111 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3112 .add(*Idx) 3113 .addImm(Offset); 3114 } 3115 3116 return true; 3117 } 3118 3119 // Control flow needs to be inserted if indexing with a VGPR. 3120 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3121 MachineBasicBlock &MBB, 3122 const GCNSubtarget &ST) { 3123 const SIInstrInfo *TII = ST.getInstrInfo(); 3124 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3125 MachineFunction *MF = MBB.getParent(); 3126 MachineRegisterInfo &MRI = MF->getRegInfo(); 3127 3128 unsigned Dst = MI.getOperand(0).getReg(); 3129 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3130 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3131 3132 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3133 3134 unsigned SubReg; 3135 std::tie(SubReg, Offset) 3136 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3137 3138 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 3139 3140 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3141 MachineBasicBlock::iterator I(&MI); 3142 const DebugLoc &DL = MI.getDebugLoc(); 3143 3144 if (UseGPRIdxMode) { 3145 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3146 // to avoid interfering with other uses, so probably requires a new 3147 // optimization pass. 3148 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3149 .addReg(SrcReg, RegState::Undef, SubReg) 3150 .addReg(SrcReg, RegState::Implicit) 3151 .addReg(AMDGPU::M0, RegState::Implicit); 3152 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3153 } else { 3154 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3155 .addReg(SrcReg, RegState::Undef, SubReg) 3156 .addReg(SrcReg, RegState::Implicit); 3157 } 3158 3159 MI.eraseFromParent(); 3160 3161 return &MBB; 3162 } 3163 3164 const DebugLoc &DL = MI.getDebugLoc(); 3165 MachineBasicBlock::iterator I(&MI); 3166 3167 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3168 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3169 3170 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3171 3172 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3173 Offset, UseGPRIdxMode, true); 3174 MachineBasicBlock *LoopBB = InsPt->getParent(); 3175 3176 if (UseGPRIdxMode) { 3177 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3178 .addReg(SrcReg, RegState::Undef, SubReg) 3179 .addReg(SrcReg, RegState::Implicit) 3180 .addReg(AMDGPU::M0, RegState::Implicit); 3181 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3182 } else { 3183 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3184 .addReg(SrcReg, RegState::Undef, SubReg) 3185 .addReg(SrcReg, RegState::Implicit); 3186 } 3187 3188 MI.eraseFromParent(); 3189 3190 return LoopBB; 3191 } 3192 3193 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI, 3194 const TargetRegisterClass *VecRC) { 3195 switch (TRI.getRegSizeInBits(*VecRC)) { 3196 case 32: // 4 bytes 3197 return AMDGPU::V_MOVRELD_B32_V1; 3198 case 64: // 8 bytes 3199 return AMDGPU::V_MOVRELD_B32_V2; 3200 case 128: // 16 bytes 3201 return AMDGPU::V_MOVRELD_B32_V4; 3202 case 256: // 32 bytes 3203 return AMDGPU::V_MOVRELD_B32_V8; 3204 case 512: // 64 bytes 3205 return AMDGPU::V_MOVRELD_B32_V16; 3206 default: 3207 llvm_unreachable("unsupported size for MOVRELD pseudos"); 3208 } 3209 } 3210 3211 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3212 MachineBasicBlock &MBB, 3213 const GCNSubtarget &ST) { 3214 const SIInstrInfo *TII = ST.getInstrInfo(); 3215 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3216 MachineFunction *MF = MBB.getParent(); 3217 MachineRegisterInfo &MRI = MF->getRegInfo(); 3218 3219 unsigned Dst = MI.getOperand(0).getReg(); 3220 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3221 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3222 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3223 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3224 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3225 3226 // This can be an immediate, but will be folded later. 3227 assert(Val->getReg()); 3228 3229 unsigned SubReg; 3230 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3231 SrcVec->getReg(), 3232 Offset); 3233 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 3234 3235 if (Idx->getReg() == AMDGPU::NoRegister) { 3236 MachineBasicBlock::iterator I(&MI); 3237 const DebugLoc &DL = MI.getDebugLoc(); 3238 3239 assert(Offset == 0); 3240 3241 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3242 .add(*SrcVec) 3243 .add(*Val) 3244 .addImm(SubReg); 3245 3246 MI.eraseFromParent(); 3247 return &MBB; 3248 } 3249 3250 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3251 MachineBasicBlock::iterator I(&MI); 3252 const DebugLoc &DL = MI.getDebugLoc(); 3253 3254 if (UseGPRIdxMode) { 3255 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 3256 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst 3257 .add(*Val) 3258 .addReg(Dst, RegState::ImplicitDefine) 3259 .addReg(SrcVec->getReg(), RegState::Implicit) 3260 .addReg(AMDGPU::M0, RegState::Implicit); 3261 3262 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3263 } else { 3264 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 3265 3266 BuildMI(MBB, I, DL, MovRelDesc) 3267 .addReg(Dst, RegState::Define) 3268 .addReg(SrcVec->getReg()) 3269 .add(*Val) 3270 .addImm(SubReg - AMDGPU::sub0); 3271 } 3272 3273 MI.eraseFromParent(); 3274 return &MBB; 3275 } 3276 3277 if (Val->isReg()) 3278 MRI.clearKillFlags(Val->getReg()); 3279 3280 const DebugLoc &DL = MI.getDebugLoc(); 3281 3282 unsigned PhiReg = MRI.createVirtualRegister(VecRC); 3283 3284 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3285 Offset, UseGPRIdxMode, false); 3286 MachineBasicBlock *LoopBB = InsPt->getParent(); 3287 3288 if (UseGPRIdxMode) { 3289 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 3290 .addReg(PhiReg, RegState::Undef, SubReg) // vdst 3291 .add(*Val) // src0 3292 .addReg(Dst, RegState::ImplicitDefine) 3293 .addReg(PhiReg, RegState::Implicit) 3294 .addReg(AMDGPU::M0, RegState::Implicit); 3295 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3296 } else { 3297 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 3298 3299 BuildMI(*LoopBB, InsPt, DL, MovRelDesc) 3300 .addReg(Dst, RegState::Define) 3301 .addReg(PhiReg) 3302 .add(*Val) 3303 .addImm(SubReg - AMDGPU::sub0); 3304 } 3305 3306 MI.eraseFromParent(); 3307 3308 return LoopBB; 3309 } 3310 3311 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3312 MachineInstr &MI, MachineBasicBlock *BB) const { 3313 3314 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3315 MachineFunction *MF = BB->getParent(); 3316 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3317 3318 if (TII->isMIMG(MI)) { 3319 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 3320 report_fatal_error("missing mem operand from MIMG instruction"); 3321 } 3322 // Add a memoperand for mimg instructions so that they aren't assumed to 3323 // be ordered memory instuctions. 3324 3325 return BB; 3326 } 3327 3328 switch (MI.getOpcode()) { 3329 case AMDGPU::S_ADD_U64_PSEUDO: 3330 case AMDGPU::S_SUB_U64_PSEUDO: { 3331 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3332 const DebugLoc &DL = MI.getDebugLoc(); 3333 3334 MachineOperand &Dest = MI.getOperand(0); 3335 MachineOperand &Src0 = MI.getOperand(1); 3336 MachineOperand &Src1 = MI.getOperand(2); 3337 3338 unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3339 unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3340 3341 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3342 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub0, 3343 &AMDGPU::SReg_32_XM0RegClass); 3344 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3345 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub1, 3346 &AMDGPU::SReg_32_XM0RegClass); 3347 3348 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3349 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub0, 3350 &AMDGPU::SReg_32_XM0RegClass); 3351 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3352 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub1, 3353 &AMDGPU::SReg_32_XM0RegClass); 3354 3355 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3356 3357 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3358 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3359 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3360 .add(Src0Sub0) 3361 .add(Src1Sub0); 3362 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3363 .add(Src0Sub1) 3364 .add(Src1Sub1); 3365 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3366 .addReg(DestSub0) 3367 .addImm(AMDGPU::sub0) 3368 .addReg(DestSub1) 3369 .addImm(AMDGPU::sub1); 3370 MI.eraseFromParent(); 3371 return BB; 3372 } 3373 case AMDGPU::SI_INIT_M0: { 3374 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3375 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3376 .add(MI.getOperand(0)); 3377 MI.eraseFromParent(); 3378 return BB; 3379 } 3380 case AMDGPU::SI_INIT_EXEC: 3381 // This should be before all vector instructions. 3382 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3383 AMDGPU::EXEC) 3384 .addImm(MI.getOperand(0).getImm()); 3385 MI.eraseFromParent(); 3386 return BB; 3387 3388 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3389 // Extract the thread count from an SGPR input and set EXEC accordingly. 3390 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3391 // 3392 // S_BFE_U32 count, input, {shift, 7} 3393 // S_BFM_B64 exec, count, 0 3394 // S_CMP_EQ_U32 count, 64 3395 // S_CMOV_B64 exec, -1 3396 MachineInstr *FirstMI = &*BB->begin(); 3397 MachineRegisterInfo &MRI = MF->getRegInfo(); 3398 unsigned InputReg = MI.getOperand(0).getReg(); 3399 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3400 bool Found = false; 3401 3402 // Move the COPY of the input reg to the beginning, so that we can use it. 3403 for (auto I = BB->begin(); I != &MI; I++) { 3404 if (I->getOpcode() != TargetOpcode::COPY || 3405 I->getOperand(0).getReg() != InputReg) 3406 continue; 3407 3408 if (I == FirstMI) { 3409 FirstMI = &*++BB->begin(); 3410 } else { 3411 I->removeFromParent(); 3412 BB->insert(FirstMI, &*I); 3413 } 3414 Found = true; 3415 break; 3416 } 3417 assert(Found); 3418 (void)Found; 3419 3420 // This should be before all vector instructions. 3421 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3422 .addReg(InputReg) 3423 .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000); 3424 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64), 3425 AMDGPU::EXEC) 3426 .addReg(CountReg) 3427 .addImm(0); 3428 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3429 .addReg(CountReg, RegState::Kill) 3430 .addImm(64); 3431 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64), 3432 AMDGPU::EXEC) 3433 .addImm(-1); 3434 MI.eraseFromParent(); 3435 return BB; 3436 } 3437 3438 case AMDGPU::GET_GROUPSTATICSIZE: { 3439 DebugLoc DL = MI.getDebugLoc(); 3440 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3441 .add(MI.getOperand(0)) 3442 .addImm(MFI->getLDSSize()); 3443 MI.eraseFromParent(); 3444 return BB; 3445 } 3446 case AMDGPU::SI_INDIRECT_SRC_V1: 3447 case AMDGPU::SI_INDIRECT_SRC_V2: 3448 case AMDGPU::SI_INDIRECT_SRC_V4: 3449 case AMDGPU::SI_INDIRECT_SRC_V8: 3450 case AMDGPU::SI_INDIRECT_SRC_V16: 3451 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3452 case AMDGPU::SI_INDIRECT_DST_V1: 3453 case AMDGPU::SI_INDIRECT_DST_V2: 3454 case AMDGPU::SI_INDIRECT_DST_V4: 3455 case AMDGPU::SI_INDIRECT_DST_V8: 3456 case AMDGPU::SI_INDIRECT_DST_V16: 3457 return emitIndirectDst(MI, *BB, *getSubtarget()); 3458 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3459 case AMDGPU::SI_KILL_I1_PSEUDO: 3460 return splitKillBlock(MI, BB); 3461 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3462 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3463 3464 unsigned Dst = MI.getOperand(0).getReg(); 3465 unsigned Src0 = MI.getOperand(1).getReg(); 3466 unsigned Src1 = MI.getOperand(2).getReg(); 3467 const DebugLoc &DL = MI.getDebugLoc(); 3468 unsigned SrcCond = MI.getOperand(3).getReg(); 3469 3470 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3471 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3472 unsigned SrcCondCopy = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass); 3473 3474 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3475 .addReg(SrcCond); 3476 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3477 .addImm(0) 3478 .addReg(Src0, 0, AMDGPU::sub0) 3479 .addImm(0) 3480 .addReg(Src1, 0, AMDGPU::sub0) 3481 .addReg(SrcCondCopy); 3482 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3483 .addImm(0) 3484 .addReg(Src0, 0, AMDGPU::sub1) 3485 .addImm(0) 3486 .addReg(Src1, 0, AMDGPU::sub1) 3487 .addReg(SrcCondCopy); 3488 3489 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3490 .addReg(DstLo) 3491 .addImm(AMDGPU::sub0) 3492 .addReg(DstHi) 3493 .addImm(AMDGPU::sub1); 3494 MI.eraseFromParent(); 3495 return BB; 3496 } 3497 case AMDGPU::SI_BR_UNDEF: { 3498 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3499 const DebugLoc &DL = MI.getDebugLoc(); 3500 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3501 .add(MI.getOperand(0)); 3502 Br->getOperand(1).setIsUndef(true); // read undef SCC 3503 MI.eraseFromParent(); 3504 return BB; 3505 } 3506 case AMDGPU::ADJCALLSTACKUP: 3507 case AMDGPU::ADJCALLSTACKDOWN: { 3508 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3509 MachineInstrBuilder MIB(*MF, &MI); 3510 3511 // Add an implicit use of the frame offset reg to prevent the restore copy 3512 // inserted after the call from being reorderd after stack operations in the 3513 // the caller's frame. 3514 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3515 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 3516 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 3517 return BB; 3518 } 3519 case AMDGPU::SI_CALL_ISEL: { 3520 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3521 const DebugLoc &DL = MI.getDebugLoc(); 3522 3523 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3524 3525 MachineInstrBuilder MIB; 3526 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 3527 3528 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 3529 MIB.add(MI.getOperand(I)); 3530 3531 MIB.cloneMemRefs(MI); 3532 MI.eraseFromParent(); 3533 return BB; 3534 } 3535 default: 3536 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3537 } 3538 } 3539 3540 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 3541 return isTypeLegal(VT.getScalarType()); 3542 } 3543 3544 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3545 // This currently forces unfolding various combinations of fsub into fma with 3546 // free fneg'd operands. As long as we have fast FMA (controlled by 3547 // isFMAFasterThanFMulAndFAdd), we should perform these. 3548 3549 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3550 // most of these combines appear to be cycle neutral but save on instruction 3551 // count / code size. 3552 return true; 3553 } 3554 3555 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3556 EVT VT) const { 3557 if (!VT.isVector()) { 3558 return MVT::i1; 3559 } 3560 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3561 } 3562 3563 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3564 // TODO: Should i16 be used always if legal? For now it would force VALU 3565 // shifts. 3566 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3567 } 3568 3569 // Answering this is somewhat tricky and depends on the specific device which 3570 // have different rates for fma or all f64 operations. 3571 // 3572 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3573 // regardless of which device (although the number of cycles differs between 3574 // devices), so it is always profitable for f64. 3575 // 3576 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3577 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3578 // which we can always do even without fused FP ops since it returns the same 3579 // result as the separate operations and since it is always full 3580 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3581 // however does not support denormals, so we do report fma as faster if we have 3582 // a fast fma device and require denormals. 3583 // 3584 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 3585 VT = VT.getScalarType(); 3586 3587 switch (VT.getSimpleVT().SimpleTy) { 3588 case MVT::f32: { 3589 // This is as fast on some subtargets. However, we always have full rate f32 3590 // mad available which returns the same result as the separate operations 3591 // which we should prefer over fma. We can't use this if we want to support 3592 // denormals, so only report this in these cases. 3593 if (Subtarget->hasFP32Denormals()) 3594 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 3595 3596 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 3597 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 3598 } 3599 case MVT::f64: 3600 return true; 3601 case MVT::f16: 3602 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals(); 3603 default: 3604 break; 3605 } 3606 3607 return false; 3608 } 3609 3610 //===----------------------------------------------------------------------===// 3611 // Custom DAG Lowering Operations 3612 //===----------------------------------------------------------------------===// 3613 3614 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3615 // wider vector type is legal. 3616 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 3617 SelectionDAG &DAG) const { 3618 unsigned Opc = Op.getOpcode(); 3619 EVT VT = Op.getValueType(); 3620 assert(VT == MVT::v4f16); 3621 3622 SDValue Lo, Hi; 3623 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 3624 3625 SDLoc SL(Op); 3626 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 3627 Op->getFlags()); 3628 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 3629 Op->getFlags()); 3630 3631 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3632 } 3633 3634 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3635 // wider vector type is legal. 3636 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 3637 SelectionDAG &DAG) const { 3638 unsigned Opc = Op.getOpcode(); 3639 EVT VT = Op.getValueType(); 3640 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 3641 3642 SDValue Lo0, Hi0; 3643 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 3644 SDValue Lo1, Hi1; 3645 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 3646 3647 SDLoc SL(Op); 3648 3649 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 3650 Op->getFlags()); 3651 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 3652 Op->getFlags()); 3653 3654 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3655 } 3656 3657 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 3658 switch (Op.getOpcode()) { 3659 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 3660 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 3661 case ISD::LOAD: { 3662 SDValue Result = LowerLOAD(Op, DAG); 3663 assert((!Result.getNode() || 3664 Result.getNode()->getNumValues() == 2) && 3665 "Load should return a value and a chain"); 3666 return Result; 3667 } 3668 3669 case ISD::FSIN: 3670 case ISD::FCOS: 3671 return LowerTrig(Op, DAG); 3672 case ISD::SELECT: return LowerSELECT(Op, DAG); 3673 case ISD::FDIV: return LowerFDIV(Op, DAG); 3674 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 3675 case ISD::STORE: return LowerSTORE(Op, DAG); 3676 case ISD::GlobalAddress: { 3677 MachineFunction &MF = DAG.getMachineFunction(); 3678 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 3679 return LowerGlobalAddress(MFI, Op, DAG); 3680 } 3681 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3682 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 3683 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 3684 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 3685 case ISD::INSERT_VECTOR_ELT: 3686 return lowerINSERT_VECTOR_ELT(Op, DAG); 3687 case ISD::EXTRACT_VECTOR_ELT: 3688 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3689 case ISD::BUILD_VECTOR: 3690 return lowerBUILD_VECTOR(Op, DAG); 3691 case ISD::FP_ROUND: 3692 return lowerFP_ROUND(Op, DAG); 3693 case ISD::TRAP: 3694 return lowerTRAP(Op, DAG); 3695 case ISD::DEBUGTRAP: 3696 return lowerDEBUGTRAP(Op, DAG); 3697 case ISD::FABS: 3698 case ISD::FNEG: 3699 case ISD::FCANONICALIZE: 3700 return splitUnaryVectorOp(Op, DAG); 3701 case ISD::FMINNUM: 3702 case ISD::FMAXNUM: 3703 return lowerFMINNUM_FMAXNUM(Op, DAG); 3704 case ISD::SHL: 3705 case ISD::SRA: 3706 case ISD::SRL: 3707 case ISD::ADD: 3708 case ISD::SUB: 3709 case ISD::MUL: 3710 case ISD::SMIN: 3711 case ISD::SMAX: 3712 case ISD::UMIN: 3713 case ISD::UMAX: 3714 case ISD::FADD: 3715 case ISD::FMUL: 3716 case ISD::FMINNUM_IEEE: 3717 case ISD::FMAXNUM_IEEE: 3718 return splitBinaryVectorOp(Op, DAG); 3719 } 3720 return SDValue(); 3721 } 3722 3723 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 3724 const SDLoc &DL, 3725 SelectionDAG &DAG, bool Unpacked) { 3726 if (!LoadVT.isVector()) 3727 return Result; 3728 3729 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 3730 // Truncate to v2i16/v4i16. 3731 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 3732 3733 // Workaround legalizer not scalarizing truncate after vector op 3734 // legalization byt not creating intermediate vector trunc. 3735 SmallVector<SDValue, 4> Elts; 3736 DAG.ExtractVectorElements(Result, Elts); 3737 for (SDValue &Elt : Elts) 3738 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 3739 3740 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 3741 3742 // Bitcast to original type (v2f16/v4f16). 3743 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 3744 } 3745 3746 // Cast back to the original packed type. 3747 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 3748 } 3749 3750 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 3751 MemSDNode *M, 3752 SelectionDAG &DAG, 3753 ArrayRef<SDValue> Ops, 3754 bool IsIntrinsic) const { 3755 SDLoc DL(M); 3756 3757 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 3758 EVT LoadVT = M->getValueType(0); 3759 3760 EVT EquivLoadVT = LoadVT; 3761 if (Unpacked && LoadVT.isVector()) { 3762 EquivLoadVT = LoadVT.isVector() ? 3763 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 3764 LoadVT.getVectorNumElements()) : LoadVT; 3765 } 3766 3767 // Change from v4f16/v2f16 to EquivLoadVT. 3768 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 3769 3770 SDValue Load 3771 = DAG.getMemIntrinsicNode( 3772 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 3773 VTList, Ops, M->getMemoryVT(), 3774 M->getMemOperand()); 3775 if (!Unpacked) // Just adjusted the opcode. 3776 return Load; 3777 3778 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 3779 3780 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 3781 } 3782 3783 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 3784 SDNode *N, SelectionDAG &DAG) { 3785 EVT VT = N->getValueType(0); 3786 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 3787 int CondCode = CD->getSExtValue(); 3788 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 3789 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 3790 return DAG.getUNDEF(VT); 3791 3792 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 3793 3794 3795 SDValue LHS = N->getOperand(1); 3796 SDValue RHS = N->getOperand(2); 3797 3798 SDLoc DL(N); 3799 3800 EVT CmpVT = LHS.getValueType(); 3801 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 3802 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 3803 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 3804 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 3805 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 3806 } 3807 3808 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 3809 3810 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, LHS, RHS, 3811 DAG.getCondCode(CCOpcode)); 3812 } 3813 3814 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 3815 SDNode *N, SelectionDAG &DAG) { 3816 EVT VT = N->getValueType(0); 3817 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 3818 3819 int CondCode = CD->getSExtValue(); 3820 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 3821 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 3822 return DAG.getUNDEF(VT); 3823 } 3824 3825 SDValue Src0 = N->getOperand(1); 3826 SDValue Src1 = N->getOperand(2); 3827 EVT CmpVT = Src0.getValueType(); 3828 SDLoc SL(N); 3829 3830 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 3831 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 3832 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 3833 } 3834 3835 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 3836 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 3837 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src0, 3838 Src1, DAG.getCondCode(CCOpcode)); 3839 } 3840 3841 void SITargetLowering::ReplaceNodeResults(SDNode *N, 3842 SmallVectorImpl<SDValue> &Results, 3843 SelectionDAG &DAG) const { 3844 switch (N->getOpcode()) { 3845 case ISD::INSERT_VECTOR_ELT: { 3846 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 3847 Results.push_back(Res); 3848 return; 3849 } 3850 case ISD::EXTRACT_VECTOR_ELT: { 3851 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 3852 Results.push_back(Res); 3853 return; 3854 } 3855 case ISD::INTRINSIC_WO_CHAIN: { 3856 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 3857 switch (IID) { 3858 case Intrinsic::amdgcn_cvt_pkrtz: { 3859 SDValue Src0 = N->getOperand(1); 3860 SDValue Src1 = N->getOperand(2); 3861 SDLoc SL(N); 3862 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 3863 Src0, Src1); 3864 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 3865 return; 3866 } 3867 case Intrinsic::amdgcn_cvt_pknorm_i16: 3868 case Intrinsic::amdgcn_cvt_pknorm_u16: 3869 case Intrinsic::amdgcn_cvt_pk_i16: 3870 case Intrinsic::amdgcn_cvt_pk_u16: { 3871 SDValue Src0 = N->getOperand(1); 3872 SDValue Src1 = N->getOperand(2); 3873 SDLoc SL(N); 3874 unsigned Opcode; 3875 3876 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 3877 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 3878 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 3879 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 3880 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 3881 Opcode = AMDGPUISD::CVT_PK_I16_I32; 3882 else 3883 Opcode = AMDGPUISD::CVT_PK_U16_U32; 3884 3885 EVT VT = N->getValueType(0); 3886 if (isTypeLegal(VT)) 3887 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 3888 else { 3889 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 3890 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 3891 } 3892 return; 3893 } 3894 } 3895 break; 3896 } 3897 case ISD::INTRINSIC_W_CHAIN: { 3898 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 3899 Results.push_back(Res); 3900 Results.push_back(Res.getValue(1)); 3901 return; 3902 } 3903 3904 break; 3905 } 3906 case ISD::SELECT: { 3907 SDLoc SL(N); 3908 EVT VT = N->getValueType(0); 3909 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 3910 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 3911 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 3912 3913 EVT SelectVT = NewVT; 3914 if (NewVT.bitsLT(MVT::i32)) { 3915 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 3916 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 3917 SelectVT = MVT::i32; 3918 } 3919 3920 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 3921 N->getOperand(0), LHS, RHS); 3922 3923 if (NewVT != SelectVT) 3924 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 3925 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 3926 return; 3927 } 3928 case ISD::FNEG: { 3929 if (N->getValueType(0) != MVT::v2f16) 3930 break; 3931 3932 SDLoc SL(N); 3933 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 3934 3935 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 3936 BC, 3937 DAG.getConstant(0x80008000, SL, MVT::i32)); 3938 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 3939 return; 3940 } 3941 case ISD::FABS: { 3942 if (N->getValueType(0) != MVT::v2f16) 3943 break; 3944 3945 SDLoc SL(N); 3946 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 3947 3948 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 3949 BC, 3950 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 3951 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 3952 return; 3953 } 3954 default: 3955 break; 3956 } 3957 } 3958 3959 /// Helper function for LowerBRCOND 3960 static SDNode *findUser(SDValue Value, unsigned Opcode) { 3961 3962 SDNode *Parent = Value.getNode(); 3963 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 3964 I != E; ++I) { 3965 3966 if (I.getUse().get() != Value) 3967 continue; 3968 3969 if (I->getOpcode() == Opcode) 3970 return *I; 3971 } 3972 return nullptr; 3973 } 3974 3975 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 3976 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 3977 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 3978 case Intrinsic::amdgcn_if: 3979 return AMDGPUISD::IF; 3980 case Intrinsic::amdgcn_else: 3981 return AMDGPUISD::ELSE; 3982 case Intrinsic::amdgcn_loop: 3983 return AMDGPUISD::LOOP; 3984 case Intrinsic::amdgcn_end_cf: 3985 llvm_unreachable("should not occur"); 3986 default: 3987 return 0; 3988 } 3989 } 3990 3991 // break, if_break, else_break are all only used as inputs to loop, not 3992 // directly as branch conditions. 3993 return 0; 3994 } 3995 3996 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 3997 const Triple &TT = getTargetMachine().getTargetTriple(); 3998 return (GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 3999 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4000 AMDGPU::shouldEmitConstantsToTextSection(TT); 4001 } 4002 4003 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4004 // FIXME: Either avoid relying on address space here or change the default 4005 // address space for functions to avoid the explicit check. 4006 return (GV->getValueType()->isFunctionTy() || 4007 GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 4008 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4009 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4010 !shouldEmitFixup(GV) && 4011 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4012 } 4013 4014 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4015 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4016 } 4017 4018 /// This transforms the control flow intrinsics to get the branch destination as 4019 /// last parameter, also switches branch target with BR if the need arise 4020 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4021 SelectionDAG &DAG) const { 4022 SDLoc DL(BRCOND); 4023 4024 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4025 SDValue Target = BRCOND.getOperand(2); 4026 SDNode *BR = nullptr; 4027 SDNode *SetCC = nullptr; 4028 4029 if (Intr->getOpcode() == ISD::SETCC) { 4030 // As long as we negate the condition everything is fine 4031 SetCC = Intr; 4032 Intr = SetCC->getOperand(0).getNode(); 4033 4034 } else { 4035 // Get the target from BR if we don't negate the condition 4036 BR = findUser(BRCOND, ISD::BR); 4037 Target = BR->getOperand(1); 4038 } 4039 4040 // FIXME: This changes the types of the intrinsics instead of introducing new 4041 // nodes with the correct types. 4042 // e.g. llvm.amdgcn.loop 4043 4044 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 4045 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 4046 4047 unsigned CFNode = isCFIntrinsic(Intr); 4048 if (CFNode == 0) { 4049 // This is a uniform branch so we don't need to legalize. 4050 return BRCOND; 4051 } 4052 4053 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4054 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4055 4056 assert(!SetCC || 4057 (SetCC->getConstantOperandVal(1) == 1 && 4058 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4059 ISD::SETNE)); 4060 4061 // operands of the new intrinsic call 4062 SmallVector<SDValue, 4> Ops; 4063 if (HaveChain) 4064 Ops.push_back(BRCOND.getOperand(0)); 4065 4066 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4067 Ops.push_back(Target); 4068 4069 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4070 4071 // build the new intrinsic call 4072 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4073 4074 if (!HaveChain) { 4075 SDValue Ops[] = { 4076 SDValue(Result, 0), 4077 BRCOND.getOperand(0) 4078 }; 4079 4080 Result = DAG.getMergeValues(Ops, DL).getNode(); 4081 } 4082 4083 if (BR) { 4084 // Give the branch instruction our target 4085 SDValue Ops[] = { 4086 BR->getOperand(0), 4087 BRCOND.getOperand(2) 4088 }; 4089 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4090 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4091 BR = NewBR.getNode(); 4092 } 4093 4094 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4095 4096 // Copy the intrinsic results to registers 4097 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4098 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4099 if (!CopyToReg) 4100 continue; 4101 4102 Chain = DAG.getCopyToReg( 4103 Chain, DL, 4104 CopyToReg->getOperand(1), 4105 SDValue(Result, i - 1), 4106 SDValue()); 4107 4108 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4109 } 4110 4111 // Remove the old intrinsic from the chain 4112 DAG.ReplaceAllUsesOfValueWith( 4113 SDValue(Intr, Intr->getNumValues() - 1), 4114 Intr->getOperand(0)); 4115 4116 return Chain; 4117 } 4118 4119 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 4120 SDValue Op, 4121 const SDLoc &DL, 4122 EVT VT) const { 4123 return Op.getValueType().bitsLE(VT) ? 4124 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4125 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 4126 } 4127 4128 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4129 assert(Op.getValueType() == MVT::f16 && 4130 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4131 4132 SDValue Src = Op.getOperand(0); 4133 EVT SrcVT = Src.getValueType(); 4134 if (SrcVT != MVT::f64) 4135 return Op; 4136 4137 SDLoc DL(Op); 4138 4139 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4140 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4141 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4142 } 4143 4144 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4145 SelectionDAG &DAG) const { 4146 EVT VT = Op.getValueType(); 4147 const MachineFunction &MF = DAG.getMachineFunction(); 4148 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4149 bool IsIEEEMode = Info->getMode().IEEE; 4150 4151 // FIXME: Assert during eslection that this is only selected for 4152 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4153 // mode functions, but this happens to be OK since it's only done in cases 4154 // where there is known no sNaN. 4155 if (IsIEEEMode) 4156 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 4157 4158 if (VT == MVT::v4f16) 4159 return splitBinaryVectorOp(Op, DAG); 4160 return Op; 4161 } 4162 4163 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4164 SDLoc SL(Op); 4165 SDValue Chain = Op.getOperand(0); 4166 4167 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4168 !Subtarget->isTrapHandlerEnabled()) 4169 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4170 4171 MachineFunction &MF = DAG.getMachineFunction(); 4172 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4173 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4174 assert(UserSGPR != AMDGPU::NoRegister); 4175 SDValue QueuePtr = CreateLiveInRegister( 4176 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4177 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4178 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4179 QueuePtr, SDValue()); 4180 SDValue Ops[] = { 4181 ToReg, 4182 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 4183 SGPR01, 4184 ToReg.getValue(1) 4185 }; 4186 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4187 } 4188 4189 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 4190 SDLoc SL(Op); 4191 SDValue Chain = Op.getOperand(0); 4192 MachineFunction &MF = DAG.getMachineFunction(); 4193 4194 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4195 !Subtarget->isTrapHandlerEnabled()) { 4196 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4197 "debugtrap handler not supported", 4198 Op.getDebugLoc(), 4199 DS_Warning); 4200 LLVMContext &Ctx = MF.getFunction().getContext(); 4201 Ctx.diagnose(NoTrap); 4202 return Chain; 4203 } 4204 4205 SDValue Ops[] = { 4206 Chain, 4207 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 4208 }; 4209 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4210 } 4211 4212 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4213 SelectionDAG &DAG) const { 4214 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4215 if (Subtarget->hasApertureRegs()) { 4216 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 4217 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4218 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4219 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 4220 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4221 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4222 unsigned Encoding = 4223 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4224 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4225 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4226 4227 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4228 SDValue ApertureReg = SDValue( 4229 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4230 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4231 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4232 } 4233 4234 MachineFunction &MF = DAG.getMachineFunction(); 4235 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4236 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4237 assert(UserSGPR != AMDGPU::NoRegister); 4238 4239 SDValue QueuePtr = CreateLiveInRegister( 4240 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4241 4242 // Offset into amd_queue_t for group_segment_aperture_base_hi / 4243 // private_segment_aperture_base_hi. 4244 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 4245 4246 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 4247 4248 // TODO: Use custom target PseudoSourceValue. 4249 // TODO: We should use the value from the IR intrinsic call, but it might not 4250 // be available and how do we get it? 4251 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()), 4252 AMDGPUAS::CONSTANT_ADDRESS)); 4253 4254 MachinePointerInfo PtrInfo(V, StructOffset); 4255 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4256 MinAlign(64, StructOffset), 4257 MachineMemOperand::MODereferenceable | 4258 MachineMemOperand::MOInvariant); 4259 } 4260 4261 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4262 SelectionDAG &DAG) const { 4263 SDLoc SL(Op); 4264 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4265 4266 SDValue Src = ASC->getOperand(0); 4267 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4268 4269 const AMDGPUTargetMachine &TM = 4270 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4271 4272 // flat -> local/private 4273 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4274 unsigned DestAS = ASC->getDestAddressSpace(); 4275 4276 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 4277 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 4278 unsigned NullVal = TM.getNullPointerValue(DestAS); 4279 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4280 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4281 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4282 4283 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4284 NonNull, Ptr, SegmentNullPtr); 4285 } 4286 } 4287 4288 // local/private -> flat 4289 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4290 unsigned SrcAS = ASC->getSrcAddressSpace(); 4291 4292 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 4293 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 4294 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4295 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4296 4297 SDValue NonNull 4298 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4299 4300 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4301 SDValue CvtPtr 4302 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4303 4304 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4305 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4306 FlatNullPtr); 4307 } 4308 } 4309 4310 // global <-> flat are no-ops and never emitted. 4311 4312 const MachineFunction &MF = DAG.getMachineFunction(); 4313 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 4314 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 4315 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 4316 4317 return DAG.getUNDEF(ASC->getValueType(0)); 4318 } 4319 4320 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4321 SelectionDAG &DAG) const { 4322 SDValue Vec = Op.getOperand(0); 4323 SDValue InsVal = Op.getOperand(1); 4324 SDValue Idx = Op.getOperand(2); 4325 EVT VecVT = Vec.getValueType(); 4326 EVT EltVT = VecVT.getVectorElementType(); 4327 unsigned VecSize = VecVT.getSizeInBits(); 4328 unsigned EltSize = EltVT.getSizeInBits(); 4329 4330 4331 assert(VecSize <= 64); 4332 4333 unsigned NumElts = VecVT.getVectorNumElements(); 4334 SDLoc SL(Op); 4335 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 4336 4337 if (NumElts == 4 && EltSize == 16 && KIdx) { 4338 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 4339 4340 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4341 DAG.getConstant(0, SL, MVT::i32)); 4342 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4343 DAG.getConstant(1, SL, MVT::i32)); 4344 4345 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 4346 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 4347 4348 unsigned Idx = KIdx->getZExtValue(); 4349 bool InsertLo = Idx < 2; 4350 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 4351 InsertLo ? LoVec : HiVec, 4352 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 4353 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 4354 4355 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 4356 4357 SDValue Concat = InsertLo ? 4358 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 4359 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 4360 4361 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 4362 } 4363 4364 if (isa<ConstantSDNode>(Idx)) 4365 return SDValue(); 4366 4367 MVT IntVT = MVT::getIntegerVT(VecSize); 4368 4369 // Avoid stack access for dynamic indexing. 4370 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 4371 4372 // Create a congruent vector with the target value in each element so that 4373 // the required element can be masked and ORed into the target vector. 4374 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 4375 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 4376 4377 assert(isPowerOf2_32(EltSize)); 4378 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4379 4380 // Convert vector index to bit-index. 4381 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4382 4383 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4384 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 4385 DAG.getConstant(0xffff, SL, IntVT), 4386 ScaledIdx); 4387 4388 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 4389 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 4390 DAG.getNOT(SL, BFM, IntVT), BCVec); 4391 4392 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 4393 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 4394 } 4395 4396 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4397 SelectionDAG &DAG) const { 4398 SDLoc SL(Op); 4399 4400 EVT ResultVT = Op.getValueType(); 4401 SDValue Vec = Op.getOperand(0); 4402 SDValue Idx = Op.getOperand(1); 4403 EVT VecVT = Vec.getValueType(); 4404 unsigned VecSize = VecVT.getSizeInBits(); 4405 EVT EltVT = VecVT.getVectorElementType(); 4406 assert(VecSize <= 64); 4407 4408 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 4409 4410 // Make sure we do any optimizations that will make it easier to fold 4411 // source modifiers before obscuring it with bit operations. 4412 4413 // XXX - Why doesn't this get called when vector_shuffle is expanded? 4414 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 4415 return Combined; 4416 4417 unsigned EltSize = EltVT.getSizeInBits(); 4418 assert(isPowerOf2_32(EltSize)); 4419 4420 MVT IntVT = MVT::getIntegerVT(VecSize); 4421 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4422 4423 // Convert vector index to bit-index (* EltSize) 4424 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4425 4426 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4427 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 4428 4429 if (ResultVT == MVT::f16) { 4430 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 4431 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 4432 } 4433 4434 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 4435 } 4436 4437 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 4438 SelectionDAG &DAG) const { 4439 SDLoc SL(Op); 4440 EVT VT = Op.getValueType(); 4441 4442 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 4443 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 4444 4445 // Turn into pair of packed build_vectors. 4446 // TODO: Special case for constants that can be materialized with s_mov_b64. 4447 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 4448 { Op.getOperand(0), Op.getOperand(1) }); 4449 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 4450 { Op.getOperand(2), Op.getOperand(3) }); 4451 4452 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 4453 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 4454 4455 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 4456 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 4457 } 4458 4459 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 4460 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 4461 4462 SDValue Lo = Op.getOperand(0); 4463 SDValue Hi = Op.getOperand(1); 4464 4465 // Avoid adding defined bits with the zero_extend. 4466 if (Hi.isUndef()) { 4467 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4468 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 4469 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 4470 } 4471 4472 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 4473 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 4474 4475 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 4476 DAG.getConstant(16, SL, MVT::i32)); 4477 if (Lo.isUndef()) 4478 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 4479 4480 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4481 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 4482 4483 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 4484 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 4485 } 4486 4487 bool 4488 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 4489 // We can fold offsets for anything that doesn't require a GOT relocation. 4490 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 4491 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4492 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4493 !shouldEmitGOTReloc(GA->getGlobal()); 4494 } 4495 4496 static SDValue 4497 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 4498 const SDLoc &DL, unsigned Offset, EVT PtrVT, 4499 unsigned GAFlags = SIInstrInfo::MO_NONE) { 4500 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 4501 // lowered to the following code sequence: 4502 // 4503 // For constant address space: 4504 // s_getpc_b64 s[0:1] 4505 // s_add_u32 s0, s0, $symbol 4506 // s_addc_u32 s1, s1, 0 4507 // 4508 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 4509 // a fixup or relocation is emitted to replace $symbol with a literal 4510 // constant, which is a pc-relative offset from the encoding of the $symbol 4511 // operand to the global variable. 4512 // 4513 // For global address space: 4514 // s_getpc_b64 s[0:1] 4515 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 4516 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 4517 // 4518 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 4519 // fixups or relocations are emitted to replace $symbol@*@lo and 4520 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 4521 // which is a 64-bit pc-relative offset from the encoding of the $symbol 4522 // operand to the global variable. 4523 // 4524 // What we want here is an offset from the value returned by s_getpc 4525 // (which is the address of the s_add_u32 instruction) to the global 4526 // variable, but since the encoding of $symbol starts 4 bytes after the start 4527 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 4528 // small. This requires us to add 4 to the global variable offset in order to 4529 // compute the correct address. 4530 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 4531 GAFlags); 4532 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 4533 GAFlags == SIInstrInfo::MO_NONE ? 4534 GAFlags : GAFlags + 1); 4535 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 4536 } 4537 4538 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 4539 SDValue Op, 4540 SelectionDAG &DAG) const { 4541 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 4542 const GlobalValue *GV = GSD->getGlobal(); 4543 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 4544 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 4545 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 4546 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 4547 4548 SDLoc DL(GSD); 4549 EVT PtrVT = Op.getValueType(); 4550 4551 // FIXME: Should not make address space based decisions here. 4552 if (shouldEmitFixup(GV)) 4553 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 4554 else if (shouldEmitPCReloc(GV)) 4555 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 4556 SIInstrInfo::MO_REL32); 4557 4558 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 4559 SIInstrInfo::MO_GOTPCREL32); 4560 4561 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 4562 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 4563 const DataLayout &DataLayout = DAG.getDataLayout(); 4564 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 4565 MachinePointerInfo PtrInfo 4566 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 4567 4568 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 4569 MachineMemOperand::MODereferenceable | 4570 MachineMemOperand::MOInvariant); 4571 } 4572 4573 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 4574 const SDLoc &DL, SDValue V) const { 4575 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 4576 // the destination register. 4577 // 4578 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 4579 // so we will end up with redundant moves to m0. 4580 // 4581 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 4582 4583 // A Null SDValue creates a glue result. 4584 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 4585 V, Chain); 4586 return SDValue(M0, 0); 4587 } 4588 4589 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 4590 SDValue Op, 4591 MVT VT, 4592 unsigned Offset) const { 4593 SDLoc SL(Op); 4594 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 4595 DAG.getEntryNode(), Offset, 4, false); 4596 // The local size values will have the hi 16-bits as zero. 4597 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 4598 DAG.getValueType(VT)); 4599 } 4600 4601 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 4602 EVT VT) { 4603 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 4604 "non-hsa intrinsic with hsa target", 4605 DL.getDebugLoc()); 4606 DAG.getContext()->diagnose(BadIntrin); 4607 return DAG.getUNDEF(VT); 4608 } 4609 4610 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 4611 EVT VT) { 4612 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 4613 "intrinsic not supported on subtarget", 4614 DL.getDebugLoc()); 4615 DAG.getContext()->diagnose(BadIntrin); 4616 return DAG.getUNDEF(VT); 4617 } 4618 4619 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 4620 ArrayRef<SDValue> Elts) { 4621 assert(!Elts.empty()); 4622 MVT Type; 4623 unsigned NumElts; 4624 4625 if (Elts.size() == 1) { 4626 Type = MVT::f32; 4627 NumElts = 1; 4628 } else if (Elts.size() == 2) { 4629 Type = MVT::v2f32; 4630 NumElts = 2; 4631 } else if (Elts.size() <= 4) { 4632 Type = MVT::v4f32; 4633 NumElts = 4; 4634 } else if (Elts.size() <= 8) { 4635 Type = MVT::v8f32; 4636 NumElts = 8; 4637 } else { 4638 assert(Elts.size() <= 16); 4639 Type = MVT::v16f32; 4640 NumElts = 16; 4641 } 4642 4643 SmallVector<SDValue, 16> VecElts(NumElts); 4644 for (unsigned i = 0; i < Elts.size(); ++i) { 4645 SDValue Elt = Elts[i]; 4646 if (Elt.getValueType() != MVT::f32) 4647 Elt = DAG.getBitcast(MVT::f32, Elt); 4648 VecElts[i] = Elt; 4649 } 4650 for (unsigned i = Elts.size(); i < NumElts; ++i) 4651 VecElts[i] = DAG.getUNDEF(MVT::f32); 4652 4653 if (NumElts == 1) 4654 return VecElts[0]; 4655 return DAG.getBuildVector(Type, DL, VecElts); 4656 } 4657 4658 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 4659 SDValue *GLC, SDValue *SLC) { 4660 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 4661 4662 uint64_t Value = CachePolicyConst->getZExtValue(); 4663 SDLoc DL(CachePolicy); 4664 if (GLC) { 4665 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 4666 Value &= ~(uint64_t)0x1; 4667 } 4668 if (SLC) { 4669 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 4670 Value &= ~(uint64_t)0x2; 4671 } 4672 4673 return Value == 0; 4674 } 4675 4676 // Re-construct the required return value for a image load intrinsic. 4677 // This is more complicated due to the optional use TexFailCtrl which means the required 4678 // return type is an aggregate 4679 static SDValue constructRetValue(SelectionDAG &DAG, 4680 MachineSDNode *Result, 4681 ArrayRef<EVT> ResultTypes, 4682 bool IsTexFail, bool Unpacked, bool IsD16, 4683 int DMaskPop, int NumVDataDwords, 4684 const SDLoc &DL, LLVMContext &Context) { 4685 // Determine the required return type. This is the same regardless of IsTexFail flag 4686 EVT ReqRetVT = ResultTypes[0]; 4687 EVT ReqRetEltVT = ReqRetVT.isVector() ? ReqRetVT.getVectorElementType() : ReqRetVT; 4688 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 4689 EVT AdjEltVT = Unpacked && IsD16 ? MVT::i32 : ReqRetEltVT; 4690 EVT AdjVT = Unpacked ? ReqRetNumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, ReqRetNumElts) 4691 : AdjEltVT 4692 : ReqRetVT; 4693 4694 // Extract data part of the result 4695 // Bitcast the result to the same type as the required return type 4696 int NumElts; 4697 if (IsD16 && !Unpacked) 4698 NumElts = NumVDataDwords << 1; 4699 else 4700 NumElts = NumVDataDwords; 4701 4702 EVT CastVT = NumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, NumElts) 4703 : AdjEltVT; 4704 4705 // Special case for v6f16. Rather than add support for this, use v3i32 to 4706 // extract the data elements 4707 bool V6F16Special = false; 4708 if (NumElts == 6) { 4709 CastVT = EVT::getVectorVT(Context, MVT::i32, NumElts / 2); 4710 DMaskPop >>= 1; 4711 ReqRetNumElts >>= 1; 4712 V6F16Special = true; 4713 AdjVT = MVT::v2i32; 4714 } 4715 4716 SDValue N = SDValue(Result, 0); 4717 SDValue CastRes = DAG.getNode(ISD::BITCAST, DL, CastVT, N); 4718 4719 // Iterate over the result 4720 SmallVector<SDValue, 4> BVElts; 4721 4722 if (CastVT.isVector()) { 4723 DAG.ExtractVectorElements(CastRes, BVElts, 0, DMaskPop); 4724 } else { 4725 BVElts.push_back(CastRes); 4726 } 4727 int ExtraElts = ReqRetNumElts - DMaskPop; 4728 while(ExtraElts--) 4729 BVElts.push_back(DAG.getUNDEF(AdjEltVT)); 4730 4731 SDValue PreTFCRes; 4732 if (ReqRetNumElts > 1) { 4733 SDValue NewVec = DAG.getBuildVector(AdjVT, DL, BVElts); 4734 if (IsD16 && Unpacked) 4735 PreTFCRes = adjustLoadValueTypeImpl(NewVec, ReqRetVT, DL, DAG, Unpacked); 4736 else 4737 PreTFCRes = NewVec; 4738 } else { 4739 PreTFCRes = BVElts[0]; 4740 } 4741 4742 if (V6F16Special) 4743 PreTFCRes = DAG.getNode(ISD::BITCAST, DL, MVT::v4f16, PreTFCRes); 4744 4745 if (!IsTexFail) { 4746 if (Result->getNumValues() > 1) 4747 return DAG.getMergeValues({PreTFCRes, SDValue(Result, 1)}, DL); 4748 else 4749 return PreTFCRes; 4750 } 4751 4752 // Extract the TexFail result and insert into aggregate return 4753 SmallVector<SDValue, 1> TFCElt; 4754 DAG.ExtractVectorElements(N, TFCElt, DMaskPop, 1); 4755 SDValue TFCRes = DAG.getNode(ISD::BITCAST, DL, ResultTypes[1], TFCElt[0]); 4756 return DAG.getMergeValues({PreTFCRes, TFCRes, SDValue(Result, 1)}, DL); 4757 } 4758 4759 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 4760 SDValue *LWE, bool &IsTexFail) { 4761 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 4762 4763 uint64_t Value = TexFailCtrlConst->getZExtValue(); 4764 if (Value) { 4765 IsTexFail = true; 4766 } 4767 4768 SDLoc DL(TexFailCtrlConst); 4769 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 4770 Value &= ~(uint64_t)0x1; 4771 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 4772 Value &= ~(uint64_t)0x2; 4773 4774 return Value == 0; 4775 } 4776 4777 SDValue SITargetLowering::lowerImage(SDValue Op, 4778 const AMDGPU::ImageDimIntrinsicInfo *Intr, 4779 SelectionDAG &DAG) const { 4780 SDLoc DL(Op); 4781 MachineFunction &MF = DAG.getMachineFunction(); 4782 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 4783 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 4784 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 4785 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 4786 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 4787 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 4788 unsigned IntrOpcode = Intr->BaseOpcode; 4789 4790 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 4791 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 4792 bool IsD16 = false; 4793 bool IsA16 = false; 4794 SDValue VData; 4795 int NumVDataDwords; 4796 bool AdjustRetType = false; 4797 4798 unsigned AddrIdx; // Index of first address argument 4799 unsigned DMask; 4800 unsigned DMaskLanes = 0; 4801 4802 if (BaseOpcode->Atomic) { 4803 VData = Op.getOperand(2); 4804 4805 bool Is64Bit = VData.getValueType() == MVT::i64; 4806 if (BaseOpcode->AtomicX2) { 4807 SDValue VData2 = Op.getOperand(3); 4808 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 4809 {VData, VData2}); 4810 if (Is64Bit) 4811 VData = DAG.getBitcast(MVT::v4i32, VData); 4812 4813 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 4814 DMask = Is64Bit ? 0xf : 0x3; 4815 NumVDataDwords = Is64Bit ? 4 : 2; 4816 AddrIdx = 4; 4817 } else { 4818 DMask = Is64Bit ? 0x3 : 0x1; 4819 NumVDataDwords = Is64Bit ? 2 : 1; 4820 AddrIdx = 3; 4821 } 4822 } else { 4823 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 4824 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 4825 DMask = DMaskConst->getZExtValue(); 4826 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 4827 4828 if (BaseOpcode->Store) { 4829 VData = Op.getOperand(2); 4830 4831 MVT StoreVT = VData.getSimpleValueType(); 4832 if (StoreVT.getScalarType() == MVT::f16) { 4833 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS || 4834 !BaseOpcode->HasD16) 4835 return Op; // D16 is unsupported for this instruction 4836 4837 IsD16 = true; 4838 VData = handleD16VData(VData, DAG); 4839 } 4840 4841 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 4842 } else { 4843 // Work out the num dwords based on the dmask popcount and underlying type 4844 // and whether packing is supported. 4845 MVT LoadVT = ResultTypes[0].getSimpleVT(); 4846 if (LoadVT.getScalarType() == MVT::f16) { 4847 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS || 4848 !BaseOpcode->HasD16) 4849 return Op; // D16 is unsupported for this instruction 4850 4851 IsD16 = true; 4852 } 4853 4854 // Confirm that the return type is large enough for the dmask specified 4855 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 4856 (!LoadVT.isVector() && DMaskLanes > 1)) 4857 return Op; 4858 4859 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 4860 NumVDataDwords = (DMaskLanes + 1) / 2; 4861 else 4862 NumVDataDwords = DMaskLanes; 4863 4864 AdjustRetType = true; 4865 } 4866 4867 AddrIdx = DMaskIdx + 1; 4868 } 4869 4870 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 4871 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 4872 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 4873 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 4874 NumCoords + NumLCM; 4875 unsigned NumMIVAddrs = NumVAddrs; 4876 4877 SmallVector<SDValue, 4> VAddrs; 4878 4879 // Optimize _L to _LZ when _L is zero 4880 if (LZMappingInfo) { 4881 if (auto ConstantLod = 4882 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 4883 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 4884 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 4885 NumMIVAddrs--; // remove 'lod' 4886 } 4887 } 4888 } 4889 4890 // Check for 16 bit addresses and pack if true. 4891 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 4892 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 4893 const MVT VAddrScalarVT = VAddrVT.getScalarType(); 4894 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16)) && 4895 ST->hasFeature(AMDGPU::FeatureR128A16)) { 4896 IsA16 = true; 4897 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 4898 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) { 4899 SDValue AddrLo, AddrHi; 4900 // Push back extra arguments. 4901 if (i < DimIdx) { 4902 AddrLo = Op.getOperand(i); 4903 } else { 4904 AddrLo = Op.getOperand(i); 4905 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, 4906 // in 1D, derivatives dx/dh and dx/dv are packed with undef. 4907 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) || 4908 ((NumGradients / 2) % 2 == 1 && 4909 (i == DimIdx + (NumGradients / 2) - 1 || 4910 i == DimIdx + NumGradients - 1))) { 4911 AddrHi = DAG.getUNDEF(MVT::f16); 4912 } else { 4913 AddrHi = Op.getOperand(i + 1); 4914 i++; 4915 } 4916 AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT, 4917 {AddrLo, AddrHi}); 4918 AddrLo = DAG.getBitcast(MVT::i32, AddrLo); 4919 } 4920 VAddrs.push_back(AddrLo); 4921 } 4922 } else { 4923 for (unsigned i = 0; i < NumMIVAddrs; ++i) 4924 VAddrs.push_back(Op.getOperand(AddrIdx + i)); 4925 } 4926 4927 SDValue VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 4928 4929 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 4930 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 4931 unsigned CtrlIdx; // Index of texfailctrl argument 4932 SDValue Unorm; 4933 if (!BaseOpcode->Sampler) { 4934 Unorm = True; 4935 CtrlIdx = AddrIdx + NumVAddrs + 1; 4936 } else { 4937 auto UnormConst = 4938 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 4939 4940 Unorm = UnormConst->getZExtValue() ? True : False; 4941 CtrlIdx = AddrIdx + NumVAddrs + 3; 4942 } 4943 4944 SDValue TFE; 4945 SDValue LWE; 4946 SDValue TexFail = Op.getOperand(CtrlIdx); 4947 bool IsTexFail = false; 4948 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 4949 return Op; 4950 4951 if (IsTexFail) { 4952 if (!DMaskLanes) { 4953 // Expecting to get an error flag since TFC is on - and dmask is 0 4954 // Force dmask to be at least 1 otherwise the instruction will fail 4955 DMask = 0x1; 4956 DMaskLanes = 1; 4957 NumVDataDwords = 1; 4958 } 4959 NumVDataDwords += 1; 4960 AdjustRetType = true; 4961 } 4962 4963 // Has something earlier tagged that the return type needs adjusting 4964 // This happens if the instruction is a load or has set TexFailCtrl flags 4965 if (AdjustRetType) { 4966 // NumVDataDwords reflects the true number of dwords required in the return type 4967 if (DMaskLanes == 0 && !BaseOpcode->Store) { 4968 // This is a no-op load. This can be eliminated 4969 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 4970 if (isa<MemSDNode>(Op)) 4971 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 4972 return Undef; 4973 } 4974 4975 EVT NewVT = NumVDataDwords > 1 ? 4976 EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumVDataDwords) 4977 : MVT::f32; 4978 4979 ResultTypes[0] = NewVT; 4980 if (ResultTypes.size() == 3) { 4981 // Original result was aggregate type used for TexFailCtrl results 4982 // The actual instruction returns as a vector type which has now been 4983 // created. Remove the aggregate result. 4984 ResultTypes.erase(&ResultTypes[1]); 4985 } 4986 } 4987 4988 SDValue GLC; 4989 SDValue SLC; 4990 if (BaseOpcode->Atomic) { 4991 GLC = True; // TODO no-return optimization 4992 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC)) 4993 return Op; 4994 } else { 4995 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC)) 4996 return Op; 4997 } 4998 4999 SmallVector<SDValue, 14> Ops; 5000 if (BaseOpcode->Store || BaseOpcode->Atomic) 5001 Ops.push_back(VData); // vdata 5002 Ops.push_back(VAddr); 5003 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 5004 if (BaseOpcode->Sampler) 5005 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 5006 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 5007 Ops.push_back(Unorm); 5008 Ops.push_back(GLC); 5009 Ops.push_back(SLC); 5010 Ops.push_back(IsA16 && // a16 or r128 5011 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 5012 Ops.push_back(TFE); // tfe 5013 Ops.push_back(LWE); // lwe 5014 Ops.push_back(DimInfo->DA ? True : False); 5015 if (BaseOpcode->HasD16) 5016 Ops.push_back(IsD16 ? True : False); 5017 if (isa<MemSDNode>(Op)) 5018 Ops.push_back(Op.getOperand(0)); // chain 5019 5020 int NumVAddrDwords = VAddr.getValueType().getSizeInBits() / 32; 5021 int Opcode = -1; 5022 5023 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5024 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 5025 NumVDataDwords, NumVAddrDwords); 5026 if (Opcode == -1) 5027 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 5028 NumVDataDwords, NumVAddrDwords); 5029 assert(Opcode != -1); 5030 5031 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 5032 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 5033 MachineMemOperand *MemRef = MemOp->getMemOperand(); 5034 DAG.setNodeMemRefs(NewNode, {MemRef}); 5035 } 5036 5037 if (BaseOpcode->AtomicX2) { 5038 SmallVector<SDValue, 1> Elt; 5039 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 5040 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 5041 } else if (!BaseOpcode->Store) { 5042 return constructRetValue(DAG, NewNode, 5043 OrigResultTypes, IsTexFail, 5044 Subtarget->hasUnpackedD16VMem(), IsD16, 5045 DMaskLanes, NumVDataDwords, DL, 5046 *DAG.getContext()); 5047 } 5048 5049 return SDValue(NewNode, 0); 5050 } 5051 5052 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 5053 SDValue Offset, SDValue GLC, 5054 SelectionDAG &DAG) const { 5055 MachineFunction &MF = DAG.getMachineFunction(); 5056 MachineMemOperand *MMO = MF.getMachineMemOperand( 5057 MachinePointerInfo(), 5058 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 5059 MachineMemOperand::MOInvariant, 5060 VT.getStoreSize(), VT.getStoreSize()); 5061 5062 if (!Offset->isDivergent()) { 5063 SDValue Ops[] = { 5064 Rsrc, 5065 Offset, // Offset 5066 GLC // glc 5067 }; 5068 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 5069 DAG.getVTList(VT), Ops, VT, MMO); 5070 } 5071 5072 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 5073 // assume that the buffer is unswizzled. 5074 SmallVector<SDValue, 4> Loads; 5075 unsigned NumLoads = 1; 5076 MVT LoadVT = VT.getSimpleVT(); 5077 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 5078 assert((LoadVT.getScalarType() == MVT::i32 || 5079 LoadVT.getScalarType() == MVT::f32) && 5080 isPowerOf2_32(NumElts)); 5081 5082 if (NumElts == 8 || NumElts == 16) { 5083 NumLoads = NumElts == 16 ? 4 : 2; 5084 LoadVT = MVT::v4i32; 5085 } 5086 5087 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 5088 unsigned CachePolicy = cast<ConstantSDNode>(GLC)->getZExtValue(); 5089 SDValue Ops[] = { 5090 DAG.getEntryNode(), // Chain 5091 Rsrc, // rsrc 5092 DAG.getConstant(0, DL, MVT::i32), // vindex 5093 {}, // voffset 5094 {}, // soffset 5095 {}, // offset 5096 DAG.getConstant(CachePolicy, DL, MVT::i32), // cachepolicy 5097 DAG.getConstant(0, DL, MVT::i1), // idxen 5098 }; 5099 5100 // Use the alignment to ensure that the required offsets will fit into the 5101 // immediate offsets. 5102 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 5103 5104 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 5105 for (unsigned i = 0; i < NumLoads; ++i) { 5106 Ops[5] = DAG.getConstant(InstOffset + 16 * i, DL, MVT::i32); 5107 Loads.push_back(DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, 5108 Ops, LoadVT, MMO)); 5109 } 5110 5111 if (VT == MVT::v8i32 || VT == MVT::v16i32) 5112 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 5113 5114 return Loads[0]; 5115 } 5116 5117 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 5118 SelectionDAG &DAG) const { 5119 MachineFunction &MF = DAG.getMachineFunction(); 5120 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 5121 5122 EVT VT = Op.getValueType(); 5123 SDLoc DL(Op); 5124 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5125 5126 // TODO: Should this propagate fast-math-flags? 5127 5128 switch (IntrinsicID) { 5129 case Intrinsic::amdgcn_implicit_buffer_ptr: { 5130 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 5131 return emitNonHSAIntrinsicError(DAG, DL, VT); 5132 return getPreloadedValue(DAG, *MFI, VT, 5133 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 5134 } 5135 case Intrinsic::amdgcn_dispatch_ptr: 5136 case Intrinsic::amdgcn_queue_ptr: { 5137 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 5138 DiagnosticInfoUnsupported BadIntrin( 5139 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 5140 DL.getDebugLoc()); 5141 DAG.getContext()->diagnose(BadIntrin); 5142 return DAG.getUNDEF(VT); 5143 } 5144 5145 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 5146 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 5147 return getPreloadedValue(DAG, *MFI, VT, RegID); 5148 } 5149 case Intrinsic::amdgcn_implicitarg_ptr: { 5150 if (MFI->isEntryFunction()) 5151 return getImplicitArgPtr(DAG, DL); 5152 return getPreloadedValue(DAG, *MFI, VT, 5153 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 5154 } 5155 case Intrinsic::amdgcn_kernarg_segment_ptr: { 5156 return getPreloadedValue(DAG, *MFI, VT, 5157 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 5158 } 5159 case Intrinsic::amdgcn_dispatch_id: { 5160 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 5161 } 5162 case Intrinsic::amdgcn_rcp: 5163 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 5164 case Intrinsic::amdgcn_rsq: 5165 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5166 case Intrinsic::amdgcn_rsq_legacy: 5167 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5168 return emitRemovedIntrinsicError(DAG, DL, VT); 5169 5170 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 5171 case Intrinsic::amdgcn_rcp_legacy: 5172 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5173 return emitRemovedIntrinsicError(DAG, DL, VT); 5174 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 5175 case Intrinsic::amdgcn_rsq_clamp: { 5176 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5177 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 5178 5179 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 5180 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 5181 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 5182 5183 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5184 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 5185 DAG.getConstantFP(Max, DL, VT)); 5186 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 5187 DAG.getConstantFP(Min, DL, VT)); 5188 } 5189 case Intrinsic::r600_read_ngroups_x: 5190 if (Subtarget->isAmdHsaOS()) 5191 return emitNonHSAIntrinsicError(DAG, DL, VT); 5192 5193 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5194 SI::KernelInputOffsets::NGROUPS_X, 4, false); 5195 case Intrinsic::r600_read_ngroups_y: 5196 if (Subtarget->isAmdHsaOS()) 5197 return emitNonHSAIntrinsicError(DAG, DL, VT); 5198 5199 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5200 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 5201 case Intrinsic::r600_read_ngroups_z: 5202 if (Subtarget->isAmdHsaOS()) 5203 return emitNonHSAIntrinsicError(DAG, DL, VT); 5204 5205 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5206 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 5207 case Intrinsic::r600_read_global_size_x: 5208 if (Subtarget->isAmdHsaOS()) 5209 return emitNonHSAIntrinsicError(DAG, DL, VT); 5210 5211 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5212 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 5213 case Intrinsic::r600_read_global_size_y: 5214 if (Subtarget->isAmdHsaOS()) 5215 return emitNonHSAIntrinsicError(DAG, DL, VT); 5216 5217 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5218 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 5219 case Intrinsic::r600_read_global_size_z: 5220 if (Subtarget->isAmdHsaOS()) 5221 return emitNonHSAIntrinsicError(DAG, DL, VT); 5222 5223 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5224 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 5225 case Intrinsic::r600_read_local_size_x: 5226 if (Subtarget->isAmdHsaOS()) 5227 return emitNonHSAIntrinsicError(DAG, DL, VT); 5228 5229 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5230 SI::KernelInputOffsets::LOCAL_SIZE_X); 5231 case Intrinsic::r600_read_local_size_y: 5232 if (Subtarget->isAmdHsaOS()) 5233 return emitNonHSAIntrinsicError(DAG, DL, VT); 5234 5235 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5236 SI::KernelInputOffsets::LOCAL_SIZE_Y); 5237 case Intrinsic::r600_read_local_size_z: 5238 if (Subtarget->isAmdHsaOS()) 5239 return emitNonHSAIntrinsicError(DAG, DL, VT); 5240 5241 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5242 SI::KernelInputOffsets::LOCAL_SIZE_Z); 5243 case Intrinsic::amdgcn_workgroup_id_x: 5244 case Intrinsic::r600_read_tgid_x: 5245 return getPreloadedValue(DAG, *MFI, VT, 5246 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 5247 case Intrinsic::amdgcn_workgroup_id_y: 5248 case Intrinsic::r600_read_tgid_y: 5249 return getPreloadedValue(DAG, *MFI, VT, 5250 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 5251 case Intrinsic::amdgcn_workgroup_id_z: 5252 case Intrinsic::r600_read_tgid_z: 5253 return getPreloadedValue(DAG, *MFI, VT, 5254 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 5255 case Intrinsic::amdgcn_workitem_id_x: 5256 case Intrinsic::r600_read_tidig_x: 5257 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5258 SDLoc(DAG.getEntryNode()), 5259 MFI->getArgInfo().WorkItemIDX); 5260 case Intrinsic::amdgcn_workitem_id_y: 5261 case Intrinsic::r600_read_tidig_y: 5262 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5263 SDLoc(DAG.getEntryNode()), 5264 MFI->getArgInfo().WorkItemIDY); 5265 case Intrinsic::amdgcn_workitem_id_z: 5266 case Intrinsic::r600_read_tidig_z: 5267 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5268 SDLoc(DAG.getEntryNode()), 5269 MFI->getArgInfo().WorkItemIDZ); 5270 case Intrinsic::amdgcn_s_buffer_load: { 5271 unsigned Cache = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 5272 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), 5273 DAG.getTargetConstant(Cache & 1, DL, MVT::i1), DAG); 5274 } 5275 case Intrinsic::amdgcn_fdiv_fast: 5276 return lowerFDIV_FAST(Op, DAG); 5277 case Intrinsic::amdgcn_interp_mov: { 5278 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 5279 SDValue Glue = M0.getValue(1); 5280 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1), 5281 Op.getOperand(2), Op.getOperand(3), Glue); 5282 } 5283 case Intrinsic::amdgcn_interp_p1: { 5284 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 5285 SDValue Glue = M0.getValue(1); 5286 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1), 5287 Op.getOperand(2), Op.getOperand(3), Glue); 5288 } 5289 case Intrinsic::amdgcn_interp_p2: { 5290 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 5291 SDValue Glue = SDValue(M0.getNode(), 1); 5292 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1), 5293 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4), 5294 Glue); 5295 } 5296 case Intrinsic::amdgcn_interp_p1_f16: { 5297 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 5298 SDValue Glue = M0.getValue(1); 5299 if (getSubtarget()->getLDSBankCount() == 16) { 5300 // 16 bank LDS 5301 SDValue S = DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, 5302 DAG.getConstant(2, DL, MVT::i32), // P0 5303 Op.getOperand(2), // Attrchan 5304 Op.getOperand(3), // Attr 5305 Glue); 5306 SDValue Ops[] = { 5307 Op.getOperand(1), // Src0 5308 Op.getOperand(2), // Attrchan 5309 Op.getOperand(3), // Attr 5310 DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers 5311 S, // Src2 - holds two f16 values selected by high 5312 DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers 5313 Op.getOperand(4), // high 5314 DAG.getConstant(0, DL, MVT::i1), // $clamp 5315 DAG.getConstant(0, DL, MVT::i32) // $omod 5316 }; 5317 return DAG.getNode(AMDGPUISD::INTERP_P1LV_F16, DL, MVT::f32, Ops); 5318 } else { 5319 // 32 bank LDS 5320 SDValue Ops[] = { 5321 Op.getOperand(1), // Src0 5322 Op.getOperand(2), // Attrchan 5323 Op.getOperand(3), // Attr 5324 DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers 5325 Op.getOperand(4), // high 5326 DAG.getConstant(0, DL, MVT::i1), // $clamp 5327 DAG.getConstant(0, DL, MVT::i32), // $omod 5328 Glue 5329 }; 5330 return DAG.getNode(AMDGPUISD::INTERP_P1LL_F16, DL, MVT::f32, Ops); 5331 } 5332 } 5333 case Intrinsic::amdgcn_interp_p2_f16: { 5334 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(6)); 5335 SDValue Glue = SDValue(M0.getNode(), 1); 5336 SDValue Ops[] = { 5337 Op.getOperand(2), // Src0 5338 Op.getOperand(3), // Attrchan 5339 Op.getOperand(4), // Attr 5340 DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers 5341 Op.getOperand(1), // Src2 5342 DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers 5343 Op.getOperand(5), // high 5344 DAG.getConstant(0, DL, MVT::i1), // $clamp 5345 Glue 5346 }; 5347 return DAG.getNode(AMDGPUISD::INTERP_P2_F16, DL, MVT::f16, Ops); 5348 } 5349 case Intrinsic::amdgcn_sin: 5350 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 5351 5352 case Intrinsic::amdgcn_cos: 5353 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 5354 5355 case Intrinsic::amdgcn_log_clamp: { 5356 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5357 return SDValue(); 5358 5359 DiagnosticInfoUnsupported BadIntrin( 5360 MF.getFunction(), "intrinsic not supported on subtarget", 5361 DL.getDebugLoc()); 5362 DAG.getContext()->diagnose(BadIntrin); 5363 return DAG.getUNDEF(VT); 5364 } 5365 case Intrinsic::amdgcn_ldexp: 5366 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 5367 Op.getOperand(1), Op.getOperand(2)); 5368 5369 case Intrinsic::amdgcn_fract: 5370 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 5371 5372 case Intrinsic::amdgcn_class: 5373 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 5374 Op.getOperand(1), Op.getOperand(2)); 5375 case Intrinsic::amdgcn_div_fmas: 5376 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 5377 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5378 Op.getOperand(4)); 5379 5380 case Intrinsic::amdgcn_div_fixup: 5381 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 5382 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5383 5384 case Intrinsic::amdgcn_trig_preop: 5385 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 5386 Op.getOperand(1), Op.getOperand(2)); 5387 case Intrinsic::amdgcn_div_scale: { 5388 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 5389 5390 // Translate to the operands expected by the machine instruction. The 5391 // first parameter must be the same as the first instruction. 5392 SDValue Numerator = Op.getOperand(1); 5393 SDValue Denominator = Op.getOperand(2); 5394 5395 // Note this order is opposite of the machine instruction's operations, 5396 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 5397 // intrinsic has the numerator as the first operand to match a normal 5398 // division operation. 5399 5400 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 5401 5402 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 5403 Denominator, Numerator); 5404 } 5405 case Intrinsic::amdgcn_icmp: { 5406 // There is a Pat that handles this variant, so return it as-is. 5407 if (Op.getOperand(1).getValueType() == MVT::i1 && 5408 Op.getConstantOperandVal(2) == 0 && 5409 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 5410 return Op; 5411 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 5412 } 5413 case Intrinsic::amdgcn_fcmp: { 5414 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 5415 } 5416 case Intrinsic::amdgcn_fmed3: 5417 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 5418 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5419 case Intrinsic::amdgcn_fdot2: 5420 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 5421 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5422 Op.getOperand(4)); 5423 case Intrinsic::amdgcn_fmul_legacy: 5424 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 5425 Op.getOperand(1), Op.getOperand(2)); 5426 case Intrinsic::amdgcn_sffbh: 5427 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 5428 case Intrinsic::amdgcn_sbfe: 5429 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 5430 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5431 case Intrinsic::amdgcn_ubfe: 5432 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 5433 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5434 case Intrinsic::amdgcn_cvt_pkrtz: 5435 case Intrinsic::amdgcn_cvt_pknorm_i16: 5436 case Intrinsic::amdgcn_cvt_pknorm_u16: 5437 case Intrinsic::amdgcn_cvt_pk_i16: 5438 case Intrinsic::amdgcn_cvt_pk_u16: { 5439 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 5440 EVT VT = Op.getValueType(); 5441 unsigned Opcode; 5442 5443 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 5444 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 5445 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 5446 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 5447 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 5448 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 5449 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 5450 Opcode = AMDGPUISD::CVT_PK_I16_I32; 5451 else 5452 Opcode = AMDGPUISD::CVT_PK_U16_U32; 5453 5454 if (isTypeLegal(VT)) 5455 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5456 5457 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 5458 Op.getOperand(1), Op.getOperand(2)); 5459 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 5460 } 5461 case Intrinsic::amdgcn_wqm: { 5462 SDValue Src = Op.getOperand(1); 5463 return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src), 5464 0); 5465 } 5466 case Intrinsic::amdgcn_wwm: { 5467 SDValue Src = Op.getOperand(1); 5468 return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src), 5469 0); 5470 } 5471 case Intrinsic::amdgcn_fmad_ftz: 5472 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 5473 Op.getOperand(2), Op.getOperand(3)); 5474 default: 5475 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 5476 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 5477 return lowerImage(Op, ImageDimIntr, DAG); 5478 5479 return Op; 5480 } 5481 } 5482 5483 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 5484 SelectionDAG &DAG) const { 5485 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 5486 SDLoc DL(Op); 5487 5488 switch (IntrID) { 5489 case Intrinsic::amdgcn_ds_ordered_add: 5490 case Intrinsic::amdgcn_ds_ordered_swap: { 5491 MemSDNode *M = cast<MemSDNode>(Op); 5492 SDValue Chain = M->getOperand(0); 5493 SDValue M0 = M->getOperand(2); 5494 SDValue Value = M->getOperand(3); 5495 unsigned OrderedCountIndex = M->getConstantOperandVal(7); 5496 unsigned WaveRelease = M->getConstantOperandVal(8); 5497 unsigned WaveDone = M->getConstantOperandVal(9); 5498 unsigned ShaderType; 5499 unsigned Instruction; 5500 5501 switch (IntrID) { 5502 case Intrinsic::amdgcn_ds_ordered_add: 5503 Instruction = 0; 5504 break; 5505 case Intrinsic::amdgcn_ds_ordered_swap: 5506 Instruction = 1; 5507 break; 5508 } 5509 5510 if (WaveDone && !WaveRelease) 5511 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 5512 5513 switch (DAG.getMachineFunction().getFunction().getCallingConv()) { 5514 case CallingConv::AMDGPU_CS: 5515 case CallingConv::AMDGPU_KERNEL: 5516 ShaderType = 0; 5517 break; 5518 case CallingConv::AMDGPU_PS: 5519 ShaderType = 1; 5520 break; 5521 case CallingConv::AMDGPU_VS: 5522 ShaderType = 2; 5523 break; 5524 case CallingConv::AMDGPU_GS: 5525 ShaderType = 3; 5526 break; 5527 default: 5528 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 5529 } 5530 5531 unsigned Offset0 = OrderedCountIndex << 2; 5532 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 5533 (Instruction << 4); 5534 unsigned Offset = Offset0 | (Offset1 << 8); 5535 5536 SDValue Ops[] = { 5537 Chain, 5538 Value, 5539 DAG.getTargetConstant(Offset, DL, MVT::i16), 5540 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 5541 }; 5542 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 5543 M->getVTList(), Ops, M->getMemoryVT(), 5544 M->getMemOperand()); 5545 } 5546 case Intrinsic::amdgcn_ds_fadd: { 5547 MemSDNode *M = cast<MemSDNode>(Op); 5548 unsigned Opc; 5549 switch (IntrID) { 5550 case Intrinsic::amdgcn_ds_fadd: 5551 Opc = ISD::ATOMIC_LOAD_FADD; 5552 break; 5553 } 5554 5555 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 5556 M->getOperand(0), M->getOperand(2), M->getOperand(3), 5557 M->getMemOperand()); 5558 } 5559 case Intrinsic::amdgcn_atomic_inc: 5560 case Intrinsic::amdgcn_atomic_dec: 5561 case Intrinsic::amdgcn_ds_fmin: 5562 case Intrinsic::amdgcn_ds_fmax: { 5563 MemSDNode *M = cast<MemSDNode>(Op); 5564 unsigned Opc; 5565 switch (IntrID) { 5566 case Intrinsic::amdgcn_atomic_inc: 5567 Opc = AMDGPUISD::ATOMIC_INC; 5568 break; 5569 case Intrinsic::amdgcn_atomic_dec: 5570 Opc = AMDGPUISD::ATOMIC_DEC; 5571 break; 5572 case Intrinsic::amdgcn_ds_fmin: 5573 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 5574 break; 5575 case Intrinsic::amdgcn_ds_fmax: 5576 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 5577 break; 5578 default: 5579 llvm_unreachable("Unknown intrinsic!"); 5580 } 5581 SDValue Ops[] = { 5582 M->getOperand(0), // Chain 5583 M->getOperand(2), // Ptr 5584 M->getOperand(3) // Value 5585 }; 5586 5587 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 5588 M->getMemoryVT(), M->getMemOperand()); 5589 } 5590 case Intrinsic::amdgcn_buffer_load: 5591 case Intrinsic::amdgcn_buffer_load_format: { 5592 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 5593 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 5594 unsigned IdxEn = 1; 5595 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 5596 IdxEn = Idx->getZExtValue() != 0; 5597 SDValue Ops[] = { 5598 Op.getOperand(0), // Chain 5599 Op.getOperand(2), // rsrc 5600 Op.getOperand(3), // vindex 5601 SDValue(), // voffset -- will be set by setBufferOffsets 5602 SDValue(), // soffset -- will be set by setBufferOffsets 5603 SDValue(), // offset -- will be set by setBufferOffsets 5604 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 5605 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 5606 }; 5607 5608 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 5609 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 5610 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 5611 5612 EVT VT = Op.getValueType(); 5613 EVT IntVT = VT.changeTypeToInteger(); 5614 auto *M = cast<MemSDNode>(Op); 5615 EVT LoadVT = Op.getValueType(); 5616 5617 if (LoadVT.getScalarType() == MVT::f16) 5618 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 5619 M, DAG, Ops); 5620 5621 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 5622 if (LoadVT.getScalarType() == MVT::i8 || 5623 LoadVT.getScalarType() == MVT::i16) 5624 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 5625 5626 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 5627 M->getMemOperand(), DAG); 5628 } 5629 case Intrinsic::amdgcn_raw_buffer_load: 5630 case Intrinsic::amdgcn_raw_buffer_load_format: { 5631 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 5632 SDValue Ops[] = { 5633 Op.getOperand(0), // Chain 5634 Op.getOperand(2), // rsrc 5635 DAG.getConstant(0, DL, MVT::i32), // vindex 5636 Offsets.first, // voffset 5637 Op.getOperand(4), // soffset 5638 Offsets.second, // offset 5639 Op.getOperand(5), // cachepolicy 5640 DAG.getConstant(0, DL, MVT::i1), // idxen 5641 }; 5642 5643 unsigned Opc = (IntrID == Intrinsic::amdgcn_raw_buffer_load) ? 5644 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 5645 5646 EVT VT = Op.getValueType(); 5647 EVT IntVT = VT.changeTypeToInteger(); 5648 auto *M = cast<MemSDNode>(Op); 5649 EVT LoadVT = Op.getValueType(); 5650 5651 if (LoadVT.getScalarType() == MVT::f16) 5652 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 5653 M, DAG, Ops); 5654 5655 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 5656 if (LoadVT.getScalarType() == MVT::i8 || 5657 LoadVT.getScalarType() == MVT::i16) 5658 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 5659 5660 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 5661 M->getMemOperand(), DAG); 5662 } 5663 case Intrinsic::amdgcn_struct_buffer_load: 5664 case Intrinsic::amdgcn_struct_buffer_load_format: { 5665 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 5666 SDValue Ops[] = { 5667 Op.getOperand(0), // Chain 5668 Op.getOperand(2), // rsrc 5669 Op.getOperand(3), // vindex 5670 Offsets.first, // voffset 5671 Op.getOperand(5), // soffset 5672 Offsets.second, // offset 5673 Op.getOperand(6), // cachepolicy 5674 DAG.getConstant(1, DL, MVT::i1), // idxen 5675 }; 5676 5677 unsigned Opc = (IntrID == Intrinsic::amdgcn_struct_buffer_load) ? 5678 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 5679 5680 EVT VT = Op.getValueType(); 5681 EVT IntVT = VT.changeTypeToInteger(); 5682 auto *M = cast<MemSDNode>(Op); 5683 EVT LoadVT = Op.getValueType(); 5684 5685 if (LoadVT.getScalarType() == MVT::f16) 5686 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 5687 M, DAG, Ops); 5688 5689 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 5690 if (LoadVT.getScalarType() == MVT::i8 || 5691 LoadVT.getScalarType() == MVT::i16) 5692 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 5693 5694 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 5695 M->getMemOperand(), DAG); 5696 } 5697 case Intrinsic::amdgcn_tbuffer_load: { 5698 MemSDNode *M = cast<MemSDNode>(Op); 5699 EVT LoadVT = Op.getValueType(); 5700 5701 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 5702 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 5703 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 5704 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 5705 unsigned IdxEn = 1; 5706 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 5707 IdxEn = Idx->getZExtValue() != 0; 5708 SDValue Ops[] = { 5709 Op.getOperand(0), // Chain 5710 Op.getOperand(2), // rsrc 5711 Op.getOperand(3), // vindex 5712 Op.getOperand(4), // voffset 5713 Op.getOperand(5), // soffset 5714 Op.getOperand(6), // offset 5715 DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 5716 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 5717 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 5718 }; 5719 5720 if (LoadVT.getScalarType() == MVT::f16) 5721 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 5722 M, DAG, Ops); 5723 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 5724 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 5725 DAG); 5726 } 5727 case Intrinsic::amdgcn_raw_tbuffer_load: { 5728 MemSDNode *M = cast<MemSDNode>(Op); 5729 EVT LoadVT = Op.getValueType(); 5730 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 5731 5732 SDValue Ops[] = { 5733 Op.getOperand(0), // Chain 5734 Op.getOperand(2), // rsrc 5735 DAG.getConstant(0, DL, MVT::i32), // vindex 5736 Offsets.first, // voffset 5737 Op.getOperand(4), // soffset 5738 Offsets.second, // offset 5739 Op.getOperand(5), // format 5740 Op.getOperand(6), // cachepolicy 5741 DAG.getConstant(0, DL, MVT::i1), // idxen 5742 }; 5743 5744 if (LoadVT.getScalarType() == MVT::f16) 5745 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 5746 M, DAG, Ops); 5747 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 5748 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 5749 DAG); 5750 } 5751 case Intrinsic::amdgcn_struct_tbuffer_load: { 5752 MemSDNode *M = cast<MemSDNode>(Op); 5753 EVT LoadVT = Op.getValueType(); 5754 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 5755 5756 SDValue Ops[] = { 5757 Op.getOperand(0), // Chain 5758 Op.getOperand(2), // rsrc 5759 Op.getOperand(3), // vindex 5760 Offsets.first, // voffset 5761 Op.getOperand(5), // soffset 5762 Offsets.second, // offset 5763 Op.getOperand(6), // format 5764 Op.getOperand(7), // cachepolicy 5765 DAG.getConstant(1, DL, MVT::i1), // idxen 5766 }; 5767 5768 if (LoadVT.getScalarType() == MVT::f16) 5769 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 5770 M, DAG, Ops); 5771 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 5772 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 5773 DAG); 5774 } 5775 case Intrinsic::amdgcn_buffer_atomic_swap: 5776 case Intrinsic::amdgcn_buffer_atomic_add: 5777 case Intrinsic::amdgcn_buffer_atomic_sub: 5778 case Intrinsic::amdgcn_buffer_atomic_smin: 5779 case Intrinsic::amdgcn_buffer_atomic_umin: 5780 case Intrinsic::amdgcn_buffer_atomic_smax: 5781 case Intrinsic::amdgcn_buffer_atomic_umax: 5782 case Intrinsic::amdgcn_buffer_atomic_and: 5783 case Intrinsic::amdgcn_buffer_atomic_or: 5784 case Intrinsic::amdgcn_buffer_atomic_xor: { 5785 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 5786 unsigned IdxEn = 1; 5787 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 5788 IdxEn = Idx->getZExtValue() != 0; 5789 SDValue Ops[] = { 5790 Op.getOperand(0), // Chain 5791 Op.getOperand(2), // vdata 5792 Op.getOperand(3), // rsrc 5793 Op.getOperand(4), // vindex 5794 SDValue(), // voffset -- will be set by setBufferOffsets 5795 SDValue(), // soffset -- will be set by setBufferOffsets 5796 SDValue(), // offset -- will be set by setBufferOffsets 5797 DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy 5798 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 5799 }; 5800 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 5801 EVT VT = Op.getValueType(); 5802 5803 auto *M = cast<MemSDNode>(Op); 5804 unsigned Opcode = 0; 5805 5806 switch (IntrID) { 5807 case Intrinsic::amdgcn_buffer_atomic_swap: 5808 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 5809 break; 5810 case Intrinsic::amdgcn_buffer_atomic_add: 5811 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 5812 break; 5813 case Intrinsic::amdgcn_buffer_atomic_sub: 5814 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 5815 break; 5816 case Intrinsic::amdgcn_buffer_atomic_smin: 5817 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 5818 break; 5819 case Intrinsic::amdgcn_buffer_atomic_umin: 5820 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 5821 break; 5822 case Intrinsic::amdgcn_buffer_atomic_smax: 5823 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 5824 break; 5825 case Intrinsic::amdgcn_buffer_atomic_umax: 5826 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 5827 break; 5828 case Intrinsic::amdgcn_buffer_atomic_and: 5829 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 5830 break; 5831 case Intrinsic::amdgcn_buffer_atomic_or: 5832 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 5833 break; 5834 case Intrinsic::amdgcn_buffer_atomic_xor: 5835 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 5836 break; 5837 default: 5838 llvm_unreachable("unhandled atomic opcode"); 5839 } 5840 5841 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 5842 M->getMemOperand()); 5843 } 5844 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 5845 case Intrinsic::amdgcn_raw_buffer_atomic_add: 5846 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 5847 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 5848 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 5849 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 5850 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 5851 case Intrinsic::amdgcn_raw_buffer_atomic_and: 5852 case Intrinsic::amdgcn_raw_buffer_atomic_or: 5853 case Intrinsic::amdgcn_raw_buffer_atomic_xor: { 5854 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 5855 SDValue Ops[] = { 5856 Op.getOperand(0), // Chain 5857 Op.getOperand(2), // vdata 5858 Op.getOperand(3), // rsrc 5859 DAG.getConstant(0, DL, MVT::i32), // vindex 5860 Offsets.first, // voffset 5861 Op.getOperand(5), // soffset 5862 Offsets.second, // offset 5863 Op.getOperand(6), // cachepolicy 5864 DAG.getConstant(0, DL, MVT::i1), // idxen 5865 }; 5866 EVT VT = Op.getValueType(); 5867 5868 auto *M = cast<MemSDNode>(Op); 5869 unsigned Opcode = 0; 5870 5871 switch (IntrID) { 5872 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 5873 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 5874 break; 5875 case Intrinsic::amdgcn_raw_buffer_atomic_add: 5876 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 5877 break; 5878 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 5879 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 5880 break; 5881 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 5882 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 5883 break; 5884 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 5885 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 5886 break; 5887 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 5888 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 5889 break; 5890 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 5891 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 5892 break; 5893 case Intrinsic::amdgcn_raw_buffer_atomic_and: 5894 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 5895 break; 5896 case Intrinsic::amdgcn_raw_buffer_atomic_or: 5897 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 5898 break; 5899 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 5900 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 5901 break; 5902 default: 5903 llvm_unreachable("unhandled atomic opcode"); 5904 } 5905 5906 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 5907 M->getMemOperand()); 5908 } 5909 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 5910 case Intrinsic::amdgcn_struct_buffer_atomic_add: 5911 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 5912 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 5913 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 5914 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 5915 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 5916 case Intrinsic::amdgcn_struct_buffer_atomic_and: 5917 case Intrinsic::amdgcn_struct_buffer_atomic_or: 5918 case Intrinsic::amdgcn_struct_buffer_atomic_xor: { 5919 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 5920 SDValue Ops[] = { 5921 Op.getOperand(0), // Chain 5922 Op.getOperand(2), // vdata 5923 Op.getOperand(3), // rsrc 5924 Op.getOperand(4), // vindex 5925 Offsets.first, // voffset 5926 Op.getOperand(6), // soffset 5927 Offsets.second, // offset 5928 Op.getOperand(7), // cachepolicy 5929 DAG.getConstant(1, DL, MVT::i1), // idxen 5930 }; 5931 EVT VT = Op.getValueType(); 5932 5933 auto *M = cast<MemSDNode>(Op); 5934 unsigned Opcode = 0; 5935 5936 switch (IntrID) { 5937 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 5938 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 5939 break; 5940 case Intrinsic::amdgcn_struct_buffer_atomic_add: 5941 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 5942 break; 5943 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 5944 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 5945 break; 5946 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 5947 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 5948 break; 5949 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 5950 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 5951 break; 5952 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 5953 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 5954 break; 5955 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 5956 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 5957 break; 5958 case Intrinsic::amdgcn_struct_buffer_atomic_and: 5959 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 5960 break; 5961 case Intrinsic::amdgcn_struct_buffer_atomic_or: 5962 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 5963 break; 5964 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 5965 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 5966 break; 5967 default: 5968 llvm_unreachable("unhandled atomic opcode"); 5969 } 5970 5971 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 5972 M->getMemOperand()); 5973 } 5974 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 5975 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 5976 unsigned IdxEn = 1; 5977 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 5978 IdxEn = Idx->getZExtValue() != 0; 5979 SDValue Ops[] = { 5980 Op.getOperand(0), // Chain 5981 Op.getOperand(2), // src 5982 Op.getOperand(3), // cmp 5983 Op.getOperand(4), // rsrc 5984 Op.getOperand(5), // vindex 5985 SDValue(), // voffset -- will be set by setBufferOffsets 5986 SDValue(), // soffset -- will be set by setBufferOffsets 5987 SDValue(), // offset -- will be set by setBufferOffsets 5988 DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy 5989 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 5990 }; 5991 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 5992 EVT VT = Op.getValueType(); 5993 auto *M = cast<MemSDNode>(Op); 5994 5995 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 5996 Op->getVTList(), Ops, VT, M->getMemOperand()); 5997 } 5998 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 5999 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6000 SDValue Ops[] = { 6001 Op.getOperand(0), // Chain 6002 Op.getOperand(2), // src 6003 Op.getOperand(3), // cmp 6004 Op.getOperand(4), // rsrc 6005 DAG.getConstant(0, DL, MVT::i32), // vindex 6006 Offsets.first, // voffset 6007 Op.getOperand(6), // soffset 6008 Offsets.second, // offset 6009 Op.getOperand(7), // cachepolicy 6010 DAG.getConstant(0, DL, MVT::i1), // idxen 6011 }; 6012 EVT VT = Op.getValueType(); 6013 auto *M = cast<MemSDNode>(Op); 6014 6015 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6016 Op->getVTList(), Ops, VT, M->getMemOperand()); 6017 } 6018 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 6019 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 6020 SDValue Ops[] = { 6021 Op.getOperand(0), // Chain 6022 Op.getOperand(2), // src 6023 Op.getOperand(3), // cmp 6024 Op.getOperand(4), // rsrc 6025 Op.getOperand(5), // vindex 6026 Offsets.first, // voffset 6027 Op.getOperand(7), // soffset 6028 Offsets.second, // offset 6029 Op.getOperand(8), // cachepolicy 6030 DAG.getConstant(1, DL, MVT::i1), // idxen 6031 }; 6032 EVT VT = Op.getValueType(); 6033 auto *M = cast<MemSDNode>(Op); 6034 6035 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6036 Op->getVTList(), Ops, VT, M->getMemOperand()); 6037 } 6038 6039 default: 6040 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6041 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 6042 return lowerImage(Op, ImageDimIntr, DAG); 6043 6044 return SDValue(); 6045 } 6046 } 6047 6048 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 6049 // dwordx4 if on SI. 6050 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 6051 SDVTList VTList, 6052 ArrayRef<SDValue> Ops, EVT MemVT, 6053 MachineMemOperand *MMO, 6054 SelectionDAG &DAG) const { 6055 EVT VT = VTList.VTs[0]; 6056 EVT WidenedVT = VT; 6057 EVT WidenedMemVT = MemVT; 6058 if (!Subtarget->hasDwordx3LoadStores() && 6059 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 6060 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 6061 WidenedVT.getVectorElementType(), 4); 6062 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 6063 WidenedMemVT.getVectorElementType(), 4); 6064 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 6065 } 6066 6067 assert(VTList.NumVTs == 2); 6068 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 6069 6070 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 6071 WidenedMemVT, MMO); 6072 if (WidenedVT != VT) { 6073 auto Extract = DAG.getNode( 6074 ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 6075 DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout()))); 6076 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 6077 } 6078 return NewOp; 6079 } 6080 6081 SDValue SITargetLowering::handleD16VData(SDValue VData, 6082 SelectionDAG &DAG) const { 6083 EVT StoreVT = VData.getValueType(); 6084 6085 // No change for f16 and legal vector D16 types. 6086 if (!StoreVT.isVector()) 6087 return VData; 6088 6089 SDLoc DL(VData); 6090 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 6091 6092 if (Subtarget->hasUnpackedD16VMem()) { 6093 // We need to unpack the packed data to store. 6094 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 6095 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 6096 6097 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 6098 StoreVT.getVectorNumElements()); 6099 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 6100 return DAG.UnrollVectorOp(ZExt.getNode()); 6101 } 6102 6103 assert(isTypeLegal(StoreVT)); 6104 return VData; 6105 } 6106 6107 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 6108 SelectionDAG &DAG) const { 6109 SDLoc DL(Op); 6110 SDValue Chain = Op.getOperand(0); 6111 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6112 MachineFunction &MF = DAG.getMachineFunction(); 6113 6114 switch (IntrinsicID) { 6115 case Intrinsic::amdgcn_exp: { 6116 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 6117 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 6118 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8)); 6119 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9)); 6120 6121 const SDValue Ops[] = { 6122 Chain, 6123 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 6124 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 6125 Op.getOperand(4), // src0 6126 Op.getOperand(5), // src1 6127 Op.getOperand(6), // src2 6128 Op.getOperand(7), // src3 6129 DAG.getTargetConstant(0, DL, MVT::i1), // compr 6130 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 6131 }; 6132 6133 unsigned Opc = Done->isNullValue() ? 6134 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 6135 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 6136 } 6137 case Intrinsic::amdgcn_exp_compr: { 6138 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 6139 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 6140 SDValue Src0 = Op.getOperand(4); 6141 SDValue Src1 = Op.getOperand(5); 6142 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 6143 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7)); 6144 6145 SDValue Undef = DAG.getUNDEF(MVT::f32); 6146 const SDValue Ops[] = { 6147 Chain, 6148 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 6149 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 6150 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), 6151 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), 6152 Undef, // src2 6153 Undef, // src3 6154 DAG.getTargetConstant(1, DL, MVT::i1), // compr 6155 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 6156 }; 6157 6158 unsigned Opc = Done->isNullValue() ? 6159 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 6160 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 6161 } 6162 case Intrinsic::amdgcn_s_sendmsg: 6163 case Intrinsic::amdgcn_s_sendmsghalt: { 6164 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ? 6165 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT; 6166 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 6167 SDValue Glue = Chain.getValue(1); 6168 return DAG.getNode(NodeOp, DL, MVT::Other, Chain, 6169 Op.getOperand(2), Glue); 6170 } 6171 case Intrinsic::amdgcn_init_exec: { 6172 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain, 6173 Op.getOperand(2)); 6174 } 6175 case Intrinsic::amdgcn_init_exec_from_input: { 6176 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain, 6177 Op.getOperand(2), Op.getOperand(3)); 6178 } 6179 case Intrinsic::amdgcn_s_barrier: { 6180 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 6181 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 6182 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 6183 if (WGSize <= ST.getWavefrontSize()) 6184 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 6185 Op.getOperand(0)), 0); 6186 } 6187 return SDValue(); 6188 }; 6189 case Intrinsic::amdgcn_tbuffer_store: { 6190 SDValue VData = Op.getOperand(2); 6191 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6192 if (IsD16) 6193 VData = handleD16VData(VData, DAG); 6194 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6195 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6196 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6197 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 6198 unsigned IdxEn = 1; 6199 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6200 IdxEn = Idx->getZExtValue() != 0; 6201 SDValue Ops[] = { 6202 Chain, 6203 VData, // vdata 6204 Op.getOperand(3), // rsrc 6205 Op.getOperand(4), // vindex 6206 Op.getOperand(5), // voffset 6207 Op.getOperand(6), // soffset 6208 Op.getOperand(7), // offset 6209 DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6210 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6211 DAG.getConstant(IdxEn, DL, MVT::i1), // idexen 6212 }; 6213 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6214 AMDGPUISD::TBUFFER_STORE_FORMAT; 6215 MemSDNode *M = cast<MemSDNode>(Op); 6216 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6217 M->getMemoryVT(), M->getMemOperand()); 6218 } 6219 6220 case Intrinsic::amdgcn_struct_tbuffer_store: { 6221 SDValue VData = Op.getOperand(2); 6222 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6223 if (IsD16) 6224 VData = handleD16VData(VData, DAG); 6225 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6226 SDValue Ops[] = { 6227 Chain, 6228 VData, // vdata 6229 Op.getOperand(3), // rsrc 6230 Op.getOperand(4), // vindex 6231 Offsets.first, // voffset 6232 Op.getOperand(6), // soffset 6233 Offsets.second, // offset 6234 Op.getOperand(7), // format 6235 Op.getOperand(8), // cachepolicy 6236 DAG.getConstant(1, DL, MVT::i1), // idexen 6237 }; 6238 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6239 AMDGPUISD::TBUFFER_STORE_FORMAT; 6240 MemSDNode *M = cast<MemSDNode>(Op); 6241 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6242 M->getMemoryVT(), M->getMemOperand()); 6243 } 6244 6245 case Intrinsic::amdgcn_raw_tbuffer_store: { 6246 SDValue VData = Op.getOperand(2); 6247 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6248 if (IsD16) 6249 VData = handleD16VData(VData, DAG); 6250 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6251 SDValue Ops[] = { 6252 Chain, 6253 VData, // vdata 6254 Op.getOperand(3), // rsrc 6255 DAG.getConstant(0, DL, MVT::i32), // vindex 6256 Offsets.first, // voffset 6257 Op.getOperand(5), // soffset 6258 Offsets.second, // offset 6259 Op.getOperand(6), // format 6260 Op.getOperand(7), // cachepolicy 6261 DAG.getConstant(0, DL, MVT::i1), // idexen 6262 }; 6263 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6264 AMDGPUISD::TBUFFER_STORE_FORMAT; 6265 MemSDNode *M = cast<MemSDNode>(Op); 6266 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6267 M->getMemoryVT(), M->getMemOperand()); 6268 } 6269 6270 case Intrinsic::amdgcn_buffer_store: 6271 case Intrinsic::amdgcn_buffer_store_format: { 6272 SDValue VData = Op.getOperand(2); 6273 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6274 if (IsD16) 6275 VData = handleD16VData(VData, DAG); 6276 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6277 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6278 unsigned IdxEn = 1; 6279 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6280 IdxEn = Idx->getZExtValue() != 0; 6281 SDValue Ops[] = { 6282 Chain, 6283 VData, 6284 Op.getOperand(3), // rsrc 6285 Op.getOperand(4), // vindex 6286 SDValue(), // voffset -- will be set by setBufferOffsets 6287 SDValue(), // soffset -- will be set by setBufferOffsets 6288 SDValue(), // offset -- will be set by setBufferOffsets 6289 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6290 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6291 }; 6292 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6293 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 6294 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6295 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6296 MemSDNode *M = cast<MemSDNode>(Op); 6297 6298 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6299 EVT VDataType = VData.getValueType().getScalarType(); 6300 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6301 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6302 6303 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6304 M->getMemoryVT(), M->getMemOperand()); 6305 } 6306 6307 case Intrinsic::amdgcn_raw_buffer_store: 6308 case Intrinsic::amdgcn_raw_buffer_store_format: { 6309 SDValue VData = Op.getOperand(2); 6310 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6311 if (IsD16) 6312 VData = handleD16VData(VData, DAG); 6313 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6314 SDValue Ops[] = { 6315 Chain, 6316 VData, 6317 Op.getOperand(3), // rsrc 6318 DAG.getConstant(0, DL, MVT::i32), // vindex 6319 Offsets.first, // voffset 6320 Op.getOperand(5), // soffset 6321 Offsets.second, // offset 6322 Op.getOperand(6), // cachepolicy 6323 DAG.getConstant(0, DL, MVT::i1), // idxen 6324 }; 6325 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_raw_buffer_store ? 6326 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6327 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6328 MemSDNode *M = cast<MemSDNode>(Op); 6329 6330 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6331 EVT VDataType = VData.getValueType().getScalarType(); 6332 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6333 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6334 6335 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6336 M->getMemoryVT(), M->getMemOperand()); 6337 } 6338 6339 case Intrinsic::amdgcn_struct_buffer_store: 6340 case Intrinsic::amdgcn_struct_buffer_store_format: { 6341 SDValue VData = Op.getOperand(2); 6342 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6343 if (IsD16) 6344 VData = handleD16VData(VData, DAG); 6345 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6346 SDValue Ops[] = { 6347 Chain, 6348 VData, 6349 Op.getOperand(3), // rsrc 6350 Op.getOperand(4), // vindex 6351 Offsets.first, // voffset 6352 Op.getOperand(6), // soffset 6353 Offsets.second, // offset 6354 Op.getOperand(7), // cachepolicy 6355 DAG.getConstant(1, DL, MVT::i1), // idxen 6356 }; 6357 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 6358 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6359 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6360 MemSDNode *M = cast<MemSDNode>(Op); 6361 6362 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6363 EVT VDataType = VData.getValueType().getScalarType(); 6364 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6365 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6366 6367 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6368 M->getMemoryVT(), M->getMemOperand()); 6369 } 6370 6371 default: { 6372 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6373 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6374 return lowerImage(Op, ImageDimIntr, DAG); 6375 6376 return Op; 6377 } 6378 } 6379 } 6380 6381 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 6382 // offset (the offset that is included in bounds checking and swizzling, to be 6383 // split between the instruction's voffset and immoffset fields) and soffset 6384 // (the offset that is excluded from bounds checking and swizzling, to go in 6385 // the instruction's soffset field). This function takes the first kind of 6386 // offset and figures out how to split it between voffset and immoffset. 6387 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 6388 SDValue Offset, SelectionDAG &DAG) const { 6389 SDLoc DL(Offset); 6390 const unsigned MaxImm = 4095; 6391 SDValue N0 = Offset; 6392 ConstantSDNode *C1 = nullptr; 6393 6394 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 6395 N0 = SDValue(); 6396 else if (DAG.isBaseWithConstantOffset(N0)) { 6397 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 6398 N0 = N0.getOperand(0); 6399 } 6400 6401 if (C1) { 6402 unsigned ImmOffset = C1->getZExtValue(); 6403 // If the immediate value is too big for the immoffset field, put the value 6404 // and -4096 into the immoffset field so that the value that is copied/added 6405 // for the voffset field is a multiple of 4096, and it stands more chance 6406 // of being CSEd with the copy/add for another similar load/store. 6407 // However, do not do that rounding down to a multiple of 4096 if that is a 6408 // negative number, as it appears to be illegal to have a negative offset 6409 // in the vgpr, even if adding the immediate offset makes it positive. 6410 unsigned Overflow = ImmOffset & ~MaxImm; 6411 ImmOffset -= Overflow; 6412 if ((int32_t)Overflow < 0) { 6413 Overflow += ImmOffset; 6414 ImmOffset = 0; 6415 } 6416 C1 = cast<ConstantSDNode>(DAG.getConstant(ImmOffset, DL, MVT::i32)); 6417 if (Overflow) { 6418 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 6419 if (!N0) 6420 N0 = OverflowVal; 6421 else { 6422 SDValue Ops[] = { N0, OverflowVal }; 6423 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 6424 } 6425 } 6426 } 6427 if (!N0) 6428 N0 = DAG.getConstant(0, DL, MVT::i32); 6429 if (!C1) 6430 C1 = cast<ConstantSDNode>(DAG.getConstant(0, DL, MVT::i32)); 6431 return {N0, SDValue(C1, 0)}; 6432 } 6433 6434 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 6435 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 6436 // pointed to by Offsets. 6437 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 6438 SelectionDAG &DAG, SDValue *Offsets, 6439 unsigned Align) const { 6440 SDLoc DL(CombinedOffset); 6441 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 6442 uint32_t Imm = C->getZExtValue(); 6443 uint32_t SOffset, ImmOffset; 6444 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 6445 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 6446 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 6447 Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32); 6448 return; 6449 } 6450 } 6451 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 6452 SDValue N0 = CombinedOffset.getOperand(0); 6453 SDValue N1 = CombinedOffset.getOperand(1); 6454 uint32_t SOffset, ImmOffset; 6455 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 6456 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 6457 Subtarget, Align)) { 6458 Offsets[0] = N0; 6459 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 6460 Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32); 6461 return; 6462 } 6463 } 6464 Offsets[0] = CombinedOffset; 6465 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 6466 Offsets[2] = DAG.getConstant(0, DL, MVT::i32); 6467 } 6468 6469 // Handle 8 bit and 16 bit buffer loads 6470 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 6471 EVT LoadVT, SDLoc DL, 6472 ArrayRef<SDValue> Ops, 6473 MemSDNode *M) const { 6474 EVT IntVT = LoadVT.changeTypeToInteger(); 6475 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 6476 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 6477 6478 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 6479 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 6480 Ops, IntVT, 6481 M->getMemOperand()); 6482 SDValue BufferLoadTrunc = DAG.getNode(ISD::TRUNCATE, DL, 6483 LoadVT.getScalarType(), BufferLoad); 6484 return DAG.getMergeValues({BufferLoadTrunc, BufferLoad.getValue(1)}, DL); 6485 } 6486 6487 // Handle 8 bit and 16 bit buffer stores 6488 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 6489 EVT VDataType, SDLoc DL, 6490 SDValue Ops[], 6491 MemSDNode *M) const { 6492 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 6493 Ops[1] = BufferStoreExt; 6494 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 6495 AMDGPUISD::BUFFER_STORE_SHORT; 6496 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 6497 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 6498 M->getMemOperand()); 6499 } 6500 6501 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 6502 ISD::LoadExtType ExtType, SDValue Op, 6503 const SDLoc &SL, EVT VT) { 6504 if (VT.bitsLT(Op.getValueType())) 6505 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 6506 6507 switch (ExtType) { 6508 case ISD::SEXTLOAD: 6509 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 6510 case ISD::ZEXTLOAD: 6511 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 6512 case ISD::EXTLOAD: 6513 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 6514 case ISD::NON_EXTLOAD: 6515 return Op; 6516 } 6517 6518 llvm_unreachable("invalid ext type"); 6519 } 6520 6521 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 6522 SelectionDAG &DAG = DCI.DAG; 6523 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 6524 return SDValue(); 6525 6526 // FIXME: Constant loads should all be marked invariant. 6527 unsigned AS = Ld->getAddressSpace(); 6528 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 6529 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 6530 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 6531 return SDValue(); 6532 6533 // Don't do this early, since it may interfere with adjacent load merging for 6534 // illegal types. We can avoid losing alignment information for exotic types 6535 // pre-legalize. 6536 EVT MemVT = Ld->getMemoryVT(); 6537 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 6538 MemVT.getSizeInBits() >= 32) 6539 return SDValue(); 6540 6541 SDLoc SL(Ld); 6542 6543 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 6544 "unexpected vector extload"); 6545 6546 // TODO: Drop only high part of range. 6547 SDValue Ptr = Ld->getBasePtr(); 6548 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 6549 MVT::i32, SL, Ld->getChain(), Ptr, 6550 Ld->getOffset(), 6551 Ld->getPointerInfo(), MVT::i32, 6552 Ld->getAlignment(), 6553 Ld->getMemOperand()->getFlags(), 6554 Ld->getAAInfo(), 6555 nullptr); // Drop ranges 6556 6557 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 6558 if (MemVT.isFloatingPoint()) { 6559 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 6560 "unexpected fp extload"); 6561 TruncVT = MemVT.changeTypeToInteger(); 6562 } 6563 6564 SDValue Cvt = NewLoad; 6565 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 6566 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 6567 DAG.getValueType(TruncVT)); 6568 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 6569 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 6570 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 6571 } else { 6572 assert(Ld->getExtensionType() == ISD::EXTLOAD); 6573 } 6574 6575 EVT VT = Ld->getValueType(0); 6576 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 6577 6578 DCI.AddToWorklist(Cvt.getNode()); 6579 6580 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 6581 // the appropriate extension from the 32-bit load. 6582 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 6583 DCI.AddToWorklist(Cvt.getNode()); 6584 6585 // Handle conversion back to floating point if necessary. 6586 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 6587 6588 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 6589 } 6590 6591 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 6592 SDLoc DL(Op); 6593 LoadSDNode *Load = cast<LoadSDNode>(Op); 6594 ISD::LoadExtType ExtType = Load->getExtensionType(); 6595 EVT MemVT = Load->getMemoryVT(); 6596 6597 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 6598 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 6599 return SDValue(); 6600 6601 // FIXME: Copied from PPC 6602 // First, load into 32 bits, then truncate to 1 bit. 6603 6604 SDValue Chain = Load->getChain(); 6605 SDValue BasePtr = Load->getBasePtr(); 6606 MachineMemOperand *MMO = Load->getMemOperand(); 6607 6608 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 6609 6610 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 6611 BasePtr, RealMemVT, MMO); 6612 6613 if (!MemVT.isVector()) { 6614 SDValue Ops[] = { 6615 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 6616 NewLD.getValue(1) 6617 }; 6618 6619 return DAG.getMergeValues(Ops, DL); 6620 } 6621 6622 SmallVector<SDValue, 3> Elts; 6623 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 6624 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 6625 DAG.getConstant(I, DL, MVT::i32)); 6626 6627 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 6628 } 6629 6630 SDValue Ops[] = { 6631 DAG.getBuildVector(MemVT, DL, Elts), 6632 NewLD.getValue(1) 6633 }; 6634 6635 return DAG.getMergeValues(Ops, DL); 6636 } 6637 6638 if (!MemVT.isVector()) 6639 return SDValue(); 6640 6641 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 6642 "Custom lowering for non-i32 vectors hasn't been implemented."); 6643 6644 unsigned Alignment = Load->getAlignment(); 6645 unsigned AS = Load->getAddressSpace(); 6646 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 6647 AS, Alignment)) { 6648 SDValue Ops[2]; 6649 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 6650 return DAG.getMergeValues(Ops, DL); 6651 } 6652 6653 MachineFunction &MF = DAG.getMachineFunction(); 6654 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 6655 // If there is a possibilty that flat instruction access scratch memory 6656 // then we need to use the same legalization rules we use for private. 6657 if (AS == AMDGPUAS::FLAT_ADDRESS) 6658 AS = MFI->hasFlatScratchInit() ? 6659 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 6660 6661 unsigned NumElements = MemVT.getVectorNumElements(); 6662 6663 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 6664 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 6665 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 6666 if (MemVT.isPow2VectorType()) 6667 return SDValue(); 6668 if (NumElements == 3) 6669 return WidenVectorLoad(Op, DAG); 6670 return SplitVectorLoad(Op, DAG); 6671 } 6672 // Non-uniform loads will be selected to MUBUF instructions, so they 6673 // have the same legalization requirements as global and private 6674 // loads. 6675 // 6676 } 6677 6678 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 6679 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 6680 AS == AMDGPUAS::GLOBAL_ADDRESS) { 6681 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 6682 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 6683 Alignment >= 4 && NumElements < 32) { 6684 if (MemVT.isPow2VectorType()) 6685 return SDValue(); 6686 if (NumElements == 3) 6687 return WidenVectorLoad(Op, DAG); 6688 return SplitVectorLoad(Op, DAG); 6689 } 6690 // Non-uniform loads will be selected to MUBUF instructions, so they 6691 // have the same legalization requirements as global and private 6692 // loads. 6693 // 6694 } 6695 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 6696 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 6697 AS == AMDGPUAS::GLOBAL_ADDRESS || 6698 AS == AMDGPUAS::FLAT_ADDRESS) { 6699 if (NumElements > 4) 6700 return SplitVectorLoad(Op, DAG); 6701 // v3 loads not supported on SI. 6702 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 6703 return WidenVectorLoad(Op, DAG); 6704 // v3 and v4 loads are supported for private and global memory. 6705 return SDValue(); 6706 } 6707 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 6708 // Depending on the setting of the private_element_size field in the 6709 // resource descriptor, we can only make private accesses up to a certain 6710 // size. 6711 switch (Subtarget->getMaxPrivateElementSize()) { 6712 case 4: 6713 return scalarizeVectorLoad(Load, DAG); 6714 case 8: 6715 if (NumElements > 2) 6716 return SplitVectorLoad(Op, DAG); 6717 return SDValue(); 6718 case 16: 6719 // Same as global/flat 6720 if (NumElements > 4) 6721 return SplitVectorLoad(Op, DAG); 6722 // v3 loads not supported on SI. 6723 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 6724 return WidenVectorLoad(Op, DAG); 6725 return SDValue(); 6726 default: 6727 llvm_unreachable("unsupported private_element_size"); 6728 } 6729 } else if (AS == AMDGPUAS::LOCAL_ADDRESS) { 6730 // Use ds_read_b128 if possible. 6731 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 6732 MemVT.getStoreSize() == 16) 6733 return SDValue(); 6734 6735 if (NumElements > 2) 6736 return SplitVectorLoad(Op, DAG); 6737 6738 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 6739 // address is negative, then the instruction is incorrectly treated as 6740 // out-of-bounds even if base + offsets is in bounds. Split vectorized 6741 // loads here to avoid emitting ds_read2_b32. We may re-combine the 6742 // load later in the SILoadStoreOptimizer. 6743 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 6744 NumElements == 2 && MemVT.getStoreSize() == 8 && 6745 Load->getAlignment() < 8) { 6746 return SplitVectorLoad(Op, DAG); 6747 } 6748 } 6749 return SDValue(); 6750 } 6751 6752 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 6753 EVT VT = Op.getValueType(); 6754 assert(VT.getSizeInBits() == 64); 6755 6756 SDLoc DL(Op); 6757 SDValue Cond = Op.getOperand(0); 6758 6759 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 6760 SDValue One = DAG.getConstant(1, DL, MVT::i32); 6761 6762 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 6763 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 6764 6765 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 6766 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 6767 6768 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 6769 6770 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 6771 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 6772 6773 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 6774 6775 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 6776 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 6777 } 6778 6779 // Catch division cases where we can use shortcuts with rcp and rsq 6780 // instructions. 6781 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 6782 SelectionDAG &DAG) const { 6783 SDLoc SL(Op); 6784 SDValue LHS = Op.getOperand(0); 6785 SDValue RHS = Op.getOperand(1); 6786 EVT VT = Op.getValueType(); 6787 const SDNodeFlags Flags = Op->getFlags(); 6788 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal(); 6789 6790 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals()) 6791 return SDValue(); 6792 6793 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 6794 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) { 6795 if (CLHS->isExactlyValue(1.0)) { 6796 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 6797 // the CI documentation has a worst case error of 1 ulp. 6798 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 6799 // use it as long as we aren't trying to use denormals. 6800 // 6801 // v_rcp_f16 and v_rsq_f16 DO support denormals. 6802 6803 // 1.0 / sqrt(x) -> rsq(x) 6804 6805 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 6806 // error seems really high at 2^29 ULP. 6807 if (RHS.getOpcode() == ISD::FSQRT) 6808 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 6809 6810 // 1.0 / x -> rcp(x) 6811 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 6812 } 6813 6814 // Same as for 1.0, but expand the sign out of the constant. 6815 if (CLHS->isExactlyValue(-1.0)) { 6816 // -1.0 / x -> rcp (fneg x) 6817 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 6818 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 6819 } 6820 } 6821 } 6822 6823 if (Unsafe) { 6824 // Turn into multiply by the reciprocal. 6825 // x / y -> x * (1.0 / y) 6826 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 6827 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 6828 } 6829 6830 return SDValue(); 6831 } 6832 6833 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 6834 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 6835 if (GlueChain->getNumValues() <= 1) { 6836 return DAG.getNode(Opcode, SL, VT, A, B); 6837 } 6838 6839 assert(GlueChain->getNumValues() == 3); 6840 6841 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 6842 switch (Opcode) { 6843 default: llvm_unreachable("no chain equivalent for opcode"); 6844 case ISD::FMUL: 6845 Opcode = AMDGPUISD::FMUL_W_CHAIN; 6846 break; 6847 } 6848 6849 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 6850 GlueChain.getValue(2)); 6851 } 6852 6853 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 6854 EVT VT, SDValue A, SDValue B, SDValue C, 6855 SDValue GlueChain) { 6856 if (GlueChain->getNumValues() <= 1) { 6857 return DAG.getNode(Opcode, SL, VT, A, B, C); 6858 } 6859 6860 assert(GlueChain->getNumValues() == 3); 6861 6862 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 6863 switch (Opcode) { 6864 default: llvm_unreachable("no chain equivalent for opcode"); 6865 case ISD::FMA: 6866 Opcode = AMDGPUISD::FMA_W_CHAIN; 6867 break; 6868 } 6869 6870 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 6871 GlueChain.getValue(2)); 6872 } 6873 6874 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 6875 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 6876 return FastLowered; 6877 6878 SDLoc SL(Op); 6879 SDValue Src0 = Op.getOperand(0); 6880 SDValue Src1 = Op.getOperand(1); 6881 6882 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 6883 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 6884 6885 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 6886 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 6887 6888 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 6889 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 6890 6891 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 6892 } 6893 6894 // Faster 2.5 ULP division that does not support denormals. 6895 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 6896 SDLoc SL(Op); 6897 SDValue LHS = Op.getOperand(1); 6898 SDValue RHS = Op.getOperand(2); 6899 6900 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 6901 6902 const APFloat K0Val(BitsToFloat(0x6f800000)); 6903 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 6904 6905 const APFloat K1Val(BitsToFloat(0x2f800000)); 6906 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 6907 6908 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 6909 6910 EVT SetCCVT = 6911 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 6912 6913 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 6914 6915 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 6916 6917 // TODO: Should this propagate fast-math-flags? 6918 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 6919 6920 // rcp does not support denormals. 6921 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 6922 6923 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 6924 6925 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 6926 } 6927 6928 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 6929 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 6930 return FastLowered; 6931 6932 SDLoc SL(Op); 6933 SDValue LHS = Op.getOperand(0); 6934 SDValue RHS = Op.getOperand(1); 6935 6936 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 6937 6938 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 6939 6940 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 6941 RHS, RHS, LHS); 6942 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 6943 LHS, RHS, LHS); 6944 6945 // Denominator is scaled to not be denormal, so using rcp is ok. 6946 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 6947 DenominatorScaled); 6948 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 6949 DenominatorScaled); 6950 6951 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 6952 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 6953 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 6954 6955 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 6956 6957 if (!Subtarget->hasFP32Denormals()) { 6958 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 6959 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 6960 SL, MVT::i32); 6961 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 6962 DAG.getEntryNode(), 6963 EnableDenormValue, BitField); 6964 SDValue Ops[3] = { 6965 NegDivScale0, 6966 EnableDenorm.getValue(0), 6967 EnableDenorm.getValue(1) 6968 }; 6969 6970 NegDivScale0 = DAG.getMergeValues(Ops, SL); 6971 } 6972 6973 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 6974 ApproxRcp, One, NegDivScale0); 6975 6976 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 6977 ApproxRcp, Fma0); 6978 6979 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 6980 Fma1, Fma1); 6981 6982 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 6983 NumeratorScaled, Mul); 6984 6985 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 6986 6987 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 6988 NumeratorScaled, Fma3); 6989 6990 if (!Subtarget->hasFP32Denormals()) { 6991 const SDValue DisableDenormValue = 6992 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 6993 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 6994 Fma4.getValue(1), 6995 DisableDenormValue, 6996 BitField, 6997 Fma4.getValue(2)); 6998 6999 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 7000 DisableDenorm, DAG.getRoot()); 7001 DAG.setRoot(OutputChain); 7002 } 7003 7004 SDValue Scale = NumeratorScaled.getValue(1); 7005 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 7006 Fma4, Fma1, Fma3, Scale); 7007 7008 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 7009 } 7010 7011 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 7012 if (DAG.getTarget().Options.UnsafeFPMath) 7013 return lowerFastUnsafeFDIV(Op, DAG); 7014 7015 SDLoc SL(Op); 7016 SDValue X = Op.getOperand(0); 7017 SDValue Y = Op.getOperand(1); 7018 7019 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 7020 7021 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 7022 7023 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 7024 7025 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 7026 7027 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 7028 7029 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 7030 7031 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 7032 7033 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 7034 7035 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 7036 7037 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 7038 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 7039 7040 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 7041 NegDivScale0, Mul, DivScale1); 7042 7043 SDValue Scale; 7044 7045 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 7046 // Workaround a hardware bug on SI where the condition output from div_scale 7047 // is not usable. 7048 7049 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 7050 7051 // Figure out if the scale to use for div_fmas. 7052 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 7053 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 7054 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 7055 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 7056 7057 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 7058 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 7059 7060 SDValue Scale0Hi 7061 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 7062 SDValue Scale1Hi 7063 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 7064 7065 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 7066 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 7067 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 7068 } else { 7069 Scale = DivScale1.getValue(1); 7070 } 7071 7072 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 7073 Fma4, Fma3, Mul, Scale); 7074 7075 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 7076 } 7077 7078 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 7079 EVT VT = Op.getValueType(); 7080 7081 if (VT == MVT::f32) 7082 return LowerFDIV32(Op, DAG); 7083 7084 if (VT == MVT::f64) 7085 return LowerFDIV64(Op, DAG); 7086 7087 if (VT == MVT::f16) 7088 return LowerFDIV16(Op, DAG); 7089 7090 llvm_unreachable("Unexpected type for fdiv"); 7091 } 7092 7093 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7094 SDLoc DL(Op); 7095 StoreSDNode *Store = cast<StoreSDNode>(Op); 7096 EVT VT = Store->getMemoryVT(); 7097 7098 if (VT == MVT::i1) { 7099 return DAG.getTruncStore(Store->getChain(), DL, 7100 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 7101 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 7102 } 7103 7104 assert(VT.isVector() && 7105 Store->getValue().getValueType().getScalarType() == MVT::i32); 7106 7107 unsigned AS = Store->getAddressSpace(); 7108 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 7109 AS, Store->getAlignment())) { 7110 return expandUnalignedStore(Store, DAG); 7111 } 7112 7113 MachineFunction &MF = DAG.getMachineFunction(); 7114 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7115 // If there is a possibilty that flat instruction access scratch memory 7116 // then we need to use the same legalization rules we use for private. 7117 if (AS == AMDGPUAS::FLAT_ADDRESS) 7118 AS = MFI->hasFlatScratchInit() ? 7119 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7120 7121 unsigned NumElements = VT.getVectorNumElements(); 7122 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 7123 AS == AMDGPUAS::FLAT_ADDRESS) { 7124 if (NumElements > 4) 7125 return SplitVectorStore(Op, DAG); 7126 // v3 stores not supported on SI. 7127 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7128 return SplitVectorStore(Op, DAG); 7129 return SDValue(); 7130 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7131 switch (Subtarget->getMaxPrivateElementSize()) { 7132 case 4: 7133 return scalarizeVectorStore(Store, DAG); 7134 case 8: 7135 if (NumElements > 2) 7136 return SplitVectorStore(Op, DAG); 7137 return SDValue(); 7138 case 16: 7139 if (NumElements > 4 || NumElements == 3) 7140 return SplitVectorStore(Op, DAG); 7141 return SDValue(); 7142 default: 7143 llvm_unreachable("unsupported private_element_size"); 7144 } 7145 } else if (AS == AMDGPUAS::LOCAL_ADDRESS) { 7146 // Use ds_write_b128 if possible. 7147 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 7148 VT.getStoreSize() == 16 && NumElements != 3) 7149 return SDValue(); 7150 7151 if (NumElements > 2) 7152 return SplitVectorStore(Op, DAG); 7153 7154 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7155 // address is negative, then the instruction is incorrectly treated as 7156 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7157 // stores here to avoid emitting ds_write2_b32. We may re-combine the 7158 // store later in the SILoadStoreOptimizer. 7159 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7160 NumElements == 2 && VT.getStoreSize() == 8 && 7161 Store->getAlignment() < 8) { 7162 return SplitVectorStore(Op, DAG); 7163 } 7164 7165 return SDValue(); 7166 } else { 7167 llvm_unreachable("unhandled address space"); 7168 } 7169 } 7170 7171 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 7172 SDLoc DL(Op); 7173 EVT VT = Op.getValueType(); 7174 SDValue Arg = Op.getOperand(0); 7175 SDValue TrigVal; 7176 7177 // TODO: Should this propagate fast-math-flags? 7178 7179 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT); 7180 7181 if (Subtarget->hasTrigReducedRange()) { 7182 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7183 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal); 7184 } else { 7185 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7186 } 7187 7188 switch (Op.getOpcode()) { 7189 case ISD::FCOS: 7190 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal); 7191 case ISD::FSIN: 7192 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal); 7193 default: 7194 llvm_unreachable("Wrong trig opcode"); 7195 } 7196 } 7197 7198 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 7199 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 7200 assert(AtomicNode->isCompareAndSwap()); 7201 unsigned AS = AtomicNode->getAddressSpace(); 7202 7203 // No custom lowering required for local address space 7204 if (!isFlatGlobalAddrSpace(AS)) 7205 return Op; 7206 7207 // Non-local address space requires custom lowering for atomic compare 7208 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 7209 SDLoc DL(Op); 7210 SDValue ChainIn = Op.getOperand(0); 7211 SDValue Addr = Op.getOperand(1); 7212 SDValue Old = Op.getOperand(2); 7213 SDValue New = Op.getOperand(3); 7214 EVT VT = Op.getValueType(); 7215 MVT SimpleVT = VT.getSimpleVT(); 7216 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 7217 7218 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 7219 SDValue Ops[] = { ChainIn, Addr, NewOld }; 7220 7221 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 7222 Ops, VT, AtomicNode->getMemOperand()); 7223 } 7224 7225 //===----------------------------------------------------------------------===// 7226 // Custom DAG optimizations 7227 //===----------------------------------------------------------------------===// 7228 7229 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 7230 DAGCombinerInfo &DCI) const { 7231 EVT VT = N->getValueType(0); 7232 EVT ScalarVT = VT.getScalarType(); 7233 if (ScalarVT != MVT::f32) 7234 return SDValue(); 7235 7236 SelectionDAG &DAG = DCI.DAG; 7237 SDLoc DL(N); 7238 7239 SDValue Src = N->getOperand(0); 7240 EVT SrcVT = Src.getValueType(); 7241 7242 // TODO: We could try to match extracting the higher bytes, which would be 7243 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 7244 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 7245 // about in practice. 7246 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 7247 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 7248 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 7249 DCI.AddToWorklist(Cvt.getNode()); 7250 return Cvt; 7251 } 7252 } 7253 7254 return SDValue(); 7255 } 7256 7257 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 7258 7259 // This is a variant of 7260 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 7261 // 7262 // The normal DAG combiner will do this, but only if the add has one use since 7263 // that would increase the number of instructions. 7264 // 7265 // This prevents us from seeing a constant offset that can be folded into a 7266 // memory instruction's addressing mode. If we know the resulting add offset of 7267 // a pointer can be folded into an addressing offset, we can replace the pointer 7268 // operand with the add of new constant offset. This eliminates one of the uses, 7269 // and may allow the remaining use to also be simplified. 7270 // 7271 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 7272 unsigned AddrSpace, 7273 EVT MemVT, 7274 DAGCombinerInfo &DCI) const { 7275 SDValue N0 = N->getOperand(0); 7276 SDValue N1 = N->getOperand(1); 7277 7278 // We only do this to handle cases where it's profitable when there are 7279 // multiple uses of the add, so defer to the standard combine. 7280 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 7281 N0->hasOneUse()) 7282 return SDValue(); 7283 7284 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 7285 if (!CN1) 7286 return SDValue(); 7287 7288 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7289 if (!CAdd) 7290 return SDValue(); 7291 7292 // If the resulting offset is too large, we can't fold it into the addressing 7293 // mode offset. 7294 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 7295 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 7296 7297 AddrMode AM; 7298 AM.HasBaseReg = true; 7299 AM.BaseOffs = Offset.getSExtValue(); 7300 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 7301 return SDValue(); 7302 7303 SelectionDAG &DAG = DCI.DAG; 7304 SDLoc SL(N); 7305 EVT VT = N->getValueType(0); 7306 7307 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 7308 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 7309 7310 SDNodeFlags Flags; 7311 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 7312 (N0.getOpcode() == ISD::OR || 7313 N0->getFlags().hasNoUnsignedWrap())); 7314 7315 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 7316 } 7317 7318 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 7319 DAGCombinerInfo &DCI) const { 7320 SDValue Ptr = N->getBasePtr(); 7321 SelectionDAG &DAG = DCI.DAG; 7322 SDLoc SL(N); 7323 7324 // TODO: We could also do this for multiplies. 7325 if (Ptr.getOpcode() == ISD::SHL) { 7326 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 7327 N->getMemoryVT(), DCI); 7328 if (NewPtr) { 7329 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 7330 7331 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 7332 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 7333 } 7334 } 7335 7336 return SDValue(); 7337 } 7338 7339 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 7340 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 7341 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 7342 (Opc == ISD::XOR && Val == 0); 7343 } 7344 7345 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 7346 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 7347 // integer combine opportunities since most 64-bit operations are decomposed 7348 // this way. TODO: We won't want this for SALU especially if it is an inline 7349 // immediate. 7350 SDValue SITargetLowering::splitBinaryBitConstantOp( 7351 DAGCombinerInfo &DCI, 7352 const SDLoc &SL, 7353 unsigned Opc, SDValue LHS, 7354 const ConstantSDNode *CRHS) const { 7355 uint64_t Val = CRHS->getZExtValue(); 7356 uint32_t ValLo = Lo_32(Val); 7357 uint32_t ValHi = Hi_32(Val); 7358 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 7359 7360 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 7361 bitOpWithConstantIsReducible(Opc, ValHi)) || 7362 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 7363 // If we need to materialize a 64-bit immediate, it will be split up later 7364 // anyway. Avoid creating the harder to understand 64-bit immediate 7365 // materialization. 7366 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 7367 } 7368 7369 return SDValue(); 7370 } 7371 7372 // Returns true if argument is a boolean value which is not serialized into 7373 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 7374 static bool isBoolSGPR(SDValue V) { 7375 if (V.getValueType() != MVT::i1) 7376 return false; 7377 switch (V.getOpcode()) { 7378 default: break; 7379 case ISD::SETCC: 7380 case ISD::AND: 7381 case ISD::OR: 7382 case ISD::XOR: 7383 case AMDGPUISD::FP_CLASS: 7384 return true; 7385 } 7386 return false; 7387 } 7388 7389 // If a constant has all zeroes or all ones within each byte return it. 7390 // Otherwise return 0. 7391 static uint32_t getConstantPermuteMask(uint32_t C) { 7392 // 0xff for any zero byte in the mask 7393 uint32_t ZeroByteMask = 0; 7394 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 7395 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 7396 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 7397 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 7398 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 7399 if ((NonZeroByteMask & C) != NonZeroByteMask) 7400 return 0; // Partial bytes selected. 7401 return C; 7402 } 7403 7404 // Check if a node selects whole bytes from its operand 0 starting at a byte 7405 // boundary while masking the rest. Returns select mask as in the v_perm_b32 7406 // or -1 if not succeeded. 7407 // Note byte select encoding: 7408 // value 0-3 selects corresponding source byte; 7409 // value 0xc selects zero; 7410 // value 0xff selects 0xff. 7411 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 7412 assert(V.getValueSizeInBits() == 32); 7413 7414 if (V.getNumOperands() != 2) 7415 return ~0; 7416 7417 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 7418 if (!N1) 7419 return ~0; 7420 7421 uint32_t C = N1->getZExtValue(); 7422 7423 switch (V.getOpcode()) { 7424 default: 7425 break; 7426 case ISD::AND: 7427 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 7428 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 7429 } 7430 break; 7431 7432 case ISD::OR: 7433 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 7434 return (0x03020100 & ~ConstMask) | ConstMask; 7435 } 7436 break; 7437 7438 case ISD::SHL: 7439 if (C % 8) 7440 return ~0; 7441 7442 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 7443 7444 case ISD::SRL: 7445 if (C % 8) 7446 return ~0; 7447 7448 return uint32_t(0x0c0c0c0c03020100ull >> C); 7449 } 7450 7451 return ~0; 7452 } 7453 7454 SDValue SITargetLowering::performAndCombine(SDNode *N, 7455 DAGCombinerInfo &DCI) const { 7456 if (DCI.isBeforeLegalize()) 7457 return SDValue(); 7458 7459 SelectionDAG &DAG = DCI.DAG; 7460 EVT VT = N->getValueType(0); 7461 SDValue LHS = N->getOperand(0); 7462 SDValue RHS = N->getOperand(1); 7463 7464 7465 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 7466 if (VT == MVT::i64 && CRHS) { 7467 if (SDValue Split 7468 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 7469 return Split; 7470 } 7471 7472 if (CRHS && VT == MVT::i32) { 7473 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 7474 // nb = number of trailing zeroes in mask 7475 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 7476 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 7477 uint64_t Mask = CRHS->getZExtValue(); 7478 unsigned Bits = countPopulation(Mask); 7479 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 7480 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 7481 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 7482 unsigned Shift = CShift->getZExtValue(); 7483 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 7484 unsigned Offset = NB + Shift; 7485 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 7486 SDLoc SL(N); 7487 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 7488 LHS->getOperand(0), 7489 DAG.getConstant(Offset, SL, MVT::i32), 7490 DAG.getConstant(Bits, SL, MVT::i32)); 7491 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 7492 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 7493 DAG.getValueType(NarrowVT)); 7494 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 7495 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 7496 return Shl; 7497 } 7498 } 7499 } 7500 7501 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 7502 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 7503 isa<ConstantSDNode>(LHS.getOperand(2))) { 7504 uint32_t Sel = getConstantPermuteMask(Mask); 7505 if (!Sel) 7506 return SDValue(); 7507 7508 // Select 0xc for all zero bytes 7509 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 7510 SDLoc DL(N); 7511 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 7512 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 7513 } 7514 } 7515 7516 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 7517 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 7518 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 7519 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7520 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 7521 7522 SDValue X = LHS.getOperand(0); 7523 SDValue Y = RHS.getOperand(0); 7524 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 7525 return SDValue(); 7526 7527 if (LCC == ISD::SETO) { 7528 if (X != LHS.getOperand(1)) 7529 return SDValue(); 7530 7531 if (RCC == ISD::SETUNE) { 7532 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 7533 if (!C1 || !C1->isInfinity() || C1->isNegative()) 7534 return SDValue(); 7535 7536 const uint32_t Mask = SIInstrFlags::N_NORMAL | 7537 SIInstrFlags::N_SUBNORMAL | 7538 SIInstrFlags::N_ZERO | 7539 SIInstrFlags::P_ZERO | 7540 SIInstrFlags::P_SUBNORMAL | 7541 SIInstrFlags::P_NORMAL; 7542 7543 static_assert(((~(SIInstrFlags::S_NAN | 7544 SIInstrFlags::Q_NAN | 7545 SIInstrFlags::N_INFINITY | 7546 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 7547 "mask not equal"); 7548 7549 SDLoc DL(N); 7550 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 7551 X, DAG.getConstant(Mask, DL, MVT::i32)); 7552 } 7553 } 7554 } 7555 7556 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 7557 std::swap(LHS, RHS); 7558 7559 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 7560 RHS.hasOneUse()) { 7561 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7562 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 7563 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 7564 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 7565 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 7566 (RHS.getOperand(0) == LHS.getOperand(0) && 7567 LHS.getOperand(0) == LHS.getOperand(1))) { 7568 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 7569 unsigned NewMask = LCC == ISD::SETO ? 7570 Mask->getZExtValue() & ~OrdMask : 7571 Mask->getZExtValue() & OrdMask; 7572 7573 SDLoc DL(N); 7574 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 7575 DAG.getConstant(NewMask, DL, MVT::i32)); 7576 } 7577 } 7578 7579 if (VT == MVT::i32 && 7580 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 7581 // and x, (sext cc from i1) => select cc, x, 0 7582 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 7583 std::swap(LHS, RHS); 7584 if (isBoolSGPR(RHS.getOperand(0))) 7585 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 7586 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 7587 } 7588 7589 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 7590 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 7591 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 7592 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 7593 uint32_t LHSMask = getPermuteMask(DAG, LHS); 7594 uint32_t RHSMask = getPermuteMask(DAG, RHS); 7595 if (LHSMask != ~0u && RHSMask != ~0u) { 7596 // Canonicalize the expression in an attempt to have fewer unique masks 7597 // and therefore fewer registers used to hold the masks. 7598 if (LHSMask > RHSMask) { 7599 std::swap(LHSMask, RHSMask); 7600 std::swap(LHS, RHS); 7601 } 7602 7603 // Select 0xc for each lane used from source operand. Zero has 0xc mask 7604 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 7605 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 7606 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 7607 7608 // Check of we need to combine values from two sources within a byte. 7609 if (!(LHSUsedLanes & RHSUsedLanes) && 7610 // If we select high and lower word keep it for SDWA. 7611 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 7612 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 7613 // Each byte in each mask is either selector mask 0-3, or has higher 7614 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 7615 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 7616 // mask which is not 0xff wins. By anding both masks we have a correct 7617 // result except that 0x0c shall be corrected to give 0x0c only. 7618 uint32_t Mask = LHSMask & RHSMask; 7619 for (unsigned I = 0; I < 32; I += 8) { 7620 uint32_t ByteSel = 0xff << I; 7621 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 7622 Mask &= (0x0c << I) & 0xffffffff; 7623 } 7624 7625 // Add 4 to each active LHS lane. It will not affect any existing 0xff 7626 // or 0x0c. 7627 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 7628 SDLoc DL(N); 7629 7630 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 7631 LHS.getOperand(0), RHS.getOperand(0), 7632 DAG.getConstant(Sel, DL, MVT::i32)); 7633 } 7634 } 7635 } 7636 7637 return SDValue(); 7638 } 7639 7640 SDValue SITargetLowering::performOrCombine(SDNode *N, 7641 DAGCombinerInfo &DCI) const { 7642 SelectionDAG &DAG = DCI.DAG; 7643 SDValue LHS = N->getOperand(0); 7644 SDValue RHS = N->getOperand(1); 7645 7646 EVT VT = N->getValueType(0); 7647 if (VT == MVT::i1) { 7648 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 7649 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 7650 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 7651 SDValue Src = LHS.getOperand(0); 7652 if (Src != RHS.getOperand(0)) 7653 return SDValue(); 7654 7655 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 7656 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 7657 if (!CLHS || !CRHS) 7658 return SDValue(); 7659 7660 // Only 10 bits are used. 7661 static const uint32_t MaxMask = 0x3ff; 7662 7663 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 7664 SDLoc DL(N); 7665 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 7666 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 7667 } 7668 7669 return SDValue(); 7670 } 7671 7672 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 7673 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 7674 LHS.getOpcode() == AMDGPUISD::PERM && 7675 isa<ConstantSDNode>(LHS.getOperand(2))) { 7676 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 7677 if (!Sel) 7678 return SDValue(); 7679 7680 Sel |= LHS.getConstantOperandVal(2); 7681 SDLoc DL(N); 7682 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 7683 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 7684 } 7685 7686 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 7687 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 7688 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 7689 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 7690 uint32_t LHSMask = getPermuteMask(DAG, LHS); 7691 uint32_t RHSMask = getPermuteMask(DAG, RHS); 7692 if (LHSMask != ~0u && RHSMask != ~0u) { 7693 // Canonicalize the expression in an attempt to have fewer unique masks 7694 // and therefore fewer registers used to hold the masks. 7695 if (LHSMask > RHSMask) { 7696 std::swap(LHSMask, RHSMask); 7697 std::swap(LHS, RHS); 7698 } 7699 7700 // Select 0xc for each lane used from source operand. Zero has 0xc mask 7701 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 7702 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 7703 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 7704 7705 // Check of we need to combine values from two sources within a byte. 7706 if (!(LHSUsedLanes & RHSUsedLanes) && 7707 // If we select high and lower word keep it for SDWA. 7708 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 7709 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 7710 // Kill zero bytes selected by other mask. Zero value is 0xc. 7711 LHSMask &= ~RHSUsedLanes; 7712 RHSMask &= ~LHSUsedLanes; 7713 // Add 4 to each active LHS lane 7714 LHSMask |= LHSUsedLanes & 0x04040404; 7715 // Combine masks 7716 uint32_t Sel = LHSMask | RHSMask; 7717 SDLoc DL(N); 7718 7719 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 7720 LHS.getOperand(0), RHS.getOperand(0), 7721 DAG.getConstant(Sel, DL, MVT::i32)); 7722 } 7723 } 7724 } 7725 7726 if (VT != MVT::i64) 7727 return SDValue(); 7728 7729 // TODO: This could be a generic combine with a predicate for extracting the 7730 // high half of an integer being free. 7731 7732 // (or i64:x, (zero_extend i32:y)) -> 7733 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 7734 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 7735 RHS.getOpcode() != ISD::ZERO_EXTEND) 7736 std::swap(LHS, RHS); 7737 7738 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 7739 SDValue ExtSrc = RHS.getOperand(0); 7740 EVT SrcVT = ExtSrc.getValueType(); 7741 if (SrcVT == MVT::i32) { 7742 SDLoc SL(N); 7743 SDValue LowLHS, HiBits; 7744 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 7745 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 7746 7747 DCI.AddToWorklist(LowOr.getNode()); 7748 DCI.AddToWorklist(HiBits.getNode()); 7749 7750 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 7751 LowOr, HiBits); 7752 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 7753 } 7754 } 7755 7756 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7757 if (CRHS) { 7758 if (SDValue Split 7759 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 7760 return Split; 7761 } 7762 7763 return SDValue(); 7764 } 7765 7766 SDValue SITargetLowering::performXorCombine(SDNode *N, 7767 DAGCombinerInfo &DCI) const { 7768 EVT VT = N->getValueType(0); 7769 if (VT != MVT::i64) 7770 return SDValue(); 7771 7772 SDValue LHS = N->getOperand(0); 7773 SDValue RHS = N->getOperand(1); 7774 7775 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 7776 if (CRHS) { 7777 if (SDValue Split 7778 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 7779 return Split; 7780 } 7781 7782 return SDValue(); 7783 } 7784 7785 // Instructions that will be lowered with a final instruction that zeros the 7786 // high result bits. 7787 // XXX - probably only need to list legal operations. 7788 static bool fp16SrcZerosHighBits(unsigned Opc) { 7789 switch (Opc) { 7790 case ISD::FADD: 7791 case ISD::FSUB: 7792 case ISD::FMUL: 7793 case ISD::FDIV: 7794 case ISD::FREM: 7795 case ISD::FMA: 7796 case ISD::FMAD: 7797 case ISD::FCANONICALIZE: 7798 case ISD::FP_ROUND: 7799 case ISD::UINT_TO_FP: 7800 case ISD::SINT_TO_FP: 7801 case ISD::FABS: 7802 // Fabs is lowered to a bit operation, but it's an and which will clear the 7803 // high bits anyway. 7804 case ISD::FSQRT: 7805 case ISD::FSIN: 7806 case ISD::FCOS: 7807 case ISD::FPOWI: 7808 case ISD::FPOW: 7809 case ISD::FLOG: 7810 case ISD::FLOG2: 7811 case ISD::FLOG10: 7812 case ISD::FEXP: 7813 case ISD::FEXP2: 7814 case ISD::FCEIL: 7815 case ISD::FTRUNC: 7816 case ISD::FRINT: 7817 case ISD::FNEARBYINT: 7818 case ISD::FROUND: 7819 case ISD::FFLOOR: 7820 case ISD::FMINNUM: 7821 case ISD::FMAXNUM: 7822 case AMDGPUISD::FRACT: 7823 case AMDGPUISD::CLAMP: 7824 case AMDGPUISD::COS_HW: 7825 case AMDGPUISD::SIN_HW: 7826 case AMDGPUISD::FMIN3: 7827 case AMDGPUISD::FMAX3: 7828 case AMDGPUISD::FMED3: 7829 case AMDGPUISD::FMAD_FTZ: 7830 case AMDGPUISD::RCP: 7831 case AMDGPUISD::RSQ: 7832 case AMDGPUISD::RCP_IFLAG: 7833 case AMDGPUISD::LDEXP: 7834 return true; 7835 default: 7836 // fcopysign, select and others may be lowered to 32-bit bit operations 7837 // which don't zero the high bits. 7838 return false; 7839 } 7840 } 7841 7842 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 7843 DAGCombinerInfo &DCI) const { 7844 if (!Subtarget->has16BitInsts() || 7845 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 7846 return SDValue(); 7847 7848 EVT VT = N->getValueType(0); 7849 if (VT != MVT::i32) 7850 return SDValue(); 7851 7852 SDValue Src = N->getOperand(0); 7853 if (Src.getValueType() != MVT::i16) 7854 return SDValue(); 7855 7856 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 7857 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 7858 if (Src.getOpcode() == ISD::BITCAST) { 7859 SDValue BCSrc = Src.getOperand(0); 7860 if (BCSrc.getValueType() == MVT::f16 && 7861 fp16SrcZerosHighBits(BCSrc.getOpcode())) 7862 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 7863 } 7864 7865 return SDValue(); 7866 } 7867 7868 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 7869 DAGCombinerInfo &DCI) 7870 const { 7871 SDValue Src = N->getOperand(0); 7872 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 7873 7874 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 7875 VTSign->getVT() == MVT::i8) || 7876 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 7877 VTSign->getVT() == MVT::i16)) && 7878 Src.hasOneUse()) { 7879 auto *M = cast<MemSDNode>(Src); 7880 SDValue Ops[] = { 7881 Src.getOperand(0), // Chain 7882 Src.getOperand(1), // rsrc 7883 Src.getOperand(2), // vindex 7884 Src.getOperand(3), // voffset 7885 Src.getOperand(4), // soffset 7886 Src.getOperand(5), // offset 7887 Src.getOperand(6), 7888 Src.getOperand(7) 7889 }; 7890 // replace with BUFFER_LOAD_BYTE/SHORT 7891 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 7892 Src.getOperand(0).getValueType()); 7893 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 7894 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 7895 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 7896 ResList, 7897 Ops, M->getMemoryVT(), 7898 M->getMemOperand()); 7899 return DCI.DAG.getMergeValues({BufferLoadSignExt, 7900 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 7901 } 7902 return SDValue(); 7903 } 7904 7905 SDValue SITargetLowering::performClassCombine(SDNode *N, 7906 DAGCombinerInfo &DCI) const { 7907 SelectionDAG &DAG = DCI.DAG; 7908 SDValue Mask = N->getOperand(1); 7909 7910 // fp_class x, 0 -> false 7911 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 7912 if (CMask->isNullValue()) 7913 return DAG.getConstant(0, SDLoc(N), MVT::i1); 7914 } 7915 7916 if (N->getOperand(0).isUndef()) 7917 return DAG.getUNDEF(MVT::i1); 7918 7919 return SDValue(); 7920 } 7921 7922 SDValue SITargetLowering::performRcpCombine(SDNode *N, 7923 DAGCombinerInfo &DCI) const { 7924 EVT VT = N->getValueType(0); 7925 SDValue N0 = N->getOperand(0); 7926 7927 if (N0.isUndef()) 7928 return N0; 7929 7930 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 7931 N0.getOpcode() == ISD::SINT_TO_FP)) { 7932 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 7933 N->getFlags()); 7934 } 7935 7936 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 7937 } 7938 7939 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 7940 unsigned MaxDepth) const { 7941 unsigned Opcode = Op.getOpcode(); 7942 if (Opcode == ISD::FCANONICALIZE) 7943 return true; 7944 7945 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 7946 auto F = CFP->getValueAPF(); 7947 if (F.isNaN() && F.isSignaling()) 7948 return false; 7949 return !F.isDenormal() || denormalsEnabledForType(Op.getValueType()); 7950 } 7951 7952 // If source is a result of another standard FP operation it is already in 7953 // canonical form. 7954 if (MaxDepth == 0) 7955 return false; 7956 7957 switch (Opcode) { 7958 // These will flush denorms if required. 7959 case ISD::FADD: 7960 case ISD::FSUB: 7961 case ISD::FMUL: 7962 case ISD::FCEIL: 7963 case ISD::FFLOOR: 7964 case ISD::FMA: 7965 case ISD::FMAD: 7966 case ISD::FSQRT: 7967 case ISD::FDIV: 7968 case ISD::FREM: 7969 case ISD::FP_ROUND: 7970 case ISD::FP_EXTEND: 7971 case AMDGPUISD::FMUL_LEGACY: 7972 case AMDGPUISD::FMAD_FTZ: 7973 case AMDGPUISD::RCP: 7974 case AMDGPUISD::RSQ: 7975 case AMDGPUISD::RSQ_CLAMP: 7976 case AMDGPUISD::RCP_LEGACY: 7977 case AMDGPUISD::RSQ_LEGACY: 7978 case AMDGPUISD::RCP_IFLAG: 7979 case AMDGPUISD::TRIG_PREOP: 7980 case AMDGPUISD::DIV_SCALE: 7981 case AMDGPUISD::DIV_FMAS: 7982 case AMDGPUISD::DIV_FIXUP: 7983 case AMDGPUISD::FRACT: 7984 case AMDGPUISD::LDEXP: 7985 case AMDGPUISD::CVT_PKRTZ_F16_F32: 7986 case AMDGPUISD::CVT_F32_UBYTE0: 7987 case AMDGPUISD::CVT_F32_UBYTE1: 7988 case AMDGPUISD::CVT_F32_UBYTE2: 7989 case AMDGPUISD::CVT_F32_UBYTE3: 7990 return true; 7991 7992 // It can/will be lowered or combined as a bit operation. 7993 // Need to check their input recursively to handle. 7994 case ISD::FNEG: 7995 case ISD::FABS: 7996 case ISD::FCOPYSIGN: 7997 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 7998 7999 case ISD::FSIN: 8000 case ISD::FCOS: 8001 case ISD::FSINCOS: 8002 return Op.getValueType().getScalarType() != MVT::f16; 8003 8004 case ISD::FMINNUM: 8005 case ISD::FMAXNUM: 8006 case ISD::FMINNUM_IEEE: 8007 case ISD::FMAXNUM_IEEE: 8008 case AMDGPUISD::CLAMP: 8009 case AMDGPUISD::FMED3: 8010 case AMDGPUISD::FMAX3: 8011 case AMDGPUISD::FMIN3: { 8012 // FIXME: Shouldn't treat the generic operations different based these. 8013 // However, we aren't really required to flush the result from 8014 // minnum/maxnum.. 8015 8016 // snans will be quieted, so we only need to worry about denormals. 8017 if (Subtarget->supportsMinMaxDenormModes() || 8018 denormalsEnabledForType(Op.getValueType())) 8019 return true; 8020 8021 // Flushing may be required. 8022 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 8023 // targets need to check their input recursively. 8024 8025 // FIXME: Does this apply with clamp? It's implemented with max. 8026 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 8027 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 8028 return false; 8029 } 8030 8031 return true; 8032 } 8033 case ISD::SELECT: { 8034 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 8035 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 8036 } 8037 case ISD::BUILD_VECTOR: { 8038 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 8039 SDValue SrcOp = Op.getOperand(i); 8040 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 8041 return false; 8042 } 8043 8044 return true; 8045 } 8046 case ISD::EXTRACT_VECTOR_ELT: 8047 case ISD::EXTRACT_SUBVECTOR: { 8048 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8049 } 8050 case ISD::INSERT_VECTOR_ELT: { 8051 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 8052 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 8053 } 8054 case ISD::UNDEF: 8055 // Could be anything. 8056 return false; 8057 8058 case ISD::BITCAST: { 8059 // Hack round the mess we make when legalizing extract_vector_elt 8060 SDValue Src = Op.getOperand(0); 8061 if (Src.getValueType() == MVT::i16 && 8062 Src.getOpcode() == ISD::TRUNCATE) { 8063 SDValue TruncSrc = Src.getOperand(0); 8064 if (TruncSrc.getValueType() == MVT::i32 && 8065 TruncSrc.getOpcode() == ISD::BITCAST && 8066 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 8067 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 8068 } 8069 } 8070 8071 return false; 8072 } 8073 case ISD::INTRINSIC_WO_CHAIN: { 8074 unsigned IntrinsicID 8075 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8076 // TODO: Handle more intrinsics 8077 switch (IntrinsicID) { 8078 case Intrinsic::amdgcn_cvt_pkrtz: 8079 case Intrinsic::amdgcn_cubeid: 8080 case Intrinsic::amdgcn_frexp_mant: 8081 case Intrinsic::amdgcn_fdot2: 8082 return true; 8083 default: 8084 break; 8085 } 8086 8087 LLVM_FALLTHROUGH; 8088 } 8089 default: 8090 return denormalsEnabledForType(Op.getValueType()) && 8091 DAG.isKnownNeverSNaN(Op); 8092 } 8093 8094 llvm_unreachable("invalid operation"); 8095 } 8096 8097 // Constant fold canonicalize. 8098 SDValue SITargetLowering::getCanonicalConstantFP( 8099 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 8100 // Flush denormals to 0 if not enabled. 8101 if (C.isDenormal() && !denormalsEnabledForType(VT)) 8102 return DAG.getConstantFP(0.0, SL, VT); 8103 8104 if (C.isNaN()) { 8105 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 8106 if (C.isSignaling()) { 8107 // Quiet a signaling NaN. 8108 // FIXME: Is this supposed to preserve payload bits? 8109 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8110 } 8111 8112 // Make sure it is the canonical NaN bitpattern. 8113 // 8114 // TODO: Can we use -1 as the canonical NaN value since it's an inline 8115 // immediate? 8116 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 8117 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8118 } 8119 8120 // Already canonical. 8121 return DAG.getConstantFP(C, SL, VT); 8122 } 8123 8124 static bool vectorEltWillFoldAway(SDValue Op) { 8125 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 8126 } 8127 8128 SDValue SITargetLowering::performFCanonicalizeCombine( 8129 SDNode *N, 8130 DAGCombinerInfo &DCI) const { 8131 SelectionDAG &DAG = DCI.DAG; 8132 SDValue N0 = N->getOperand(0); 8133 EVT VT = N->getValueType(0); 8134 8135 // fcanonicalize undef -> qnan 8136 if (N0.isUndef()) { 8137 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 8138 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 8139 } 8140 8141 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 8142 EVT VT = N->getValueType(0); 8143 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 8144 } 8145 8146 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 8147 // (fcanonicalize k) 8148 // 8149 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 8150 8151 // TODO: This could be better with wider vectors that will be split to v2f16, 8152 // and to consider uses since there aren't that many packed operations. 8153 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 8154 isTypeLegal(MVT::v2f16)) { 8155 SDLoc SL(N); 8156 SDValue NewElts[2]; 8157 SDValue Lo = N0.getOperand(0); 8158 SDValue Hi = N0.getOperand(1); 8159 EVT EltVT = Lo.getValueType(); 8160 8161 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 8162 for (unsigned I = 0; I != 2; ++I) { 8163 SDValue Op = N0.getOperand(I); 8164 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8165 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 8166 CFP->getValueAPF()); 8167 } else if (Op.isUndef()) { 8168 // Handled below based on what the other operand is. 8169 NewElts[I] = Op; 8170 } else { 8171 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 8172 } 8173 } 8174 8175 // If one half is undef, and one is constant, perfer a splat vector rather 8176 // than the normal qNaN. If it's a register, prefer 0.0 since that's 8177 // cheaper to use and may be free with a packed operation. 8178 if (NewElts[0].isUndef()) { 8179 if (isa<ConstantFPSDNode>(NewElts[1])) 8180 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 8181 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 8182 } 8183 8184 if (NewElts[1].isUndef()) { 8185 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 8186 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 8187 } 8188 8189 return DAG.getBuildVector(VT, SL, NewElts); 8190 } 8191 } 8192 8193 unsigned SrcOpc = N0.getOpcode(); 8194 8195 // If it's free to do so, push canonicalizes further up the source, which may 8196 // find a canonical source. 8197 // 8198 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 8199 // sNaNs. 8200 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 8201 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 8202 if (CRHS && N0.hasOneUse()) { 8203 SDLoc SL(N); 8204 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 8205 N0.getOperand(0)); 8206 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 8207 DCI.AddToWorklist(Canon0.getNode()); 8208 8209 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 8210 } 8211 } 8212 8213 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 8214 } 8215 8216 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 8217 switch (Opc) { 8218 case ISD::FMAXNUM: 8219 case ISD::FMAXNUM_IEEE: 8220 return AMDGPUISD::FMAX3; 8221 case ISD::SMAX: 8222 return AMDGPUISD::SMAX3; 8223 case ISD::UMAX: 8224 return AMDGPUISD::UMAX3; 8225 case ISD::FMINNUM: 8226 case ISD::FMINNUM_IEEE: 8227 return AMDGPUISD::FMIN3; 8228 case ISD::SMIN: 8229 return AMDGPUISD::SMIN3; 8230 case ISD::UMIN: 8231 return AMDGPUISD::UMIN3; 8232 default: 8233 llvm_unreachable("Not a min/max opcode"); 8234 } 8235 } 8236 8237 SDValue SITargetLowering::performIntMed3ImmCombine( 8238 SelectionDAG &DAG, const SDLoc &SL, 8239 SDValue Op0, SDValue Op1, bool Signed) const { 8240 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 8241 if (!K1) 8242 return SDValue(); 8243 8244 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 8245 if (!K0) 8246 return SDValue(); 8247 8248 if (Signed) { 8249 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 8250 return SDValue(); 8251 } else { 8252 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 8253 return SDValue(); 8254 } 8255 8256 EVT VT = K0->getValueType(0); 8257 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 8258 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 8259 return DAG.getNode(Med3Opc, SL, VT, 8260 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 8261 } 8262 8263 // If there isn't a 16-bit med3 operation, convert to 32-bit. 8264 MVT NVT = MVT::i32; 8265 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8266 8267 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 8268 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 8269 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 8270 8271 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 8272 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 8273 } 8274 8275 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 8276 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 8277 return C; 8278 8279 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 8280 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 8281 return C; 8282 } 8283 8284 return nullptr; 8285 } 8286 8287 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 8288 const SDLoc &SL, 8289 SDValue Op0, 8290 SDValue Op1) const { 8291 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 8292 if (!K1) 8293 return SDValue(); 8294 8295 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 8296 if (!K0) 8297 return SDValue(); 8298 8299 // Ordered >= (although NaN inputs should have folded away by now). 8300 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 8301 if (Cmp == APFloat::cmpGreaterThan) 8302 return SDValue(); 8303 8304 const MachineFunction &MF = DAG.getMachineFunction(); 8305 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 8306 8307 // TODO: Check IEEE bit enabled? 8308 EVT VT = Op0.getValueType(); 8309 if (Info->getMode().DX10Clamp) { 8310 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 8311 // hardware fmed3 behavior converting to a min. 8312 // FIXME: Should this be allowing -0.0? 8313 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 8314 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 8315 } 8316 8317 // med3 for f16 is only available on gfx9+, and not available for v2f16. 8318 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 8319 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 8320 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 8321 // then give the other result, which is different from med3 with a NaN 8322 // input. 8323 SDValue Var = Op0.getOperand(0); 8324 if (!DAG.isKnownNeverSNaN(Var)) 8325 return SDValue(); 8326 8327 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8328 8329 if ((!K0->hasOneUse() || 8330 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 8331 (!K1->hasOneUse() || 8332 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 8333 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 8334 Var, SDValue(K0, 0), SDValue(K1, 0)); 8335 } 8336 } 8337 8338 return SDValue(); 8339 } 8340 8341 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 8342 DAGCombinerInfo &DCI) const { 8343 SelectionDAG &DAG = DCI.DAG; 8344 8345 EVT VT = N->getValueType(0); 8346 unsigned Opc = N->getOpcode(); 8347 SDValue Op0 = N->getOperand(0); 8348 SDValue Op1 = N->getOperand(1); 8349 8350 // Only do this if the inner op has one use since this will just increases 8351 // register pressure for no benefit. 8352 8353 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 8354 !VT.isVector() && 8355 (VT == MVT::i32 || VT == MVT::f32 || 8356 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 8357 // max(max(a, b), c) -> max3(a, b, c) 8358 // min(min(a, b), c) -> min3(a, b, c) 8359 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 8360 SDLoc DL(N); 8361 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 8362 DL, 8363 N->getValueType(0), 8364 Op0.getOperand(0), 8365 Op0.getOperand(1), 8366 Op1); 8367 } 8368 8369 // Try commuted. 8370 // max(a, max(b, c)) -> max3(a, b, c) 8371 // min(a, min(b, c)) -> min3(a, b, c) 8372 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 8373 SDLoc DL(N); 8374 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 8375 DL, 8376 N->getValueType(0), 8377 Op0, 8378 Op1.getOperand(0), 8379 Op1.getOperand(1)); 8380 } 8381 } 8382 8383 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 8384 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 8385 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 8386 return Med3; 8387 } 8388 8389 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 8390 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 8391 return Med3; 8392 } 8393 8394 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 8395 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 8396 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 8397 (Opc == AMDGPUISD::FMIN_LEGACY && 8398 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 8399 (VT == MVT::f32 || VT == MVT::f64 || 8400 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 8401 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 8402 Op0.hasOneUse()) { 8403 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 8404 return Res; 8405 } 8406 8407 return SDValue(); 8408 } 8409 8410 static bool isClampZeroToOne(SDValue A, SDValue B) { 8411 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 8412 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 8413 // FIXME: Should this be allowing -0.0? 8414 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 8415 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 8416 } 8417 } 8418 8419 return false; 8420 } 8421 8422 // FIXME: Should only worry about snans for version with chain. 8423 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 8424 DAGCombinerInfo &DCI) const { 8425 EVT VT = N->getValueType(0); 8426 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 8427 // NaNs. With a NaN input, the order of the operands may change the result. 8428 8429 SelectionDAG &DAG = DCI.DAG; 8430 SDLoc SL(N); 8431 8432 SDValue Src0 = N->getOperand(0); 8433 SDValue Src1 = N->getOperand(1); 8434 SDValue Src2 = N->getOperand(2); 8435 8436 if (isClampZeroToOne(Src0, Src1)) { 8437 // const_a, const_b, x -> clamp is safe in all cases including signaling 8438 // nans. 8439 // FIXME: Should this be allowing -0.0? 8440 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 8441 } 8442 8443 const MachineFunction &MF = DAG.getMachineFunction(); 8444 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 8445 8446 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 8447 // handling no dx10-clamp? 8448 if (Info->getMode().DX10Clamp) { 8449 // If NaNs is clamped to 0, we are free to reorder the inputs. 8450 8451 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 8452 std::swap(Src0, Src1); 8453 8454 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 8455 std::swap(Src1, Src2); 8456 8457 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 8458 std::swap(Src0, Src1); 8459 8460 if (isClampZeroToOne(Src1, Src2)) 8461 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 8462 } 8463 8464 return SDValue(); 8465 } 8466 8467 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 8468 DAGCombinerInfo &DCI) const { 8469 SDValue Src0 = N->getOperand(0); 8470 SDValue Src1 = N->getOperand(1); 8471 if (Src0.isUndef() && Src1.isUndef()) 8472 return DCI.DAG.getUNDEF(N->getValueType(0)); 8473 return SDValue(); 8474 } 8475 8476 SDValue SITargetLowering::performExtractVectorEltCombine( 8477 SDNode *N, DAGCombinerInfo &DCI) const { 8478 SDValue Vec = N->getOperand(0); 8479 SelectionDAG &DAG = DCI.DAG; 8480 8481 EVT VecVT = Vec.getValueType(); 8482 EVT EltVT = VecVT.getVectorElementType(); 8483 8484 if ((Vec.getOpcode() == ISD::FNEG || 8485 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 8486 SDLoc SL(N); 8487 EVT EltVT = N->getValueType(0); 8488 SDValue Idx = N->getOperand(1); 8489 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 8490 Vec.getOperand(0), Idx); 8491 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 8492 } 8493 8494 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 8495 // => 8496 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 8497 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 8498 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 8499 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 8500 SDLoc SL(N); 8501 EVT EltVT = N->getValueType(0); 8502 SDValue Idx = N->getOperand(1); 8503 unsigned Opc = Vec.getOpcode(); 8504 8505 switch(Opc) { 8506 default: 8507 break; 8508 // TODO: Support other binary operations. 8509 case ISD::FADD: 8510 case ISD::FSUB: 8511 case ISD::FMUL: 8512 case ISD::ADD: 8513 case ISD::UMIN: 8514 case ISD::UMAX: 8515 case ISD::SMIN: 8516 case ISD::SMAX: 8517 case ISD::FMAXNUM: 8518 case ISD::FMINNUM: 8519 case ISD::FMAXNUM_IEEE: 8520 case ISD::FMINNUM_IEEE: { 8521 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 8522 Vec.getOperand(0), Idx); 8523 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 8524 Vec.getOperand(1), Idx); 8525 8526 DCI.AddToWorklist(Elt0.getNode()); 8527 DCI.AddToWorklist(Elt1.getNode()); 8528 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 8529 } 8530 } 8531 } 8532 8533 unsigned VecSize = VecVT.getSizeInBits(); 8534 unsigned EltSize = EltVT.getSizeInBits(); 8535 8536 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 8537 // This elminates non-constant index and subsequent movrel or scratch access. 8538 // Sub-dword vectors of size 2 dword or less have better implementation. 8539 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 8540 // instructions. 8541 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) && 8542 !isa<ConstantSDNode>(N->getOperand(1))) { 8543 SDLoc SL(N); 8544 SDValue Idx = N->getOperand(1); 8545 EVT IdxVT = Idx.getValueType(); 8546 SDValue V; 8547 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 8548 SDValue IC = DAG.getConstant(I, SL, IdxVT); 8549 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 8550 if (I == 0) 8551 V = Elt; 8552 else 8553 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 8554 } 8555 return V; 8556 } 8557 8558 if (!DCI.isBeforeLegalize()) 8559 return SDValue(); 8560 8561 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 8562 // elements. This exposes more load reduction opportunities by replacing 8563 // multiple small extract_vector_elements with a single 32-bit extract. 8564 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8565 if (isa<MemSDNode>(Vec) && 8566 EltSize <= 16 && 8567 EltVT.isByteSized() && 8568 VecSize > 32 && 8569 VecSize % 32 == 0 && 8570 Idx) { 8571 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 8572 8573 unsigned BitIndex = Idx->getZExtValue() * EltSize; 8574 unsigned EltIdx = BitIndex / 32; 8575 unsigned LeftoverBitIdx = BitIndex % 32; 8576 SDLoc SL(N); 8577 8578 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 8579 DCI.AddToWorklist(Cast.getNode()); 8580 8581 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 8582 DAG.getConstant(EltIdx, SL, MVT::i32)); 8583 DCI.AddToWorklist(Elt.getNode()); 8584 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 8585 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 8586 DCI.AddToWorklist(Srl.getNode()); 8587 8588 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 8589 DCI.AddToWorklist(Trunc.getNode()); 8590 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 8591 } 8592 8593 return SDValue(); 8594 } 8595 8596 SDValue 8597 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 8598 DAGCombinerInfo &DCI) const { 8599 SDValue Vec = N->getOperand(0); 8600 SDValue Idx = N->getOperand(2); 8601 EVT VecVT = Vec.getValueType(); 8602 EVT EltVT = VecVT.getVectorElementType(); 8603 unsigned VecSize = VecVT.getSizeInBits(); 8604 unsigned EltSize = EltVT.getSizeInBits(); 8605 8606 // INSERT_VECTOR_ELT (<n x e>, var-idx) 8607 // => BUILD_VECTOR n x select (e, const-idx) 8608 // This elminates non-constant index and subsequent movrel or scratch access. 8609 // Sub-dword vectors of size 2 dword or less have better implementation. 8610 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 8611 // instructions. 8612 if (isa<ConstantSDNode>(Idx) || 8613 VecSize > 256 || (VecSize <= 64 && EltSize < 32)) 8614 return SDValue(); 8615 8616 SelectionDAG &DAG = DCI.DAG; 8617 SDLoc SL(N); 8618 SDValue Ins = N->getOperand(1); 8619 EVT IdxVT = Idx.getValueType(); 8620 8621 SmallVector<SDValue, 16> Ops; 8622 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 8623 SDValue IC = DAG.getConstant(I, SL, IdxVT); 8624 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 8625 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 8626 Ops.push_back(V); 8627 } 8628 8629 return DAG.getBuildVector(VecVT, SL, Ops); 8630 } 8631 8632 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 8633 const SDNode *N0, 8634 const SDNode *N1) const { 8635 EVT VT = N0->getValueType(0); 8636 8637 // Only do this if we are not trying to support denormals. v_mad_f32 does not 8638 // support denormals ever. 8639 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) || 8640 (VT == MVT::f16 && !Subtarget->hasFP16Denormals())) 8641 return ISD::FMAD; 8642 8643 const TargetOptions &Options = DAG.getTarget().Options; 8644 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 8645 (N0->getFlags().hasAllowContract() && 8646 N1->getFlags().hasAllowContract())) && 8647 isFMAFasterThanFMulAndFAdd(VT)) { 8648 return ISD::FMA; 8649 } 8650 8651 return 0; 8652 } 8653 8654 // For a reassociatable opcode perform: 8655 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 8656 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 8657 SelectionDAG &DAG) const { 8658 EVT VT = N->getValueType(0); 8659 if (VT != MVT::i32 && VT != MVT::i64) 8660 return SDValue(); 8661 8662 unsigned Opc = N->getOpcode(); 8663 SDValue Op0 = N->getOperand(0); 8664 SDValue Op1 = N->getOperand(1); 8665 8666 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 8667 return SDValue(); 8668 8669 if (Op0->isDivergent()) 8670 std::swap(Op0, Op1); 8671 8672 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 8673 return SDValue(); 8674 8675 SDValue Op2 = Op1.getOperand(1); 8676 Op1 = Op1.getOperand(0); 8677 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 8678 return SDValue(); 8679 8680 if (Op1->isDivergent()) 8681 std::swap(Op1, Op2); 8682 8683 // If either operand is constant this will conflict with 8684 // DAGCombiner::ReassociateOps(). 8685 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 8686 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 8687 return SDValue(); 8688 8689 SDLoc SL(N); 8690 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 8691 return DAG.getNode(Opc, SL, VT, Add1, Op2); 8692 } 8693 8694 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 8695 EVT VT, 8696 SDValue N0, SDValue N1, SDValue N2, 8697 bool Signed) { 8698 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 8699 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 8700 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 8701 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 8702 } 8703 8704 SDValue SITargetLowering::performAddCombine(SDNode *N, 8705 DAGCombinerInfo &DCI) const { 8706 SelectionDAG &DAG = DCI.DAG; 8707 EVT VT = N->getValueType(0); 8708 SDLoc SL(N); 8709 SDValue LHS = N->getOperand(0); 8710 SDValue RHS = N->getOperand(1); 8711 8712 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 8713 && Subtarget->hasMad64_32() && 8714 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 8715 VT.getScalarSizeInBits() <= 64) { 8716 if (LHS.getOpcode() != ISD::MUL) 8717 std::swap(LHS, RHS); 8718 8719 SDValue MulLHS = LHS.getOperand(0); 8720 SDValue MulRHS = LHS.getOperand(1); 8721 SDValue AddRHS = RHS; 8722 8723 // TODO: Maybe restrict if SGPR inputs. 8724 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 8725 numBitsUnsigned(MulRHS, DAG) <= 32) { 8726 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 8727 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 8728 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 8729 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 8730 } 8731 8732 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 8733 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 8734 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 8735 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 8736 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 8737 } 8738 8739 return SDValue(); 8740 } 8741 8742 if (SDValue V = reassociateScalarOps(N, DAG)) { 8743 return V; 8744 } 8745 8746 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 8747 return SDValue(); 8748 8749 // add x, zext (setcc) => addcarry x, 0, setcc 8750 // add x, sext (setcc) => subcarry x, 0, setcc 8751 unsigned Opc = LHS.getOpcode(); 8752 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 8753 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 8754 std::swap(RHS, LHS); 8755 8756 Opc = RHS.getOpcode(); 8757 switch (Opc) { 8758 default: break; 8759 case ISD::ZERO_EXTEND: 8760 case ISD::SIGN_EXTEND: 8761 case ISD::ANY_EXTEND: { 8762 auto Cond = RHS.getOperand(0); 8763 if (!isBoolSGPR(Cond)) 8764 break; 8765 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 8766 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 8767 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 8768 return DAG.getNode(Opc, SL, VTList, Args); 8769 } 8770 case ISD::ADDCARRY: { 8771 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 8772 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8773 if (!C || C->getZExtValue() != 0) break; 8774 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 8775 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 8776 } 8777 } 8778 return SDValue(); 8779 } 8780 8781 SDValue SITargetLowering::performSubCombine(SDNode *N, 8782 DAGCombinerInfo &DCI) const { 8783 SelectionDAG &DAG = DCI.DAG; 8784 EVT VT = N->getValueType(0); 8785 8786 if (VT != MVT::i32) 8787 return SDValue(); 8788 8789 SDLoc SL(N); 8790 SDValue LHS = N->getOperand(0); 8791 SDValue RHS = N->getOperand(1); 8792 8793 if (LHS.getOpcode() == ISD::SUBCARRY) { 8794 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 8795 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8796 if (!C || !C->isNullValue()) 8797 return SDValue(); 8798 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 8799 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 8800 } 8801 return SDValue(); 8802 } 8803 8804 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 8805 DAGCombinerInfo &DCI) const { 8806 8807 if (N->getValueType(0) != MVT::i32) 8808 return SDValue(); 8809 8810 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8811 if (!C || C->getZExtValue() != 0) 8812 return SDValue(); 8813 8814 SelectionDAG &DAG = DCI.DAG; 8815 SDValue LHS = N->getOperand(0); 8816 8817 // addcarry (add x, y), 0, cc => addcarry x, y, cc 8818 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 8819 unsigned LHSOpc = LHS.getOpcode(); 8820 unsigned Opc = N->getOpcode(); 8821 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 8822 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 8823 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 8824 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 8825 } 8826 return SDValue(); 8827 } 8828 8829 SDValue SITargetLowering::performFAddCombine(SDNode *N, 8830 DAGCombinerInfo &DCI) const { 8831 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8832 return SDValue(); 8833 8834 SelectionDAG &DAG = DCI.DAG; 8835 EVT VT = N->getValueType(0); 8836 8837 SDLoc SL(N); 8838 SDValue LHS = N->getOperand(0); 8839 SDValue RHS = N->getOperand(1); 8840 8841 // These should really be instruction patterns, but writing patterns with 8842 // source modiifiers is a pain. 8843 8844 // fadd (fadd (a, a), b) -> mad 2.0, a, b 8845 if (LHS.getOpcode() == ISD::FADD) { 8846 SDValue A = LHS.getOperand(0); 8847 if (A == LHS.getOperand(1)) { 8848 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 8849 if (FusedOp != 0) { 8850 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 8851 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 8852 } 8853 } 8854 } 8855 8856 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 8857 if (RHS.getOpcode() == ISD::FADD) { 8858 SDValue A = RHS.getOperand(0); 8859 if (A == RHS.getOperand(1)) { 8860 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 8861 if (FusedOp != 0) { 8862 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 8863 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 8864 } 8865 } 8866 } 8867 8868 return SDValue(); 8869 } 8870 8871 SDValue SITargetLowering::performFSubCombine(SDNode *N, 8872 DAGCombinerInfo &DCI) const { 8873 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8874 return SDValue(); 8875 8876 SelectionDAG &DAG = DCI.DAG; 8877 SDLoc SL(N); 8878 EVT VT = N->getValueType(0); 8879 assert(!VT.isVector()); 8880 8881 // Try to get the fneg to fold into the source modifier. This undoes generic 8882 // DAG combines and folds them into the mad. 8883 // 8884 // Only do this if we are not trying to support denormals. v_mad_f32 does 8885 // not support denormals ever. 8886 SDValue LHS = N->getOperand(0); 8887 SDValue RHS = N->getOperand(1); 8888 if (LHS.getOpcode() == ISD::FADD) { 8889 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 8890 SDValue A = LHS.getOperand(0); 8891 if (A == LHS.getOperand(1)) { 8892 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 8893 if (FusedOp != 0){ 8894 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 8895 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8896 8897 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 8898 } 8899 } 8900 } 8901 8902 if (RHS.getOpcode() == ISD::FADD) { 8903 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 8904 8905 SDValue A = RHS.getOperand(0); 8906 if (A == RHS.getOperand(1)) { 8907 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 8908 if (FusedOp != 0){ 8909 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 8910 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 8911 } 8912 } 8913 } 8914 8915 return SDValue(); 8916 } 8917 8918 SDValue SITargetLowering::performFMACombine(SDNode *N, 8919 DAGCombinerInfo &DCI) const { 8920 SelectionDAG &DAG = DCI.DAG; 8921 EVT VT = N->getValueType(0); 8922 SDLoc SL(N); 8923 8924 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 8925 return SDValue(); 8926 8927 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 8928 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 8929 SDValue Op1 = N->getOperand(0); 8930 SDValue Op2 = N->getOperand(1); 8931 SDValue FMA = N->getOperand(2); 8932 8933 if (FMA.getOpcode() != ISD::FMA || 8934 Op1.getOpcode() != ISD::FP_EXTEND || 8935 Op2.getOpcode() != ISD::FP_EXTEND) 8936 return SDValue(); 8937 8938 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 8939 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 8940 // is sufficient to allow generaing fdot2. 8941 const TargetOptions &Options = DAG.getTarget().Options; 8942 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 8943 (N->getFlags().hasAllowContract() && 8944 FMA->getFlags().hasAllowContract())) { 8945 Op1 = Op1.getOperand(0); 8946 Op2 = Op2.getOperand(0); 8947 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 8948 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 8949 return SDValue(); 8950 8951 SDValue Vec1 = Op1.getOperand(0); 8952 SDValue Idx1 = Op1.getOperand(1); 8953 SDValue Vec2 = Op2.getOperand(0); 8954 8955 SDValue FMAOp1 = FMA.getOperand(0); 8956 SDValue FMAOp2 = FMA.getOperand(1); 8957 SDValue FMAAcc = FMA.getOperand(2); 8958 8959 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 8960 FMAOp2.getOpcode() != ISD::FP_EXTEND) 8961 return SDValue(); 8962 8963 FMAOp1 = FMAOp1.getOperand(0); 8964 FMAOp2 = FMAOp2.getOperand(0); 8965 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 8966 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 8967 return SDValue(); 8968 8969 SDValue Vec3 = FMAOp1.getOperand(0); 8970 SDValue Vec4 = FMAOp2.getOperand(0); 8971 SDValue Idx2 = FMAOp1.getOperand(1); 8972 8973 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 8974 // Idx1 and Idx2 cannot be the same. 8975 Idx1 == Idx2) 8976 return SDValue(); 8977 8978 if (Vec1 == Vec2 || Vec3 == Vec4) 8979 return SDValue(); 8980 8981 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 8982 return SDValue(); 8983 8984 if ((Vec1 == Vec3 && Vec2 == Vec4) || 8985 (Vec1 == Vec4 && Vec2 == Vec3)) { 8986 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 8987 DAG.getTargetConstant(0, SL, MVT::i1)); 8988 } 8989 } 8990 return SDValue(); 8991 } 8992 8993 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 8994 DAGCombinerInfo &DCI) const { 8995 SelectionDAG &DAG = DCI.DAG; 8996 SDLoc SL(N); 8997 8998 SDValue LHS = N->getOperand(0); 8999 SDValue RHS = N->getOperand(1); 9000 EVT VT = LHS.getValueType(); 9001 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 9002 9003 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 9004 if (!CRHS) { 9005 CRHS = dyn_cast<ConstantSDNode>(LHS); 9006 if (CRHS) { 9007 std::swap(LHS, RHS); 9008 CC = getSetCCSwappedOperands(CC); 9009 } 9010 } 9011 9012 if (CRHS) { 9013 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 9014 isBoolSGPR(LHS.getOperand(0))) { 9015 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 9016 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 9017 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 9018 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 9019 if ((CRHS->isAllOnesValue() && 9020 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 9021 (CRHS->isNullValue() && 9022 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 9023 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9024 DAG.getConstant(-1, SL, MVT::i1)); 9025 if ((CRHS->isAllOnesValue() && 9026 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 9027 (CRHS->isNullValue() && 9028 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 9029 return LHS.getOperand(0); 9030 } 9031 9032 uint64_t CRHSVal = CRHS->getZExtValue(); 9033 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 9034 LHS.getOpcode() == ISD::SELECT && 9035 isa<ConstantSDNode>(LHS.getOperand(1)) && 9036 isa<ConstantSDNode>(LHS.getOperand(2)) && 9037 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 9038 isBoolSGPR(LHS.getOperand(0))) { 9039 // Given CT != FT: 9040 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 9041 // setcc (select cc, CT, CF), CF, ne => cc 9042 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 9043 // setcc (select cc, CT, CF), CT, eq => cc 9044 uint64_t CT = LHS.getConstantOperandVal(1); 9045 uint64_t CF = LHS.getConstantOperandVal(2); 9046 9047 if ((CF == CRHSVal && CC == ISD::SETEQ) || 9048 (CT == CRHSVal && CC == ISD::SETNE)) 9049 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9050 DAG.getConstant(-1, SL, MVT::i1)); 9051 if ((CF == CRHSVal && CC == ISD::SETNE) || 9052 (CT == CRHSVal && CC == ISD::SETEQ)) 9053 return LHS.getOperand(0); 9054 } 9055 } 9056 9057 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 9058 VT != MVT::f16)) 9059 return SDValue(); 9060 9061 // Match isinf/isfinite pattern 9062 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 9063 // (fcmp one (fabs x), inf) -> (fp_class x, 9064 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 9065 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 9066 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 9067 if (!CRHS) 9068 return SDValue(); 9069 9070 const APFloat &APF = CRHS->getValueAPF(); 9071 if (APF.isInfinity() && !APF.isNegative()) { 9072 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 9073 SIInstrFlags::N_INFINITY; 9074 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 9075 SIInstrFlags::P_ZERO | 9076 SIInstrFlags::N_NORMAL | 9077 SIInstrFlags::P_NORMAL | 9078 SIInstrFlags::N_SUBNORMAL | 9079 SIInstrFlags::P_SUBNORMAL; 9080 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 9081 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 9082 DAG.getConstant(Mask, SL, MVT::i32)); 9083 } 9084 } 9085 9086 return SDValue(); 9087 } 9088 9089 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 9090 DAGCombinerInfo &DCI) const { 9091 SelectionDAG &DAG = DCI.DAG; 9092 SDLoc SL(N); 9093 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 9094 9095 SDValue Src = N->getOperand(0); 9096 SDValue Srl = N->getOperand(0); 9097 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 9098 Srl = Srl.getOperand(0); 9099 9100 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 9101 if (Srl.getOpcode() == ISD::SRL) { 9102 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 9103 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 9104 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 9105 9106 if (const ConstantSDNode *C = 9107 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 9108 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 9109 EVT(MVT::i32)); 9110 9111 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 9112 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 9113 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 9114 MVT::f32, Srl); 9115 } 9116 } 9117 } 9118 9119 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 9120 9121 KnownBits Known; 9122 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 9123 !DCI.isBeforeLegalizeOps()); 9124 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9125 if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) { 9126 DCI.CommitTargetLoweringOpt(TLO); 9127 } 9128 9129 return SDValue(); 9130 } 9131 9132 SDValue SITargetLowering::performClampCombine(SDNode *N, 9133 DAGCombinerInfo &DCI) const { 9134 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 9135 if (!CSrc) 9136 return SDValue(); 9137 9138 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 9139 const APFloat &F = CSrc->getValueAPF(); 9140 APFloat Zero = APFloat::getZero(F.getSemantics()); 9141 APFloat::cmpResult Cmp0 = F.compare(Zero); 9142 if (Cmp0 == APFloat::cmpLessThan || 9143 (Cmp0 == APFloat::cmpUnordered && 9144 MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 9145 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 9146 } 9147 9148 APFloat One(F.getSemantics(), "1.0"); 9149 APFloat::cmpResult Cmp1 = F.compare(One); 9150 if (Cmp1 == APFloat::cmpGreaterThan) 9151 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 9152 9153 return SDValue(CSrc, 0); 9154 } 9155 9156 9157 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 9158 DAGCombinerInfo &DCI) const { 9159 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 9160 return SDValue(); 9161 switch (N->getOpcode()) { 9162 default: 9163 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9164 case ISD::ADD: 9165 return performAddCombine(N, DCI); 9166 case ISD::SUB: 9167 return performSubCombine(N, DCI); 9168 case ISD::ADDCARRY: 9169 case ISD::SUBCARRY: 9170 return performAddCarrySubCarryCombine(N, DCI); 9171 case ISD::FADD: 9172 return performFAddCombine(N, DCI); 9173 case ISD::FSUB: 9174 return performFSubCombine(N, DCI); 9175 case ISD::SETCC: 9176 return performSetCCCombine(N, DCI); 9177 case ISD::FMAXNUM: 9178 case ISD::FMINNUM: 9179 case ISD::FMAXNUM_IEEE: 9180 case ISD::FMINNUM_IEEE: 9181 case ISD::SMAX: 9182 case ISD::SMIN: 9183 case ISD::UMAX: 9184 case ISD::UMIN: 9185 case AMDGPUISD::FMIN_LEGACY: 9186 case AMDGPUISD::FMAX_LEGACY: 9187 return performMinMaxCombine(N, DCI); 9188 case ISD::FMA: 9189 return performFMACombine(N, DCI); 9190 case ISD::LOAD: { 9191 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 9192 return Widended; 9193 LLVM_FALLTHROUGH; 9194 } 9195 case ISD::STORE: 9196 case ISD::ATOMIC_LOAD: 9197 case ISD::ATOMIC_STORE: 9198 case ISD::ATOMIC_CMP_SWAP: 9199 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 9200 case ISD::ATOMIC_SWAP: 9201 case ISD::ATOMIC_LOAD_ADD: 9202 case ISD::ATOMIC_LOAD_SUB: 9203 case ISD::ATOMIC_LOAD_AND: 9204 case ISD::ATOMIC_LOAD_OR: 9205 case ISD::ATOMIC_LOAD_XOR: 9206 case ISD::ATOMIC_LOAD_NAND: 9207 case ISD::ATOMIC_LOAD_MIN: 9208 case ISD::ATOMIC_LOAD_MAX: 9209 case ISD::ATOMIC_LOAD_UMIN: 9210 case ISD::ATOMIC_LOAD_UMAX: 9211 case ISD::ATOMIC_LOAD_FADD: 9212 case AMDGPUISD::ATOMIC_INC: 9213 case AMDGPUISD::ATOMIC_DEC: 9214 case AMDGPUISD::ATOMIC_LOAD_FMIN: 9215 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 9216 if (DCI.isBeforeLegalize()) 9217 break; 9218 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 9219 case ISD::AND: 9220 return performAndCombine(N, DCI); 9221 case ISD::OR: 9222 return performOrCombine(N, DCI); 9223 case ISD::XOR: 9224 return performXorCombine(N, DCI); 9225 case ISD::ZERO_EXTEND: 9226 return performZeroExtendCombine(N, DCI); 9227 case ISD::SIGN_EXTEND_INREG: 9228 return performSignExtendInRegCombine(N , DCI); 9229 case AMDGPUISD::FP_CLASS: 9230 return performClassCombine(N, DCI); 9231 case ISD::FCANONICALIZE: 9232 return performFCanonicalizeCombine(N, DCI); 9233 case AMDGPUISD::RCP: 9234 return performRcpCombine(N, DCI); 9235 case AMDGPUISD::FRACT: 9236 case AMDGPUISD::RSQ: 9237 case AMDGPUISD::RCP_LEGACY: 9238 case AMDGPUISD::RSQ_LEGACY: 9239 case AMDGPUISD::RCP_IFLAG: 9240 case AMDGPUISD::RSQ_CLAMP: 9241 case AMDGPUISD::LDEXP: { 9242 SDValue Src = N->getOperand(0); 9243 if (Src.isUndef()) 9244 return Src; 9245 break; 9246 } 9247 case ISD::SINT_TO_FP: 9248 case ISD::UINT_TO_FP: 9249 return performUCharToFloatCombine(N, DCI); 9250 case AMDGPUISD::CVT_F32_UBYTE0: 9251 case AMDGPUISD::CVT_F32_UBYTE1: 9252 case AMDGPUISD::CVT_F32_UBYTE2: 9253 case AMDGPUISD::CVT_F32_UBYTE3: 9254 return performCvtF32UByteNCombine(N, DCI); 9255 case AMDGPUISD::FMED3: 9256 return performFMed3Combine(N, DCI); 9257 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9258 return performCvtPkRTZCombine(N, DCI); 9259 case AMDGPUISD::CLAMP: 9260 return performClampCombine(N, DCI); 9261 case ISD::SCALAR_TO_VECTOR: { 9262 SelectionDAG &DAG = DCI.DAG; 9263 EVT VT = N->getValueType(0); 9264 9265 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 9266 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 9267 SDLoc SL(N); 9268 SDValue Src = N->getOperand(0); 9269 EVT EltVT = Src.getValueType(); 9270 if (EltVT == MVT::f16) 9271 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 9272 9273 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 9274 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 9275 } 9276 9277 break; 9278 } 9279 case ISD::EXTRACT_VECTOR_ELT: 9280 return performExtractVectorEltCombine(N, DCI); 9281 case ISD::INSERT_VECTOR_ELT: 9282 return performInsertVectorEltCombine(N, DCI); 9283 } 9284 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9285 } 9286 9287 /// Helper function for adjustWritemask 9288 static unsigned SubIdx2Lane(unsigned Idx) { 9289 switch (Idx) { 9290 default: return 0; 9291 case AMDGPU::sub0: return 0; 9292 case AMDGPU::sub1: return 1; 9293 case AMDGPU::sub2: return 2; 9294 case AMDGPU::sub3: return 3; 9295 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 9296 } 9297 } 9298 9299 /// Adjust the writemask of MIMG instructions 9300 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 9301 SelectionDAG &DAG) const { 9302 unsigned Opcode = Node->getMachineOpcode(); 9303 9304 // Subtract 1 because the vdata output is not a MachineSDNode operand. 9305 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 9306 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 9307 return Node; // not implemented for D16 9308 9309 SDNode *Users[5] = { nullptr }; 9310 unsigned Lane = 0; 9311 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 9312 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 9313 unsigned NewDmask = 0; 9314 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 9315 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 9316 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 9317 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 9318 unsigned TFCLane = 0; 9319 bool HasChain = Node->getNumValues() > 1; 9320 9321 if (OldDmask == 0) { 9322 // These are folded out, but on the chance it happens don't assert. 9323 return Node; 9324 } 9325 9326 unsigned OldBitsSet = countPopulation(OldDmask); 9327 // Work out which is the TFE/LWE lane if that is enabled. 9328 if (UsesTFC) { 9329 TFCLane = OldBitsSet; 9330 } 9331 9332 // Try to figure out the used register components 9333 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 9334 I != E; ++I) { 9335 9336 // Don't look at users of the chain. 9337 if (I.getUse().getResNo() != 0) 9338 continue; 9339 9340 // Abort if we can't understand the usage 9341 if (!I->isMachineOpcode() || 9342 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 9343 return Node; 9344 9345 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 9346 // Note that subregs are packed, i.e. Lane==0 is the first bit set 9347 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 9348 // set, etc. 9349 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 9350 9351 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 9352 if (UsesTFC && Lane == TFCLane) { 9353 Users[Lane] = *I; 9354 } else { 9355 // Set which texture component corresponds to the lane. 9356 unsigned Comp; 9357 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 9358 Comp = countTrailingZeros(Dmask); 9359 Dmask &= ~(1 << Comp); 9360 } 9361 9362 // Abort if we have more than one user per component. 9363 if (Users[Lane]) 9364 return Node; 9365 9366 Users[Lane] = *I; 9367 NewDmask |= 1 << Comp; 9368 } 9369 } 9370 9371 // Don't allow 0 dmask, as hardware assumes one channel enabled. 9372 bool NoChannels = !NewDmask; 9373 if (NoChannels) { 9374 if (!UsesTFC) { 9375 // No uses of the result and not using TFC. Then do nothing. 9376 return Node; 9377 } 9378 // If the original dmask has one channel - then nothing to do 9379 if (OldBitsSet == 1) 9380 return Node; 9381 // Use an arbitrary dmask - required for the instruction to work 9382 NewDmask = 1; 9383 } 9384 // Abort if there's no change 9385 if (NewDmask == OldDmask) 9386 return Node; 9387 9388 unsigned BitsSet = countPopulation(NewDmask); 9389 9390 // Check for TFE or LWE - increase the number of channels by one to account 9391 // for the extra return value 9392 // This will need adjustment for D16 if this is also included in 9393 // adjustWriteMask (this function) but at present D16 are excluded. 9394 unsigned NewChannels = BitsSet + UsesTFC; 9395 9396 int NewOpcode = 9397 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 9398 assert(NewOpcode != -1 && 9399 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 9400 "failed to find equivalent MIMG op"); 9401 9402 // Adjust the writemask in the node 9403 SmallVector<SDValue, 12> Ops; 9404 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 9405 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 9406 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 9407 9408 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 9409 9410 MVT ResultVT = NewChannels == 1 ? 9411 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 9412 NewChannels == 5 ? 8 : NewChannels); 9413 SDVTList NewVTList = HasChain ? 9414 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 9415 9416 9417 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 9418 NewVTList, Ops); 9419 9420 if (HasChain) { 9421 // Update chain. 9422 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 9423 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 9424 } 9425 9426 if (NewChannels == 1) { 9427 assert(Node->hasNUsesOfValue(1, 0)); 9428 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 9429 SDLoc(Node), Users[Lane]->getValueType(0), 9430 SDValue(NewNode, 0)); 9431 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 9432 return nullptr; 9433 } 9434 9435 // Update the users of the node with the new indices 9436 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 9437 SDNode *User = Users[i]; 9438 if (!User) { 9439 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 9440 // Users[0] is still nullptr because channel 0 doesn't really have a use. 9441 if (i || !NoChannels) 9442 continue; 9443 } else { 9444 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 9445 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 9446 } 9447 9448 switch (Idx) { 9449 default: break; 9450 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 9451 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 9452 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 9453 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 9454 } 9455 } 9456 9457 DAG.RemoveDeadNode(Node); 9458 return nullptr; 9459 } 9460 9461 static bool isFrameIndexOp(SDValue Op) { 9462 if (Op.getOpcode() == ISD::AssertZext) 9463 Op = Op.getOperand(0); 9464 9465 return isa<FrameIndexSDNode>(Op); 9466 } 9467 9468 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 9469 /// with frame index operands. 9470 /// LLVM assumes that inputs are to these instructions are registers. 9471 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 9472 SelectionDAG &DAG) const { 9473 if (Node->getOpcode() == ISD::CopyToReg) { 9474 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 9475 SDValue SrcVal = Node->getOperand(2); 9476 9477 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 9478 // to try understanding copies to physical registers. 9479 if (SrcVal.getValueType() == MVT::i1 && 9480 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) { 9481 SDLoc SL(Node); 9482 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 9483 SDValue VReg = DAG.getRegister( 9484 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 9485 9486 SDNode *Glued = Node->getGluedNode(); 9487 SDValue ToVReg 9488 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 9489 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 9490 SDValue ToResultReg 9491 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 9492 VReg, ToVReg.getValue(1)); 9493 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 9494 DAG.RemoveDeadNode(Node); 9495 return ToResultReg.getNode(); 9496 } 9497 } 9498 9499 SmallVector<SDValue, 8> Ops; 9500 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 9501 if (!isFrameIndexOp(Node->getOperand(i))) { 9502 Ops.push_back(Node->getOperand(i)); 9503 continue; 9504 } 9505 9506 SDLoc DL(Node); 9507 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 9508 Node->getOperand(i).getValueType(), 9509 Node->getOperand(i)), 0)); 9510 } 9511 9512 return DAG.UpdateNodeOperands(Node, Ops); 9513 } 9514 9515 /// Fold the instructions after selecting them. 9516 /// Returns null if users were already updated. 9517 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 9518 SelectionDAG &DAG) const { 9519 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9520 unsigned Opcode = Node->getMachineOpcode(); 9521 9522 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 9523 !TII->isGather4(Opcode)) { 9524 return adjustWritemask(Node, DAG); 9525 } 9526 9527 if (Opcode == AMDGPU::INSERT_SUBREG || 9528 Opcode == AMDGPU::REG_SEQUENCE) { 9529 legalizeTargetIndependentNode(Node, DAG); 9530 return Node; 9531 } 9532 9533 switch (Opcode) { 9534 case AMDGPU::V_DIV_SCALE_F32: 9535 case AMDGPU::V_DIV_SCALE_F64: { 9536 // Satisfy the operand register constraint when one of the inputs is 9537 // undefined. Ordinarily each undef value will have its own implicit_def of 9538 // a vreg, so force these to use a single register. 9539 SDValue Src0 = Node->getOperand(0); 9540 SDValue Src1 = Node->getOperand(1); 9541 SDValue Src2 = Node->getOperand(2); 9542 9543 if ((Src0.isMachineOpcode() && 9544 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 9545 (Src0 == Src1 || Src0 == Src2)) 9546 break; 9547 9548 MVT VT = Src0.getValueType().getSimpleVT(); 9549 const TargetRegisterClass *RC = getRegClassFor(VT); 9550 9551 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 9552 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 9553 9554 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 9555 UndefReg, Src0, SDValue()); 9556 9557 // src0 must be the same register as src1 or src2, even if the value is 9558 // undefined, so make sure we don't violate this constraint. 9559 if (Src0.isMachineOpcode() && 9560 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 9561 if (Src1.isMachineOpcode() && 9562 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 9563 Src0 = Src1; 9564 else if (Src2.isMachineOpcode() && 9565 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 9566 Src0 = Src2; 9567 else { 9568 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 9569 Src0 = UndefReg; 9570 Src1 = UndefReg; 9571 } 9572 } else 9573 break; 9574 9575 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 9576 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 9577 Ops.push_back(Node->getOperand(I)); 9578 9579 Ops.push_back(ImpDef.getValue(1)); 9580 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 9581 } 9582 default: 9583 break; 9584 } 9585 9586 return Node; 9587 } 9588 9589 /// Assign the register class depending on the number of 9590 /// bits set in the writemask 9591 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9592 SDNode *Node) const { 9593 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9594 9595 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 9596 9597 if (TII->isVOP3(MI.getOpcode())) { 9598 // Make sure constant bus requirements are respected. 9599 TII->legalizeOperandsVOP3(MRI, MI); 9600 return; 9601 } 9602 9603 // Replace unused atomics with the no return version. 9604 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 9605 if (NoRetAtomicOp != -1) { 9606 if (!Node->hasAnyUseOfValue(0)) { 9607 MI.setDesc(TII->get(NoRetAtomicOp)); 9608 MI.RemoveOperand(0); 9609 return; 9610 } 9611 9612 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 9613 // instruction, because the return type of these instructions is a vec2 of 9614 // the memory type, so it can be tied to the input operand. 9615 // This means these instructions always have a use, so we need to add a 9616 // special case to check if the atomic has only one extract_subreg use, 9617 // which itself has no uses. 9618 if ((Node->hasNUsesOfValue(1, 0) && 9619 Node->use_begin()->isMachineOpcode() && 9620 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 9621 !Node->use_begin()->hasAnyUseOfValue(0))) { 9622 unsigned Def = MI.getOperand(0).getReg(); 9623 9624 // Change this into a noret atomic. 9625 MI.setDesc(TII->get(NoRetAtomicOp)); 9626 MI.RemoveOperand(0); 9627 9628 // If we only remove the def operand from the atomic instruction, the 9629 // extract_subreg will be left with a use of a vreg without a def. 9630 // So we need to insert an implicit_def to avoid machine verifier 9631 // errors. 9632 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 9633 TII->get(AMDGPU::IMPLICIT_DEF), Def); 9634 } 9635 return; 9636 } 9637 } 9638 9639 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 9640 uint64_t Val) { 9641 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 9642 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 9643 } 9644 9645 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 9646 const SDLoc &DL, 9647 SDValue Ptr) const { 9648 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9649 9650 // Build the half of the subregister with the constants before building the 9651 // full 128-bit register. If we are building multiple resource descriptors, 9652 // this will allow CSEing of the 2-component register. 9653 const SDValue Ops0[] = { 9654 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 9655 buildSMovImm32(DAG, DL, 0), 9656 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 9657 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 9658 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 9659 }; 9660 9661 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 9662 MVT::v2i32, Ops0), 0); 9663 9664 // Combine the constants and the pointer. 9665 const SDValue Ops1[] = { 9666 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 9667 Ptr, 9668 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 9669 SubRegHi, 9670 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 9671 }; 9672 9673 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 9674 } 9675 9676 /// Return a resource descriptor with the 'Add TID' bit enabled 9677 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 9678 /// of the resource descriptor) to create an offset, which is added to 9679 /// the resource pointer. 9680 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 9681 SDValue Ptr, uint32_t RsrcDword1, 9682 uint64_t RsrcDword2And3) const { 9683 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 9684 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 9685 if (RsrcDword1) { 9686 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 9687 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 9688 0); 9689 } 9690 9691 SDValue DataLo = buildSMovImm32(DAG, DL, 9692 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 9693 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 9694 9695 const SDValue Ops[] = { 9696 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 9697 PtrLo, 9698 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 9699 PtrHi, 9700 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 9701 DataLo, 9702 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 9703 DataHi, 9704 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 9705 }; 9706 9707 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 9708 } 9709 9710 //===----------------------------------------------------------------------===// 9711 // SI Inline Assembly Support 9712 //===----------------------------------------------------------------------===// 9713 9714 std::pair<unsigned, const TargetRegisterClass *> 9715 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 9716 StringRef Constraint, 9717 MVT VT) const { 9718 const TargetRegisterClass *RC = nullptr; 9719 if (Constraint.size() == 1) { 9720 switch (Constraint[0]) { 9721 default: 9722 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 9723 case 's': 9724 case 'r': 9725 switch (VT.getSizeInBits()) { 9726 default: 9727 return std::make_pair(0U, nullptr); 9728 case 32: 9729 case 16: 9730 RC = &AMDGPU::SReg_32_XM0RegClass; 9731 break; 9732 case 64: 9733 RC = &AMDGPU::SGPR_64RegClass; 9734 break; 9735 case 96: 9736 RC = &AMDGPU::SReg_96RegClass; 9737 break; 9738 case 128: 9739 RC = &AMDGPU::SReg_128RegClass; 9740 break; 9741 case 160: 9742 RC = &AMDGPU::SReg_160RegClass; 9743 break; 9744 case 256: 9745 RC = &AMDGPU::SReg_256RegClass; 9746 break; 9747 case 512: 9748 RC = &AMDGPU::SReg_512RegClass; 9749 break; 9750 } 9751 break; 9752 case 'v': 9753 switch (VT.getSizeInBits()) { 9754 default: 9755 return std::make_pair(0U, nullptr); 9756 case 32: 9757 case 16: 9758 RC = &AMDGPU::VGPR_32RegClass; 9759 break; 9760 case 64: 9761 RC = &AMDGPU::VReg_64RegClass; 9762 break; 9763 case 96: 9764 RC = &AMDGPU::VReg_96RegClass; 9765 break; 9766 case 128: 9767 RC = &AMDGPU::VReg_128RegClass; 9768 break; 9769 case 160: 9770 RC = &AMDGPU::VReg_160RegClass; 9771 break; 9772 case 256: 9773 RC = &AMDGPU::VReg_256RegClass; 9774 break; 9775 case 512: 9776 RC = &AMDGPU::VReg_512RegClass; 9777 break; 9778 } 9779 break; 9780 } 9781 // We actually support i128, i16 and f16 as inline parameters 9782 // even if they are not reported as legal 9783 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 9784 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 9785 return std::make_pair(0U, RC); 9786 } 9787 9788 if (Constraint.size() > 1) { 9789 if (Constraint[1] == 'v') { 9790 RC = &AMDGPU::VGPR_32RegClass; 9791 } else if (Constraint[1] == 's') { 9792 RC = &AMDGPU::SGPR_32RegClass; 9793 } 9794 9795 if (RC) { 9796 uint32_t Idx; 9797 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 9798 if (!Failed && Idx < RC->getNumRegs()) 9799 return std::make_pair(RC->getRegister(Idx), RC); 9800 } 9801 } 9802 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 9803 } 9804 9805 SITargetLowering::ConstraintType 9806 SITargetLowering::getConstraintType(StringRef Constraint) const { 9807 if (Constraint.size() == 1) { 9808 switch (Constraint[0]) { 9809 default: break; 9810 case 's': 9811 case 'v': 9812 return C_RegisterClass; 9813 } 9814 } 9815 return TargetLowering::getConstraintType(Constraint); 9816 } 9817 9818 // Figure out which registers should be reserved for stack access. Only after 9819 // the function is legalized do we know all of the non-spill stack objects or if 9820 // calls are present. 9821 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 9822 MachineRegisterInfo &MRI = MF.getRegInfo(); 9823 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9824 const MachineFrameInfo &MFI = MF.getFrameInfo(); 9825 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 9826 9827 if (Info->isEntryFunction()) { 9828 // Callable functions have fixed registers used for stack access. 9829 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 9830 } 9831 9832 // We have to assume the SP is needed in case there are calls in the function 9833 // during lowering. Calls are only detected after the function is 9834 // lowered. We're about to reserve registers, so don't bother using it if we 9835 // aren't really going to use it. 9836 bool NeedSP = !Info->isEntryFunction() || 9837 MFI.hasVarSizedObjects() || 9838 MFI.hasCalls(); 9839 9840 if (NeedSP) { 9841 unsigned ReservedStackPtrOffsetReg = TRI->reservedStackPtrOffsetReg(MF); 9842 Info->setStackPtrOffsetReg(ReservedStackPtrOffsetReg); 9843 9844 assert(Info->getStackPtrOffsetReg() != Info->getFrameOffsetReg()); 9845 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 9846 Info->getStackPtrOffsetReg())); 9847 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 9848 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 9849 } 9850 9851 // We need to worry about replacing the default register with itself in case 9852 // of MIR testcases missing the MFI. 9853 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 9854 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 9855 9856 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 9857 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 9858 9859 if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) { 9860 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG, 9861 Info->getScratchWaveOffsetReg()); 9862 } 9863 9864 Info->limitOccupancy(MF); 9865 9866 TargetLoweringBase::finalizeLowering(MF); 9867 } 9868 9869 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 9870 KnownBits &Known, 9871 const APInt &DemandedElts, 9872 const SelectionDAG &DAG, 9873 unsigned Depth) const { 9874 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 9875 DAG, Depth); 9876 9877 if (getSubtarget()->enableHugePrivateBuffer()) 9878 return; 9879 9880 // Technically it may be possible to have a dispatch with a single workitem 9881 // that uses the full private memory size, but that's not really useful. We 9882 // can't use vaddr in MUBUF instructions if we don't know the address 9883 // calculation won't overflow, so assume the sign bit is never set. 9884 Known.Zero.setHighBits(AssumeFrameIndexHighZeroBits); 9885 } 9886 9887 LLVM_ATTRIBUTE_UNUSED 9888 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 9889 assert(N->getOpcode() == ISD::CopyFromReg); 9890 do { 9891 // Follow the chain until we find an INLINEASM node. 9892 N = N->getOperand(0).getNode(); 9893 if (N->getOpcode() == ISD::INLINEASM || 9894 N->getOpcode() == ISD::INLINEASM_BR) 9895 return true; 9896 } while (N->getOpcode() == ISD::CopyFromReg); 9897 return false; 9898 } 9899 9900 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 9901 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 9902 { 9903 switch (N->getOpcode()) { 9904 case ISD::CopyFromReg: 9905 { 9906 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 9907 const MachineFunction * MF = FLI->MF; 9908 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 9909 const MachineRegisterInfo &MRI = MF->getRegInfo(); 9910 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo(); 9911 unsigned Reg = R->getReg(); 9912 if (TRI.isPhysicalRegister(Reg)) 9913 return !TRI.isSGPRReg(MRI, Reg); 9914 9915 if (MRI.isLiveIn(Reg)) { 9916 // workitem.id.x workitem.id.y workitem.id.z 9917 // Any VGPR formal argument is also considered divergent 9918 if (!TRI.isSGPRReg(MRI, Reg)) 9919 return true; 9920 // Formal arguments of non-entry functions 9921 // are conservatively considered divergent 9922 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv())) 9923 return true; 9924 return false; 9925 } 9926 const Value *V = FLI->getValueFromVirtualReg(Reg); 9927 if (V) 9928 return KDA->isDivergent(V); 9929 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 9930 return !TRI.isSGPRReg(MRI, Reg); 9931 } 9932 break; 9933 case ISD::LOAD: { 9934 const LoadSDNode *L = cast<LoadSDNode>(N); 9935 unsigned AS = L->getAddressSpace(); 9936 // A flat load may access private memory. 9937 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 9938 } break; 9939 case ISD::CALLSEQ_END: 9940 return true; 9941 break; 9942 case ISD::INTRINSIC_WO_CHAIN: 9943 { 9944 9945 } 9946 return AMDGPU::isIntrinsicSourceOfDivergence( 9947 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 9948 case ISD::INTRINSIC_W_CHAIN: 9949 return AMDGPU::isIntrinsicSourceOfDivergence( 9950 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 9951 // In some cases intrinsics that are a source of divergence have been 9952 // lowered to AMDGPUISD so we also need to check those too. 9953 case AMDGPUISD::INTERP_MOV: 9954 case AMDGPUISD::INTERP_P1: 9955 case AMDGPUISD::INTERP_P2: 9956 return true; 9957 } 9958 return false; 9959 } 9960 9961 bool SITargetLowering::denormalsEnabledForType(EVT VT) const { 9962 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 9963 case MVT::f32: 9964 return Subtarget->hasFP32Denormals(); 9965 case MVT::f64: 9966 return Subtarget->hasFP64Denormals(); 9967 case MVT::f16: 9968 return Subtarget->hasFP16Denormals(); 9969 default: 9970 return false; 9971 } 9972 } 9973 9974 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 9975 const SelectionDAG &DAG, 9976 bool SNaN, 9977 unsigned Depth) const { 9978 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 9979 const MachineFunction &MF = DAG.getMachineFunction(); 9980 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9981 9982 if (Info->getMode().DX10Clamp) 9983 return true; // Clamped to 0. 9984 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 9985 } 9986 9987 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 9988 SNaN, Depth); 9989 } 9990 9991 TargetLowering::AtomicExpansionKind 9992 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 9993 switch (RMW->getOperation()) { 9994 case AtomicRMWInst::FAdd: { 9995 Type *Ty = RMW->getType(); 9996 9997 // We don't have a way to support 16-bit atomics now, so just leave them 9998 // as-is. 9999 if (Ty->isHalfTy()) 10000 return AtomicExpansionKind::None; 10001 10002 if (!Ty->isFloatTy()) 10003 return AtomicExpansionKind::CmpXChg; 10004 10005 // TODO: Do have these for flat. Older targets also had them for buffers. 10006 unsigned AS = RMW->getPointerAddressSpace(); 10007 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 10008 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 10009 } 10010 default: 10011 break; 10012 } 10013 10014 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 10015 } 10016