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 DebugLoc DL = MI.getDebugLoc(); 3592 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3593 .add(MI.getOperand(0)) 3594 .addImm(MFI->getLDSSize()); 3595 MI.eraseFromParent(); 3596 return BB; 3597 } 3598 case AMDGPU::SI_INDIRECT_SRC_V1: 3599 case AMDGPU::SI_INDIRECT_SRC_V2: 3600 case AMDGPU::SI_INDIRECT_SRC_V4: 3601 case AMDGPU::SI_INDIRECT_SRC_V8: 3602 case AMDGPU::SI_INDIRECT_SRC_V16: 3603 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3604 case AMDGPU::SI_INDIRECT_DST_V1: 3605 case AMDGPU::SI_INDIRECT_DST_V2: 3606 case AMDGPU::SI_INDIRECT_DST_V4: 3607 case AMDGPU::SI_INDIRECT_DST_V8: 3608 case AMDGPU::SI_INDIRECT_DST_V16: 3609 return emitIndirectDst(MI, *BB, *getSubtarget()); 3610 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3611 case AMDGPU::SI_KILL_I1_PSEUDO: 3612 return splitKillBlock(MI, BB); 3613 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3614 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3615 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3616 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3617 3618 unsigned Dst = MI.getOperand(0).getReg(); 3619 unsigned Src0 = MI.getOperand(1).getReg(); 3620 unsigned Src1 = MI.getOperand(2).getReg(); 3621 const DebugLoc &DL = MI.getDebugLoc(); 3622 unsigned SrcCond = MI.getOperand(3).getReg(); 3623 3624 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3625 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3626 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3627 unsigned SrcCondCopy = MRI.createVirtualRegister(CondRC); 3628 3629 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3630 .addReg(SrcCond); 3631 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3632 .addImm(0) 3633 .addReg(Src0, 0, AMDGPU::sub0) 3634 .addImm(0) 3635 .addReg(Src1, 0, AMDGPU::sub0) 3636 .addReg(SrcCondCopy); 3637 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3638 .addImm(0) 3639 .addReg(Src0, 0, AMDGPU::sub1) 3640 .addImm(0) 3641 .addReg(Src1, 0, AMDGPU::sub1) 3642 .addReg(SrcCondCopy); 3643 3644 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3645 .addReg(DstLo) 3646 .addImm(AMDGPU::sub0) 3647 .addReg(DstHi) 3648 .addImm(AMDGPU::sub1); 3649 MI.eraseFromParent(); 3650 return BB; 3651 } 3652 case AMDGPU::SI_BR_UNDEF: { 3653 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3654 const DebugLoc &DL = MI.getDebugLoc(); 3655 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3656 .add(MI.getOperand(0)); 3657 Br->getOperand(1).setIsUndef(true); // read undef SCC 3658 MI.eraseFromParent(); 3659 return BB; 3660 } 3661 case AMDGPU::ADJCALLSTACKUP: 3662 case AMDGPU::ADJCALLSTACKDOWN: { 3663 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3664 MachineInstrBuilder MIB(*MF, &MI); 3665 3666 // Add an implicit use of the frame offset reg to prevent the restore copy 3667 // inserted after the call from being reorderd after stack operations in the 3668 // the caller's frame. 3669 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3670 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 3671 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 3672 return BB; 3673 } 3674 case AMDGPU::SI_CALL_ISEL: { 3675 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3676 const DebugLoc &DL = MI.getDebugLoc(); 3677 3678 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3679 3680 MachineInstrBuilder MIB; 3681 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 3682 3683 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 3684 MIB.add(MI.getOperand(I)); 3685 3686 MIB.cloneMemRefs(MI); 3687 MI.eraseFromParent(); 3688 return BB; 3689 } 3690 case AMDGPU::V_ADD_I32_e32: 3691 case AMDGPU::V_SUB_I32_e32: 3692 case AMDGPU::V_SUBREV_I32_e32: { 3693 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 3694 const DebugLoc &DL = MI.getDebugLoc(); 3695 unsigned Opc = MI.getOpcode(); 3696 3697 bool NeedClampOperand = false; 3698 if (TII->pseudoToMCOpcode(Opc) == -1) { 3699 Opc = AMDGPU::getVOPe64(Opc); 3700 NeedClampOperand = true; 3701 } 3702 3703 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 3704 if (TII->isVOP3(*I)) { 3705 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3706 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3707 I.addReg(TRI->getVCC(), RegState::Define); 3708 } 3709 I.add(MI.getOperand(1)) 3710 .add(MI.getOperand(2)); 3711 if (NeedClampOperand) 3712 I.addImm(0); // clamp bit for e64 encoding 3713 3714 TII->legalizeOperands(*I); 3715 3716 MI.eraseFromParent(); 3717 return BB; 3718 } 3719 case AMDGPU::DS_GWS_INIT: 3720 case AMDGPU::DS_GWS_SEMA_V: 3721 case AMDGPU::DS_GWS_SEMA_BR: 3722 case AMDGPU::DS_GWS_SEMA_P: 3723 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 3724 case AMDGPU::DS_GWS_BARRIER: 3725 if (getSubtarget()->hasGWSAutoReplay()) 3726 return BB; 3727 return emitGWSMemViolTestLoop(MI, BB); 3728 default: 3729 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3730 } 3731 } 3732 3733 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 3734 return isTypeLegal(VT.getScalarType()); 3735 } 3736 3737 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3738 // This currently forces unfolding various combinations of fsub into fma with 3739 // free fneg'd operands. As long as we have fast FMA (controlled by 3740 // isFMAFasterThanFMulAndFAdd), we should perform these. 3741 3742 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3743 // most of these combines appear to be cycle neutral but save on instruction 3744 // count / code size. 3745 return true; 3746 } 3747 3748 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3749 EVT VT) const { 3750 if (!VT.isVector()) { 3751 return MVT::i1; 3752 } 3753 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3754 } 3755 3756 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3757 // TODO: Should i16 be used always if legal? For now it would force VALU 3758 // shifts. 3759 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3760 } 3761 3762 // Answering this is somewhat tricky and depends on the specific device which 3763 // have different rates for fma or all f64 operations. 3764 // 3765 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3766 // regardless of which device (although the number of cycles differs between 3767 // devices), so it is always profitable for f64. 3768 // 3769 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3770 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3771 // which we can always do even without fused FP ops since it returns the same 3772 // result as the separate operations and since it is always full 3773 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3774 // however does not support denormals, so we do report fma as faster if we have 3775 // a fast fma device and require denormals. 3776 // 3777 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 3778 VT = VT.getScalarType(); 3779 3780 switch (VT.getSimpleVT().SimpleTy) { 3781 case MVT::f32: { 3782 // This is as fast on some subtargets. However, we always have full rate f32 3783 // mad available which returns the same result as the separate operations 3784 // which we should prefer over fma. We can't use this if we want to support 3785 // denormals, so only report this in these cases. 3786 if (Subtarget->hasFP32Denormals()) 3787 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 3788 3789 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 3790 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 3791 } 3792 case MVT::f64: 3793 return true; 3794 case MVT::f16: 3795 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals(); 3796 default: 3797 break; 3798 } 3799 3800 return false; 3801 } 3802 3803 //===----------------------------------------------------------------------===// 3804 // Custom DAG Lowering Operations 3805 //===----------------------------------------------------------------------===// 3806 3807 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3808 // wider vector type is legal. 3809 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 3810 SelectionDAG &DAG) const { 3811 unsigned Opc = Op.getOpcode(); 3812 EVT VT = Op.getValueType(); 3813 assert(VT == MVT::v4f16); 3814 3815 SDValue Lo, Hi; 3816 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 3817 3818 SDLoc SL(Op); 3819 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 3820 Op->getFlags()); 3821 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 3822 Op->getFlags()); 3823 3824 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3825 } 3826 3827 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3828 // wider vector type is legal. 3829 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 3830 SelectionDAG &DAG) const { 3831 unsigned Opc = Op.getOpcode(); 3832 EVT VT = Op.getValueType(); 3833 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 3834 3835 SDValue Lo0, Hi0; 3836 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 3837 SDValue Lo1, Hi1; 3838 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 3839 3840 SDLoc SL(Op); 3841 3842 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 3843 Op->getFlags()); 3844 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 3845 Op->getFlags()); 3846 3847 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3848 } 3849 3850 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 3851 switch (Op.getOpcode()) { 3852 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 3853 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 3854 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 3855 case ISD::LOAD: { 3856 SDValue Result = LowerLOAD(Op, DAG); 3857 assert((!Result.getNode() || 3858 Result.getNode()->getNumValues() == 2) && 3859 "Load should return a value and a chain"); 3860 return Result; 3861 } 3862 3863 case ISD::FSIN: 3864 case ISD::FCOS: 3865 return LowerTrig(Op, DAG); 3866 case ISD::SELECT: return LowerSELECT(Op, DAG); 3867 case ISD::FDIV: return LowerFDIV(Op, DAG); 3868 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 3869 case ISD::STORE: return LowerSTORE(Op, DAG); 3870 case ISD::GlobalAddress: { 3871 MachineFunction &MF = DAG.getMachineFunction(); 3872 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 3873 return LowerGlobalAddress(MFI, Op, DAG); 3874 } 3875 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3876 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 3877 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 3878 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 3879 case ISD::INSERT_VECTOR_ELT: 3880 return lowerINSERT_VECTOR_ELT(Op, DAG); 3881 case ISD::EXTRACT_VECTOR_ELT: 3882 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3883 case ISD::BUILD_VECTOR: 3884 return lowerBUILD_VECTOR(Op, DAG); 3885 case ISD::FP_ROUND: 3886 return lowerFP_ROUND(Op, DAG); 3887 case ISD::TRAP: 3888 return lowerTRAP(Op, DAG); 3889 case ISD::DEBUGTRAP: 3890 return lowerDEBUGTRAP(Op, DAG); 3891 case ISD::FABS: 3892 case ISD::FNEG: 3893 case ISD::FCANONICALIZE: 3894 return splitUnaryVectorOp(Op, DAG); 3895 case ISD::FMINNUM: 3896 case ISD::FMAXNUM: 3897 return lowerFMINNUM_FMAXNUM(Op, DAG); 3898 case ISD::SHL: 3899 case ISD::SRA: 3900 case ISD::SRL: 3901 case ISD::ADD: 3902 case ISD::SUB: 3903 case ISD::MUL: 3904 case ISD::SMIN: 3905 case ISD::SMAX: 3906 case ISD::UMIN: 3907 case ISD::UMAX: 3908 case ISD::FADD: 3909 case ISD::FMUL: 3910 case ISD::FMINNUM_IEEE: 3911 case ISD::FMAXNUM_IEEE: 3912 return splitBinaryVectorOp(Op, DAG); 3913 } 3914 return SDValue(); 3915 } 3916 3917 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 3918 const SDLoc &DL, 3919 SelectionDAG &DAG, bool Unpacked) { 3920 if (!LoadVT.isVector()) 3921 return Result; 3922 3923 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 3924 // Truncate to v2i16/v4i16. 3925 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 3926 3927 // Workaround legalizer not scalarizing truncate after vector op 3928 // legalization byt not creating intermediate vector trunc. 3929 SmallVector<SDValue, 4> Elts; 3930 DAG.ExtractVectorElements(Result, Elts); 3931 for (SDValue &Elt : Elts) 3932 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 3933 3934 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 3935 3936 // Bitcast to original type (v2f16/v4f16). 3937 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 3938 } 3939 3940 // Cast back to the original packed type. 3941 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 3942 } 3943 3944 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 3945 MemSDNode *M, 3946 SelectionDAG &DAG, 3947 ArrayRef<SDValue> Ops, 3948 bool IsIntrinsic) const { 3949 SDLoc DL(M); 3950 3951 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 3952 EVT LoadVT = M->getValueType(0); 3953 3954 EVT EquivLoadVT = LoadVT; 3955 if (Unpacked && LoadVT.isVector()) { 3956 EquivLoadVT = LoadVT.isVector() ? 3957 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 3958 LoadVT.getVectorNumElements()) : LoadVT; 3959 } 3960 3961 // Change from v4f16/v2f16 to EquivLoadVT. 3962 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 3963 3964 SDValue Load 3965 = DAG.getMemIntrinsicNode( 3966 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 3967 VTList, Ops, M->getMemoryVT(), 3968 M->getMemOperand()); 3969 if (!Unpacked) // Just adjusted the opcode. 3970 return Load; 3971 3972 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 3973 3974 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 3975 } 3976 3977 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 3978 SDNode *N, SelectionDAG &DAG) { 3979 EVT VT = N->getValueType(0); 3980 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 3981 int CondCode = CD->getSExtValue(); 3982 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 3983 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 3984 return DAG.getUNDEF(VT); 3985 3986 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 3987 3988 SDValue LHS = N->getOperand(1); 3989 SDValue RHS = N->getOperand(2); 3990 3991 SDLoc DL(N); 3992 3993 EVT CmpVT = LHS.getValueType(); 3994 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 3995 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 3996 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 3997 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 3998 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 3999 } 4000 4001 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4002 4003 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4004 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4005 4006 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4007 DAG.getCondCode(CCOpcode)); 4008 if (VT.bitsEq(CCVT)) 4009 return SetCC; 4010 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4011 } 4012 4013 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4014 SDNode *N, SelectionDAG &DAG) { 4015 EVT VT = N->getValueType(0); 4016 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4017 4018 int CondCode = CD->getSExtValue(); 4019 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4020 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4021 return DAG.getUNDEF(VT); 4022 } 4023 4024 SDValue Src0 = N->getOperand(1); 4025 SDValue Src1 = N->getOperand(2); 4026 EVT CmpVT = Src0.getValueType(); 4027 SDLoc SL(N); 4028 4029 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4030 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4031 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4032 } 4033 4034 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4035 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4036 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4037 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4038 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4039 Src1, DAG.getCondCode(CCOpcode)); 4040 if (VT.bitsEq(CCVT)) 4041 return SetCC; 4042 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4043 } 4044 4045 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4046 SmallVectorImpl<SDValue> &Results, 4047 SelectionDAG &DAG) const { 4048 switch (N->getOpcode()) { 4049 case ISD::INSERT_VECTOR_ELT: { 4050 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4051 Results.push_back(Res); 4052 return; 4053 } 4054 case ISD::EXTRACT_VECTOR_ELT: { 4055 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4056 Results.push_back(Res); 4057 return; 4058 } 4059 case ISD::INTRINSIC_WO_CHAIN: { 4060 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4061 switch (IID) { 4062 case Intrinsic::amdgcn_cvt_pkrtz: { 4063 SDValue Src0 = N->getOperand(1); 4064 SDValue Src1 = N->getOperand(2); 4065 SDLoc SL(N); 4066 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4067 Src0, Src1); 4068 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4069 return; 4070 } 4071 case Intrinsic::amdgcn_cvt_pknorm_i16: 4072 case Intrinsic::amdgcn_cvt_pknorm_u16: 4073 case Intrinsic::amdgcn_cvt_pk_i16: 4074 case Intrinsic::amdgcn_cvt_pk_u16: { 4075 SDValue Src0 = N->getOperand(1); 4076 SDValue Src1 = N->getOperand(2); 4077 SDLoc SL(N); 4078 unsigned Opcode; 4079 4080 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4081 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4082 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4083 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4084 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4085 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4086 else 4087 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4088 4089 EVT VT = N->getValueType(0); 4090 if (isTypeLegal(VT)) 4091 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4092 else { 4093 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4094 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4095 } 4096 return; 4097 } 4098 } 4099 break; 4100 } 4101 case ISD::INTRINSIC_W_CHAIN: { 4102 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4103 Results.push_back(Res); 4104 Results.push_back(Res.getValue(1)); 4105 return; 4106 } 4107 4108 break; 4109 } 4110 case ISD::SELECT: { 4111 SDLoc SL(N); 4112 EVT VT = N->getValueType(0); 4113 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4114 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4115 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4116 4117 EVT SelectVT = NewVT; 4118 if (NewVT.bitsLT(MVT::i32)) { 4119 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4120 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4121 SelectVT = MVT::i32; 4122 } 4123 4124 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4125 N->getOperand(0), LHS, RHS); 4126 4127 if (NewVT != SelectVT) 4128 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4129 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4130 return; 4131 } 4132 case ISD::FNEG: { 4133 if (N->getValueType(0) != MVT::v2f16) 4134 break; 4135 4136 SDLoc SL(N); 4137 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4138 4139 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4140 BC, 4141 DAG.getConstant(0x80008000, SL, MVT::i32)); 4142 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4143 return; 4144 } 4145 case ISD::FABS: { 4146 if (N->getValueType(0) != MVT::v2f16) 4147 break; 4148 4149 SDLoc SL(N); 4150 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4151 4152 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4153 BC, 4154 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4155 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4156 return; 4157 } 4158 default: 4159 break; 4160 } 4161 } 4162 4163 /// Helper function for LowerBRCOND 4164 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4165 4166 SDNode *Parent = Value.getNode(); 4167 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4168 I != E; ++I) { 4169 4170 if (I.getUse().get() != Value) 4171 continue; 4172 4173 if (I->getOpcode() == Opcode) 4174 return *I; 4175 } 4176 return nullptr; 4177 } 4178 4179 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4180 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4181 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4182 case Intrinsic::amdgcn_if: 4183 return AMDGPUISD::IF; 4184 case Intrinsic::amdgcn_else: 4185 return AMDGPUISD::ELSE; 4186 case Intrinsic::amdgcn_loop: 4187 return AMDGPUISD::LOOP; 4188 case Intrinsic::amdgcn_end_cf: 4189 llvm_unreachable("should not occur"); 4190 default: 4191 return 0; 4192 } 4193 } 4194 4195 // break, if_break, else_break are all only used as inputs to loop, not 4196 // directly as branch conditions. 4197 return 0; 4198 } 4199 4200 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4201 const Triple &TT = getTargetMachine().getTargetTriple(); 4202 return (GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4203 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4204 AMDGPU::shouldEmitConstantsToTextSection(TT); 4205 } 4206 4207 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4208 // FIXME: Either avoid relying on address space here or change the default 4209 // address space for functions to avoid the explicit check. 4210 return (GV->getValueType()->isFunctionTy() || 4211 GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 4212 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4213 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4214 !shouldEmitFixup(GV) && 4215 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4216 } 4217 4218 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4219 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4220 } 4221 4222 /// This transforms the control flow intrinsics to get the branch destination as 4223 /// last parameter, also switches branch target with BR if the need arise 4224 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4225 SelectionDAG &DAG) const { 4226 SDLoc DL(BRCOND); 4227 4228 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4229 SDValue Target = BRCOND.getOperand(2); 4230 SDNode *BR = nullptr; 4231 SDNode *SetCC = nullptr; 4232 4233 if (Intr->getOpcode() == ISD::SETCC) { 4234 // As long as we negate the condition everything is fine 4235 SetCC = Intr; 4236 Intr = SetCC->getOperand(0).getNode(); 4237 4238 } else { 4239 // Get the target from BR if we don't negate the condition 4240 BR = findUser(BRCOND, ISD::BR); 4241 Target = BR->getOperand(1); 4242 } 4243 4244 // FIXME: This changes the types of the intrinsics instead of introducing new 4245 // nodes with the correct types. 4246 // e.g. llvm.amdgcn.loop 4247 4248 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 4249 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 4250 4251 unsigned CFNode = isCFIntrinsic(Intr); 4252 if (CFNode == 0) { 4253 // This is a uniform branch so we don't need to legalize. 4254 return BRCOND; 4255 } 4256 4257 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4258 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4259 4260 assert(!SetCC || 4261 (SetCC->getConstantOperandVal(1) == 1 && 4262 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4263 ISD::SETNE)); 4264 4265 // operands of the new intrinsic call 4266 SmallVector<SDValue, 4> Ops; 4267 if (HaveChain) 4268 Ops.push_back(BRCOND.getOperand(0)); 4269 4270 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4271 Ops.push_back(Target); 4272 4273 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4274 4275 // build the new intrinsic call 4276 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4277 4278 if (!HaveChain) { 4279 SDValue Ops[] = { 4280 SDValue(Result, 0), 4281 BRCOND.getOperand(0) 4282 }; 4283 4284 Result = DAG.getMergeValues(Ops, DL).getNode(); 4285 } 4286 4287 if (BR) { 4288 // Give the branch instruction our target 4289 SDValue Ops[] = { 4290 BR->getOperand(0), 4291 BRCOND.getOperand(2) 4292 }; 4293 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4294 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4295 BR = NewBR.getNode(); 4296 } 4297 4298 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4299 4300 // Copy the intrinsic results to registers 4301 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4302 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4303 if (!CopyToReg) 4304 continue; 4305 4306 Chain = DAG.getCopyToReg( 4307 Chain, DL, 4308 CopyToReg->getOperand(1), 4309 SDValue(Result, i - 1), 4310 SDValue()); 4311 4312 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4313 } 4314 4315 // Remove the old intrinsic from the chain 4316 DAG.ReplaceAllUsesOfValueWith( 4317 SDValue(Intr, Intr->getNumValues() - 1), 4318 Intr->getOperand(0)); 4319 4320 return Chain; 4321 } 4322 4323 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4324 SelectionDAG &DAG) const { 4325 MVT VT = Op.getSimpleValueType(); 4326 SDLoc DL(Op); 4327 // Checking the depth 4328 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4329 return DAG.getConstant(0, DL, VT); 4330 4331 MachineFunction &MF = DAG.getMachineFunction(); 4332 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4333 // Check for kernel and shader functions 4334 if (Info->isEntryFunction()) 4335 return DAG.getConstant(0, DL, VT); 4336 4337 MachineFrameInfo &MFI = MF.getFrameInfo(); 4338 // There is a call to @llvm.returnaddress in this function 4339 MFI.setReturnAddressIsTaken(true); 4340 4341 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4342 // Get the return address reg and mark it as an implicit live-in 4343 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4344 4345 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4346 } 4347 4348 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 4349 SDValue Op, 4350 const SDLoc &DL, 4351 EVT VT) const { 4352 return Op.getValueType().bitsLE(VT) ? 4353 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4354 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 4355 } 4356 4357 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4358 assert(Op.getValueType() == MVT::f16 && 4359 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4360 4361 SDValue Src = Op.getOperand(0); 4362 EVT SrcVT = Src.getValueType(); 4363 if (SrcVT != MVT::f64) 4364 return Op; 4365 4366 SDLoc DL(Op); 4367 4368 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4369 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4370 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4371 } 4372 4373 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4374 SelectionDAG &DAG) const { 4375 EVT VT = Op.getValueType(); 4376 const MachineFunction &MF = DAG.getMachineFunction(); 4377 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4378 bool IsIEEEMode = Info->getMode().IEEE; 4379 4380 // FIXME: Assert during eslection that this is only selected for 4381 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4382 // mode functions, but this happens to be OK since it's only done in cases 4383 // where there is known no sNaN. 4384 if (IsIEEEMode) 4385 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 4386 4387 if (VT == MVT::v4f16) 4388 return splitBinaryVectorOp(Op, DAG); 4389 return Op; 4390 } 4391 4392 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4393 SDLoc SL(Op); 4394 SDValue Chain = Op.getOperand(0); 4395 4396 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4397 !Subtarget->isTrapHandlerEnabled()) 4398 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4399 4400 MachineFunction &MF = DAG.getMachineFunction(); 4401 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4402 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4403 assert(UserSGPR != AMDGPU::NoRegister); 4404 SDValue QueuePtr = CreateLiveInRegister( 4405 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4406 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4407 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4408 QueuePtr, SDValue()); 4409 SDValue Ops[] = { 4410 ToReg, 4411 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 4412 SGPR01, 4413 ToReg.getValue(1) 4414 }; 4415 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4416 } 4417 4418 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 4419 SDLoc SL(Op); 4420 SDValue Chain = Op.getOperand(0); 4421 MachineFunction &MF = DAG.getMachineFunction(); 4422 4423 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4424 !Subtarget->isTrapHandlerEnabled()) { 4425 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4426 "debugtrap handler not supported", 4427 Op.getDebugLoc(), 4428 DS_Warning); 4429 LLVMContext &Ctx = MF.getFunction().getContext(); 4430 Ctx.diagnose(NoTrap); 4431 return Chain; 4432 } 4433 4434 SDValue Ops[] = { 4435 Chain, 4436 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 4437 }; 4438 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4439 } 4440 4441 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4442 SelectionDAG &DAG) const { 4443 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4444 if (Subtarget->hasApertureRegs()) { 4445 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 4446 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4447 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4448 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 4449 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4450 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4451 unsigned Encoding = 4452 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4453 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4454 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4455 4456 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4457 SDValue ApertureReg = SDValue( 4458 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4459 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4460 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4461 } 4462 4463 MachineFunction &MF = DAG.getMachineFunction(); 4464 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4465 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4466 assert(UserSGPR != AMDGPU::NoRegister); 4467 4468 SDValue QueuePtr = CreateLiveInRegister( 4469 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4470 4471 // Offset into amd_queue_t for group_segment_aperture_base_hi / 4472 // private_segment_aperture_base_hi. 4473 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 4474 4475 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 4476 4477 // TODO: Use custom target PseudoSourceValue. 4478 // TODO: We should use the value from the IR intrinsic call, but it might not 4479 // be available and how do we get it? 4480 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()), 4481 AMDGPUAS::CONSTANT_ADDRESS)); 4482 4483 MachinePointerInfo PtrInfo(V, StructOffset); 4484 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4485 MinAlign(64, StructOffset), 4486 MachineMemOperand::MODereferenceable | 4487 MachineMemOperand::MOInvariant); 4488 } 4489 4490 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4491 SelectionDAG &DAG) const { 4492 SDLoc SL(Op); 4493 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4494 4495 SDValue Src = ASC->getOperand(0); 4496 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4497 4498 const AMDGPUTargetMachine &TM = 4499 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4500 4501 // flat -> local/private 4502 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4503 unsigned DestAS = ASC->getDestAddressSpace(); 4504 4505 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 4506 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 4507 unsigned NullVal = TM.getNullPointerValue(DestAS); 4508 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4509 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4510 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4511 4512 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4513 NonNull, Ptr, SegmentNullPtr); 4514 } 4515 } 4516 4517 // local/private -> flat 4518 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4519 unsigned SrcAS = ASC->getSrcAddressSpace(); 4520 4521 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 4522 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 4523 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4524 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4525 4526 SDValue NonNull 4527 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4528 4529 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4530 SDValue CvtPtr 4531 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4532 4533 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4534 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4535 FlatNullPtr); 4536 } 4537 } 4538 4539 // global <-> flat are no-ops and never emitted. 4540 4541 const MachineFunction &MF = DAG.getMachineFunction(); 4542 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 4543 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 4544 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 4545 4546 return DAG.getUNDEF(ASC->getValueType(0)); 4547 } 4548 4549 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4550 SelectionDAG &DAG) const { 4551 SDValue Vec = Op.getOperand(0); 4552 SDValue InsVal = Op.getOperand(1); 4553 SDValue Idx = Op.getOperand(2); 4554 EVT VecVT = Vec.getValueType(); 4555 EVT EltVT = VecVT.getVectorElementType(); 4556 unsigned VecSize = VecVT.getSizeInBits(); 4557 unsigned EltSize = EltVT.getSizeInBits(); 4558 4559 4560 assert(VecSize <= 64); 4561 4562 unsigned NumElts = VecVT.getVectorNumElements(); 4563 SDLoc SL(Op); 4564 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 4565 4566 if (NumElts == 4 && EltSize == 16 && KIdx) { 4567 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 4568 4569 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4570 DAG.getConstant(0, SL, MVT::i32)); 4571 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4572 DAG.getConstant(1, SL, MVT::i32)); 4573 4574 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 4575 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 4576 4577 unsigned Idx = KIdx->getZExtValue(); 4578 bool InsertLo = Idx < 2; 4579 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 4580 InsertLo ? LoVec : HiVec, 4581 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 4582 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 4583 4584 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 4585 4586 SDValue Concat = InsertLo ? 4587 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 4588 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 4589 4590 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 4591 } 4592 4593 if (isa<ConstantSDNode>(Idx)) 4594 return SDValue(); 4595 4596 MVT IntVT = MVT::getIntegerVT(VecSize); 4597 4598 // Avoid stack access for dynamic indexing. 4599 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 4600 4601 // Create a congruent vector with the target value in each element so that 4602 // the required element can be masked and ORed into the target vector. 4603 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 4604 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 4605 4606 assert(isPowerOf2_32(EltSize)); 4607 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4608 4609 // Convert vector index to bit-index. 4610 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4611 4612 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4613 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 4614 DAG.getConstant(0xffff, SL, IntVT), 4615 ScaledIdx); 4616 4617 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 4618 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 4619 DAG.getNOT(SL, BFM, IntVT), BCVec); 4620 4621 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 4622 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 4623 } 4624 4625 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4626 SelectionDAG &DAG) const { 4627 SDLoc SL(Op); 4628 4629 EVT ResultVT = Op.getValueType(); 4630 SDValue Vec = Op.getOperand(0); 4631 SDValue Idx = Op.getOperand(1); 4632 EVT VecVT = Vec.getValueType(); 4633 unsigned VecSize = VecVT.getSizeInBits(); 4634 EVT EltVT = VecVT.getVectorElementType(); 4635 assert(VecSize <= 64); 4636 4637 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 4638 4639 // Make sure we do any optimizations that will make it easier to fold 4640 // source modifiers before obscuring it with bit operations. 4641 4642 // XXX - Why doesn't this get called when vector_shuffle is expanded? 4643 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 4644 return Combined; 4645 4646 unsigned EltSize = EltVT.getSizeInBits(); 4647 assert(isPowerOf2_32(EltSize)); 4648 4649 MVT IntVT = MVT::getIntegerVT(VecSize); 4650 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4651 4652 // Convert vector index to bit-index (* EltSize) 4653 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4654 4655 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4656 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 4657 4658 if (ResultVT == MVT::f16) { 4659 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 4660 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 4661 } 4662 4663 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 4664 } 4665 4666 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 4667 SelectionDAG &DAG) const { 4668 SDLoc SL(Op); 4669 EVT VT = Op.getValueType(); 4670 4671 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 4672 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 4673 4674 // Turn into pair of packed build_vectors. 4675 // TODO: Special case for constants that can be materialized with s_mov_b64. 4676 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 4677 { Op.getOperand(0), Op.getOperand(1) }); 4678 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 4679 { Op.getOperand(2), Op.getOperand(3) }); 4680 4681 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 4682 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 4683 4684 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 4685 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 4686 } 4687 4688 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 4689 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 4690 4691 SDValue Lo = Op.getOperand(0); 4692 SDValue Hi = Op.getOperand(1); 4693 4694 // Avoid adding defined bits with the zero_extend. 4695 if (Hi.isUndef()) { 4696 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4697 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 4698 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 4699 } 4700 4701 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 4702 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 4703 4704 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 4705 DAG.getConstant(16, SL, MVT::i32)); 4706 if (Lo.isUndef()) 4707 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 4708 4709 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4710 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 4711 4712 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 4713 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 4714 } 4715 4716 bool 4717 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 4718 // We can fold offsets for anything that doesn't require a GOT relocation. 4719 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 4720 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4721 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4722 !shouldEmitGOTReloc(GA->getGlobal()); 4723 } 4724 4725 static SDValue 4726 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 4727 const SDLoc &DL, unsigned Offset, EVT PtrVT, 4728 unsigned GAFlags = SIInstrInfo::MO_NONE) { 4729 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 4730 // lowered to the following code sequence: 4731 // 4732 // For constant address space: 4733 // s_getpc_b64 s[0:1] 4734 // s_add_u32 s0, s0, $symbol 4735 // s_addc_u32 s1, s1, 0 4736 // 4737 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 4738 // a fixup or relocation is emitted to replace $symbol with a literal 4739 // constant, which is a pc-relative offset from the encoding of the $symbol 4740 // operand to the global variable. 4741 // 4742 // For global address space: 4743 // s_getpc_b64 s[0:1] 4744 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 4745 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 4746 // 4747 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 4748 // fixups or relocations are emitted to replace $symbol@*@lo and 4749 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 4750 // which is a 64-bit pc-relative offset from the encoding of the $symbol 4751 // operand to the global variable. 4752 // 4753 // What we want here is an offset from the value returned by s_getpc 4754 // (which is the address of the s_add_u32 instruction) to the global 4755 // variable, but since the encoding of $symbol starts 4 bytes after the start 4756 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 4757 // small. This requires us to add 4 to the global variable offset in order to 4758 // compute the correct address. 4759 unsigned LoFlags = GAFlags; 4760 if (LoFlags == SIInstrInfo::MO_NONE) 4761 LoFlags = SIInstrInfo::MO_REL32; 4762 SDValue PtrLo = 4763 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, LoFlags); 4764 SDValue PtrHi; 4765 if (GAFlags == SIInstrInfo::MO_NONE) { 4766 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 4767 } else { 4768 PtrHi = 4769 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 4770 } 4771 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 4772 } 4773 4774 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 4775 SDValue Op, 4776 SelectionDAG &DAG) const { 4777 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 4778 const GlobalValue *GV = GSD->getGlobal(); 4779 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 4780 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 4781 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 4782 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 4783 4784 SDLoc DL(GSD); 4785 EVT PtrVT = Op.getValueType(); 4786 4787 // FIXME: Should not make address space based decisions here. 4788 if (shouldEmitFixup(GV)) 4789 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 4790 else if (shouldEmitPCReloc(GV)) 4791 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 4792 SIInstrInfo::MO_REL32); 4793 4794 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 4795 SIInstrInfo::MO_GOTPCREL32); 4796 4797 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 4798 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 4799 const DataLayout &DataLayout = DAG.getDataLayout(); 4800 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 4801 MachinePointerInfo PtrInfo 4802 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 4803 4804 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 4805 MachineMemOperand::MODereferenceable | 4806 MachineMemOperand::MOInvariant); 4807 } 4808 4809 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 4810 const SDLoc &DL, SDValue V) const { 4811 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 4812 // the destination register. 4813 // 4814 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 4815 // so we will end up with redundant moves to m0. 4816 // 4817 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 4818 4819 // A Null SDValue creates a glue result. 4820 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 4821 V, Chain); 4822 return SDValue(M0, 0); 4823 } 4824 4825 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 4826 SDValue Op, 4827 MVT VT, 4828 unsigned Offset) const { 4829 SDLoc SL(Op); 4830 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 4831 DAG.getEntryNode(), Offset, 4, false); 4832 // The local size values will have the hi 16-bits as zero. 4833 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 4834 DAG.getValueType(VT)); 4835 } 4836 4837 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 4838 EVT VT) { 4839 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 4840 "non-hsa intrinsic with hsa target", 4841 DL.getDebugLoc()); 4842 DAG.getContext()->diagnose(BadIntrin); 4843 return DAG.getUNDEF(VT); 4844 } 4845 4846 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 4847 EVT VT) { 4848 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 4849 "intrinsic not supported on subtarget", 4850 DL.getDebugLoc()); 4851 DAG.getContext()->diagnose(BadIntrin); 4852 return DAG.getUNDEF(VT); 4853 } 4854 4855 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 4856 ArrayRef<SDValue> Elts) { 4857 assert(!Elts.empty()); 4858 MVT Type; 4859 unsigned NumElts; 4860 4861 if (Elts.size() == 1) { 4862 Type = MVT::f32; 4863 NumElts = 1; 4864 } else if (Elts.size() == 2) { 4865 Type = MVT::v2f32; 4866 NumElts = 2; 4867 } else if (Elts.size() <= 4) { 4868 Type = MVT::v4f32; 4869 NumElts = 4; 4870 } else if (Elts.size() <= 8) { 4871 Type = MVT::v8f32; 4872 NumElts = 8; 4873 } else { 4874 assert(Elts.size() <= 16); 4875 Type = MVT::v16f32; 4876 NumElts = 16; 4877 } 4878 4879 SmallVector<SDValue, 16> VecElts(NumElts); 4880 for (unsigned i = 0; i < Elts.size(); ++i) { 4881 SDValue Elt = Elts[i]; 4882 if (Elt.getValueType() != MVT::f32) 4883 Elt = DAG.getBitcast(MVT::f32, Elt); 4884 VecElts[i] = Elt; 4885 } 4886 for (unsigned i = Elts.size(); i < NumElts; ++i) 4887 VecElts[i] = DAG.getUNDEF(MVT::f32); 4888 4889 if (NumElts == 1) 4890 return VecElts[0]; 4891 return DAG.getBuildVector(Type, DL, VecElts); 4892 } 4893 4894 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 4895 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 4896 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 4897 4898 uint64_t Value = CachePolicyConst->getZExtValue(); 4899 SDLoc DL(CachePolicy); 4900 if (GLC) { 4901 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 4902 Value &= ~(uint64_t)0x1; 4903 } 4904 if (SLC) { 4905 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 4906 Value &= ~(uint64_t)0x2; 4907 } 4908 if (DLC) { 4909 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 4910 Value &= ~(uint64_t)0x4; 4911 } 4912 4913 return Value == 0; 4914 } 4915 4916 // Re-construct the required return value for a image load intrinsic. 4917 // This is more complicated due to the optional use TexFailCtrl which means the required 4918 // return type is an aggregate 4919 static SDValue constructRetValue(SelectionDAG &DAG, 4920 MachineSDNode *Result, 4921 ArrayRef<EVT> ResultTypes, 4922 bool IsTexFail, bool Unpacked, bool IsD16, 4923 int DMaskPop, int NumVDataDwords, 4924 const SDLoc &DL, LLVMContext &Context) { 4925 // Determine the required return type. This is the same regardless of IsTexFail flag 4926 EVT ReqRetVT = ResultTypes[0]; 4927 EVT ReqRetEltVT = ReqRetVT.isVector() ? ReqRetVT.getVectorElementType() : ReqRetVT; 4928 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 4929 EVT AdjEltVT = Unpacked && IsD16 ? MVT::i32 : ReqRetEltVT; 4930 EVT AdjVT = Unpacked ? ReqRetNumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, ReqRetNumElts) 4931 : AdjEltVT 4932 : ReqRetVT; 4933 4934 // Extract data part of the result 4935 // Bitcast the result to the same type as the required return type 4936 int NumElts; 4937 if (IsD16 && !Unpacked) 4938 NumElts = NumVDataDwords << 1; 4939 else 4940 NumElts = NumVDataDwords; 4941 4942 EVT CastVT = NumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, NumElts) 4943 : AdjEltVT; 4944 4945 // Special case for v6f16. Rather than add support for this, use v3i32 to 4946 // extract the data elements 4947 bool V6F16Special = false; 4948 if (NumElts == 6) { 4949 CastVT = EVT::getVectorVT(Context, MVT::i32, NumElts / 2); 4950 DMaskPop >>= 1; 4951 ReqRetNumElts >>= 1; 4952 V6F16Special = true; 4953 AdjVT = MVT::v2i32; 4954 } 4955 4956 SDValue N = SDValue(Result, 0); 4957 SDValue CastRes = DAG.getNode(ISD::BITCAST, DL, CastVT, N); 4958 4959 // Iterate over the result 4960 SmallVector<SDValue, 4> BVElts; 4961 4962 if (CastVT.isVector()) { 4963 DAG.ExtractVectorElements(CastRes, BVElts, 0, DMaskPop); 4964 } else { 4965 BVElts.push_back(CastRes); 4966 } 4967 int ExtraElts = ReqRetNumElts - DMaskPop; 4968 while(ExtraElts--) 4969 BVElts.push_back(DAG.getUNDEF(AdjEltVT)); 4970 4971 SDValue PreTFCRes; 4972 if (ReqRetNumElts > 1) { 4973 SDValue NewVec = DAG.getBuildVector(AdjVT, DL, BVElts); 4974 if (IsD16 && Unpacked) 4975 PreTFCRes = adjustLoadValueTypeImpl(NewVec, ReqRetVT, DL, DAG, Unpacked); 4976 else 4977 PreTFCRes = NewVec; 4978 } else { 4979 PreTFCRes = BVElts[0]; 4980 } 4981 4982 if (V6F16Special) 4983 PreTFCRes = DAG.getNode(ISD::BITCAST, DL, MVT::v4f16, PreTFCRes); 4984 4985 if (!IsTexFail) { 4986 if (Result->getNumValues() > 1) 4987 return DAG.getMergeValues({PreTFCRes, SDValue(Result, 1)}, DL); 4988 else 4989 return PreTFCRes; 4990 } 4991 4992 // Extract the TexFail result and insert into aggregate return 4993 SmallVector<SDValue, 1> TFCElt; 4994 DAG.ExtractVectorElements(N, TFCElt, DMaskPop, 1); 4995 SDValue TFCRes = DAG.getNode(ISD::BITCAST, DL, ResultTypes[1], TFCElt[0]); 4996 return DAG.getMergeValues({PreTFCRes, TFCRes, SDValue(Result, 1)}, DL); 4997 } 4998 4999 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5000 SDValue *LWE, bool &IsTexFail) { 5001 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5002 5003 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5004 if (Value) { 5005 IsTexFail = true; 5006 } 5007 5008 SDLoc DL(TexFailCtrlConst); 5009 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5010 Value &= ~(uint64_t)0x1; 5011 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5012 Value &= ~(uint64_t)0x2; 5013 5014 return Value == 0; 5015 } 5016 5017 SDValue SITargetLowering::lowerImage(SDValue Op, 5018 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5019 SelectionDAG &DAG) const { 5020 SDLoc DL(Op); 5021 MachineFunction &MF = DAG.getMachineFunction(); 5022 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5023 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5024 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5025 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5026 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5027 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5028 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5029 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5030 unsigned IntrOpcode = Intr->BaseOpcode; 5031 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5032 5033 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5034 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5035 bool IsD16 = false; 5036 bool IsA16 = false; 5037 SDValue VData; 5038 int NumVDataDwords; 5039 bool AdjustRetType = false; 5040 5041 unsigned AddrIdx; // Index of first address argument 5042 unsigned DMask; 5043 unsigned DMaskLanes = 0; 5044 5045 if (BaseOpcode->Atomic) { 5046 VData = Op.getOperand(2); 5047 5048 bool Is64Bit = VData.getValueType() == MVT::i64; 5049 if (BaseOpcode->AtomicX2) { 5050 SDValue VData2 = Op.getOperand(3); 5051 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5052 {VData, VData2}); 5053 if (Is64Bit) 5054 VData = DAG.getBitcast(MVT::v4i32, VData); 5055 5056 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5057 DMask = Is64Bit ? 0xf : 0x3; 5058 NumVDataDwords = Is64Bit ? 4 : 2; 5059 AddrIdx = 4; 5060 } else { 5061 DMask = Is64Bit ? 0x3 : 0x1; 5062 NumVDataDwords = Is64Bit ? 2 : 1; 5063 AddrIdx = 3; 5064 } 5065 } else { 5066 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5067 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5068 DMask = DMaskConst->getZExtValue(); 5069 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5070 5071 if (BaseOpcode->Store) { 5072 VData = Op.getOperand(2); 5073 5074 MVT StoreVT = VData.getSimpleValueType(); 5075 if (StoreVT.getScalarType() == MVT::f16) { 5076 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5077 return Op; // D16 is unsupported for this instruction 5078 5079 IsD16 = true; 5080 VData = handleD16VData(VData, DAG); 5081 } 5082 5083 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5084 } else { 5085 // Work out the num dwords based on the dmask popcount and underlying type 5086 // and whether packing is supported. 5087 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5088 if (LoadVT.getScalarType() == MVT::f16) { 5089 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5090 return Op; // D16 is unsupported for this instruction 5091 5092 IsD16 = true; 5093 } 5094 5095 // Confirm that the return type is large enough for the dmask specified 5096 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5097 (!LoadVT.isVector() && DMaskLanes > 1)) 5098 return Op; 5099 5100 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5101 NumVDataDwords = (DMaskLanes + 1) / 2; 5102 else 5103 NumVDataDwords = DMaskLanes; 5104 5105 AdjustRetType = true; 5106 } 5107 5108 AddrIdx = DMaskIdx + 1; 5109 } 5110 5111 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5112 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5113 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5114 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5115 NumCoords + NumLCM; 5116 unsigned NumMIVAddrs = NumVAddrs; 5117 5118 SmallVector<SDValue, 4> VAddrs; 5119 5120 // Optimize _L to _LZ when _L is zero 5121 if (LZMappingInfo) { 5122 if (auto ConstantLod = 5123 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5124 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5125 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5126 NumMIVAddrs--; // remove 'lod' 5127 } 5128 } 5129 } 5130 5131 // Optimize _mip away, when 'lod' is zero 5132 if (MIPMappingInfo) { 5133 if (auto ConstantLod = 5134 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5135 if (ConstantLod->isNullValue()) { 5136 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5137 NumMIVAddrs--; // remove 'lod' 5138 } 5139 } 5140 } 5141 5142 // Check for 16 bit addresses and pack if true. 5143 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5144 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5145 const MVT VAddrScalarVT = VAddrVT.getScalarType(); 5146 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16)) && 5147 ST->hasFeature(AMDGPU::FeatureR128A16)) { 5148 IsA16 = true; 5149 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5150 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) { 5151 SDValue AddrLo, AddrHi; 5152 // Push back extra arguments. 5153 if (i < DimIdx) { 5154 AddrLo = Op.getOperand(i); 5155 } else { 5156 AddrLo = Op.getOperand(i); 5157 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, 5158 // in 1D, derivatives dx/dh and dx/dv are packed with undef. 5159 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) || 5160 ((NumGradients / 2) % 2 == 1 && 5161 (i == DimIdx + (NumGradients / 2) - 1 || 5162 i == DimIdx + NumGradients - 1))) { 5163 AddrHi = DAG.getUNDEF(MVT::f16); 5164 } else { 5165 AddrHi = Op.getOperand(i + 1); 5166 i++; 5167 } 5168 AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT, 5169 {AddrLo, AddrHi}); 5170 AddrLo = DAG.getBitcast(MVT::i32, AddrLo); 5171 } 5172 VAddrs.push_back(AddrLo); 5173 } 5174 } else { 5175 for (unsigned i = 0; i < NumMIVAddrs; ++i) 5176 VAddrs.push_back(Op.getOperand(AddrIdx + i)); 5177 } 5178 5179 // If the register allocator cannot place the address registers contiguously 5180 // without introducing moves, then using the non-sequential address encoding 5181 // is always preferable, since it saves VALU instructions and is usually a 5182 // wash in terms of code size or even better. 5183 // 5184 // However, we currently have no way of hinting to the register allocator that 5185 // MIMG addresses should be placed contiguously when it is possible to do so, 5186 // so force non-NSA for the common 2-address case as a heuristic. 5187 // 5188 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5189 // allocation when possible. 5190 bool UseNSA = 5191 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5192 SDValue VAddr; 5193 if (!UseNSA) 5194 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5195 5196 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5197 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5198 unsigned CtrlIdx; // Index of texfailctrl argument 5199 SDValue Unorm; 5200 if (!BaseOpcode->Sampler) { 5201 Unorm = True; 5202 CtrlIdx = AddrIdx + NumVAddrs + 1; 5203 } else { 5204 auto UnormConst = 5205 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 5206 5207 Unorm = UnormConst->getZExtValue() ? True : False; 5208 CtrlIdx = AddrIdx + NumVAddrs + 3; 5209 } 5210 5211 SDValue TFE; 5212 SDValue LWE; 5213 SDValue TexFail = Op.getOperand(CtrlIdx); 5214 bool IsTexFail = false; 5215 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 5216 return Op; 5217 5218 if (IsTexFail) { 5219 if (!DMaskLanes) { 5220 // Expecting to get an error flag since TFC is on - and dmask is 0 5221 // Force dmask to be at least 1 otherwise the instruction will fail 5222 DMask = 0x1; 5223 DMaskLanes = 1; 5224 NumVDataDwords = 1; 5225 } 5226 NumVDataDwords += 1; 5227 AdjustRetType = true; 5228 } 5229 5230 // Has something earlier tagged that the return type needs adjusting 5231 // This happens if the instruction is a load or has set TexFailCtrl flags 5232 if (AdjustRetType) { 5233 // NumVDataDwords reflects the true number of dwords required in the return type 5234 if (DMaskLanes == 0 && !BaseOpcode->Store) { 5235 // This is a no-op load. This can be eliminated 5236 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 5237 if (isa<MemSDNode>(Op)) 5238 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 5239 return Undef; 5240 } 5241 5242 EVT NewVT = NumVDataDwords > 1 ? 5243 EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumVDataDwords) 5244 : MVT::f32; 5245 5246 ResultTypes[0] = NewVT; 5247 if (ResultTypes.size() == 3) { 5248 // Original result was aggregate type used for TexFailCtrl results 5249 // The actual instruction returns as a vector type which has now been 5250 // created. Remove the aggregate result. 5251 ResultTypes.erase(&ResultTypes[1]); 5252 } 5253 } 5254 5255 SDValue GLC; 5256 SDValue SLC; 5257 SDValue DLC; 5258 if (BaseOpcode->Atomic) { 5259 GLC = True; // TODO no-return optimization 5260 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 5261 IsGFX10 ? &DLC : nullptr)) 5262 return Op; 5263 } else { 5264 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 5265 IsGFX10 ? &DLC : nullptr)) 5266 return Op; 5267 } 5268 5269 SmallVector<SDValue, 26> Ops; 5270 if (BaseOpcode->Store || BaseOpcode->Atomic) 5271 Ops.push_back(VData); // vdata 5272 if (UseNSA) { 5273 for (const SDValue &Addr : VAddrs) 5274 Ops.push_back(Addr); 5275 } else { 5276 Ops.push_back(VAddr); 5277 } 5278 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 5279 if (BaseOpcode->Sampler) 5280 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 5281 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 5282 if (IsGFX10) 5283 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 5284 Ops.push_back(Unorm); 5285 if (IsGFX10) 5286 Ops.push_back(DLC); 5287 Ops.push_back(GLC); 5288 Ops.push_back(SLC); 5289 Ops.push_back(IsA16 && // a16 or r128 5290 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 5291 Ops.push_back(TFE); // tfe 5292 Ops.push_back(LWE); // lwe 5293 if (!IsGFX10) 5294 Ops.push_back(DimInfo->DA ? True : False); 5295 if (BaseOpcode->HasD16) 5296 Ops.push_back(IsD16 ? True : False); 5297 if (isa<MemSDNode>(Op)) 5298 Ops.push_back(Op.getOperand(0)); // chain 5299 5300 int NumVAddrDwords = 5301 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 5302 int Opcode = -1; 5303 5304 if (IsGFX10) { 5305 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 5306 UseNSA ? AMDGPU::MIMGEncGfx10NSA 5307 : AMDGPU::MIMGEncGfx10Default, 5308 NumVDataDwords, NumVAddrDwords); 5309 } else { 5310 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5311 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 5312 NumVDataDwords, NumVAddrDwords); 5313 if (Opcode == -1) 5314 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 5315 NumVDataDwords, NumVAddrDwords); 5316 } 5317 assert(Opcode != -1); 5318 5319 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 5320 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 5321 MachineMemOperand *MemRef = MemOp->getMemOperand(); 5322 DAG.setNodeMemRefs(NewNode, {MemRef}); 5323 } 5324 5325 if (BaseOpcode->AtomicX2) { 5326 SmallVector<SDValue, 1> Elt; 5327 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 5328 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 5329 } else if (!BaseOpcode->Store) { 5330 return constructRetValue(DAG, NewNode, 5331 OrigResultTypes, IsTexFail, 5332 Subtarget->hasUnpackedD16VMem(), IsD16, 5333 DMaskLanes, NumVDataDwords, DL, 5334 *DAG.getContext()); 5335 } 5336 5337 return SDValue(NewNode, 0); 5338 } 5339 5340 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 5341 SDValue Offset, SDValue GLC, SDValue DLC, 5342 SelectionDAG &DAG) const { 5343 MachineFunction &MF = DAG.getMachineFunction(); 5344 MachineMemOperand *MMO = MF.getMachineMemOperand( 5345 MachinePointerInfo(), 5346 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 5347 MachineMemOperand::MOInvariant, 5348 VT.getStoreSize(), VT.getStoreSize()); 5349 5350 if (!Offset->isDivergent()) { 5351 SDValue Ops[] = { 5352 Rsrc, 5353 Offset, // Offset 5354 GLC, 5355 DLC, 5356 }; 5357 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 5358 DAG.getVTList(VT), Ops, VT, MMO); 5359 } 5360 5361 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 5362 // assume that the buffer is unswizzled. 5363 SmallVector<SDValue, 4> Loads; 5364 unsigned NumLoads = 1; 5365 MVT LoadVT = VT.getSimpleVT(); 5366 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 5367 assert((LoadVT.getScalarType() == MVT::i32 || 5368 LoadVT.getScalarType() == MVT::f32) && 5369 isPowerOf2_32(NumElts)); 5370 5371 if (NumElts == 8 || NumElts == 16) { 5372 NumLoads = NumElts == 16 ? 4 : 2; 5373 LoadVT = MVT::v4i32; 5374 } 5375 5376 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 5377 unsigned CachePolicy = cast<ConstantSDNode>(GLC)->getZExtValue(); 5378 SDValue Ops[] = { 5379 DAG.getEntryNode(), // Chain 5380 Rsrc, // rsrc 5381 DAG.getConstant(0, DL, MVT::i32), // vindex 5382 {}, // voffset 5383 {}, // soffset 5384 {}, // offset 5385 DAG.getConstant(CachePolicy, DL, MVT::i32), // cachepolicy 5386 DAG.getConstant(0, DL, MVT::i1), // idxen 5387 }; 5388 5389 // Use the alignment to ensure that the required offsets will fit into the 5390 // immediate offsets. 5391 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 5392 5393 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 5394 for (unsigned i = 0; i < NumLoads; ++i) { 5395 Ops[5] = DAG.getConstant(InstOffset + 16 * i, DL, MVT::i32); 5396 Loads.push_back(DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, 5397 Ops, LoadVT, MMO)); 5398 } 5399 5400 if (VT == MVT::v8i32 || VT == MVT::v16i32) 5401 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 5402 5403 return Loads[0]; 5404 } 5405 5406 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 5407 SelectionDAG &DAG) const { 5408 MachineFunction &MF = DAG.getMachineFunction(); 5409 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 5410 5411 EVT VT = Op.getValueType(); 5412 SDLoc DL(Op); 5413 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5414 5415 // TODO: Should this propagate fast-math-flags? 5416 5417 switch (IntrinsicID) { 5418 case Intrinsic::amdgcn_implicit_buffer_ptr: { 5419 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 5420 return emitNonHSAIntrinsicError(DAG, DL, VT); 5421 return getPreloadedValue(DAG, *MFI, VT, 5422 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 5423 } 5424 case Intrinsic::amdgcn_dispatch_ptr: 5425 case Intrinsic::amdgcn_queue_ptr: { 5426 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 5427 DiagnosticInfoUnsupported BadIntrin( 5428 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 5429 DL.getDebugLoc()); 5430 DAG.getContext()->diagnose(BadIntrin); 5431 return DAG.getUNDEF(VT); 5432 } 5433 5434 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 5435 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 5436 return getPreloadedValue(DAG, *MFI, VT, RegID); 5437 } 5438 case Intrinsic::amdgcn_implicitarg_ptr: { 5439 if (MFI->isEntryFunction()) 5440 return getImplicitArgPtr(DAG, DL); 5441 return getPreloadedValue(DAG, *MFI, VT, 5442 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 5443 } 5444 case Intrinsic::amdgcn_kernarg_segment_ptr: { 5445 return getPreloadedValue(DAG, *MFI, VT, 5446 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 5447 } 5448 case Intrinsic::amdgcn_dispatch_id: { 5449 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 5450 } 5451 case Intrinsic::amdgcn_rcp: 5452 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 5453 case Intrinsic::amdgcn_rsq: 5454 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5455 case Intrinsic::amdgcn_rsq_legacy: 5456 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5457 return emitRemovedIntrinsicError(DAG, DL, VT); 5458 5459 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 5460 case Intrinsic::amdgcn_rcp_legacy: 5461 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5462 return emitRemovedIntrinsicError(DAG, DL, VT); 5463 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 5464 case Intrinsic::amdgcn_rsq_clamp: { 5465 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5466 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 5467 5468 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 5469 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 5470 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 5471 5472 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5473 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 5474 DAG.getConstantFP(Max, DL, VT)); 5475 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 5476 DAG.getConstantFP(Min, DL, VT)); 5477 } 5478 case Intrinsic::r600_read_ngroups_x: 5479 if (Subtarget->isAmdHsaOS()) 5480 return emitNonHSAIntrinsicError(DAG, DL, VT); 5481 5482 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5483 SI::KernelInputOffsets::NGROUPS_X, 4, false); 5484 case Intrinsic::r600_read_ngroups_y: 5485 if (Subtarget->isAmdHsaOS()) 5486 return emitNonHSAIntrinsicError(DAG, DL, VT); 5487 5488 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5489 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 5490 case Intrinsic::r600_read_ngroups_z: 5491 if (Subtarget->isAmdHsaOS()) 5492 return emitNonHSAIntrinsicError(DAG, DL, VT); 5493 5494 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5495 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 5496 case Intrinsic::r600_read_global_size_x: 5497 if (Subtarget->isAmdHsaOS()) 5498 return emitNonHSAIntrinsicError(DAG, DL, VT); 5499 5500 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5501 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 5502 case Intrinsic::r600_read_global_size_y: 5503 if (Subtarget->isAmdHsaOS()) 5504 return emitNonHSAIntrinsicError(DAG, DL, VT); 5505 5506 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5507 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 5508 case Intrinsic::r600_read_global_size_z: 5509 if (Subtarget->isAmdHsaOS()) 5510 return emitNonHSAIntrinsicError(DAG, DL, VT); 5511 5512 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5513 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 5514 case Intrinsic::r600_read_local_size_x: 5515 if (Subtarget->isAmdHsaOS()) 5516 return emitNonHSAIntrinsicError(DAG, DL, VT); 5517 5518 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5519 SI::KernelInputOffsets::LOCAL_SIZE_X); 5520 case Intrinsic::r600_read_local_size_y: 5521 if (Subtarget->isAmdHsaOS()) 5522 return emitNonHSAIntrinsicError(DAG, DL, VT); 5523 5524 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5525 SI::KernelInputOffsets::LOCAL_SIZE_Y); 5526 case Intrinsic::r600_read_local_size_z: 5527 if (Subtarget->isAmdHsaOS()) 5528 return emitNonHSAIntrinsicError(DAG, DL, VT); 5529 5530 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5531 SI::KernelInputOffsets::LOCAL_SIZE_Z); 5532 case Intrinsic::amdgcn_workgroup_id_x: 5533 case Intrinsic::r600_read_tgid_x: 5534 return getPreloadedValue(DAG, *MFI, VT, 5535 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 5536 case Intrinsic::amdgcn_workgroup_id_y: 5537 case Intrinsic::r600_read_tgid_y: 5538 return getPreloadedValue(DAG, *MFI, VT, 5539 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 5540 case Intrinsic::amdgcn_workgroup_id_z: 5541 case Intrinsic::r600_read_tgid_z: 5542 return getPreloadedValue(DAG, *MFI, VT, 5543 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 5544 case Intrinsic::amdgcn_workitem_id_x: 5545 case Intrinsic::r600_read_tidig_x: 5546 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5547 SDLoc(DAG.getEntryNode()), 5548 MFI->getArgInfo().WorkItemIDX); 5549 case Intrinsic::amdgcn_workitem_id_y: 5550 case Intrinsic::r600_read_tidig_y: 5551 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5552 SDLoc(DAG.getEntryNode()), 5553 MFI->getArgInfo().WorkItemIDY); 5554 case Intrinsic::amdgcn_workitem_id_z: 5555 case Intrinsic::r600_read_tidig_z: 5556 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5557 SDLoc(DAG.getEntryNode()), 5558 MFI->getArgInfo().WorkItemIDZ); 5559 case Intrinsic::amdgcn_wavefrontsize: 5560 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 5561 SDLoc(Op), MVT::i32); 5562 case Intrinsic::amdgcn_s_buffer_load: { 5563 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5564 SDValue GLC; 5565 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 5566 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 5567 IsGFX10 ? &DLC : nullptr)) 5568 return Op; 5569 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), GLC, DLC, 5570 DAG); 5571 } 5572 case Intrinsic::amdgcn_fdiv_fast: 5573 return lowerFDIV_FAST(Op, DAG); 5574 case Intrinsic::amdgcn_interp_mov: { 5575 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 5576 SDValue Glue = M0.getValue(1); 5577 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1), 5578 Op.getOperand(2), Op.getOperand(3), Glue); 5579 } 5580 case Intrinsic::amdgcn_interp_p1: { 5581 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 5582 SDValue Glue = M0.getValue(1); 5583 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1), 5584 Op.getOperand(2), Op.getOperand(3), Glue); 5585 } 5586 case Intrinsic::amdgcn_interp_p2: { 5587 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 5588 SDValue Glue = SDValue(M0.getNode(), 1); 5589 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1), 5590 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4), 5591 Glue); 5592 } 5593 case Intrinsic::amdgcn_interp_p1_f16: { 5594 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 5595 SDValue Glue = M0.getValue(1); 5596 if (getSubtarget()->getLDSBankCount() == 16) { 5597 // 16 bank LDS 5598 SDValue S = DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, 5599 DAG.getConstant(2, DL, MVT::i32), // P0 5600 Op.getOperand(2), // Attrchan 5601 Op.getOperand(3), // Attr 5602 Glue); 5603 SDValue Ops[] = { 5604 Op.getOperand(1), // Src0 5605 Op.getOperand(2), // Attrchan 5606 Op.getOperand(3), // Attr 5607 DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers 5608 S, // Src2 - holds two f16 values selected by high 5609 DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers 5610 Op.getOperand(4), // high 5611 DAG.getConstant(0, DL, MVT::i1), // $clamp 5612 DAG.getConstant(0, DL, MVT::i32) // $omod 5613 }; 5614 return DAG.getNode(AMDGPUISD::INTERP_P1LV_F16, DL, MVT::f32, Ops); 5615 } else { 5616 // 32 bank LDS 5617 SDValue Ops[] = { 5618 Op.getOperand(1), // Src0 5619 Op.getOperand(2), // Attrchan 5620 Op.getOperand(3), // Attr 5621 DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers 5622 Op.getOperand(4), // high 5623 DAG.getConstant(0, DL, MVT::i1), // $clamp 5624 DAG.getConstant(0, DL, MVT::i32), // $omod 5625 Glue 5626 }; 5627 return DAG.getNode(AMDGPUISD::INTERP_P1LL_F16, DL, MVT::f32, Ops); 5628 } 5629 } 5630 case Intrinsic::amdgcn_interp_p2_f16: { 5631 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(6)); 5632 SDValue Glue = SDValue(M0.getNode(), 1); 5633 SDValue Ops[] = { 5634 Op.getOperand(2), // Src0 5635 Op.getOperand(3), // Attrchan 5636 Op.getOperand(4), // Attr 5637 DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers 5638 Op.getOperand(1), // Src2 5639 DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers 5640 Op.getOperand(5), // high 5641 DAG.getConstant(0, DL, MVT::i1), // $clamp 5642 Glue 5643 }; 5644 return DAG.getNode(AMDGPUISD::INTERP_P2_F16, DL, MVT::f16, Ops); 5645 } 5646 case Intrinsic::amdgcn_sin: 5647 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 5648 5649 case Intrinsic::amdgcn_cos: 5650 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 5651 5652 case Intrinsic::amdgcn_log_clamp: { 5653 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5654 return SDValue(); 5655 5656 DiagnosticInfoUnsupported BadIntrin( 5657 MF.getFunction(), "intrinsic not supported on subtarget", 5658 DL.getDebugLoc()); 5659 DAG.getContext()->diagnose(BadIntrin); 5660 return DAG.getUNDEF(VT); 5661 } 5662 case Intrinsic::amdgcn_ldexp: 5663 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 5664 Op.getOperand(1), Op.getOperand(2)); 5665 5666 case Intrinsic::amdgcn_fract: 5667 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 5668 5669 case Intrinsic::amdgcn_class: 5670 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 5671 Op.getOperand(1), Op.getOperand(2)); 5672 case Intrinsic::amdgcn_div_fmas: 5673 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 5674 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5675 Op.getOperand(4)); 5676 5677 case Intrinsic::amdgcn_div_fixup: 5678 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 5679 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5680 5681 case Intrinsic::amdgcn_trig_preop: 5682 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 5683 Op.getOperand(1), Op.getOperand(2)); 5684 case Intrinsic::amdgcn_div_scale: { 5685 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 5686 5687 // Translate to the operands expected by the machine instruction. The 5688 // first parameter must be the same as the first instruction. 5689 SDValue Numerator = Op.getOperand(1); 5690 SDValue Denominator = Op.getOperand(2); 5691 5692 // Note this order is opposite of the machine instruction's operations, 5693 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 5694 // intrinsic has the numerator as the first operand to match a normal 5695 // division operation. 5696 5697 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 5698 5699 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 5700 Denominator, Numerator); 5701 } 5702 case Intrinsic::amdgcn_icmp: { 5703 // There is a Pat that handles this variant, so return it as-is. 5704 if (Op.getOperand(1).getValueType() == MVT::i1 && 5705 Op.getConstantOperandVal(2) == 0 && 5706 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 5707 return Op; 5708 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 5709 } 5710 case Intrinsic::amdgcn_fcmp: { 5711 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 5712 } 5713 case Intrinsic::amdgcn_fmed3: 5714 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 5715 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5716 case Intrinsic::amdgcn_fdot2: 5717 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 5718 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5719 Op.getOperand(4)); 5720 case Intrinsic::amdgcn_fmul_legacy: 5721 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 5722 Op.getOperand(1), Op.getOperand(2)); 5723 case Intrinsic::amdgcn_sffbh: 5724 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 5725 case Intrinsic::amdgcn_sbfe: 5726 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 5727 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5728 case Intrinsic::amdgcn_ubfe: 5729 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 5730 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5731 case Intrinsic::amdgcn_cvt_pkrtz: 5732 case Intrinsic::amdgcn_cvt_pknorm_i16: 5733 case Intrinsic::amdgcn_cvt_pknorm_u16: 5734 case Intrinsic::amdgcn_cvt_pk_i16: 5735 case Intrinsic::amdgcn_cvt_pk_u16: { 5736 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 5737 EVT VT = Op.getValueType(); 5738 unsigned Opcode; 5739 5740 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 5741 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 5742 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 5743 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 5744 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 5745 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 5746 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 5747 Opcode = AMDGPUISD::CVT_PK_I16_I32; 5748 else 5749 Opcode = AMDGPUISD::CVT_PK_U16_U32; 5750 5751 if (isTypeLegal(VT)) 5752 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5753 5754 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 5755 Op.getOperand(1), Op.getOperand(2)); 5756 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 5757 } 5758 case Intrinsic::amdgcn_wqm: { 5759 SDValue Src = Op.getOperand(1); 5760 return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src), 5761 0); 5762 } 5763 case Intrinsic::amdgcn_wwm: { 5764 SDValue Src = Op.getOperand(1); 5765 return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src), 5766 0); 5767 } 5768 case Intrinsic::amdgcn_fmad_ftz: 5769 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 5770 Op.getOperand(2), Op.getOperand(3)); 5771 5772 case Intrinsic::amdgcn_if_break: 5773 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 5774 Op->getOperand(1), Op->getOperand(2)), 0); 5775 5776 default: 5777 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 5778 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 5779 return lowerImage(Op, ImageDimIntr, DAG); 5780 5781 return Op; 5782 } 5783 } 5784 5785 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 5786 SelectionDAG &DAG) const { 5787 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 5788 SDLoc DL(Op); 5789 5790 switch (IntrID) { 5791 case Intrinsic::amdgcn_ds_ordered_add: 5792 case Intrinsic::amdgcn_ds_ordered_swap: { 5793 MemSDNode *M = cast<MemSDNode>(Op); 5794 SDValue Chain = M->getOperand(0); 5795 SDValue M0 = M->getOperand(2); 5796 SDValue Value = M->getOperand(3); 5797 unsigned OrderedCountIndex = M->getConstantOperandVal(7); 5798 unsigned WaveRelease = M->getConstantOperandVal(8); 5799 unsigned WaveDone = M->getConstantOperandVal(9); 5800 unsigned ShaderType; 5801 unsigned Instruction; 5802 5803 switch (IntrID) { 5804 case Intrinsic::amdgcn_ds_ordered_add: 5805 Instruction = 0; 5806 break; 5807 case Intrinsic::amdgcn_ds_ordered_swap: 5808 Instruction = 1; 5809 break; 5810 } 5811 5812 if (WaveDone && !WaveRelease) 5813 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 5814 5815 switch (DAG.getMachineFunction().getFunction().getCallingConv()) { 5816 case CallingConv::AMDGPU_CS: 5817 case CallingConv::AMDGPU_KERNEL: 5818 ShaderType = 0; 5819 break; 5820 case CallingConv::AMDGPU_PS: 5821 ShaderType = 1; 5822 break; 5823 case CallingConv::AMDGPU_VS: 5824 ShaderType = 2; 5825 break; 5826 case CallingConv::AMDGPU_GS: 5827 ShaderType = 3; 5828 break; 5829 default: 5830 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 5831 } 5832 5833 unsigned Offset0 = OrderedCountIndex << 2; 5834 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 5835 (Instruction << 4); 5836 unsigned Offset = Offset0 | (Offset1 << 8); 5837 5838 SDValue Ops[] = { 5839 Chain, 5840 Value, 5841 DAG.getTargetConstant(Offset, DL, MVT::i16), 5842 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 5843 }; 5844 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 5845 M->getVTList(), Ops, M->getMemoryVT(), 5846 M->getMemOperand()); 5847 } 5848 case Intrinsic::amdgcn_ds_fadd: { 5849 MemSDNode *M = cast<MemSDNode>(Op); 5850 unsigned Opc; 5851 switch (IntrID) { 5852 case Intrinsic::amdgcn_ds_fadd: 5853 Opc = ISD::ATOMIC_LOAD_FADD; 5854 break; 5855 } 5856 5857 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 5858 M->getOperand(0), M->getOperand(2), M->getOperand(3), 5859 M->getMemOperand()); 5860 } 5861 case Intrinsic::amdgcn_atomic_inc: 5862 case Intrinsic::amdgcn_atomic_dec: 5863 case Intrinsic::amdgcn_ds_fmin: 5864 case Intrinsic::amdgcn_ds_fmax: { 5865 MemSDNode *M = cast<MemSDNode>(Op); 5866 unsigned Opc; 5867 switch (IntrID) { 5868 case Intrinsic::amdgcn_atomic_inc: 5869 Opc = AMDGPUISD::ATOMIC_INC; 5870 break; 5871 case Intrinsic::amdgcn_atomic_dec: 5872 Opc = AMDGPUISD::ATOMIC_DEC; 5873 break; 5874 case Intrinsic::amdgcn_ds_fmin: 5875 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 5876 break; 5877 case Intrinsic::amdgcn_ds_fmax: 5878 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 5879 break; 5880 default: 5881 llvm_unreachable("Unknown intrinsic!"); 5882 } 5883 SDValue Ops[] = { 5884 M->getOperand(0), // Chain 5885 M->getOperand(2), // Ptr 5886 M->getOperand(3) // Value 5887 }; 5888 5889 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 5890 M->getMemoryVT(), M->getMemOperand()); 5891 } 5892 case Intrinsic::amdgcn_buffer_load: 5893 case Intrinsic::amdgcn_buffer_load_format: { 5894 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 5895 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 5896 unsigned IdxEn = 1; 5897 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 5898 IdxEn = Idx->getZExtValue() != 0; 5899 SDValue Ops[] = { 5900 Op.getOperand(0), // Chain 5901 Op.getOperand(2), // rsrc 5902 Op.getOperand(3), // vindex 5903 SDValue(), // voffset -- will be set by setBufferOffsets 5904 SDValue(), // soffset -- will be set by setBufferOffsets 5905 SDValue(), // offset -- will be set by setBufferOffsets 5906 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 5907 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 5908 }; 5909 5910 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 5911 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 5912 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 5913 5914 EVT VT = Op.getValueType(); 5915 EVT IntVT = VT.changeTypeToInteger(); 5916 auto *M = cast<MemSDNode>(Op); 5917 EVT LoadVT = Op.getValueType(); 5918 5919 if (LoadVT.getScalarType() == MVT::f16) 5920 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 5921 M, DAG, Ops); 5922 5923 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 5924 if (LoadVT.getScalarType() == MVT::i8 || 5925 LoadVT.getScalarType() == MVT::i16) 5926 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 5927 5928 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 5929 M->getMemOperand(), DAG); 5930 } 5931 case Intrinsic::amdgcn_raw_buffer_load: 5932 case Intrinsic::amdgcn_raw_buffer_load_format: { 5933 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 5934 SDValue Ops[] = { 5935 Op.getOperand(0), // Chain 5936 Op.getOperand(2), // rsrc 5937 DAG.getConstant(0, DL, MVT::i32), // vindex 5938 Offsets.first, // voffset 5939 Op.getOperand(4), // soffset 5940 Offsets.second, // offset 5941 Op.getOperand(5), // cachepolicy 5942 DAG.getConstant(0, DL, MVT::i1), // idxen 5943 }; 5944 5945 unsigned Opc = (IntrID == Intrinsic::amdgcn_raw_buffer_load) ? 5946 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 5947 5948 EVT VT = Op.getValueType(); 5949 EVT IntVT = VT.changeTypeToInteger(); 5950 auto *M = cast<MemSDNode>(Op); 5951 EVT LoadVT = Op.getValueType(); 5952 5953 if (LoadVT.getScalarType() == MVT::f16) 5954 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 5955 M, DAG, Ops); 5956 5957 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 5958 if (LoadVT.getScalarType() == MVT::i8 || 5959 LoadVT.getScalarType() == MVT::i16) 5960 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 5961 5962 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 5963 M->getMemOperand(), DAG); 5964 } 5965 case Intrinsic::amdgcn_struct_buffer_load: 5966 case Intrinsic::amdgcn_struct_buffer_load_format: { 5967 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 5968 SDValue Ops[] = { 5969 Op.getOperand(0), // Chain 5970 Op.getOperand(2), // rsrc 5971 Op.getOperand(3), // vindex 5972 Offsets.first, // voffset 5973 Op.getOperand(5), // soffset 5974 Offsets.second, // offset 5975 Op.getOperand(6), // cachepolicy 5976 DAG.getConstant(1, DL, MVT::i1), // idxen 5977 }; 5978 5979 unsigned Opc = (IntrID == Intrinsic::amdgcn_struct_buffer_load) ? 5980 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 5981 5982 EVT VT = Op.getValueType(); 5983 EVT IntVT = VT.changeTypeToInteger(); 5984 auto *M = cast<MemSDNode>(Op); 5985 EVT LoadVT = Op.getValueType(); 5986 5987 if (LoadVT.getScalarType() == MVT::f16) 5988 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 5989 M, DAG, Ops); 5990 5991 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 5992 if (LoadVT.getScalarType() == MVT::i8 || 5993 LoadVT.getScalarType() == MVT::i16) 5994 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 5995 5996 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 5997 M->getMemOperand(), DAG); 5998 } 5999 case Intrinsic::amdgcn_tbuffer_load: { 6000 MemSDNode *M = cast<MemSDNode>(Op); 6001 EVT LoadVT = Op.getValueType(); 6002 6003 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6004 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6005 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6006 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6007 unsigned IdxEn = 1; 6008 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6009 IdxEn = Idx->getZExtValue() != 0; 6010 SDValue Ops[] = { 6011 Op.getOperand(0), // Chain 6012 Op.getOperand(2), // rsrc 6013 Op.getOperand(3), // vindex 6014 Op.getOperand(4), // voffset 6015 Op.getOperand(5), // soffset 6016 Op.getOperand(6), // offset 6017 DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6018 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6019 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6020 }; 6021 6022 if (LoadVT.getScalarType() == MVT::f16) 6023 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6024 M, DAG, Ops); 6025 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6026 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6027 DAG); 6028 } 6029 case Intrinsic::amdgcn_raw_tbuffer_load: { 6030 MemSDNode *M = cast<MemSDNode>(Op); 6031 EVT LoadVT = Op.getValueType(); 6032 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6033 6034 SDValue Ops[] = { 6035 Op.getOperand(0), // Chain 6036 Op.getOperand(2), // rsrc 6037 DAG.getConstant(0, DL, MVT::i32), // vindex 6038 Offsets.first, // voffset 6039 Op.getOperand(4), // soffset 6040 Offsets.second, // offset 6041 Op.getOperand(5), // format 6042 Op.getOperand(6), // cachepolicy 6043 DAG.getConstant(0, DL, MVT::i1), // idxen 6044 }; 6045 6046 if (LoadVT.getScalarType() == MVT::f16) 6047 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6048 M, DAG, Ops); 6049 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6050 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6051 DAG); 6052 } 6053 case Intrinsic::amdgcn_struct_tbuffer_load: { 6054 MemSDNode *M = cast<MemSDNode>(Op); 6055 EVT LoadVT = Op.getValueType(); 6056 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6057 6058 SDValue Ops[] = { 6059 Op.getOperand(0), // Chain 6060 Op.getOperand(2), // rsrc 6061 Op.getOperand(3), // vindex 6062 Offsets.first, // voffset 6063 Op.getOperand(5), // soffset 6064 Offsets.second, // offset 6065 Op.getOperand(6), // format 6066 Op.getOperand(7), // cachepolicy 6067 DAG.getConstant(1, DL, MVT::i1), // idxen 6068 }; 6069 6070 if (LoadVT.getScalarType() == MVT::f16) 6071 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6072 M, DAG, Ops); 6073 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6074 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6075 DAG); 6076 } 6077 case Intrinsic::amdgcn_buffer_atomic_swap: 6078 case Intrinsic::amdgcn_buffer_atomic_add: 6079 case Intrinsic::amdgcn_buffer_atomic_sub: 6080 case Intrinsic::amdgcn_buffer_atomic_smin: 6081 case Intrinsic::amdgcn_buffer_atomic_umin: 6082 case Intrinsic::amdgcn_buffer_atomic_smax: 6083 case Intrinsic::amdgcn_buffer_atomic_umax: 6084 case Intrinsic::amdgcn_buffer_atomic_and: 6085 case Intrinsic::amdgcn_buffer_atomic_or: 6086 case Intrinsic::amdgcn_buffer_atomic_xor: { 6087 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6088 unsigned IdxEn = 1; 6089 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6090 IdxEn = Idx->getZExtValue() != 0; 6091 SDValue Ops[] = { 6092 Op.getOperand(0), // Chain 6093 Op.getOperand(2), // vdata 6094 Op.getOperand(3), // rsrc 6095 Op.getOperand(4), // vindex 6096 SDValue(), // voffset -- will be set by setBufferOffsets 6097 SDValue(), // soffset -- will be set by setBufferOffsets 6098 SDValue(), // offset -- will be set by setBufferOffsets 6099 DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6100 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6101 }; 6102 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6103 EVT VT = Op.getValueType(); 6104 6105 auto *M = cast<MemSDNode>(Op); 6106 unsigned Opcode = 0; 6107 6108 switch (IntrID) { 6109 case Intrinsic::amdgcn_buffer_atomic_swap: 6110 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6111 break; 6112 case Intrinsic::amdgcn_buffer_atomic_add: 6113 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6114 break; 6115 case Intrinsic::amdgcn_buffer_atomic_sub: 6116 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6117 break; 6118 case Intrinsic::amdgcn_buffer_atomic_smin: 6119 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6120 break; 6121 case Intrinsic::amdgcn_buffer_atomic_umin: 6122 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6123 break; 6124 case Intrinsic::amdgcn_buffer_atomic_smax: 6125 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6126 break; 6127 case Intrinsic::amdgcn_buffer_atomic_umax: 6128 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6129 break; 6130 case Intrinsic::amdgcn_buffer_atomic_and: 6131 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6132 break; 6133 case Intrinsic::amdgcn_buffer_atomic_or: 6134 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6135 break; 6136 case Intrinsic::amdgcn_buffer_atomic_xor: 6137 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6138 break; 6139 default: 6140 llvm_unreachable("unhandled atomic opcode"); 6141 } 6142 6143 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6144 M->getMemOperand()); 6145 } 6146 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6147 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6148 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6149 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6150 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6151 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6152 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6153 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6154 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6155 case Intrinsic::amdgcn_raw_buffer_atomic_xor: { 6156 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6157 SDValue Ops[] = { 6158 Op.getOperand(0), // Chain 6159 Op.getOperand(2), // vdata 6160 Op.getOperand(3), // rsrc 6161 DAG.getConstant(0, DL, MVT::i32), // vindex 6162 Offsets.first, // voffset 6163 Op.getOperand(5), // soffset 6164 Offsets.second, // offset 6165 Op.getOperand(6), // cachepolicy 6166 DAG.getConstant(0, DL, MVT::i1), // idxen 6167 }; 6168 EVT VT = Op.getValueType(); 6169 6170 auto *M = cast<MemSDNode>(Op); 6171 unsigned Opcode = 0; 6172 6173 switch (IntrID) { 6174 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6175 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6176 break; 6177 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6178 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6179 break; 6180 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6181 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6182 break; 6183 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6184 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6185 break; 6186 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6187 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6188 break; 6189 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6190 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6191 break; 6192 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6193 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6194 break; 6195 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6196 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6197 break; 6198 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6199 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6200 break; 6201 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6202 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6203 break; 6204 default: 6205 llvm_unreachable("unhandled atomic opcode"); 6206 } 6207 6208 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6209 M->getMemOperand()); 6210 } 6211 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6212 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6213 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6214 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6215 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6216 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6217 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6218 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6219 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6220 case Intrinsic::amdgcn_struct_buffer_atomic_xor: { 6221 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6222 SDValue Ops[] = { 6223 Op.getOperand(0), // Chain 6224 Op.getOperand(2), // vdata 6225 Op.getOperand(3), // rsrc 6226 Op.getOperand(4), // vindex 6227 Offsets.first, // voffset 6228 Op.getOperand(6), // soffset 6229 Offsets.second, // offset 6230 Op.getOperand(7), // cachepolicy 6231 DAG.getConstant(1, DL, MVT::i1), // idxen 6232 }; 6233 EVT VT = Op.getValueType(); 6234 6235 auto *M = cast<MemSDNode>(Op); 6236 unsigned Opcode = 0; 6237 6238 switch (IntrID) { 6239 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6240 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6241 break; 6242 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6243 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6244 break; 6245 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6246 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6247 break; 6248 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6249 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6250 break; 6251 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6252 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6253 break; 6254 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6255 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6256 break; 6257 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6258 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6259 break; 6260 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6261 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6262 break; 6263 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6264 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6265 break; 6266 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6267 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6268 break; 6269 default: 6270 llvm_unreachable("unhandled atomic opcode"); 6271 } 6272 6273 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6274 M->getMemOperand()); 6275 } 6276 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 6277 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6278 unsigned IdxEn = 1; 6279 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 6280 IdxEn = Idx->getZExtValue() != 0; 6281 SDValue Ops[] = { 6282 Op.getOperand(0), // Chain 6283 Op.getOperand(2), // src 6284 Op.getOperand(3), // cmp 6285 Op.getOperand(4), // rsrc 6286 Op.getOperand(5), // vindex 6287 SDValue(), // voffset -- will be set by setBufferOffsets 6288 SDValue(), // soffset -- will be set by setBufferOffsets 6289 SDValue(), // offset -- will be set by setBufferOffsets 6290 DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6291 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6292 }; 6293 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 6294 EVT VT = Op.getValueType(); 6295 auto *M = cast<MemSDNode>(Op); 6296 6297 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6298 Op->getVTList(), Ops, VT, M->getMemOperand()); 6299 } 6300 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 6301 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6302 SDValue Ops[] = { 6303 Op.getOperand(0), // Chain 6304 Op.getOperand(2), // src 6305 Op.getOperand(3), // cmp 6306 Op.getOperand(4), // rsrc 6307 DAG.getConstant(0, DL, MVT::i32), // vindex 6308 Offsets.first, // voffset 6309 Op.getOperand(6), // soffset 6310 Offsets.second, // offset 6311 Op.getOperand(7), // cachepolicy 6312 DAG.getConstant(0, DL, MVT::i1), // idxen 6313 }; 6314 EVT VT = Op.getValueType(); 6315 auto *M = cast<MemSDNode>(Op); 6316 6317 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6318 Op->getVTList(), Ops, VT, M->getMemOperand()); 6319 } 6320 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 6321 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 6322 SDValue Ops[] = { 6323 Op.getOperand(0), // Chain 6324 Op.getOperand(2), // src 6325 Op.getOperand(3), // cmp 6326 Op.getOperand(4), // rsrc 6327 Op.getOperand(5), // vindex 6328 Offsets.first, // voffset 6329 Op.getOperand(7), // soffset 6330 Offsets.second, // offset 6331 Op.getOperand(8), // cachepolicy 6332 DAG.getConstant(1, DL, MVT::i1), // idxen 6333 }; 6334 EVT VT = Op.getValueType(); 6335 auto *M = cast<MemSDNode>(Op); 6336 6337 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6338 Op->getVTList(), Ops, VT, M->getMemOperand()); 6339 } 6340 6341 default: 6342 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6343 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 6344 return lowerImage(Op, ImageDimIntr, DAG); 6345 6346 return SDValue(); 6347 } 6348 } 6349 6350 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 6351 // dwordx4 if on SI. 6352 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 6353 SDVTList VTList, 6354 ArrayRef<SDValue> Ops, EVT MemVT, 6355 MachineMemOperand *MMO, 6356 SelectionDAG &DAG) const { 6357 EVT VT = VTList.VTs[0]; 6358 EVT WidenedVT = VT; 6359 EVT WidenedMemVT = MemVT; 6360 if (!Subtarget->hasDwordx3LoadStores() && 6361 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 6362 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 6363 WidenedVT.getVectorElementType(), 4); 6364 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 6365 WidenedMemVT.getVectorElementType(), 4); 6366 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 6367 } 6368 6369 assert(VTList.NumVTs == 2); 6370 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 6371 6372 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 6373 WidenedMemVT, MMO); 6374 if (WidenedVT != VT) { 6375 auto Extract = DAG.getNode( 6376 ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 6377 DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout()))); 6378 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 6379 } 6380 return NewOp; 6381 } 6382 6383 SDValue SITargetLowering::handleD16VData(SDValue VData, 6384 SelectionDAG &DAG) const { 6385 EVT StoreVT = VData.getValueType(); 6386 6387 // No change for f16 and legal vector D16 types. 6388 if (!StoreVT.isVector()) 6389 return VData; 6390 6391 SDLoc DL(VData); 6392 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 6393 6394 if (Subtarget->hasUnpackedD16VMem()) { 6395 // We need to unpack the packed data to store. 6396 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 6397 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 6398 6399 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 6400 StoreVT.getVectorNumElements()); 6401 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 6402 return DAG.UnrollVectorOp(ZExt.getNode()); 6403 } 6404 6405 assert(isTypeLegal(StoreVT)); 6406 return VData; 6407 } 6408 6409 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 6410 SelectionDAG &DAG) const { 6411 SDLoc DL(Op); 6412 SDValue Chain = Op.getOperand(0); 6413 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6414 MachineFunction &MF = DAG.getMachineFunction(); 6415 6416 switch (IntrinsicID) { 6417 case Intrinsic::amdgcn_exp: { 6418 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 6419 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 6420 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8)); 6421 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9)); 6422 6423 const SDValue Ops[] = { 6424 Chain, 6425 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 6426 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 6427 Op.getOperand(4), // src0 6428 Op.getOperand(5), // src1 6429 Op.getOperand(6), // src2 6430 Op.getOperand(7), // src3 6431 DAG.getTargetConstant(0, DL, MVT::i1), // compr 6432 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 6433 }; 6434 6435 unsigned Opc = Done->isNullValue() ? 6436 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 6437 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 6438 } 6439 case Intrinsic::amdgcn_exp_compr: { 6440 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 6441 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 6442 SDValue Src0 = Op.getOperand(4); 6443 SDValue Src1 = Op.getOperand(5); 6444 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 6445 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7)); 6446 6447 SDValue Undef = DAG.getUNDEF(MVT::f32); 6448 const SDValue Ops[] = { 6449 Chain, 6450 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 6451 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 6452 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), 6453 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), 6454 Undef, // src2 6455 Undef, // src3 6456 DAG.getTargetConstant(1, DL, MVT::i1), // compr 6457 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 6458 }; 6459 6460 unsigned Opc = Done->isNullValue() ? 6461 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 6462 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 6463 } 6464 case Intrinsic::amdgcn_s_sendmsg: 6465 case Intrinsic::amdgcn_s_sendmsghalt: { 6466 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ? 6467 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT; 6468 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 6469 SDValue Glue = Chain.getValue(1); 6470 return DAG.getNode(NodeOp, DL, MVT::Other, Chain, 6471 Op.getOperand(2), Glue); 6472 } 6473 case Intrinsic::amdgcn_init_exec: { 6474 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain, 6475 Op.getOperand(2)); 6476 } 6477 case Intrinsic::amdgcn_init_exec_from_input: { 6478 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain, 6479 Op.getOperand(2), Op.getOperand(3)); 6480 } 6481 case Intrinsic::amdgcn_s_barrier: { 6482 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 6483 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 6484 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 6485 if (WGSize <= ST.getWavefrontSize()) 6486 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 6487 Op.getOperand(0)), 0); 6488 } 6489 return SDValue(); 6490 }; 6491 case Intrinsic::amdgcn_tbuffer_store: { 6492 SDValue VData = Op.getOperand(2); 6493 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6494 if (IsD16) 6495 VData = handleD16VData(VData, DAG); 6496 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6497 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6498 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6499 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 6500 unsigned IdxEn = 1; 6501 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6502 IdxEn = Idx->getZExtValue() != 0; 6503 SDValue Ops[] = { 6504 Chain, 6505 VData, // vdata 6506 Op.getOperand(3), // rsrc 6507 Op.getOperand(4), // vindex 6508 Op.getOperand(5), // voffset 6509 Op.getOperand(6), // soffset 6510 Op.getOperand(7), // offset 6511 DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6512 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6513 DAG.getConstant(IdxEn, DL, MVT::i1), // idexen 6514 }; 6515 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6516 AMDGPUISD::TBUFFER_STORE_FORMAT; 6517 MemSDNode *M = cast<MemSDNode>(Op); 6518 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6519 M->getMemoryVT(), M->getMemOperand()); 6520 } 6521 6522 case Intrinsic::amdgcn_struct_tbuffer_store: { 6523 SDValue VData = Op.getOperand(2); 6524 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6525 if (IsD16) 6526 VData = handleD16VData(VData, DAG); 6527 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6528 SDValue Ops[] = { 6529 Chain, 6530 VData, // vdata 6531 Op.getOperand(3), // rsrc 6532 Op.getOperand(4), // vindex 6533 Offsets.first, // voffset 6534 Op.getOperand(6), // soffset 6535 Offsets.second, // offset 6536 Op.getOperand(7), // format 6537 Op.getOperand(8), // cachepolicy 6538 DAG.getConstant(1, DL, MVT::i1), // idexen 6539 }; 6540 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6541 AMDGPUISD::TBUFFER_STORE_FORMAT; 6542 MemSDNode *M = cast<MemSDNode>(Op); 6543 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6544 M->getMemoryVT(), M->getMemOperand()); 6545 } 6546 6547 case Intrinsic::amdgcn_raw_tbuffer_store: { 6548 SDValue VData = Op.getOperand(2); 6549 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6550 if (IsD16) 6551 VData = handleD16VData(VData, DAG); 6552 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6553 SDValue Ops[] = { 6554 Chain, 6555 VData, // vdata 6556 Op.getOperand(3), // rsrc 6557 DAG.getConstant(0, DL, MVT::i32), // vindex 6558 Offsets.first, // voffset 6559 Op.getOperand(5), // soffset 6560 Offsets.second, // offset 6561 Op.getOperand(6), // format 6562 Op.getOperand(7), // cachepolicy 6563 DAG.getConstant(0, DL, MVT::i1), // idexen 6564 }; 6565 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6566 AMDGPUISD::TBUFFER_STORE_FORMAT; 6567 MemSDNode *M = cast<MemSDNode>(Op); 6568 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6569 M->getMemoryVT(), M->getMemOperand()); 6570 } 6571 6572 case Intrinsic::amdgcn_buffer_store: 6573 case Intrinsic::amdgcn_buffer_store_format: { 6574 SDValue VData = Op.getOperand(2); 6575 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6576 if (IsD16) 6577 VData = handleD16VData(VData, DAG); 6578 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6579 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6580 unsigned IdxEn = 1; 6581 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6582 IdxEn = Idx->getZExtValue() != 0; 6583 SDValue Ops[] = { 6584 Chain, 6585 VData, 6586 Op.getOperand(3), // rsrc 6587 Op.getOperand(4), // vindex 6588 SDValue(), // voffset -- will be set by setBufferOffsets 6589 SDValue(), // soffset -- will be set by setBufferOffsets 6590 SDValue(), // offset -- will be set by setBufferOffsets 6591 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6592 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6593 }; 6594 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6595 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 6596 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6597 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6598 MemSDNode *M = cast<MemSDNode>(Op); 6599 6600 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6601 EVT VDataType = VData.getValueType().getScalarType(); 6602 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6603 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6604 6605 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6606 M->getMemoryVT(), M->getMemOperand()); 6607 } 6608 6609 case Intrinsic::amdgcn_raw_buffer_store: 6610 case Intrinsic::amdgcn_raw_buffer_store_format: { 6611 SDValue VData = Op.getOperand(2); 6612 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6613 if (IsD16) 6614 VData = handleD16VData(VData, DAG); 6615 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6616 SDValue Ops[] = { 6617 Chain, 6618 VData, 6619 Op.getOperand(3), // rsrc 6620 DAG.getConstant(0, DL, MVT::i32), // vindex 6621 Offsets.first, // voffset 6622 Op.getOperand(5), // soffset 6623 Offsets.second, // offset 6624 Op.getOperand(6), // cachepolicy 6625 DAG.getConstant(0, DL, MVT::i1), // idxen 6626 }; 6627 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_raw_buffer_store ? 6628 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6629 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6630 MemSDNode *M = cast<MemSDNode>(Op); 6631 6632 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6633 EVT VDataType = VData.getValueType().getScalarType(); 6634 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6635 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6636 6637 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6638 M->getMemoryVT(), M->getMemOperand()); 6639 } 6640 6641 case Intrinsic::amdgcn_struct_buffer_store: 6642 case Intrinsic::amdgcn_struct_buffer_store_format: { 6643 SDValue VData = Op.getOperand(2); 6644 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6645 if (IsD16) 6646 VData = handleD16VData(VData, DAG); 6647 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6648 SDValue Ops[] = { 6649 Chain, 6650 VData, 6651 Op.getOperand(3), // rsrc 6652 Op.getOperand(4), // vindex 6653 Offsets.first, // voffset 6654 Op.getOperand(6), // soffset 6655 Offsets.second, // offset 6656 Op.getOperand(7), // cachepolicy 6657 DAG.getConstant(1, DL, MVT::i1), // idxen 6658 }; 6659 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 6660 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6661 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6662 MemSDNode *M = cast<MemSDNode>(Op); 6663 6664 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6665 EVT VDataType = VData.getValueType().getScalarType(); 6666 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6667 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6668 6669 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6670 M->getMemoryVT(), M->getMemOperand()); 6671 } 6672 6673 case Intrinsic::amdgcn_end_cf: 6674 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 6675 Op->getOperand(2), Chain), 0); 6676 6677 default: { 6678 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6679 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6680 return lowerImage(Op, ImageDimIntr, DAG); 6681 6682 return Op; 6683 } 6684 } 6685 } 6686 6687 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 6688 // offset (the offset that is included in bounds checking and swizzling, to be 6689 // split between the instruction's voffset and immoffset fields) and soffset 6690 // (the offset that is excluded from bounds checking and swizzling, to go in 6691 // the instruction's soffset field). This function takes the first kind of 6692 // offset and figures out how to split it between voffset and immoffset. 6693 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 6694 SDValue Offset, SelectionDAG &DAG) const { 6695 SDLoc DL(Offset); 6696 const unsigned MaxImm = 4095; 6697 SDValue N0 = Offset; 6698 ConstantSDNode *C1 = nullptr; 6699 6700 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 6701 N0 = SDValue(); 6702 else if (DAG.isBaseWithConstantOffset(N0)) { 6703 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 6704 N0 = N0.getOperand(0); 6705 } 6706 6707 if (C1) { 6708 unsigned ImmOffset = C1->getZExtValue(); 6709 // If the immediate value is too big for the immoffset field, put the value 6710 // and -4096 into the immoffset field so that the value that is copied/added 6711 // for the voffset field is a multiple of 4096, and it stands more chance 6712 // of being CSEd with the copy/add for another similar load/store. 6713 // However, do not do that rounding down to a multiple of 4096 if that is a 6714 // negative number, as it appears to be illegal to have a negative offset 6715 // in the vgpr, even if adding the immediate offset makes it positive. 6716 unsigned Overflow = ImmOffset & ~MaxImm; 6717 ImmOffset -= Overflow; 6718 if ((int32_t)Overflow < 0) { 6719 Overflow += ImmOffset; 6720 ImmOffset = 0; 6721 } 6722 C1 = cast<ConstantSDNode>(DAG.getConstant(ImmOffset, DL, MVT::i32)); 6723 if (Overflow) { 6724 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 6725 if (!N0) 6726 N0 = OverflowVal; 6727 else { 6728 SDValue Ops[] = { N0, OverflowVal }; 6729 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 6730 } 6731 } 6732 } 6733 if (!N0) 6734 N0 = DAG.getConstant(0, DL, MVT::i32); 6735 if (!C1) 6736 C1 = cast<ConstantSDNode>(DAG.getConstant(0, DL, MVT::i32)); 6737 return {N0, SDValue(C1, 0)}; 6738 } 6739 6740 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 6741 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 6742 // pointed to by Offsets. 6743 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 6744 SelectionDAG &DAG, SDValue *Offsets, 6745 unsigned Align) const { 6746 SDLoc DL(CombinedOffset); 6747 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 6748 uint32_t Imm = C->getZExtValue(); 6749 uint32_t SOffset, ImmOffset; 6750 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 6751 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 6752 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 6753 Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32); 6754 return; 6755 } 6756 } 6757 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 6758 SDValue N0 = CombinedOffset.getOperand(0); 6759 SDValue N1 = CombinedOffset.getOperand(1); 6760 uint32_t SOffset, ImmOffset; 6761 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 6762 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 6763 Subtarget, Align)) { 6764 Offsets[0] = N0; 6765 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 6766 Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32); 6767 return; 6768 } 6769 } 6770 Offsets[0] = CombinedOffset; 6771 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 6772 Offsets[2] = DAG.getConstant(0, DL, MVT::i32); 6773 } 6774 6775 // Handle 8 bit and 16 bit buffer loads 6776 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 6777 EVT LoadVT, SDLoc DL, 6778 ArrayRef<SDValue> Ops, 6779 MemSDNode *M) const { 6780 EVT IntVT = LoadVT.changeTypeToInteger(); 6781 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 6782 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 6783 6784 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 6785 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 6786 Ops, IntVT, 6787 M->getMemOperand()); 6788 SDValue BufferLoadTrunc = DAG.getNode(ISD::TRUNCATE, DL, 6789 LoadVT.getScalarType(), BufferLoad); 6790 return DAG.getMergeValues({BufferLoadTrunc, BufferLoad.getValue(1)}, DL); 6791 } 6792 6793 // Handle 8 bit and 16 bit buffer stores 6794 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 6795 EVT VDataType, SDLoc DL, 6796 SDValue Ops[], 6797 MemSDNode *M) const { 6798 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 6799 Ops[1] = BufferStoreExt; 6800 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 6801 AMDGPUISD::BUFFER_STORE_SHORT; 6802 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 6803 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 6804 M->getMemOperand()); 6805 } 6806 6807 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 6808 ISD::LoadExtType ExtType, SDValue Op, 6809 const SDLoc &SL, EVT VT) { 6810 if (VT.bitsLT(Op.getValueType())) 6811 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 6812 6813 switch (ExtType) { 6814 case ISD::SEXTLOAD: 6815 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 6816 case ISD::ZEXTLOAD: 6817 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 6818 case ISD::EXTLOAD: 6819 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 6820 case ISD::NON_EXTLOAD: 6821 return Op; 6822 } 6823 6824 llvm_unreachable("invalid ext type"); 6825 } 6826 6827 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 6828 SelectionDAG &DAG = DCI.DAG; 6829 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 6830 return SDValue(); 6831 6832 // FIXME: Constant loads should all be marked invariant. 6833 unsigned AS = Ld->getAddressSpace(); 6834 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 6835 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 6836 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 6837 return SDValue(); 6838 6839 // Don't do this early, since it may interfere with adjacent load merging for 6840 // illegal types. We can avoid losing alignment information for exotic types 6841 // pre-legalize. 6842 EVT MemVT = Ld->getMemoryVT(); 6843 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 6844 MemVT.getSizeInBits() >= 32) 6845 return SDValue(); 6846 6847 SDLoc SL(Ld); 6848 6849 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 6850 "unexpected vector extload"); 6851 6852 // TODO: Drop only high part of range. 6853 SDValue Ptr = Ld->getBasePtr(); 6854 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 6855 MVT::i32, SL, Ld->getChain(), Ptr, 6856 Ld->getOffset(), 6857 Ld->getPointerInfo(), MVT::i32, 6858 Ld->getAlignment(), 6859 Ld->getMemOperand()->getFlags(), 6860 Ld->getAAInfo(), 6861 nullptr); // Drop ranges 6862 6863 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 6864 if (MemVT.isFloatingPoint()) { 6865 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 6866 "unexpected fp extload"); 6867 TruncVT = MemVT.changeTypeToInteger(); 6868 } 6869 6870 SDValue Cvt = NewLoad; 6871 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 6872 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 6873 DAG.getValueType(TruncVT)); 6874 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 6875 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 6876 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 6877 } else { 6878 assert(Ld->getExtensionType() == ISD::EXTLOAD); 6879 } 6880 6881 EVT VT = Ld->getValueType(0); 6882 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 6883 6884 DCI.AddToWorklist(Cvt.getNode()); 6885 6886 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 6887 // the appropriate extension from the 32-bit load. 6888 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 6889 DCI.AddToWorklist(Cvt.getNode()); 6890 6891 // Handle conversion back to floating point if necessary. 6892 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 6893 6894 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 6895 } 6896 6897 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 6898 SDLoc DL(Op); 6899 LoadSDNode *Load = cast<LoadSDNode>(Op); 6900 ISD::LoadExtType ExtType = Load->getExtensionType(); 6901 EVT MemVT = Load->getMemoryVT(); 6902 6903 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 6904 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 6905 return SDValue(); 6906 6907 // FIXME: Copied from PPC 6908 // First, load into 32 bits, then truncate to 1 bit. 6909 6910 SDValue Chain = Load->getChain(); 6911 SDValue BasePtr = Load->getBasePtr(); 6912 MachineMemOperand *MMO = Load->getMemOperand(); 6913 6914 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 6915 6916 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 6917 BasePtr, RealMemVT, MMO); 6918 6919 if (!MemVT.isVector()) { 6920 SDValue Ops[] = { 6921 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 6922 NewLD.getValue(1) 6923 }; 6924 6925 return DAG.getMergeValues(Ops, DL); 6926 } 6927 6928 SmallVector<SDValue, 3> Elts; 6929 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 6930 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 6931 DAG.getConstant(I, DL, MVT::i32)); 6932 6933 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 6934 } 6935 6936 SDValue Ops[] = { 6937 DAG.getBuildVector(MemVT, DL, Elts), 6938 NewLD.getValue(1) 6939 }; 6940 6941 return DAG.getMergeValues(Ops, DL); 6942 } 6943 6944 if (!MemVT.isVector()) 6945 return SDValue(); 6946 6947 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 6948 "Custom lowering for non-i32 vectors hasn't been implemented."); 6949 6950 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 6951 *Load->getMemOperand())) { 6952 SDValue Ops[2]; 6953 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 6954 return DAG.getMergeValues(Ops, DL); 6955 } 6956 6957 unsigned Alignment = Load->getAlignment(); 6958 unsigned AS = Load->getAddressSpace(); 6959 if (Subtarget->hasLDSMisalignedBug() && 6960 AS == AMDGPUAS::FLAT_ADDRESS && 6961 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 6962 return SplitVectorLoad(Op, DAG); 6963 } 6964 6965 MachineFunction &MF = DAG.getMachineFunction(); 6966 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 6967 // If there is a possibilty that flat instruction access scratch memory 6968 // then we need to use the same legalization rules we use for private. 6969 if (AS == AMDGPUAS::FLAT_ADDRESS) 6970 AS = MFI->hasFlatScratchInit() ? 6971 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 6972 6973 unsigned NumElements = MemVT.getVectorNumElements(); 6974 6975 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 6976 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 6977 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 6978 if (MemVT.isPow2VectorType()) 6979 return SDValue(); 6980 if (NumElements == 3) 6981 return WidenVectorLoad(Op, DAG); 6982 return SplitVectorLoad(Op, DAG); 6983 } 6984 // Non-uniform loads will be selected to MUBUF instructions, so they 6985 // have the same legalization requirements as global and private 6986 // loads. 6987 // 6988 } 6989 6990 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 6991 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 6992 AS == AMDGPUAS::GLOBAL_ADDRESS) { 6993 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 6994 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 6995 Alignment >= 4 && NumElements < 32) { 6996 if (MemVT.isPow2VectorType()) 6997 return SDValue(); 6998 if (NumElements == 3) 6999 return WidenVectorLoad(Op, DAG); 7000 return SplitVectorLoad(Op, DAG); 7001 } 7002 // Non-uniform loads will be selected to MUBUF instructions, so they 7003 // have the same legalization requirements as global and private 7004 // loads. 7005 // 7006 } 7007 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7008 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7009 AS == AMDGPUAS::GLOBAL_ADDRESS || 7010 AS == AMDGPUAS::FLAT_ADDRESS) { 7011 if (NumElements > 4) 7012 return SplitVectorLoad(Op, DAG); 7013 // v3 loads not supported on SI. 7014 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7015 return WidenVectorLoad(Op, DAG); 7016 // v3 and v4 loads are supported for private and global memory. 7017 return SDValue(); 7018 } 7019 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7020 // Depending on the setting of the private_element_size field in the 7021 // resource descriptor, we can only make private accesses up to a certain 7022 // size. 7023 switch (Subtarget->getMaxPrivateElementSize()) { 7024 case 4: 7025 return scalarizeVectorLoad(Load, DAG); 7026 case 8: 7027 if (NumElements > 2) 7028 return SplitVectorLoad(Op, DAG); 7029 return SDValue(); 7030 case 16: 7031 // Same as global/flat 7032 if (NumElements > 4) 7033 return SplitVectorLoad(Op, DAG); 7034 // v3 loads not supported on SI. 7035 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7036 return WidenVectorLoad(Op, DAG); 7037 return SDValue(); 7038 default: 7039 llvm_unreachable("unsupported private_element_size"); 7040 } 7041 } else if (AS == AMDGPUAS::LOCAL_ADDRESS) { 7042 // Use ds_read_b128 if possible. 7043 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7044 MemVT.getStoreSize() == 16) 7045 return SDValue(); 7046 7047 if (NumElements > 2) 7048 return SplitVectorLoad(Op, DAG); 7049 7050 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7051 // address is negative, then the instruction is incorrectly treated as 7052 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7053 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7054 // load later in the SILoadStoreOptimizer. 7055 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7056 NumElements == 2 && MemVT.getStoreSize() == 8 && 7057 Load->getAlignment() < 8) { 7058 return SplitVectorLoad(Op, DAG); 7059 } 7060 } 7061 return SDValue(); 7062 } 7063 7064 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7065 EVT VT = Op.getValueType(); 7066 assert(VT.getSizeInBits() == 64); 7067 7068 SDLoc DL(Op); 7069 SDValue Cond = Op.getOperand(0); 7070 7071 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7072 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7073 7074 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7075 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7076 7077 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7078 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7079 7080 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7081 7082 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7083 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7084 7085 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7086 7087 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7088 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7089 } 7090 7091 // Catch division cases where we can use shortcuts with rcp and rsq 7092 // instructions. 7093 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7094 SelectionDAG &DAG) const { 7095 SDLoc SL(Op); 7096 SDValue LHS = Op.getOperand(0); 7097 SDValue RHS = Op.getOperand(1); 7098 EVT VT = Op.getValueType(); 7099 const SDNodeFlags Flags = Op->getFlags(); 7100 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal(); 7101 7102 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals()) 7103 return SDValue(); 7104 7105 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7106 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) { 7107 if (CLHS->isExactlyValue(1.0)) { 7108 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7109 // the CI documentation has a worst case error of 1 ulp. 7110 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7111 // use it as long as we aren't trying to use denormals. 7112 // 7113 // v_rcp_f16 and v_rsq_f16 DO support denormals. 7114 7115 // 1.0 / sqrt(x) -> rsq(x) 7116 7117 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 7118 // error seems really high at 2^29 ULP. 7119 if (RHS.getOpcode() == ISD::FSQRT) 7120 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 7121 7122 // 1.0 / x -> rcp(x) 7123 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7124 } 7125 7126 // Same as for 1.0, but expand the sign out of the constant. 7127 if (CLHS->isExactlyValue(-1.0)) { 7128 // -1.0 / x -> rcp (fneg x) 7129 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7130 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 7131 } 7132 } 7133 } 7134 7135 if (Unsafe) { 7136 // Turn into multiply by the reciprocal. 7137 // x / y -> x * (1.0 / y) 7138 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7139 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 7140 } 7141 7142 return SDValue(); 7143 } 7144 7145 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7146 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 7147 if (GlueChain->getNumValues() <= 1) { 7148 return DAG.getNode(Opcode, SL, VT, A, B); 7149 } 7150 7151 assert(GlueChain->getNumValues() == 3); 7152 7153 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7154 switch (Opcode) { 7155 default: llvm_unreachable("no chain equivalent for opcode"); 7156 case ISD::FMUL: 7157 Opcode = AMDGPUISD::FMUL_W_CHAIN; 7158 break; 7159 } 7160 7161 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 7162 GlueChain.getValue(2)); 7163 } 7164 7165 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7166 EVT VT, SDValue A, SDValue B, SDValue C, 7167 SDValue GlueChain) { 7168 if (GlueChain->getNumValues() <= 1) { 7169 return DAG.getNode(Opcode, SL, VT, A, B, C); 7170 } 7171 7172 assert(GlueChain->getNumValues() == 3); 7173 7174 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7175 switch (Opcode) { 7176 default: llvm_unreachable("no chain equivalent for opcode"); 7177 case ISD::FMA: 7178 Opcode = AMDGPUISD::FMA_W_CHAIN; 7179 break; 7180 } 7181 7182 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 7183 GlueChain.getValue(2)); 7184 } 7185 7186 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 7187 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7188 return FastLowered; 7189 7190 SDLoc SL(Op); 7191 SDValue Src0 = Op.getOperand(0); 7192 SDValue Src1 = Op.getOperand(1); 7193 7194 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 7195 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 7196 7197 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 7198 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 7199 7200 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 7201 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 7202 7203 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 7204 } 7205 7206 // Faster 2.5 ULP division that does not support denormals. 7207 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 7208 SDLoc SL(Op); 7209 SDValue LHS = Op.getOperand(1); 7210 SDValue RHS = Op.getOperand(2); 7211 7212 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 7213 7214 const APFloat K0Val(BitsToFloat(0x6f800000)); 7215 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 7216 7217 const APFloat K1Val(BitsToFloat(0x2f800000)); 7218 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 7219 7220 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7221 7222 EVT SetCCVT = 7223 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 7224 7225 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 7226 7227 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 7228 7229 // TODO: Should this propagate fast-math-flags? 7230 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 7231 7232 // rcp does not support denormals. 7233 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 7234 7235 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 7236 7237 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 7238 } 7239 7240 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 7241 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7242 return FastLowered; 7243 7244 SDLoc SL(Op); 7245 SDValue LHS = Op.getOperand(0); 7246 SDValue RHS = Op.getOperand(1); 7247 7248 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7249 7250 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 7251 7252 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7253 RHS, RHS, LHS); 7254 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7255 LHS, RHS, LHS); 7256 7257 // Denominator is scaled to not be denormal, so using rcp is ok. 7258 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 7259 DenominatorScaled); 7260 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 7261 DenominatorScaled); 7262 7263 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 7264 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 7265 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 7266 7267 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 7268 7269 if (!Subtarget->hasFP32Denormals()) { 7270 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 7271 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 7272 SL, MVT::i32); 7273 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 7274 DAG.getEntryNode(), 7275 EnableDenormValue, BitField); 7276 SDValue Ops[3] = { 7277 NegDivScale0, 7278 EnableDenorm.getValue(0), 7279 EnableDenorm.getValue(1) 7280 }; 7281 7282 NegDivScale0 = DAG.getMergeValues(Ops, SL); 7283 } 7284 7285 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 7286 ApproxRcp, One, NegDivScale0); 7287 7288 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 7289 ApproxRcp, Fma0); 7290 7291 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 7292 Fma1, Fma1); 7293 7294 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 7295 NumeratorScaled, Mul); 7296 7297 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 7298 7299 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 7300 NumeratorScaled, Fma3); 7301 7302 if (!Subtarget->hasFP32Denormals()) { 7303 const SDValue DisableDenormValue = 7304 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 7305 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 7306 Fma4.getValue(1), 7307 DisableDenormValue, 7308 BitField, 7309 Fma4.getValue(2)); 7310 7311 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 7312 DisableDenorm, DAG.getRoot()); 7313 DAG.setRoot(OutputChain); 7314 } 7315 7316 SDValue Scale = NumeratorScaled.getValue(1); 7317 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 7318 Fma4, Fma1, Fma3, Scale); 7319 7320 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 7321 } 7322 7323 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 7324 if (DAG.getTarget().Options.UnsafeFPMath) 7325 return lowerFastUnsafeFDIV(Op, DAG); 7326 7327 SDLoc SL(Op); 7328 SDValue X = Op.getOperand(0); 7329 SDValue Y = Op.getOperand(1); 7330 7331 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 7332 7333 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 7334 7335 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 7336 7337 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 7338 7339 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 7340 7341 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 7342 7343 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 7344 7345 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 7346 7347 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 7348 7349 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 7350 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 7351 7352 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 7353 NegDivScale0, Mul, DivScale1); 7354 7355 SDValue Scale; 7356 7357 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 7358 // Workaround a hardware bug on SI where the condition output from div_scale 7359 // is not usable. 7360 7361 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 7362 7363 // Figure out if the scale to use for div_fmas. 7364 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 7365 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 7366 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 7367 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 7368 7369 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 7370 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 7371 7372 SDValue Scale0Hi 7373 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 7374 SDValue Scale1Hi 7375 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 7376 7377 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 7378 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 7379 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 7380 } else { 7381 Scale = DivScale1.getValue(1); 7382 } 7383 7384 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 7385 Fma4, Fma3, Mul, Scale); 7386 7387 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 7388 } 7389 7390 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 7391 EVT VT = Op.getValueType(); 7392 7393 if (VT == MVT::f32) 7394 return LowerFDIV32(Op, DAG); 7395 7396 if (VT == MVT::f64) 7397 return LowerFDIV64(Op, DAG); 7398 7399 if (VT == MVT::f16) 7400 return LowerFDIV16(Op, DAG); 7401 7402 llvm_unreachable("Unexpected type for fdiv"); 7403 } 7404 7405 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7406 SDLoc DL(Op); 7407 StoreSDNode *Store = cast<StoreSDNode>(Op); 7408 EVT VT = Store->getMemoryVT(); 7409 7410 if (VT == MVT::i1) { 7411 return DAG.getTruncStore(Store->getChain(), DL, 7412 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 7413 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 7414 } 7415 7416 assert(VT.isVector() && 7417 Store->getValue().getValueType().getScalarType() == MVT::i32); 7418 7419 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 7420 *Store->getMemOperand())) { 7421 return expandUnalignedStore(Store, DAG); 7422 } 7423 7424 unsigned AS = Store->getAddressSpace(); 7425 if (Subtarget->hasLDSMisalignedBug() && 7426 AS == AMDGPUAS::FLAT_ADDRESS && 7427 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 7428 return SplitVectorStore(Op, DAG); 7429 } 7430 7431 MachineFunction &MF = DAG.getMachineFunction(); 7432 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7433 // If there is a possibilty that flat instruction access scratch memory 7434 // then we need to use the same legalization rules we use for private. 7435 if (AS == AMDGPUAS::FLAT_ADDRESS) 7436 AS = MFI->hasFlatScratchInit() ? 7437 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7438 7439 unsigned NumElements = VT.getVectorNumElements(); 7440 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 7441 AS == AMDGPUAS::FLAT_ADDRESS) { 7442 if (NumElements > 4) 7443 return SplitVectorStore(Op, DAG); 7444 // v3 stores not supported on SI. 7445 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7446 return SplitVectorStore(Op, DAG); 7447 return SDValue(); 7448 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7449 switch (Subtarget->getMaxPrivateElementSize()) { 7450 case 4: 7451 return scalarizeVectorStore(Store, DAG); 7452 case 8: 7453 if (NumElements > 2) 7454 return SplitVectorStore(Op, DAG); 7455 return SDValue(); 7456 case 16: 7457 if (NumElements > 4 || NumElements == 3) 7458 return SplitVectorStore(Op, DAG); 7459 return SDValue(); 7460 default: 7461 llvm_unreachable("unsupported private_element_size"); 7462 } 7463 } else if (AS == AMDGPUAS::LOCAL_ADDRESS) { 7464 // Use ds_write_b128 if possible. 7465 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 7466 VT.getStoreSize() == 16 && NumElements != 3) 7467 return SDValue(); 7468 7469 if (NumElements > 2) 7470 return SplitVectorStore(Op, DAG); 7471 7472 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7473 // address is negative, then the instruction is incorrectly treated as 7474 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7475 // stores here to avoid emitting ds_write2_b32. We may re-combine the 7476 // store later in the SILoadStoreOptimizer. 7477 if (!Subtarget->hasUsableDSOffset() && 7478 NumElements == 2 && VT.getStoreSize() == 8 && 7479 Store->getAlignment() < 8) { 7480 return SplitVectorStore(Op, DAG); 7481 } 7482 7483 return SDValue(); 7484 } else { 7485 llvm_unreachable("unhandled address space"); 7486 } 7487 } 7488 7489 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 7490 SDLoc DL(Op); 7491 EVT VT = Op.getValueType(); 7492 SDValue Arg = Op.getOperand(0); 7493 SDValue TrigVal; 7494 7495 // TODO: Should this propagate fast-math-flags? 7496 7497 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT); 7498 7499 if (Subtarget->hasTrigReducedRange()) { 7500 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7501 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal); 7502 } else { 7503 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7504 } 7505 7506 switch (Op.getOpcode()) { 7507 case ISD::FCOS: 7508 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal); 7509 case ISD::FSIN: 7510 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal); 7511 default: 7512 llvm_unreachable("Wrong trig opcode"); 7513 } 7514 } 7515 7516 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 7517 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 7518 assert(AtomicNode->isCompareAndSwap()); 7519 unsigned AS = AtomicNode->getAddressSpace(); 7520 7521 // No custom lowering required for local address space 7522 if (!isFlatGlobalAddrSpace(AS)) 7523 return Op; 7524 7525 // Non-local address space requires custom lowering for atomic compare 7526 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 7527 SDLoc DL(Op); 7528 SDValue ChainIn = Op.getOperand(0); 7529 SDValue Addr = Op.getOperand(1); 7530 SDValue Old = Op.getOperand(2); 7531 SDValue New = Op.getOperand(3); 7532 EVT VT = Op.getValueType(); 7533 MVT SimpleVT = VT.getSimpleVT(); 7534 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 7535 7536 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 7537 SDValue Ops[] = { ChainIn, Addr, NewOld }; 7538 7539 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 7540 Ops, VT, AtomicNode->getMemOperand()); 7541 } 7542 7543 //===----------------------------------------------------------------------===// 7544 // Custom DAG optimizations 7545 //===----------------------------------------------------------------------===// 7546 7547 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 7548 DAGCombinerInfo &DCI) const { 7549 EVT VT = N->getValueType(0); 7550 EVT ScalarVT = VT.getScalarType(); 7551 if (ScalarVT != MVT::f32) 7552 return SDValue(); 7553 7554 SelectionDAG &DAG = DCI.DAG; 7555 SDLoc DL(N); 7556 7557 SDValue Src = N->getOperand(0); 7558 EVT SrcVT = Src.getValueType(); 7559 7560 // TODO: We could try to match extracting the higher bytes, which would be 7561 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 7562 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 7563 // about in practice. 7564 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 7565 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 7566 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 7567 DCI.AddToWorklist(Cvt.getNode()); 7568 return Cvt; 7569 } 7570 } 7571 7572 return SDValue(); 7573 } 7574 7575 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 7576 7577 // This is a variant of 7578 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 7579 // 7580 // The normal DAG combiner will do this, but only if the add has one use since 7581 // that would increase the number of instructions. 7582 // 7583 // This prevents us from seeing a constant offset that can be folded into a 7584 // memory instruction's addressing mode. If we know the resulting add offset of 7585 // a pointer can be folded into an addressing offset, we can replace the pointer 7586 // operand with the add of new constant offset. This eliminates one of the uses, 7587 // and may allow the remaining use to also be simplified. 7588 // 7589 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 7590 unsigned AddrSpace, 7591 EVT MemVT, 7592 DAGCombinerInfo &DCI) const { 7593 SDValue N0 = N->getOperand(0); 7594 SDValue N1 = N->getOperand(1); 7595 7596 // We only do this to handle cases where it's profitable when there are 7597 // multiple uses of the add, so defer to the standard combine. 7598 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 7599 N0->hasOneUse()) 7600 return SDValue(); 7601 7602 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 7603 if (!CN1) 7604 return SDValue(); 7605 7606 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7607 if (!CAdd) 7608 return SDValue(); 7609 7610 // If the resulting offset is too large, we can't fold it into the addressing 7611 // mode offset. 7612 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 7613 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 7614 7615 AddrMode AM; 7616 AM.HasBaseReg = true; 7617 AM.BaseOffs = Offset.getSExtValue(); 7618 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 7619 return SDValue(); 7620 7621 SelectionDAG &DAG = DCI.DAG; 7622 SDLoc SL(N); 7623 EVT VT = N->getValueType(0); 7624 7625 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 7626 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 7627 7628 SDNodeFlags Flags; 7629 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 7630 (N0.getOpcode() == ISD::OR || 7631 N0->getFlags().hasNoUnsignedWrap())); 7632 7633 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 7634 } 7635 7636 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 7637 DAGCombinerInfo &DCI) const { 7638 SDValue Ptr = N->getBasePtr(); 7639 SelectionDAG &DAG = DCI.DAG; 7640 SDLoc SL(N); 7641 7642 // TODO: We could also do this for multiplies. 7643 if (Ptr.getOpcode() == ISD::SHL) { 7644 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 7645 N->getMemoryVT(), DCI); 7646 if (NewPtr) { 7647 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 7648 7649 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 7650 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 7651 } 7652 } 7653 7654 return SDValue(); 7655 } 7656 7657 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 7658 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 7659 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 7660 (Opc == ISD::XOR && Val == 0); 7661 } 7662 7663 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 7664 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 7665 // integer combine opportunities since most 64-bit operations are decomposed 7666 // this way. TODO: We won't want this for SALU especially if it is an inline 7667 // immediate. 7668 SDValue SITargetLowering::splitBinaryBitConstantOp( 7669 DAGCombinerInfo &DCI, 7670 const SDLoc &SL, 7671 unsigned Opc, SDValue LHS, 7672 const ConstantSDNode *CRHS) const { 7673 uint64_t Val = CRHS->getZExtValue(); 7674 uint32_t ValLo = Lo_32(Val); 7675 uint32_t ValHi = Hi_32(Val); 7676 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 7677 7678 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 7679 bitOpWithConstantIsReducible(Opc, ValHi)) || 7680 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 7681 // If we need to materialize a 64-bit immediate, it will be split up later 7682 // anyway. Avoid creating the harder to understand 64-bit immediate 7683 // materialization. 7684 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 7685 } 7686 7687 return SDValue(); 7688 } 7689 7690 // Returns true if argument is a boolean value which is not serialized into 7691 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 7692 static bool isBoolSGPR(SDValue V) { 7693 if (V.getValueType() != MVT::i1) 7694 return false; 7695 switch (V.getOpcode()) { 7696 default: break; 7697 case ISD::SETCC: 7698 case ISD::AND: 7699 case ISD::OR: 7700 case ISD::XOR: 7701 case AMDGPUISD::FP_CLASS: 7702 return true; 7703 } 7704 return false; 7705 } 7706 7707 // If a constant has all zeroes or all ones within each byte return it. 7708 // Otherwise return 0. 7709 static uint32_t getConstantPermuteMask(uint32_t C) { 7710 // 0xff for any zero byte in the mask 7711 uint32_t ZeroByteMask = 0; 7712 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 7713 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 7714 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 7715 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 7716 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 7717 if ((NonZeroByteMask & C) != NonZeroByteMask) 7718 return 0; // Partial bytes selected. 7719 return C; 7720 } 7721 7722 // Check if a node selects whole bytes from its operand 0 starting at a byte 7723 // boundary while masking the rest. Returns select mask as in the v_perm_b32 7724 // or -1 if not succeeded. 7725 // Note byte select encoding: 7726 // value 0-3 selects corresponding source byte; 7727 // value 0xc selects zero; 7728 // value 0xff selects 0xff. 7729 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 7730 assert(V.getValueSizeInBits() == 32); 7731 7732 if (V.getNumOperands() != 2) 7733 return ~0; 7734 7735 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 7736 if (!N1) 7737 return ~0; 7738 7739 uint32_t C = N1->getZExtValue(); 7740 7741 switch (V.getOpcode()) { 7742 default: 7743 break; 7744 case ISD::AND: 7745 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 7746 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 7747 } 7748 break; 7749 7750 case ISD::OR: 7751 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 7752 return (0x03020100 & ~ConstMask) | ConstMask; 7753 } 7754 break; 7755 7756 case ISD::SHL: 7757 if (C % 8) 7758 return ~0; 7759 7760 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 7761 7762 case ISD::SRL: 7763 if (C % 8) 7764 return ~0; 7765 7766 return uint32_t(0x0c0c0c0c03020100ull >> C); 7767 } 7768 7769 return ~0; 7770 } 7771 7772 SDValue SITargetLowering::performAndCombine(SDNode *N, 7773 DAGCombinerInfo &DCI) const { 7774 if (DCI.isBeforeLegalize()) 7775 return SDValue(); 7776 7777 SelectionDAG &DAG = DCI.DAG; 7778 EVT VT = N->getValueType(0); 7779 SDValue LHS = N->getOperand(0); 7780 SDValue RHS = N->getOperand(1); 7781 7782 7783 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 7784 if (VT == MVT::i64 && CRHS) { 7785 if (SDValue Split 7786 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 7787 return Split; 7788 } 7789 7790 if (CRHS && VT == MVT::i32) { 7791 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 7792 // nb = number of trailing zeroes in mask 7793 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 7794 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 7795 uint64_t Mask = CRHS->getZExtValue(); 7796 unsigned Bits = countPopulation(Mask); 7797 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 7798 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 7799 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 7800 unsigned Shift = CShift->getZExtValue(); 7801 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 7802 unsigned Offset = NB + Shift; 7803 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 7804 SDLoc SL(N); 7805 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 7806 LHS->getOperand(0), 7807 DAG.getConstant(Offset, SL, MVT::i32), 7808 DAG.getConstant(Bits, SL, MVT::i32)); 7809 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 7810 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 7811 DAG.getValueType(NarrowVT)); 7812 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 7813 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 7814 return Shl; 7815 } 7816 } 7817 } 7818 7819 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 7820 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 7821 isa<ConstantSDNode>(LHS.getOperand(2))) { 7822 uint32_t Sel = getConstantPermuteMask(Mask); 7823 if (!Sel) 7824 return SDValue(); 7825 7826 // Select 0xc for all zero bytes 7827 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 7828 SDLoc DL(N); 7829 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 7830 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 7831 } 7832 } 7833 7834 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 7835 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 7836 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 7837 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7838 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 7839 7840 SDValue X = LHS.getOperand(0); 7841 SDValue Y = RHS.getOperand(0); 7842 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 7843 return SDValue(); 7844 7845 if (LCC == ISD::SETO) { 7846 if (X != LHS.getOperand(1)) 7847 return SDValue(); 7848 7849 if (RCC == ISD::SETUNE) { 7850 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 7851 if (!C1 || !C1->isInfinity() || C1->isNegative()) 7852 return SDValue(); 7853 7854 const uint32_t Mask = SIInstrFlags::N_NORMAL | 7855 SIInstrFlags::N_SUBNORMAL | 7856 SIInstrFlags::N_ZERO | 7857 SIInstrFlags::P_ZERO | 7858 SIInstrFlags::P_SUBNORMAL | 7859 SIInstrFlags::P_NORMAL; 7860 7861 static_assert(((~(SIInstrFlags::S_NAN | 7862 SIInstrFlags::Q_NAN | 7863 SIInstrFlags::N_INFINITY | 7864 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 7865 "mask not equal"); 7866 7867 SDLoc DL(N); 7868 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 7869 X, DAG.getConstant(Mask, DL, MVT::i32)); 7870 } 7871 } 7872 } 7873 7874 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 7875 std::swap(LHS, RHS); 7876 7877 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 7878 RHS.hasOneUse()) { 7879 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 7880 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 7881 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 7882 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 7883 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 7884 (RHS.getOperand(0) == LHS.getOperand(0) && 7885 LHS.getOperand(0) == LHS.getOperand(1))) { 7886 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 7887 unsigned NewMask = LCC == ISD::SETO ? 7888 Mask->getZExtValue() & ~OrdMask : 7889 Mask->getZExtValue() & OrdMask; 7890 7891 SDLoc DL(N); 7892 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 7893 DAG.getConstant(NewMask, DL, MVT::i32)); 7894 } 7895 } 7896 7897 if (VT == MVT::i32 && 7898 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 7899 // and x, (sext cc from i1) => select cc, x, 0 7900 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 7901 std::swap(LHS, RHS); 7902 if (isBoolSGPR(RHS.getOperand(0))) 7903 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 7904 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 7905 } 7906 7907 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 7908 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 7909 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 7910 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 7911 uint32_t LHSMask = getPermuteMask(DAG, LHS); 7912 uint32_t RHSMask = getPermuteMask(DAG, RHS); 7913 if (LHSMask != ~0u && RHSMask != ~0u) { 7914 // Canonicalize the expression in an attempt to have fewer unique masks 7915 // and therefore fewer registers used to hold the masks. 7916 if (LHSMask > RHSMask) { 7917 std::swap(LHSMask, RHSMask); 7918 std::swap(LHS, RHS); 7919 } 7920 7921 // Select 0xc for each lane used from source operand. Zero has 0xc mask 7922 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 7923 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 7924 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 7925 7926 // Check of we need to combine values from two sources within a byte. 7927 if (!(LHSUsedLanes & RHSUsedLanes) && 7928 // If we select high and lower word keep it for SDWA. 7929 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 7930 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 7931 // Each byte in each mask is either selector mask 0-3, or has higher 7932 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 7933 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 7934 // mask which is not 0xff wins. By anding both masks we have a correct 7935 // result except that 0x0c shall be corrected to give 0x0c only. 7936 uint32_t Mask = LHSMask & RHSMask; 7937 for (unsigned I = 0; I < 32; I += 8) { 7938 uint32_t ByteSel = 0xff << I; 7939 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 7940 Mask &= (0x0c << I) & 0xffffffff; 7941 } 7942 7943 // Add 4 to each active LHS lane. It will not affect any existing 0xff 7944 // or 0x0c. 7945 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 7946 SDLoc DL(N); 7947 7948 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 7949 LHS.getOperand(0), RHS.getOperand(0), 7950 DAG.getConstant(Sel, DL, MVT::i32)); 7951 } 7952 } 7953 } 7954 7955 return SDValue(); 7956 } 7957 7958 SDValue SITargetLowering::performOrCombine(SDNode *N, 7959 DAGCombinerInfo &DCI) const { 7960 SelectionDAG &DAG = DCI.DAG; 7961 SDValue LHS = N->getOperand(0); 7962 SDValue RHS = N->getOperand(1); 7963 7964 EVT VT = N->getValueType(0); 7965 if (VT == MVT::i1) { 7966 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 7967 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 7968 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 7969 SDValue Src = LHS.getOperand(0); 7970 if (Src != RHS.getOperand(0)) 7971 return SDValue(); 7972 7973 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 7974 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 7975 if (!CLHS || !CRHS) 7976 return SDValue(); 7977 7978 // Only 10 bits are used. 7979 static const uint32_t MaxMask = 0x3ff; 7980 7981 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 7982 SDLoc DL(N); 7983 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 7984 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 7985 } 7986 7987 return SDValue(); 7988 } 7989 7990 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 7991 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 7992 LHS.getOpcode() == AMDGPUISD::PERM && 7993 isa<ConstantSDNode>(LHS.getOperand(2))) { 7994 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 7995 if (!Sel) 7996 return SDValue(); 7997 7998 Sel |= LHS.getConstantOperandVal(2); 7999 SDLoc DL(N); 8000 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8001 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8002 } 8003 8004 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8005 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8006 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8007 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8008 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8009 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8010 if (LHSMask != ~0u && RHSMask != ~0u) { 8011 // Canonicalize the expression in an attempt to have fewer unique masks 8012 // and therefore fewer registers used to hold the masks. 8013 if (LHSMask > RHSMask) { 8014 std::swap(LHSMask, RHSMask); 8015 std::swap(LHS, RHS); 8016 } 8017 8018 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8019 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8020 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8021 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8022 8023 // Check of we need to combine values from two sources within a byte. 8024 if (!(LHSUsedLanes & RHSUsedLanes) && 8025 // If we select high and lower word keep it for SDWA. 8026 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8027 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8028 // Kill zero bytes selected by other mask. Zero value is 0xc. 8029 LHSMask &= ~RHSUsedLanes; 8030 RHSMask &= ~LHSUsedLanes; 8031 // Add 4 to each active LHS lane 8032 LHSMask |= LHSUsedLanes & 0x04040404; 8033 // Combine masks 8034 uint32_t Sel = LHSMask | RHSMask; 8035 SDLoc DL(N); 8036 8037 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8038 LHS.getOperand(0), RHS.getOperand(0), 8039 DAG.getConstant(Sel, DL, MVT::i32)); 8040 } 8041 } 8042 } 8043 8044 if (VT != MVT::i64) 8045 return SDValue(); 8046 8047 // TODO: This could be a generic combine with a predicate for extracting the 8048 // high half of an integer being free. 8049 8050 // (or i64:x, (zero_extend i32:y)) -> 8051 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8052 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8053 RHS.getOpcode() != ISD::ZERO_EXTEND) 8054 std::swap(LHS, RHS); 8055 8056 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8057 SDValue ExtSrc = RHS.getOperand(0); 8058 EVT SrcVT = ExtSrc.getValueType(); 8059 if (SrcVT == MVT::i32) { 8060 SDLoc SL(N); 8061 SDValue LowLHS, HiBits; 8062 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 8063 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 8064 8065 DCI.AddToWorklist(LowOr.getNode()); 8066 DCI.AddToWorklist(HiBits.getNode()); 8067 8068 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 8069 LowOr, HiBits); 8070 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 8071 } 8072 } 8073 8074 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8075 if (CRHS) { 8076 if (SDValue Split 8077 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 8078 return Split; 8079 } 8080 8081 return SDValue(); 8082 } 8083 8084 SDValue SITargetLowering::performXorCombine(SDNode *N, 8085 DAGCombinerInfo &DCI) const { 8086 EVT VT = N->getValueType(0); 8087 if (VT != MVT::i64) 8088 return SDValue(); 8089 8090 SDValue LHS = N->getOperand(0); 8091 SDValue RHS = N->getOperand(1); 8092 8093 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8094 if (CRHS) { 8095 if (SDValue Split 8096 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 8097 return Split; 8098 } 8099 8100 return SDValue(); 8101 } 8102 8103 // Instructions that will be lowered with a final instruction that zeros the 8104 // high result bits. 8105 // XXX - probably only need to list legal operations. 8106 static bool fp16SrcZerosHighBits(unsigned Opc) { 8107 switch (Opc) { 8108 case ISD::FADD: 8109 case ISD::FSUB: 8110 case ISD::FMUL: 8111 case ISD::FDIV: 8112 case ISD::FREM: 8113 case ISD::FMA: 8114 case ISD::FMAD: 8115 case ISD::FCANONICALIZE: 8116 case ISD::FP_ROUND: 8117 case ISD::UINT_TO_FP: 8118 case ISD::SINT_TO_FP: 8119 case ISD::FABS: 8120 // Fabs is lowered to a bit operation, but it's an and which will clear the 8121 // high bits anyway. 8122 case ISD::FSQRT: 8123 case ISD::FSIN: 8124 case ISD::FCOS: 8125 case ISD::FPOWI: 8126 case ISD::FPOW: 8127 case ISD::FLOG: 8128 case ISD::FLOG2: 8129 case ISD::FLOG10: 8130 case ISD::FEXP: 8131 case ISD::FEXP2: 8132 case ISD::FCEIL: 8133 case ISD::FTRUNC: 8134 case ISD::FRINT: 8135 case ISD::FNEARBYINT: 8136 case ISD::FROUND: 8137 case ISD::FFLOOR: 8138 case ISD::FMINNUM: 8139 case ISD::FMAXNUM: 8140 case AMDGPUISD::FRACT: 8141 case AMDGPUISD::CLAMP: 8142 case AMDGPUISD::COS_HW: 8143 case AMDGPUISD::SIN_HW: 8144 case AMDGPUISD::FMIN3: 8145 case AMDGPUISD::FMAX3: 8146 case AMDGPUISD::FMED3: 8147 case AMDGPUISD::FMAD_FTZ: 8148 case AMDGPUISD::RCP: 8149 case AMDGPUISD::RSQ: 8150 case AMDGPUISD::RCP_IFLAG: 8151 case AMDGPUISD::LDEXP: 8152 return true; 8153 default: 8154 // fcopysign, select and others may be lowered to 32-bit bit operations 8155 // which don't zero the high bits. 8156 return false; 8157 } 8158 } 8159 8160 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 8161 DAGCombinerInfo &DCI) const { 8162 if (!Subtarget->has16BitInsts() || 8163 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8164 return SDValue(); 8165 8166 EVT VT = N->getValueType(0); 8167 if (VT != MVT::i32) 8168 return SDValue(); 8169 8170 SDValue Src = N->getOperand(0); 8171 if (Src.getValueType() != MVT::i16) 8172 return SDValue(); 8173 8174 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 8175 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 8176 if (Src.getOpcode() == ISD::BITCAST) { 8177 SDValue BCSrc = Src.getOperand(0); 8178 if (BCSrc.getValueType() == MVT::f16 && 8179 fp16SrcZerosHighBits(BCSrc.getOpcode())) 8180 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 8181 } 8182 8183 return SDValue(); 8184 } 8185 8186 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 8187 DAGCombinerInfo &DCI) 8188 const { 8189 SDValue Src = N->getOperand(0); 8190 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 8191 8192 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 8193 VTSign->getVT() == MVT::i8) || 8194 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 8195 VTSign->getVT() == MVT::i16)) && 8196 Src.hasOneUse()) { 8197 auto *M = cast<MemSDNode>(Src); 8198 SDValue Ops[] = { 8199 Src.getOperand(0), // Chain 8200 Src.getOperand(1), // rsrc 8201 Src.getOperand(2), // vindex 8202 Src.getOperand(3), // voffset 8203 Src.getOperand(4), // soffset 8204 Src.getOperand(5), // offset 8205 Src.getOperand(6), 8206 Src.getOperand(7) 8207 }; 8208 // replace with BUFFER_LOAD_BYTE/SHORT 8209 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 8210 Src.getOperand(0).getValueType()); 8211 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 8212 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 8213 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 8214 ResList, 8215 Ops, M->getMemoryVT(), 8216 M->getMemOperand()); 8217 return DCI.DAG.getMergeValues({BufferLoadSignExt, 8218 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 8219 } 8220 return SDValue(); 8221 } 8222 8223 SDValue SITargetLowering::performClassCombine(SDNode *N, 8224 DAGCombinerInfo &DCI) const { 8225 SelectionDAG &DAG = DCI.DAG; 8226 SDValue Mask = N->getOperand(1); 8227 8228 // fp_class x, 0 -> false 8229 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 8230 if (CMask->isNullValue()) 8231 return DAG.getConstant(0, SDLoc(N), MVT::i1); 8232 } 8233 8234 if (N->getOperand(0).isUndef()) 8235 return DAG.getUNDEF(MVT::i1); 8236 8237 return SDValue(); 8238 } 8239 8240 SDValue SITargetLowering::performRcpCombine(SDNode *N, 8241 DAGCombinerInfo &DCI) const { 8242 EVT VT = N->getValueType(0); 8243 SDValue N0 = N->getOperand(0); 8244 8245 if (N0.isUndef()) 8246 return N0; 8247 8248 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 8249 N0.getOpcode() == ISD::SINT_TO_FP)) { 8250 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 8251 N->getFlags()); 8252 } 8253 8254 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 8255 } 8256 8257 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 8258 unsigned MaxDepth) const { 8259 unsigned Opcode = Op.getOpcode(); 8260 if (Opcode == ISD::FCANONICALIZE) 8261 return true; 8262 8263 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8264 auto F = CFP->getValueAPF(); 8265 if (F.isNaN() && F.isSignaling()) 8266 return false; 8267 return !F.isDenormal() || denormalsEnabledForType(Op.getValueType()); 8268 } 8269 8270 // If source is a result of another standard FP operation it is already in 8271 // canonical form. 8272 if (MaxDepth == 0) 8273 return false; 8274 8275 switch (Opcode) { 8276 // These will flush denorms if required. 8277 case ISD::FADD: 8278 case ISD::FSUB: 8279 case ISD::FMUL: 8280 case ISD::FCEIL: 8281 case ISD::FFLOOR: 8282 case ISD::FMA: 8283 case ISD::FMAD: 8284 case ISD::FSQRT: 8285 case ISD::FDIV: 8286 case ISD::FREM: 8287 case ISD::FP_ROUND: 8288 case ISD::FP_EXTEND: 8289 case AMDGPUISD::FMUL_LEGACY: 8290 case AMDGPUISD::FMAD_FTZ: 8291 case AMDGPUISD::RCP: 8292 case AMDGPUISD::RSQ: 8293 case AMDGPUISD::RSQ_CLAMP: 8294 case AMDGPUISD::RCP_LEGACY: 8295 case AMDGPUISD::RSQ_LEGACY: 8296 case AMDGPUISD::RCP_IFLAG: 8297 case AMDGPUISD::TRIG_PREOP: 8298 case AMDGPUISD::DIV_SCALE: 8299 case AMDGPUISD::DIV_FMAS: 8300 case AMDGPUISD::DIV_FIXUP: 8301 case AMDGPUISD::FRACT: 8302 case AMDGPUISD::LDEXP: 8303 case AMDGPUISD::CVT_PKRTZ_F16_F32: 8304 case AMDGPUISD::CVT_F32_UBYTE0: 8305 case AMDGPUISD::CVT_F32_UBYTE1: 8306 case AMDGPUISD::CVT_F32_UBYTE2: 8307 case AMDGPUISD::CVT_F32_UBYTE3: 8308 return true; 8309 8310 // It can/will be lowered or combined as a bit operation. 8311 // Need to check their input recursively to handle. 8312 case ISD::FNEG: 8313 case ISD::FABS: 8314 case ISD::FCOPYSIGN: 8315 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8316 8317 case ISD::FSIN: 8318 case ISD::FCOS: 8319 case ISD::FSINCOS: 8320 return Op.getValueType().getScalarType() != MVT::f16; 8321 8322 case ISD::FMINNUM: 8323 case ISD::FMAXNUM: 8324 case ISD::FMINNUM_IEEE: 8325 case ISD::FMAXNUM_IEEE: 8326 case AMDGPUISD::CLAMP: 8327 case AMDGPUISD::FMED3: 8328 case AMDGPUISD::FMAX3: 8329 case AMDGPUISD::FMIN3: { 8330 // FIXME: Shouldn't treat the generic operations different based these. 8331 // However, we aren't really required to flush the result from 8332 // minnum/maxnum.. 8333 8334 // snans will be quieted, so we only need to worry about denormals. 8335 if (Subtarget->supportsMinMaxDenormModes() || 8336 denormalsEnabledForType(Op.getValueType())) 8337 return true; 8338 8339 // Flushing may be required. 8340 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 8341 // targets need to check their input recursively. 8342 8343 // FIXME: Does this apply with clamp? It's implemented with max. 8344 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 8345 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 8346 return false; 8347 } 8348 8349 return true; 8350 } 8351 case ISD::SELECT: { 8352 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 8353 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 8354 } 8355 case ISD::BUILD_VECTOR: { 8356 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 8357 SDValue SrcOp = Op.getOperand(i); 8358 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 8359 return false; 8360 } 8361 8362 return true; 8363 } 8364 case ISD::EXTRACT_VECTOR_ELT: 8365 case ISD::EXTRACT_SUBVECTOR: { 8366 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8367 } 8368 case ISD::INSERT_VECTOR_ELT: { 8369 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 8370 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 8371 } 8372 case ISD::UNDEF: 8373 // Could be anything. 8374 return false; 8375 8376 case ISD::BITCAST: { 8377 // Hack round the mess we make when legalizing extract_vector_elt 8378 SDValue Src = Op.getOperand(0); 8379 if (Src.getValueType() == MVT::i16 && 8380 Src.getOpcode() == ISD::TRUNCATE) { 8381 SDValue TruncSrc = Src.getOperand(0); 8382 if (TruncSrc.getValueType() == MVT::i32 && 8383 TruncSrc.getOpcode() == ISD::BITCAST && 8384 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 8385 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 8386 } 8387 } 8388 8389 return false; 8390 } 8391 case ISD::INTRINSIC_WO_CHAIN: { 8392 unsigned IntrinsicID 8393 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8394 // TODO: Handle more intrinsics 8395 switch (IntrinsicID) { 8396 case Intrinsic::amdgcn_cvt_pkrtz: 8397 case Intrinsic::amdgcn_cubeid: 8398 case Intrinsic::amdgcn_frexp_mant: 8399 case Intrinsic::amdgcn_fdot2: 8400 return true; 8401 default: 8402 break; 8403 } 8404 8405 LLVM_FALLTHROUGH; 8406 } 8407 default: 8408 return denormalsEnabledForType(Op.getValueType()) && 8409 DAG.isKnownNeverSNaN(Op); 8410 } 8411 8412 llvm_unreachable("invalid operation"); 8413 } 8414 8415 // Constant fold canonicalize. 8416 SDValue SITargetLowering::getCanonicalConstantFP( 8417 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 8418 // Flush denormals to 0 if not enabled. 8419 if (C.isDenormal() && !denormalsEnabledForType(VT)) 8420 return DAG.getConstantFP(0.0, SL, VT); 8421 8422 if (C.isNaN()) { 8423 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 8424 if (C.isSignaling()) { 8425 // Quiet a signaling NaN. 8426 // FIXME: Is this supposed to preserve payload bits? 8427 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8428 } 8429 8430 // Make sure it is the canonical NaN bitpattern. 8431 // 8432 // TODO: Can we use -1 as the canonical NaN value since it's an inline 8433 // immediate? 8434 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 8435 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8436 } 8437 8438 // Already canonical. 8439 return DAG.getConstantFP(C, SL, VT); 8440 } 8441 8442 static bool vectorEltWillFoldAway(SDValue Op) { 8443 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 8444 } 8445 8446 SDValue SITargetLowering::performFCanonicalizeCombine( 8447 SDNode *N, 8448 DAGCombinerInfo &DCI) const { 8449 SelectionDAG &DAG = DCI.DAG; 8450 SDValue N0 = N->getOperand(0); 8451 EVT VT = N->getValueType(0); 8452 8453 // fcanonicalize undef -> qnan 8454 if (N0.isUndef()) { 8455 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 8456 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 8457 } 8458 8459 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 8460 EVT VT = N->getValueType(0); 8461 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 8462 } 8463 8464 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 8465 // (fcanonicalize k) 8466 // 8467 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 8468 8469 // TODO: This could be better with wider vectors that will be split to v2f16, 8470 // and to consider uses since there aren't that many packed operations. 8471 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 8472 isTypeLegal(MVT::v2f16)) { 8473 SDLoc SL(N); 8474 SDValue NewElts[2]; 8475 SDValue Lo = N0.getOperand(0); 8476 SDValue Hi = N0.getOperand(1); 8477 EVT EltVT = Lo.getValueType(); 8478 8479 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 8480 for (unsigned I = 0; I != 2; ++I) { 8481 SDValue Op = N0.getOperand(I); 8482 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8483 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 8484 CFP->getValueAPF()); 8485 } else if (Op.isUndef()) { 8486 // Handled below based on what the other operand is. 8487 NewElts[I] = Op; 8488 } else { 8489 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 8490 } 8491 } 8492 8493 // If one half is undef, and one is constant, perfer a splat vector rather 8494 // than the normal qNaN. If it's a register, prefer 0.0 since that's 8495 // cheaper to use and may be free with a packed operation. 8496 if (NewElts[0].isUndef()) { 8497 if (isa<ConstantFPSDNode>(NewElts[1])) 8498 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 8499 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 8500 } 8501 8502 if (NewElts[1].isUndef()) { 8503 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 8504 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 8505 } 8506 8507 return DAG.getBuildVector(VT, SL, NewElts); 8508 } 8509 } 8510 8511 unsigned SrcOpc = N0.getOpcode(); 8512 8513 // If it's free to do so, push canonicalizes further up the source, which may 8514 // find a canonical source. 8515 // 8516 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 8517 // sNaNs. 8518 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 8519 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 8520 if (CRHS && N0.hasOneUse()) { 8521 SDLoc SL(N); 8522 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 8523 N0.getOperand(0)); 8524 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 8525 DCI.AddToWorklist(Canon0.getNode()); 8526 8527 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 8528 } 8529 } 8530 8531 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 8532 } 8533 8534 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 8535 switch (Opc) { 8536 case ISD::FMAXNUM: 8537 case ISD::FMAXNUM_IEEE: 8538 return AMDGPUISD::FMAX3; 8539 case ISD::SMAX: 8540 return AMDGPUISD::SMAX3; 8541 case ISD::UMAX: 8542 return AMDGPUISD::UMAX3; 8543 case ISD::FMINNUM: 8544 case ISD::FMINNUM_IEEE: 8545 return AMDGPUISD::FMIN3; 8546 case ISD::SMIN: 8547 return AMDGPUISD::SMIN3; 8548 case ISD::UMIN: 8549 return AMDGPUISD::UMIN3; 8550 default: 8551 llvm_unreachable("Not a min/max opcode"); 8552 } 8553 } 8554 8555 SDValue SITargetLowering::performIntMed3ImmCombine( 8556 SelectionDAG &DAG, const SDLoc &SL, 8557 SDValue Op0, SDValue Op1, bool Signed) const { 8558 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 8559 if (!K1) 8560 return SDValue(); 8561 8562 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 8563 if (!K0) 8564 return SDValue(); 8565 8566 if (Signed) { 8567 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 8568 return SDValue(); 8569 } else { 8570 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 8571 return SDValue(); 8572 } 8573 8574 EVT VT = K0->getValueType(0); 8575 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 8576 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 8577 return DAG.getNode(Med3Opc, SL, VT, 8578 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 8579 } 8580 8581 // If there isn't a 16-bit med3 operation, convert to 32-bit. 8582 MVT NVT = MVT::i32; 8583 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8584 8585 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 8586 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 8587 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 8588 8589 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 8590 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 8591 } 8592 8593 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 8594 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 8595 return C; 8596 8597 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 8598 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 8599 return C; 8600 } 8601 8602 return nullptr; 8603 } 8604 8605 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 8606 const SDLoc &SL, 8607 SDValue Op0, 8608 SDValue Op1) const { 8609 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 8610 if (!K1) 8611 return SDValue(); 8612 8613 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 8614 if (!K0) 8615 return SDValue(); 8616 8617 // Ordered >= (although NaN inputs should have folded away by now). 8618 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 8619 if (Cmp == APFloat::cmpGreaterThan) 8620 return SDValue(); 8621 8622 const MachineFunction &MF = DAG.getMachineFunction(); 8623 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 8624 8625 // TODO: Check IEEE bit enabled? 8626 EVT VT = Op0.getValueType(); 8627 if (Info->getMode().DX10Clamp) { 8628 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 8629 // hardware fmed3 behavior converting to a min. 8630 // FIXME: Should this be allowing -0.0? 8631 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 8632 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 8633 } 8634 8635 // med3 for f16 is only available on gfx9+, and not available for v2f16. 8636 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 8637 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 8638 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 8639 // then give the other result, which is different from med3 with a NaN 8640 // input. 8641 SDValue Var = Op0.getOperand(0); 8642 if (!DAG.isKnownNeverSNaN(Var)) 8643 return SDValue(); 8644 8645 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8646 8647 if ((!K0->hasOneUse() || 8648 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 8649 (!K1->hasOneUse() || 8650 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 8651 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 8652 Var, SDValue(K0, 0), SDValue(K1, 0)); 8653 } 8654 } 8655 8656 return SDValue(); 8657 } 8658 8659 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 8660 DAGCombinerInfo &DCI) const { 8661 SelectionDAG &DAG = DCI.DAG; 8662 8663 EVT VT = N->getValueType(0); 8664 unsigned Opc = N->getOpcode(); 8665 SDValue Op0 = N->getOperand(0); 8666 SDValue Op1 = N->getOperand(1); 8667 8668 // Only do this if the inner op has one use since this will just increases 8669 // register pressure for no benefit. 8670 8671 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 8672 !VT.isVector() && 8673 (VT == MVT::i32 || VT == MVT::f32 || 8674 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 8675 // max(max(a, b), c) -> max3(a, b, c) 8676 // min(min(a, b), c) -> min3(a, b, c) 8677 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 8678 SDLoc DL(N); 8679 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 8680 DL, 8681 N->getValueType(0), 8682 Op0.getOperand(0), 8683 Op0.getOperand(1), 8684 Op1); 8685 } 8686 8687 // Try commuted. 8688 // max(a, max(b, c)) -> max3(a, b, c) 8689 // min(a, min(b, c)) -> min3(a, b, c) 8690 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 8691 SDLoc DL(N); 8692 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 8693 DL, 8694 N->getValueType(0), 8695 Op0, 8696 Op1.getOperand(0), 8697 Op1.getOperand(1)); 8698 } 8699 } 8700 8701 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 8702 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 8703 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 8704 return Med3; 8705 } 8706 8707 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 8708 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 8709 return Med3; 8710 } 8711 8712 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 8713 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 8714 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 8715 (Opc == AMDGPUISD::FMIN_LEGACY && 8716 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 8717 (VT == MVT::f32 || VT == MVT::f64 || 8718 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 8719 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 8720 Op0.hasOneUse()) { 8721 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 8722 return Res; 8723 } 8724 8725 return SDValue(); 8726 } 8727 8728 static bool isClampZeroToOne(SDValue A, SDValue B) { 8729 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 8730 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 8731 // FIXME: Should this be allowing -0.0? 8732 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 8733 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 8734 } 8735 } 8736 8737 return false; 8738 } 8739 8740 // FIXME: Should only worry about snans for version with chain. 8741 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 8742 DAGCombinerInfo &DCI) const { 8743 EVT VT = N->getValueType(0); 8744 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 8745 // NaNs. With a NaN input, the order of the operands may change the result. 8746 8747 SelectionDAG &DAG = DCI.DAG; 8748 SDLoc SL(N); 8749 8750 SDValue Src0 = N->getOperand(0); 8751 SDValue Src1 = N->getOperand(1); 8752 SDValue Src2 = N->getOperand(2); 8753 8754 if (isClampZeroToOne(Src0, Src1)) { 8755 // const_a, const_b, x -> clamp is safe in all cases including signaling 8756 // nans. 8757 // FIXME: Should this be allowing -0.0? 8758 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 8759 } 8760 8761 const MachineFunction &MF = DAG.getMachineFunction(); 8762 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 8763 8764 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 8765 // handling no dx10-clamp? 8766 if (Info->getMode().DX10Clamp) { 8767 // If NaNs is clamped to 0, we are free to reorder the inputs. 8768 8769 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 8770 std::swap(Src0, Src1); 8771 8772 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 8773 std::swap(Src1, Src2); 8774 8775 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 8776 std::swap(Src0, Src1); 8777 8778 if (isClampZeroToOne(Src1, Src2)) 8779 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 8780 } 8781 8782 return SDValue(); 8783 } 8784 8785 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 8786 DAGCombinerInfo &DCI) const { 8787 SDValue Src0 = N->getOperand(0); 8788 SDValue Src1 = N->getOperand(1); 8789 if (Src0.isUndef() && Src1.isUndef()) 8790 return DCI.DAG.getUNDEF(N->getValueType(0)); 8791 return SDValue(); 8792 } 8793 8794 SDValue SITargetLowering::performExtractVectorEltCombine( 8795 SDNode *N, DAGCombinerInfo &DCI) const { 8796 SDValue Vec = N->getOperand(0); 8797 SelectionDAG &DAG = DCI.DAG; 8798 8799 EVT VecVT = Vec.getValueType(); 8800 EVT EltVT = VecVT.getVectorElementType(); 8801 8802 if ((Vec.getOpcode() == ISD::FNEG || 8803 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 8804 SDLoc SL(N); 8805 EVT EltVT = N->getValueType(0); 8806 SDValue Idx = N->getOperand(1); 8807 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 8808 Vec.getOperand(0), Idx); 8809 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 8810 } 8811 8812 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 8813 // => 8814 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 8815 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 8816 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 8817 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 8818 SDLoc SL(N); 8819 EVT EltVT = N->getValueType(0); 8820 SDValue Idx = N->getOperand(1); 8821 unsigned Opc = Vec.getOpcode(); 8822 8823 switch(Opc) { 8824 default: 8825 break; 8826 // TODO: Support other binary operations. 8827 case ISD::FADD: 8828 case ISD::FSUB: 8829 case ISD::FMUL: 8830 case ISD::ADD: 8831 case ISD::UMIN: 8832 case ISD::UMAX: 8833 case ISD::SMIN: 8834 case ISD::SMAX: 8835 case ISD::FMAXNUM: 8836 case ISD::FMINNUM: 8837 case ISD::FMAXNUM_IEEE: 8838 case ISD::FMINNUM_IEEE: { 8839 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 8840 Vec.getOperand(0), Idx); 8841 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 8842 Vec.getOperand(1), Idx); 8843 8844 DCI.AddToWorklist(Elt0.getNode()); 8845 DCI.AddToWorklist(Elt1.getNode()); 8846 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 8847 } 8848 } 8849 } 8850 8851 unsigned VecSize = VecVT.getSizeInBits(); 8852 unsigned EltSize = EltVT.getSizeInBits(); 8853 8854 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 8855 // This elminates non-constant index and subsequent movrel or scratch access. 8856 // Sub-dword vectors of size 2 dword or less have better implementation. 8857 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 8858 // instructions. 8859 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) && 8860 !isa<ConstantSDNode>(N->getOperand(1))) { 8861 SDLoc SL(N); 8862 SDValue Idx = N->getOperand(1); 8863 EVT IdxVT = Idx.getValueType(); 8864 SDValue V; 8865 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 8866 SDValue IC = DAG.getConstant(I, SL, IdxVT); 8867 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 8868 if (I == 0) 8869 V = Elt; 8870 else 8871 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 8872 } 8873 return V; 8874 } 8875 8876 if (!DCI.isBeforeLegalize()) 8877 return SDValue(); 8878 8879 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 8880 // elements. This exposes more load reduction opportunities by replacing 8881 // multiple small extract_vector_elements with a single 32-bit extract. 8882 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8883 if (isa<MemSDNode>(Vec) && 8884 EltSize <= 16 && 8885 EltVT.isByteSized() && 8886 VecSize > 32 && 8887 VecSize % 32 == 0 && 8888 Idx) { 8889 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 8890 8891 unsigned BitIndex = Idx->getZExtValue() * EltSize; 8892 unsigned EltIdx = BitIndex / 32; 8893 unsigned LeftoverBitIdx = BitIndex % 32; 8894 SDLoc SL(N); 8895 8896 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 8897 DCI.AddToWorklist(Cast.getNode()); 8898 8899 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 8900 DAG.getConstant(EltIdx, SL, MVT::i32)); 8901 DCI.AddToWorklist(Elt.getNode()); 8902 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 8903 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 8904 DCI.AddToWorklist(Srl.getNode()); 8905 8906 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 8907 DCI.AddToWorklist(Trunc.getNode()); 8908 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 8909 } 8910 8911 return SDValue(); 8912 } 8913 8914 SDValue 8915 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 8916 DAGCombinerInfo &DCI) const { 8917 SDValue Vec = N->getOperand(0); 8918 SDValue Idx = N->getOperand(2); 8919 EVT VecVT = Vec.getValueType(); 8920 EVT EltVT = VecVT.getVectorElementType(); 8921 unsigned VecSize = VecVT.getSizeInBits(); 8922 unsigned EltSize = EltVT.getSizeInBits(); 8923 8924 // INSERT_VECTOR_ELT (<n x e>, var-idx) 8925 // => BUILD_VECTOR n x select (e, const-idx) 8926 // This elminates non-constant index and subsequent movrel or scratch access. 8927 // Sub-dword vectors of size 2 dword or less have better implementation. 8928 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 8929 // instructions. 8930 if (isa<ConstantSDNode>(Idx) || 8931 VecSize > 256 || (VecSize <= 64 && EltSize < 32)) 8932 return SDValue(); 8933 8934 SelectionDAG &DAG = DCI.DAG; 8935 SDLoc SL(N); 8936 SDValue Ins = N->getOperand(1); 8937 EVT IdxVT = Idx.getValueType(); 8938 8939 SmallVector<SDValue, 16> Ops; 8940 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 8941 SDValue IC = DAG.getConstant(I, SL, IdxVT); 8942 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 8943 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 8944 Ops.push_back(V); 8945 } 8946 8947 return DAG.getBuildVector(VecVT, SL, Ops); 8948 } 8949 8950 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 8951 const SDNode *N0, 8952 const SDNode *N1) const { 8953 EVT VT = N0->getValueType(0); 8954 8955 // Only do this if we are not trying to support denormals. v_mad_f32 does not 8956 // support denormals ever. 8957 if (((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) || 8958 (VT == MVT::f16 && !Subtarget->hasFP16Denormals() && 8959 getSubtarget()->hasMadF16())) && 8960 isOperationLegal(ISD::FMAD, VT)) 8961 return ISD::FMAD; 8962 8963 const TargetOptions &Options = DAG.getTarget().Options; 8964 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 8965 (N0->getFlags().hasAllowContract() && 8966 N1->getFlags().hasAllowContract())) && 8967 isFMAFasterThanFMulAndFAdd(VT)) { 8968 return ISD::FMA; 8969 } 8970 8971 return 0; 8972 } 8973 8974 // For a reassociatable opcode perform: 8975 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 8976 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 8977 SelectionDAG &DAG) const { 8978 EVT VT = N->getValueType(0); 8979 if (VT != MVT::i32 && VT != MVT::i64) 8980 return SDValue(); 8981 8982 unsigned Opc = N->getOpcode(); 8983 SDValue Op0 = N->getOperand(0); 8984 SDValue Op1 = N->getOperand(1); 8985 8986 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 8987 return SDValue(); 8988 8989 if (Op0->isDivergent()) 8990 std::swap(Op0, Op1); 8991 8992 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 8993 return SDValue(); 8994 8995 SDValue Op2 = Op1.getOperand(1); 8996 Op1 = Op1.getOperand(0); 8997 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 8998 return SDValue(); 8999 9000 if (Op1->isDivergent()) 9001 std::swap(Op1, Op2); 9002 9003 // If either operand is constant this will conflict with 9004 // DAGCombiner::ReassociateOps(). 9005 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9006 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9007 return SDValue(); 9008 9009 SDLoc SL(N); 9010 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9011 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9012 } 9013 9014 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9015 EVT VT, 9016 SDValue N0, SDValue N1, SDValue N2, 9017 bool Signed) { 9018 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9019 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9020 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 9021 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 9022 } 9023 9024 SDValue SITargetLowering::performAddCombine(SDNode *N, 9025 DAGCombinerInfo &DCI) const { 9026 SelectionDAG &DAG = DCI.DAG; 9027 EVT VT = N->getValueType(0); 9028 SDLoc SL(N); 9029 SDValue LHS = N->getOperand(0); 9030 SDValue RHS = N->getOperand(1); 9031 9032 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 9033 && Subtarget->hasMad64_32() && 9034 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 9035 VT.getScalarSizeInBits() <= 64) { 9036 if (LHS.getOpcode() != ISD::MUL) 9037 std::swap(LHS, RHS); 9038 9039 SDValue MulLHS = LHS.getOperand(0); 9040 SDValue MulRHS = LHS.getOperand(1); 9041 SDValue AddRHS = RHS; 9042 9043 // TODO: Maybe restrict if SGPR inputs. 9044 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 9045 numBitsUnsigned(MulRHS, DAG) <= 32) { 9046 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 9047 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 9048 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 9049 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 9050 } 9051 9052 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 9053 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 9054 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 9055 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 9056 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 9057 } 9058 9059 return SDValue(); 9060 } 9061 9062 if (SDValue V = reassociateScalarOps(N, DAG)) { 9063 return V; 9064 } 9065 9066 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 9067 return SDValue(); 9068 9069 // add x, zext (setcc) => addcarry x, 0, setcc 9070 // add x, sext (setcc) => subcarry x, 0, setcc 9071 unsigned Opc = LHS.getOpcode(); 9072 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9073 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 9074 std::swap(RHS, LHS); 9075 9076 Opc = RHS.getOpcode(); 9077 switch (Opc) { 9078 default: break; 9079 case ISD::ZERO_EXTEND: 9080 case ISD::SIGN_EXTEND: 9081 case ISD::ANY_EXTEND: { 9082 auto Cond = RHS.getOperand(0); 9083 if (!isBoolSGPR(Cond)) 9084 break; 9085 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9086 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9087 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9088 return DAG.getNode(Opc, SL, VTList, Args); 9089 } 9090 case ISD::ADDCARRY: { 9091 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 9092 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9093 if (!C || C->getZExtValue() != 0) break; 9094 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 9095 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 9096 } 9097 } 9098 return SDValue(); 9099 } 9100 9101 SDValue SITargetLowering::performSubCombine(SDNode *N, 9102 DAGCombinerInfo &DCI) const { 9103 SelectionDAG &DAG = DCI.DAG; 9104 EVT VT = N->getValueType(0); 9105 9106 if (VT != MVT::i32) 9107 return SDValue(); 9108 9109 SDLoc SL(N); 9110 SDValue LHS = N->getOperand(0); 9111 SDValue RHS = N->getOperand(1); 9112 9113 if (LHS.getOpcode() == ISD::SUBCARRY) { 9114 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 9115 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9116 if (!C || !C->isNullValue()) 9117 return SDValue(); 9118 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 9119 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 9120 } 9121 return SDValue(); 9122 } 9123 9124 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 9125 DAGCombinerInfo &DCI) const { 9126 9127 if (N->getValueType(0) != MVT::i32) 9128 return SDValue(); 9129 9130 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9131 if (!C || C->getZExtValue() != 0) 9132 return SDValue(); 9133 9134 SelectionDAG &DAG = DCI.DAG; 9135 SDValue LHS = N->getOperand(0); 9136 9137 // addcarry (add x, y), 0, cc => addcarry x, y, cc 9138 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 9139 unsigned LHSOpc = LHS.getOpcode(); 9140 unsigned Opc = N->getOpcode(); 9141 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 9142 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 9143 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 9144 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 9145 } 9146 return SDValue(); 9147 } 9148 9149 SDValue SITargetLowering::performFAddCombine(SDNode *N, 9150 DAGCombinerInfo &DCI) const { 9151 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9152 return SDValue(); 9153 9154 SelectionDAG &DAG = DCI.DAG; 9155 EVT VT = N->getValueType(0); 9156 9157 SDLoc SL(N); 9158 SDValue LHS = N->getOperand(0); 9159 SDValue RHS = N->getOperand(1); 9160 9161 // These should really be instruction patterns, but writing patterns with 9162 // source modiifiers is a pain. 9163 9164 // fadd (fadd (a, a), b) -> mad 2.0, a, b 9165 if (LHS.getOpcode() == ISD::FADD) { 9166 SDValue A = LHS.getOperand(0); 9167 if (A == LHS.getOperand(1)) { 9168 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9169 if (FusedOp != 0) { 9170 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9171 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 9172 } 9173 } 9174 } 9175 9176 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 9177 if (RHS.getOpcode() == ISD::FADD) { 9178 SDValue A = RHS.getOperand(0); 9179 if (A == RHS.getOperand(1)) { 9180 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9181 if (FusedOp != 0) { 9182 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9183 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 9184 } 9185 } 9186 } 9187 9188 return SDValue(); 9189 } 9190 9191 SDValue SITargetLowering::performFSubCombine(SDNode *N, 9192 DAGCombinerInfo &DCI) const { 9193 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9194 return SDValue(); 9195 9196 SelectionDAG &DAG = DCI.DAG; 9197 SDLoc SL(N); 9198 EVT VT = N->getValueType(0); 9199 assert(!VT.isVector()); 9200 9201 // Try to get the fneg to fold into the source modifier. This undoes generic 9202 // DAG combines and folds them into the mad. 9203 // 9204 // Only do this if we are not trying to support denormals. v_mad_f32 does 9205 // not support denormals ever. 9206 SDValue LHS = N->getOperand(0); 9207 SDValue RHS = N->getOperand(1); 9208 if (LHS.getOpcode() == ISD::FADD) { 9209 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 9210 SDValue A = LHS.getOperand(0); 9211 if (A == LHS.getOperand(1)) { 9212 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9213 if (FusedOp != 0){ 9214 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9215 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 9216 9217 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 9218 } 9219 } 9220 } 9221 9222 if (RHS.getOpcode() == ISD::FADD) { 9223 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 9224 9225 SDValue A = RHS.getOperand(0); 9226 if (A == RHS.getOperand(1)) { 9227 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9228 if (FusedOp != 0){ 9229 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 9230 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 9231 } 9232 } 9233 } 9234 9235 return SDValue(); 9236 } 9237 9238 SDValue SITargetLowering::performFMACombine(SDNode *N, 9239 DAGCombinerInfo &DCI) const { 9240 SelectionDAG &DAG = DCI.DAG; 9241 EVT VT = N->getValueType(0); 9242 SDLoc SL(N); 9243 9244 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 9245 return SDValue(); 9246 9247 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 9248 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 9249 SDValue Op1 = N->getOperand(0); 9250 SDValue Op2 = N->getOperand(1); 9251 SDValue FMA = N->getOperand(2); 9252 9253 if (FMA.getOpcode() != ISD::FMA || 9254 Op1.getOpcode() != ISD::FP_EXTEND || 9255 Op2.getOpcode() != ISD::FP_EXTEND) 9256 return SDValue(); 9257 9258 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 9259 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 9260 // is sufficient to allow generaing fdot2. 9261 const TargetOptions &Options = DAG.getTarget().Options; 9262 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9263 (N->getFlags().hasAllowContract() && 9264 FMA->getFlags().hasAllowContract())) { 9265 Op1 = Op1.getOperand(0); 9266 Op2 = Op2.getOperand(0); 9267 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9268 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9269 return SDValue(); 9270 9271 SDValue Vec1 = Op1.getOperand(0); 9272 SDValue Idx1 = Op1.getOperand(1); 9273 SDValue Vec2 = Op2.getOperand(0); 9274 9275 SDValue FMAOp1 = FMA.getOperand(0); 9276 SDValue FMAOp2 = FMA.getOperand(1); 9277 SDValue FMAAcc = FMA.getOperand(2); 9278 9279 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 9280 FMAOp2.getOpcode() != ISD::FP_EXTEND) 9281 return SDValue(); 9282 9283 FMAOp1 = FMAOp1.getOperand(0); 9284 FMAOp2 = FMAOp2.getOperand(0); 9285 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9286 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9287 return SDValue(); 9288 9289 SDValue Vec3 = FMAOp1.getOperand(0); 9290 SDValue Vec4 = FMAOp2.getOperand(0); 9291 SDValue Idx2 = FMAOp1.getOperand(1); 9292 9293 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 9294 // Idx1 and Idx2 cannot be the same. 9295 Idx1 == Idx2) 9296 return SDValue(); 9297 9298 if (Vec1 == Vec2 || Vec3 == Vec4) 9299 return SDValue(); 9300 9301 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 9302 return SDValue(); 9303 9304 if ((Vec1 == Vec3 && Vec2 == Vec4) || 9305 (Vec1 == Vec4 && Vec2 == Vec3)) { 9306 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 9307 DAG.getTargetConstant(0, SL, MVT::i1)); 9308 } 9309 } 9310 return SDValue(); 9311 } 9312 9313 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 9314 DAGCombinerInfo &DCI) const { 9315 SelectionDAG &DAG = DCI.DAG; 9316 SDLoc SL(N); 9317 9318 SDValue LHS = N->getOperand(0); 9319 SDValue RHS = N->getOperand(1); 9320 EVT VT = LHS.getValueType(); 9321 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 9322 9323 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 9324 if (!CRHS) { 9325 CRHS = dyn_cast<ConstantSDNode>(LHS); 9326 if (CRHS) { 9327 std::swap(LHS, RHS); 9328 CC = getSetCCSwappedOperands(CC); 9329 } 9330 } 9331 9332 if (CRHS) { 9333 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 9334 isBoolSGPR(LHS.getOperand(0))) { 9335 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 9336 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 9337 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 9338 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 9339 if ((CRHS->isAllOnesValue() && 9340 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 9341 (CRHS->isNullValue() && 9342 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 9343 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9344 DAG.getConstant(-1, SL, MVT::i1)); 9345 if ((CRHS->isAllOnesValue() && 9346 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 9347 (CRHS->isNullValue() && 9348 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 9349 return LHS.getOperand(0); 9350 } 9351 9352 uint64_t CRHSVal = CRHS->getZExtValue(); 9353 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 9354 LHS.getOpcode() == ISD::SELECT && 9355 isa<ConstantSDNode>(LHS.getOperand(1)) && 9356 isa<ConstantSDNode>(LHS.getOperand(2)) && 9357 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 9358 isBoolSGPR(LHS.getOperand(0))) { 9359 // Given CT != FT: 9360 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 9361 // setcc (select cc, CT, CF), CF, ne => cc 9362 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 9363 // setcc (select cc, CT, CF), CT, eq => cc 9364 uint64_t CT = LHS.getConstantOperandVal(1); 9365 uint64_t CF = LHS.getConstantOperandVal(2); 9366 9367 if ((CF == CRHSVal && CC == ISD::SETEQ) || 9368 (CT == CRHSVal && CC == ISD::SETNE)) 9369 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9370 DAG.getConstant(-1, SL, MVT::i1)); 9371 if ((CF == CRHSVal && CC == ISD::SETNE) || 9372 (CT == CRHSVal && CC == ISD::SETEQ)) 9373 return LHS.getOperand(0); 9374 } 9375 } 9376 9377 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 9378 VT != MVT::f16)) 9379 return SDValue(); 9380 9381 // Match isinf/isfinite pattern 9382 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 9383 // (fcmp one (fabs x), inf) -> (fp_class x, 9384 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 9385 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 9386 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 9387 if (!CRHS) 9388 return SDValue(); 9389 9390 const APFloat &APF = CRHS->getValueAPF(); 9391 if (APF.isInfinity() && !APF.isNegative()) { 9392 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 9393 SIInstrFlags::N_INFINITY; 9394 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 9395 SIInstrFlags::P_ZERO | 9396 SIInstrFlags::N_NORMAL | 9397 SIInstrFlags::P_NORMAL | 9398 SIInstrFlags::N_SUBNORMAL | 9399 SIInstrFlags::P_SUBNORMAL; 9400 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 9401 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 9402 DAG.getConstant(Mask, SL, MVT::i32)); 9403 } 9404 } 9405 9406 return SDValue(); 9407 } 9408 9409 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 9410 DAGCombinerInfo &DCI) const { 9411 SelectionDAG &DAG = DCI.DAG; 9412 SDLoc SL(N); 9413 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 9414 9415 SDValue Src = N->getOperand(0); 9416 SDValue Srl = N->getOperand(0); 9417 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 9418 Srl = Srl.getOperand(0); 9419 9420 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 9421 if (Srl.getOpcode() == ISD::SRL) { 9422 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 9423 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 9424 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 9425 9426 if (const ConstantSDNode *C = 9427 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 9428 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 9429 EVT(MVT::i32)); 9430 9431 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 9432 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 9433 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 9434 MVT::f32, Srl); 9435 } 9436 } 9437 } 9438 9439 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 9440 9441 KnownBits Known; 9442 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 9443 !DCI.isBeforeLegalizeOps()); 9444 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9445 if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) { 9446 DCI.CommitTargetLoweringOpt(TLO); 9447 } 9448 9449 return SDValue(); 9450 } 9451 9452 SDValue SITargetLowering::performClampCombine(SDNode *N, 9453 DAGCombinerInfo &DCI) const { 9454 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 9455 if (!CSrc) 9456 return SDValue(); 9457 9458 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 9459 const APFloat &F = CSrc->getValueAPF(); 9460 APFloat Zero = APFloat::getZero(F.getSemantics()); 9461 APFloat::cmpResult Cmp0 = F.compare(Zero); 9462 if (Cmp0 == APFloat::cmpLessThan || 9463 (Cmp0 == APFloat::cmpUnordered && 9464 MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 9465 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 9466 } 9467 9468 APFloat One(F.getSemantics(), "1.0"); 9469 APFloat::cmpResult Cmp1 = F.compare(One); 9470 if (Cmp1 == APFloat::cmpGreaterThan) 9471 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 9472 9473 return SDValue(CSrc, 0); 9474 } 9475 9476 9477 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 9478 DAGCombinerInfo &DCI) const { 9479 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 9480 return SDValue(); 9481 switch (N->getOpcode()) { 9482 default: 9483 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9484 case ISD::ADD: 9485 return performAddCombine(N, DCI); 9486 case ISD::SUB: 9487 return performSubCombine(N, DCI); 9488 case ISD::ADDCARRY: 9489 case ISD::SUBCARRY: 9490 return performAddCarrySubCarryCombine(N, DCI); 9491 case ISD::FADD: 9492 return performFAddCombine(N, DCI); 9493 case ISD::FSUB: 9494 return performFSubCombine(N, DCI); 9495 case ISD::SETCC: 9496 return performSetCCCombine(N, DCI); 9497 case ISD::FMAXNUM: 9498 case ISD::FMINNUM: 9499 case ISD::FMAXNUM_IEEE: 9500 case ISD::FMINNUM_IEEE: 9501 case ISD::SMAX: 9502 case ISD::SMIN: 9503 case ISD::UMAX: 9504 case ISD::UMIN: 9505 case AMDGPUISD::FMIN_LEGACY: 9506 case AMDGPUISD::FMAX_LEGACY: 9507 return performMinMaxCombine(N, DCI); 9508 case ISD::FMA: 9509 return performFMACombine(N, DCI); 9510 case ISD::LOAD: { 9511 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 9512 return Widended; 9513 LLVM_FALLTHROUGH; 9514 } 9515 case ISD::STORE: 9516 case ISD::ATOMIC_LOAD: 9517 case ISD::ATOMIC_STORE: 9518 case ISD::ATOMIC_CMP_SWAP: 9519 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 9520 case ISD::ATOMIC_SWAP: 9521 case ISD::ATOMIC_LOAD_ADD: 9522 case ISD::ATOMIC_LOAD_SUB: 9523 case ISD::ATOMIC_LOAD_AND: 9524 case ISD::ATOMIC_LOAD_OR: 9525 case ISD::ATOMIC_LOAD_XOR: 9526 case ISD::ATOMIC_LOAD_NAND: 9527 case ISD::ATOMIC_LOAD_MIN: 9528 case ISD::ATOMIC_LOAD_MAX: 9529 case ISD::ATOMIC_LOAD_UMIN: 9530 case ISD::ATOMIC_LOAD_UMAX: 9531 case ISD::ATOMIC_LOAD_FADD: 9532 case AMDGPUISD::ATOMIC_INC: 9533 case AMDGPUISD::ATOMIC_DEC: 9534 case AMDGPUISD::ATOMIC_LOAD_FMIN: 9535 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 9536 if (DCI.isBeforeLegalize()) 9537 break; 9538 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 9539 case ISD::AND: 9540 return performAndCombine(N, DCI); 9541 case ISD::OR: 9542 return performOrCombine(N, DCI); 9543 case ISD::XOR: 9544 return performXorCombine(N, DCI); 9545 case ISD::ZERO_EXTEND: 9546 return performZeroExtendCombine(N, DCI); 9547 case ISD::SIGN_EXTEND_INREG: 9548 return performSignExtendInRegCombine(N , DCI); 9549 case AMDGPUISD::FP_CLASS: 9550 return performClassCombine(N, DCI); 9551 case ISD::FCANONICALIZE: 9552 return performFCanonicalizeCombine(N, DCI); 9553 case AMDGPUISD::RCP: 9554 return performRcpCombine(N, DCI); 9555 case AMDGPUISD::FRACT: 9556 case AMDGPUISD::RSQ: 9557 case AMDGPUISD::RCP_LEGACY: 9558 case AMDGPUISD::RSQ_LEGACY: 9559 case AMDGPUISD::RCP_IFLAG: 9560 case AMDGPUISD::RSQ_CLAMP: 9561 case AMDGPUISD::LDEXP: { 9562 SDValue Src = N->getOperand(0); 9563 if (Src.isUndef()) 9564 return Src; 9565 break; 9566 } 9567 case ISD::SINT_TO_FP: 9568 case ISD::UINT_TO_FP: 9569 return performUCharToFloatCombine(N, DCI); 9570 case AMDGPUISD::CVT_F32_UBYTE0: 9571 case AMDGPUISD::CVT_F32_UBYTE1: 9572 case AMDGPUISD::CVT_F32_UBYTE2: 9573 case AMDGPUISD::CVT_F32_UBYTE3: 9574 return performCvtF32UByteNCombine(N, DCI); 9575 case AMDGPUISD::FMED3: 9576 return performFMed3Combine(N, DCI); 9577 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9578 return performCvtPkRTZCombine(N, DCI); 9579 case AMDGPUISD::CLAMP: 9580 return performClampCombine(N, DCI); 9581 case ISD::SCALAR_TO_VECTOR: { 9582 SelectionDAG &DAG = DCI.DAG; 9583 EVT VT = N->getValueType(0); 9584 9585 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 9586 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 9587 SDLoc SL(N); 9588 SDValue Src = N->getOperand(0); 9589 EVT EltVT = Src.getValueType(); 9590 if (EltVT == MVT::f16) 9591 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 9592 9593 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 9594 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 9595 } 9596 9597 break; 9598 } 9599 case ISD::EXTRACT_VECTOR_ELT: 9600 return performExtractVectorEltCombine(N, DCI); 9601 case ISD::INSERT_VECTOR_ELT: 9602 return performInsertVectorEltCombine(N, DCI); 9603 } 9604 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9605 } 9606 9607 /// Helper function for adjustWritemask 9608 static unsigned SubIdx2Lane(unsigned Idx) { 9609 switch (Idx) { 9610 default: return 0; 9611 case AMDGPU::sub0: return 0; 9612 case AMDGPU::sub1: return 1; 9613 case AMDGPU::sub2: return 2; 9614 case AMDGPU::sub3: return 3; 9615 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 9616 } 9617 } 9618 9619 /// Adjust the writemask of MIMG instructions 9620 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 9621 SelectionDAG &DAG) const { 9622 unsigned Opcode = Node->getMachineOpcode(); 9623 9624 // Subtract 1 because the vdata output is not a MachineSDNode operand. 9625 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 9626 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 9627 return Node; // not implemented for D16 9628 9629 SDNode *Users[5] = { nullptr }; 9630 unsigned Lane = 0; 9631 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 9632 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 9633 unsigned NewDmask = 0; 9634 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 9635 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 9636 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 9637 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 9638 unsigned TFCLane = 0; 9639 bool HasChain = Node->getNumValues() > 1; 9640 9641 if (OldDmask == 0) { 9642 // These are folded out, but on the chance it happens don't assert. 9643 return Node; 9644 } 9645 9646 unsigned OldBitsSet = countPopulation(OldDmask); 9647 // Work out which is the TFE/LWE lane if that is enabled. 9648 if (UsesTFC) { 9649 TFCLane = OldBitsSet; 9650 } 9651 9652 // Try to figure out the used register components 9653 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 9654 I != E; ++I) { 9655 9656 // Don't look at users of the chain. 9657 if (I.getUse().getResNo() != 0) 9658 continue; 9659 9660 // Abort if we can't understand the usage 9661 if (!I->isMachineOpcode() || 9662 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 9663 return Node; 9664 9665 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 9666 // Note that subregs are packed, i.e. Lane==0 is the first bit set 9667 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 9668 // set, etc. 9669 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 9670 9671 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 9672 if (UsesTFC && Lane == TFCLane) { 9673 Users[Lane] = *I; 9674 } else { 9675 // Set which texture component corresponds to the lane. 9676 unsigned Comp; 9677 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 9678 Comp = countTrailingZeros(Dmask); 9679 Dmask &= ~(1 << Comp); 9680 } 9681 9682 // Abort if we have more than one user per component. 9683 if (Users[Lane]) 9684 return Node; 9685 9686 Users[Lane] = *I; 9687 NewDmask |= 1 << Comp; 9688 } 9689 } 9690 9691 // Don't allow 0 dmask, as hardware assumes one channel enabled. 9692 bool NoChannels = !NewDmask; 9693 if (NoChannels) { 9694 if (!UsesTFC) { 9695 // No uses of the result and not using TFC. Then do nothing. 9696 return Node; 9697 } 9698 // If the original dmask has one channel - then nothing to do 9699 if (OldBitsSet == 1) 9700 return Node; 9701 // Use an arbitrary dmask - required for the instruction to work 9702 NewDmask = 1; 9703 } 9704 // Abort if there's no change 9705 if (NewDmask == OldDmask) 9706 return Node; 9707 9708 unsigned BitsSet = countPopulation(NewDmask); 9709 9710 // Check for TFE or LWE - increase the number of channels by one to account 9711 // for the extra return value 9712 // This will need adjustment for D16 if this is also included in 9713 // adjustWriteMask (this function) but at present D16 are excluded. 9714 unsigned NewChannels = BitsSet + UsesTFC; 9715 9716 int NewOpcode = 9717 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 9718 assert(NewOpcode != -1 && 9719 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 9720 "failed to find equivalent MIMG op"); 9721 9722 // Adjust the writemask in the node 9723 SmallVector<SDValue, 12> Ops; 9724 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 9725 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 9726 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 9727 9728 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 9729 9730 MVT ResultVT = NewChannels == 1 ? 9731 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 9732 NewChannels == 5 ? 8 : NewChannels); 9733 SDVTList NewVTList = HasChain ? 9734 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 9735 9736 9737 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 9738 NewVTList, Ops); 9739 9740 if (HasChain) { 9741 // Update chain. 9742 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 9743 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 9744 } 9745 9746 if (NewChannels == 1) { 9747 assert(Node->hasNUsesOfValue(1, 0)); 9748 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 9749 SDLoc(Node), Users[Lane]->getValueType(0), 9750 SDValue(NewNode, 0)); 9751 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 9752 return nullptr; 9753 } 9754 9755 // Update the users of the node with the new indices 9756 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 9757 SDNode *User = Users[i]; 9758 if (!User) { 9759 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 9760 // Users[0] is still nullptr because channel 0 doesn't really have a use. 9761 if (i || !NoChannels) 9762 continue; 9763 } else { 9764 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 9765 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 9766 } 9767 9768 switch (Idx) { 9769 default: break; 9770 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 9771 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 9772 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 9773 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 9774 } 9775 } 9776 9777 DAG.RemoveDeadNode(Node); 9778 return nullptr; 9779 } 9780 9781 static bool isFrameIndexOp(SDValue Op) { 9782 if (Op.getOpcode() == ISD::AssertZext) 9783 Op = Op.getOperand(0); 9784 9785 return isa<FrameIndexSDNode>(Op); 9786 } 9787 9788 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 9789 /// with frame index operands. 9790 /// LLVM assumes that inputs are to these instructions are registers. 9791 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 9792 SelectionDAG &DAG) const { 9793 if (Node->getOpcode() == ISD::CopyToReg) { 9794 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 9795 SDValue SrcVal = Node->getOperand(2); 9796 9797 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 9798 // to try understanding copies to physical registers. 9799 if (SrcVal.getValueType() == MVT::i1 && 9800 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) { 9801 SDLoc SL(Node); 9802 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 9803 SDValue VReg = DAG.getRegister( 9804 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 9805 9806 SDNode *Glued = Node->getGluedNode(); 9807 SDValue ToVReg 9808 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 9809 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 9810 SDValue ToResultReg 9811 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 9812 VReg, ToVReg.getValue(1)); 9813 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 9814 DAG.RemoveDeadNode(Node); 9815 return ToResultReg.getNode(); 9816 } 9817 } 9818 9819 SmallVector<SDValue, 8> Ops; 9820 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 9821 if (!isFrameIndexOp(Node->getOperand(i))) { 9822 Ops.push_back(Node->getOperand(i)); 9823 continue; 9824 } 9825 9826 SDLoc DL(Node); 9827 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 9828 Node->getOperand(i).getValueType(), 9829 Node->getOperand(i)), 0)); 9830 } 9831 9832 return DAG.UpdateNodeOperands(Node, Ops); 9833 } 9834 9835 /// Fold the instructions after selecting them. 9836 /// Returns null if users were already updated. 9837 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 9838 SelectionDAG &DAG) const { 9839 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9840 unsigned Opcode = Node->getMachineOpcode(); 9841 9842 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 9843 !TII->isGather4(Opcode)) { 9844 return adjustWritemask(Node, DAG); 9845 } 9846 9847 if (Opcode == AMDGPU::INSERT_SUBREG || 9848 Opcode == AMDGPU::REG_SEQUENCE) { 9849 legalizeTargetIndependentNode(Node, DAG); 9850 return Node; 9851 } 9852 9853 switch (Opcode) { 9854 case AMDGPU::V_DIV_SCALE_F32: 9855 case AMDGPU::V_DIV_SCALE_F64: { 9856 // Satisfy the operand register constraint when one of the inputs is 9857 // undefined. Ordinarily each undef value will have its own implicit_def of 9858 // a vreg, so force these to use a single register. 9859 SDValue Src0 = Node->getOperand(0); 9860 SDValue Src1 = Node->getOperand(1); 9861 SDValue Src2 = Node->getOperand(2); 9862 9863 if ((Src0.isMachineOpcode() && 9864 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 9865 (Src0 == Src1 || Src0 == Src2)) 9866 break; 9867 9868 MVT VT = Src0.getValueType().getSimpleVT(); 9869 const TargetRegisterClass *RC = 9870 getRegClassFor(VT, Src0.getNode()->isDivergent()); 9871 9872 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 9873 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 9874 9875 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 9876 UndefReg, Src0, SDValue()); 9877 9878 // src0 must be the same register as src1 or src2, even if the value is 9879 // undefined, so make sure we don't violate this constraint. 9880 if (Src0.isMachineOpcode() && 9881 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 9882 if (Src1.isMachineOpcode() && 9883 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 9884 Src0 = Src1; 9885 else if (Src2.isMachineOpcode() && 9886 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 9887 Src0 = Src2; 9888 else { 9889 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 9890 Src0 = UndefReg; 9891 Src1 = UndefReg; 9892 } 9893 } else 9894 break; 9895 9896 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 9897 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 9898 Ops.push_back(Node->getOperand(I)); 9899 9900 Ops.push_back(ImpDef.getValue(1)); 9901 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 9902 } 9903 case AMDGPU::V_PERMLANE16_B32: 9904 case AMDGPU::V_PERMLANEX16_B32: { 9905 ConstantSDNode *FI = cast<ConstantSDNode>(Node->getOperand(0)); 9906 ConstantSDNode *BC = cast<ConstantSDNode>(Node->getOperand(2)); 9907 if (!FI->getZExtValue() && !BC->getZExtValue()) 9908 break; 9909 SDValue VDstIn = Node->getOperand(6); 9910 if (VDstIn.isMachineOpcode() 9911 && VDstIn.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) 9912 break; 9913 MachineSDNode *ImpDef = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, 9914 SDLoc(Node), MVT::i32); 9915 SmallVector<SDValue, 8> Ops = { SDValue(FI, 0), Node->getOperand(1), 9916 SDValue(BC, 0), Node->getOperand(3), 9917 Node->getOperand(4), Node->getOperand(5), 9918 SDValue(ImpDef, 0), Node->getOperand(7) }; 9919 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 9920 } 9921 default: 9922 break; 9923 } 9924 9925 return Node; 9926 } 9927 9928 /// Assign the register class depending on the number of 9929 /// bits set in the writemask 9930 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9931 SDNode *Node) const { 9932 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9933 9934 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 9935 9936 if (TII->isVOP3(MI.getOpcode())) { 9937 // Make sure constant bus requirements are respected. 9938 TII->legalizeOperandsVOP3(MRI, MI); 9939 return; 9940 } 9941 9942 // Replace unused atomics with the no return version. 9943 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 9944 if (NoRetAtomicOp != -1) { 9945 if (!Node->hasAnyUseOfValue(0)) { 9946 MI.setDesc(TII->get(NoRetAtomicOp)); 9947 MI.RemoveOperand(0); 9948 return; 9949 } 9950 9951 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 9952 // instruction, because the return type of these instructions is a vec2 of 9953 // the memory type, so it can be tied to the input operand. 9954 // This means these instructions always have a use, so we need to add a 9955 // special case to check if the atomic has only one extract_subreg use, 9956 // which itself has no uses. 9957 if ((Node->hasNUsesOfValue(1, 0) && 9958 Node->use_begin()->isMachineOpcode() && 9959 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 9960 !Node->use_begin()->hasAnyUseOfValue(0))) { 9961 unsigned Def = MI.getOperand(0).getReg(); 9962 9963 // Change this into a noret atomic. 9964 MI.setDesc(TII->get(NoRetAtomicOp)); 9965 MI.RemoveOperand(0); 9966 9967 // If we only remove the def operand from the atomic instruction, the 9968 // extract_subreg will be left with a use of a vreg without a def. 9969 // So we need to insert an implicit_def to avoid machine verifier 9970 // errors. 9971 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 9972 TII->get(AMDGPU::IMPLICIT_DEF), Def); 9973 } 9974 return; 9975 } 9976 } 9977 9978 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 9979 uint64_t Val) { 9980 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 9981 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 9982 } 9983 9984 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 9985 const SDLoc &DL, 9986 SDValue Ptr) const { 9987 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9988 9989 // Build the half of the subregister with the constants before building the 9990 // full 128-bit register. If we are building multiple resource descriptors, 9991 // this will allow CSEing of the 2-component register. 9992 const SDValue Ops0[] = { 9993 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 9994 buildSMovImm32(DAG, DL, 0), 9995 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 9996 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 9997 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 9998 }; 9999 10000 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 10001 MVT::v2i32, Ops0), 0); 10002 10003 // Combine the constants and the pointer. 10004 const SDValue Ops1[] = { 10005 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 10006 Ptr, 10007 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 10008 SubRegHi, 10009 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 10010 }; 10011 10012 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 10013 } 10014 10015 /// Return a resource descriptor with the 'Add TID' bit enabled 10016 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 10017 /// of the resource descriptor) to create an offset, which is added to 10018 /// the resource pointer. 10019 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 10020 SDValue Ptr, uint32_t RsrcDword1, 10021 uint64_t RsrcDword2And3) const { 10022 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 10023 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 10024 if (RsrcDword1) { 10025 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 10026 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 10027 0); 10028 } 10029 10030 SDValue DataLo = buildSMovImm32(DAG, DL, 10031 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 10032 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 10033 10034 const SDValue Ops[] = { 10035 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 10036 PtrLo, 10037 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10038 PtrHi, 10039 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 10040 DataLo, 10041 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 10042 DataHi, 10043 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 10044 }; 10045 10046 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 10047 } 10048 10049 //===----------------------------------------------------------------------===// 10050 // SI Inline Assembly Support 10051 //===----------------------------------------------------------------------===// 10052 10053 std::pair<unsigned, const TargetRegisterClass *> 10054 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10055 StringRef Constraint, 10056 MVT VT) const { 10057 const TargetRegisterClass *RC = nullptr; 10058 if (Constraint.size() == 1) { 10059 switch (Constraint[0]) { 10060 default: 10061 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10062 case 's': 10063 case 'r': 10064 switch (VT.getSizeInBits()) { 10065 default: 10066 return std::make_pair(0U, nullptr); 10067 case 32: 10068 case 16: 10069 RC = &AMDGPU::SReg_32_XM0RegClass; 10070 break; 10071 case 64: 10072 RC = &AMDGPU::SGPR_64RegClass; 10073 break; 10074 case 96: 10075 RC = &AMDGPU::SReg_96RegClass; 10076 break; 10077 case 128: 10078 RC = &AMDGPU::SReg_128RegClass; 10079 break; 10080 case 160: 10081 RC = &AMDGPU::SReg_160RegClass; 10082 break; 10083 case 256: 10084 RC = &AMDGPU::SReg_256RegClass; 10085 break; 10086 case 512: 10087 RC = &AMDGPU::SReg_512RegClass; 10088 break; 10089 } 10090 break; 10091 case 'v': 10092 switch (VT.getSizeInBits()) { 10093 default: 10094 return std::make_pair(0U, nullptr); 10095 case 32: 10096 case 16: 10097 RC = &AMDGPU::VGPR_32RegClass; 10098 break; 10099 case 64: 10100 RC = &AMDGPU::VReg_64RegClass; 10101 break; 10102 case 96: 10103 RC = &AMDGPU::VReg_96RegClass; 10104 break; 10105 case 128: 10106 RC = &AMDGPU::VReg_128RegClass; 10107 break; 10108 case 160: 10109 RC = &AMDGPU::VReg_160RegClass; 10110 break; 10111 case 256: 10112 RC = &AMDGPU::VReg_256RegClass; 10113 break; 10114 case 512: 10115 RC = &AMDGPU::VReg_512RegClass; 10116 break; 10117 } 10118 break; 10119 } 10120 // We actually support i128, i16 and f16 as inline parameters 10121 // even if they are not reported as legal 10122 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 10123 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 10124 return std::make_pair(0U, RC); 10125 } 10126 10127 if (Constraint.size() > 1) { 10128 if (Constraint[1] == 'v') { 10129 RC = &AMDGPU::VGPR_32RegClass; 10130 } else if (Constraint[1] == 's') { 10131 RC = &AMDGPU::SGPR_32RegClass; 10132 } 10133 10134 if (RC) { 10135 uint32_t Idx; 10136 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 10137 if (!Failed && Idx < RC->getNumRegs()) 10138 return std::make_pair(RC->getRegister(Idx), RC); 10139 } 10140 } 10141 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10142 } 10143 10144 SITargetLowering::ConstraintType 10145 SITargetLowering::getConstraintType(StringRef Constraint) const { 10146 if (Constraint.size() == 1) { 10147 switch (Constraint[0]) { 10148 default: break; 10149 case 's': 10150 case 'v': 10151 return C_RegisterClass; 10152 } 10153 } 10154 return TargetLowering::getConstraintType(Constraint); 10155 } 10156 10157 // Figure out which registers should be reserved for stack access. Only after 10158 // the function is legalized do we know all of the non-spill stack objects or if 10159 // calls are present. 10160 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 10161 MachineRegisterInfo &MRI = MF.getRegInfo(); 10162 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10163 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 10164 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10165 10166 if (Info->isEntryFunction()) { 10167 // Callable functions have fixed registers used for stack access. 10168 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 10169 } 10170 10171 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 10172 Info->getStackPtrOffsetReg())); 10173 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 10174 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 10175 10176 // We need to worry about replacing the default register with itself in case 10177 // of MIR testcases missing the MFI. 10178 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 10179 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 10180 10181 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 10182 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 10183 10184 if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) { 10185 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG, 10186 Info->getScratchWaveOffsetReg()); 10187 } 10188 10189 Info->limitOccupancy(MF); 10190 10191 if (ST.isWave32() && !MF.empty()) { 10192 // Add VCC_HI def because many instructions marked as imp-use VCC where 10193 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 10194 // having a use of undef. 10195 10196 const SIInstrInfo *TII = ST.getInstrInfo(); 10197 DebugLoc DL; 10198 10199 MachineBasicBlock &MBB = MF.front(); 10200 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 10201 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 10202 10203 for (auto &MBB : MF) { 10204 for (auto &MI : MBB) { 10205 TII->fixImplicitOperands(MI); 10206 } 10207 } 10208 } 10209 10210 TargetLoweringBase::finalizeLowering(MF); 10211 } 10212 10213 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 10214 KnownBits &Known, 10215 const APInt &DemandedElts, 10216 const SelectionDAG &DAG, 10217 unsigned Depth) const { 10218 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 10219 DAG, Depth); 10220 10221 // Set the high bits to zero based on the maximum allowed scratch size per 10222 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 10223 // calculation won't overflow, so assume the sign bit is never set. 10224 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 10225 } 10226 10227 unsigned SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 10228 const unsigned PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 10229 const unsigned CacheLineAlign = 6; // log2(64) 10230 10231 // Pre-GFX10 target did not benefit from loop alignment 10232 if (!ML || DisableLoopAlignment || 10233 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 10234 getSubtarget()->hasInstFwdPrefetchBug()) 10235 return PrefAlign; 10236 10237 // On GFX10 I$ is 4 x 64 bytes cache lines. 10238 // By default prefetcher keeps one cache line behind and reads two ahead. 10239 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 10240 // behind and one ahead. 10241 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 10242 // If loop fits 64 bytes it always spans no more than two cache lines and 10243 // does not need an alignment. 10244 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 10245 // Else if loop is less or equal 192 bytes we need two lines behind. 10246 10247 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10248 const MachineBasicBlock *Header = ML->getHeader(); 10249 if (Header->getAlignment() != PrefAlign) 10250 return Header->getAlignment(); // Already processed. 10251 10252 unsigned LoopSize = 0; 10253 for (const MachineBasicBlock *MBB : ML->blocks()) { 10254 // If inner loop block is aligned assume in average half of the alignment 10255 // size to be added as nops. 10256 if (MBB != Header) 10257 LoopSize += (1 << MBB->getAlignment()) / 2; 10258 10259 for (const MachineInstr &MI : *MBB) { 10260 LoopSize += TII->getInstSizeInBytes(MI); 10261 if (LoopSize > 192) 10262 return PrefAlign; 10263 } 10264 } 10265 10266 if (LoopSize <= 64) 10267 return PrefAlign; 10268 10269 if (LoopSize <= 128) 10270 return CacheLineAlign; 10271 10272 // If any of parent loops is surrounded by prefetch instructions do not 10273 // insert new for inner loop, which would reset parent's settings. 10274 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 10275 if (MachineBasicBlock *Exit = P->getExitBlock()) { 10276 auto I = Exit->getFirstNonDebugInstr(); 10277 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 10278 return CacheLineAlign; 10279 } 10280 } 10281 10282 MachineBasicBlock *Pre = ML->getLoopPreheader(); 10283 MachineBasicBlock *Exit = ML->getExitBlock(); 10284 10285 if (Pre && Exit) { 10286 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 10287 TII->get(AMDGPU::S_INST_PREFETCH)) 10288 .addImm(1); // prefetch 2 lines behind PC 10289 10290 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 10291 TII->get(AMDGPU::S_INST_PREFETCH)) 10292 .addImm(2); // prefetch 1 line behind PC 10293 } 10294 10295 return CacheLineAlign; 10296 } 10297 10298 LLVM_ATTRIBUTE_UNUSED 10299 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 10300 assert(N->getOpcode() == ISD::CopyFromReg); 10301 do { 10302 // Follow the chain until we find an INLINEASM node. 10303 N = N->getOperand(0).getNode(); 10304 if (N->getOpcode() == ISD::INLINEASM || 10305 N->getOpcode() == ISD::INLINEASM_BR) 10306 return true; 10307 } while (N->getOpcode() == ISD::CopyFromReg); 10308 return false; 10309 } 10310 10311 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 10312 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 10313 { 10314 switch (N->getOpcode()) { 10315 case ISD::CopyFromReg: 10316 { 10317 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 10318 const MachineFunction * MF = FLI->MF; 10319 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 10320 const MachineRegisterInfo &MRI = MF->getRegInfo(); 10321 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo(); 10322 unsigned Reg = R->getReg(); 10323 if (TRI.isPhysicalRegister(Reg)) 10324 return !TRI.isSGPRReg(MRI, Reg); 10325 10326 if (MRI.isLiveIn(Reg)) { 10327 // workitem.id.x workitem.id.y workitem.id.z 10328 // Any VGPR formal argument is also considered divergent 10329 if (!TRI.isSGPRReg(MRI, Reg)) 10330 return true; 10331 // Formal arguments of non-entry functions 10332 // are conservatively considered divergent 10333 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv())) 10334 return true; 10335 return false; 10336 } 10337 const Value *V = FLI->getValueFromVirtualReg(Reg); 10338 if (V) 10339 return KDA->isDivergent(V); 10340 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 10341 return !TRI.isSGPRReg(MRI, Reg); 10342 } 10343 break; 10344 case ISD::LOAD: { 10345 const LoadSDNode *L = cast<LoadSDNode>(N); 10346 unsigned AS = L->getAddressSpace(); 10347 // A flat load may access private memory. 10348 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 10349 } break; 10350 case ISD::CALLSEQ_END: 10351 return true; 10352 break; 10353 case ISD::INTRINSIC_WO_CHAIN: 10354 { 10355 10356 } 10357 return AMDGPU::isIntrinsicSourceOfDivergence( 10358 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 10359 case ISD::INTRINSIC_W_CHAIN: 10360 return AMDGPU::isIntrinsicSourceOfDivergence( 10361 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 10362 // In some cases intrinsics that are a source of divergence have been 10363 // lowered to AMDGPUISD so we also need to check those too. 10364 case AMDGPUISD::INTERP_MOV: 10365 case AMDGPUISD::INTERP_P1: 10366 case AMDGPUISD::INTERP_P2: 10367 return true; 10368 } 10369 return false; 10370 } 10371 10372 bool SITargetLowering::denormalsEnabledForType(EVT VT) const { 10373 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 10374 case MVT::f32: 10375 return Subtarget->hasFP32Denormals(); 10376 case MVT::f64: 10377 return Subtarget->hasFP64Denormals(); 10378 case MVT::f16: 10379 return Subtarget->hasFP16Denormals(); 10380 default: 10381 return false; 10382 } 10383 } 10384 10385 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 10386 const SelectionDAG &DAG, 10387 bool SNaN, 10388 unsigned Depth) const { 10389 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 10390 const MachineFunction &MF = DAG.getMachineFunction(); 10391 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10392 10393 if (Info->getMode().DX10Clamp) 10394 return true; // Clamped to 0. 10395 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 10396 } 10397 10398 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 10399 SNaN, Depth); 10400 } 10401 10402 TargetLowering::AtomicExpansionKind 10403 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 10404 switch (RMW->getOperation()) { 10405 case AtomicRMWInst::FAdd: { 10406 Type *Ty = RMW->getType(); 10407 10408 // We don't have a way to support 16-bit atomics now, so just leave them 10409 // as-is. 10410 if (Ty->isHalfTy()) 10411 return AtomicExpansionKind::None; 10412 10413 if (!Ty->isFloatTy()) 10414 return AtomicExpansionKind::CmpXChg; 10415 10416 // TODO: Do have these for flat. Older targets also had them for buffers. 10417 unsigned AS = RMW->getPointerAddressSpace(); 10418 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 10419 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 10420 } 10421 default: 10422 break; 10423 } 10424 10425 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 10426 } 10427