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