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 "MCTargetDesc/AMDGPUMCTargetDesc.h" 24 #include "SIDefines.h" 25 #include "SIInstrInfo.h" 26 #include "SIMachineFunctionInfo.h" 27 #include "SIRegisterInfo.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/Analysis/LegacyDivergenceAnalysis.h" 39 #include "llvm/CodeGen/Analysis.h" 40 #include "llvm/CodeGen/CallingConvLower.h" 41 #include "llvm/CodeGen/DAGCombine.h" 42 #include "llvm/CodeGen/ISDOpcodes.h" 43 #include "llvm/CodeGen/MachineBasicBlock.h" 44 #include "llvm/CodeGen/MachineFrameInfo.h" 45 #include "llvm/CodeGen/MachineFunction.h" 46 #include "llvm/CodeGen/MachineInstr.h" 47 #include "llvm/CodeGen/MachineInstrBuilder.h" 48 #include "llvm/CodeGen/MachineLoopInfo.h" 49 #include "llvm/CodeGen/MachineMemOperand.h" 50 #include "llvm/CodeGen/MachineModuleInfo.h" 51 #include "llvm/CodeGen/MachineOperand.h" 52 #include "llvm/CodeGen/MachineRegisterInfo.h" 53 #include "llvm/CodeGen/SelectionDAG.h" 54 #include "llvm/CodeGen/SelectionDAGNodes.h" 55 #include "llvm/CodeGen/TargetCallingConv.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/Constants.h" 59 #include "llvm/IR/DataLayout.h" 60 #include "llvm/IR/DebugLoc.h" 61 #include "llvm/IR/DerivedTypes.h" 62 #include "llvm/IR/DiagnosticInfo.h" 63 #include "llvm/IR/Function.h" 64 #include "llvm/IR/GlobalValue.h" 65 #include "llvm/IR/InstrTypes.h" 66 #include "llvm/IR/Instruction.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/IntrinsicInst.h" 69 #include "llvm/IR/Type.h" 70 #include "llvm/Support/Casting.h" 71 #include "llvm/Support/CodeGen.h" 72 #include "llvm/Support/CommandLine.h" 73 #include "llvm/Support/Compiler.h" 74 #include "llvm/Support/ErrorHandling.h" 75 #include "llvm/Support/KnownBits.h" 76 #include "llvm/Support/MachineValueType.h" 77 #include "llvm/Support/MathExtras.h" 78 #include "llvm/Target/TargetOptions.h" 79 #include <cassert> 80 #include <cmath> 81 #include <cstdint> 82 #include <iterator> 83 #include <tuple> 84 #include <utility> 85 #include <vector> 86 87 using namespace llvm; 88 89 #define DEBUG_TYPE "si-lower" 90 91 STATISTIC(NumTailCalls, "Number of tail calls"); 92 93 static cl::opt<bool> EnableVGPRIndexMode( 94 "amdgpu-vgpr-index-mode", 95 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"), 96 cl::init(false)); 97 98 static cl::opt<bool> DisableLoopAlignment( 99 "amdgpu-disable-loop-alignment", 100 cl::desc("Do not align and prefetch loops"), 101 cl::init(false)); 102 103 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 104 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 105 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 106 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 107 return AMDGPU::SGPR0 + Reg; 108 } 109 } 110 llvm_unreachable("Cannot allocate sgpr"); 111 } 112 113 SITargetLowering::SITargetLowering(const TargetMachine &TM, 114 const GCNSubtarget &STI) 115 : AMDGPUTargetLowering(TM, STI), 116 Subtarget(&STI) { 117 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 118 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 119 120 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 121 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 122 123 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 124 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 125 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 126 127 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 128 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 129 130 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 131 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 132 133 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 134 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 135 136 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 137 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 138 139 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass); 140 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 141 142 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass); 143 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 144 145 if (Subtarget->has16BitInsts()) { 146 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 147 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 148 149 // Unless there are also VOP3P operations, not operations are really legal. 150 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 151 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 152 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 153 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 154 } 155 156 if (Subtarget->hasMAIInsts()) { 157 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 158 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 159 } 160 161 computeRegisterProperties(Subtarget->getRegisterInfo()); 162 163 // We need to custom lower vector stores from local memory 164 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 165 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 166 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 167 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 168 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 169 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 170 setOperationAction(ISD::LOAD, MVT::i1, Custom); 171 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 172 173 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 174 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 175 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 176 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 177 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 178 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 179 setOperationAction(ISD::STORE, MVT::i1, Custom); 180 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 181 182 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 183 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 184 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 185 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 186 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 187 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 188 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 189 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 190 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 191 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 192 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 193 194 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 195 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 196 197 setOperationAction(ISD::SELECT, MVT::i1, Promote); 198 setOperationAction(ISD::SELECT, MVT::i64, Custom); 199 setOperationAction(ISD::SELECT, MVT::f64, Promote); 200 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 201 202 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 203 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 204 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 205 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 206 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 207 208 setOperationAction(ISD::SETCC, MVT::i1, Promote); 209 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 210 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 211 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 212 213 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 214 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 215 216 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 217 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 218 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 219 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 220 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 221 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 222 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 223 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 224 225 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 226 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 227 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 228 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 229 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 230 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 231 232 setOperationAction(ISD::UADDO, MVT::i32, Legal); 233 setOperationAction(ISD::USUBO, MVT::i32, Legal); 234 235 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 236 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 237 238 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 239 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 240 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 241 242 #if 0 243 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 244 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 245 #endif 246 247 // We only support LOAD/STORE and vector manipulation ops for vectors 248 // with > 4 elements. 249 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 250 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 251 MVT::v32i32, MVT::v32f32 }) { 252 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 253 switch (Op) { 254 case ISD::LOAD: 255 case ISD::STORE: 256 case ISD::BUILD_VECTOR: 257 case ISD::BITCAST: 258 case ISD::EXTRACT_VECTOR_ELT: 259 case ISD::INSERT_VECTOR_ELT: 260 case ISD::INSERT_SUBVECTOR: 261 case ISD::EXTRACT_SUBVECTOR: 262 case ISD::SCALAR_TO_VECTOR: 263 break; 264 case ISD::CONCAT_VECTORS: 265 setOperationAction(Op, VT, Custom); 266 break; 267 default: 268 setOperationAction(Op, VT, Expand); 269 break; 270 } 271 } 272 } 273 274 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 275 276 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 277 // is expanded to avoid having two separate loops in case the index is a VGPR. 278 279 // Most operations are naturally 32-bit vector operations. We only support 280 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 281 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 282 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 283 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 284 285 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 286 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 287 288 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 289 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 290 291 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 292 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 293 } 294 295 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 296 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 297 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 298 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 299 300 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 301 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 302 303 // Avoid stack access for these. 304 // TODO: Generalize to more vector types. 305 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 306 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 307 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 308 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 309 310 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 311 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 312 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 313 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 314 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 315 316 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 317 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 318 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 319 320 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 321 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 322 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 323 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 324 325 // Deal with vec3 vector operations when widened to vec4. 326 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 327 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 328 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 329 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 330 331 // Deal with vec5 vector operations when widened to vec8. 332 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 333 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 334 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 335 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 336 337 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 338 // and output demarshalling 339 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 340 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 341 342 // We can't return success/failure, only the old value, 343 // let LLVM add the comparison 344 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 345 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 346 347 if (Subtarget->hasFlatAddressSpace()) { 348 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 349 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 350 } 351 352 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 353 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 354 355 // On SI this is s_memtime and s_memrealtime on VI. 356 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 357 setOperationAction(ISD::TRAP, MVT::Other, Custom); 358 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 359 360 if (Subtarget->has16BitInsts()) { 361 setOperationAction(ISD::FLOG, MVT::f16, Custom); 362 setOperationAction(ISD::FEXP, MVT::f16, Custom); 363 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 364 } 365 366 // v_mad_f32 does not support denormals according to some sources. 367 if (!Subtarget->hasFP32Denormals()) 368 setOperationAction(ISD::FMAD, MVT::f32, Legal); 369 370 if (!Subtarget->hasBFI()) { 371 // fcopysign can be done in a single instruction with BFI. 372 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 373 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 374 } 375 376 if (!Subtarget->hasBCNT(32)) 377 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 378 379 if (!Subtarget->hasBCNT(64)) 380 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 381 382 if (Subtarget->hasFFBH()) 383 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 384 385 if (Subtarget->hasFFBL()) 386 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 387 388 // We only really have 32-bit BFE instructions (and 16-bit on VI). 389 // 390 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 391 // effort to match them now. We want this to be false for i64 cases when the 392 // extraction isn't restricted to the upper or lower half. Ideally we would 393 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 394 // span the midpoint are probably relatively rare, so don't worry about them 395 // for now. 396 if (Subtarget->hasBFE()) 397 setHasExtractBitsInsn(true); 398 399 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 400 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 401 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 402 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 403 404 405 // These are really only legal for ieee_mode functions. We should be avoiding 406 // them for functions that don't have ieee_mode enabled, so just say they are 407 // legal. 408 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 409 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 410 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 411 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 412 413 414 if (Subtarget->haveRoundOpsF64()) { 415 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 416 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 417 setOperationAction(ISD::FRINT, MVT::f64, Legal); 418 } else { 419 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 420 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 421 setOperationAction(ISD::FRINT, MVT::f64, Custom); 422 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 423 } 424 425 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 426 427 setOperationAction(ISD::FSIN, MVT::f32, Custom); 428 setOperationAction(ISD::FCOS, MVT::f32, Custom); 429 setOperationAction(ISD::FDIV, MVT::f32, Custom); 430 setOperationAction(ISD::FDIV, MVT::f64, Custom); 431 432 if (Subtarget->has16BitInsts()) { 433 setOperationAction(ISD::Constant, MVT::i16, Legal); 434 435 setOperationAction(ISD::SMIN, MVT::i16, Legal); 436 setOperationAction(ISD::SMAX, MVT::i16, Legal); 437 438 setOperationAction(ISD::UMIN, MVT::i16, Legal); 439 setOperationAction(ISD::UMAX, MVT::i16, Legal); 440 441 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 442 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 443 444 setOperationAction(ISD::ROTR, MVT::i16, Promote); 445 setOperationAction(ISD::ROTL, MVT::i16, Promote); 446 447 setOperationAction(ISD::SDIV, MVT::i16, Promote); 448 setOperationAction(ISD::UDIV, MVT::i16, Promote); 449 setOperationAction(ISD::SREM, MVT::i16, Promote); 450 setOperationAction(ISD::UREM, MVT::i16, Promote); 451 452 setOperationAction(ISD::BSWAP, MVT::i16, Promote); 453 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 454 455 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 456 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 457 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 458 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 459 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 460 461 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 462 463 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 464 465 setOperationAction(ISD::LOAD, MVT::i16, Custom); 466 467 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 468 469 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 470 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 471 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 472 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 473 474 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 475 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 476 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote); 477 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote); 478 479 // F16 - Constant Actions. 480 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 481 482 // F16 - Load/Store Actions. 483 setOperationAction(ISD::LOAD, MVT::f16, Promote); 484 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 485 setOperationAction(ISD::STORE, MVT::f16, Promote); 486 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 487 488 // F16 - VOP1 Actions. 489 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 490 setOperationAction(ISD::FCOS, MVT::f16, Promote); 491 setOperationAction(ISD::FSIN, MVT::f16, Promote); 492 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 493 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 494 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 495 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 496 setOperationAction(ISD::FROUND, MVT::f16, Custom); 497 498 // F16 - VOP2 Actions. 499 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 500 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 501 502 setOperationAction(ISD::FDIV, MVT::f16, Custom); 503 504 // F16 - VOP3 Actions. 505 setOperationAction(ISD::FMA, MVT::f16, Legal); 506 if (!Subtarget->hasFP16Denormals() && STI.hasMadF16()) 507 setOperationAction(ISD::FMAD, MVT::f16, Legal); 508 509 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 510 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 511 switch (Op) { 512 case ISD::LOAD: 513 case ISD::STORE: 514 case ISD::BUILD_VECTOR: 515 case ISD::BITCAST: 516 case ISD::EXTRACT_VECTOR_ELT: 517 case ISD::INSERT_VECTOR_ELT: 518 case ISD::INSERT_SUBVECTOR: 519 case ISD::EXTRACT_SUBVECTOR: 520 case ISD::SCALAR_TO_VECTOR: 521 break; 522 case ISD::CONCAT_VECTORS: 523 setOperationAction(Op, VT, Custom); 524 break; 525 default: 526 setOperationAction(Op, VT, Expand); 527 break; 528 } 529 } 530 } 531 532 // XXX - Do these do anything? Vector constants turn into build_vector. 533 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 534 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 535 536 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 537 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 538 539 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 540 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 541 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 542 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 543 544 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 545 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 546 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 547 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 548 549 setOperationAction(ISD::AND, MVT::v2i16, Promote); 550 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 551 setOperationAction(ISD::OR, MVT::v2i16, Promote); 552 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 553 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 554 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 555 556 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 557 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 558 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 559 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 560 561 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 562 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 563 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 564 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 565 566 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 567 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 568 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 569 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 570 571 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 572 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 573 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 574 575 if (!Subtarget->hasVOP3PInsts()) { 576 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 577 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 578 } 579 580 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 581 // This isn't really legal, but this avoids the legalizer unrolling it (and 582 // allows matching fneg (fabs x) patterns) 583 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 584 585 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 586 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 587 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 588 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 589 590 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 591 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 592 593 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 594 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 595 } 596 597 if (Subtarget->hasVOP3PInsts()) { 598 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 599 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 600 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 601 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 602 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 603 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 604 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 605 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 606 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 607 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 608 609 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 610 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 611 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 612 613 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 614 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 615 616 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 617 618 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 619 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 620 621 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 622 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 623 624 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 625 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 626 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 627 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 628 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 629 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 630 631 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 632 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 633 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 634 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 635 636 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 637 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 638 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 639 640 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 641 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 642 643 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 644 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 645 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 646 647 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 648 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 649 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 650 } 651 652 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 653 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 654 655 if (Subtarget->has16BitInsts()) { 656 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 657 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 658 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 659 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 660 } else { 661 // Legalization hack. 662 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 663 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 664 665 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 666 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 667 } 668 669 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 670 setOperationAction(ISD::SELECT, VT, Custom); 671 } 672 673 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 674 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 675 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 676 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 677 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 678 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 679 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 680 681 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 682 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 683 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 684 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 685 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 686 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 687 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 688 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 689 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 690 691 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 692 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 693 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 694 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 695 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 696 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 697 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 698 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 699 700 setTargetDAGCombine(ISD::ADD); 701 setTargetDAGCombine(ISD::ADDCARRY); 702 setTargetDAGCombine(ISD::SUB); 703 setTargetDAGCombine(ISD::SUBCARRY); 704 setTargetDAGCombine(ISD::FADD); 705 setTargetDAGCombine(ISD::FSUB); 706 setTargetDAGCombine(ISD::FMINNUM); 707 setTargetDAGCombine(ISD::FMAXNUM); 708 setTargetDAGCombine(ISD::FMINNUM_IEEE); 709 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 710 setTargetDAGCombine(ISD::FMA); 711 setTargetDAGCombine(ISD::SMIN); 712 setTargetDAGCombine(ISD::SMAX); 713 setTargetDAGCombine(ISD::UMIN); 714 setTargetDAGCombine(ISD::UMAX); 715 setTargetDAGCombine(ISD::SETCC); 716 setTargetDAGCombine(ISD::AND); 717 setTargetDAGCombine(ISD::OR); 718 setTargetDAGCombine(ISD::XOR); 719 setTargetDAGCombine(ISD::SINT_TO_FP); 720 setTargetDAGCombine(ISD::UINT_TO_FP); 721 setTargetDAGCombine(ISD::FCANONICALIZE); 722 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 723 setTargetDAGCombine(ISD::ZERO_EXTEND); 724 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 725 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 726 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 727 728 // All memory operations. Some folding on the pointer operand is done to help 729 // matching the constant offsets in the addressing modes. 730 setTargetDAGCombine(ISD::LOAD); 731 setTargetDAGCombine(ISD::STORE); 732 setTargetDAGCombine(ISD::ATOMIC_LOAD); 733 setTargetDAGCombine(ISD::ATOMIC_STORE); 734 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 735 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 736 setTargetDAGCombine(ISD::ATOMIC_SWAP); 737 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 738 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 739 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 740 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 741 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 742 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 743 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 744 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 745 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 746 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 747 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 748 749 setSchedulingPreference(Sched::RegPressure); 750 } 751 752 const GCNSubtarget *SITargetLowering::getSubtarget() const { 753 return Subtarget; 754 } 755 756 //===----------------------------------------------------------------------===// 757 // TargetLowering queries 758 //===----------------------------------------------------------------------===// 759 760 // v_mad_mix* support a conversion from f16 to f32. 761 // 762 // There is only one special case when denormals are enabled we don't currently, 763 // where this is OK to use. 764 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 765 EVT DestVT, EVT SrcVT) const { 766 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 767 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 768 DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() && 769 SrcVT.getScalarType() == MVT::f16; 770 } 771 772 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 773 // SI has some legal vector types, but no legal vector operations. Say no 774 // shuffles are legal in order to prefer scalarizing some vector operations. 775 return false; 776 } 777 778 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 779 CallingConv::ID CC, 780 EVT VT) const { 781 if (CC == CallingConv::AMDGPU_KERNEL) 782 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 783 784 if (VT.isVector()) { 785 EVT ScalarVT = VT.getScalarType(); 786 unsigned Size = ScalarVT.getSizeInBits(); 787 if (Size == 32) 788 return ScalarVT.getSimpleVT(); 789 790 if (Size > 32) 791 return MVT::i32; 792 793 if (Size == 16 && Subtarget->has16BitInsts()) 794 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 795 } else if (VT.getSizeInBits() > 32) 796 return MVT::i32; 797 798 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 799 } 800 801 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 802 CallingConv::ID CC, 803 EVT VT) const { 804 if (CC == CallingConv::AMDGPU_KERNEL) 805 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 806 807 if (VT.isVector()) { 808 unsigned NumElts = VT.getVectorNumElements(); 809 EVT ScalarVT = VT.getScalarType(); 810 unsigned Size = ScalarVT.getSizeInBits(); 811 812 if (Size == 32) 813 return NumElts; 814 815 if (Size > 32) 816 return NumElts * ((Size + 31) / 32); 817 818 if (Size == 16 && Subtarget->has16BitInsts()) 819 return (NumElts + 1) / 2; 820 } else if (VT.getSizeInBits() > 32) 821 return (VT.getSizeInBits() + 31) / 32; 822 823 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 824 } 825 826 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 827 LLVMContext &Context, CallingConv::ID CC, 828 EVT VT, EVT &IntermediateVT, 829 unsigned &NumIntermediates, MVT &RegisterVT) const { 830 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 831 unsigned NumElts = VT.getVectorNumElements(); 832 EVT ScalarVT = VT.getScalarType(); 833 unsigned Size = ScalarVT.getSizeInBits(); 834 if (Size == 32) { 835 RegisterVT = ScalarVT.getSimpleVT(); 836 IntermediateVT = RegisterVT; 837 NumIntermediates = NumElts; 838 return NumIntermediates; 839 } 840 841 if (Size > 32) { 842 RegisterVT = MVT::i32; 843 IntermediateVT = RegisterVT; 844 NumIntermediates = NumElts * ((Size + 31) / 32); 845 return NumIntermediates; 846 } 847 848 // FIXME: We should fix the ABI to be the same on targets without 16-bit 849 // support, but unless we can properly handle 3-vectors, it will be still be 850 // inconsistent. 851 if (Size == 16 && Subtarget->has16BitInsts()) { 852 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 853 IntermediateVT = RegisterVT; 854 NumIntermediates = (NumElts + 1) / 2; 855 return NumIntermediates; 856 } 857 } 858 859 return TargetLowering::getVectorTypeBreakdownForCallingConv( 860 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 861 } 862 863 static MVT memVTFromAggregate(Type *Ty) { 864 // Only limited forms of aggregate type currently expected. 865 assert(Ty->isStructTy() && "Expected struct type"); 866 867 868 Type *ElementType = nullptr; 869 unsigned NumElts; 870 if (Ty->getContainedType(0)->isVectorTy()) { 871 VectorType *VecComponent = cast<VectorType>(Ty->getContainedType(0)); 872 ElementType = VecComponent->getElementType(); 873 NumElts = VecComponent->getNumElements(); 874 } else { 875 ElementType = Ty->getContainedType(0); 876 NumElts = 1; 877 } 878 879 assert((Ty->getContainedType(1) && Ty->getContainedType(1)->isIntegerTy(32)) && "Expected int32 type"); 880 881 // Calculate the size of the memVT type from the aggregate 882 unsigned Pow2Elts = 0; 883 unsigned ElementSize; 884 switch (ElementType->getTypeID()) { 885 default: 886 llvm_unreachable("Unknown type!"); 887 case Type::IntegerTyID: 888 ElementSize = cast<IntegerType>(ElementType)->getBitWidth(); 889 break; 890 case Type::HalfTyID: 891 ElementSize = 16; 892 break; 893 case Type::FloatTyID: 894 ElementSize = 32; 895 break; 896 } 897 unsigned AdditionalElts = ElementSize == 16 ? 2 : 1; 898 Pow2Elts = 1 << Log2_32_Ceil(NumElts + AdditionalElts); 899 900 return MVT::getVectorVT(MVT::getVT(ElementType, false), 901 Pow2Elts); 902 } 903 904 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 905 const CallInst &CI, 906 MachineFunction &MF, 907 unsigned IntrID) const { 908 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 909 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 910 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 911 (Intrinsic::ID)IntrID); 912 if (Attr.hasFnAttribute(Attribute::ReadNone)) 913 return false; 914 915 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 916 917 if (RsrcIntr->IsImage) { 918 Info.ptrVal = MFI->getImagePSV( 919 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 920 CI.getArgOperand(RsrcIntr->RsrcArg)); 921 Info.align.reset(); 922 } else { 923 Info.ptrVal = MFI->getBufferPSV( 924 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 925 CI.getArgOperand(RsrcIntr->RsrcArg)); 926 } 927 928 Info.flags = MachineMemOperand::MODereferenceable; 929 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 930 Info.opc = ISD::INTRINSIC_W_CHAIN; 931 Info.memVT = MVT::getVT(CI.getType(), true); 932 if (Info.memVT == MVT::Other) { 933 // Some intrinsics return an aggregate type - special case to work out 934 // the correct memVT 935 Info.memVT = memVTFromAggregate(CI.getType()); 936 } 937 Info.flags |= MachineMemOperand::MOLoad; 938 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 939 Info.opc = ISD::INTRINSIC_VOID; 940 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 941 Info.flags |= MachineMemOperand::MOStore; 942 } else { 943 // Atomic 944 Info.opc = ISD::INTRINSIC_W_CHAIN; 945 Info.memVT = MVT::getVT(CI.getType()); 946 Info.flags = MachineMemOperand::MOLoad | 947 MachineMemOperand::MOStore | 948 MachineMemOperand::MODereferenceable; 949 950 // XXX - Should this be volatile without known ordering? 951 Info.flags |= MachineMemOperand::MOVolatile; 952 } 953 return true; 954 } 955 956 switch (IntrID) { 957 case Intrinsic::amdgcn_atomic_inc: 958 case Intrinsic::amdgcn_atomic_dec: 959 case Intrinsic::amdgcn_ds_ordered_add: 960 case Intrinsic::amdgcn_ds_ordered_swap: 961 case Intrinsic::amdgcn_ds_fadd: 962 case Intrinsic::amdgcn_ds_fmin: 963 case Intrinsic::amdgcn_ds_fmax: { 964 Info.opc = ISD::INTRINSIC_W_CHAIN; 965 Info.memVT = MVT::getVT(CI.getType()); 966 Info.ptrVal = CI.getOperand(0); 967 Info.align.reset(); 968 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 969 970 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 971 if (!Vol->isZero()) 972 Info.flags |= MachineMemOperand::MOVolatile; 973 974 return true; 975 } 976 case Intrinsic::amdgcn_buffer_atomic_fadd: { 977 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 978 979 Info.opc = ISD::INTRINSIC_VOID; 980 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 981 Info.ptrVal = MFI->getBufferPSV( 982 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 983 CI.getArgOperand(1)); 984 Info.align.reset(); 985 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 986 987 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 988 if (!Vol || !Vol->isZero()) 989 Info.flags |= MachineMemOperand::MOVolatile; 990 991 return true; 992 } 993 case Intrinsic::amdgcn_global_atomic_fadd: { 994 Info.opc = ISD::INTRINSIC_VOID; 995 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 996 ->getPointerElementType()); 997 Info.ptrVal = CI.getOperand(0); 998 Info.align.reset(); 999 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1000 1001 return true; 1002 } 1003 case Intrinsic::amdgcn_ds_append: 1004 case Intrinsic::amdgcn_ds_consume: { 1005 Info.opc = ISD::INTRINSIC_W_CHAIN; 1006 Info.memVT = MVT::getVT(CI.getType()); 1007 Info.ptrVal = CI.getOperand(0); 1008 Info.align.reset(); 1009 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1010 1011 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1012 if (!Vol->isZero()) 1013 Info.flags |= MachineMemOperand::MOVolatile; 1014 1015 return true; 1016 } 1017 case Intrinsic::amdgcn_ds_gws_init: 1018 case Intrinsic::amdgcn_ds_gws_barrier: 1019 case Intrinsic::amdgcn_ds_gws_sema_v: 1020 case Intrinsic::amdgcn_ds_gws_sema_br: 1021 case Intrinsic::amdgcn_ds_gws_sema_p: 1022 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1023 Info.opc = ISD::INTRINSIC_VOID; 1024 1025 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1026 Info.ptrVal = 1027 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1028 1029 // This is an abstract access, but we need to specify a type and size. 1030 Info.memVT = MVT::i32; 1031 Info.size = 4; 1032 Info.align = Align(4); 1033 1034 Info.flags = MachineMemOperand::MOStore; 1035 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1036 Info.flags = MachineMemOperand::MOLoad; 1037 return true; 1038 } 1039 default: 1040 return false; 1041 } 1042 } 1043 1044 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1045 SmallVectorImpl<Value*> &Ops, 1046 Type *&AccessTy) const { 1047 switch (II->getIntrinsicID()) { 1048 case Intrinsic::amdgcn_atomic_inc: 1049 case Intrinsic::amdgcn_atomic_dec: 1050 case Intrinsic::amdgcn_ds_ordered_add: 1051 case Intrinsic::amdgcn_ds_ordered_swap: 1052 case Intrinsic::amdgcn_ds_fadd: 1053 case Intrinsic::amdgcn_ds_fmin: 1054 case Intrinsic::amdgcn_ds_fmax: { 1055 Value *Ptr = II->getArgOperand(0); 1056 AccessTy = II->getType(); 1057 Ops.push_back(Ptr); 1058 return true; 1059 } 1060 default: 1061 return false; 1062 } 1063 } 1064 1065 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1066 if (!Subtarget->hasFlatInstOffsets()) { 1067 // Flat instructions do not have offsets, and only have the register 1068 // address. 1069 return AM.BaseOffs == 0 && AM.Scale == 0; 1070 } 1071 1072 // GFX9 added a 13-bit signed offset. When using regular flat instructions, 1073 // the sign bit is ignored and is treated as a 12-bit unsigned offset. 1074 1075 // GFX10 shrinked signed offset to 12 bits. When using regular flat 1076 // instructions, the sign bit is also ignored and is treated as 11-bit 1077 // unsigned offset. 1078 1079 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 1080 return isUInt<11>(AM.BaseOffs) && AM.Scale == 0; 1081 1082 // Just r + i 1083 return isUInt<12>(AM.BaseOffs) && AM.Scale == 0; 1084 } 1085 1086 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1087 if (Subtarget->hasFlatGlobalInsts()) 1088 return isInt<13>(AM.BaseOffs) && AM.Scale == 0; 1089 1090 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1091 // Assume the we will use FLAT for all global memory accesses 1092 // on VI. 1093 // FIXME: This assumption is currently wrong. On VI we still use 1094 // MUBUF instructions for the r + i addressing mode. As currently 1095 // implemented, the MUBUF instructions only work on buffer < 4GB. 1096 // It may be possible to support > 4GB buffers with MUBUF instructions, 1097 // by setting the stride value in the resource descriptor which would 1098 // increase the size limit to (stride * 4GB). However, this is risky, 1099 // because it has never been validated. 1100 return isLegalFlatAddressingMode(AM); 1101 } 1102 1103 return isLegalMUBUFAddressingMode(AM); 1104 } 1105 1106 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1107 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1108 // additionally can do r + r + i with addr64. 32-bit has more addressing 1109 // mode options. Depending on the resource constant, it can also do 1110 // (i64 r0) + (i32 r1) * (i14 i). 1111 // 1112 // Private arrays end up using a scratch buffer most of the time, so also 1113 // assume those use MUBUF instructions. Scratch loads / stores are currently 1114 // implemented as mubuf instructions with offen bit set, so slightly 1115 // different than the normal addr64. 1116 if (!isUInt<12>(AM.BaseOffs)) 1117 return false; 1118 1119 // FIXME: Since we can split immediate into soffset and immediate offset, 1120 // would it make sense to allow any immediate? 1121 1122 switch (AM.Scale) { 1123 case 0: // r + i or just i, depending on HasBaseReg. 1124 return true; 1125 case 1: 1126 return true; // We have r + r or r + i. 1127 case 2: 1128 if (AM.HasBaseReg) { 1129 // Reject 2 * r + r. 1130 return false; 1131 } 1132 1133 // Allow 2 * r as r + r 1134 // Or 2 * r + i is allowed as r + r + i. 1135 return true; 1136 default: // Don't allow n * r 1137 return false; 1138 } 1139 } 1140 1141 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1142 const AddrMode &AM, Type *Ty, 1143 unsigned AS, Instruction *I) const { 1144 // No global is ever allowed as a base. 1145 if (AM.BaseGV) 1146 return false; 1147 1148 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1149 return isLegalGlobalAddressingMode(AM); 1150 1151 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1152 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1153 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1154 // If the offset isn't a multiple of 4, it probably isn't going to be 1155 // correctly aligned. 1156 // FIXME: Can we get the real alignment here? 1157 if (AM.BaseOffs % 4 != 0) 1158 return isLegalMUBUFAddressingMode(AM); 1159 1160 // There are no SMRD extloads, so if we have to do a small type access we 1161 // will use a MUBUF load. 1162 // FIXME?: We also need to do this if unaligned, but we don't know the 1163 // alignment here. 1164 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1165 return isLegalGlobalAddressingMode(AM); 1166 1167 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1168 // SMRD instructions have an 8-bit, dword offset on SI. 1169 if (!isUInt<8>(AM.BaseOffs / 4)) 1170 return false; 1171 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1172 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1173 // in 8-bits, it can use a smaller encoding. 1174 if (!isUInt<32>(AM.BaseOffs / 4)) 1175 return false; 1176 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1177 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1178 if (!isUInt<20>(AM.BaseOffs)) 1179 return false; 1180 } else 1181 llvm_unreachable("unhandled generation"); 1182 1183 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1184 return true; 1185 1186 if (AM.Scale == 1 && AM.HasBaseReg) 1187 return true; 1188 1189 return false; 1190 1191 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1192 return isLegalMUBUFAddressingMode(AM); 1193 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1194 AS == AMDGPUAS::REGION_ADDRESS) { 1195 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1196 // field. 1197 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1198 // an 8-bit dword offset but we don't know the alignment here. 1199 if (!isUInt<16>(AM.BaseOffs)) 1200 return false; 1201 1202 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1203 return true; 1204 1205 if (AM.Scale == 1 && AM.HasBaseReg) 1206 return true; 1207 1208 return false; 1209 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1210 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1211 // For an unknown address space, this usually means that this is for some 1212 // reason being used for pure arithmetic, and not based on some addressing 1213 // computation. We don't have instructions that compute pointers with any 1214 // addressing modes, so treat them as having no offset like flat 1215 // instructions. 1216 return isLegalFlatAddressingMode(AM); 1217 } else { 1218 llvm_unreachable("unhandled address space"); 1219 } 1220 } 1221 1222 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1223 const SelectionDAG &DAG) const { 1224 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1225 return (MemVT.getSizeInBits() <= 4 * 32); 1226 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1227 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1228 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1229 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1230 return (MemVT.getSizeInBits() <= 2 * 32); 1231 } 1232 return true; 1233 } 1234 1235 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1236 unsigned Size, unsigned AddrSpace, unsigned Align, 1237 MachineMemOperand::Flags Flags, bool *IsFast) const { 1238 if (IsFast) 1239 *IsFast = false; 1240 1241 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1242 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1243 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1244 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1245 // with adjacent offsets. 1246 bool AlignedBy4 = (Align % 4 == 0); 1247 if (IsFast) 1248 *IsFast = AlignedBy4; 1249 1250 return AlignedBy4; 1251 } 1252 1253 // FIXME: We have to be conservative here and assume that flat operations 1254 // will access scratch. If we had access to the IR function, then we 1255 // could determine if any private memory was used in the function. 1256 if (!Subtarget->hasUnalignedScratchAccess() && 1257 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1258 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1259 bool AlignedBy4 = Align >= 4; 1260 if (IsFast) 1261 *IsFast = AlignedBy4; 1262 1263 return AlignedBy4; 1264 } 1265 1266 if (Subtarget->hasUnalignedBufferAccess()) { 1267 // If we have an uniform constant load, it still requires using a slow 1268 // buffer instruction if unaligned. 1269 if (IsFast) { 1270 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1271 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1272 (Align % 4 == 0) : true; 1273 } 1274 1275 return true; 1276 } 1277 1278 // Smaller than dword value must be aligned. 1279 if (Size < 32) 1280 return false; 1281 1282 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1283 // byte-address are ignored, thus forcing Dword alignment. 1284 // This applies to private, global, and constant memory. 1285 if (IsFast) 1286 *IsFast = true; 1287 1288 return Size >= 32 && Align >= 4; 1289 } 1290 1291 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1292 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1293 bool *IsFast) const { 1294 if (IsFast) 1295 *IsFast = false; 1296 1297 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1298 // which isn't a simple VT. 1299 // Until MVT is extended to handle this, simply check for the size and 1300 // rely on the condition below: allow accesses if the size is a multiple of 4. 1301 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1302 VT.getStoreSize() > 16)) { 1303 return false; 1304 } 1305 1306 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1307 Align, Flags, IsFast); 1308 } 1309 1310 EVT SITargetLowering::getOptimalMemOpType( 1311 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 1312 bool ZeroMemset, bool MemcpyStrSrc, 1313 const AttributeList &FuncAttributes) const { 1314 // FIXME: Should account for address space here. 1315 1316 // The default fallback uses the private pointer size as a guess for a type to 1317 // use. Make sure we switch these to 64-bit accesses. 1318 1319 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global 1320 return MVT::v4i32; 1321 1322 if (Size >= 8 && DstAlign >= 4) 1323 return MVT::v2i32; 1324 1325 // Use the default. 1326 return MVT::Other; 1327 } 1328 1329 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1330 unsigned DestAS) const { 1331 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1332 } 1333 1334 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1335 const MemSDNode *MemNode = cast<MemSDNode>(N); 1336 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1337 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1338 return I && I->getMetadata("amdgpu.noclobber"); 1339 } 1340 1341 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1342 unsigned DestAS) const { 1343 // Flat -> private/local is a simple truncate. 1344 // Flat -> global is no-op 1345 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1346 return true; 1347 1348 return isNoopAddrSpaceCast(SrcAS, DestAS); 1349 } 1350 1351 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1352 const MemSDNode *MemNode = cast<MemSDNode>(N); 1353 1354 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1355 } 1356 1357 TargetLoweringBase::LegalizeTypeAction 1358 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1359 int NumElts = VT.getVectorNumElements(); 1360 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1361 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1362 return TargetLoweringBase::getPreferredVectorAction(VT); 1363 } 1364 1365 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1366 Type *Ty) const { 1367 // FIXME: Could be smarter if called for vector constants. 1368 return true; 1369 } 1370 1371 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1372 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1373 switch (Op) { 1374 case ISD::LOAD: 1375 case ISD::STORE: 1376 1377 // These operations are done with 32-bit instructions anyway. 1378 case ISD::AND: 1379 case ISD::OR: 1380 case ISD::XOR: 1381 case ISD::SELECT: 1382 // TODO: Extensions? 1383 return true; 1384 default: 1385 return false; 1386 } 1387 } 1388 1389 // SimplifySetCC uses this function to determine whether or not it should 1390 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1391 if (VT == MVT::i1 && Op == ISD::SETCC) 1392 return false; 1393 1394 return TargetLowering::isTypeDesirableForOp(Op, VT); 1395 } 1396 1397 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1398 const SDLoc &SL, 1399 SDValue Chain, 1400 uint64_t Offset) const { 1401 const DataLayout &DL = DAG.getDataLayout(); 1402 MachineFunction &MF = DAG.getMachineFunction(); 1403 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1404 1405 const ArgDescriptor *InputPtrReg; 1406 const TargetRegisterClass *RC; 1407 1408 std::tie(InputPtrReg, RC) 1409 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1410 1411 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1412 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1413 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1414 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1415 1416 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1417 } 1418 1419 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1420 const SDLoc &SL) const { 1421 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1422 FIRST_IMPLICIT); 1423 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1424 } 1425 1426 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1427 const SDLoc &SL, SDValue Val, 1428 bool Signed, 1429 const ISD::InputArg *Arg) const { 1430 // First, if it is a widened vector, narrow it. 1431 if (VT.isVector() && 1432 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1433 EVT NarrowedVT = 1434 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1435 VT.getVectorNumElements()); 1436 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1437 DAG.getConstant(0, SL, MVT::i32)); 1438 } 1439 1440 // Then convert the vector elements or scalar value. 1441 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1442 VT.bitsLT(MemVT)) { 1443 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1444 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1445 } 1446 1447 if (MemVT.isFloatingPoint()) 1448 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT); 1449 else if (Signed) 1450 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1451 else 1452 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1453 1454 return Val; 1455 } 1456 1457 SDValue SITargetLowering::lowerKernargMemParameter( 1458 SelectionDAG &DAG, EVT VT, EVT MemVT, 1459 const SDLoc &SL, SDValue Chain, 1460 uint64_t Offset, unsigned Align, bool Signed, 1461 const ISD::InputArg *Arg) const { 1462 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 1463 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 1464 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 1465 1466 // Try to avoid using an extload by loading earlier than the argument address, 1467 // and extracting the relevant bits. The load should hopefully be merged with 1468 // the previous argument. 1469 if (MemVT.getStoreSize() < 4 && Align < 4) { 1470 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1471 int64_t AlignDownOffset = alignDown(Offset, 4); 1472 int64_t OffsetDiff = Offset - AlignDownOffset; 1473 1474 EVT IntVT = MemVT.changeTypeToInteger(); 1475 1476 // TODO: If we passed in the base kernel offset we could have a better 1477 // alignment than 4, but we don't really need it. 1478 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1479 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1480 MachineMemOperand::MODereferenceable | 1481 MachineMemOperand::MOInvariant); 1482 1483 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1484 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1485 1486 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1487 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1488 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1489 1490 1491 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1492 } 1493 1494 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1495 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1496 MachineMemOperand::MODereferenceable | 1497 MachineMemOperand::MOInvariant); 1498 1499 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1500 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1501 } 1502 1503 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1504 const SDLoc &SL, SDValue Chain, 1505 const ISD::InputArg &Arg) const { 1506 MachineFunction &MF = DAG.getMachineFunction(); 1507 MachineFrameInfo &MFI = MF.getFrameInfo(); 1508 1509 if (Arg.Flags.isByVal()) { 1510 unsigned Size = Arg.Flags.getByValSize(); 1511 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1512 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1513 } 1514 1515 unsigned ArgOffset = VA.getLocMemOffset(); 1516 unsigned ArgSize = VA.getValVT().getStoreSize(); 1517 1518 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1519 1520 // Create load nodes to retrieve arguments from the stack. 1521 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1522 SDValue ArgValue; 1523 1524 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1525 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1526 MVT MemVT = VA.getValVT(); 1527 1528 switch (VA.getLocInfo()) { 1529 default: 1530 break; 1531 case CCValAssign::BCvt: 1532 MemVT = VA.getLocVT(); 1533 break; 1534 case CCValAssign::SExt: 1535 ExtType = ISD::SEXTLOAD; 1536 break; 1537 case CCValAssign::ZExt: 1538 ExtType = ISD::ZEXTLOAD; 1539 break; 1540 case CCValAssign::AExt: 1541 ExtType = ISD::EXTLOAD; 1542 break; 1543 } 1544 1545 ArgValue = DAG.getExtLoad( 1546 ExtType, SL, VA.getLocVT(), Chain, FIN, 1547 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1548 MemVT); 1549 return ArgValue; 1550 } 1551 1552 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1553 const SIMachineFunctionInfo &MFI, 1554 EVT VT, 1555 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1556 const ArgDescriptor *Reg; 1557 const TargetRegisterClass *RC; 1558 1559 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1560 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1561 } 1562 1563 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1564 CallingConv::ID CallConv, 1565 ArrayRef<ISD::InputArg> Ins, 1566 BitVector &Skipped, 1567 FunctionType *FType, 1568 SIMachineFunctionInfo *Info) { 1569 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1570 const ISD::InputArg *Arg = &Ins[I]; 1571 1572 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1573 "vector type argument should have been split"); 1574 1575 // First check if it's a PS input addr. 1576 if (CallConv == CallingConv::AMDGPU_PS && 1577 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1578 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1579 1580 // Inconveniently only the first part of the split is marked as isSplit, 1581 // so skip to the end. We only want to increment PSInputNum once for the 1582 // entire split argument. 1583 if (Arg->Flags.isSplit()) { 1584 while (!Arg->Flags.isSplitEnd()) { 1585 assert((!Arg->VT.isVector() || 1586 Arg->VT.getScalarSizeInBits() == 16) && 1587 "unexpected vector split in ps argument type"); 1588 if (!SkipArg) 1589 Splits.push_back(*Arg); 1590 Arg = &Ins[++I]; 1591 } 1592 } 1593 1594 if (SkipArg) { 1595 // We can safely skip PS inputs. 1596 Skipped.set(Arg->getOrigArgIndex()); 1597 ++PSInputNum; 1598 continue; 1599 } 1600 1601 Info->markPSInputAllocated(PSInputNum); 1602 if (Arg->Used) 1603 Info->markPSInputEnabled(PSInputNum); 1604 1605 ++PSInputNum; 1606 } 1607 1608 Splits.push_back(*Arg); 1609 } 1610 } 1611 1612 // Allocate special inputs passed in VGPRs. 1613 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1614 MachineFunction &MF, 1615 const SIRegisterInfo &TRI, 1616 SIMachineFunctionInfo &Info) const { 1617 const LLT S32 = LLT::scalar(32); 1618 MachineRegisterInfo &MRI = MF.getRegInfo(); 1619 1620 if (Info.hasWorkItemIDX()) { 1621 Register Reg = AMDGPU::VGPR0; 1622 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1623 1624 CCInfo.AllocateReg(Reg); 1625 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1626 } 1627 1628 if (Info.hasWorkItemIDY()) { 1629 Register Reg = AMDGPU::VGPR1; 1630 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1631 1632 CCInfo.AllocateReg(Reg); 1633 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1634 } 1635 1636 if (Info.hasWorkItemIDZ()) { 1637 Register Reg = AMDGPU::VGPR2; 1638 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1639 1640 CCInfo.AllocateReg(Reg); 1641 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1642 } 1643 } 1644 1645 // Try to allocate a VGPR at the end of the argument list, or if no argument 1646 // VGPRs are left allocating a stack slot. 1647 // If \p Mask is is given it indicates bitfield position in the register. 1648 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1649 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1650 ArgDescriptor Arg = ArgDescriptor()) { 1651 if (Arg.isSet()) 1652 return ArgDescriptor::createArg(Arg, Mask); 1653 1654 ArrayRef<MCPhysReg> ArgVGPRs 1655 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1656 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1657 if (RegIdx == ArgVGPRs.size()) { 1658 // Spill to stack required. 1659 int64_t Offset = CCInfo.AllocateStack(4, 4); 1660 1661 return ArgDescriptor::createStack(Offset, Mask); 1662 } 1663 1664 unsigned Reg = ArgVGPRs[RegIdx]; 1665 Reg = CCInfo.AllocateReg(Reg); 1666 assert(Reg != AMDGPU::NoRegister); 1667 1668 MachineFunction &MF = CCInfo.getMachineFunction(); 1669 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1670 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1671 return ArgDescriptor::createRegister(Reg, Mask); 1672 } 1673 1674 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1675 const TargetRegisterClass *RC, 1676 unsigned NumArgRegs) { 1677 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1678 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1679 if (RegIdx == ArgSGPRs.size()) 1680 report_fatal_error("ran out of SGPRs for arguments"); 1681 1682 unsigned Reg = ArgSGPRs[RegIdx]; 1683 Reg = CCInfo.AllocateReg(Reg); 1684 assert(Reg != AMDGPU::NoRegister); 1685 1686 MachineFunction &MF = CCInfo.getMachineFunction(); 1687 MF.addLiveIn(Reg, RC); 1688 return ArgDescriptor::createRegister(Reg); 1689 } 1690 1691 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1692 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1693 } 1694 1695 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1696 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1697 } 1698 1699 void SITargetLowering::allocateSpecialInputVGPRs(CCState &CCInfo, 1700 MachineFunction &MF, 1701 const SIRegisterInfo &TRI, 1702 SIMachineFunctionInfo &Info) const { 1703 const unsigned Mask = 0x3ff; 1704 ArgDescriptor Arg; 1705 1706 if (Info.hasWorkItemIDX()) { 1707 Arg = allocateVGPR32Input(CCInfo, Mask); 1708 Info.setWorkItemIDX(Arg); 1709 } 1710 1711 if (Info.hasWorkItemIDY()) { 1712 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1713 Info.setWorkItemIDY(Arg); 1714 } 1715 1716 if (Info.hasWorkItemIDZ()) 1717 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1718 } 1719 1720 void SITargetLowering::allocateSpecialInputSGPRs( 1721 CCState &CCInfo, 1722 MachineFunction &MF, 1723 const SIRegisterInfo &TRI, 1724 SIMachineFunctionInfo &Info) const { 1725 auto &ArgInfo = Info.getArgInfo(); 1726 1727 // TODO: Unify handling with private memory pointers. 1728 1729 if (Info.hasDispatchPtr()) 1730 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1731 1732 if (Info.hasQueuePtr()) 1733 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1734 1735 if (Info.hasKernargSegmentPtr()) 1736 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo); 1737 1738 if (Info.hasDispatchID()) 1739 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1740 1741 // flat_scratch_init is not applicable for non-kernel functions. 1742 1743 if (Info.hasWorkGroupIDX()) 1744 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1745 1746 if (Info.hasWorkGroupIDY()) 1747 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1748 1749 if (Info.hasWorkGroupIDZ()) 1750 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1751 1752 if (Info.hasImplicitArgPtr()) 1753 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1754 } 1755 1756 // Allocate special inputs passed in user SGPRs. 1757 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1758 MachineFunction &MF, 1759 const SIRegisterInfo &TRI, 1760 SIMachineFunctionInfo &Info) const { 1761 if (Info.hasImplicitBufferPtr()) { 1762 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1763 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1764 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1765 } 1766 1767 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1768 if (Info.hasPrivateSegmentBuffer()) { 1769 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1770 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1771 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1772 } 1773 1774 if (Info.hasDispatchPtr()) { 1775 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1776 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1777 CCInfo.AllocateReg(DispatchPtrReg); 1778 } 1779 1780 if (Info.hasQueuePtr()) { 1781 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1782 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1783 CCInfo.AllocateReg(QueuePtrReg); 1784 } 1785 1786 if (Info.hasKernargSegmentPtr()) { 1787 MachineRegisterInfo &MRI = MF.getRegInfo(); 1788 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1789 CCInfo.AllocateReg(InputPtrReg); 1790 1791 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1792 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1793 } 1794 1795 if (Info.hasDispatchID()) { 1796 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1797 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1798 CCInfo.AllocateReg(DispatchIDReg); 1799 } 1800 1801 if (Info.hasFlatScratchInit()) { 1802 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1803 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1804 CCInfo.AllocateReg(FlatScratchInitReg); 1805 } 1806 1807 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1808 // these from the dispatch pointer. 1809 } 1810 1811 // Allocate special input registers that are initialized per-wave. 1812 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1813 MachineFunction &MF, 1814 SIMachineFunctionInfo &Info, 1815 CallingConv::ID CallConv, 1816 bool IsShader) const { 1817 if (Info.hasWorkGroupIDX()) { 1818 unsigned Reg = Info.addWorkGroupIDX(); 1819 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1820 CCInfo.AllocateReg(Reg); 1821 } 1822 1823 if (Info.hasWorkGroupIDY()) { 1824 unsigned Reg = Info.addWorkGroupIDY(); 1825 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1826 CCInfo.AllocateReg(Reg); 1827 } 1828 1829 if (Info.hasWorkGroupIDZ()) { 1830 unsigned Reg = Info.addWorkGroupIDZ(); 1831 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1832 CCInfo.AllocateReg(Reg); 1833 } 1834 1835 if (Info.hasWorkGroupInfo()) { 1836 unsigned Reg = Info.addWorkGroupInfo(); 1837 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1838 CCInfo.AllocateReg(Reg); 1839 } 1840 1841 if (Info.hasPrivateSegmentWaveByteOffset()) { 1842 // Scratch wave offset passed in system SGPR. 1843 unsigned PrivateSegmentWaveByteOffsetReg; 1844 1845 if (IsShader) { 1846 PrivateSegmentWaveByteOffsetReg = 1847 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1848 1849 // This is true if the scratch wave byte offset doesn't have a fixed 1850 // location. 1851 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1852 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1853 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1854 } 1855 } else 1856 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1857 1858 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1859 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1860 } 1861 } 1862 1863 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1864 MachineFunction &MF, 1865 const SIRegisterInfo &TRI, 1866 SIMachineFunctionInfo &Info) { 1867 // Now that we've figured out where the scratch register inputs are, see if 1868 // should reserve the arguments and use them directly. 1869 MachineFrameInfo &MFI = MF.getFrameInfo(); 1870 bool HasStackObjects = MFI.hasStackObjects(); 1871 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 1872 1873 // Record that we know we have non-spill stack objects so we don't need to 1874 // check all stack objects later. 1875 if (HasStackObjects) 1876 Info.setHasNonSpillStackObjects(true); 1877 1878 // Everything live out of a block is spilled with fast regalloc, so it's 1879 // almost certain that spilling will be required. 1880 if (TM.getOptLevel() == CodeGenOpt::None) 1881 HasStackObjects = true; 1882 1883 // For now assume stack access is needed in any callee functions, so we need 1884 // the scratch registers to pass in. 1885 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1886 1887 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 1888 // If we have stack objects, we unquestionably need the private buffer 1889 // resource. For the Code Object V2 ABI, this will be the first 4 user 1890 // SGPR inputs. We can reserve those and use them directly. 1891 1892 Register PrivateSegmentBufferReg = 1893 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 1894 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1895 } else { 1896 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1897 // We tentatively reserve the last registers (skipping the last registers 1898 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 1899 // we'll replace these with the ones immediately after those which were 1900 // really allocated. In the prologue copies will be inserted from the 1901 // argument to these reserved registers. 1902 1903 // Without HSA, relocations are used for the scratch pointer and the 1904 // buffer resource setup is always inserted in the prologue. Scratch wave 1905 // offset is still in an input SGPR. 1906 Info.setScratchRSrcReg(ReservedBufferReg); 1907 } 1908 1909 // hasFP should be accurate for kernels even before the frame is finalized. 1910 if (ST.getFrameLowering()->hasFP(MF)) { 1911 MachineRegisterInfo &MRI = MF.getRegInfo(); 1912 1913 // Try to use s32 as the SP, but move it if it would interfere with input 1914 // arguments. This won't work with calls though. 1915 // 1916 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 1917 // registers. 1918 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 1919 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 1920 } else { 1921 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 1922 1923 if (MFI.hasCalls()) 1924 report_fatal_error("call in graphics shader with too many input SGPRs"); 1925 1926 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 1927 if (!MRI.isLiveIn(Reg)) { 1928 Info.setStackPtrOffsetReg(Reg); 1929 break; 1930 } 1931 } 1932 1933 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 1934 report_fatal_error("failed to find register for SP"); 1935 } 1936 1937 if (MFI.hasCalls()) { 1938 Info.setScratchWaveOffsetReg(AMDGPU::SGPR33); 1939 Info.setFrameOffsetReg(AMDGPU::SGPR33); 1940 } else { 1941 unsigned ReservedOffsetReg = 1942 TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1943 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1944 Info.setFrameOffsetReg(ReservedOffsetReg); 1945 } 1946 } else if (RequiresStackAccess) { 1947 assert(!MFI.hasCalls()); 1948 // We know there are accesses and they will be done relative to SP, so just 1949 // pin it to the input. 1950 // 1951 // FIXME: Should not do this if inline asm is reading/writing these 1952 // registers. 1953 Register PreloadedSP = Info.getPreloadedReg( 1954 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1955 1956 Info.setStackPtrOffsetReg(PreloadedSP); 1957 Info.setScratchWaveOffsetReg(PreloadedSP); 1958 Info.setFrameOffsetReg(PreloadedSP); 1959 } else { 1960 assert(!MFI.hasCalls()); 1961 1962 // There may not be stack access at all. There may still be spills, or 1963 // access of a constant pointer (in which cases an extra copy will be 1964 // emitted in the prolog). 1965 unsigned ReservedOffsetReg 1966 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1967 Info.setStackPtrOffsetReg(ReservedOffsetReg); 1968 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1969 Info.setFrameOffsetReg(ReservedOffsetReg); 1970 } 1971 } 1972 1973 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 1974 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 1975 return !Info->isEntryFunction(); 1976 } 1977 1978 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 1979 1980 } 1981 1982 void SITargetLowering::insertCopiesSplitCSR( 1983 MachineBasicBlock *Entry, 1984 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 1985 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1986 1987 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 1988 if (!IStart) 1989 return; 1990 1991 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1992 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 1993 MachineBasicBlock::iterator MBBI = Entry->begin(); 1994 for (const MCPhysReg *I = IStart; *I; ++I) { 1995 const TargetRegisterClass *RC = nullptr; 1996 if (AMDGPU::SReg_64RegClass.contains(*I)) 1997 RC = &AMDGPU::SGPR_64RegClass; 1998 else if (AMDGPU::SReg_32RegClass.contains(*I)) 1999 RC = &AMDGPU::SGPR_32RegClass; 2000 else 2001 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2002 2003 Register NewVR = MRI->createVirtualRegister(RC); 2004 // Create copy from CSR to a virtual register. 2005 Entry->addLiveIn(*I); 2006 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2007 .addReg(*I); 2008 2009 // Insert the copy-back instructions right before the terminator. 2010 for (auto *Exit : Exits) 2011 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2012 TII->get(TargetOpcode::COPY), *I) 2013 .addReg(NewVR); 2014 } 2015 } 2016 2017 SDValue SITargetLowering::LowerFormalArguments( 2018 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2019 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2020 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2021 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2022 2023 MachineFunction &MF = DAG.getMachineFunction(); 2024 const Function &Fn = MF.getFunction(); 2025 FunctionType *FType = MF.getFunction().getFunctionType(); 2026 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2027 2028 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2029 DiagnosticInfoUnsupported NoGraphicsHSA( 2030 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2031 DAG.getContext()->diagnose(NoGraphicsHSA); 2032 return DAG.getEntryNode(); 2033 } 2034 2035 SmallVector<ISD::InputArg, 16> Splits; 2036 SmallVector<CCValAssign, 16> ArgLocs; 2037 BitVector Skipped(Ins.size()); 2038 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2039 *DAG.getContext()); 2040 2041 bool IsShader = AMDGPU::isShader(CallConv); 2042 bool IsKernel = AMDGPU::isKernel(CallConv); 2043 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2044 2045 if (IsShader) { 2046 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2047 2048 // At least one interpolation mode must be enabled or else the GPU will 2049 // hang. 2050 // 2051 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2052 // set PSInputAddr, the user wants to enable some bits after the compilation 2053 // based on run-time states. Since we can't know what the final PSInputEna 2054 // will look like, so we shouldn't do anything here and the user should take 2055 // responsibility for the correct programming. 2056 // 2057 // Otherwise, the following restrictions apply: 2058 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2059 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2060 // enabled too. 2061 if (CallConv == CallingConv::AMDGPU_PS) { 2062 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2063 ((Info->getPSInputAddr() & 0xF) == 0 && 2064 Info->isPSInputAllocated(11))) { 2065 CCInfo.AllocateReg(AMDGPU::VGPR0); 2066 CCInfo.AllocateReg(AMDGPU::VGPR1); 2067 Info->markPSInputAllocated(0); 2068 Info->markPSInputEnabled(0); 2069 } 2070 if (Subtarget->isAmdPalOS()) { 2071 // For isAmdPalOS, the user does not enable some bits after compilation 2072 // based on run-time states; the register values being generated here are 2073 // the final ones set in hardware. Therefore we need to apply the 2074 // workaround to PSInputAddr and PSInputEnable together. (The case where 2075 // a bit is set in PSInputAddr but not PSInputEnable is where the 2076 // frontend set up an input arg for a particular interpolation mode, but 2077 // nothing uses that input arg. Really we should have an earlier pass 2078 // that removes such an arg.) 2079 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2080 if ((PsInputBits & 0x7F) == 0 || 2081 ((PsInputBits & 0xF) == 0 && 2082 (PsInputBits >> 11 & 1))) 2083 Info->markPSInputEnabled( 2084 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2085 } 2086 } 2087 2088 assert(!Info->hasDispatchPtr() && 2089 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2090 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2091 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2092 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2093 !Info->hasWorkItemIDZ()); 2094 } else if (IsKernel) { 2095 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2096 } else { 2097 Splits.append(Ins.begin(), Ins.end()); 2098 } 2099 2100 if (IsEntryFunc) { 2101 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2102 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2103 } 2104 2105 if (IsKernel) { 2106 analyzeFormalArgumentsCompute(CCInfo, Ins); 2107 } else { 2108 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2109 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2110 } 2111 2112 SmallVector<SDValue, 16> Chains; 2113 2114 // FIXME: This is the minimum kernel argument alignment. We should improve 2115 // this to the maximum alignment of the arguments. 2116 // 2117 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2118 // kern arg offset. 2119 const unsigned KernelArgBaseAlign = 16; 2120 2121 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2122 const ISD::InputArg &Arg = Ins[i]; 2123 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2124 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2125 continue; 2126 } 2127 2128 CCValAssign &VA = ArgLocs[ArgIdx++]; 2129 MVT VT = VA.getLocVT(); 2130 2131 if (IsEntryFunc && VA.isMemLoc()) { 2132 VT = Ins[i].VT; 2133 EVT MemVT = VA.getLocVT(); 2134 2135 const uint64_t Offset = VA.getLocMemOffset(); 2136 unsigned Align = MinAlign(KernelArgBaseAlign, Offset); 2137 2138 SDValue Arg = lowerKernargMemParameter( 2139 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]); 2140 Chains.push_back(Arg.getValue(1)); 2141 2142 auto *ParamTy = 2143 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2144 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2145 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2146 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2147 // On SI local pointers are just offsets into LDS, so they are always 2148 // less than 16-bits. On CI and newer they could potentially be 2149 // real pointers, so we can't guarantee their size. 2150 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2151 DAG.getValueType(MVT::i16)); 2152 } 2153 2154 InVals.push_back(Arg); 2155 continue; 2156 } else if (!IsEntryFunc && VA.isMemLoc()) { 2157 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2158 InVals.push_back(Val); 2159 if (!Arg.Flags.isByVal()) 2160 Chains.push_back(Val.getValue(1)); 2161 continue; 2162 } 2163 2164 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2165 2166 Register Reg = VA.getLocReg(); 2167 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2168 EVT ValVT = VA.getValVT(); 2169 2170 Reg = MF.addLiveIn(Reg, RC); 2171 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2172 2173 if (Arg.Flags.isSRet()) { 2174 // The return object should be reasonably addressable. 2175 2176 // FIXME: This helps when the return is a real sret. If it is a 2177 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2178 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2179 unsigned NumBits 2180 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2181 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2182 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2183 } 2184 2185 // If this is an 8 or 16-bit value, it is really passed promoted 2186 // to 32 bits. Insert an assert[sz]ext to capture this, then 2187 // truncate to the right size. 2188 switch (VA.getLocInfo()) { 2189 case CCValAssign::Full: 2190 break; 2191 case CCValAssign::BCvt: 2192 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2193 break; 2194 case CCValAssign::SExt: 2195 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2196 DAG.getValueType(ValVT)); 2197 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2198 break; 2199 case CCValAssign::ZExt: 2200 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2201 DAG.getValueType(ValVT)); 2202 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2203 break; 2204 case CCValAssign::AExt: 2205 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2206 break; 2207 default: 2208 llvm_unreachable("Unknown loc info!"); 2209 } 2210 2211 InVals.push_back(Val); 2212 } 2213 2214 if (!IsEntryFunc) { 2215 // Special inputs come after user arguments. 2216 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2217 } 2218 2219 // Start adding system SGPRs. 2220 if (IsEntryFunc) { 2221 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2222 } else { 2223 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2224 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg()); 2225 CCInfo.AllocateReg(Info->getFrameOffsetReg()); 2226 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2227 } 2228 2229 auto &ArgUsageInfo = 2230 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2231 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2232 2233 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2234 Info->setBytesInStackArgArea(StackArgSize); 2235 2236 return Chains.empty() ? Chain : 2237 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2238 } 2239 2240 // TODO: If return values can't fit in registers, we should return as many as 2241 // possible in registers before passing on stack. 2242 bool SITargetLowering::CanLowerReturn( 2243 CallingConv::ID CallConv, 2244 MachineFunction &MF, bool IsVarArg, 2245 const SmallVectorImpl<ISD::OutputArg> &Outs, 2246 LLVMContext &Context) const { 2247 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2248 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2249 // for shaders. Vector types should be explicitly handled by CC. 2250 if (AMDGPU::isEntryFunctionCC(CallConv)) 2251 return true; 2252 2253 SmallVector<CCValAssign, 16> RVLocs; 2254 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2255 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2256 } 2257 2258 SDValue 2259 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2260 bool isVarArg, 2261 const SmallVectorImpl<ISD::OutputArg> &Outs, 2262 const SmallVectorImpl<SDValue> &OutVals, 2263 const SDLoc &DL, SelectionDAG &DAG) const { 2264 MachineFunction &MF = DAG.getMachineFunction(); 2265 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2266 2267 if (AMDGPU::isKernel(CallConv)) { 2268 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2269 OutVals, DL, DAG); 2270 } 2271 2272 bool IsShader = AMDGPU::isShader(CallConv); 2273 2274 Info->setIfReturnsVoid(Outs.empty()); 2275 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2276 2277 // CCValAssign - represent the assignment of the return value to a location. 2278 SmallVector<CCValAssign, 48> RVLocs; 2279 SmallVector<ISD::OutputArg, 48> Splits; 2280 2281 // CCState - Info about the registers and stack slots. 2282 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2283 *DAG.getContext()); 2284 2285 // Analyze outgoing return values. 2286 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2287 2288 SDValue Flag; 2289 SmallVector<SDValue, 48> RetOps; 2290 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2291 2292 // Add return address for callable functions. 2293 if (!Info->isEntryFunction()) { 2294 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2295 SDValue ReturnAddrReg = CreateLiveInRegister( 2296 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2297 2298 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2299 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2300 MVT::i64); 2301 Chain = 2302 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2303 Flag = Chain.getValue(1); 2304 RetOps.push_back(ReturnAddrVirtualReg); 2305 } 2306 2307 // Copy the result values into the output registers. 2308 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2309 ++I, ++RealRVLocIdx) { 2310 CCValAssign &VA = RVLocs[I]; 2311 assert(VA.isRegLoc() && "Can only return in registers!"); 2312 // TODO: Partially return in registers if return values don't fit. 2313 SDValue Arg = OutVals[RealRVLocIdx]; 2314 2315 // Copied from other backends. 2316 switch (VA.getLocInfo()) { 2317 case CCValAssign::Full: 2318 break; 2319 case CCValAssign::BCvt: 2320 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2321 break; 2322 case CCValAssign::SExt: 2323 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2324 break; 2325 case CCValAssign::ZExt: 2326 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2327 break; 2328 case CCValAssign::AExt: 2329 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2330 break; 2331 default: 2332 llvm_unreachable("Unknown loc info!"); 2333 } 2334 2335 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2336 Flag = Chain.getValue(1); 2337 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2338 } 2339 2340 // FIXME: Does sret work properly? 2341 if (!Info->isEntryFunction()) { 2342 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2343 const MCPhysReg *I = 2344 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2345 if (I) { 2346 for (; *I; ++I) { 2347 if (AMDGPU::SReg_64RegClass.contains(*I)) 2348 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2349 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2350 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2351 else 2352 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2353 } 2354 } 2355 } 2356 2357 // Update chain and glue. 2358 RetOps[0] = Chain; 2359 if (Flag.getNode()) 2360 RetOps.push_back(Flag); 2361 2362 unsigned Opc = AMDGPUISD::ENDPGM; 2363 if (!IsWaveEnd) 2364 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2365 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2366 } 2367 2368 SDValue SITargetLowering::LowerCallResult( 2369 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2370 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2371 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2372 SDValue ThisVal) const { 2373 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2374 2375 // Assign locations to each value returned by this call. 2376 SmallVector<CCValAssign, 16> RVLocs; 2377 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2378 *DAG.getContext()); 2379 CCInfo.AnalyzeCallResult(Ins, RetCC); 2380 2381 // Copy all of the result registers out of their specified physreg. 2382 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2383 CCValAssign VA = RVLocs[i]; 2384 SDValue Val; 2385 2386 if (VA.isRegLoc()) { 2387 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2388 Chain = Val.getValue(1); 2389 InFlag = Val.getValue(2); 2390 } else if (VA.isMemLoc()) { 2391 report_fatal_error("TODO: return values in memory"); 2392 } else 2393 llvm_unreachable("unknown argument location type"); 2394 2395 switch (VA.getLocInfo()) { 2396 case CCValAssign::Full: 2397 break; 2398 case CCValAssign::BCvt: 2399 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2400 break; 2401 case CCValAssign::ZExt: 2402 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2403 DAG.getValueType(VA.getValVT())); 2404 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2405 break; 2406 case CCValAssign::SExt: 2407 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2408 DAG.getValueType(VA.getValVT())); 2409 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2410 break; 2411 case CCValAssign::AExt: 2412 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2413 break; 2414 default: 2415 llvm_unreachable("Unknown loc info!"); 2416 } 2417 2418 InVals.push_back(Val); 2419 } 2420 2421 return Chain; 2422 } 2423 2424 // Add code to pass special inputs required depending on used features separate 2425 // from the explicit user arguments present in the IR. 2426 void SITargetLowering::passSpecialInputs( 2427 CallLoweringInfo &CLI, 2428 CCState &CCInfo, 2429 const SIMachineFunctionInfo &Info, 2430 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2431 SmallVectorImpl<SDValue> &MemOpChains, 2432 SDValue Chain) const { 2433 // If we don't have a call site, this was a call inserted by 2434 // legalization. These can never use special inputs. 2435 if (!CLI.CS) 2436 return; 2437 2438 const Function *CalleeFunc = CLI.CS.getCalledFunction(); 2439 assert(CalleeFunc); 2440 2441 SelectionDAG &DAG = CLI.DAG; 2442 const SDLoc &DL = CLI.DL; 2443 2444 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2445 2446 auto &ArgUsageInfo = 2447 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2448 const AMDGPUFunctionArgInfo &CalleeArgInfo 2449 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2450 2451 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2452 2453 // TODO: Unify with private memory register handling. This is complicated by 2454 // the fact that at least in kernels, the input argument is not necessarily 2455 // in the same location as the input. 2456 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2457 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2458 AMDGPUFunctionArgInfo::QUEUE_PTR, 2459 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR, 2460 AMDGPUFunctionArgInfo::DISPATCH_ID, 2461 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2462 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2463 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z, 2464 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR 2465 }; 2466 2467 for (auto InputID : InputRegs) { 2468 const ArgDescriptor *OutgoingArg; 2469 const TargetRegisterClass *ArgRC; 2470 2471 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID); 2472 if (!OutgoingArg) 2473 continue; 2474 2475 const ArgDescriptor *IncomingArg; 2476 const TargetRegisterClass *IncomingArgRC; 2477 std::tie(IncomingArg, IncomingArgRC) 2478 = CallerArgInfo.getPreloadedValue(InputID); 2479 assert(IncomingArgRC == ArgRC); 2480 2481 // All special arguments are ints for now. 2482 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2483 SDValue InputReg; 2484 2485 if (IncomingArg) { 2486 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2487 } else { 2488 // The implicit arg ptr is special because it doesn't have a corresponding 2489 // input for kernels, and is computed from the kernarg segment pointer. 2490 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2491 InputReg = getImplicitArgPtr(DAG, DL); 2492 } 2493 2494 if (OutgoingArg->isRegister()) { 2495 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2496 } else { 2497 unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4); 2498 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2499 SpecialArgOffset); 2500 MemOpChains.push_back(ArgStore); 2501 } 2502 } 2503 2504 // Pack workitem IDs into a single register or pass it as is if already 2505 // packed. 2506 const ArgDescriptor *OutgoingArg; 2507 const TargetRegisterClass *ArgRC; 2508 2509 std::tie(OutgoingArg, ArgRC) = 2510 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2511 if (!OutgoingArg) 2512 std::tie(OutgoingArg, ArgRC) = 2513 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2514 if (!OutgoingArg) 2515 std::tie(OutgoingArg, ArgRC) = 2516 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2517 if (!OutgoingArg) 2518 return; 2519 2520 const ArgDescriptor *IncomingArgX 2521 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first; 2522 const ArgDescriptor *IncomingArgY 2523 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first; 2524 const ArgDescriptor *IncomingArgZ 2525 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first; 2526 2527 SDValue InputReg; 2528 SDLoc SL; 2529 2530 // If incoming ids are not packed we need to pack them. 2531 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo.WorkItemIDX) 2532 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2533 2534 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo.WorkItemIDY) { 2535 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2536 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2537 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2538 InputReg = InputReg.getNode() ? 2539 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2540 } 2541 2542 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo.WorkItemIDZ) { 2543 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2544 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2545 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2546 InputReg = InputReg.getNode() ? 2547 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2548 } 2549 2550 if (!InputReg.getNode()) { 2551 // Workitem ids are already packed, any of present incoming arguments 2552 // will carry all required fields. 2553 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2554 IncomingArgX ? *IncomingArgX : 2555 IncomingArgY ? *IncomingArgY : 2556 *IncomingArgZ, ~0u); 2557 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2558 } 2559 2560 if (OutgoingArg->isRegister()) { 2561 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2562 } else { 2563 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4); 2564 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2565 SpecialArgOffset); 2566 MemOpChains.push_back(ArgStore); 2567 } 2568 } 2569 2570 static bool canGuaranteeTCO(CallingConv::ID CC) { 2571 return CC == CallingConv::Fast; 2572 } 2573 2574 /// Return true if we might ever do TCO for calls with this calling convention. 2575 static bool mayTailCallThisCC(CallingConv::ID CC) { 2576 switch (CC) { 2577 case CallingConv::C: 2578 return true; 2579 default: 2580 return canGuaranteeTCO(CC); 2581 } 2582 } 2583 2584 bool SITargetLowering::isEligibleForTailCallOptimization( 2585 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2586 const SmallVectorImpl<ISD::OutputArg> &Outs, 2587 const SmallVectorImpl<SDValue> &OutVals, 2588 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2589 if (!mayTailCallThisCC(CalleeCC)) 2590 return false; 2591 2592 MachineFunction &MF = DAG.getMachineFunction(); 2593 const Function &CallerF = MF.getFunction(); 2594 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2595 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2596 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2597 2598 // Kernels aren't callable, and don't have a live in return address so it 2599 // doesn't make sense to do a tail call with entry functions. 2600 if (!CallerPreserved) 2601 return false; 2602 2603 bool CCMatch = CallerCC == CalleeCC; 2604 2605 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2606 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2607 return true; 2608 return false; 2609 } 2610 2611 // TODO: Can we handle var args? 2612 if (IsVarArg) 2613 return false; 2614 2615 for (const Argument &Arg : CallerF.args()) { 2616 if (Arg.hasByValAttr()) 2617 return false; 2618 } 2619 2620 LLVMContext &Ctx = *DAG.getContext(); 2621 2622 // Check that the call results are passed in the same way. 2623 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2624 CCAssignFnForCall(CalleeCC, IsVarArg), 2625 CCAssignFnForCall(CallerCC, IsVarArg))) 2626 return false; 2627 2628 // The callee has to preserve all registers the caller needs to preserve. 2629 if (!CCMatch) { 2630 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2631 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2632 return false; 2633 } 2634 2635 // Nothing more to check if the callee is taking no arguments. 2636 if (Outs.empty()) 2637 return true; 2638 2639 SmallVector<CCValAssign, 16> ArgLocs; 2640 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2641 2642 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2643 2644 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2645 // If the stack arguments for this call do not fit into our own save area then 2646 // the call cannot be made tail. 2647 // TODO: Is this really necessary? 2648 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2649 return false; 2650 2651 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2652 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2653 } 2654 2655 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2656 if (!CI->isTailCall()) 2657 return false; 2658 2659 const Function *ParentFn = CI->getParent()->getParent(); 2660 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2661 return false; 2662 2663 auto Attr = ParentFn->getFnAttribute("disable-tail-calls"); 2664 return (Attr.getValueAsString() != "true"); 2665 } 2666 2667 // The wave scratch offset register is used as the global base pointer. 2668 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2669 SmallVectorImpl<SDValue> &InVals) const { 2670 SelectionDAG &DAG = CLI.DAG; 2671 const SDLoc &DL = CLI.DL; 2672 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2673 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2674 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2675 SDValue Chain = CLI.Chain; 2676 SDValue Callee = CLI.Callee; 2677 bool &IsTailCall = CLI.IsTailCall; 2678 CallingConv::ID CallConv = CLI.CallConv; 2679 bool IsVarArg = CLI.IsVarArg; 2680 bool IsSibCall = false; 2681 bool IsThisReturn = false; 2682 MachineFunction &MF = DAG.getMachineFunction(); 2683 2684 if (Callee.isUndef() || isNullConstant(Callee)) { 2685 if (!CLI.IsTailCall) { 2686 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2687 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2688 } 2689 2690 return Chain; 2691 } 2692 2693 if (IsVarArg) { 2694 return lowerUnhandledCall(CLI, InVals, 2695 "unsupported call to variadic function "); 2696 } 2697 2698 if (!CLI.CS.getInstruction()) 2699 report_fatal_error("unsupported libcall legalization"); 2700 2701 if (!CLI.CS.getCalledFunction()) { 2702 return lowerUnhandledCall(CLI, InVals, 2703 "unsupported indirect call to function "); 2704 } 2705 2706 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2707 return lowerUnhandledCall(CLI, InVals, 2708 "unsupported required tail call to function "); 2709 } 2710 2711 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2712 // Note the issue is with the CC of the calling function, not of the call 2713 // itself. 2714 return lowerUnhandledCall(CLI, InVals, 2715 "unsupported call from graphics shader of function "); 2716 } 2717 2718 if (IsTailCall) { 2719 IsTailCall = isEligibleForTailCallOptimization( 2720 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2721 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) { 2722 report_fatal_error("failed to perform tail call elimination on a call " 2723 "site marked musttail"); 2724 } 2725 2726 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2727 2728 // A sibling call is one where we're under the usual C ABI and not planning 2729 // to change that but can still do a tail call: 2730 if (!TailCallOpt && IsTailCall) 2731 IsSibCall = true; 2732 2733 if (IsTailCall) 2734 ++NumTailCalls; 2735 } 2736 2737 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2738 2739 // Analyze operands of the call, assigning locations to each operand. 2740 SmallVector<CCValAssign, 16> ArgLocs; 2741 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2742 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2743 2744 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2745 2746 // Get a count of how many bytes are to be pushed on the stack. 2747 unsigned NumBytes = CCInfo.getNextStackOffset(); 2748 2749 if (IsSibCall) { 2750 // Since we're not changing the ABI to make this a tail call, the memory 2751 // operands are already available in the caller's incoming argument space. 2752 NumBytes = 0; 2753 } 2754 2755 // FPDiff is the byte offset of the call's argument area from the callee's. 2756 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2757 // by this amount for a tail call. In a sibling call it must be 0 because the 2758 // caller will deallocate the entire stack and the callee still expects its 2759 // arguments to begin at SP+0. Completely unused for non-tail calls. 2760 int32_t FPDiff = 0; 2761 MachineFrameInfo &MFI = MF.getFrameInfo(); 2762 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2763 2764 // Adjust the stack pointer for the new arguments... 2765 // These operations are automatically eliminated by the prolog/epilog pass 2766 if (!IsSibCall) { 2767 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2768 2769 SmallVector<SDValue, 4> CopyFromChains; 2770 2771 // In the HSA case, this should be an identity copy. 2772 SDValue ScratchRSrcReg 2773 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2774 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2775 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2776 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2777 } 2778 2779 SmallVector<SDValue, 8> MemOpChains; 2780 MVT PtrVT = MVT::i32; 2781 2782 // Walk the register/memloc assignments, inserting copies/loads. 2783 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 2784 ++i, ++realArgIdx) { 2785 CCValAssign &VA = ArgLocs[i]; 2786 SDValue Arg = OutVals[realArgIdx]; 2787 2788 // Promote the value if needed. 2789 switch (VA.getLocInfo()) { 2790 case CCValAssign::Full: 2791 break; 2792 case CCValAssign::BCvt: 2793 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2794 break; 2795 case CCValAssign::ZExt: 2796 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2797 break; 2798 case CCValAssign::SExt: 2799 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2800 break; 2801 case CCValAssign::AExt: 2802 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2803 break; 2804 case CCValAssign::FPExt: 2805 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2806 break; 2807 default: 2808 llvm_unreachable("Unknown loc info!"); 2809 } 2810 2811 if (VA.isRegLoc()) { 2812 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2813 } else { 2814 assert(VA.isMemLoc()); 2815 2816 SDValue DstAddr; 2817 MachinePointerInfo DstInfo; 2818 2819 unsigned LocMemOffset = VA.getLocMemOffset(); 2820 int32_t Offset = LocMemOffset; 2821 2822 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2823 MaybeAlign Alignment; 2824 2825 if (IsTailCall) { 2826 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2827 unsigned OpSize = Flags.isByVal() ? 2828 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2829 2830 // FIXME: We can have better than the minimum byval required alignment. 2831 Alignment = 2832 Flags.isByVal() 2833 ? MaybeAlign(Flags.getByValAlign()) 2834 : commonAlignment(Subtarget->getStackAlignment(), Offset); 2835 2836 Offset = Offset + FPDiff; 2837 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2838 2839 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2840 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2841 2842 // Make sure any stack arguments overlapping with where we're storing 2843 // are loaded before this eventual operation. Otherwise they'll be 2844 // clobbered. 2845 2846 // FIXME: Why is this really necessary? This seems to just result in a 2847 // lot of code to copy the stack and write them back to the same 2848 // locations, which are supposed to be immutable? 2849 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2850 } else { 2851 DstAddr = PtrOff; 2852 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2853 Alignment = 2854 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 2855 } 2856 2857 if (Outs[i].Flags.isByVal()) { 2858 SDValue SizeNode = 2859 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2860 SDValue Cpy = DAG.getMemcpy( 2861 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 2862 /*isVol = */ false, /*AlwaysInline = */ true, 2863 /*isTailCall = */ false, DstInfo, 2864 MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy( 2865 *DAG.getContext(), AMDGPUAS::PRIVATE_ADDRESS)))); 2866 2867 MemOpChains.push_back(Cpy); 2868 } else { 2869 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 2870 Alignment ? Alignment->value() : 0); 2871 MemOpChains.push_back(Store); 2872 } 2873 } 2874 } 2875 2876 // Copy special input registers after user input arguments. 2877 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2878 2879 if (!MemOpChains.empty()) 2880 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2881 2882 // Build a sequence of copy-to-reg nodes chained together with token chain 2883 // and flag operands which copy the outgoing args into the appropriate regs. 2884 SDValue InFlag; 2885 for (auto &RegToPass : RegsToPass) { 2886 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2887 RegToPass.second, InFlag); 2888 InFlag = Chain.getValue(1); 2889 } 2890 2891 2892 SDValue PhysReturnAddrReg; 2893 if (IsTailCall) { 2894 // Since the return is being combined with the call, we need to pass on the 2895 // return address. 2896 2897 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2898 SDValue ReturnAddrReg = CreateLiveInRegister( 2899 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2900 2901 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2902 MVT::i64); 2903 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2904 InFlag = Chain.getValue(1); 2905 } 2906 2907 // We don't usually want to end the call-sequence here because we would tidy 2908 // the frame up *after* the call, however in the ABI-changing tail-call case 2909 // we've carefully laid out the parameters so that when sp is reset they'll be 2910 // in the correct location. 2911 if (IsTailCall && !IsSibCall) { 2912 Chain = DAG.getCALLSEQ_END(Chain, 2913 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2914 DAG.getTargetConstant(0, DL, MVT::i32), 2915 InFlag, DL); 2916 InFlag = Chain.getValue(1); 2917 } 2918 2919 std::vector<SDValue> Ops; 2920 Ops.push_back(Chain); 2921 Ops.push_back(Callee); 2922 // Add a redundant copy of the callee global which will not be legalized, as 2923 // we need direct access to the callee later. 2924 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee); 2925 const GlobalValue *GV = GSD->getGlobal(); 2926 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 2927 2928 if (IsTailCall) { 2929 // Each tail call may have to adjust the stack by a different amount, so 2930 // this information must travel along with the operation for eventual 2931 // consumption by emitEpilogue. 2932 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 2933 2934 Ops.push_back(PhysReturnAddrReg); 2935 } 2936 2937 // Add argument registers to the end of the list so that they are known live 2938 // into the call. 2939 for (auto &RegToPass : RegsToPass) { 2940 Ops.push_back(DAG.getRegister(RegToPass.first, 2941 RegToPass.second.getValueType())); 2942 } 2943 2944 // Add a register mask operand representing the call-preserved registers. 2945 2946 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 2947 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2948 assert(Mask && "Missing call preserved mask for calling convention"); 2949 Ops.push_back(DAG.getRegisterMask(Mask)); 2950 2951 if (InFlag.getNode()) 2952 Ops.push_back(InFlag); 2953 2954 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2955 2956 // If we're doing a tall call, use a TC_RETURN here rather than an 2957 // actual call instruction. 2958 if (IsTailCall) { 2959 MFI.setHasTailCall(); 2960 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 2961 } 2962 2963 // Returns a chain and a flag for retval copy to use. 2964 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 2965 Chain = Call.getValue(0); 2966 InFlag = Call.getValue(1); 2967 2968 uint64_t CalleePopBytes = NumBytes; 2969 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 2970 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 2971 InFlag, DL); 2972 if (!Ins.empty()) 2973 InFlag = Chain.getValue(1); 2974 2975 // Handle result values, copying them out of physregs into vregs that we 2976 // return. 2977 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 2978 InVals, IsThisReturn, 2979 IsThisReturn ? OutVals[0] : SDValue()); 2980 } 2981 2982 Register SITargetLowering::getRegisterByName(const char* RegName, EVT VT, 2983 const MachineFunction &MF) const { 2984 Register Reg = StringSwitch<Register>(RegName) 2985 .Case("m0", AMDGPU::M0) 2986 .Case("exec", AMDGPU::EXEC) 2987 .Case("exec_lo", AMDGPU::EXEC_LO) 2988 .Case("exec_hi", AMDGPU::EXEC_HI) 2989 .Case("flat_scratch", AMDGPU::FLAT_SCR) 2990 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 2991 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 2992 .Default(Register()); 2993 2994 if (Reg == AMDGPU::NoRegister) { 2995 report_fatal_error(Twine("invalid register name \"" 2996 + StringRef(RegName) + "\".")); 2997 2998 } 2999 3000 if (!Subtarget->hasFlatScrRegister() && 3001 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3002 report_fatal_error(Twine("invalid register \"" 3003 + StringRef(RegName) + "\" for subtarget.")); 3004 } 3005 3006 switch (Reg) { 3007 case AMDGPU::M0: 3008 case AMDGPU::EXEC_LO: 3009 case AMDGPU::EXEC_HI: 3010 case AMDGPU::FLAT_SCR_LO: 3011 case AMDGPU::FLAT_SCR_HI: 3012 if (VT.getSizeInBits() == 32) 3013 return Reg; 3014 break; 3015 case AMDGPU::EXEC: 3016 case AMDGPU::FLAT_SCR: 3017 if (VT.getSizeInBits() == 64) 3018 return Reg; 3019 break; 3020 default: 3021 llvm_unreachable("missing register type checking"); 3022 } 3023 3024 report_fatal_error(Twine("invalid type for register \"" 3025 + StringRef(RegName) + "\".")); 3026 } 3027 3028 // If kill is not the last instruction, split the block so kill is always a 3029 // proper terminator. 3030 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3031 MachineBasicBlock *BB) const { 3032 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3033 3034 MachineBasicBlock::iterator SplitPoint(&MI); 3035 ++SplitPoint; 3036 3037 if (SplitPoint == BB->end()) { 3038 // Don't bother with a new block. 3039 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3040 return BB; 3041 } 3042 3043 MachineFunction *MF = BB->getParent(); 3044 MachineBasicBlock *SplitBB 3045 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3046 3047 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3048 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3049 3050 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3051 BB->addSuccessor(SplitBB); 3052 3053 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3054 return SplitBB; 3055 } 3056 3057 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3058 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3059 // be the first instruction in the remainder block. 3060 // 3061 /// \returns { LoopBody, Remainder } 3062 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3063 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3064 MachineFunction *MF = MBB.getParent(); 3065 MachineBasicBlock::iterator I(&MI); 3066 3067 // To insert the loop we need to split the block. Move everything after this 3068 // point to a new block, and insert a new empty block between the two. 3069 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3070 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3071 MachineFunction::iterator MBBI(MBB); 3072 ++MBBI; 3073 3074 MF->insert(MBBI, LoopBB); 3075 MF->insert(MBBI, RemainderBB); 3076 3077 LoopBB->addSuccessor(LoopBB); 3078 LoopBB->addSuccessor(RemainderBB); 3079 3080 // Move the rest of the block into a new block. 3081 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3082 3083 if (InstInLoop) { 3084 auto Next = std::next(I); 3085 3086 // Move instruction to loop body. 3087 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3088 3089 // Move the rest of the block. 3090 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3091 } else { 3092 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3093 } 3094 3095 MBB.addSuccessor(LoopBB); 3096 3097 return std::make_pair(LoopBB, RemainderBB); 3098 } 3099 3100 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3101 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3102 MachineBasicBlock *MBB = MI.getParent(); 3103 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3104 auto I = MI.getIterator(); 3105 auto E = std::next(I); 3106 3107 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3108 .addImm(0); 3109 3110 MIBundleBuilder Bundler(*MBB, I, E); 3111 finalizeBundle(*MBB, Bundler.begin()); 3112 } 3113 3114 MachineBasicBlock * 3115 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3116 MachineBasicBlock *BB) const { 3117 const DebugLoc &DL = MI.getDebugLoc(); 3118 3119 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3120 3121 MachineBasicBlock *LoopBB; 3122 MachineBasicBlock *RemainderBB; 3123 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3124 3125 // Apparently kill flags are only valid if the def is in the same block? 3126 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3127 Src->setIsKill(false); 3128 3129 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3130 3131 MachineBasicBlock::iterator I = LoopBB->end(); 3132 3133 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3134 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3135 3136 // Clear TRAP_STS.MEM_VIOL 3137 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3138 .addImm(0) 3139 .addImm(EncodedReg); 3140 3141 bundleInstWithWaitcnt(MI); 3142 3143 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3144 3145 // Load and check TRAP_STS.MEM_VIOL 3146 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3147 .addImm(EncodedReg); 3148 3149 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3150 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3151 .addReg(Reg, RegState::Kill) 3152 .addImm(0); 3153 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3154 .addMBB(LoopBB); 3155 3156 return RemainderBB; 3157 } 3158 3159 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3160 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3161 // will only do one iteration. In the worst case, this will loop 64 times. 3162 // 3163 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3164 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3165 const SIInstrInfo *TII, 3166 MachineRegisterInfo &MRI, 3167 MachineBasicBlock &OrigBB, 3168 MachineBasicBlock &LoopBB, 3169 const DebugLoc &DL, 3170 const MachineOperand &IdxReg, 3171 unsigned InitReg, 3172 unsigned ResultReg, 3173 unsigned PhiReg, 3174 unsigned InitSaveExecReg, 3175 int Offset, 3176 bool UseGPRIdxMode, 3177 bool IsIndirectSrc) { 3178 MachineFunction *MF = OrigBB.getParent(); 3179 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3180 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3181 MachineBasicBlock::iterator I = LoopBB.begin(); 3182 3183 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3184 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3185 Register NewExec = MRI.createVirtualRegister(BoolRC); 3186 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3187 Register CondReg = MRI.createVirtualRegister(BoolRC); 3188 3189 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3190 .addReg(InitReg) 3191 .addMBB(&OrigBB) 3192 .addReg(ResultReg) 3193 .addMBB(&LoopBB); 3194 3195 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3196 .addReg(InitSaveExecReg) 3197 .addMBB(&OrigBB) 3198 .addReg(NewExec) 3199 .addMBB(&LoopBB); 3200 3201 // Read the next variant <- also loop target. 3202 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3203 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3204 3205 // Compare the just read M0 value to all possible Idx values. 3206 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3207 .addReg(CurrentIdxReg) 3208 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3209 3210 // Update EXEC, save the original EXEC value to VCC. 3211 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3212 : AMDGPU::S_AND_SAVEEXEC_B64), 3213 NewExec) 3214 .addReg(CondReg, RegState::Kill); 3215 3216 MRI.setSimpleHint(NewExec, CondReg); 3217 3218 if (UseGPRIdxMode) { 3219 unsigned IdxReg; 3220 if (Offset == 0) { 3221 IdxReg = CurrentIdxReg; 3222 } else { 3223 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3224 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3225 .addReg(CurrentIdxReg, RegState::Kill) 3226 .addImm(Offset); 3227 } 3228 unsigned IdxMode = IsIndirectSrc ? 3229 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3230 MachineInstr *SetOn = 3231 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3232 .addReg(IdxReg, RegState::Kill) 3233 .addImm(IdxMode); 3234 SetOn->getOperand(3).setIsUndef(); 3235 } else { 3236 // Move index from VCC into M0 3237 if (Offset == 0) { 3238 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3239 .addReg(CurrentIdxReg, RegState::Kill); 3240 } else { 3241 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3242 .addReg(CurrentIdxReg, RegState::Kill) 3243 .addImm(Offset); 3244 } 3245 } 3246 3247 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3248 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3249 MachineInstr *InsertPt = 3250 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3251 : AMDGPU::S_XOR_B64_term), Exec) 3252 .addReg(Exec) 3253 .addReg(NewExec); 3254 3255 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3256 // s_cbranch_scc0? 3257 3258 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3259 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3260 .addMBB(&LoopBB); 3261 3262 return InsertPt->getIterator(); 3263 } 3264 3265 // This has slightly sub-optimal regalloc when the source vector is killed by 3266 // the read. The register allocator does not understand that the kill is 3267 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3268 // subregister from it, using 1 more VGPR than necessary. This was saved when 3269 // this was expanded after register allocation. 3270 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3271 MachineBasicBlock &MBB, 3272 MachineInstr &MI, 3273 unsigned InitResultReg, 3274 unsigned PhiReg, 3275 int Offset, 3276 bool UseGPRIdxMode, 3277 bool IsIndirectSrc) { 3278 MachineFunction *MF = MBB.getParent(); 3279 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3280 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3281 MachineRegisterInfo &MRI = MF->getRegInfo(); 3282 const DebugLoc &DL = MI.getDebugLoc(); 3283 MachineBasicBlock::iterator I(&MI); 3284 3285 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3286 Register DstReg = MI.getOperand(0).getReg(); 3287 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3288 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3289 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3290 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3291 3292 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3293 3294 // Save the EXEC mask 3295 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3296 .addReg(Exec); 3297 3298 MachineBasicBlock *LoopBB; 3299 MachineBasicBlock *RemainderBB; 3300 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3301 3302 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3303 3304 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3305 InitResultReg, DstReg, PhiReg, TmpExec, 3306 Offset, UseGPRIdxMode, IsIndirectSrc); 3307 3308 MachineBasicBlock::iterator First = RemainderBB->begin(); 3309 BuildMI(*RemainderBB, First, DL, TII->get(MovExecOpc), Exec) 3310 .addReg(SaveExec); 3311 3312 return InsPt; 3313 } 3314 3315 // Returns subreg index, offset 3316 static std::pair<unsigned, int> 3317 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3318 const TargetRegisterClass *SuperRC, 3319 unsigned VecReg, 3320 int Offset) { 3321 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3322 3323 // Skip out of bounds offsets, or else we would end up using an undefined 3324 // register. 3325 if (Offset >= NumElts || Offset < 0) 3326 return std::make_pair(AMDGPU::sub0, Offset); 3327 3328 return std::make_pair(AMDGPU::sub0 + Offset, 0); 3329 } 3330 3331 // Return true if the index is an SGPR and was set. 3332 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3333 MachineRegisterInfo &MRI, 3334 MachineInstr &MI, 3335 int Offset, 3336 bool UseGPRIdxMode, 3337 bool IsIndirectSrc) { 3338 MachineBasicBlock *MBB = MI.getParent(); 3339 const DebugLoc &DL = MI.getDebugLoc(); 3340 MachineBasicBlock::iterator I(&MI); 3341 3342 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3343 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3344 3345 assert(Idx->getReg() != AMDGPU::NoRegister); 3346 3347 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3348 return false; 3349 3350 if (UseGPRIdxMode) { 3351 unsigned IdxMode = IsIndirectSrc ? 3352 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3353 if (Offset == 0) { 3354 MachineInstr *SetOn = 3355 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3356 .add(*Idx) 3357 .addImm(IdxMode); 3358 3359 SetOn->getOperand(3).setIsUndef(); 3360 } else { 3361 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3362 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3363 .add(*Idx) 3364 .addImm(Offset); 3365 MachineInstr *SetOn = 3366 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3367 .addReg(Tmp, RegState::Kill) 3368 .addImm(IdxMode); 3369 3370 SetOn->getOperand(3).setIsUndef(); 3371 } 3372 3373 return true; 3374 } 3375 3376 if (Offset == 0) { 3377 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3378 .add(*Idx); 3379 } else { 3380 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3381 .add(*Idx) 3382 .addImm(Offset); 3383 } 3384 3385 return true; 3386 } 3387 3388 // Control flow needs to be inserted if indexing with a VGPR. 3389 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3390 MachineBasicBlock &MBB, 3391 const GCNSubtarget &ST) { 3392 const SIInstrInfo *TII = ST.getInstrInfo(); 3393 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3394 MachineFunction *MF = MBB.getParent(); 3395 MachineRegisterInfo &MRI = MF->getRegInfo(); 3396 3397 Register Dst = MI.getOperand(0).getReg(); 3398 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3399 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3400 3401 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3402 3403 unsigned SubReg; 3404 std::tie(SubReg, Offset) 3405 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3406 3407 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 3408 3409 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3410 MachineBasicBlock::iterator I(&MI); 3411 const DebugLoc &DL = MI.getDebugLoc(); 3412 3413 if (UseGPRIdxMode) { 3414 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3415 // to avoid interfering with other uses, so probably requires a new 3416 // optimization pass. 3417 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3418 .addReg(SrcReg, RegState::Undef, SubReg) 3419 .addReg(SrcReg, RegState::Implicit) 3420 .addReg(AMDGPU::M0, RegState::Implicit); 3421 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3422 } else { 3423 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3424 .addReg(SrcReg, RegState::Undef, SubReg) 3425 .addReg(SrcReg, RegState::Implicit); 3426 } 3427 3428 MI.eraseFromParent(); 3429 3430 return &MBB; 3431 } 3432 3433 const DebugLoc &DL = MI.getDebugLoc(); 3434 MachineBasicBlock::iterator I(&MI); 3435 3436 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3437 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3438 3439 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3440 3441 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3442 Offset, UseGPRIdxMode, true); 3443 MachineBasicBlock *LoopBB = InsPt->getParent(); 3444 3445 if (UseGPRIdxMode) { 3446 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3447 .addReg(SrcReg, RegState::Undef, SubReg) 3448 .addReg(SrcReg, RegState::Implicit) 3449 .addReg(AMDGPU::M0, RegState::Implicit); 3450 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3451 } else { 3452 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3453 .addReg(SrcReg, RegState::Undef, SubReg) 3454 .addReg(SrcReg, RegState::Implicit); 3455 } 3456 3457 MI.eraseFromParent(); 3458 3459 return LoopBB; 3460 } 3461 3462 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI, 3463 const TargetRegisterClass *VecRC) { 3464 switch (TRI.getRegSizeInBits(*VecRC)) { 3465 case 32: // 4 bytes 3466 return AMDGPU::V_MOVRELD_B32_V1; 3467 case 64: // 8 bytes 3468 return AMDGPU::V_MOVRELD_B32_V2; 3469 case 128: // 16 bytes 3470 return AMDGPU::V_MOVRELD_B32_V4; 3471 case 256: // 32 bytes 3472 return AMDGPU::V_MOVRELD_B32_V8; 3473 case 512: // 64 bytes 3474 return AMDGPU::V_MOVRELD_B32_V16; 3475 default: 3476 llvm_unreachable("unsupported size for MOVRELD pseudos"); 3477 } 3478 } 3479 3480 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3481 MachineBasicBlock &MBB, 3482 const GCNSubtarget &ST) { 3483 const SIInstrInfo *TII = ST.getInstrInfo(); 3484 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3485 MachineFunction *MF = MBB.getParent(); 3486 MachineRegisterInfo &MRI = MF->getRegInfo(); 3487 3488 Register Dst = MI.getOperand(0).getReg(); 3489 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3490 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3491 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3492 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3493 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3494 3495 // This can be an immediate, but will be folded later. 3496 assert(Val->getReg()); 3497 3498 unsigned SubReg; 3499 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3500 SrcVec->getReg(), 3501 Offset); 3502 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 3503 3504 if (Idx->getReg() == AMDGPU::NoRegister) { 3505 MachineBasicBlock::iterator I(&MI); 3506 const DebugLoc &DL = MI.getDebugLoc(); 3507 3508 assert(Offset == 0); 3509 3510 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3511 .add(*SrcVec) 3512 .add(*Val) 3513 .addImm(SubReg); 3514 3515 MI.eraseFromParent(); 3516 return &MBB; 3517 } 3518 3519 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3520 MachineBasicBlock::iterator I(&MI); 3521 const DebugLoc &DL = MI.getDebugLoc(); 3522 3523 if (UseGPRIdxMode) { 3524 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 3525 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst 3526 .add(*Val) 3527 .addReg(Dst, RegState::ImplicitDefine) 3528 .addReg(SrcVec->getReg(), RegState::Implicit) 3529 .addReg(AMDGPU::M0, RegState::Implicit); 3530 3531 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3532 } else { 3533 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 3534 3535 BuildMI(MBB, I, DL, MovRelDesc) 3536 .addReg(Dst, RegState::Define) 3537 .addReg(SrcVec->getReg()) 3538 .add(*Val) 3539 .addImm(SubReg - AMDGPU::sub0); 3540 } 3541 3542 MI.eraseFromParent(); 3543 return &MBB; 3544 } 3545 3546 if (Val->isReg()) 3547 MRI.clearKillFlags(Val->getReg()); 3548 3549 const DebugLoc &DL = MI.getDebugLoc(); 3550 3551 Register PhiReg = MRI.createVirtualRegister(VecRC); 3552 3553 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3554 Offset, UseGPRIdxMode, false); 3555 MachineBasicBlock *LoopBB = InsPt->getParent(); 3556 3557 if (UseGPRIdxMode) { 3558 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 3559 .addReg(PhiReg, RegState::Undef, SubReg) // vdst 3560 .add(*Val) // src0 3561 .addReg(Dst, RegState::ImplicitDefine) 3562 .addReg(PhiReg, RegState::Implicit) 3563 .addReg(AMDGPU::M0, RegState::Implicit); 3564 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3565 } else { 3566 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 3567 3568 BuildMI(*LoopBB, InsPt, DL, MovRelDesc) 3569 .addReg(Dst, RegState::Define) 3570 .addReg(PhiReg) 3571 .add(*Val) 3572 .addImm(SubReg - AMDGPU::sub0); 3573 } 3574 3575 MI.eraseFromParent(); 3576 3577 return LoopBB; 3578 } 3579 3580 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3581 MachineInstr &MI, MachineBasicBlock *BB) const { 3582 3583 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3584 MachineFunction *MF = BB->getParent(); 3585 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3586 3587 if (TII->isMIMG(MI)) { 3588 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 3589 report_fatal_error("missing mem operand from MIMG instruction"); 3590 } 3591 // Add a memoperand for mimg instructions so that they aren't assumed to 3592 // be ordered memory instuctions. 3593 3594 return BB; 3595 } 3596 3597 switch (MI.getOpcode()) { 3598 case AMDGPU::S_ADD_U64_PSEUDO: 3599 case AMDGPU::S_SUB_U64_PSEUDO: { 3600 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3601 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3602 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3603 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3604 const DebugLoc &DL = MI.getDebugLoc(); 3605 3606 MachineOperand &Dest = MI.getOperand(0); 3607 MachineOperand &Src0 = MI.getOperand(1); 3608 MachineOperand &Src1 = MI.getOperand(2); 3609 3610 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3611 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3612 3613 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3614 Src0, BoolRC, AMDGPU::sub0, 3615 &AMDGPU::SReg_32RegClass); 3616 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3617 Src0, BoolRC, AMDGPU::sub1, 3618 &AMDGPU::SReg_32RegClass); 3619 3620 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3621 Src1, BoolRC, AMDGPU::sub0, 3622 &AMDGPU::SReg_32RegClass); 3623 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3624 Src1, BoolRC, AMDGPU::sub1, 3625 &AMDGPU::SReg_32RegClass); 3626 3627 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3628 3629 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3630 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3631 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3632 .add(Src0Sub0) 3633 .add(Src1Sub0); 3634 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3635 .add(Src0Sub1) 3636 .add(Src1Sub1); 3637 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3638 .addReg(DestSub0) 3639 .addImm(AMDGPU::sub0) 3640 .addReg(DestSub1) 3641 .addImm(AMDGPU::sub1); 3642 MI.eraseFromParent(); 3643 return BB; 3644 } 3645 case AMDGPU::SI_INIT_M0: { 3646 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3647 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3648 .add(MI.getOperand(0)); 3649 MI.eraseFromParent(); 3650 return BB; 3651 } 3652 case AMDGPU::SI_INIT_EXEC: 3653 // This should be before all vector instructions. 3654 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3655 AMDGPU::EXEC) 3656 .addImm(MI.getOperand(0).getImm()); 3657 MI.eraseFromParent(); 3658 return BB; 3659 3660 case AMDGPU::SI_INIT_EXEC_LO: 3661 // This should be before all vector instructions. 3662 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3663 AMDGPU::EXEC_LO) 3664 .addImm(MI.getOperand(0).getImm()); 3665 MI.eraseFromParent(); 3666 return BB; 3667 3668 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3669 // Extract the thread count from an SGPR input and set EXEC accordingly. 3670 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3671 // 3672 // S_BFE_U32 count, input, {shift, 7} 3673 // S_BFM_B64 exec, count, 0 3674 // S_CMP_EQ_U32 count, 64 3675 // S_CMOV_B64 exec, -1 3676 MachineInstr *FirstMI = &*BB->begin(); 3677 MachineRegisterInfo &MRI = MF->getRegInfo(); 3678 Register InputReg = MI.getOperand(0).getReg(); 3679 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3680 bool Found = false; 3681 3682 // Move the COPY of the input reg to the beginning, so that we can use it. 3683 for (auto I = BB->begin(); I != &MI; I++) { 3684 if (I->getOpcode() != TargetOpcode::COPY || 3685 I->getOperand(0).getReg() != InputReg) 3686 continue; 3687 3688 if (I == FirstMI) { 3689 FirstMI = &*++BB->begin(); 3690 } else { 3691 I->removeFromParent(); 3692 BB->insert(FirstMI, &*I); 3693 } 3694 Found = true; 3695 break; 3696 } 3697 assert(Found); 3698 (void)Found; 3699 3700 // This should be before all vector instructions. 3701 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3702 bool isWave32 = getSubtarget()->isWave32(); 3703 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3704 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3705 .addReg(InputReg) 3706 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3707 BuildMI(*BB, FirstMI, DebugLoc(), 3708 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3709 Exec) 3710 .addReg(CountReg) 3711 .addImm(0); 3712 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3713 .addReg(CountReg, RegState::Kill) 3714 .addImm(getSubtarget()->getWavefrontSize()); 3715 BuildMI(*BB, FirstMI, DebugLoc(), 3716 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3717 Exec) 3718 .addImm(-1); 3719 MI.eraseFromParent(); 3720 return BB; 3721 } 3722 3723 case AMDGPU::GET_GROUPSTATICSIZE: { 3724 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 3725 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 3726 DebugLoc DL = MI.getDebugLoc(); 3727 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3728 .add(MI.getOperand(0)) 3729 .addImm(MFI->getLDSSize()); 3730 MI.eraseFromParent(); 3731 return BB; 3732 } 3733 case AMDGPU::SI_INDIRECT_SRC_V1: 3734 case AMDGPU::SI_INDIRECT_SRC_V2: 3735 case AMDGPU::SI_INDIRECT_SRC_V4: 3736 case AMDGPU::SI_INDIRECT_SRC_V8: 3737 case AMDGPU::SI_INDIRECT_SRC_V16: 3738 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3739 case AMDGPU::SI_INDIRECT_DST_V1: 3740 case AMDGPU::SI_INDIRECT_DST_V2: 3741 case AMDGPU::SI_INDIRECT_DST_V4: 3742 case AMDGPU::SI_INDIRECT_DST_V8: 3743 case AMDGPU::SI_INDIRECT_DST_V16: 3744 return emitIndirectDst(MI, *BB, *getSubtarget()); 3745 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3746 case AMDGPU::SI_KILL_I1_PSEUDO: 3747 return splitKillBlock(MI, BB); 3748 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3749 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3750 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3751 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3752 3753 Register Dst = MI.getOperand(0).getReg(); 3754 Register Src0 = MI.getOperand(1).getReg(); 3755 Register Src1 = MI.getOperand(2).getReg(); 3756 const DebugLoc &DL = MI.getDebugLoc(); 3757 Register SrcCond = MI.getOperand(3).getReg(); 3758 3759 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3760 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3761 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3762 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 3763 3764 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3765 .addReg(SrcCond); 3766 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3767 .addImm(0) 3768 .addReg(Src0, 0, AMDGPU::sub0) 3769 .addImm(0) 3770 .addReg(Src1, 0, AMDGPU::sub0) 3771 .addReg(SrcCondCopy); 3772 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3773 .addImm(0) 3774 .addReg(Src0, 0, AMDGPU::sub1) 3775 .addImm(0) 3776 .addReg(Src1, 0, AMDGPU::sub1) 3777 .addReg(SrcCondCopy); 3778 3779 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3780 .addReg(DstLo) 3781 .addImm(AMDGPU::sub0) 3782 .addReg(DstHi) 3783 .addImm(AMDGPU::sub1); 3784 MI.eraseFromParent(); 3785 return BB; 3786 } 3787 case AMDGPU::SI_BR_UNDEF: { 3788 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3789 const DebugLoc &DL = MI.getDebugLoc(); 3790 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3791 .add(MI.getOperand(0)); 3792 Br->getOperand(1).setIsUndef(true); // read undef SCC 3793 MI.eraseFromParent(); 3794 return BB; 3795 } 3796 case AMDGPU::ADJCALLSTACKUP: 3797 case AMDGPU::ADJCALLSTACKDOWN: { 3798 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3799 MachineInstrBuilder MIB(*MF, &MI); 3800 3801 // Add an implicit use of the frame offset reg to prevent the restore copy 3802 // inserted after the call from being reorderd after stack operations in the 3803 // the caller's frame. 3804 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3805 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 3806 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 3807 return BB; 3808 } 3809 case AMDGPU::SI_CALL_ISEL: { 3810 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3811 const DebugLoc &DL = MI.getDebugLoc(); 3812 3813 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3814 3815 MachineInstrBuilder MIB; 3816 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 3817 3818 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 3819 MIB.add(MI.getOperand(I)); 3820 3821 MIB.cloneMemRefs(MI); 3822 MI.eraseFromParent(); 3823 return BB; 3824 } 3825 case AMDGPU::V_ADD_I32_e32: 3826 case AMDGPU::V_SUB_I32_e32: 3827 case AMDGPU::V_SUBREV_I32_e32: { 3828 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 3829 const DebugLoc &DL = MI.getDebugLoc(); 3830 unsigned Opc = MI.getOpcode(); 3831 3832 bool NeedClampOperand = false; 3833 if (TII->pseudoToMCOpcode(Opc) == -1) { 3834 Opc = AMDGPU::getVOPe64(Opc); 3835 NeedClampOperand = true; 3836 } 3837 3838 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 3839 if (TII->isVOP3(*I)) { 3840 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3841 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3842 I.addReg(TRI->getVCC(), RegState::Define); 3843 } 3844 I.add(MI.getOperand(1)) 3845 .add(MI.getOperand(2)); 3846 if (NeedClampOperand) 3847 I.addImm(0); // clamp bit for e64 encoding 3848 3849 TII->legalizeOperands(*I); 3850 3851 MI.eraseFromParent(); 3852 return BB; 3853 } 3854 case AMDGPU::DS_GWS_INIT: 3855 case AMDGPU::DS_GWS_SEMA_V: 3856 case AMDGPU::DS_GWS_SEMA_BR: 3857 case AMDGPU::DS_GWS_SEMA_P: 3858 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 3859 case AMDGPU::DS_GWS_BARRIER: 3860 // A s_waitcnt 0 is required to be the instruction immediately following. 3861 if (getSubtarget()->hasGWSAutoReplay()) { 3862 bundleInstWithWaitcnt(MI); 3863 return BB; 3864 } 3865 3866 return emitGWSMemViolTestLoop(MI, BB); 3867 default: 3868 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3869 } 3870 } 3871 3872 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 3873 return isTypeLegal(VT.getScalarType()); 3874 } 3875 3876 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3877 // This currently forces unfolding various combinations of fsub into fma with 3878 // free fneg'd operands. As long as we have fast FMA (controlled by 3879 // isFMAFasterThanFMulAndFAdd), we should perform these. 3880 3881 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3882 // most of these combines appear to be cycle neutral but save on instruction 3883 // count / code size. 3884 return true; 3885 } 3886 3887 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3888 EVT VT) const { 3889 if (!VT.isVector()) { 3890 return MVT::i1; 3891 } 3892 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3893 } 3894 3895 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3896 // TODO: Should i16 be used always if legal? For now it would force VALU 3897 // shifts. 3898 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3899 } 3900 3901 // Answering this is somewhat tricky and depends on the specific device which 3902 // have different rates for fma or all f64 operations. 3903 // 3904 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3905 // regardless of which device (although the number of cycles differs between 3906 // devices), so it is always profitable for f64. 3907 // 3908 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3909 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3910 // which we can always do even without fused FP ops since it returns the same 3911 // result as the separate operations and since it is always full 3912 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3913 // however does not support denormals, so we do report fma as faster if we have 3914 // a fast fma device and require denormals. 3915 // 3916 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 3917 VT = VT.getScalarType(); 3918 3919 switch (VT.getSimpleVT().SimpleTy) { 3920 case MVT::f32: { 3921 // This is as fast on some subtargets. However, we always have full rate f32 3922 // mad available which returns the same result as the separate operations 3923 // which we should prefer over fma. We can't use this if we want to support 3924 // denormals, so only report this in these cases. 3925 if (Subtarget->hasFP32Denormals()) 3926 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 3927 3928 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 3929 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 3930 } 3931 case MVT::f64: 3932 return true; 3933 case MVT::f16: 3934 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals(); 3935 default: 3936 break; 3937 } 3938 3939 return false; 3940 } 3941 3942 bool SITargetLowering::isFMADLegalForFAddFSub(const SelectionDAG &DAG, 3943 const SDNode *N) const { 3944 // TODO: Check future ftz flag 3945 // v_mad_f32/v_mac_f32 do not support denormals. 3946 EVT VT = N->getValueType(0); 3947 if (VT == MVT::f32) 3948 return !Subtarget->hasFP32Denormals(); 3949 if (VT == MVT::f16) 3950 return !Subtarget->hasFP16Denormals() && Subtarget->hasMadF16(); 3951 3952 return false; 3953 } 3954 3955 //===----------------------------------------------------------------------===// 3956 // Custom DAG Lowering Operations 3957 //===----------------------------------------------------------------------===// 3958 3959 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3960 // wider vector type is legal. 3961 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 3962 SelectionDAG &DAG) const { 3963 unsigned Opc = Op.getOpcode(); 3964 EVT VT = Op.getValueType(); 3965 assert(VT == MVT::v4f16); 3966 3967 SDValue Lo, Hi; 3968 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 3969 3970 SDLoc SL(Op); 3971 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 3972 Op->getFlags()); 3973 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 3974 Op->getFlags()); 3975 3976 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3977 } 3978 3979 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3980 // wider vector type is legal. 3981 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 3982 SelectionDAG &DAG) const { 3983 unsigned Opc = Op.getOpcode(); 3984 EVT VT = Op.getValueType(); 3985 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 3986 3987 SDValue Lo0, Hi0; 3988 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 3989 SDValue Lo1, Hi1; 3990 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 3991 3992 SDLoc SL(Op); 3993 3994 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 3995 Op->getFlags()); 3996 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 3997 Op->getFlags()); 3998 3999 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4000 } 4001 4002 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4003 SelectionDAG &DAG) const { 4004 unsigned Opc = Op.getOpcode(); 4005 EVT VT = Op.getValueType(); 4006 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4007 4008 SDValue Lo0, Hi0; 4009 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4010 SDValue Lo1, Hi1; 4011 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4012 SDValue Lo2, Hi2; 4013 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4014 4015 SDLoc SL(Op); 4016 4017 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4018 Op->getFlags()); 4019 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4020 Op->getFlags()); 4021 4022 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4023 } 4024 4025 4026 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4027 switch (Op.getOpcode()) { 4028 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4029 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4030 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4031 case ISD::LOAD: { 4032 SDValue Result = LowerLOAD(Op, DAG); 4033 assert((!Result.getNode() || 4034 Result.getNode()->getNumValues() == 2) && 4035 "Load should return a value and a chain"); 4036 return Result; 4037 } 4038 4039 case ISD::FSIN: 4040 case ISD::FCOS: 4041 return LowerTrig(Op, DAG); 4042 case ISD::SELECT: return LowerSELECT(Op, DAG); 4043 case ISD::FDIV: return LowerFDIV(Op, DAG); 4044 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4045 case ISD::STORE: return LowerSTORE(Op, DAG); 4046 case ISD::GlobalAddress: { 4047 MachineFunction &MF = DAG.getMachineFunction(); 4048 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4049 return LowerGlobalAddress(MFI, Op, DAG); 4050 } 4051 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4052 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4053 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4054 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4055 case ISD::INSERT_SUBVECTOR: 4056 return lowerINSERT_SUBVECTOR(Op, DAG); 4057 case ISD::INSERT_VECTOR_ELT: 4058 return lowerINSERT_VECTOR_ELT(Op, DAG); 4059 case ISD::EXTRACT_VECTOR_ELT: 4060 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4061 case ISD::VECTOR_SHUFFLE: 4062 return lowerVECTOR_SHUFFLE(Op, DAG); 4063 case ISD::BUILD_VECTOR: 4064 return lowerBUILD_VECTOR(Op, DAG); 4065 case ISD::FP_ROUND: 4066 return lowerFP_ROUND(Op, DAG); 4067 case ISD::TRAP: 4068 return lowerTRAP(Op, DAG); 4069 case ISD::DEBUGTRAP: 4070 return lowerDEBUGTRAP(Op, DAG); 4071 case ISD::FABS: 4072 case ISD::FNEG: 4073 case ISD::FCANONICALIZE: 4074 return splitUnaryVectorOp(Op, DAG); 4075 case ISD::FMINNUM: 4076 case ISD::FMAXNUM: 4077 return lowerFMINNUM_FMAXNUM(Op, DAG); 4078 case ISD::FMA: 4079 return splitTernaryVectorOp(Op, DAG); 4080 case ISD::SHL: 4081 case ISD::SRA: 4082 case ISD::SRL: 4083 case ISD::ADD: 4084 case ISD::SUB: 4085 case ISD::MUL: 4086 case ISD::SMIN: 4087 case ISD::SMAX: 4088 case ISD::UMIN: 4089 case ISD::UMAX: 4090 case ISD::FADD: 4091 case ISD::FMUL: 4092 case ISD::FMINNUM_IEEE: 4093 case ISD::FMAXNUM_IEEE: 4094 return splitBinaryVectorOp(Op, DAG); 4095 } 4096 return SDValue(); 4097 } 4098 4099 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4100 const SDLoc &DL, 4101 SelectionDAG &DAG, bool Unpacked) { 4102 if (!LoadVT.isVector()) 4103 return Result; 4104 4105 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4106 // Truncate to v2i16/v4i16. 4107 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4108 4109 // Workaround legalizer not scalarizing truncate after vector op 4110 // legalization byt not creating intermediate vector trunc. 4111 SmallVector<SDValue, 4> Elts; 4112 DAG.ExtractVectorElements(Result, Elts); 4113 for (SDValue &Elt : Elts) 4114 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4115 4116 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4117 4118 // Bitcast to original type (v2f16/v4f16). 4119 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4120 } 4121 4122 // Cast back to the original packed type. 4123 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4124 } 4125 4126 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4127 MemSDNode *M, 4128 SelectionDAG &DAG, 4129 ArrayRef<SDValue> Ops, 4130 bool IsIntrinsic) const { 4131 SDLoc DL(M); 4132 4133 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4134 EVT LoadVT = M->getValueType(0); 4135 4136 EVT EquivLoadVT = LoadVT; 4137 if (Unpacked && LoadVT.isVector()) { 4138 EquivLoadVT = LoadVT.isVector() ? 4139 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4140 LoadVT.getVectorNumElements()) : LoadVT; 4141 } 4142 4143 // Change from v4f16/v2f16 to EquivLoadVT. 4144 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4145 4146 SDValue Load 4147 = DAG.getMemIntrinsicNode( 4148 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4149 VTList, Ops, M->getMemoryVT(), 4150 M->getMemOperand()); 4151 if (!Unpacked) // Just adjusted the opcode. 4152 return Load; 4153 4154 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4155 4156 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4157 } 4158 4159 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4160 SelectionDAG &DAG, 4161 ArrayRef<SDValue> Ops) const { 4162 SDLoc DL(M); 4163 EVT LoadVT = M->getValueType(0); 4164 EVT EltType = LoadVT.getScalarType(); 4165 EVT IntVT = LoadVT.changeTypeToInteger(); 4166 4167 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4168 4169 unsigned Opc = 4170 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4171 4172 if (IsD16) { 4173 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4174 } 4175 4176 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4177 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4178 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4179 4180 if (isTypeLegal(LoadVT)) { 4181 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4182 M->getMemOperand(), DAG); 4183 } 4184 4185 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4186 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4187 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4188 M->getMemOperand(), DAG); 4189 return DAG.getMergeValues( 4190 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4191 DL); 4192 } 4193 4194 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4195 SDNode *N, SelectionDAG &DAG) { 4196 EVT VT = N->getValueType(0); 4197 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4198 int CondCode = CD->getSExtValue(); 4199 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4200 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4201 return DAG.getUNDEF(VT); 4202 4203 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4204 4205 SDValue LHS = N->getOperand(1); 4206 SDValue RHS = N->getOperand(2); 4207 4208 SDLoc DL(N); 4209 4210 EVT CmpVT = LHS.getValueType(); 4211 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4212 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4213 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4214 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4215 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4216 } 4217 4218 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4219 4220 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4221 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4222 4223 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4224 DAG.getCondCode(CCOpcode)); 4225 if (VT.bitsEq(CCVT)) 4226 return SetCC; 4227 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4228 } 4229 4230 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4231 SDNode *N, SelectionDAG &DAG) { 4232 EVT VT = N->getValueType(0); 4233 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4234 4235 int CondCode = CD->getSExtValue(); 4236 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4237 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4238 return DAG.getUNDEF(VT); 4239 } 4240 4241 SDValue Src0 = N->getOperand(1); 4242 SDValue Src1 = N->getOperand(2); 4243 EVT CmpVT = Src0.getValueType(); 4244 SDLoc SL(N); 4245 4246 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4247 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4248 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4249 } 4250 4251 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4252 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4253 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4254 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4255 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4256 Src1, DAG.getCondCode(CCOpcode)); 4257 if (VT.bitsEq(CCVT)) 4258 return SetCC; 4259 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4260 } 4261 4262 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4263 SmallVectorImpl<SDValue> &Results, 4264 SelectionDAG &DAG) const { 4265 switch (N->getOpcode()) { 4266 case ISD::INSERT_VECTOR_ELT: { 4267 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4268 Results.push_back(Res); 4269 return; 4270 } 4271 case ISD::EXTRACT_VECTOR_ELT: { 4272 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4273 Results.push_back(Res); 4274 return; 4275 } 4276 case ISD::INTRINSIC_WO_CHAIN: { 4277 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4278 switch (IID) { 4279 case Intrinsic::amdgcn_cvt_pkrtz: { 4280 SDValue Src0 = N->getOperand(1); 4281 SDValue Src1 = N->getOperand(2); 4282 SDLoc SL(N); 4283 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4284 Src0, Src1); 4285 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4286 return; 4287 } 4288 case Intrinsic::amdgcn_cvt_pknorm_i16: 4289 case Intrinsic::amdgcn_cvt_pknorm_u16: 4290 case Intrinsic::amdgcn_cvt_pk_i16: 4291 case Intrinsic::amdgcn_cvt_pk_u16: { 4292 SDValue Src0 = N->getOperand(1); 4293 SDValue Src1 = N->getOperand(2); 4294 SDLoc SL(N); 4295 unsigned Opcode; 4296 4297 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4298 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4299 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4300 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4301 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4302 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4303 else 4304 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4305 4306 EVT VT = N->getValueType(0); 4307 if (isTypeLegal(VT)) 4308 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4309 else { 4310 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4311 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4312 } 4313 return; 4314 } 4315 } 4316 break; 4317 } 4318 case ISD::INTRINSIC_W_CHAIN: { 4319 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4320 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4321 // FIXME: Hacky 4322 Results.push_back(Res.getOperand(0)); 4323 Results.push_back(Res.getOperand(1)); 4324 } else { 4325 Results.push_back(Res); 4326 Results.push_back(Res.getValue(1)); 4327 } 4328 return; 4329 } 4330 4331 break; 4332 } 4333 case ISD::SELECT: { 4334 SDLoc SL(N); 4335 EVT VT = N->getValueType(0); 4336 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4337 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4338 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4339 4340 EVT SelectVT = NewVT; 4341 if (NewVT.bitsLT(MVT::i32)) { 4342 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4343 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4344 SelectVT = MVT::i32; 4345 } 4346 4347 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4348 N->getOperand(0), LHS, RHS); 4349 4350 if (NewVT != SelectVT) 4351 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4352 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4353 return; 4354 } 4355 case ISD::FNEG: { 4356 if (N->getValueType(0) != MVT::v2f16) 4357 break; 4358 4359 SDLoc SL(N); 4360 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4361 4362 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4363 BC, 4364 DAG.getConstant(0x80008000, SL, MVT::i32)); 4365 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4366 return; 4367 } 4368 case ISD::FABS: { 4369 if (N->getValueType(0) != MVT::v2f16) 4370 break; 4371 4372 SDLoc SL(N); 4373 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4374 4375 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4376 BC, 4377 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4378 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4379 return; 4380 } 4381 default: 4382 break; 4383 } 4384 } 4385 4386 /// Helper function for LowerBRCOND 4387 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4388 4389 SDNode *Parent = Value.getNode(); 4390 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4391 I != E; ++I) { 4392 4393 if (I.getUse().get() != Value) 4394 continue; 4395 4396 if (I->getOpcode() == Opcode) 4397 return *I; 4398 } 4399 return nullptr; 4400 } 4401 4402 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4403 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4404 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4405 case Intrinsic::amdgcn_if: 4406 return AMDGPUISD::IF; 4407 case Intrinsic::amdgcn_else: 4408 return AMDGPUISD::ELSE; 4409 case Intrinsic::amdgcn_loop: 4410 return AMDGPUISD::LOOP; 4411 case Intrinsic::amdgcn_end_cf: 4412 llvm_unreachable("should not occur"); 4413 default: 4414 return 0; 4415 } 4416 } 4417 4418 // break, if_break, else_break are all only used as inputs to loop, not 4419 // directly as branch conditions. 4420 return 0; 4421 } 4422 4423 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4424 const Triple &TT = getTargetMachine().getTargetTriple(); 4425 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4426 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4427 AMDGPU::shouldEmitConstantsToTextSection(TT); 4428 } 4429 4430 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4431 // FIXME: Either avoid relying on address space here or change the default 4432 // address space for functions to avoid the explicit check. 4433 return (GV->getValueType()->isFunctionTy() || 4434 GV->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 4435 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4436 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4437 !shouldEmitFixup(GV) && 4438 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4439 } 4440 4441 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4442 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4443 } 4444 4445 /// This transforms the control flow intrinsics to get the branch destination as 4446 /// last parameter, also switches branch target with BR if the need arise 4447 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4448 SelectionDAG &DAG) const { 4449 SDLoc DL(BRCOND); 4450 4451 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4452 SDValue Target = BRCOND.getOperand(2); 4453 SDNode *BR = nullptr; 4454 SDNode *SetCC = nullptr; 4455 4456 if (Intr->getOpcode() == ISD::SETCC) { 4457 // As long as we negate the condition everything is fine 4458 SetCC = Intr; 4459 Intr = SetCC->getOperand(0).getNode(); 4460 4461 } else { 4462 // Get the target from BR if we don't negate the condition 4463 BR = findUser(BRCOND, ISD::BR); 4464 Target = BR->getOperand(1); 4465 } 4466 4467 // FIXME: This changes the types of the intrinsics instead of introducing new 4468 // nodes with the correct types. 4469 // e.g. llvm.amdgcn.loop 4470 4471 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 4472 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 4473 4474 unsigned CFNode = isCFIntrinsic(Intr); 4475 if (CFNode == 0) { 4476 // This is a uniform branch so we don't need to legalize. 4477 return BRCOND; 4478 } 4479 4480 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4481 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4482 4483 assert(!SetCC || 4484 (SetCC->getConstantOperandVal(1) == 1 && 4485 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4486 ISD::SETNE)); 4487 4488 // operands of the new intrinsic call 4489 SmallVector<SDValue, 4> Ops; 4490 if (HaveChain) 4491 Ops.push_back(BRCOND.getOperand(0)); 4492 4493 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4494 Ops.push_back(Target); 4495 4496 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4497 4498 // build the new intrinsic call 4499 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4500 4501 if (!HaveChain) { 4502 SDValue Ops[] = { 4503 SDValue(Result, 0), 4504 BRCOND.getOperand(0) 4505 }; 4506 4507 Result = DAG.getMergeValues(Ops, DL).getNode(); 4508 } 4509 4510 if (BR) { 4511 // Give the branch instruction our target 4512 SDValue Ops[] = { 4513 BR->getOperand(0), 4514 BRCOND.getOperand(2) 4515 }; 4516 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4517 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4518 BR = NewBR.getNode(); 4519 } 4520 4521 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4522 4523 // Copy the intrinsic results to registers 4524 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4525 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4526 if (!CopyToReg) 4527 continue; 4528 4529 Chain = DAG.getCopyToReg( 4530 Chain, DL, 4531 CopyToReg->getOperand(1), 4532 SDValue(Result, i - 1), 4533 SDValue()); 4534 4535 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4536 } 4537 4538 // Remove the old intrinsic from the chain 4539 DAG.ReplaceAllUsesOfValueWith( 4540 SDValue(Intr, Intr->getNumValues() - 1), 4541 Intr->getOperand(0)); 4542 4543 return Chain; 4544 } 4545 4546 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4547 SelectionDAG &DAG) const { 4548 MVT VT = Op.getSimpleValueType(); 4549 SDLoc DL(Op); 4550 // Checking the depth 4551 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4552 return DAG.getConstant(0, DL, VT); 4553 4554 MachineFunction &MF = DAG.getMachineFunction(); 4555 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4556 // Check for kernel and shader functions 4557 if (Info->isEntryFunction()) 4558 return DAG.getConstant(0, DL, VT); 4559 4560 MachineFrameInfo &MFI = MF.getFrameInfo(); 4561 // There is a call to @llvm.returnaddress in this function 4562 MFI.setReturnAddressIsTaken(true); 4563 4564 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4565 // Get the return address reg and mark it as an implicit live-in 4566 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4567 4568 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4569 } 4570 4571 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 4572 SDValue Op, 4573 const SDLoc &DL, 4574 EVT VT) const { 4575 return Op.getValueType().bitsLE(VT) ? 4576 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4577 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 4578 } 4579 4580 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4581 assert(Op.getValueType() == MVT::f16 && 4582 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4583 4584 SDValue Src = Op.getOperand(0); 4585 EVT SrcVT = Src.getValueType(); 4586 if (SrcVT != MVT::f64) 4587 return Op; 4588 4589 SDLoc DL(Op); 4590 4591 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4592 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4593 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4594 } 4595 4596 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4597 SelectionDAG &DAG) const { 4598 EVT VT = Op.getValueType(); 4599 const MachineFunction &MF = DAG.getMachineFunction(); 4600 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4601 bool IsIEEEMode = Info->getMode().IEEE; 4602 4603 // FIXME: Assert during eslection that this is only selected for 4604 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4605 // mode functions, but this happens to be OK since it's only done in cases 4606 // where there is known no sNaN. 4607 if (IsIEEEMode) 4608 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 4609 4610 if (VT == MVT::v4f16) 4611 return splitBinaryVectorOp(Op, DAG); 4612 return Op; 4613 } 4614 4615 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4616 SDLoc SL(Op); 4617 SDValue Chain = Op.getOperand(0); 4618 4619 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4620 !Subtarget->isTrapHandlerEnabled()) 4621 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4622 4623 MachineFunction &MF = DAG.getMachineFunction(); 4624 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4625 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4626 assert(UserSGPR != AMDGPU::NoRegister); 4627 SDValue QueuePtr = CreateLiveInRegister( 4628 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4629 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4630 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4631 QueuePtr, SDValue()); 4632 SDValue Ops[] = { 4633 ToReg, 4634 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 4635 SGPR01, 4636 ToReg.getValue(1) 4637 }; 4638 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4639 } 4640 4641 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 4642 SDLoc SL(Op); 4643 SDValue Chain = Op.getOperand(0); 4644 MachineFunction &MF = DAG.getMachineFunction(); 4645 4646 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4647 !Subtarget->isTrapHandlerEnabled()) { 4648 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4649 "debugtrap handler not supported", 4650 Op.getDebugLoc(), 4651 DS_Warning); 4652 LLVMContext &Ctx = MF.getFunction().getContext(); 4653 Ctx.diagnose(NoTrap); 4654 return Chain; 4655 } 4656 4657 SDValue Ops[] = { 4658 Chain, 4659 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 4660 }; 4661 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4662 } 4663 4664 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4665 SelectionDAG &DAG) const { 4666 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4667 if (Subtarget->hasApertureRegs()) { 4668 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 4669 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4670 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4671 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 4672 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4673 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4674 unsigned Encoding = 4675 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4676 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4677 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4678 4679 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4680 SDValue ApertureReg = SDValue( 4681 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4682 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4683 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4684 } 4685 4686 MachineFunction &MF = DAG.getMachineFunction(); 4687 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4688 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4689 assert(UserSGPR != AMDGPU::NoRegister); 4690 4691 SDValue QueuePtr = CreateLiveInRegister( 4692 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4693 4694 // Offset into amd_queue_t for group_segment_aperture_base_hi / 4695 // private_segment_aperture_base_hi. 4696 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 4697 4698 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 4699 4700 // TODO: Use custom target PseudoSourceValue. 4701 // TODO: We should use the value from the IR intrinsic call, but it might not 4702 // be available and how do we get it? 4703 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()), 4704 AMDGPUAS::CONSTANT_ADDRESS)); 4705 4706 MachinePointerInfo PtrInfo(V, StructOffset); 4707 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4708 MinAlign(64, StructOffset), 4709 MachineMemOperand::MODereferenceable | 4710 MachineMemOperand::MOInvariant); 4711 } 4712 4713 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4714 SelectionDAG &DAG) const { 4715 SDLoc SL(Op); 4716 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4717 4718 SDValue Src = ASC->getOperand(0); 4719 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4720 4721 const AMDGPUTargetMachine &TM = 4722 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4723 4724 // flat -> local/private 4725 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4726 unsigned DestAS = ASC->getDestAddressSpace(); 4727 4728 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 4729 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 4730 unsigned NullVal = TM.getNullPointerValue(DestAS); 4731 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4732 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4733 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4734 4735 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4736 NonNull, Ptr, SegmentNullPtr); 4737 } 4738 } 4739 4740 // local/private -> flat 4741 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4742 unsigned SrcAS = ASC->getSrcAddressSpace(); 4743 4744 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 4745 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 4746 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4747 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4748 4749 SDValue NonNull 4750 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4751 4752 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4753 SDValue CvtPtr 4754 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4755 4756 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4757 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4758 FlatNullPtr); 4759 } 4760 } 4761 4762 // global <-> flat are no-ops and never emitted. 4763 4764 const MachineFunction &MF = DAG.getMachineFunction(); 4765 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 4766 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 4767 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 4768 4769 return DAG.getUNDEF(ASC->getValueType(0)); 4770 } 4771 4772 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 4773 // the small vector and inserting them into the big vector. That is better than 4774 // the default expansion of doing it via a stack slot. Even though the use of 4775 // the stack slot would be optimized away afterwards, the stack slot itself 4776 // remains. 4777 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4778 SelectionDAG &DAG) const { 4779 SDValue Vec = Op.getOperand(0); 4780 SDValue Ins = Op.getOperand(1); 4781 SDValue Idx = Op.getOperand(2); 4782 EVT VecVT = Vec.getValueType(); 4783 EVT InsVT = Ins.getValueType(); 4784 EVT EltVT = VecVT.getVectorElementType(); 4785 unsigned InsNumElts = InsVT.getVectorNumElements(); 4786 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 4787 SDLoc SL(Op); 4788 4789 for (unsigned I = 0; I != InsNumElts; ++I) { 4790 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 4791 DAG.getConstant(I, SL, MVT::i32)); 4792 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 4793 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 4794 } 4795 return Vec; 4796 } 4797 4798 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4799 SelectionDAG &DAG) const { 4800 SDValue Vec = Op.getOperand(0); 4801 SDValue InsVal = Op.getOperand(1); 4802 SDValue Idx = Op.getOperand(2); 4803 EVT VecVT = Vec.getValueType(); 4804 EVT EltVT = VecVT.getVectorElementType(); 4805 unsigned VecSize = VecVT.getSizeInBits(); 4806 unsigned EltSize = EltVT.getSizeInBits(); 4807 4808 4809 assert(VecSize <= 64); 4810 4811 unsigned NumElts = VecVT.getVectorNumElements(); 4812 SDLoc SL(Op); 4813 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 4814 4815 if (NumElts == 4 && EltSize == 16 && KIdx) { 4816 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 4817 4818 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4819 DAG.getConstant(0, SL, MVT::i32)); 4820 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4821 DAG.getConstant(1, SL, MVT::i32)); 4822 4823 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 4824 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 4825 4826 unsigned Idx = KIdx->getZExtValue(); 4827 bool InsertLo = Idx < 2; 4828 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 4829 InsertLo ? LoVec : HiVec, 4830 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 4831 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 4832 4833 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 4834 4835 SDValue Concat = InsertLo ? 4836 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 4837 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 4838 4839 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 4840 } 4841 4842 if (isa<ConstantSDNode>(Idx)) 4843 return SDValue(); 4844 4845 MVT IntVT = MVT::getIntegerVT(VecSize); 4846 4847 // Avoid stack access for dynamic indexing. 4848 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 4849 4850 // Create a congruent vector with the target value in each element so that 4851 // the required element can be masked and ORed into the target vector. 4852 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 4853 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 4854 4855 assert(isPowerOf2_32(EltSize)); 4856 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4857 4858 // Convert vector index to bit-index. 4859 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4860 4861 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4862 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 4863 DAG.getConstant(0xffff, SL, IntVT), 4864 ScaledIdx); 4865 4866 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 4867 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 4868 DAG.getNOT(SL, BFM, IntVT), BCVec); 4869 4870 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 4871 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 4872 } 4873 4874 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4875 SelectionDAG &DAG) const { 4876 SDLoc SL(Op); 4877 4878 EVT ResultVT = Op.getValueType(); 4879 SDValue Vec = Op.getOperand(0); 4880 SDValue Idx = Op.getOperand(1); 4881 EVT VecVT = Vec.getValueType(); 4882 unsigned VecSize = VecVT.getSizeInBits(); 4883 EVT EltVT = VecVT.getVectorElementType(); 4884 assert(VecSize <= 64); 4885 4886 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 4887 4888 // Make sure we do any optimizations that will make it easier to fold 4889 // source modifiers before obscuring it with bit operations. 4890 4891 // XXX - Why doesn't this get called when vector_shuffle is expanded? 4892 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 4893 return Combined; 4894 4895 unsigned EltSize = EltVT.getSizeInBits(); 4896 assert(isPowerOf2_32(EltSize)); 4897 4898 MVT IntVT = MVT::getIntegerVT(VecSize); 4899 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4900 4901 // Convert vector index to bit-index (* EltSize) 4902 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4903 4904 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4905 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 4906 4907 if (ResultVT == MVT::f16) { 4908 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 4909 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 4910 } 4911 4912 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 4913 } 4914 4915 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 4916 assert(Elt % 2 == 0); 4917 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 4918 } 4919 4920 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 4921 SelectionDAG &DAG) const { 4922 SDLoc SL(Op); 4923 EVT ResultVT = Op.getValueType(); 4924 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 4925 4926 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 4927 EVT EltVT = PackVT.getVectorElementType(); 4928 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 4929 4930 // vector_shuffle <0,1,6,7> lhs, rhs 4931 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 4932 // 4933 // vector_shuffle <6,7,2,3> lhs, rhs 4934 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 4935 // 4936 // vector_shuffle <6,7,0,1> lhs, rhs 4937 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 4938 4939 // Avoid scalarizing when both halves are reading from consecutive elements. 4940 SmallVector<SDValue, 4> Pieces; 4941 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 4942 if (elementPairIsContiguous(SVN->getMask(), I)) { 4943 const int Idx = SVN->getMaskElt(I); 4944 int VecIdx = Idx < SrcNumElts ? 0 : 1; 4945 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 4946 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 4947 PackVT, SVN->getOperand(VecIdx), 4948 DAG.getConstant(EltIdx, SL, MVT::i32)); 4949 Pieces.push_back(SubVec); 4950 } else { 4951 const int Idx0 = SVN->getMaskElt(I); 4952 const int Idx1 = SVN->getMaskElt(I + 1); 4953 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 4954 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 4955 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 4956 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 4957 4958 SDValue Vec0 = SVN->getOperand(VecIdx0); 4959 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4960 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 4961 4962 SDValue Vec1 = SVN->getOperand(VecIdx1); 4963 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4964 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 4965 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 4966 } 4967 } 4968 4969 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 4970 } 4971 4972 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 4973 SelectionDAG &DAG) const { 4974 SDLoc SL(Op); 4975 EVT VT = Op.getValueType(); 4976 4977 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 4978 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 4979 4980 // Turn into pair of packed build_vectors. 4981 // TODO: Special case for constants that can be materialized with s_mov_b64. 4982 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 4983 { Op.getOperand(0), Op.getOperand(1) }); 4984 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 4985 { Op.getOperand(2), Op.getOperand(3) }); 4986 4987 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 4988 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 4989 4990 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 4991 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 4992 } 4993 4994 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 4995 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 4996 4997 SDValue Lo = Op.getOperand(0); 4998 SDValue Hi = Op.getOperand(1); 4999 5000 // Avoid adding defined bits with the zero_extend. 5001 if (Hi.isUndef()) { 5002 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5003 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5004 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5005 } 5006 5007 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5008 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5009 5010 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5011 DAG.getConstant(16, SL, MVT::i32)); 5012 if (Lo.isUndef()) 5013 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5014 5015 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5016 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5017 5018 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5019 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5020 } 5021 5022 bool 5023 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5024 // We can fold offsets for anything that doesn't require a GOT relocation. 5025 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5026 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5027 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5028 !shouldEmitGOTReloc(GA->getGlobal()); 5029 } 5030 5031 static SDValue 5032 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5033 const SDLoc &DL, unsigned Offset, EVT PtrVT, 5034 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5035 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5036 // lowered to the following code sequence: 5037 // 5038 // For constant address space: 5039 // s_getpc_b64 s[0:1] 5040 // s_add_u32 s0, s0, $symbol 5041 // s_addc_u32 s1, s1, 0 5042 // 5043 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5044 // a fixup or relocation is emitted to replace $symbol with a literal 5045 // constant, which is a pc-relative offset from the encoding of the $symbol 5046 // operand to the global variable. 5047 // 5048 // For global address space: 5049 // s_getpc_b64 s[0:1] 5050 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5051 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5052 // 5053 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5054 // fixups or relocations are emitted to replace $symbol@*@lo and 5055 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5056 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5057 // operand to the global variable. 5058 // 5059 // What we want here is an offset from the value returned by s_getpc 5060 // (which is the address of the s_add_u32 instruction) to the global 5061 // variable, but since the encoding of $symbol starts 4 bytes after the start 5062 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5063 // small. This requires us to add 4 to the global variable offset in order to 5064 // compute the correct address. 5065 SDValue PtrLo = 5066 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5067 SDValue PtrHi; 5068 if (GAFlags == SIInstrInfo::MO_NONE) { 5069 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5070 } else { 5071 PtrHi = 5072 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5073 } 5074 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5075 } 5076 5077 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5078 SDValue Op, 5079 SelectionDAG &DAG) const { 5080 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5081 const GlobalValue *GV = GSD->getGlobal(); 5082 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5083 (!GV->hasExternalLinkage() || 5084 getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 5085 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL)) || 5086 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5087 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5088 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5089 5090 SDLoc DL(GSD); 5091 EVT PtrVT = Op.getValueType(); 5092 5093 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5094 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5095 SIInstrInfo::MO_ABS32_LO); 5096 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5097 } 5098 5099 if (shouldEmitFixup(GV)) 5100 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5101 else if (shouldEmitPCReloc(GV)) 5102 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5103 SIInstrInfo::MO_REL32); 5104 5105 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5106 SIInstrInfo::MO_GOTPCREL32); 5107 5108 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5109 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5110 const DataLayout &DataLayout = DAG.getDataLayout(); 5111 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 5112 MachinePointerInfo PtrInfo 5113 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5114 5115 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 5116 MachineMemOperand::MODereferenceable | 5117 MachineMemOperand::MOInvariant); 5118 } 5119 5120 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5121 const SDLoc &DL, SDValue V) const { 5122 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5123 // the destination register. 5124 // 5125 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5126 // so we will end up with redundant moves to m0. 5127 // 5128 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5129 5130 // A Null SDValue creates a glue result. 5131 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5132 V, Chain); 5133 return SDValue(M0, 0); 5134 } 5135 5136 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5137 SDValue Op, 5138 MVT VT, 5139 unsigned Offset) const { 5140 SDLoc SL(Op); 5141 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 5142 DAG.getEntryNode(), Offset, 4, false); 5143 // The local size values will have the hi 16-bits as zero. 5144 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5145 DAG.getValueType(VT)); 5146 } 5147 5148 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5149 EVT VT) { 5150 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5151 "non-hsa intrinsic with hsa target", 5152 DL.getDebugLoc()); 5153 DAG.getContext()->diagnose(BadIntrin); 5154 return DAG.getUNDEF(VT); 5155 } 5156 5157 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5158 EVT VT) { 5159 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5160 "intrinsic not supported on subtarget", 5161 DL.getDebugLoc()); 5162 DAG.getContext()->diagnose(BadIntrin); 5163 return DAG.getUNDEF(VT); 5164 } 5165 5166 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5167 ArrayRef<SDValue> Elts) { 5168 assert(!Elts.empty()); 5169 MVT Type; 5170 unsigned NumElts; 5171 5172 if (Elts.size() == 1) { 5173 Type = MVT::f32; 5174 NumElts = 1; 5175 } else if (Elts.size() == 2) { 5176 Type = MVT::v2f32; 5177 NumElts = 2; 5178 } else if (Elts.size() <= 4) { 5179 Type = MVT::v4f32; 5180 NumElts = 4; 5181 } else if (Elts.size() <= 8) { 5182 Type = MVT::v8f32; 5183 NumElts = 8; 5184 } else { 5185 assert(Elts.size() <= 16); 5186 Type = MVT::v16f32; 5187 NumElts = 16; 5188 } 5189 5190 SmallVector<SDValue, 16> VecElts(NumElts); 5191 for (unsigned i = 0; i < Elts.size(); ++i) { 5192 SDValue Elt = Elts[i]; 5193 if (Elt.getValueType() != MVT::f32) 5194 Elt = DAG.getBitcast(MVT::f32, Elt); 5195 VecElts[i] = Elt; 5196 } 5197 for (unsigned i = Elts.size(); i < NumElts; ++i) 5198 VecElts[i] = DAG.getUNDEF(MVT::f32); 5199 5200 if (NumElts == 1) 5201 return VecElts[0]; 5202 return DAG.getBuildVector(Type, DL, VecElts); 5203 } 5204 5205 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5206 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5207 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5208 5209 uint64_t Value = CachePolicyConst->getZExtValue(); 5210 SDLoc DL(CachePolicy); 5211 if (GLC) { 5212 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5213 Value &= ~(uint64_t)0x1; 5214 } 5215 if (SLC) { 5216 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5217 Value &= ~(uint64_t)0x2; 5218 } 5219 if (DLC) { 5220 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5221 Value &= ~(uint64_t)0x4; 5222 } 5223 5224 return Value == 0; 5225 } 5226 5227 // Re-construct the required return value for a image load intrinsic. 5228 // This is more complicated due to the optional use TexFailCtrl which means the required 5229 // return type is an aggregate 5230 static SDValue constructRetValue(SelectionDAG &DAG, 5231 MachineSDNode *Result, 5232 ArrayRef<EVT> ResultTypes, 5233 bool IsTexFail, bool Unpacked, bool IsD16, 5234 int DMaskPop, int NumVDataDwords, 5235 const SDLoc &DL, LLVMContext &Context) { 5236 // Determine the required return type. This is the same regardless of IsTexFail flag 5237 EVT ReqRetVT = ResultTypes[0]; 5238 EVT ReqRetEltVT = ReqRetVT.isVector() ? ReqRetVT.getVectorElementType() : ReqRetVT; 5239 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5240 EVT AdjEltVT = Unpacked && IsD16 ? MVT::i32 : ReqRetEltVT; 5241 EVT AdjVT = Unpacked ? ReqRetNumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, ReqRetNumElts) 5242 : AdjEltVT 5243 : ReqRetVT; 5244 5245 // Extract data part of the result 5246 // Bitcast the result to the same type as the required return type 5247 int NumElts; 5248 if (IsD16 && !Unpacked) 5249 NumElts = NumVDataDwords << 1; 5250 else 5251 NumElts = NumVDataDwords; 5252 5253 EVT CastVT = NumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, NumElts) 5254 : AdjEltVT; 5255 5256 // Special case for v6f16. Rather than add support for this, use v3i32 to 5257 // extract the data elements 5258 bool V6F16Special = false; 5259 if (NumElts == 6) { 5260 CastVT = EVT::getVectorVT(Context, MVT::i32, NumElts / 2); 5261 DMaskPop >>= 1; 5262 ReqRetNumElts >>= 1; 5263 V6F16Special = true; 5264 AdjVT = MVT::v2i32; 5265 } 5266 5267 SDValue N = SDValue(Result, 0); 5268 SDValue CastRes = DAG.getNode(ISD::BITCAST, DL, CastVT, N); 5269 5270 // Iterate over the result 5271 SmallVector<SDValue, 4> BVElts; 5272 5273 if (CastVT.isVector()) { 5274 DAG.ExtractVectorElements(CastRes, BVElts, 0, DMaskPop); 5275 } else { 5276 BVElts.push_back(CastRes); 5277 } 5278 int ExtraElts = ReqRetNumElts - DMaskPop; 5279 while(ExtraElts--) 5280 BVElts.push_back(DAG.getUNDEF(AdjEltVT)); 5281 5282 SDValue PreTFCRes; 5283 if (ReqRetNumElts > 1) { 5284 SDValue NewVec = DAG.getBuildVector(AdjVT, DL, BVElts); 5285 if (IsD16 && Unpacked) 5286 PreTFCRes = adjustLoadValueTypeImpl(NewVec, ReqRetVT, DL, DAG, Unpacked); 5287 else 5288 PreTFCRes = NewVec; 5289 } else { 5290 PreTFCRes = BVElts[0]; 5291 } 5292 5293 if (V6F16Special) 5294 PreTFCRes = DAG.getNode(ISD::BITCAST, DL, MVT::v4f16, PreTFCRes); 5295 5296 if (!IsTexFail) { 5297 if (Result->getNumValues() > 1) 5298 return DAG.getMergeValues({PreTFCRes, SDValue(Result, 1)}, DL); 5299 else 5300 return PreTFCRes; 5301 } 5302 5303 // Extract the TexFail result and insert into aggregate return 5304 SmallVector<SDValue, 1> TFCElt; 5305 DAG.ExtractVectorElements(N, TFCElt, DMaskPop, 1); 5306 SDValue TFCRes = DAG.getNode(ISD::BITCAST, DL, ResultTypes[1], TFCElt[0]); 5307 return DAG.getMergeValues({PreTFCRes, TFCRes, SDValue(Result, 1)}, DL); 5308 } 5309 5310 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5311 SDValue *LWE, bool &IsTexFail) { 5312 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5313 5314 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5315 if (Value) { 5316 IsTexFail = true; 5317 } 5318 5319 SDLoc DL(TexFailCtrlConst); 5320 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5321 Value &= ~(uint64_t)0x1; 5322 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5323 Value &= ~(uint64_t)0x2; 5324 5325 return Value == 0; 5326 } 5327 5328 SDValue SITargetLowering::lowerImage(SDValue Op, 5329 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5330 SelectionDAG &DAG) const { 5331 SDLoc DL(Op); 5332 MachineFunction &MF = DAG.getMachineFunction(); 5333 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5334 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5335 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5336 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5337 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5338 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5339 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5340 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5341 unsigned IntrOpcode = Intr->BaseOpcode; 5342 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5343 5344 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5345 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5346 bool IsD16 = false; 5347 bool IsA16 = false; 5348 SDValue VData; 5349 int NumVDataDwords; 5350 bool AdjustRetType = false; 5351 5352 unsigned AddrIdx; // Index of first address argument 5353 unsigned DMask; 5354 unsigned DMaskLanes = 0; 5355 5356 if (BaseOpcode->Atomic) { 5357 VData = Op.getOperand(2); 5358 5359 bool Is64Bit = VData.getValueType() == MVT::i64; 5360 if (BaseOpcode->AtomicX2) { 5361 SDValue VData2 = Op.getOperand(3); 5362 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5363 {VData, VData2}); 5364 if (Is64Bit) 5365 VData = DAG.getBitcast(MVT::v4i32, VData); 5366 5367 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5368 DMask = Is64Bit ? 0xf : 0x3; 5369 NumVDataDwords = Is64Bit ? 4 : 2; 5370 AddrIdx = 4; 5371 } else { 5372 DMask = Is64Bit ? 0x3 : 0x1; 5373 NumVDataDwords = Is64Bit ? 2 : 1; 5374 AddrIdx = 3; 5375 } 5376 } else { 5377 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5378 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5379 DMask = DMaskConst->getZExtValue(); 5380 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5381 5382 if (BaseOpcode->Store) { 5383 VData = Op.getOperand(2); 5384 5385 MVT StoreVT = VData.getSimpleValueType(); 5386 if (StoreVT.getScalarType() == MVT::f16) { 5387 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5388 return Op; // D16 is unsupported for this instruction 5389 5390 IsD16 = true; 5391 VData = handleD16VData(VData, DAG); 5392 } 5393 5394 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5395 } else { 5396 // Work out the num dwords based on the dmask popcount and underlying type 5397 // and whether packing is supported. 5398 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5399 if (LoadVT.getScalarType() == MVT::f16) { 5400 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5401 return Op; // D16 is unsupported for this instruction 5402 5403 IsD16 = true; 5404 } 5405 5406 // Confirm that the return type is large enough for the dmask specified 5407 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5408 (!LoadVT.isVector() && DMaskLanes > 1)) 5409 return Op; 5410 5411 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5412 NumVDataDwords = (DMaskLanes + 1) / 2; 5413 else 5414 NumVDataDwords = DMaskLanes; 5415 5416 AdjustRetType = true; 5417 } 5418 5419 AddrIdx = DMaskIdx + 1; 5420 } 5421 5422 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5423 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5424 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5425 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5426 NumCoords + NumLCM; 5427 unsigned NumMIVAddrs = NumVAddrs; 5428 5429 SmallVector<SDValue, 4> VAddrs; 5430 5431 // Optimize _L to _LZ when _L is zero 5432 if (LZMappingInfo) { 5433 if (auto ConstantLod = 5434 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5435 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5436 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5437 NumMIVAddrs--; // remove 'lod' 5438 } 5439 } 5440 } 5441 5442 // Optimize _mip away, when 'lod' is zero 5443 if (MIPMappingInfo) { 5444 if (auto ConstantLod = 5445 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5446 if (ConstantLod->isNullValue()) { 5447 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5448 NumMIVAddrs--; // remove 'lod' 5449 } 5450 } 5451 } 5452 5453 // Check for 16 bit addresses and pack if true. 5454 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5455 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5456 const MVT VAddrScalarVT = VAddrVT.getScalarType(); 5457 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16)) && 5458 ST->hasFeature(AMDGPU::FeatureR128A16)) { 5459 IsA16 = true; 5460 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5461 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) { 5462 SDValue AddrLo, AddrHi; 5463 // Push back extra arguments. 5464 if (i < DimIdx) { 5465 AddrLo = Op.getOperand(i); 5466 } else { 5467 AddrLo = Op.getOperand(i); 5468 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, 5469 // in 1D, derivatives dx/dh and dx/dv are packed with undef. 5470 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) || 5471 ((NumGradients / 2) % 2 == 1 && 5472 (i == DimIdx + (NumGradients / 2) - 1 || 5473 i == DimIdx + NumGradients - 1))) { 5474 AddrHi = DAG.getUNDEF(MVT::f16); 5475 } else { 5476 AddrHi = Op.getOperand(i + 1); 5477 i++; 5478 } 5479 AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT, 5480 {AddrLo, AddrHi}); 5481 AddrLo = DAG.getBitcast(MVT::i32, AddrLo); 5482 } 5483 VAddrs.push_back(AddrLo); 5484 } 5485 } else { 5486 for (unsigned i = 0; i < NumMIVAddrs; ++i) 5487 VAddrs.push_back(Op.getOperand(AddrIdx + i)); 5488 } 5489 5490 // If the register allocator cannot place the address registers contiguously 5491 // without introducing moves, then using the non-sequential address encoding 5492 // is always preferable, since it saves VALU instructions and is usually a 5493 // wash in terms of code size or even better. 5494 // 5495 // However, we currently have no way of hinting to the register allocator that 5496 // MIMG addresses should be placed contiguously when it is possible to do so, 5497 // so force non-NSA for the common 2-address case as a heuristic. 5498 // 5499 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5500 // allocation when possible. 5501 bool UseNSA = 5502 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5503 SDValue VAddr; 5504 if (!UseNSA) 5505 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5506 5507 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5508 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5509 unsigned CtrlIdx; // Index of texfailctrl argument 5510 SDValue Unorm; 5511 if (!BaseOpcode->Sampler) { 5512 Unorm = True; 5513 CtrlIdx = AddrIdx + NumVAddrs + 1; 5514 } else { 5515 auto UnormConst = 5516 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 5517 5518 Unorm = UnormConst->getZExtValue() ? True : False; 5519 CtrlIdx = AddrIdx + NumVAddrs + 3; 5520 } 5521 5522 SDValue TFE; 5523 SDValue LWE; 5524 SDValue TexFail = Op.getOperand(CtrlIdx); 5525 bool IsTexFail = false; 5526 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 5527 return Op; 5528 5529 if (IsTexFail) { 5530 if (!DMaskLanes) { 5531 // Expecting to get an error flag since TFC is on - and dmask is 0 5532 // Force dmask to be at least 1 otherwise the instruction will fail 5533 DMask = 0x1; 5534 DMaskLanes = 1; 5535 NumVDataDwords = 1; 5536 } 5537 NumVDataDwords += 1; 5538 AdjustRetType = true; 5539 } 5540 5541 // Has something earlier tagged that the return type needs adjusting 5542 // This happens if the instruction is a load or has set TexFailCtrl flags 5543 if (AdjustRetType) { 5544 // NumVDataDwords reflects the true number of dwords required in the return type 5545 if (DMaskLanes == 0 && !BaseOpcode->Store) { 5546 // This is a no-op load. This can be eliminated 5547 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 5548 if (isa<MemSDNode>(Op)) 5549 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 5550 return Undef; 5551 } 5552 5553 EVT NewVT = NumVDataDwords > 1 ? 5554 EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumVDataDwords) 5555 : MVT::f32; 5556 5557 ResultTypes[0] = NewVT; 5558 if (ResultTypes.size() == 3) { 5559 // Original result was aggregate type used for TexFailCtrl results 5560 // The actual instruction returns as a vector type which has now been 5561 // created. Remove the aggregate result. 5562 ResultTypes.erase(&ResultTypes[1]); 5563 } 5564 } 5565 5566 SDValue GLC; 5567 SDValue SLC; 5568 SDValue DLC; 5569 if (BaseOpcode->Atomic) { 5570 GLC = True; // TODO no-return optimization 5571 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 5572 IsGFX10 ? &DLC : nullptr)) 5573 return Op; 5574 } else { 5575 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 5576 IsGFX10 ? &DLC : nullptr)) 5577 return Op; 5578 } 5579 5580 SmallVector<SDValue, 26> Ops; 5581 if (BaseOpcode->Store || BaseOpcode->Atomic) 5582 Ops.push_back(VData); // vdata 5583 if (UseNSA) { 5584 for (const SDValue &Addr : VAddrs) 5585 Ops.push_back(Addr); 5586 } else { 5587 Ops.push_back(VAddr); 5588 } 5589 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 5590 if (BaseOpcode->Sampler) 5591 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 5592 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 5593 if (IsGFX10) 5594 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 5595 Ops.push_back(Unorm); 5596 if (IsGFX10) 5597 Ops.push_back(DLC); 5598 Ops.push_back(GLC); 5599 Ops.push_back(SLC); 5600 Ops.push_back(IsA16 && // a16 or r128 5601 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 5602 Ops.push_back(TFE); // tfe 5603 Ops.push_back(LWE); // lwe 5604 if (!IsGFX10) 5605 Ops.push_back(DimInfo->DA ? True : False); 5606 if (BaseOpcode->HasD16) 5607 Ops.push_back(IsD16 ? True : False); 5608 if (isa<MemSDNode>(Op)) 5609 Ops.push_back(Op.getOperand(0)); // chain 5610 5611 int NumVAddrDwords = 5612 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 5613 int Opcode = -1; 5614 5615 if (IsGFX10) { 5616 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 5617 UseNSA ? AMDGPU::MIMGEncGfx10NSA 5618 : AMDGPU::MIMGEncGfx10Default, 5619 NumVDataDwords, NumVAddrDwords); 5620 } else { 5621 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5622 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 5623 NumVDataDwords, NumVAddrDwords); 5624 if (Opcode == -1) 5625 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 5626 NumVDataDwords, NumVAddrDwords); 5627 } 5628 assert(Opcode != -1); 5629 5630 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 5631 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 5632 MachineMemOperand *MemRef = MemOp->getMemOperand(); 5633 DAG.setNodeMemRefs(NewNode, {MemRef}); 5634 } 5635 5636 if (BaseOpcode->AtomicX2) { 5637 SmallVector<SDValue, 1> Elt; 5638 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 5639 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 5640 } else if (!BaseOpcode->Store) { 5641 return constructRetValue(DAG, NewNode, 5642 OrigResultTypes, IsTexFail, 5643 Subtarget->hasUnpackedD16VMem(), IsD16, 5644 DMaskLanes, NumVDataDwords, DL, 5645 *DAG.getContext()); 5646 } 5647 5648 return SDValue(NewNode, 0); 5649 } 5650 5651 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 5652 SDValue Offset, SDValue GLC, SDValue DLC, 5653 SelectionDAG &DAG) const { 5654 MachineFunction &MF = DAG.getMachineFunction(); 5655 MachineMemOperand *MMO = MF.getMachineMemOperand( 5656 MachinePointerInfo(), 5657 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 5658 MachineMemOperand::MOInvariant, 5659 VT.getStoreSize(), VT.getStoreSize()); 5660 5661 if (!Offset->isDivergent()) { 5662 SDValue Ops[] = { 5663 Rsrc, 5664 Offset, // Offset 5665 GLC, 5666 DLC, 5667 }; 5668 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 5669 DAG.getVTList(VT), Ops, VT, MMO); 5670 } 5671 5672 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 5673 // assume that the buffer is unswizzled. 5674 SmallVector<SDValue, 4> Loads; 5675 unsigned NumLoads = 1; 5676 MVT LoadVT = VT.getSimpleVT(); 5677 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 5678 assert((LoadVT.getScalarType() == MVT::i32 || 5679 LoadVT.getScalarType() == MVT::f32) && 5680 isPowerOf2_32(NumElts)); 5681 5682 if (NumElts == 8 || NumElts == 16) { 5683 NumLoads = NumElts == 16 ? 4 : 2; 5684 LoadVT = MVT::v4i32; 5685 } 5686 5687 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 5688 unsigned CachePolicy = cast<ConstantSDNode>(GLC)->getZExtValue(); 5689 SDValue Ops[] = { 5690 DAG.getEntryNode(), // Chain 5691 Rsrc, // rsrc 5692 DAG.getConstant(0, DL, MVT::i32), // vindex 5693 {}, // voffset 5694 {}, // soffset 5695 {}, // offset 5696 DAG.getTargetConstant(CachePolicy, DL, MVT::i32), // cachepolicy 5697 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 5698 }; 5699 5700 // Use the alignment to ensure that the required offsets will fit into the 5701 // immediate offsets. 5702 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 5703 5704 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 5705 for (unsigned i = 0; i < NumLoads; ++i) { 5706 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 5707 Loads.push_back(DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, 5708 Ops, LoadVT, MMO)); 5709 } 5710 5711 if (VT == MVT::v8i32 || VT == MVT::v16i32) 5712 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 5713 5714 return Loads[0]; 5715 } 5716 5717 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 5718 SelectionDAG &DAG) const { 5719 MachineFunction &MF = DAG.getMachineFunction(); 5720 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 5721 5722 EVT VT = Op.getValueType(); 5723 SDLoc DL(Op); 5724 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5725 5726 // TODO: Should this propagate fast-math-flags? 5727 5728 switch (IntrinsicID) { 5729 case Intrinsic::amdgcn_implicit_buffer_ptr: { 5730 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 5731 return emitNonHSAIntrinsicError(DAG, DL, VT); 5732 return getPreloadedValue(DAG, *MFI, VT, 5733 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 5734 } 5735 case Intrinsic::amdgcn_dispatch_ptr: 5736 case Intrinsic::amdgcn_queue_ptr: { 5737 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 5738 DiagnosticInfoUnsupported BadIntrin( 5739 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 5740 DL.getDebugLoc()); 5741 DAG.getContext()->diagnose(BadIntrin); 5742 return DAG.getUNDEF(VT); 5743 } 5744 5745 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 5746 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 5747 return getPreloadedValue(DAG, *MFI, VT, RegID); 5748 } 5749 case Intrinsic::amdgcn_implicitarg_ptr: { 5750 if (MFI->isEntryFunction()) 5751 return getImplicitArgPtr(DAG, DL); 5752 return getPreloadedValue(DAG, *MFI, VT, 5753 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 5754 } 5755 case Intrinsic::amdgcn_kernarg_segment_ptr: { 5756 return getPreloadedValue(DAG, *MFI, VT, 5757 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 5758 } 5759 case Intrinsic::amdgcn_dispatch_id: { 5760 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 5761 } 5762 case Intrinsic::amdgcn_rcp: 5763 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 5764 case Intrinsic::amdgcn_rsq: 5765 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5766 case Intrinsic::amdgcn_rsq_legacy: 5767 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5768 return emitRemovedIntrinsicError(DAG, DL, VT); 5769 5770 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 5771 case Intrinsic::amdgcn_rcp_legacy: 5772 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5773 return emitRemovedIntrinsicError(DAG, DL, VT); 5774 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 5775 case Intrinsic::amdgcn_rsq_clamp: { 5776 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5777 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 5778 5779 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 5780 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 5781 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 5782 5783 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5784 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 5785 DAG.getConstantFP(Max, DL, VT)); 5786 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 5787 DAG.getConstantFP(Min, DL, VT)); 5788 } 5789 case Intrinsic::r600_read_ngroups_x: 5790 if (Subtarget->isAmdHsaOS()) 5791 return emitNonHSAIntrinsicError(DAG, DL, VT); 5792 5793 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5794 SI::KernelInputOffsets::NGROUPS_X, 4, false); 5795 case Intrinsic::r600_read_ngroups_y: 5796 if (Subtarget->isAmdHsaOS()) 5797 return emitNonHSAIntrinsicError(DAG, DL, VT); 5798 5799 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5800 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 5801 case Intrinsic::r600_read_ngroups_z: 5802 if (Subtarget->isAmdHsaOS()) 5803 return emitNonHSAIntrinsicError(DAG, DL, VT); 5804 5805 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5806 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 5807 case Intrinsic::r600_read_global_size_x: 5808 if (Subtarget->isAmdHsaOS()) 5809 return emitNonHSAIntrinsicError(DAG, DL, VT); 5810 5811 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5812 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 5813 case Intrinsic::r600_read_global_size_y: 5814 if (Subtarget->isAmdHsaOS()) 5815 return emitNonHSAIntrinsicError(DAG, DL, VT); 5816 5817 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5818 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 5819 case Intrinsic::r600_read_global_size_z: 5820 if (Subtarget->isAmdHsaOS()) 5821 return emitNonHSAIntrinsicError(DAG, DL, VT); 5822 5823 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5824 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 5825 case Intrinsic::r600_read_local_size_x: 5826 if (Subtarget->isAmdHsaOS()) 5827 return emitNonHSAIntrinsicError(DAG, DL, VT); 5828 5829 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5830 SI::KernelInputOffsets::LOCAL_SIZE_X); 5831 case Intrinsic::r600_read_local_size_y: 5832 if (Subtarget->isAmdHsaOS()) 5833 return emitNonHSAIntrinsicError(DAG, DL, VT); 5834 5835 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5836 SI::KernelInputOffsets::LOCAL_SIZE_Y); 5837 case Intrinsic::r600_read_local_size_z: 5838 if (Subtarget->isAmdHsaOS()) 5839 return emitNonHSAIntrinsicError(DAG, DL, VT); 5840 5841 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5842 SI::KernelInputOffsets::LOCAL_SIZE_Z); 5843 case Intrinsic::amdgcn_workgroup_id_x: 5844 case Intrinsic::r600_read_tgid_x: 5845 return getPreloadedValue(DAG, *MFI, VT, 5846 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 5847 case Intrinsic::amdgcn_workgroup_id_y: 5848 case Intrinsic::r600_read_tgid_y: 5849 return getPreloadedValue(DAG, *MFI, VT, 5850 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 5851 case Intrinsic::amdgcn_workgroup_id_z: 5852 case Intrinsic::r600_read_tgid_z: 5853 return getPreloadedValue(DAG, *MFI, VT, 5854 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 5855 case Intrinsic::amdgcn_workitem_id_x: 5856 case Intrinsic::r600_read_tidig_x: 5857 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5858 SDLoc(DAG.getEntryNode()), 5859 MFI->getArgInfo().WorkItemIDX); 5860 case Intrinsic::amdgcn_workitem_id_y: 5861 case Intrinsic::r600_read_tidig_y: 5862 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5863 SDLoc(DAG.getEntryNode()), 5864 MFI->getArgInfo().WorkItemIDY); 5865 case Intrinsic::amdgcn_workitem_id_z: 5866 case Intrinsic::r600_read_tidig_z: 5867 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5868 SDLoc(DAG.getEntryNode()), 5869 MFI->getArgInfo().WorkItemIDZ); 5870 case Intrinsic::amdgcn_wavefrontsize: 5871 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 5872 SDLoc(Op), MVT::i32); 5873 case Intrinsic::amdgcn_s_buffer_load: { 5874 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5875 SDValue GLC; 5876 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 5877 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 5878 IsGFX10 ? &DLC : nullptr)) 5879 return Op; 5880 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), GLC, DLC, 5881 DAG); 5882 } 5883 case Intrinsic::amdgcn_fdiv_fast: 5884 return lowerFDIV_FAST(Op, DAG); 5885 case Intrinsic::amdgcn_interp_p1_f16: { 5886 SDValue ToM0 = DAG.getCopyToReg(DAG.getEntryNode(), DL, AMDGPU::M0, 5887 Op.getOperand(5), SDValue()); 5888 if (getSubtarget()->getLDSBankCount() == 16) { 5889 // 16 bank LDS 5890 5891 // FIXME: This implicitly will insert a second CopyToReg to M0. 5892 SDValue S = DAG.getNode( 5893 ISD::INTRINSIC_WO_CHAIN, DL, MVT::f32, 5894 DAG.getTargetConstant(Intrinsic::amdgcn_interp_mov, DL, MVT::i32), 5895 DAG.getConstant(2, DL, MVT::i32), // P0 5896 Op.getOperand(2), // Attrchan 5897 Op.getOperand(3), // Attr 5898 Op.getOperand(5)); // m0 5899 5900 SDValue Ops[] = { 5901 Op.getOperand(1), // Src0 5902 Op.getOperand(2), // Attrchan 5903 Op.getOperand(3), // Attr 5904 DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers 5905 S, // Src2 - holds two f16 values selected by high 5906 DAG.getTargetConstant(0, DL, MVT::i32), // $src2_modifiers 5907 Op.getOperand(4), // high 5908 DAG.getTargetConstant(0, DL, MVT::i1), // $clamp 5909 DAG.getTargetConstant(0, DL, MVT::i32) // $omod 5910 }; 5911 return DAG.getNode(AMDGPUISD::INTERP_P1LV_F16, DL, MVT::f32, Ops); 5912 } else { 5913 // 32 bank LDS 5914 SDValue Ops[] = { 5915 Op.getOperand(1), // Src0 5916 Op.getOperand(2), // Attrchan 5917 Op.getOperand(3), // Attr 5918 DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers 5919 Op.getOperand(4), // high 5920 DAG.getTargetConstant(0, DL, MVT::i1), // $clamp 5921 DAG.getTargetConstant(0, DL, MVT::i32), // $omod 5922 ToM0.getValue(1) 5923 }; 5924 return DAG.getNode(AMDGPUISD::INTERP_P1LL_F16, DL, MVT::f32, Ops); 5925 } 5926 } 5927 case Intrinsic::amdgcn_interp_p2_f16: { 5928 SDValue ToM0 = DAG.getCopyToReg(DAG.getEntryNode(), DL, AMDGPU::M0, 5929 Op.getOperand(6), SDValue()); 5930 SDValue Ops[] = { 5931 Op.getOperand(2), // Src0 5932 Op.getOperand(3), // Attrchan 5933 Op.getOperand(4), // Attr 5934 DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers 5935 Op.getOperand(1), // Src2 5936 DAG.getTargetConstant(0, DL, MVT::i32), // $src2_modifiers 5937 Op.getOperand(5), // high 5938 DAG.getTargetConstant(0, DL, MVT::i1), // $clamp 5939 ToM0.getValue(1) 5940 }; 5941 return DAG.getNode(AMDGPUISD::INTERP_P2_F16, DL, MVT::f16, Ops); 5942 } 5943 case Intrinsic::amdgcn_sin: 5944 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 5945 5946 case Intrinsic::amdgcn_cos: 5947 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 5948 5949 case Intrinsic::amdgcn_mul_u24: 5950 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5951 case Intrinsic::amdgcn_mul_i24: 5952 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5953 5954 case Intrinsic::amdgcn_log_clamp: { 5955 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5956 return SDValue(); 5957 5958 DiagnosticInfoUnsupported BadIntrin( 5959 MF.getFunction(), "intrinsic not supported on subtarget", 5960 DL.getDebugLoc()); 5961 DAG.getContext()->diagnose(BadIntrin); 5962 return DAG.getUNDEF(VT); 5963 } 5964 case Intrinsic::amdgcn_ldexp: 5965 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 5966 Op.getOperand(1), Op.getOperand(2)); 5967 5968 case Intrinsic::amdgcn_fract: 5969 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 5970 5971 case Intrinsic::amdgcn_class: 5972 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 5973 Op.getOperand(1), Op.getOperand(2)); 5974 case Intrinsic::amdgcn_div_fmas: 5975 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 5976 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5977 Op.getOperand(4)); 5978 5979 case Intrinsic::amdgcn_div_fixup: 5980 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 5981 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5982 5983 case Intrinsic::amdgcn_trig_preop: 5984 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 5985 Op.getOperand(1), Op.getOperand(2)); 5986 case Intrinsic::amdgcn_div_scale: { 5987 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 5988 5989 // Translate to the operands expected by the machine instruction. The 5990 // first parameter must be the same as the first instruction. 5991 SDValue Numerator = Op.getOperand(1); 5992 SDValue Denominator = Op.getOperand(2); 5993 5994 // Note this order is opposite of the machine instruction's operations, 5995 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 5996 // intrinsic has the numerator as the first operand to match a normal 5997 // division operation. 5998 5999 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6000 6001 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6002 Denominator, Numerator); 6003 } 6004 case Intrinsic::amdgcn_icmp: { 6005 // There is a Pat that handles this variant, so return it as-is. 6006 if (Op.getOperand(1).getValueType() == MVT::i1 && 6007 Op.getConstantOperandVal(2) == 0 && 6008 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6009 return Op; 6010 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6011 } 6012 case Intrinsic::amdgcn_fcmp: { 6013 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6014 } 6015 case Intrinsic::amdgcn_fmed3: 6016 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6017 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6018 case Intrinsic::amdgcn_fdot2: 6019 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6020 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6021 Op.getOperand(4)); 6022 case Intrinsic::amdgcn_fmul_legacy: 6023 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6024 Op.getOperand(1), Op.getOperand(2)); 6025 case Intrinsic::amdgcn_sffbh: 6026 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6027 case Intrinsic::amdgcn_sbfe: 6028 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6029 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6030 case Intrinsic::amdgcn_ubfe: 6031 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6032 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6033 case Intrinsic::amdgcn_cvt_pkrtz: 6034 case Intrinsic::amdgcn_cvt_pknorm_i16: 6035 case Intrinsic::amdgcn_cvt_pknorm_u16: 6036 case Intrinsic::amdgcn_cvt_pk_i16: 6037 case Intrinsic::amdgcn_cvt_pk_u16: { 6038 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6039 EVT VT = Op.getValueType(); 6040 unsigned Opcode; 6041 6042 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6043 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6044 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6045 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6046 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6047 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6048 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6049 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6050 else 6051 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6052 6053 if (isTypeLegal(VT)) 6054 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6055 6056 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6057 Op.getOperand(1), Op.getOperand(2)); 6058 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6059 } 6060 case Intrinsic::amdgcn_fmad_ftz: 6061 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6062 Op.getOperand(2), Op.getOperand(3)); 6063 6064 case Intrinsic::amdgcn_if_break: 6065 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6066 Op->getOperand(1), Op->getOperand(2)), 0); 6067 6068 case Intrinsic::amdgcn_groupstaticsize: { 6069 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6070 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6071 return Op; 6072 6073 const Module *M = MF.getFunction().getParent(); 6074 const GlobalValue *GV = 6075 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6076 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6077 SIInstrInfo::MO_ABS32_LO); 6078 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6079 } 6080 case Intrinsic::amdgcn_is_shared: 6081 case Intrinsic::amdgcn_is_private: { 6082 SDLoc SL(Op); 6083 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6084 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6085 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6086 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6087 Op.getOperand(1)); 6088 6089 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6090 DAG.getConstant(1, SL, MVT::i32)); 6091 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6092 } 6093 default: 6094 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6095 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6096 return lowerImage(Op, ImageDimIntr, DAG); 6097 6098 return Op; 6099 } 6100 } 6101 6102 // This function computes an appropriate offset to pass to 6103 // MachineMemOperand::setOffset() based on the offset inputs to 6104 // an intrinsic. If any of the offsets are non-contstant or 6105 // if VIndex is non-zero then this function returns 0. Otherwise, 6106 // it returns the sum of VOffset, SOffset, and Offset. 6107 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6108 SDValue SOffset, 6109 SDValue Offset, 6110 SDValue VIndex = SDValue()) { 6111 6112 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6113 !isa<ConstantSDNode>(Offset)) 6114 return 0; 6115 6116 if (VIndex) { 6117 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6118 return 0; 6119 } 6120 6121 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6122 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6123 cast<ConstantSDNode>(Offset)->getSExtValue(); 6124 } 6125 6126 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6127 SelectionDAG &DAG) const { 6128 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6129 SDLoc DL(Op); 6130 6131 switch (IntrID) { 6132 case Intrinsic::amdgcn_ds_ordered_add: 6133 case Intrinsic::amdgcn_ds_ordered_swap: { 6134 MemSDNode *M = cast<MemSDNode>(Op); 6135 SDValue Chain = M->getOperand(0); 6136 SDValue M0 = M->getOperand(2); 6137 SDValue Value = M->getOperand(3); 6138 unsigned IndexOperand = M->getConstantOperandVal(7); 6139 unsigned WaveRelease = M->getConstantOperandVal(8); 6140 unsigned WaveDone = M->getConstantOperandVal(9); 6141 unsigned ShaderType; 6142 unsigned Instruction; 6143 6144 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6145 IndexOperand &= ~0x3f; 6146 unsigned CountDw = 0; 6147 6148 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6149 CountDw = (IndexOperand >> 24) & 0xf; 6150 IndexOperand &= ~(0xf << 24); 6151 6152 if (CountDw < 1 || CountDw > 4) { 6153 report_fatal_error( 6154 "ds_ordered_count: dword count must be between 1 and 4"); 6155 } 6156 } 6157 6158 if (IndexOperand) 6159 report_fatal_error("ds_ordered_count: bad index operand"); 6160 6161 switch (IntrID) { 6162 case Intrinsic::amdgcn_ds_ordered_add: 6163 Instruction = 0; 6164 break; 6165 case Intrinsic::amdgcn_ds_ordered_swap: 6166 Instruction = 1; 6167 break; 6168 } 6169 6170 if (WaveDone && !WaveRelease) 6171 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6172 6173 switch (DAG.getMachineFunction().getFunction().getCallingConv()) { 6174 case CallingConv::AMDGPU_CS: 6175 case CallingConv::AMDGPU_KERNEL: 6176 ShaderType = 0; 6177 break; 6178 case CallingConv::AMDGPU_PS: 6179 ShaderType = 1; 6180 break; 6181 case CallingConv::AMDGPU_VS: 6182 ShaderType = 2; 6183 break; 6184 case CallingConv::AMDGPU_GS: 6185 ShaderType = 3; 6186 break; 6187 default: 6188 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6189 } 6190 6191 unsigned Offset0 = OrderedCountIndex << 2; 6192 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6193 (Instruction << 4); 6194 6195 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6196 Offset1 |= (CountDw - 1) << 6; 6197 6198 unsigned Offset = Offset0 | (Offset1 << 8); 6199 6200 SDValue Ops[] = { 6201 Chain, 6202 Value, 6203 DAG.getTargetConstant(Offset, DL, MVT::i16), 6204 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6205 }; 6206 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6207 M->getVTList(), Ops, M->getMemoryVT(), 6208 M->getMemOperand()); 6209 } 6210 case Intrinsic::amdgcn_ds_fadd: { 6211 MemSDNode *M = cast<MemSDNode>(Op); 6212 unsigned Opc; 6213 switch (IntrID) { 6214 case Intrinsic::amdgcn_ds_fadd: 6215 Opc = ISD::ATOMIC_LOAD_FADD; 6216 break; 6217 } 6218 6219 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6220 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6221 M->getMemOperand()); 6222 } 6223 case Intrinsic::amdgcn_atomic_inc: 6224 case Intrinsic::amdgcn_atomic_dec: 6225 case Intrinsic::amdgcn_ds_fmin: 6226 case Intrinsic::amdgcn_ds_fmax: { 6227 MemSDNode *M = cast<MemSDNode>(Op); 6228 unsigned Opc; 6229 switch (IntrID) { 6230 case Intrinsic::amdgcn_atomic_inc: 6231 Opc = AMDGPUISD::ATOMIC_INC; 6232 break; 6233 case Intrinsic::amdgcn_atomic_dec: 6234 Opc = AMDGPUISD::ATOMIC_DEC; 6235 break; 6236 case Intrinsic::amdgcn_ds_fmin: 6237 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6238 break; 6239 case Intrinsic::amdgcn_ds_fmax: 6240 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6241 break; 6242 default: 6243 llvm_unreachable("Unknown intrinsic!"); 6244 } 6245 SDValue Ops[] = { 6246 M->getOperand(0), // Chain 6247 M->getOperand(2), // Ptr 6248 M->getOperand(3) // Value 6249 }; 6250 6251 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6252 M->getMemoryVT(), M->getMemOperand()); 6253 } 6254 case Intrinsic::amdgcn_buffer_load: 6255 case Intrinsic::amdgcn_buffer_load_format: { 6256 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6257 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6258 unsigned IdxEn = 1; 6259 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6260 IdxEn = Idx->getZExtValue() != 0; 6261 SDValue Ops[] = { 6262 Op.getOperand(0), // Chain 6263 Op.getOperand(2), // rsrc 6264 Op.getOperand(3), // vindex 6265 SDValue(), // voffset -- will be set by setBufferOffsets 6266 SDValue(), // soffset -- will be set by setBufferOffsets 6267 SDValue(), // offset -- will be set by setBufferOffsets 6268 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6269 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6270 }; 6271 6272 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6273 // We don't know the offset if vindex is non-zero, so clear it. 6274 if (IdxEn) 6275 Offset = 0; 6276 6277 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6278 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6279 6280 EVT VT = Op.getValueType(); 6281 EVT IntVT = VT.changeTypeToInteger(); 6282 auto *M = cast<MemSDNode>(Op); 6283 M->getMemOperand()->setOffset(Offset); 6284 EVT LoadVT = Op.getValueType(); 6285 6286 if (LoadVT.getScalarType() == MVT::f16) 6287 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6288 M, DAG, Ops); 6289 6290 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6291 if (LoadVT.getScalarType() == MVT::i8 || 6292 LoadVT.getScalarType() == MVT::i16) 6293 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6294 6295 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6296 M->getMemOperand(), DAG); 6297 } 6298 case Intrinsic::amdgcn_raw_buffer_load: 6299 case Intrinsic::amdgcn_raw_buffer_load_format: { 6300 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6301 6302 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6303 SDValue Ops[] = { 6304 Op.getOperand(0), // Chain 6305 Op.getOperand(2), // rsrc 6306 DAG.getConstant(0, DL, MVT::i32), // vindex 6307 Offsets.first, // voffset 6308 Op.getOperand(4), // soffset 6309 Offsets.second, // offset 6310 Op.getOperand(5), // cachepolicy, swizzled buffer 6311 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6312 }; 6313 6314 auto *M = cast<MemSDNode>(Op); 6315 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6316 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6317 } 6318 case Intrinsic::amdgcn_struct_buffer_load: 6319 case Intrinsic::amdgcn_struct_buffer_load_format: { 6320 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6321 6322 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6323 SDValue Ops[] = { 6324 Op.getOperand(0), // Chain 6325 Op.getOperand(2), // rsrc 6326 Op.getOperand(3), // vindex 6327 Offsets.first, // voffset 6328 Op.getOperand(5), // soffset 6329 Offsets.second, // offset 6330 Op.getOperand(6), // cachepolicy, swizzled buffer 6331 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6332 }; 6333 6334 auto *M = cast<MemSDNode>(Op); 6335 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6336 Ops[2])); 6337 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6338 } 6339 case Intrinsic::amdgcn_tbuffer_load: { 6340 MemSDNode *M = cast<MemSDNode>(Op); 6341 EVT LoadVT = Op.getValueType(); 6342 6343 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6344 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6345 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6346 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6347 unsigned IdxEn = 1; 6348 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6349 IdxEn = Idx->getZExtValue() != 0; 6350 SDValue Ops[] = { 6351 Op.getOperand(0), // Chain 6352 Op.getOperand(2), // rsrc 6353 Op.getOperand(3), // vindex 6354 Op.getOperand(4), // voffset 6355 Op.getOperand(5), // soffset 6356 Op.getOperand(6), // offset 6357 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6358 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6359 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6360 }; 6361 6362 if (LoadVT.getScalarType() == MVT::f16) 6363 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6364 M, DAG, Ops); 6365 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6366 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6367 DAG); 6368 } 6369 case Intrinsic::amdgcn_raw_tbuffer_load: { 6370 MemSDNode *M = cast<MemSDNode>(Op); 6371 EVT LoadVT = Op.getValueType(); 6372 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6373 6374 SDValue Ops[] = { 6375 Op.getOperand(0), // Chain 6376 Op.getOperand(2), // rsrc 6377 DAG.getConstant(0, DL, MVT::i32), // vindex 6378 Offsets.first, // voffset 6379 Op.getOperand(4), // soffset 6380 Offsets.second, // offset 6381 Op.getOperand(5), // format 6382 Op.getOperand(6), // cachepolicy, swizzled buffer 6383 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6384 }; 6385 6386 if (LoadVT.getScalarType() == MVT::f16) 6387 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6388 M, DAG, Ops); 6389 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6390 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6391 DAG); 6392 } 6393 case Intrinsic::amdgcn_struct_tbuffer_load: { 6394 MemSDNode *M = cast<MemSDNode>(Op); 6395 EVT LoadVT = Op.getValueType(); 6396 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6397 6398 SDValue Ops[] = { 6399 Op.getOperand(0), // Chain 6400 Op.getOperand(2), // rsrc 6401 Op.getOperand(3), // vindex 6402 Offsets.first, // voffset 6403 Op.getOperand(5), // soffset 6404 Offsets.second, // offset 6405 Op.getOperand(6), // format 6406 Op.getOperand(7), // cachepolicy, swizzled buffer 6407 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6408 }; 6409 6410 if (LoadVT.getScalarType() == MVT::f16) 6411 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6412 M, DAG, Ops); 6413 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6414 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6415 DAG); 6416 } 6417 case Intrinsic::amdgcn_buffer_atomic_swap: 6418 case Intrinsic::amdgcn_buffer_atomic_add: 6419 case Intrinsic::amdgcn_buffer_atomic_sub: 6420 case Intrinsic::amdgcn_buffer_atomic_smin: 6421 case Intrinsic::amdgcn_buffer_atomic_umin: 6422 case Intrinsic::amdgcn_buffer_atomic_smax: 6423 case Intrinsic::amdgcn_buffer_atomic_umax: 6424 case Intrinsic::amdgcn_buffer_atomic_and: 6425 case Intrinsic::amdgcn_buffer_atomic_or: 6426 case Intrinsic::amdgcn_buffer_atomic_xor: { 6427 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6428 unsigned IdxEn = 1; 6429 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6430 IdxEn = Idx->getZExtValue() != 0; 6431 SDValue Ops[] = { 6432 Op.getOperand(0), // Chain 6433 Op.getOperand(2), // vdata 6434 Op.getOperand(3), // rsrc 6435 Op.getOperand(4), // vindex 6436 SDValue(), // voffset -- will be set by setBufferOffsets 6437 SDValue(), // soffset -- will be set by setBufferOffsets 6438 SDValue(), // offset -- will be set by setBufferOffsets 6439 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6440 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6441 }; 6442 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6443 // We don't know the offset if vindex is non-zero, so clear it. 6444 if (IdxEn) 6445 Offset = 0; 6446 EVT VT = Op.getValueType(); 6447 6448 auto *M = cast<MemSDNode>(Op); 6449 M->getMemOperand()->setOffset(Offset); 6450 unsigned Opcode = 0; 6451 6452 switch (IntrID) { 6453 case Intrinsic::amdgcn_buffer_atomic_swap: 6454 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6455 break; 6456 case Intrinsic::amdgcn_buffer_atomic_add: 6457 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6458 break; 6459 case Intrinsic::amdgcn_buffer_atomic_sub: 6460 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6461 break; 6462 case Intrinsic::amdgcn_buffer_atomic_smin: 6463 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6464 break; 6465 case Intrinsic::amdgcn_buffer_atomic_umin: 6466 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6467 break; 6468 case Intrinsic::amdgcn_buffer_atomic_smax: 6469 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6470 break; 6471 case Intrinsic::amdgcn_buffer_atomic_umax: 6472 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6473 break; 6474 case Intrinsic::amdgcn_buffer_atomic_and: 6475 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6476 break; 6477 case Intrinsic::amdgcn_buffer_atomic_or: 6478 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6479 break; 6480 case Intrinsic::amdgcn_buffer_atomic_xor: 6481 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6482 break; 6483 default: 6484 llvm_unreachable("unhandled atomic opcode"); 6485 } 6486 6487 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6488 M->getMemOperand()); 6489 } 6490 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6491 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6492 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6493 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6494 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6495 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6496 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6497 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6498 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6499 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6500 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6501 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 6502 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6503 SDValue Ops[] = { 6504 Op.getOperand(0), // Chain 6505 Op.getOperand(2), // vdata 6506 Op.getOperand(3), // rsrc 6507 DAG.getConstant(0, DL, MVT::i32), // vindex 6508 Offsets.first, // voffset 6509 Op.getOperand(5), // soffset 6510 Offsets.second, // offset 6511 Op.getOperand(6), // cachepolicy 6512 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6513 }; 6514 EVT VT = Op.getValueType(); 6515 6516 auto *M = cast<MemSDNode>(Op); 6517 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6518 unsigned Opcode = 0; 6519 6520 switch (IntrID) { 6521 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6522 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6523 break; 6524 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6525 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6526 break; 6527 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6528 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6529 break; 6530 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6531 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6532 break; 6533 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6534 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6535 break; 6536 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6537 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6538 break; 6539 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6540 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6541 break; 6542 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6543 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6544 break; 6545 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6546 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6547 break; 6548 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6549 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6550 break; 6551 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6552 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6553 break; 6554 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 6555 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6556 break; 6557 default: 6558 llvm_unreachable("unhandled atomic opcode"); 6559 } 6560 6561 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6562 M->getMemOperand()); 6563 } 6564 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6565 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6566 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6567 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6568 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6569 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6570 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6571 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6572 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6573 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6574 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6575 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 6576 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6577 SDValue Ops[] = { 6578 Op.getOperand(0), // Chain 6579 Op.getOperand(2), // vdata 6580 Op.getOperand(3), // rsrc 6581 Op.getOperand(4), // vindex 6582 Offsets.first, // voffset 6583 Op.getOperand(6), // soffset 6584 Offsets.second, // offset 6585 Op.getOperand(7), // cachepolicy 6586 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6587 }; 6588 EVT VT = Op.getValueType(); 6589 6590 auto *M = cast<MemSDNode>(Op); 6591 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6592 Ops[3])); 6593 unsigned Opcode = 0; 6594 6595 switch (IntrID) { 6596 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6597 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6598 break; 6599 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6600 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6601 break; 6602 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6603 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6604 break; 6605 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6606 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6607 break; 6608 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6609 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6610 break; 6611 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6612 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6613 break; 6614 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6615 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6616 break; 6617 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6618 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6619 break; 6620 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6621 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6622 break; 6623 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6624 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6625 break; 6626 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6627 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6628 break; 6629 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 6630 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6631 break; 6632 default: 6633 llvm_unreachable("unhandled atomic opcode"); 6634 } 6635 6636 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6637 M->getMemOperand()); 6638 } 6639 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 6640 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6641 unsigned IdxEn = 1; 6642 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 6643 IdxEn = Idx->getZExtValue() != 0; 6644 SDValue Ops[] = { 6645 Op.getOperand(0), // Chain 6646 Op.getOperand(2), // src 6647 Op.getOperand(3), // cmp 6648 Op.getOperand(4), // rsrc 6649 Op.getOperand(5), // vindex 6650 SDValue(), // voffset -- will be set by setBufferOffsets 6651 SDValue(), // soffset -- will be set by setBufferOffsets 6652 SDValue(), // offset -- will be set by setBufferOffsets 6653 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6654 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6655 }; 6656 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 6657 // We don't know the offset if vindex is non-zero, so clear it. 6658 if (IdxEn) 6659 Offset = 0; 6660 EVT VT = Op.getValueType(); 6661 auto *M = cast<MemSDNode>(Op); 6662 M->getMemOperand()->setOffset(Offset); 6663 6664 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6665 Op->getVTList(), Ops, VT, M->getMemOperand()); 6666 } 6667 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 6668 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6669 SDValue Ops[] = { 6670 Op.getOperand(0), // Chain 6671 Op.getOperand(2), // src 6672 Op.getOperand(3), // cmp 6673 Op.getOperand(4), // rsrc 6674 DAG.getConstant(0, DL, MVT::i32), // vindex 6675 Offsets.first, // voffset 6676 Op.getOperand(6), // soffset 6677 Offsets.second, // offset 6678 Op.getOperand(7), // cachepolicy 6679 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6680 }; 6681 EVT VT = Op.getValueType(); 6682 auto *M = cast<MemSDNode>(Op); 6683 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 6684 6685 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6686 Op->getVTList(), Ops, VT, M->getMemOperand()); 6687 } 6688 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 6689 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 6690 SDValue Ops[] = { 6691 Op.getOperand(0), // Chain 6692 Op.getOperand(2), // src 6693 Op.getOperand(3), // cmp 6694 Op.getOperand(4), // rsrc 6695 Op.getOperand(5), // vindex 6696 Offsets.first, // voffset 6697 Op.getOperand(7), // soffset 6698 Offsets.second, // offset 6699 Op.getOperand(8), // cachepolicy 6700 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6701 }; 6702 EVT VT = Op.getValueType(); 6703 auto *M = cast<MemSDNode>(Op); 6704 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 6705 Ops[4])); 6706 6707 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6708 Op->getVTList(), Ops, VT, M->getMemOperand()); 6709 } 6710 6711 default: 6712 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6713 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 6714 return lowerImage(Op, ImageDimIntr, DAG); 6715 6716 return SDValue(); 6717 } 6718 } 6719 6720 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 6721 // dwordx4 if on SI. 6722 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 6723 SDVTList VTList, 6724 ArrayRef<SDValue> Ops, EVT MemVT, 6725 MachineMemOperand *MMO, 6726 SelectionDAG &DAG) const { 6727 EVT VT = VTList.VTs[0]; 6728 EVT WidenedVT = VT; 6729 EVT WidenedMemVT = MemVT; 6730 if (!Subtarget->hasDwordx3LoadStores() && 6731 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 6732 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 6733 WidenedVT.getVectorElementType(), 4); 6734 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 6735 WidenedMemVT.getVectorElementType(), 4); 6736 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 6737 } 6738 6739 assert(VTList.NumVTs == 2); 6740 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 6741 6742 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 6743 WidenedMemVT, MMO); 6744 if (WidenedVT != VT) { 6745 auto Extract = DAG.getNode( 6746 ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 6747 DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout()))); 6748 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 6749 } 6750 return NewOp; 6751 } 6752 6753 SDValue SITargetLowering::handleD16VData(SDValue VData, 6754 SelectionDAG &DAG) const { 6755 EVT StoreVT = VData.getValueType(); 6756 6757 // No change for f16 and legal vector D16 types. 6758 if (!StoreVT.isVector()) 6759 return VData; 6760 6761 SDLoc DL(VData); 6762 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 6763 6764 if (Subtarget->hasUnpackedD16VMem()) { 6765 // We need to unpack the packed data to store. 6766 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 6767 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 6768 6769 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 6770 StoreVT.getVectorNumElements()); 6771 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 6772 return DAG.UnrollVectorOp(ZExt.getNode()); 6773 } 6774 6775 assert(isTypeLegal(StoreVT)); 6776 return VData; 6777 } 6778 6779 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 6780 SelectionDAG &DAG) const { 6781 SDLoc DL(Op); 6782 SDValue Chain = Op.getOperand(0); 6783 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6784 MachineFunction &MF = DAG.getMachineFunction(); 6785 6786 switch (IntrinsicID) { 6787 case Intrinsic::amdgcn_exp: { 6788 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 6789 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 6790 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8)); 6791 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9)); 6792 6793 const SDValue Ops[] = { 6794 Chain, 6795 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 6796 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 6797 Op.getOperand(4), // src0 6798 Op.getOperand(5), // src1 6799 Op.getOperand(6), // src2 6800 Op.getOperand(7), // src3 6801 DAG.getTargetConstant(0, DL, MVT::i1), // compr 6802 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 6803 }; 6804 6805 unsigned Opc = Done->isNullValue() ? 6806 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 6807 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 6808 } 6809 case Intrinsic::amdgcn_exp_compr: { 6810 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 6811 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 6812 SDValue Src0 = Op.getOperand(4); 6813 SDValue Src1 = Op.getOperand(5); 6814 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 6815 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7)); 6816 6817 SDValue Undef = DAG.getUNDEF(MVT::f32); 6818 const SDValue Ops[] = { 6819 Chain, 6820 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 6821 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 6822 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), 6823 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), 6824 Undef, // src2 6825 Undef, // src3 6826 DAG.getTargetConstant(1, DL, MVT::i1), // compr 6827 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 6828 }; 6829 6830 unsigned Opc = Done->isNullValue() ? 6831 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 6832 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 6833 } 6834 case Intrinsic::amdgcn_s_barrier: { 6835 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 6836 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 6837 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 6838 if (WGSize <= ST.getWavefrontSize()) 6839 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 6840 Op.getOperand(0)), 0); 6841 } 6842 return SDValue(); 6843 }; 6844 case Intrinsic::amdgcn_tbuffer_store: { 6845 SDValue VData = Op.getOperand(2); 6846 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6847 if (IsD16) 6848 VData = handleD16VData(VData, DAG); 6849 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6850 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6851 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6852 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 6853 unsigned IdxEn = 1; 6854 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6855 IdxEn = Idx->getZExtValue() != 0; 6856 SDValue Ops[] = { 6857 Chain, 6858 VData, // vdata 6859 Op.getOperand(3), // rsrc 6860 Op.getOperand(4), // vindex 6861 Op.getOperand(5), // voffset 6862 Op.getOperand(6), // soffset 6863 Op.getOperand(7), // offset 6864 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6865 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6866 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 6867 }; 6868 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6869 AMDGPUISD::TBUFFER_STORE_FORMAT; 6870 MemSDNode *M = cast<MemSDNode>(Op); 6871 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6872 M->getMemoryVT(), M->getMemOperand()); 6873 } 6874 6875 case Intrinsic::amdgcn_struct_tbuffer_store: { 6876 SDValue VData = Op.getOperand(2); 6877 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6878 if (IsD16) 6879 VData = handleD16VData(VData, DAG); 6880 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6881 SDValue Ops[] = { 6882 Chain, 6883 VData, // vdata 6884 Op.getOperand(3), // rsrc 6885 Op.getOperand(4), // vindex 6886 Offsets.first, // voffset 6887 Op.getOperand(6), // soffset 6888 Offsets.second, // offset 6889 Op.getOperand(7), // format 6890 Op.getOperand(8), // cachepolicy, swizzled buffer 6891 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 6892 }; 6893 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6894 AMDGPUISD::TBUFFER_STORE_FORMAT; 6895 MemSDNode *M = cast<MemSDNode>(Op); 6896 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6897 M->getMemoryVT(), M->getMemOperand()); 6898 } 6899 6900 case Intrinsic::amdgcn_raw_tbuffer_store: { 6901 SDValue VData = Op.getOperand(2); 6902 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6903 if (IsD16) 6904 VData = handleD16VData(VData, DAG); 6905 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6906 SDValue Ops[] = { 6907 Chain, 6908 VData, // vdata 6909 Op.getOperand(3), // rsrc 6910 DAG.getConstant(0, DL, MVT::i32), // vindex 6911 Offsets.first, // voffset 6912 Op.getOperand(5), // soffset 6913 Offsets.second, // offset 6914 Op.getOperand(6), // format 6915 Op.getOperand(7), // cachepolicy, swizzled buffer 6916 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 6917 }; 6918 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6919 AMDGPUISD::TBUFFER_STORE_FORMAT; 6920 MemSDNode *M = cast<MemSDNode>(Op); 6921 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6922 M->getMemoryVT(), M->getMemOperand()); 6923 } 6924 6925 case Intrinsic::amdgcn_buffer_store: 6926 case Intrinsic::amdgcn_buffer_store_format: { 6927 SDValue VData = Op.getOperand(2); 6928 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6929 if (IsD16) 6930 VData = handleD16VData(VData, DAG); 6931 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6932 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6933 unsigned IdxEn = 1; 6934 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6935 IdxEn = Idx->getZExtValue() != 0; 6936 SDValue Ops[] = { 6937 Chain, 6938 VData, 6939 Op.getOperand(3), // rsrc 6940 Op.getOperand(4), // vindex 6941 SDValue(), // voffset -- will be set by setBufferOffsets 6942 SDValue(), // soffset -- will be set by setBufferOffsets 6943 SDValue(), // offset -- will be set by setBufferOffsets 6944 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6945 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6946 }; 6947 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6948 // We don't know the offset if vindex is non-zero, so clear it. 6949 if (IdxEn) 6950 Offset = 0; 6951 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 6952 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6953 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6954 MemSDNode *M = cast<MemSDNode>(Op); 6955 M->getMemOperand()->setOffset(Offset); 6956 6957 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6958 EVT VDataType = VData.getValueType().getScalarType(); 6959 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6960 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6961 6962 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6963 M->getMemoryVT(), M->getMemOperand()); 6964 } 6965 6966 case Intrinsic::amdgcn_raw_buffer_store: 6967 case Intrinsic::amdgcn_raw_buffer_store_format: { 6968 const bool IsFormat = 6969 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 6970 6971 SDValue VData = Op.getOperand(2); 6972 EVT VDataVT = VData.getValueType(); 6973 EVT EltType = VDataVT.getScalarType(); 6974 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 6975 if (IsD16) 6976 VData = handleD16VData(VData, DAG); 6977 6978 if (!isTypeLegal(VDataVT)) { 6979 VData = 6980 DAG.getNode(ISD::BITCAST, DL, 6981 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 6982 } 6983 6984 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6985 SDValue Ops[] = { 6986 Chain, 6987 VData, 6988 Op.getOperand(3), // rsrc 6989 DAG.getConstant(0, DL, MVT::i32), // vindex 6990 Offsets.first, // voffset 6991 Op.getOperand(5), // soffset 6992 Offsets.second, // offset 6993 Op.getOperand(6), // cachepolicy, swizzled buffer 6994 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6995 }; 6996 unsigned Opc = 6997 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 6998 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6999 MemSDNode *M = cast<MemSDNode>(Op); 7000 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7001 7002 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7003 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7004 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7005 7006 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7007 M->getMemoryVT(), M->getMemOperand()); 7008 } 7009 7010 case Intrinsic::amdgcn_struct_buffer_store: 7011 case Intrinsic::amdgcn_struct_buffer_store_format: { 7012 const bool IsFormat = 7013 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7014 7015 SDValue VData = Op.getOperand(2); 7016 EVT VDataVT = VData.getValueType(); 7017 EVT EltType = VDataVT.getScalarType(); 7018 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7019 7020 if (IsD16) 7021 VData = handleD16VData(VData, DAG); 7022 7023 if (!isTypeLegal(VDataVT)) { 7024 VData = 7025 DAG.getNode(ISD::BITCAST, DL, 7026 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7027 } 7028 7029 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7030 SDValue Ops[] = { 7031 Chain, 7032 VData, 7033 Op.getOperand(3), // rsrc 7034 Op.getOperand(4), // vindex 7035 Offsets.first, // voffset 7036 Op.getOperand(6), // soffset 7037 Offsets.second, // offset 7038 Op.getOperand(7), // cachepolicy, swizzled buffer 7039 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7040 }; 7041 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7042 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7043 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7044 MemSDNode *M = cast<MemSDNode>(Op); 7045 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7046 Ops[3])); 7047 7048 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7049 EVT VDataType = VData.getValueType().getScalarType(); 7050 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7051 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7052 7053 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7054 M->getMemoryVT(), M->getMemOperand()); 7055 } 7056 7057 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7058 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7059 unsigned IdxEn = 1; 7060 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7061 IdxEn = Idx->getZExtValue() != 0; 7062 SDValue Ops[] = { 7063 Chain, 7064 Op.getOperand(2), // vdata 7065 Op.getOperand(3), // rsrc 7066 Op.getOperand(4), // vindex 7067 SDValue(), // voffset -- will be set by setBufferOffsets 7068 SDValue(), // soffset -- will be set by setBufferOffsets 7069 SDValue(), // offset -- will be set by setBufferOffsets 7070 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7071 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7072 }; 7073 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7074 // We don't know the offset if vindex is non-zero, so clear it. 7075 if (IdxEn) 7076 Offset = 0; 7077 EVT VT = Op.getOperand(2).getValueType(); 7078 7079 auto *M = cast<MemSDNode>(Op); 7080 M->getMemOperand()->setOffset(Offset); 7081 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 7082 : AMDGPUISD::BUFFER_ATOMIC_FADD; 7083 7084 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7085 M->getMemOperand()); 7086 } 7087 7088 case Intrinsic::amdgcn_global_atomic_fadd: { 7089 SDValue Ops[] = { 7090 Chain, 7091 Op.getOperand(2), // ptr 7092 Op.getOperand(3) // vdata 7093 }; 7094 EVT VT = Op.getOperand(3).getValueType(); 7095 7096 auto *M = cast<MemSDNode>(Op); 7097 if (VT.isVector()) { 7098 return DAG.getMemIntrinsicNode( 7099 AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT, 7100 M->getMemOperand()); 7101 } 7102 7103 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7104 DAG.getVTList(VT, MVT::Other), Ops, 7105 M->getMemOperand()).getValue(1); 7106 } 7107 case Intrinsic::amdgcn_end_cf: 7108 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7109 Op->getOperand(2), Chain), 0); 7110 7111 default: { 7112 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7113 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7114 return lowerImage(Op, ImageDimIntr, DAG); 7115 7116 return Op; 7117 } 7118 } 7119 } 7120 7121 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7122 // offset (the offset that is included in bounds checking and swizzling, to be 7123 // split between the instruction's voffset and immoffset fields) and soffset 7124 // (the offset that is excluded from bounds checking and swizzling, to go in 7125 // the instruction's soffset field). This function takes the first kind of 7126 // offset and figures out how to split it between voffset and immoffset. 7127 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7128 SDValue Offset, SelectionDAG &DAG) const { 7129 SDLoc DL(Offset); 7130 const unsigned MaxImm = 4095; 7131 SDValue N0 = Offset; 7132 ConstantSDNode *C1 = nullptr; 7133 7134 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7135 N0 = SDValue(); 7136 else if (DAG.isBaseWithConstantOffset(N0)) { 7137 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7138 N0 = N0.getOperand(0); 7139 } 7140 7141 if (C1) { 7142 unsigned ImmOffset = C1->getZExtValue(); 7143 // If the immediate value is too big for the immoffset field, put the value 7144 // and -4096 into the immoffset field so that the value that is copied/added 7145 // for the voffset field is a multiple of 4096, and it stands more chance 7146 // of being CSEd with the copy/add for another similar load/store. 7147 // However, do not do that rounding down to a multiple of 4096 if that is a 7148 // negative number, as it appears to be illegal to have a negative offset 7149 // in the vgpr, even if adding the immediate offset makes it positive. 7150 unsigned Overflow = ImmOffset & ~MaxImm; 7151 ImmOffset -= Overflow; 7152 if ((int32_t)Overflow < 0) { 7153 Overflow += ImmOffset; 7154 ImmOffset = 0; 7155 } 7156 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7157 if (Overflow) { 7158 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7159 if (!N0) 7160 N0 = OverflowVal; 7161 else { 7162 SDValue Ops[] = { N0, OverflowVal }; 7163 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7164 } 7165 } 7166 } 7167 if (!N0) 7168 N0 = DAG.getConstant(0, DL, MVT::i32); 7169 if (!C1) 7170 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7171 return {N0, SDValue(C1, 0)}; 7172 } 7173 7174 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7175 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7176 // pointed to by Offsets. 7177 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7178 SelectionDAG &DAG, SDValue *Offsets, 7179 unsigned Align) const { 7180 SDLoc DL(CombinedOffset); 7181 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7182 uint32_t Imm = C->getZExtValue(); 7183 uint32_t SOffset, ImmOffset; 7184 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 7185 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7186 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7187 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7188 return SOffset + ImmOffset; 7189 } 7190 } 7191 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7192 SDValue N0 = CombinedOffset.getOperand(0); 7193 SDValue N1 = CombinedOffset.getOperand(1); 7194 uint32_t SOffset, ImmOffset; 7195 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7196 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7197 Subtarget, Align)) { 7198 Offsets[0] = N0; 7199 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7200 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7201 return 0; 7202 } 7203 } 7204 Offsets[0] = CombinedOffset; 7205 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7206 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7207 return 0; 7208 } 7209 7210 // Handle 8 bit and 16 bit buffer loads 7211 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7212 EVT LoadVT, SDLoc DL, 7213 ArrayRef<SDValue> Ops, 7214 MemSDNode *M) const { 7215 EVT IntVT = LoadVT.changeTypeToInteger(); 7216 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7217 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7218 7219 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7220 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7221 Ops, IntVT, 7222 M->getMemOperand()); 7223 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7224 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7225 7226 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7227 } 7228 7229 // Handle 8 bit and 16 bit buffer stores 7230 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7231 EVT VDataType, SDLoc DL, 7232 SDValue Ops[], 7233 MemSDNode *M) const { 7234 if (VDataType == MVT::f16) 7235 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7236 7237 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7238 Ops[1] = BufferStoreExt; 7239 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7240 AMDGPUISD::BUFFER_STORE_SHORT; 7241 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7242 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7243 M->getMemOperand()); 7244 } 7245 7246 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7247 ISD::LoadExtType ExtType, SDValue Op, 7248 const SDLoc &SL, EVT VT) { 7249 if (VT.bitsLT(Op.getValueType())) 7250 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7251 7252 switch (ExtType) { 7253 case ISD::SEXTLOAD: 7254 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7255 case ISD::ZEXTLOAD: 7256 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7257 case ISD::EXTLOAD: 7258 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7259 case ISD::NON_EXTLOAD: 7260 return Op; 7261 } 7262 7263 llvm_unreachable("invalid ext type"); 7264 } 7265 7266 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7267 SelectionDAG &DAG = DCI.DAG; 7268 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7269 return SDValue(); 7270 7271 // FIXME: Constant loads should all be marked invariant. 7272 unsigned AS = Ld->getAddressSpace(); 7273 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7274 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7275 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7276 return SDValue(); 7277 7278 // Don't do this early, since it may interfere with adjacent load merging for 7279 // illegal types. We can avoid losing alignment information for exotic types 7280 // pre-legalize. 7281 EVT MemVT = Ld->getMemoryVT(); 7282 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7283 MemVT.getSizeInBits() >= 32) 7284 return SDValue(); 7285 7286 SDLoc SL(Ld); 7287 7288 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7289 "unexpected vector extload"); 7290 7291 // TODO: Drop only high part of range. 7292 SDValue Ptr = Ld->getBasePtr(); 7293 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7294 MVT::i32, SL, Ld->getChain(), Ptr, 7295 Ld->getOffset(), 7296 Ld->getPointerInfo(), MVT::i32, 7297 Ld->getAlignment(), 7298 Ld->getMemOperand()->getFlags(), 7299 Ld->getAAInfo(), 7300 nullptr); // Drop ranges 7301 7302 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7303 if (MemVT.isFloatingPoint()) { 7304 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7305 "unexpected fp extload"); 7306 TruncVT = MemVT.changeTypeToInteger(); 7307 } 7308 7309 SDValue Cvt = NewLoad; 7310 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7311 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7312 DAG.getValueType(TruncVT)); 7313 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7314 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7315 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7316 } else { 7317 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7318 } 7319 7320 EVT VT = Ld->getValueType(0); 7321 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7322 7323 DCI.AddToWorklist(Cvt.getNode()); 7324 7325 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7326 // the appropriate extension from the 32-bit load. 7327 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7328 DCI.AddToWorklist(Cvt.getNode()); 7329 7330 // Handle conversion back to floating point if necessary. 7331 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7332 7333 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7334 } 7335 7336 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7337 SDLoc DL(Op); 7338 LoadSDNode *Load = cast<LoadSDNode>(Op); 7339 ISD::LoadExtType ExtType = Load->getExtensionType(); 7340 EVT MemVT = Load->getMemoryVT(); 7341 7342 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7343 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7344 return SDValue(); 7345 7346 // FIXME: Copied from PPC 7347 // First, load into 32 bits, then truncate to 1 bit. 7348 7349 SDValue Chain = Load->getChain(); 7350 SDValue BasePtr = Load->getBasePtr(); 7351 MachineMemOperand *MMO = Load->getMemOperand(); 7352 7353 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7354 7355 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7356 BasePtr, RealMemVT, MMO); 7357 7358 if (!MemVT.isVector()) { 7359 SDValue Ops[] = { 7360 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7361 NewLD.getValue(1) 7362 }; 7363 7364 return DAG.getMergeValues(Ops, DL); 7365 } 7366 7367 SmallVector<SDValue, 3> Elts; 7368 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7369 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7370 DAG.getConstant(I, DL, MVT::i32)); 7371 7372 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7373 } 7374 7375 SDValue Ops[] = { 7376 DAG.getBuildVector(MemVT, DL, Elts), 7377 NewLD.getValue(1) 7378 }; 7379 7380 return DAG.getMergeValues(Ops, DL); 7381 } 7382 7383 if (!MemVT.isVector()) 7384 return SDValue(); 7385 7386 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7387 "Custom lowering for non-i32 vectors hasn't been implemented."); 7388 7389 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7390 MemVT, *Load->getMemOperand())) { 7391 SDValue Ops[2]; 7392 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7393 return DAG.getMergeValues(Ops, DL); 7394 } 7395 7396 unsigned Alignment = Load->getAlignment(); 7397 unsigned AS = Load->getAddressSpace(); 7398 if (Subtarget->hasLDSMisalignedBug() && 7399 AS == AMDGPUAS::FLAT_ADDRESS && 7400 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7401 return SplitVectorLoad(Op, DAG); 7402 } 7403 7404 MachineFunction &MF = DAG.getMachineFunction(); 7405 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7406 // If there is a possibilty that flat instruction access scratch memory 7407 // then we need to use the same legalization rules we use for private. 7408 if (AS == AMDGPUAS::FLAT_ADDRESS) 7409 AS = MFI->hasFlatScratchInit() ? 7410 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7411 7412 unsigned NumElements = MemVT.getVectorNumElements(); 7413 7414 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7415 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7416 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7417 if (MemVT.isPow2VectorType()) 7418 return SDValue(); 7419 if (NumElements == 3) 7420 return WidenVectorLoad(Op, DAG); 7421 return SplitVectorLoad(Op, DAG); 7422 } 7423 // Non-uniform loads will be selected to MUBUF instructions, so they 7424 // have the same legalization requirements as global and private 7425 // loads. 7426 // 7427 } 7428 7429 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7430 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7431 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7432 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7433 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 7434 Alignment >= 4 && NumElements < 32) { 7435 if (MemVT.isPow2VectorType()) 7436 return SDValue(); 7437 if (NumElements == 3) 7438 return WidenVectorLoad(Op, DAG); 7439 return SplitVectorLoad(Op, DAG); 7440 } 7441 // Non-uniform loads will be selected to MUBUF instructions, so they 7442 // have the same legalization requirements as global and private 7443 // loads. 7444 // 7445 } 7446 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7447 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7448 AS == AMDGPUAS::GLOBAL_ADDRESS || 7449 AS == AMDGPUAS::FLAT_ADDRESS) { 7450 if (NumElements > 4) 7451 return SplitVectorLoad(Op, DAG); 7452 // v3 loads not supported on SI. 7453 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7454 return WidenVectorLoad(Op, DAG); 7455 // v3 and v4 loads are supported for private and global memory. 7456 return SDValue(); 7457 } 7458 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7459 // Depending on the setting of the private_element_size field in the 7460 // resource descriptor, we can only make private accesses up to a certain 7461 // size. 7462 switch (Subtarget->getMaxPrivateElementSize()) { 7463 case 4: 7464 return scalarizeVectorLoad(Load, DAG); 7465 case 8: 7466 if (NumElements > 2) 7467 return SplitVectorLoad(Op, DAG); 7468 return SDValue(); 7469 case 16: 7470 // Same as global/flat 7471 if (NumElements > 4) 7472 return SplitVectorLoad(Op, DAG); 7473 // v3 loads not supported on SI. 7474 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7475 return WidenVectorLoad(Op, DAG); 7476 return SDValue(); 7477 default: 7478 llvm_unreachable("unsupported private_element_size"); 7479 } 7480 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7481 // Use ds_read_b128 if possible. 7482 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7483 MemVT.getStoreSize() == 16) 7484 return SDValue(); 7485 7486 if (NumElements > 2) 7487 return SplitVectorLoad(Op, DAG); 7488 7489 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7490 // address is negative, then the instruction is incorrectly treated as 7491 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7492 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7493 // load later in the SILoadStoreOptimizer. 7494 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7495 NumElements == 2 && MemVT.getStoreSize() == 8 && 7496 Load->getAlignment() < 8) { 7497 return SplitVectorLoad(Op, DAG); 7498 } 7499 } 7500 return SDValue(); 7501 } 7502 7503 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7504 EVT VT = Op.getValueType(); 7505 assert(VT.getSizeInBits() == 64); 7506 7507 SDLoc DL(Op); 7508 SDValue Cond = Op.getOperand(0); 7509 7510 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7511 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7512 7513 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7514 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7515 7516 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7517 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7518 7519 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7520 7521 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7522 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7523 7524 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7525 7526 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7527 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7528 } 7529 7530 // Catch division cases where we can use shortcuts with rcp and rsq 7531 // instructions. 7532 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7533 SelectionDAG &DAG) const { 7534 SDLoc SL(Op); 7535 SDValue LHS = Op.getOperand(0); 7536 SDValue RHS = Op.getOperand(1); 7537 EVT VT = Op.getValueType(); 7538 const SDNodeFlags Flags = Op->getFlags(); 7539 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal(); 7540 7541 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals()) 7542 return SDValue(); 7543 7544 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7545 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) { 7546 if (CLHS->isExactlyValue(1.0)) { 7547 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7548 // the CI documentation has a worst case error of 1 ulp. 7549 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7550 // use it as long as we aren't trying to use denormals. 7551 // 7552 // v_rcp_f16 and v_rsq_f16 DO support denormals. 7553 7554 // 1.0 / sqrt(x) -> rsq(x) 7555 7556 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 7557 // error seems really high at 2^29 ULP. 7558 if (RHS.getOpcode() == ISD::FSQRT) 7559 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 7560 7561 // 1.0 / x -> rcp(x) 7562 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7563 } 7564 7565 // Same as for 1.0, but expand the sign out of the constant. 7566 if (CLHS->isExactlyValue(-1.0)) { 7567 // -1.0 / x -> rcp (fneg x) 7568 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7569 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 7570 } 7571 } 7572 } 7573 7574 if (Unsafe) { 7575 // Turn into multiply by the reciprocal. 7576 // x / y -> x * (1.0 / y) 7577 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7578 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 7579 } 7580 7581 return SDValue(); 7582 } 7583 7584 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7585 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 7586 if (GlueChain->getNumValues() <= 1) { 7587 return DAG.getNode(Opcode, SL, VT, A, B); 7588 } 7589 7590 assert(GlueChain->getNumValues() == 3); 7591 7592 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7593 switch (Opcode) { 7594 default: llvm_unreachable("no chain equivalent for opcode"); 7595 case ISD::FMUL: 7596 Opcode = AMDGPUISD::FMUL_W_CHAIN; 7597 break; 7598 } 7599 7600 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 7601 GlueChain.getValue(2)); 7602 } 7603 7604 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7605 EVT VT, SDValue A, SDValue B, SDValue C, 7606 SDValue GlueChain) { 7607 if (GlueChain->getNumValues() <= 1) { 7608 return DAG.getNode(Opcode, SL, VT, A, B, C); 7609 } 7610 7611 assert(GlueChain->getNumValues() == 3); 7612 7613 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7614 switch (Opcode) { 7615 default: llvm_unreachable("no chain equivalent for opcode"); 7616 case ISD::FMA: 7617 Opcode = AMDGPUISD::FMA_W_CHAIN; 7618 break; 7619 } 7620 7621 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 7622 GlueChain.getValue(2)); 7623 } 7624 7625 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 7626 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7627 return FastLowered; 7628 7629 SDLoc SL(Op); 7630 SDValue Src0 = Op.getOperand(0); 7631 SDValue Src1 = Op.getOperand(1); 7632 7633 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 7634 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 7635 7636 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 7637 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 7638 7639 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 7640 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 7641 7642 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 7643 } 7644 7645 // Faster 2.5 ULP division that does not support denormals. 7646 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 7647 SDLoc SL(Op); 7648 SDValue LHS = Op.getOperand(1); 7649 SDValue RHS = Op.getOperand(2); 7650 7651 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 7652 7653 const APFloat K0Val(BitsToFloat(0x6f800000)); 7654 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 7655 7656 const APFloat K1Val(BitsToFloat(0x2f800000)); 7657 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 7658 7659 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7660 7661 EVT SetCCVT = 7662 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 7663 7664 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 7665 7666 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 7667 7668 // TODO: Should this propagate fast-math-flags? 7669 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 7670 7671 // rcp does not support denormals. 7672 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 7673 7674 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 7675 7676 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 7677 } 7678 7679 // Returns immediate value for setting the F32 denorm mode when using the 7680 // S_DENORM_MODE instruction. 7681 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 7682 const SDLoc &SL, const GCNSubtarget *ST) { 7683 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 7684 int DPDenormModeDefault = ST->hasFP64Denormals() 7685 ? FP_DENORM_FLUSH_NONE 7686 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 7687 7688 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 7689 return DAG.getTargetConstant(Mode, SL, MVT::i32); 7690 } 7691 7692 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 7693 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7694 return FastLowered; 7695 7696 SDLoc SL(Op); 7697 SDValue LHS = Op.getOperand(0); 7698 SDValue RHS = Op.getOperand(1); 7699 7700 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7701 7702 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 7703 7704 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7705 RHS, RHS, LHS); 7706 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7707 LHS, RHS, LHS); 7708 7709 // Denominator is scaled to not be denormal, so using rcp is ok. 7710 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 7711 DenominatorScaled); 7712 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 7713 DenominatorScaled); 7714 7715 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 7716 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 7717 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 7718 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 7719 7720 if (!Subtarget->hasFP32Denormals()) { 7721 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 7722 7723 SDValue EnableDenorm; 7724 if (Subtarget->hasDenormModeInst()) { 7725 const SDValue EnableDenormValue = 7726 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 7727 7728 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 7729 DAG.getEntryNode(), EnableDenormValue); 7730 } else { 7731 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 7732 SL, MVT::i32); 7733 EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 7734 DAG.getEntryNode(), EnableDenormValue, 7735 BitField); 7736 } 7737 7738 SDValue Ops[3] = { 7739 NegDivScale0, 7740 EnableDenorm.getValue(0), 7741 EnableDenorm.getValue(1) 7742 }; 7743 7744 NegDivScale0 = DAG.getMergeValues(Ops, SL); 7745 } 7746 7747 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 7748 ApproxRcp, One, NegDivScale0); 7749 7750 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 7751 ApproxRcp, Fma0); 7752 7753 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 7754 Fma1, Fma1); 7755 7756 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 7757 NumeratorScaled, Mul); 7758 7759 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 7760 7761 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 7762 NumeratorScaled, Fma3); 7763 7764 if (!Subtarget->hasFP32Denormals()) { 7765 7766 SDValue DisableDenorm; 7767 if (Subtarget->hasDenormModeInst()) { 7768 const SDValue DisableDenormValue = 7769 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 7770 7771 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 7772 Fma4.getValue(1), DisableDenormValue, 7773 Fma4.getValue(2)); 7774 } else { 7775 const SDValue DisableDenormValue = 7776 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 7777 7778 DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 7779 Fma4.getValue(1), DisableDenormValue, 7780 BitField, Fma4.getValue(2)); 7781 } 7782 7783 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 7784 DisableDenorm, DAG.getRoot()); 7785 DAG.setRoot(OutputChain); 7786 } 7787 7788 SDValue Scale = NumeratorScaled.getValue(1); 7789 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 7790 Fma4, Fma1, Fma3, Scale); 7791 7792 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 7793 } 7794 7795 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 7796 if (DAG.getTarget().Options.UnsafeFPMath) 7797 return lowerFastUnsafeFDIV(Op, DAG); 7798 7799 SDLoc SL(Op); 7800 SDValue X = Op.getOperand(0); 7801 SDValue Y = Op.getOperand(1); 7802 7803 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 7804 7805 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 7806 7807 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 7808 7809 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 7810 7811 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 7812 7813 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 7814 7815 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 7816 7817 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 7818 7819 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 7820 7821 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 7822 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 7823 7824 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 7825 NegDivScale0, Mul, DivScale1); 7826 7827 SDValue Scale; 7828 7829 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 7830 // Workaround a hardware bug on SI where the condition output from div_scale 7831 // is not usable. 7832 7833 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 7834 7835 // Figure out if the scale to use for div_fmas. 7836 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 7837 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 7838 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 7839 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 7840 7841 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 7842 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 7843 7844 SDValue Scale0Hi 7845 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 7846 SDValue Scale1Hi 7847 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 7848 7849 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 7850 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 7851 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 7852 } else { 7853 Scale = DivScale1.getValue(1); 7854 } 7855 7856 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 7857 Fma4, Fma3, Mul, Scale); 7858 7859 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 7860 } 7861 7862 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 7863 EVT VT = Op.getValueType(); 7864 7865 if (VT == MVT::f32) 7866 return LowerFDIV32(Op, DAG); 7867 7868 if (VT == MVT::f64) 7869 return LowerFDIV64(Op, DAG); 7870 7871 if (VT == MVT::f16) 7872 return LowerFDIV16(Op, DAG); 7873 7874 llvm_unreachable("Unexpected type for fdiv"); 7875 } 7876 7877 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7878 SDLoc DL(Op); 7879 StoreSDNode *Store = cast<StoreSDNode>(Op); 7880 EVT VT = Store->getMemoryVT(); 7881 7882 if (VT == MVT::i1) { 7883 return DAG.getTruncStore(Store->getChain(), DL, 7884 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 7885 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 7886 } 7887 7888 assert(VT.isVector() && 7889 Store->getValue().getValueType().getScalarType() == MVT::i32); 7890 7891 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7892 VT, *Store->getMemOperand())) { 7893 return expandUnalignedStore(Store, DAG); 7894 } 7895 7896 unsigned AS = Store->getAddressSpace(); 7897 if (Subtarget->hasLDSMisalignedBug() && 7898 AS == AMDGPUAS::FLAT_ADDRESS && 7899 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 7900 return SplitVectorStore(Op, DAG); 7901 } 7902 7903 MachineFunction &MF = DAG.getMachineFunction(); 7904 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7905 // If there is a possibilty that flat instruction access scratch memory 7906 // then we need to use the same legalization rules we use for private. 7907 if (AS == AMDGPUAS::FLAT_ADDRESS) 7908 AS = MFI->hasFlatScratchInit() ? 7909 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7910 7911 unsigned NumElements = VT.getVectorNumElements(); 7912 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 7913 AS == AMDGPUAS::FLAT_ADDRESS) { 7914 if (NumElements > 4) 7915 return SplitVectorStore(Op, DAG); 7916 // v3 stores not supported on SI. 7917 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7918 return SplitVectorStore(Op, DAG); 7919 return SDValue(); 7920 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7921 switch (Subtarget->getMaxPrivateElementSize()) { 7922 case 4: 7923 return scalarizeVectorStore(Store, DAG); 7924 case 8: 7925 if (NumElements > 2) 7926 return SplitVectorStore(Op, DAG); 7927 return SDValue(); 7928 case 16: 7929 if (NumElements > 4 || NumElements == 3) 7930 return SplitVectorStore(Op, DAG); 7931 return SDValue(); 7932 default: 7933 llvm_unreachable("unsupported private_element_size"); 7934 } 7935 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7936 // Use ds_write_b128 if possible. 7937 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 7938 VT.getStoreSize() == 16 && NumElements != 3) 7939 return SDValue(); 7940 7941 if (NumElements > 2) 7942 return SplitVectorStore(Op, DAG); 7943 7944 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7945 // address is negative, then the instruction is incorrectly treated as 7946 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7947 // stores here to avoid emitting ds_write2_b32. We may re-combine the 7948 // store later in the SILoadStoreOptimizer. 7949 if (!Subtarget->hasUsableDSOffset() && 7950 NumElements == 2 && VT.getStoreSize() == 8 && 7951 Store->getAlignment() < 8) { 7952 return SplitVectorStore(Op, DAG); 7953 } 7954 7955 return SDValue(); 7956 } else { 7957 llvm_unreachable("unhandled address space"); 7958 } 7959 } 7960 7961 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 7962 SDLoc DL(Op); 7963 EVT VT = Op.getValueType(); 7964 SDValue Arg = Op.getOperand(0); 7965 SDValue TrigVal; 7966 7967 // TODO: Should this propagate fast-math-flags? 7968 7969 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT); 7970 7971 if (Subtarget->hasTrigReducedRange()) { 7972 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7973 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal); 7974 } else { 7975 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7976 } 7977 7978 switch (Op.getOpcode()) { 7979 case ISD::FCOS: 7980 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal); 7981 case ISD::FSIN: 7982 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal); 7983 default: 7984 llvm_unreachable("Wrong trig opcode"); 7985 } 7986 } 7987 7988 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 7989 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 7990 assert(AtomicNode->isCompareAndSwap()); 7991 unsigned AS = AtomicNode->getAddressSpace(); 7992 7993 // No custom lowering required for local address space 7994 if (!isFlatGlobalAddrSpace(AS)) 7995 return Op; 7996 7997 // Non-local address space requires custom lowering for atomic compare 7998 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 7999 SDLoc DL(Op); 8000 SDValue ChainIn = Op.getOperand(0); 8001 SDValue Addr = Op.getOperand(1); 8002 SDValue Old = Op.getOperand(2); 8003 SDValue New = Op.getOperand(3); 8004 EVT VT = Op.getValueType(); 8005 MVT SimpleVT = VT.getSimpleVT(); 8006 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8007 8008 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8009 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8010 8011 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8012 Ops, VT, AtomicNode->getMemOperand()); 8013 } 8014 8015 //===----------------------------------------------------------------------===// 8016 // Custom DAG optimizations 8017 //===----------------------------------------------------------------------===// 8018 8019 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8020 DAGCombinerInfo &DCI) const { 8021 EVT VT = N->getValueType(0); 8022 EVT ScalarVT = VT.getScalarType(); 8023 if (ScalarVT != MVT::f32) 8024 return SDValue(); 8025 8026 SelectionDAG &DAG = DCI.DAG; 8027 SDLoc DL(N); 8028 8029 SDValue Src = N->getOperand(0); 8030 EVT SrcVT = Src.getValueType(); 8031 8032 // TODO: We could try to match extracting the higher bytes, which would be 8033 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8034 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8035 // about in practice. 8036 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8037 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8038 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 8039 DCI.AddToWorklist(Cvt.getNode()); 8040 return Cvt; 8041 } 8042 } 8043 8044 return SDValue(); 8045 } 8046 8047 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8048 8049 // This is a variant of 8050 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8051 // 8052 // The normal DAG combiner will do this, but only if the add has one use since 8053 // that would increase the number of instructions. 8054 // 8055 // This prevents us from seeing a constant offset that can be folded into a 8056 // memory instruction's addressing mode. If we know the resulting add offset of 8057 // a pointer can be folded into an addressing offset, we can replace the pointer 8058 // operand with the add of new constant offset. This eliminates one of the uses, 8059 // and may allow the remaining use to also be simplified. 8060 // 8061 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8062 unsigned AddrSpace, 8063 EVT MemVT, 8064 DAGCombinerInfo &DCI) const { 8065 SDValue N0 = N->getOperand(0); 8066 SDValue N1 = N->getOperand(1); 8067 8068 // We only do this to handle cases where it's profitable when there are 8069 // multiple uses of the add, so defer to the standard combine. 8070 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8071 N0->hasOneUse()) 8072 return SDValue(); 8073 8074 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8075 if (!CN1) 8076 return SDValue(); 8077 8078 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8079 if (!CAdd) 8080 return SDValue(); 8081 8082 // If the resulting offset is too large, we can't fold it into the addressing 8083 // mode offset. 8084 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8085 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8086 8087 AddrMode AM; 8088 AM.HasBaseReg = true; 8089 AM.BaseOffs = Offset.getSExtValue(); 8090 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8091 return SDValue(); 8092 8093 SelectionDAG &DAG = DCI.DAG; 8094 SDLoc SL(N); 8095 EVT VT = N->getValueType(0); 8096 8097 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8098 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 8099 8100 SDNodeFlags Flags; 8101 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8102 (N0.getOpcode() == ISD::OR || 8103 N0->getFlags().hasNoUnsignedWrap())); 8104 8105 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8106 } 8107 8108 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8109 DAGCombinerInfo &DCI) const { 8110 SDValue Ptr = N->getBasePtr(); 8111 SelectionDAG &DAG = DCI.DAG; 8112 SDLoc SL(N); 8113 8114 // TODO: We could also do this for multiplies. 8115 if (Ptr.getOpcode() == ISD::SHL) { 8116 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8117 N->getMemoryVT(), DCI); 8118 if (NewPtr) { 8119 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8120 8121 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8122 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8123 } 8124 } 8125 8126 return SDValue(); 8127 } 8128 8129 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8130 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8131 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8132 (Opc == ISD::XOR && Val == 0); 8133 } 8134 8135 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8136 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8137 // integer combine opportunities since most 64-bit operations are decomposed 8138 // this way. TODO: We won't want this for SALU especially if it is an inline 8139 // immediate. 8140 SDValue SITargetLowering::splitBinaryBitConstantOp( 8141 DAGCombinerInfo &DCI, 8142 const SDLoc &SL, 8143 unsigned Opc, SDValue LHS, 8144 const ConstantSDNode *CRHS) const { 8145 uint64_t Val = CRHS->getZExtValue(); 8146 uint32_t ValLo = Lo_32(Val); 8147 uint32_t ValHi = Hi_32(Val); 8148 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8149 8150 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8151 bitOpWithConstantIsReducible(Opc, ValHi)) || 8152 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8153 // If we need to materialize a 64-bit immediate, it will be split up later 8154 // anyway. Avoid creating the harder to understand 64-bit immediate 8155 // materialization. 8156 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8157 } 8158 8159 return SDValue(); 8160 } 8161 8162 // Returns true if argument is a boolean value which is not serialized into 8163 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8164 static bool isBoolSGPR(SDValue V) { 8165 if (V.getValueType() != MVT::i1) 8166 return false; 8167 switch (V.getOpcode()) { 8168 default: break; 8169 case ISD::SETCC: 8170 case ISD::AND: 8171 case ISD::OR: 8172 case ISD::XOR: 8173 case AMDGPUISD::FP_CLASS: 8174 return true; 8175 } 8176 return false; 8177 } 8178 8179 // If a constant has all zeroes or all ones within each byte return it. 8180 // Otherwise return 0. 8181 static uint32_t getConstantPermuteMask(uint32_t C) { 8182 // 0xff for any zero byte in the mask 8183 uint32_t ZeroByteMask = 0; 8184 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8185 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8186 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8187 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8188 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8189 if ((NonZeroByteMask & C) != NonZeroByteMask) 8190 return 0; // Partial bytes selected. 8191 return C; 8192 } 8193 8194 // Check if a node selects whole bytes from its operand 0 starting at a byte 8195 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8196 // or -1 if not succeeded. 8197 // Note byte select encoding: 8198 // value 0-3 selects corresponding source byte; 8199 // value 0xc selects zero; 8200 // value 0xff selects 0xff. 8201 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8202 assert(V.getValueSizeInBits() == 32); 8203 8204 if (V.getNumOperands() != 2) 8205 return ~0; 8206 8207 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8208 if (!N1) 8209 return ~0; 8210 8211 uint32_t C = N1->getZExtValue(); 8212 8213 switch (V.getOpcode()) { 8214 default: 8215 break; 8216 case ISD::AND: 8217 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8218 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8219 } 8220 break; 8221 8222 case ISD::OR: 8223 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8224 return (0x03020100 & ~ConstMask) | ConstMask; 8225 } 8226 break; 8227 8228 case ISD::SHL: 8229 if (C % 8) 8230 return ~0; 8231 8232 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8233 8234 case ISD::SRL: 8235 if (C % 8) 8236 return ~0; 8237 8238 return uint32_t(0x0c0c0c0c03020100ull >> C); 8239 } 8240 8241 return ~0; 8242 } 8243 8244 SDValue SITargetLowering::performAndCombine(SDNode *N, 8245 DAGCombinerInfo &DCI) const { 8246 if (DCI.isBeforeLegalize()) 8247 return SDValue(); 8248 8249 SelectionDAG &DAG = DCI.DAG; 8250 EVT VT = N->getValueType(0); 8251 SDValue LHS = N->getOperand(0); 8252 SDValue RHS = N->getOperand(1); 8253 8254 8255 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8256 if (VT == MVT::i64 && CRHS) { 8257 if (SDValue Split 8258 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8259 return Split; 8260 } 8261 8262 if (CRHS && VT == MVT::i32) { 8263 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8264 // nb = number of trailing zeroes in mask 8265 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8266 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8267 uint64_t Mask = CRHS->getZExtValue(); 8268 unsigned Bits = countPopulation(Mask); 8269 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8270 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8271 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8272 unsigned Shift = CShift->getZExtValue(); 8273 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8274 unsigned Offset = NB + Shift; 8275 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8276 SDLoc SL(N); 8277 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8278 LHS->getOperand(0), 8279 DAG.getConstant(Offset, SL, MVT::i32), 8280 DAG.getConstant(Bits, SL, MVT::i32)); 8281 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8282 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8283 DAG.getValueType(NarrowVT)); 8284 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8285 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8286 return Shl; 8287 } 8288 } 8289 } 8290 8291 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8292 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8293 isa<ConstantSDNode>(LHS.getOperand(2))) { 8294 uint32_t Sel = getConstantPermuteMask(Mask); 8295 if (!Sel) 8296 return SDValue(); 8297 8298 // Select 0xc for all zero bytes 8299 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8300 SDLoc DL(N); 8301 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8302 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8303 } 8304 } 8305 8306 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8307 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8308 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8309 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8310 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8311 8312 SDValue X = LHS.getOperand(0); 8313 SDValue Y = RHS.getOperand(0); 8314 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8315 return SDValue(); 8316 8317 if (LCC == ISD::SETO) { 8318 if (X != LHS.getOperand(1)) 8319 return SDValue(); 8320 8321 if (RCC == ISD::SETUNE) { 8322 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8323 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8324 return SDValue(); 8325 8326 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8327 SIInstrFlags::N_SUBNORMAL | 8328 SIInstrFlags::N_ZERO | 8329 SIInstrFlags::P_ZERO | 8330 SIInstrFlags::P_SUBNORMAL | 8331 SIInstrFlags::P_NORMAL; 8332 8333 static_assert(((~(SIInstrFlags::S_NAN | 8334 SIInstrFlags::Q_NAN | 8335 SIInstrFlags::N_INFINITY | 8336 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8337 "mask not equal"); 8338 8339 SDLoc DL(N); 8340 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8341 X, DAG.getConstant(Mask, DL, MVT::i32)); 8342 } 8343 } 8344 } 8345 8346 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8347 std::swap(LHS, RHS); 8348 8349 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8350 RHS.hasOneUse()) { 8351 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8352 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8353 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8354 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8355 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8356 (RHS.getOperand(0) == LHS.getOperand(0) && 8357 LHS.getOperand(0) == LHS.getOperand(1))) { 8358 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8359 unsigned NewMask = LCC == ISD::SETO ? 8360 Mask->getZExtValue() & ~OrdMask : 8361 Mask->getZExtValue() & OrdMask; 8362 8363 SDLoc DL(N); 8364 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8365 DAG.getConstant(NewMask, DL, MVT::i32)); 8366 } 8367 } 8368 8369 if (VT == MVT::i32 && 8370 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8371 // and x, (sext cc from i1) => select cc, x, 0 8372 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8373 std::swap(LHS, RHS); 8374 if (isBoolSGPR(RHS.getOperand(0))) 8375 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8376 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8377 } 8378 8379 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8380 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8381 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8382 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8383 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8384 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8385 if (LHSMask != ~0u && RHSMask != ~0u) { 8386 // Canonicalize the expression in an attempt to have fewer unique masks 8387 // and therefore fewer registers used to hold the masks. 8388 if (LHSMask > RHSMask) { 8389 std::swap(LHSMask, RHSMask); 8390 std::swap(LHS, RHS); 8391 } 8392 8393 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8394 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8395 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8396 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8397 8398 // Check of we need to combine values from two sources within a byte. 8399 if (!(LHSUsedLanes & RHSUsedLanes) && 8400 // If we select high and lower word keep it for SDWA. 8401 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8402 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8403 // Each byte in each mask is either selector mask 0-3, or has higher 8404 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8405 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8406 // mask which is not 0xff wins. By anding both masks we have a correct 8407 // result except that 0x0c shall be corrected to give 0x0c only. 8408 uint32_t Mask = LHSMask & RHSMask; 8409 for (unsigned I = 0; I < 32; I += 8) { 8410 uint32_t ByteSel = 0xff << I; 8411 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8412 Mask &= (0x0c << I) & 0xffffffff; 8413 } 8414 8415 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8416 // or 0x0c. 8417 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8418 SDLoc DL(N); 8419 8420 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8421 LHS.getOperand(0), RHS.getOperand(0), 8422 DAG.getConstant(Sel, DL, MVT::i32)); 8423 } 8424 } 8425 } 8426 8427 return SDValue(); 8428 } 8429 8430 SDValue SITargetLowering::performOrCombine(SDNode *N, 8431 DAGCombinerInfo &DCI) const { 8432 SelectionDAG &DAG = DCI.DAG; 8433 SDValue LHS = N->getOperand(0); 8434 SDValue RHS = N->getOperand(1); 8435 8436 EVT VT = N->getValueType(0); 8437 if (VT == MVT::i1) { 8438 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8439 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8440 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8441 SDValue Src = LHS.getOperand(0); 8442 if (Src != RHS.getOperand(0)) 8443 return SDValue(); 8444 8445 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8446 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8447 if (!CLHS || !CRHS) 8448 return SDValue(); 8449 8450 // Only 10 bits are used. 8451 static const uint32_t MaxMask = 0x3ff; 8452 8453 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8454 SDLoc DL(N); 8455 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8456 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8457 } 8458 8459 return SDValue(); 8460 } 8461 8462 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8463 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8464 LHS.getOpcode() == AMDGPUISD::PERM && 8465 isa<ConstantSDNode>(LHS.getOperand(2))) { 8466 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8467 if (!Sel) 8468 return SDValue(); 8469 8470 Sel |= LHS.getConstantOperandVal(2); 8471 SDLoc DL(N); 8472 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8473 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8474 } 8475 8476 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8477 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8478 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8479 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8480 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8481 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8482 if (LHSMask != ~0u && RHSMask != ~0u) { 8483 // Canonicalize the expression in an attempt to have fewer unique masks 8484 // and therefore fewer registers used to hold the masks. 8485 if (LHSMask > RHSMask) { 8486 std::swap(LHSMask, RHSMask); 8487 std::swap(LHS, RHS); 8488 } 8489 8490 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8491 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8492 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8493 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8494 8495 // Check of we need to combine values from two sources within a byte. 8496 if (!(LHSUsedLanes & RHSUsedLanes) && 8497 // If we select high and lower word keep it for SDWA. 8498 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8499 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8500 // Kill zero bytes selected by other mask. Zero value is 0xc. 8501 LHSMask &= ~RHSUsedLanes; 8502 RHSMask &= ~LHSUsedLanes; 8503 // Add 4 to each active LHS lane 8504 LHSMask |= LHSUsedLanes & 0x04040404; 8505 // Combine masks 8506 uint32_t Sel = LHSMask | RHSMask; 8507 SDLoc DL(N); 8508 8509 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8510 LHS.getOperand(0), RHS.getOperand(0), 8511 DAG.getConstant(Sel, DL, MVT::i32)); 8512 } 8513 } 8514 } 8515 8516 if (VT != MVT::i64) 8517 return SDValue(); 8518 8519 // TODO: This could be a generic combine with a predicate for extracting the 8520 // high half of an integer being free. 8521 8522 // (or i64:x, (zero_extend i32:y)) -> 8523 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8524 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8525 RHS.getOpcode() != ISD::ZERO_EXTEND) 8526 std::swap(LHS, RHS); 8527 8528 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8529 SDValue ExtSrc = RHS.getOperand(0); 8530 EVT SrcVT = ExtSrc.getValueType(); 8531 if (SrcVT == MVT::i32) { 8532 SDLoc SL(N); 8533 SDValue LowLHS, HiBits; 8534 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 8535 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 8536 8537 DCI.AddToWorklist(LowOr.getNode()); 8538 DCI.AddToWorklist(HiBits.getNode()); 8539 8540 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 8541 LowOr, HiBits); 8542 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 8543 } 8544 } 8545 8546 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8547 if (CRHS) { 8548 if (SDValue Split 8549 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 8550 return Split; 8551 } 8552 8553 return SDValue(); 8554 } 8555 8556 SDValue SITargetLowering::performXorCombine(SDNode *N, 8557 DAGCombinerInfo &DCI) const { 8558 EVT VT = N->getValueType(0); 8559 if (VT != MVT::i64) 8560 return SDValue(); 8561 8562 SDValue LHS = N->getOperand(0); 8563 SDValue RHS = N->getOperand(1); 8564 8565 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8566 if (CRHS) { 8567 if (SDValue Split 8568 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 8569 return Split; 8570 } 8571 8572 return SDValue(); 8573 } 8574 8575 // Instructions that will be lowered with a final instruction that zeros the 8576 // high result bits. 8577 // XXX - probably only need to list legal operations. 8578 static bool fp16SrcZerosHighBits(unsigned Opc) { 8579 switch (Opc) { 8580 case ISD::FADD: 8581 case ISD::FSUB: 8582 case ISD::FMUL: 8583 case ISD::FDIV: 8584 case ISD::FREM: 8585 case ISD::FMA: 8586 case ISD::FMAD: 8587 case ISD::FCANONICALIZE: 8588 case ISD::FP_ROUND: 8589 case ISD::UINT_TO_FP: 8590 case ISD::SINT_TO_FP: 8591 case ISD::FABS: 8592 // Fabs is lowered to a bit operation, but it's an and which will clear the 8593 // high bits anyway. 8594 case ISD::FSQRT: 8595 case ISD::FSIN: 8596 case ISD::FCOS: 8597 case ISD::FPOWI: 8598 case ISD::FPOW: 8599 case ISD::FLOG: 8600 case ISD::FLOG2: 8601 case ISD::FLOG10: 8602 case ISD::FEXP: 8603 case ISD::FEXP2: 8604 case ISD::FCEIL: 8605 case ISD::FTRUNC: 8606 case ISD::FRINT: 8607 case ISD::FNEARBYINT: 8608 case ISD::FROUND: 8609 case ISD::FFLOOR: 8610 case ISD::FMINNUM: 8611 case ISD::FMAXNUM: 8612 case AMDGPUISD::FRACT: 8613 case AMDGPUISD::CLAMP: 8614 case AMDGPUISD::COS_HW: 8615 case AMDGPUISD::SIN_HW: 8616 case AMDGPUISD::FMIN3: 8617 case AMDGPUISD::FMAX3: 8618 case AMDGPUISD::FMED3: 8619 case AMDGPUISD::FMAD_FTZ: 8620 case AMDGPUISD::RCP: 8621 case AMDGPUISD::RSQ: 8622 case AMDGPUISD::RCP_IFLAG: 8623 case AMDGPUISD::LDEXP: 8624 return true; 8625 default: 8626 // fcopysign, select and others may be lowered to 32-bit bit operations 8627 // which don't zero the high bits. 8628 return false; 8629 } 8630 } 8631 8632 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 8633 DAGCombinerInfo &DCI) const { 8634 if (!Subtarget->has16BitInsts() || 8635 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8636 return SDValue(); 8637 8638 EVT VT = N->getValueType(0); 8639 if (VT != MVT::i32) 8640 return SDValue(); 8641 8642 SDValue Src = N->getOperand(0); 8643 if (Src.getValueType() != MVT::i16) 8644 return SDValue(); 8645 8646 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 8647 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 8648 if (Src.getOpcode() == ISD::BITCAST) { 8649 SDValue BCSrc = Src.getOperand(0); 8650 if (BCSrc.getValueType() == MVT::f16 && 8651 fp16SrcZerosHighBits(BCSrc.getOpcode())) 8652 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 8653 } 8654 8655 return SDValue(); 8656 } 8657 8658 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 8659 DAGCombinerInfo &DCI) 8660 const { 8661 SDValue Src = N->getOperand(0); 8662 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 8663 8664 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 8665 VTSign->getVT() == MVT::i8) || 8666 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 8667 VTSign->getVT() == MVT::i16)) && 8668 Src.hasOneUse()) { 8669 auto *M = cast<MemSDNode>(Src); 8670 SDValue Ops[] = { 8671 Src.getOperand(0), // Chain 8672 Src.getOperand(1), // rsrc 8673 Src.getOperand(2), // vindex 8674 Src.getOperand(3), // voffset 8675 Src.getOperand(4), // soffset 8676 Src.getOperand(5), // offset 8677 Src.getOperand(6), 8678 Src.getOperand(7) 8679 }; 8680 // replace with BUFFER_LOAD_BYTE/SHORT 8681 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 8682 Src.getOperand(0).getValueType()); 8683 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 8684 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 8685 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 8686 ResList, 8687 Ops, M->getMemoryVT(), 8688 M->getMemOperand()); 8689 return DCI.DAG.getMergeValues({BufferLoadSignExt, 8690 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 8691 } 8692 return SDValue(); 8693 } 8694 8695 SDValue SITargetLowering::performClassCombine(SDNode *N, 8696 DAGCombinerInfo &DCI) const { 8697 SelectionDAG &DAG = DCI.DAG; 8698 SDValue Mask = N->getOperand(1); 8699 8700 // fp_class x, 0 -> false 8701 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 8702 if (CMask->isNullValue()) 8703 return DAG.getConstant(0, SDLoc(N), MVT::i1); 8704 } 8705 8706 if (N->getOperand(0).isUndef()) 8707 return DAG.getUNDEF(MVT::i1); 8708 8709 return SDValue(); 8710 } 8711 8712 SDValue SITargetLowering::performRcpCombine(SDNode *N, 8713 DAGCombinerInfo &DCI) const { 8714 EVT VT = N->getValueType(0); 8715 SDValue N0 = N->getOperand(0); 8716 8717 if (N0.isUndef()) 8718 return N0; 8719 8720 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 8721 N0.getOpcode() == ISD::SINT_TO_FP)) { 8722 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 8723 N->getFlags()); 8724 } 8725 8726 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 8727 } 8728 8729 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 8730 unsigned MaxDepth) const { 8731 unsigned Opcode = Op.getOpcode(); 8732 if (Opcode == ISD::FCANONICALIZE) 8733 return true; 8734 8735 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8736 auto F = CFP->getValueAPF(); 8737 if (F.isNaN() && F.isSignaling()) 8738 return false; 8739 return !F.isDenormal() || denormalsEnabledForType(Op.getValueType()); 8740 } 8741 8742 // If source is a result of another standard FP operation it is already in 8743 // canonical form. 8744 if (MaxDepth == 0) 8745 return false; 8746 8747 switch (Opcode) { 8748 // These will flush denorms if required. 8749 case ISD::FADD: 8750 case ISD::FSUB: 8751 case ISD::FMUL: 8752 case ISD::FCEIL: 8753 case ISD::FFLOOR: 8754 case ISD::FMA: 8755 case ISD::FMAD: 8756 case ISD::FSQRT: 8757 case ISD::FDIV: 8758 case ISD::FREM: 8759 case ISD::FP_ROUND: 8760 case ISD::FP_EXTEND: 8761 case AMDGPUISD::FMUL_LEGACY: 8762 case AMDGPUISD::FMAD_FTZ: 8763 case AMDGPUISD::RCP: 8764 case AMDGPUISD::RSQ: 8765 case AMDGPUISD::RSQ_CLAMP: 8766 case AMDGPUISD::RCP_LEGACY: 8767 case AMDGPUISD::RSQ_LEGACY: 8768 case AMDGPUISD::RCP_IFLAG: 8769 case AMDGPUISD::TRIG_PREOP: 8770 case AMDGPUISD::DIV_SCALE: 8771 case AMDGPUISD::DIV_FMAS: 8772 case AMDGPUISD::DIV_FIXUP: 8773 case AMDGPUISD::FRACT: 8774 case AMDGPUISD::LDEXP: 8775 case AMDGPUISD::CVT_PKRTZ_F16_F32: 8776 case AMDGPUISD::CVT_F32_UBYTE0: 8777 case AMDGPUISD::CVT_F32_UBYTE1: 8778 case AMDGPUISD::CVT_F32_UBYTE2: 8779 case AMDGPUISD::CVT_F32_UBYTE3: 8780 return true; 8781 8782 // It can/will be lowered or combined as a bit operation. 8783 // Need to check their input recursively to handle. 8784 case ISD::FNEG: 8785 case ISD::FABS: 8786 case ISD::FCOPYSIGN: 8787 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8788 8789 case ISD::FSIN: 8790 case ISD::FCOS: 8791 case ISD::FSINCOS: 8792 return Op.getValueType().getScalarType() != MVT::f16; 8793 8794 case ISD::FMINNUM: 8795 case ISD::FMAXNUM: 8796 case ISD::FMINNUM_IEEE: 8797 case ISD::FMAXNUM_IEEE: 8798 case AMDGPUISD::CLAMP: 8799 case AMDGPUISD::FMED3: 8800 case AMDGPUISD::FMAX3: 8801 case AMDGPUISD::FMIN3: { 8802 // FIXME: Shouldn't treat the generic operations different based these. 8803 // However, we aren't really required to flush the result from 8804 // minnum/maxnum.. 8805 8806 // snans will be quieted, so we only need to worry about denormals. 8807 if (Subtarget->supportsMinMaxDenormModes() || 8808 denormalsEnabledForType(Op.getValueType())) 8809 return true; 8810 8811 // Flushing may be required. 8812 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 8813 // targets need to check their input recursively. 8814 8815 // FIXME: Does this apply with clamp? It's implemented with max. 8816 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 8817 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 8818 return false; 8819 } 8820 8821 return true; 8822 } 8823 case ISD::SELECT: { 8824 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 8825 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 8826 } 8827 case ISD::BUILD_VECTOR: { 8828 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 8829 SDValue SrcOp = Op.getOperand(i); 8830 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 8831 return false; 8832 } 8833 8834 return true; 8835 } 8836 case ISD::EXTRACT_VECTOR_ELT: 8837 case ISD::EXTRACT_SUBVECTOR: { 8838 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8839 } 8840 case ISD::INSERT_VECTOR_ELT: { 8841 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 8842 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 8843 } 8844 case ISD::UNDEF: 8845 // Could be anything. 8846 return false; 8847 8848 case ISD::BITCAST: { 8849 // Hack round the mess we make when legalizing extract_vector_elt 8850 SDValue Src = Op.getOperand(0); 8851 if (Src.getValueType() == MVT::i16 && 8852 Src.getOpcode() == ISD::TRUNCATE) { 8853 SDValue TruncSrc = Src.getOperand(0); 8854 if (TruncSrc.getValueType() == MVT::i32 && 8855 TruncSrc.getOpcode() == ISD::BITCAST && 8856 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 8857 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 8858 } 8859 } 8860 8861 return false; 8862 } 8863 case ISD::INTRINSIC_WO_CHAIN: { 8864 unsigned IntrinsicID 8865 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8866 // TODO: Handle more intrinsics 8867 switch (IntrinsicID) { 8868 case Intrinsic::amdgcn_cvt_pkrtz: 8869 case Intrinsic::amdgcn_cubeid: 8870 case Intrinsic::amdgcn_frexp_mant: 8871 case Intrinsic::amdgcn_fdot2: 8872 return true; 8873 default: 8874 break; 8875 } 8876 8877 LLVM_FALLTHROUGH; 8878 } 8879 default: 8880 return denormalsEnabledForType(Op.getValueType()) && 8881 DAG.isKnownNeverSNaN(Op); 8882 } 8883 8884 llvm_unreachable("invalid operation"); 8885 } 8886 8887 // Constant fold canonicalize. 8888 SDValue SITargetLowering::getCanonicalConstantFP( 8889 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 8890 // Flush denormals to 0 if not enabled. 8891 if (C.isDenormal() && !denormalsEnabledForType(VT)) 8892 return DAG.getConstantFP(0.0, SL, VT); 8893 8894 if (C.isNaN()) { 8895 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 8896 if (C.isSignaling()) { 8897 // Quiet a signaling NaN. 8898 // FIXME: Is this supposed to preserve payload bits? 8899 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8900 } 8901 8902 // Make sure it is the canonical NaN bitpattern. 8903 // 8904 // TODO: Can we use -1 as the canonical NaN value since it's an inline 8905 // immediate? 8906 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 8907 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8908 } 8909 8910 // Already canonical. 8911 return DAG.getConstantFP(C, SL, VT); 8912 } 8913 8914 static bool vectorEltWillFoldAway(SDValue Op) { 8915 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 8916 } 8917 8918 SDValue SITargetLowering::performFCanonicalizeCombine( 8919 SDNode *N, 8920 DAGCombinerInfo &DCI) const { 8921 SelectionDAG &DAG = DCI.DAG; 8922 SDValue N0 = N->getOperand(0); 8923 EVT VT = N->getValueType(0); 8924 8925 // fcanonicalize undef -> qnan 8926 if (N0.isUndef()) { 8927 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 8928 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 8929 } 8930 8931 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 8932 EVT VT = N->getValueType(0); 8933 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 8934 } 8935 8936 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 8937 // (fcanonicalize k) 8938 // 8939 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 8940 8941 // TODO: This could be better with wider vectors that will be split to v2f16, 8942 // and to consider uses since there aren't that many packed operations. 8943 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 8944 isTypeLegal(MVT::v2f16)) { 8945 SDLoc SL(N); 8946 SDValue NewElts[2]; 8947 SDValue Lo = N0.getOperand(0); 8948 SDValue Hi = N0.getOperand(1); 8949 EVT EltVT = Lo.getValueType(); 8950 8951 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 8952 for (unsigned I = 0; I != 2; ++I) { 8953 SDValue Op = N0.getOperand(I); 8954 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8955 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 8956 CFP->getValueAPF()); 8957 } else if (Op.isUndef()) { 8958 // Handled below based on what the other operand is. 8959 NewElts[I] = Op; 8960 } else { 8961 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 8962 } 8963 } 8964 8965 // If one half is undef, and one is constant, perfer a splat vector rather 8966 // than the normal qNaN. If it's a register, prefer 0.0 since that's 8967 // cheaper to use and may be free with a packed operation. 8968 if (NewElts[0].isUndef()) { 8969 if (isa<ConstantFPSDNode>(NewElts[1])) 8970 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 8971 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 8972 } 8973 8974 if (NewElts[1].isUndef()) { 8975 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 8976 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 8977 } 8978 8979 return DAG.getBuildVector(VT, SL, NewElts); 8980 } 8981 } 8982 8983 unsigned SrcOpc = N0.getOpcode(); 8984 8985 // If it's free to do so, push canonicalizes further up the source, which may 8986 // find a canonical source. 8987 // 8988 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 8989 // sNaNs. 8990 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 8991 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 8992 if (CRHS && N0.hasOneUse()) { 8993 SDLoc SL(N); 8994 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 8995 N0.getOperand(0)); 8996 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 8997 DCI.AddToWorklist(Canon0.getNode()); 8998 8999 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9000 } 9001 } 9002 9003 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9004 } 9005 9006 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9007 switch (Opc) { 9008 case ISD::FMAXNUM: 9009 case ISD::FMAXNUM_IEEE: 9010 return AMDGPUISD::FMAX3; 9011 case ISD::SMAX: 9012 return AMDGPUISD::SMAX3; 9013 case ISD::UMAX: 9014 return AMDGPUISD::UMAX3; 9015 case ISD::FMINNUM: 9016 case ISD::FMINNUM_IEEE: 9017 return AMDGPUISD::FMIN3; 9018 case ISD::SMIN: 9019 return AMDGPUISD::SMIN3; 9020 case ISD::UMIN: 9021 return AMDGPUISD::UMIN3; 9022 default: 9023 llvm_unreachable("Not a min/max opcode"); 9024 } 9025 } 9026 9027 SDValue SITargetLowering::performIntMed3ImmCombine( 9028 SelectionDAG &DAG, const SDLoc &SL, 9029 SDValue Op0, SDValue Op1, bool Signed) const { 9030 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9031 if (!K1) 9032 return SDValue(); 9033 9034 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9035 if (!K0) 9036 return SDValue(); 9037 9038 if (Signed) { 9039 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9040 return SDValue(); 9041 } else { 9042 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9043 return SDValue(); 9044 } 9045 9046 EVT VT = K0->getValueType(0); 9047 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9048 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9049 return DAG.getNode(Med3Opc, SL, VT, 9050 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9051 } 9052 9053 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9054 MVT NVT = MVT::i32; 9055 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9056 9057 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9058 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9059 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9060 9061 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9062 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9063 } 9064 9065 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9066 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9067 return C; 9068 9069 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9070 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9071 return C; 9072 } 9073 9074 return nullptr; 9075 } 9076 9077 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9078 const SDLoc &SL, 9079 SDValue Op0, 9080 SDValue Op1) const { 9081 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9082 if (!K1) 9083 return SDValue(); 9084 9085 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9086 if (!K0) 9087 return SDValue(); 9088 9089 // Ordered >= (although NaN inputs should have folded away by now). 9090 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 9091 if (Cmp == APFloat::cmpGreaterThan) 9092 return SDValue(); 9093 9094 const MachineFunction &MF = DAG.getMachineFunction(); 9095 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9096 9097 // TODO: Check IEEE bit enabled? 9098 EVT VT = Op0.getValueType(); 9099 if (Info->getMode().DX10Clamp) { 9100 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9101 // hardware fmed3 behavior converting to a min. 9102 // FIXME: Should this be allowing -0.0? 9103 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9104 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9105 } 9106 9107 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9108 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9109 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9110 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9111 // then give the other result, which is different from med3 with a NaN 9112 // input. 9113 SDValue Var = Op0.getOperand(0); 9114 if (!DAG.isKnownNeverSNaN(Var)) 9115 return SDValue(); 9116 9117 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9118 9119 if ((!K0->hasOneUse() || 9120 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9121 (!K1->hasOneUse() || 9122 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9123 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9124 Var, SDValue(K0, 0), SDValue(K1, 0)); 9125 } 9126 } 9127 9128 return SDValue(); 9129 } 9130 9131 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9132 DAGCombinerInfo &DCI) const { 9133 SelectionDAG &DAG = DCI.DAG; 9134 9135 EVT VT = N->getValueType(0); 9136 unsigned Opc = N->getOpcode(); 9137 SDValue Op0 = N->getOperand(0); 9138 SDValue Op1 = N->getOperand(1); 9139 9140 // Only do this if the inner op has one use since this will just increases 9141 // register pressure for no benefit. 9142 9143 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9144 !VT.isVector() && 9145 (VT == MVT::i32 || VT == MVT::f32 || 9146 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9147 // max(max(a, b), c) -> max3(a, b, c) 9148 // min(min(a, b), c) -> min3(a, b, c) 9149 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9150 SDLoc DL(N); 9151 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9152 DL, 9153 N->getValueType(0), 9154 Op0.getOperand(0), 9155 Op0.getOperand(1), 9156 Op1); 9157 } 9158 9159 // Try commuted. 9160 // max(a, max(b, c)) -> max3(a, b, c) 9161 // min(a, min(b, c)) -> min3(a, b, c) 9162 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9163 SDLoc DL(N); 9164 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9165 DL, 9166 N->getValueType(0), 9167 Op0, 9168 Op1.getOperand(0), 9169 Op1.getOperand(1)); 9170 } 9171 } 9172 9173 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9174 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9175 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9176 return Med3; 9177 } 9178 9179 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9180 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9181 return Med3; 9182 } 9183 9184 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9185 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9186 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9187 (Opc == AMDGPUISD::FMIN_LEGACY && 9188 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9189 (VT == MVT::f32 || VT == MVT::f64 || 9190 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9191 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9192 Op0.hasOneUse()) { 9193 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9194 return Res; 9195 } 9196 9197 return SDValue(); 9198 } 9199 9200 static bool isClampZeroToOne(SDValue A, SDValue B) { 9201 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9202 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9203 // FIXME: Should this be allowing -0.0? 9204 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9205 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9206 } 9207 } 9208 9209 return false; 9210 } 9211 9212 // FIXME: Should only worry about snans for version with chain. 9213 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9214 DAGCombinerInfo &DCI) const { 9215 EVT VT = N->getValueType(0); 9216 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9217 // NaNs. With a NaN input, the order of the operands may change the result. 9218 9219 SelectionDAG &DAG = DCI.DAG; 9220 SDLoc SL(N); 9221 9222 SDValue Src0 = N->getOperand(0); 9223 SDValue Src1 = N->getOperand(1); 9224 SDValue Src2 = N->getOperand(2); 9225 9226 if (isClampZeroToOne(Src0, Src1)) { 9227 // const_a, const_b, x -> clamp is safe in all cases including signaling 9228 // nans. 9229 // FIXME: Should this be allowing -0.0? 9230 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9231 } 9232 9233 const MachineFunction &MF = DAG.getMachineFunction(); 9234 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9235 9236 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9237 // handling no dx10-clamp? 9238 if (Info->getMode().DX10Clamp) { 9239 // If NaNs is clamped to 0, we are free to reorder the inputs. 9240 9241 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9242 std::swap(Src0, Src1); 9243 9244 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9245 std::swap(Src1, Src2); 9246 9247 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9248 std::swap(Src0, Src1); 9249 9250 if (isClampZeroToOne(Src1, Src2)) 9251 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9252 } 9253 9254 return SDValue(); 9255 } 9256 9257 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9258 DAGCombinerInfo &DCI) const { 9259 SDValue Src0 = N->getOperand(0); 9260 SDValue Src1 = N->getOperand(1); 9261 if (Src0.isUndef() && Src1.isUndef()) 9262 return DCI.DAG.getUNDEF(N->getValueType(0)); 9263 return SDValue(); 9264 } 9265 9266 SDValue SITargetLowering::performExtractVectorEltCombine( 9267 SDNode *N, DAGCombinerInfo &DCI) const { 9268 SDValue Vec = N->getOperand(0); 9269 SelectionDAG &DAG = DCI.DAG; 9270 9271 EVT VecVT = Vec.getValueType(); 9272 EVT EltVT = VecVT.getVectorElementType(); 9273 9274 if ((Vec.getOpcode() == ISD::FNEG || 9275 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9276 SDLoc SL(N); 9277 EVT EltVT = N->getValueType(0); 9278 SDValue Idx = N->getOperand(1); 9279 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9280 Vec.getOperand(0), Idx); 9281 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9282 } 9283 9284 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9285 // => 9286 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9287 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9288 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9289 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9290 SDLoc SL(N); 9291 EVT EltVT = N->getValueType(0); 9292 SDValue Idx = N->getOperand(1); 9293 unsigned Opc = Vec.getOpcode(); 9294 9295 switch(Opc) { 9296 default: 9297 break; 9298 // TODO: Support other binary operations. 9299 case ISD::FADD: 9300 case ISD::FSUB: 9301 case ISD::FMUL: 9302 case ISD::ADD: 9303 case ISD::UMIN: 9304 case ISD::UMAX: 9305 case ISD::SMIN: 9306 case ISD::SMAX: 9307 case ISD::FMAXNUM: 9308 case ISD::FMINNUM: 9309 case ISD::FMAXNUM_IEEE: 9310 case ISD::FMINNUM_IEEE: { 9311 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9312 Vec.getOperand(0), Idx); 9313 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9314 Vec.getOperand(1), Idx); 9315 9316 DCI.AddToWorklist(Elt0.getNode()); 9317 DCI.AddToWorklist(Elt1.getNode()); 9318 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9319 } 9320 } 9321 } 9322 9323 unsigned VecSize = VecVT.getSizeInBits(); 9324 unsigned EltSize = EltVT.getSizeInBits(); 9325 9326 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9327 // This elminates non-constant index and subsequent movrel or scratch access. 9328 // Sub-dword vectors of size 2 dword or less have better implementation. 9329 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9330 // instructions. 9331 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) && 9332 !isa<ConstantSDNode>(N->getOperand(1))) { 9333 SDLoc SL(N); 9334 SDValue Idx = N->getOperand(1); 9335 EVT IdxVT = Idx.getValueType(); 9336 SDValue V; 9337 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9338 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9339 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9340 if (I == 0) 9341 V = Elt; 9342 else 9343 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9344 } 9345 return V; 9346 } 9347 9348 if (!DCI.isBeforeLegalize()) 9349 return SDValue(); 9350 9351 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9352 // elements. This exposes more load reduction opportunities by replacing 9353 // multiple small extract_vector_elements with a single 32-bit extract. 9354 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9355 if (isa<MemSDNode>(Vec) && 9356 EltSize <= 16 && 9357 EltVT.isByteSized() && 9358 VecSize > 32 && 9359 VecSize % 32 == 0 && 9360 Idx) { 9361 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9362 9363 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9364 unsigned EltIdx = BitIndex / 32; 9365 unsigned LeftoverBitIdx = BitIndex % 32; 9366 SDLoc SL(N); 9367 9368 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9369 DCI.AddToWorklist(Cast.getNode()); 9370 9371 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9372 DAG.getConstant(EltIdx, SL, MVT::i32)); 9373 DCI.AddToWorklist(Elt.getNode()); 9374 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9375 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9376 DCI.AddToWorklist(Srl.getNode()); 9377 9378 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9379 DCI.AddToWorklist(Trunc.getNode()); 9380 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9381 } 9382 9383 return SDValue(); 9384 } 9385 9386 SDValue 9387 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9388 DAGCombinerInfo &DCI) const { 9389 SDValue Vec = N->getOperand(0); 9390 SDValue Idx = N->getOperand(2); 9391 EVT VecVT = Vec.getValueType(); 9392 EVT EltVT = VecVT.getVectorElementType(); 9393 unsigned VecSize = VecVT.getSizeInBits(); 9394 unsigned EltSize = EltVT.getSizeInBits(); 9395 9396 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9397 // => BUILD_VECTOR n x select (e, const-idx) 9398 // This elminates non-constant index and subsequent movrel or scratch access. 9399 // Sub-dword vectors of size 2 dword or less have better implementation. 9400 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9401 // instructions. 9402 if (isa<ConstantSDNode>(Idx) || 9403 VecSize > 256 || (VecSize <= 64 && EltSize < 32)) 9404 return SDValue(); 9405 9406 SelectionDAG &DAG = DCI.DAG; 9407 SDLoc SL(N); 9408 SDValue Ins = N->getOperand(1); 9409 EVT IdxVT = Idx.getValueType(); 9410 9411 SmallVector<SDValue, 16> Ops; 9412 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9413 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9414 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9415 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9416 Ops.push_back(V); 9417 } 9418 9419 return DAG.getBuildVector(VecVT, SL, Ops); 9420 } 9421 9422 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9423 const SDNode *N0, 9424 const SDNode *N1) const { 9425 EVT VT = N0->getValueType(0); 9426 9427 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9428 // support denormals ever. 9429 if (((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) || 9430 (VT == MVT::f16 && !Subtarget->hasFP16Denormals() && 9431 getSubtarget()->hasMadF16())) && 9432 isOperationLegal(ISD::FMAD, VT)) 9433 return ISD::FMAD; 9434 9435 const TargetOptions &Options = DAG.getTarget().Options; 9436 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9437 (N0->getFlags().hasAllowContract() && 9438 N1->getFlags().hasAllowContract())) && 9439 isFMAFasterThanFMulAndFAdd(VT)) { 9440 return ISD::FMA; 9441 } 9442 9443 return 0; 9444 } 9445 9446 // For a reassociatable opcode perform: 9447 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9448 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9449 SelectionDAG &DAG) const { 9450 EVT VT = N->getValueType(0); 9451 if (VT != MVT::i32 && VT != MVT::i64) 9452 return SDValue(); 9453 9454 unsigned Opc = N->getOpcode(); 9455 SDValue Op0 = N->getOperand(0); 9456 SDValue Op1 = N->getOperand(1); 9457 9458 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9459 return SDValue(); 9460 9461 if (Op0->isDivergent()) 9462 std::swap(Op0, Op1); 9463 9464 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9465 return SDValue(); 9466 9467 SDValue Op2 = Op1.getOperand(1); 9468 Op1 = Op1.getOperand(0); 9469 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9470 return SDValue(); 9471 9472 if (Op1->isDivergent()) 9473 std::swap(Op1, Op2); 9474 9475 // If either operand is constant this will conflict with 9476 // DAGCombiner::ReassociateOps(). 9477 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9478 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9479 return SDValue(); 9480 9481 SDLoc SL(N); 9482 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9483 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9484 } 9485 9486 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9487 EVT VT, 9488 SDValue N0, SDValue N1, SDValue N2, 9489 bool Signed) { 9490 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9491 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9492 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 9493 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 9494 } 9495 9496 SDValue SITargetLowering::performAddCombine(SDNode *N, 9497 DAGCombinerInfo &DCI) const { 9498 SelectionDAG &DAG = DCI.DAG; 9499 EVT VT = N->getValueType(0); 9500 SDLoc SL(N); 9501 SDValue LHS = N->getOperand(0); 9502 SDValue RHS = N->getOperand(1); 9503 9504 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 9505 && Subtarget->hasMad64_32() && 9506 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 9507 VT.getScalarSizeInBits() <= 64) { 9508 if (LHS.getOpcode() != ISD::MUL) 9509 std::swap(LHS, RHS); 9510 9511 SDValue MulLHS = LHS.getOperand(0); 9512 SDValue MulRHS = LHS.getOperand(1); 9513 SDValue AddRHS = RHS; 9514 9515 // TODO: Maybe restrict if SGPR inputs. 9516 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 9517 numBitsUnsigned(MulRHS, DAG) <= 32) { 9518 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 9519 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 9520 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 9521 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 9522 } 9523 9524 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 9525 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 9526 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 9527 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 9528 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 9529 } 9530 9531 return SDValue(); 9532 } 9533 9534 if (SDValue V = reassociateScalarOps(N, DAG)) { 9535 return V; 9536 } 9537 9538 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 9539 return SDValue(); 9540 9541 // add x, zext (setcc) => addcarry x, 0, setcc 9542 // add x, sext (setcc) => subcarry x, 0, setcc 9543 unsigned Opc = LHS.getOpcode(); 9544 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9545 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 9546 std::swap(RHS, LHS); 9547 9548 Opc = RHS.getOpcode(); 9549 switch (Opc) { 9550 default: break; 9551 case ISD::ZERO_EXTEND: 9552 case ISD::SIGN_EXTEND: 9553 case ISD::ANY_EXTEND: { 9554 auto Cond = RHS.getOperand(0); 9555 if (!isBoolSGPR(Cond)) 9556 break; 9557 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9558 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9559 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9560 return DAG.getNode(Opc, SL, VTList, Args); 9561 } 9562 case ISD::ADDCARRY: { 9563 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 9564 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9565 if (!C || C->getZExtValue() != 0) break; 9566 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 9567 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 9568 } 9569 } 9570 return SDValue(); 9571 } 9572 9573 SDValue SITargetLowering::performSubCombine(SDNode *N, 9574 DAGCombinerInfo &DCI) const { 9575 SelectionDAG &DAG = DCI.DAG; 9576 EVT VT = N->getValueType(0); 9577 9578 if (VT != MVT::i32) 9579 return SDValue(); 9580 9581 SDLoc SL(N); 9582 SDValue LHS = N->getOperand(0); 9583 SDValue RHS = N->getOperand(1); 9584 9585 if (LHS.getOpcode() == ISD::SUBCARRY) { 9586 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 9587 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9588 if (!C || !C->isNullValue()) 9589 return SDValue(); 9590 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 9591 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 9592 } 9593 return SDValue(); 9594 } 9595 9596 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 9597 DAGCombinerInfo &DCI) const { 9598 9599 if (N->getValueType(0) != MVT::i32) 9600 return SDValue(); 9601 9602 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9603 if (!C || C->getZExtValue() != 0) 9604 return SDValue(); 9605 9606 SelectionDAG &DAG = DCI.DAG; 9607 SDValue LHS = N->getOperand(0); 9608 9609 // addcarry (add x, y), 0, cc => addcarry x, y, cc 9610 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 9611 unsigned LHSOpc = LHS.getOpcode(); 9612 unsigned Opc = N->getOpcode(); 9613 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 9614 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 9615 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 9616 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 9617 } 9618 return SDValue(); 9619 } 9620 9621 SDValue SITargetLowering::performFAddCombine(SDNode *N, 9622 DAGCombinerInfo &DCI) const { 9623 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9624 return SDValue(); 9625 9626 SelectionDAG &DAG = DCI.DAG; 9627 EVT VT = N->getValueType(0); 9628 9629 SDLoc SL(N); 9630 SDValue LHS = N->getOperand(0); 9631 SDValue RHS = N->getOperand(1); 9632 9633 // These should really be instruction patterns, but writing patterns with 9634 // source modiifiers is a pain. 9635 9636 // fadd (fadd (a, a), b) -> mad 2.0, a, b 9637 if (LHS.getOpcode() == ISD::FADD) { 9638 SDValue A = LHS.getOperand(0); 9639 if (A == LHS.getOperand(1)) { 9640 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9641 if (FusedOp != 0) { 9642 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9643 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 9644 } 9645 } 9646 } 9647 9648 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 9649 if (RHS.getOpcode() == ISD::FADD) { 9650 SDValue A = RHS.getOperand(0); 9651 if (A == RHS.getOperand(1)) { 9652 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9653 if (FusedOp != 0) { 9654 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9655 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 9656 } 9657 } 9658 } 9659 9660 return SDValue(); 9661 } 9662 9663 SDValue SITargetLowering::performFSubCombine(SDNode *N, 9664 DAGCombinerInfo &DCI) const { 9665 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9666 return SDValue(); 9667 9668 SelectionDAG &DAG = DCI.DAG; 9669 SDLoc SL(N); 9670 EVT VT = N->getValueType(0); 9671 assert(!VT.isVector()); 9672 9673 // Try to get the fneg to fold into the source modifier. This undoes generic 9674 // DAG combines and folds them into the mad. 9675 // 9676 // Only do this if we are not trying to support denormals. v_mad_f32 does 9677 // not support denormals ever. 9678 SDValue LHS = N->getOperand(0); 9679 SDValue RHS = N->getOperand(1); 9680 if (LHS.getOpcode() == ISD::FADD) { 9681 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 9682 SDValue A = LHS.getOperand(0); 9683 if (A == LHS.getOperand(1)) { 9684 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9685 if (FusedOp != 0){ 9686 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9687 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 9688 9689 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 9690 } 9691 } 9692 } 9693 9694 if (RHS.getOpcode() == ISD::FADD) { 9695 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 9696 9697 SDValue A = RHS.getOperand(0); 9698 if (A == RHS.getOperand(1)) { 9699 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9700 if (FusedOp != 0){ 9701 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 9702 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 9703 } 9704 } 9705 } 9706 9707 return SDValue(); 9708 } 9709 9710 SDValue SITargetLowering::performFMACombine(SDNode *N, 9711 DAGCombinerInfo &DCI) const { 9712 SelectionDAG &DAG = DCI.DAG; 9713 EVT VT = N->getValueType(0); 9714 SDLoc SL(N); 9715 9716 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 9717 return SDValue(); 9718 9719 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 9720 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 9721 SDValue Op1 = N->getOperand(0); 9722 SDValue Op2 = N->getOperand(1); 9723 SDValue FMA = N->getOperand(2); 9724 9725 if (FMA.getOpcode() != ISD::FMA || 9726 Op1.getOpcode() != ISD::FP_EXTEND || 9727 Op2.getOpcode() != ISD::FP_EXTEND) 9728 return SDValue(); 9729 9730 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 9731 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 9732 // is sufficient to allow generaing fdot2. 9733 const TargetOptions &Options = DAG.getTarget().Options; 9734 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9735 (N->getFlags().hasAllowContract() && 9736 FMA->getFlags().hasAllowContract())) { 9737 Op1 = Op1.getOperand(0); 9738 Op2 = Op2.getOperand(0); 9739 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9740 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9741 return SDValue(); 9742 9743 SDValue Vec1 = Op1.getOperand(0); 9744 SDValue Idx1 = Op1.getOperand(1); 9745 SDValue Vec2 = Op2.getOperand(0); 9746 9747 SDValue FMAOp1 = FMA.getOperand(0); 9748 SDValue FMAOp2 = FMA.getOperand(1); 9749 SDValue FMAAcc = FMA.getOperand(2); 9750 9751 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 9752 FMAOp2.getOpcode() != ISD::FP_EXTEND) 9753 return SDValue(); 9754 9755 FMAOp1 = FMAOp1.getOperand(0); 9756 FMAOp2 = FMAOp2.getOperand(0); 9757 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9758 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9759 return SDValue(); 9760 9761 SDValue Vec3 = FMAOp1.getOperand(0); 9762 SDValue Vec4 = FMAOp2.getOperand(0); 9763 SDValue Idx2 = FMAOp1.getOperand(1); 9764 9765 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 9766 // Idx1 and Idx2 cannot be the same. 9767 Idx1 == Idx2) 9768 return SDValue(); 9769 9770 if (Vec1 == Vec2 || Vec3 == Vec4) 9771 return SDValue(); 9772 9773 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 9774 return SDValue(); 9775 9776 if ((Vec1 == Vec3 && Vec2 == Vec4) || 9777 (Vec1 == Vec4 && Vec2 == Vec3)) { 9778 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 9779 DAG.getTargetConstant(0, SL, MVT::i1)); 9780 } 9781 } 9782 return SDValue(); 9783 } 9784 9785 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 9786 DAGCombinerInfo &DCI) const { 9787 SelectionDAG &DAG = DCI.DAG; 9788 SDLoc SL(N); 9789 9790 SDValue LHS = N->getOperand(0); 9791 SDValue RHS = N->getOperand(1); 9792 EVT VT = LHS.getValueType(); 9793 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 9794 9795 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 9796 if (!CRHS) { 9797 CRHS = dyn_cast<ConstantSDNode>(LHS); 9798 if (CRHS) { 9799 std::swap(LHS, RHS); 9800 CC = getSetCCSwappedOperands(CC); 9801 } 9802 } 9803 9804 if (CRHS) { 9805 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 9806 isBoolSGPR(LHS.getOperand(0))) { 9807 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 9808 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 9809 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 9810 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 9811 if ((CRHS->isAllOnesValue() && 9812 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 9813 (CRHS->isNullValue() && 9814 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 9815 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9816 DAG.getConstant(-1, SL, MVT::i1)); 9817 if ((CRHS->isAllOnesValue() && 9818 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 9819 (CRHS->isNullValue() && 9820 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 9821 return LHS.getOperand(0); 9822 } 9823 9824 uint64_t CRHSVal = CRHS->getZExtValue(); 9825 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 9826 LHS.getOpcode() == ISD::SELECT && 9827 isa<ConstantSDNode>(LHS.getOperand(1)) && 9828 isa<ConstantSDNode>(LHS.getOperand(2)) && 9829 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 9830 isBoolSGPR(LHS.getOperand(0))) { 9831 // Given CT != FT: 9832 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 9833 // setcc (select cc, CT, CF), CF, ne => cc 9834 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 9835 // setcc (select cc, CT, CF), CT, eq => cc 9836 uint64_t CT = LHS.getConstantOperandVal(1); 9837 uint64_t CF = LHS.getConstantOperandVal(2); 9838 9839 if ((CF == CRHSVal && CC == ISD::SETEQ) || 9840 (CT == CRHSVal && CC == ISD::SETNE)) 9841 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9842 DAG.getConstant(-1, SL, MVT::i1)); 9843 if ((CF == CRHSVal && CC == ISD::SETNE) || 9844 (CT == CRHSVal && CC == ISD::SETEQ)) 9845 return LHS.getOperand(0); 9846 } 9847 } 9848 9849 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 9850 VT != MVT::f16)) 9851 return SDValue(); 9852 9853 // Match isinf/isfinite pattern 9854 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 9855 // (fcmp one (fabs x), inf) -> (fp_class x, 9856 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 9857 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 9858 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 9859 if (!CRHS) 9860 return SDValue(); 9861 9862 const APFloat &APF = CRHS->getValueAPF(); 9863 if (APF.isInfinity() && !APF.isNegative()) { 9864 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 9865 SIInstrFlags::N_INFINITY; 9866 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 9867 SIInstrFlags::P_ZERO | 9868 SIInstrFlags::N_NORMAL | 9869 SIInstrFlags::P_NORMAL | 9870 SIInstrFlags::N_SUBNORMAL | 9871 SIInstrFlags::P_SUBNORMAL; 9872 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 9873 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 9874 DAG.getConstant(Mask, SL, MVT::i32)); 9875 } 9876 } 9877 9878 return SDValue(); 9879 } 9880 9881 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 9882 DAGCombinerInfo &DCI) const { 9883 SelectionDAG &DAG = DCI.DAG; 9884 SDLoc SL(N); 9885 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 9886 9887 SDValue Src = N->getOperand(0); 9888 SDValue Srl = N->getOperand(0); 9889 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 9890 Srl = Srl.getOperand(0); 9891 9892 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 9893 if (Srl.getOpcode() == ISD::SRL) { 9894 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 9895 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 9896 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 9897 9898 if (const ConstantSDNode *C = 9899 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 9900 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 9901 EVT(MVT::i32)); 9902 9903 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 9904 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 9905 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 9906 MVT::f32, Srl); 9907 } 9908 } 9909 } 9910 9911 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 9912 9913 KnownBits Known; 9914 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 9915 !DCI.isBeforeLegalizeOps()); 9916 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9917 if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) { 9918 DCI.CommitTargetLoweringOpt(TLO); 9919 } 9920 9921 return SDValue(); 9922 } 9923 9924 SDValue SITargetLowering::performClampCombine(SDNode *N, 9925 DAGCombinerInfo &DCI) const { 9926 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 9927 if (!CSrc) 9928 return SDValue(); 9929 9930 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 9931 const APFloat &F = CSrc->getValueAPF(); 9932 APFloat Zero = APFloat::getZero(F.getSemantics()); 9933 APFloat::cmpResult Cmp0 = F.compare(Zero); 9934 if (Cmp0 == APFloat::cmpLessThan || 9935 (Cmp0 == APFloat::cmpUnordered && 9936 MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 9937 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 9938 } 9939 9940 APFloat One(F.getSemantics(), "1.0"); 9941 APFloat::cmpResult Cmp1 = F.compare(One); 9942 if (Cmp1 == APFloat::cmpGreaterThan) 9943 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 9944 9945 return SDValue(CSrc, 0); 9946 } 9947 9948 9949 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 9950 DAGCombinerInfo &DCI) const { 9951 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 9952 return SDValue(); 9953 switch (N->getOpcode()) { 9954 default: 9955 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9956 case ISD::ADD: 9957 return performAddCombine(N, DCI); 9958 case ISD::SUB: 9959 return performSubCombine(N, DCI); 9960 case ISD::ADDCARRY: 9961 case ISD::SUBCARRY: 9962 return performAddCarrySubCarryCombine(N, DCI); 9963 case ISD::FADD: 9964 return performFAddCombine(N, DCI); 9965 case ISD::FSUB: 9966 return performFSubCombine(N, DCI); 9967 case ISD::SETCC: 9968 return performSetCCCombine(N, DCI); 9969 case ISD::FMAXNUM: 9970 case ISD::FMINNUM: 9971 case ISD::FMAXNUM_IEEE: 9972 case ISD::FMINNUM_IEEE: 9973 case ISD::SMAX: 9974 case ISD::SMIN: 9975 case ISD::UMAX: 9976 case ISD::UMIN: 9977 case AMDGPUISD::FMIN_LEGACY: 9978 case AMDGPUISD::FMAX_LEGACY: 9979 return performMinMaxCombine(N, DCI); 9980 case ISD::FMA: 9981 return performFMACombine(N, DCI); 9982 case ISD::LOAD: { 9983 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 9984 return Widended; 9985 LLVM_FALLTHROUGH; 9986 } 9987 case ISD::STORE: 9988 case ISD::ATOMIC_LOAD: 9989 case ISD::ATOMIC_STORE: 9990 case ISD::ATOMIC_CMP_SWAP: 9991 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 9992 case ISD::ATOMIC_SWAP: 9993 case ISD::ATOMIC_LOAD_ADD: 9994 case ISD::ATOMIC_LOAD_SUB: 9995 case ISD::ATOMIC_LOAD_AND: 9996 case ISD::ATOMIC_LOAD_OR: 9997 case ISD::ATOMIC_LOAD_XOR: 9998 case ISD::ATOMIC_LOAD_NAND: 9999 case ISD::ATOMIC_LOAD_MIN: 10000 case ISD::ATOMIC_LOAD_MAX: 10001 case ISD::ATOMIC_LOAD_UMIN: 10002 case ISD::ATOMIC_LOAD_UMAX: 10003 case ISD::ATOMIC_LOAD_FADD: 10004 case AMDGPUISD::ATOMIC_INC: 10005 case AMDGPUISD::ATOMIC_DEC: 10006 case AMDGPUISD::ATOMIC_LOAD_FMIN: 10007 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 10008 if (DCI.isBeforeLegalize()) 10009 break; 10010 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 10011 case ISD::AND: 10012 return performAndCombine(N, DCI); 10013 case ISD::OR: 10014 return performOrCombine(N, DCI); 10015 case ISD::XOR: 10016 return performXorCombine(N, DCI); 10017 case ISD::ZERO_EXTEND: 10018 return performZeroExtendCombine(N, DCI); 10019 case ISD::SIGN_EXTEND_INREG: 10020 return performSignExtendInRegCombine(N , DCI); 10021 case AMDGPUISD::FP_CLASS: 10022 return performClassCombine(N, DCI); 10023 case ISD::FCANONICALIZE: 10024 return performFCanonicalizeCombine(N, DCI); 10025 case AMDGPUISD::RCP: 10026 return performRcpCombine(N, DCI); 10027 case AMDGPUISD::FRACT: 10028 case AMDGPUISD::RSQ: 10029 case AMDGPUISD::RCP_LEGACY: 10030 case AMDGPUISD::RSQ_LEGACY: 10031 case AMDGPUISD::RCP_IFLAG: 10032 case AMDGPUISD::RSQ_CLAMP: 10033 case AMDGPUISD::LDEXP: { 10034 SDValue Src = N->getOperand(0); 10035 if (Src.isUndef()) 10036 return Src; 10037 break; 10038 } 10039 case ISD::SINT_TO_FP: 10040 case ISD::UINT_TO_FP: 10041 return performUCharToFloatCombine(N, DCI); 10042 case AMDGPUISD::CVT_F32_UBYTE0: 10043 case AMDGPUISD::CVT_F32_UBYTE1: 10044 case AMDGPUISD::CVT_F32_UBYTE2: 10045 case AMDGPUISD::CVT_F32_UBYTE3: 10046 return performCvtF32UByteNCombine(N, DCI); 10047 case AMDGPUISD::FMED3: 10048 return performFMed3Combine(N, DCI); 10049 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10050 return performCvtPkRTZCombine(N, DCI); 10051 case AMDGPUISD::CLAMP: 10052 return performClampCombine(N, DCI); 10053 case ISD::SCALAR_TO_VECTOR: { 10054 SelectionDAG &DAG = DCI.DAG; 10055 EVT VT = N->getValueType(0); 10056 10057 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10058 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10059 SDLoc SL(N); 10060 SDValue Src = N->getOperand(0); 10061 EVT EltVT = Src.getValueType(); 10062 if (EltVT == MVT::f16) 10063 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10064 10065 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10066 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10067 } 10068 10069 break; 10070 } 10071 case ISD::EXTRACT_VECTOR_ELT: 10072 return performExtractVectorEltCombine(N, DCI); 10073 case ISD::INSERT_VECTOR_ELT: 10074 return performInsertVectorEltCombine(N, DCI); 10075 } 10076 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10077 } 10078 10079 /// Helper function for adjustWritemask 10080 static unsigned SubIdx2Lane(unsigned Idx) { 10081 switch (Idx) { 10082 default: return 0; 10083 case AMDGPU::sub0: return 0; 10084 case AMDGPU::sub1: return 1; 10085 case AMDGPU::sub2: return 2; 10086 case AMDGPU::sub3: return 3; 10087 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10088 } 10089 } 10090 10091 /// Adjust the writemask of MIMG instructions 10092 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10093 SelectionDAG &DAG) const { 10094 unsigned Opcode = Node->getMachineOpcode(); 10095 10096 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10097 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10098 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10099 return Node; // not implemented for D16 10100 10101 SDNode *Users[5] = { nullptr }; 10102 unsigned Lane = 0; 10103 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10104 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10105 unsigned NewDmask = 0; 10106 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10107 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10108 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10109 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10110 unsigned TFCLane = 0; 10111 bool HasChain = Node->getNumValues() > 1; 10112 10113 if (OldDmask == 0) { 10114 // These are folded out, but on the chance it happens don't assert. 10115 return Node; 10116 } 10117 10118 unsigned OldBitsSet = countPopulation(OldDmask); 10119 // Work out which is the TFE/LWE lane if that is enabled. 10120 if (UsesTFC) { 10121 TFCLane = OldBitsSet; 10122 } 10123 10124 // Try to figure out the used register components 10125 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10126 I != E; ++I) { 10127 10128 // Don't look at users of the chain. 10129 if (I.getUse().getResNo() != 0) 10130 continue; 10131 10132 // Abort if we can't understand the usage 10133 if (!I->isMachineOpcode() || 10134 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10135 return Node; 10136 10137 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10138 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10139 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10140 // set, etc. 10141 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10142 10143 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10144 if (UsesTFC && Lane == TFCLane) { 10145 Users[Lane] = *I; 10146 } else { 10147 // Set which texture component corresponds to the lane. 10148 unsigned Comp; 10149 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10150 Comp = countTrailingZeros(Dmask); 10151 Dmask &= ~(1 << Comp); 10152 } 10153 10154 // Abort if we have more than one user per component. 10155 if (Users[Lane]) 10156 return Node; 10157 10158 Users[Lane] = *I; 10159 NewDmask |= 1 << Comp; 10160 } 10161 } 10162 10163 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10164 bool NoChannels = !NewDmask; 10165 if (NoChannels) { 10166 if (!UsesTFC) { 10167 // No uses of the result and not using TFC. Then do nothing. 10168 return Node; 10169 } 10170 // If the original dmask has one channel - then nothing to do 10171 if (OldBitsSet == 1) 10172 return Node; 10173 // Use an arbitrary dmask - required for the instruction to work 10174 NewDmask = 1; 10175 } 10176 // Abort if there's no change 10177 if (NewDmask == OldDmask) 10178 return Node; 10179 10180 unsigned BitsSet = countPopulation(NewDmask); 10181 10182 // Check for TFE or LWE - increase the number of channels by one to account 10183 // for the extra return value 10184 // This will need adjustment for D16 if this is also included in 10185 // adjustWriteMask (this function) but at present D16 are excluded. 10186 unsigned NewChannels = BitsSet + UsesTFC; 10187 10188 int NewOpcode = 10189 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10190 assert(NewOpcode != -1 && 10191 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10192 "failed to find equivalent MIMG op"); 10193 10194 // Adjust the writemask in the node 10195 SmallVector<SDValue, 12> Ops; 10196 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10197 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10198 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10199 10200 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10201 10202 MVT ResultVT = NewChannels == 1 ? 10203 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10204 NewChannels == 5 ? 8 : NewChannels); 10205 SDVTList NewVTList = HasChain ? 10206 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10207 10208 10209 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10210 NewVTList, Ops); 10211 10212 if (HasChain) { 10213 // Update chain. 10214 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10215 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10216 } 10217 10218 if (NewChannels == 1) { 10219 assert(Node->hasNUsesOfValue(1, 0)); 10220 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10221 SDLoc(Node), Users[Lane]->getValueType(0), 10222 SDValue(NewNode, 0)); 10223 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10224 return nullptr; 10225 } 10226 10227 // Update the users of the node with the new indices 10228 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10229 SDNode *User = Users[i]; 10230 if (!User) { 10231 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10232 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10233 if (i || !NoChannels) 10234 continue; 10235 } else { 10236 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10237 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10238 } 10239 10240 switch (Idx) { 10241 default: break; 10242 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10243 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10244 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10245 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10246 } 10247 } 10248 10249 DAG.RemoveDeadNode(Node); 10250 return nullptr; 10251 } 10252 10253 static bool isFrameIndexOp(SDValue Op) { 10254 if (Op.getOpcode() == ISD::AssertZext) 10255 Op = Op.getOperand(0); 10256 10257 return isa<FrameIndexSDNode>(Op); 10258 } 10259 10260 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10261 /// with frame index operands. 10262 /// LLVM assumes that inputs are to these instructions are registers. 10263 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10264 SelectionDAG &DAG) const { 10265 if (Node->getOpcode() == ISD::CopyToReg) { 10266 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10267 SDValue SrcVal = Node->getOperand(2); 10268 10269 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10270 // to try understanding copies to physical registers. 10271 if (SrcVal.getValueType() == MVT::i1 && 10272 Register::isPhysicalRegister(DestReg->getReg())) { 10273 SDLoc SL(Node); 10274 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10275 SDValue VReg = DAG.getRegister( 10276 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10277 10278 SDNode *Glued = Node->getGluedNode(); 10279 SDValue ToVReg 10280 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10281 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10282 SDValue ToResultReg 10283 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10284 VReg, ToVReg.getValue(1)); 10285 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10286 DAG.RemoveDeadNode(Node); 10287 return ToResultReg.getNode(); 10288 } 10289 } 10290 10291 SmallVector<SDValue, 8> Ops; 10292 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10293 if (!isFrameIndexOp(Node->getOperand(i))) { 10294 Ops.push_back(Node->getOperand(i)); 10295 continue; 10296 } 10297 10298 SDLoc DL(Node); 10299 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10300 Node->getOperand(i).getValueType(), 10301 Node->getOperand(i)), 0)); 10302 } 10303 10304 return DAG.UpdateNodeOperands(Node, Ops); 10305 } 10306 10307 /// Fold the instructions after selecting them. 10308 /// Returns null if users were already updated. 10309 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10310 SelectionDAG &DAG) const { 10311 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10312 unsigned Opcode = Node->getMachineOpcode(); 10313 10314 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10315 !TII->isGather4(Opcode)) { 10316 return adjustWritemask(Node, DAG); 10317 } 10318 10319 if (Opcode == AMDGPU::INSERT_SUBREG || 10320 Opcode == AMDGPU::REG_SEQUENCE) { 10321 legalizeTargetIndependentNode(Node, DAG); 10322 return Node; 10323 } 10324 10325 switch (Opcode) { 10326 case AMDGPU::V_DIV_SCALE_F32: 10327 case AMDGPU::V_DIV_SCALE_F64: { 10328 // Satisfy the operand register constraint when one of the inputs is 10329 // undefined. Ordinarily each undef value will have its own implicit_def of 10330 // a vreg, so force these to use a single register. 10331 SDValue Src0 = Node->getOperand(0); 10332 SDValue Src1 = Node->getOperand(1); 10333 SDValue Src2 = Node->getOperand(2); 10334 10335 if ((Src0.isMachineOpcode() && 10336 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10337 (Src0 == Src1 || Src0 == Src2)) 10338 break; 10339 10340 MVT VT = Src0.getValueType().getSimpleVT(); 10341 const TargetRegisterClass *RC = 10342 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10343 10344 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10345 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10346 10347 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10348 UndefReg, Src0, SDValue()); 10349 10350 // src0 must be the same register as src1 or src2, even if the value is 10351 // undefined, so make sure we don't violate this constraint. 10352 if (Src0.isMachineOpcode() && 10353 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10354 if (Src1.isMachineOpcode() && 10355 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10356 Src0 = Src1; 10357 else if (Src2.isMachineOpcode() && 10358 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10359 Src0 = Src2; 10360 else { 10361 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10362 Src0 = UndefReg; 10363 Src1 = UndefReg; 10364 } 10365 } else 10366 break; 10367 10368 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10369 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10370 Ops.push_back(Node->getOperand(I)); 10371 10372 Ops.push_back(ImpDef.getValue(1)); 10373 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10374 } 10375 case AMDGPU::V_PERMLANE16_B32: 10376 case AMDGPU::V_PERMLANEX16_B32: { 10377 ConstantSDNode *FI = cast<ConstantSDNode>(Node->getOperand(0)); 10378 ConstantSDNode *BC = cast<ConstantSDNode>(Node->getOperand(2)); 10379 if (!FI->getZExtValue() && !BC->getZExtValue()) 10380 break; 10381 SDValue VDstIn = Node->getOperand(6); 10382 if (VDstIn.isMachineOpcode() 10383 && VDstIn.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) 10384 break; 10385 MachineSDNode *ImpDef = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, 10386 SDLoc(Node), MVT::i32); 10387 SmallVector<SDValue, 8> Ops = { SDValue(FI, 0), Node->getOperand(1), 10388 SDValue(BC, 0), Node->getOperand(3), 10389 Node->getOperand(4), Node->getOperand(5), 10390 SDValue(ImpDef, 0), Node->getOperand(7) }; 10391 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10392 } 10393 default: 10394 break; 10395 } 10396 10397 return Node; 10398 } 10399 10400 /// Assign the register class depending on the number of 10401 /// bits set in the writemask 10402 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10403 SDNode *Node) const { 10404 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10405 10406 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10407 10408 if (TII->isVOP3(MI.getOpcode())) { 10409 // Make sure constant bus requirements are respected. 10410 TII->legalizeOperandsVOP3(MRI, MI); 10411 10412 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10413 // This saves a chain-copy of registers and better ballance register 10414 // use between vgpr and agpr as agpr tuples tend to be big. 10415 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10416 unsigned Opc = MI.getOpcode(); 10417 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10418 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10419 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10420 if (I == -1) 10421 break; 10422 MachineOperand &Op = MI.getOperand(I); 10423 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10424 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10425 !Register::isVirtualRegister(Op.getReg()) || 10426 !TRI->isAGPR(MRI, Op.getReg())) 10427 continue; 10428 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10429 if (!Src || !Src->isCopy() || 10430 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10431 continue; 10432 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10433 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10434 // All uses of agpr64 and agpr32 can also accept vgpr except for 10435 // v_accvgpr_read, but we do not produce agpr reads during selection, 10436 // so no use checks are needed. 10437 MRI.setRegClass(Op.getReg(), NewRC); 10438 } 10439 } 10440 10441 return; 10442 } 10443 10444 // Replace unused atomics with the no return version. 10445 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10446 if (NoRetAtomicOp != -1) { 10447 if (!Node->hasAnyUseOfValue(0)) { 10448 MI.setDesc(TII->get(NoRetAtomicOp)); 10449 MI.RemoveOperand(0); 10450 return; 10451 } 10452 10453 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10454 // instruction, because the return type of these instructions is a vec2 of 10455 // the memory type, so it can be tied to the input operand. 10456 // This means these instructions always have a use, so we need to add a 10457 // special case to check if the atomic has only one extract_subreg use, 10458 // which itself has no uses. 10459 if ((Node->hasNUsesOfValue(1, 0) && 10460 Node->use_begin()->isMachineOpcode() && 10461 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10462 !Node->use_begin()->hasAnyUseOfValue(0))) { 10463 Register Def = MI.getOperand(0).getReg(); 10464 10465 // Change this into a noret atomic. 10466 MI.setDesc(TII->get(NoRetAtomicOp)); 10467 MI.RemoveOperand(0); 10468 10469 // If we only remove the def operand from the atomic instruction, the 10470 // extract_subreg will be left with a use of a vreg without a def. 10471 // So we need to insert an implicit_def to avoid machine verifier 10472 // errors. 10473 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10474 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10475 } 10476 return; 10477 } 10478 } 10479 10480 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 10481 uint64_t Val) { 10482 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 10483 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 10484 } 10485 10486 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 10487 const SDLoc &DL, 10488 SDValue Ptr) const { 10489 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10490 10491 // Build the half of the subregister with the constants before building the 10492 // full 128-bit register. If we are building multiple resource descriptors, 10493 // this will allow CSEing of the 2-component register. 10494 const SDValue Ops0[] = { 10495 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 10496 buildSMovImm32(DAG, DL, 0), 10497 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10498 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 10499 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 10500 }; 10501 10502 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 10503 MVT::v2i32, Ops0), 0); 10504 10505 // Combine the constants and the pointer. 10506 const SDValue Ops1[] = { 10507 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10508 Ptr, 10509 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 10510 SubRegHi, 10511 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 10512 }; 10513 10514 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 10515 } 10516 10517 /// Return a resource descriptor with the 'Add TID' bit enabled 10518 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 10519 /// of the resource descriptor) to create an offset, which is added to 10520 /// the resource pointer. 10521 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 10522 SDValue Ptr, uint32_t RsrcDword1, 10523 uint64_t RsrcDword2And3) const { 10524 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 10525 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 10526 if (RsrcDword1) { 10527 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 10528 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 10529 0); 10530 } 10531 10532 SDValue DataLo = buildSMovImm32(DAG, DL, 10533 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 10534 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 10535 10536 const SDValue Ops[] = { 10537 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10538 PtrLo, 10539 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10540 PtrHi, 10541 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 10542 DataLo, 10543 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 10544 DataHi, 10545 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 10546 }; 10547 10548 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 10549 } 10550 10551 //===----------------------------------------------------------------------===// 10552 // SI Inline Assembly Support 10553 //===----------------------------------------------------------------------===// 10554 10555 std::pair<unsigned, const TargetRegisterClass *> 10556 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10557 StringRef Constraint, 10558 MVT VT) const { 10559 const TargetRegisterClass *RC = nullptr; 10560 if (Constraint.size() == 1) { 10561 switch (Constraint[0]) { 10562 default: 10563 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10564 case 's': 10565 case 'r': 10566 switch (VT.getSizeInBits()) { 10567 default: 10568 return std::make_pair(0U, nullptr); 10569 case 32: 10570 case 16: 10571 RC = &AMDGPU::SReg_32RegClass; 10572 break; 10573 case 64: 10574 RC = &AMDGPU::SGPR_64RegClass; 10575 break; 10576 case 96: 10577 RC = &AMDGPU::SReg_96RegClass; 10578 break; 10579 case 128: 10580 RC = &AMDGPU::SGPR_128RegClass; 10581 break; 10582 case 160: 10583 RC = &AMDGPU::SReg_160RegClass; 10584 break; 10585 case 256: 10586 RC = &AMDGPU::SReg_256RegClass; 10587 break; 10588 case 512: 10589 RC = &AMDGPU::SReg_512RegClass; 10590 break; 10591 } 10592 break; 10593 case 'v': 10594 switch (VT.getSizeInBits()) { 10595 default: 10596 return std::make_pair(0U, nullptr); 10597 case 32: 10598 case 16: 10599 RC = &AMDGPU::VGPR_32RegClass; 10600 break; 10601 case 64: 10602 RC = &AMDGPU::VReg_64RegClass; 10603 break; 10604 case 96: 10605 RC = &AMDGPU::VReg_96RegClass; 10606 break; 10607 case 128: 10608 RC = &AMDGPU::VReg_128RegClass; 10609 break; 10610 case 160: 10611 RC = &AMDGPU::VReg_160RegClass; 10612 break; 10613 case 256: 10614 RC = &AMDGPU::VReg_256RegClass; 10615 break; 10616 case 512: 10617 RC = &AMDGPU::VReg_512RegClass; 10618 break; 10619 } 10620 break; 10621 case 'a': 10622 if (!Subtarget->hasMAIInsts()) 10623 break; 10624 switch (VT.getSizeInBits()) { 10625 default: 10626 return std::make_pair(0U, nullptr); 10627 case 32: 10628 case 16: 10629 RC = &AMDGPU::AGPR_32RegClass; 10630 break; 10631 case 64: 10632 RC = &AMDGPU::AReg_64RegClass; 10633 break; 10634 case 128: 10635 RC = &AMDGPU::AReg_128RegClass; 10636 break; 10637 case 512: 10638 RC = &AMDGPU::AReg_512RegClass; 10639 break; 10640 case 1024: 10641 RC = &AMDGPU::AReg_1024RegClass; 10642 // v32 types are not legal but we support them here. 10643 return std::make_pair(0U, RC); 10644 } 10645 break; 10646 } 10647 // We actually support i128, i16 and f16 as inline parameters 10648 // even if they are not reported as legal 10649 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 10650 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 10651 return std::make_pair(0U, RC); 10652 } 10653 10654 if (Constraint.size() > 1) { 10655 if (Constraint[1] == 'v') { 10656 RC = &AMDGPU::VGPR_32RegClass; 10657 } else if (Constraint[1] == 's') { 10658 RC = &AMDGPU::SGPR_32RegClass; 10659 } else if (Constraint[1] == 'a') { 10660 RC = &AMDGPU::AGPR_32RegClass; 10661 } 10662 10663 if (RC) { 10664 uint32_t Idx; 10665 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 10666 if (!Failed && Idx < RC->getNumRegs()) 10667 return std::make_pair(RC->getRegister(Idx), RC); 10668 } 10669 } 10670 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10671 } 10672 10673 SITargetLowering::ConstraintType 10674 SITargetLowering::getConstraintType(StringRef Constraint) const { 10675 if (Constraint.size() == 1) { 10676 switch (Constraint[0]) { 10677 default: break; 10678 case 's': 10679 case 'v': 10680 case 'a': 10681 return C_RegisterClass; 10682 } 10683 } 10684 return TargetLowering::getConstraintType(Constraint); 10685 } 10686 10687 // Figure out which registers should be reserved for stack access. Only after 10688 // the function is legalized do we know all of the non-spill stack objects or if 10689 // calls are present. 10690 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 10691 MachineRegisterInfo &MRI = MF.getRegInfo(); 10692 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10693 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 10694 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10695 10696 if (Info->isEntryFunction()) { 10697 // Callable functions have fixed registers used for stack access. 10698 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 10699 } 10700 10701 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 10702 Info->getStackPtrOffsetReg())); 10703 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 10704 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 10705 10706 // We need to worry about replacing the default register with itself in case 10707 // of MIR testcases missing the MFI. 10708 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 10709 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 10710 10711 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 10712 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 10713 10714 if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) { 10715 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG, 10716 Info->getScratchWaveOffsetReg()); 10717 } 10718 10719 Info->limitOccupancy(MF); 10720 10721 if (ST.isWave32() && !MF.empty()) { 10722 // Add VCC_HI def because many instructions marked as imp-use VCC where 10723 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 10724 // having a use of undef. 10725 10726 const SIInstrInfo *TII = ST.getInstrInfo(); 10727 DebugLoc DL; 10728 10729 MachineBasicBlock &MBB = MF.front(); 10730 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 10731 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 10732 10733 for (auto &MBB : MF) { 10734 for (auto &MI : MBB) { 10735 TII->fixImplicitOperands(MI); 10736 } 10737 } 10738 } 10739 10740 TargetLoweringBase::finalizeLowering(MF); 10741 } 10742 10743 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 10744 KnownBits &Known, 10745 const APInt &DemandedElts, 10746 const SelectionDAG &DAG, 10747 unsigned Depth) const { 10748 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 10749 DAG, Depth); 10750 10751 // Set the high bits to zero based on the maximum allowed scratch size per 10752 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 10753 // calculation won't overflow, so assume the sign bit is never set. 10754 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 10755 } 10756 10757 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 10758 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 10759 const Align CacheLineAlign = Align(64); 10760 10761 // Pre-GFX10 target did not benefit from loop alignment 10762 if (!ML || DisableLoopAlignment || 10763 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 10764 getSubtarget()->hasInstFwdPrefetchBug()) 10765 return PrefAlign; 10766 10767 // On GFX10 I$ is 4 x 64 bytes cache lines. 10768 // By default prefetcher keeps one cache line behind and reads two ahead. 10769 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 10770 // behind and one ahead. 10771 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 10772 // If loop fits 64 bytes it always spans no more than two cache lines and 10773 // does not need an alignment. 10774 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 10775 // Else if loop is less or equal 192 bytes we need two lines behind. 10776 10777 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10778 const MachineBasicBlock *Header = ML->getHeader(); 10779 if (Header->getAlignment() != PrefAlign) 10780 return Header->getAlignment(); // Already processed. 10781 10782 unsigned LoopSize = 0; 10783 for (const MachineBasicBlock *MBB : ML->blocks()) { 10784 // If inner loop block is aligned assume in average half of the alignment 10785 // size to be added as nops. 10786 if (MBB != Header) 10787 LoopSize += MBB->getAlignment().value() / 2; 10788 10789 for (const MachineInstr &MI : *MBB) { 10790 LoopSize += TII->getInstSizeInBytes(MI); 10791 if (LoopSize > 192) 10792 return PrefAlign; 10793 } 10794 } 10795 10796 if (LoopSize <= 64) 10797 return PrefAlign; 10798 10799 if (LoopSize <= 128) 10800 return CacheLineAlign; 10801 10802 // If any of parent loops is surrounded by prefetch instructions do not 10803 // insert new for inner loop, which would reset parent's settings. 10804 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 10805 if (MachineBasicBlock *Exit = P->getExitBlock()) { 10806 auto I = Exit->getFirstNonDebugInstr(); 10807 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 10808 return CacheLineAlign; 10809 } 10810 } 10811 10812 MachineBasicBlock *Pre = ML->getLoopPreheader(); 10813 MachineBasicBlock *Exit = ML->getExitBlock(); 10814 10815 if (Pre && Exit) { 10816 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 10817 TII->get(AMDGPU::S_INST_PREFETCH)) 10818 .addImm(1); // prefetch 2 lines behind PC 10819 10820 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 10821 TII->get(AMDGPU::S_INST_PREFETCH)) 10822 .addImm(2); // prefetch 1 line behind PC 10823 } 10824 10825 return CacheLineAlign; 10826 } 10827 10828 LLVM_ATTRIBUTE_UNUSED 10829 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 10830 assert(N->getOpcode() == ISD::CopyFromReg); 10831 do { 10832 // Follow the chain until we find an INLINEASM node. 10833 N = N->getOperand(0).getNode(); 10834 if (N->getOpcode() == ISD::INLINEASM || 10835 N->getOpcode() == ISD::INLINEASM_BR) 10836 return true; 10837 } while (N->getOpcode() == ISD::CopyFromReg); 10838 return false; 10839 } 10840 10841 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 10842 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 10843 { 10844 switch (N->getOpcode()) { 10845 case ISD::CopyFromReg: 10846 { 10847 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 10848 const MachineFunction * MF = FLI->MF; 10849 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 10850 const MachineRegisterInfo &MRI = MF->getRegInfo(); 10851 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo(); 10852 unsigned Reg = R->getReg(); 10853 if (Register::isPhysicalRegister(Reg)) 10854 return !TRI.isSGPRReg(MRI, Reg); 10855 10856 if (MRI.isLiveIn(Reg)) { 10857 // workitem.id.x workitem.id.y workitem.id.z 10858 // Any VGPR formal argument is also considered divergent 10859 if (!TRI.isSGPRReg(MRI, Reg)) 10860 return true; 10861 // Formal arguments of non-entry functions 10862 // are conservatively considered divergent 10863 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv())) 10864 return true; 10865 return false; 10866 } 10867 const Value *V = FLI->getValueFromVirtualReg(Reg); 10868 if (V) 10869 return KDA->isDivergent(V); 10870 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 10871 return !TRI.isSGPRReg(MRI, Reg); 10872 } 10873 break; 10874 case ISD::LOAD: { 10875 const LoadSDNode *L = cast<LoadSDNode>(N); 10876 unsigned AS = L->getAddressSpace(); 10877 // A flat load may access private memory. 10878 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 10879 } break; 10880 case ISD::CALLSEQ_END: 10881 return true; 10882 break; 10883 case ISD::INTRINSIC_WO_CHAIN: 10884 { 10885 10886 } 10887 return AMDGPU::isIntrinsicSourceOfDivergence( 10888 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 10889 case ISD::INTRINSIC_W_CHAIN: 10890 return AMDGPU::isIntrinsicSourceOfDivergence( 10891 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 10892 } 10893 return false; 10894 } 10895 10896 bool SITargetLowering::denormalsEnabledForType(EVT VT) const { 10897 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 10898 case MVT::f32: 10899 return Subtarget->hasFP32Denormals(); 10900 case MVT::f64: 10901 return Subtarget->hasFP64Denormals(); 10902 case MVT::f16: 10903 return Subtarget->hasFP16Denormals(); 10904 default: 10905 return false; 10906 } 10907 } 10908 10909 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 10910 const SelectionDAG &DAG, 10911 bool SNaN, 10912 unsigned Depth) const { 10913 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 10914 const MachineFunction &MF = DAG.getMachineFunction(); 10915 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10916 10917 if (Info->getMode().DX10Clamp) 10918 return true; // Clamped to 0. 10919 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 10920 } 10921 10922 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 10923 SNaN, Depth); 10924 } 10925 10926 TargetLowering::AtomicExpansionKind 10927 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 10928 switch (RMW->getOperation()) { 10929 case AtomicRMWInst::FAdd: { 10930 Type *Ty = RMW->getType(); 10931 10932 // We don't have a way to support 16-bit atomics now, so just leave them 10933 // as-is. 10934 if (Ty->isHalfTy()) 10935 return AtomicExpansionKind::None; 10936 10937 if (!Ty->isFloatTy()) 10938 return AtomicExpansionKind::CmpXChg; 10939 10940 // TODO: Do have these for flat. Older targets also had them for buffers. 10941 unsigned AS = RMW->getPointerAddressSpace(); 10942 10943 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 10944 return RMW->use_empty() ? AtomicExpansionKind::None : 10945 AtomicExpansionKind::CmpXChg; 10946 } 10947 10948 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 10949 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 10950 } 10951 default: 10952 break; 10953 } 10954 10955 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 10956 } 10957 10958 const TargetRegisterClass * 10959 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 10960 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 10961 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10962 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 10963 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 10964 : &AMDGPU::SReg_32RegClass; 10965 if (!TRI->isSGPRClass(RC) && !isDivergent) 10966 return TRI->getEquivalentSGPRClass(RC); 10967 else if (TRI->isSGPRClass(RC) && isDivergent) 10968 return TRI->getEquivalentVGPRClass(RC); 10969 10970 return RC; 10971 } 10972 10973 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited) { 10974 if (!Visited.insert(V).second) 10975 return false; 10976 bool Result = false; 10977 for (auto U : V->users()) { 10978 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 10979 if (V == U->getOperand(1)) { 10980 switch (Intrinsic->getIntrinsicID()) { 10981 default: 10982 Result = false; 10983 break; 10984 case Intrinsic::amdgcn_if_break: 10985 case Intrinsic::amdgcn_if: 10986 case Intrinsic::amdgcn_else: 10987 Result = true; 10988 break; 10989 } 10990 } 10991 if (V == U->getOperand(0)) { 10992 switch (Intrinsic->getIntrinsicID()) { 10993 default: 10994 Result = false; 10995 break; 10996 case Intrinsic::amdgcn_end_cf: 10997 case Intrinsic::amdgcn_loop: 10998 Result = true; 10999 break; 11000 } 11001 } 11002 } else { 11003 Result = hasCFUser(U, Visited); 11004 } 11005 if (Result) 11006 break; 11007 } 11008 return Result; 11009 } 11010 11011 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11012 const Value *V) const { 11013 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) { 11014 switch (Intrinsic->getIntrinsicID()) { 11015 default: 11016 return false; 11017 case Intrinsic::amdgcn_if_break: 11018 return true; 11019 } 11020 } 11021 if (const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V)) { 11022 if (const IntrinsicInst *Intrinsic = 11023 dyn_cast<IntrinsicInst>(ExtValue->getOperand(0))) { 11024 switch (Intrinsic->getIntrinsicID()) { 11025 default: 11026 return false; 11027 case Intrinsic::amdgcn_if: 11028 case Intrinsic::amdgcn_else: { 11029 ArrayRef<unsigned> Indices = ExtValue->getIndices(); 11030 if (Indices.size() == 1 && Indices[0] == 1) { 11031 return true; 11032 } 11033 } 11034 } 11035 } 11036 } 11037 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11038 if (isa<InlineAsm>(CI->getCalledValue())) { 11039 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11040 ImmutableCallSite CS(CI); 11041 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11042 MF.getDataLayout(), Subtarget->getRegisterInfo(), CS); 11043 for (auto &TC : TargetConstraints) { 11044 if (TC.Type == InlineAsm::isOutput) { 11045 ComputeConstraintToUse(TC, SDValue()); 11046 unsigned AssignedReg; 11047 const TargetRegisterClass *RC; 11048 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11049 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11050 if (RC) { 11051 MachineRegisterInfo &MRI = MF.getRegInfo(); 11052 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11053 return true; 11054 else if (SIRI->isSGPRClass(RC)) 11055 return true; 11056 } 11057 } 11058 } 11059 } 11060 } 11061 SmallPtrSet<const Value *, 16> Visited; 11062 return hasCFUser(V, Visited); 11063 } 11064