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