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> DisableLoopAlignment( 94 "amdgpu-disable-loop-alignment", 95 cl::desc("Do not align and prefetch loops"), 96 cl::init(false)); 97 98 static bool hasFP32Denormals(const MachineFunction &MF) { 99 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 100 return Info->getMode().allFP32Denormals(); 101 } 102 103 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 104 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 105 return Info->getMode().allFP64FP16Denormals(); 106 } 107 108 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 109 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 110 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 111 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 112 return AMDGPU::SGPR0 + Reg; 113 } 114 } 115 llvm_unreachable("Cannot allocate sgpr"); 116 } 117 118 SITargetLowering::SITargetLowering(const TargetMachine &TM, 119 const GCNSubtarget &STI) 120 : AMDGPUTargetLowering(TM, STI), 121 Subtarget(&STI) { 122 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 123 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 124 125 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 126 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 127 128 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 129 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 130 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 131 132 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 133 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 134 135 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 136 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 137 138 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 139 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 140 141 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 142 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 143 144 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass); 145 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 146 147 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass); 148 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 149 150 if (Subtarget->has16BitInsts()) { 151 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 152 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 153 154 // Unless there are also VOP3P operations, not operations are really legal. 155 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 156 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 157 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 158 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 159 } 160 161 if (Subtarget->hasMAIInsts()) { 162 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 163 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 164 } 165 166 computeRegisterProperties(Subtarget->getRegisterInfo()); 167 168 // The boolean content concept here is too inflexible. Compares only ever 169 // really produce a 1-bit result. Any copy/extend from these will turn into a 170 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 171 // it's what most targets use. 172 setBooleanContents(ZeroOrOneBooleanContent); 173 setBooleanVectorContents(ZeroOrOneBooleanContent); 174 175 // We need to custom lower vector stores from local memory 176 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 177 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 178 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 179 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 180 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 181 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 182 setOperationAction(ISD::LOAD, MVT::i1, Custom); 183 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 184 185 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 186 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 187 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 188 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 189 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 190 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 191 setOperationAction(ISD::STORE, MVT::i1, Custom); 192 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 193 194 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 195 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 196 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 197 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 198 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 199 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 200 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 201 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 202 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 203 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 204 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 205 206 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 207 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 208 209 setOperationAction(ISD::SELECT, MVT::i1, Promote); 210 setOperationAction(ISD::SELECT, MVT::i64, Custom); 211 setOperationAction(ISD::SELECT, MVT::f64, Promote); 212 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 213 214 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 215 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 216 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 217 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 218 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 219 220 setOperationAction(ISD::SETCC, MVT::i1, Promote); 221 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 222 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 223 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 224 225 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 226 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 227 228 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 229 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 230 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 231 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 232 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 233 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 234 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 235 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 236 237 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 238 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 239 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 240 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 241 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 242 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 243 244 setOperationAction(ISD::UADDO, MVT::i32, Legal); 245 setOperationAction(ISD::USUBO, MVT::i32, Legal); 246 247 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 248 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 249 250 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 251 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 252 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 253 254 #if 0 255 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 256 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 257 #endif 258 259 // We only support LOAD/STORE and vector manipulation ops for vectors 260 // with > 4 elements. 261 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 262 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 263 MVT::v32i32, MVT::v32f32 }) { 264 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 265 switch (Op) { 266 case ISD::LOAD: 267 case ISD::STORE: 268 case ISD::BUILD_VECTOR: 269 case ISD::BITCAST: 270 case ISD::EXTRACT_VECTOR_ELT: 271 case ISD::INSERT_VECTOR_ELT: 272 case ISD::INSERT_SUBVECTOR: 273 case ISD::EXTRACT_SUBVECTOR: 274 case ISD::SCALAR_TO_VECTOR: 275 break; 276 case ISD::CONCAT_VECTORS: 277 setOperationAction(Op, VT, Custom); 278 break; 279 default: 280 setOperationAction(Op, VT, Expand); 281 break; 282 } 283 } 284 } 285 286 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 287 288 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 289 // is expanded to avoid having two separate loops in case the index is a VGPR. 290 291 // Most operations are naturally 32-bit vector operations. We only support 292 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 293 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 294 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 295 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 296 297 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 298 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 299 300 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 301 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 302 303 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 304 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 305 } 306 307 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 308 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 309 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 310 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 311 312 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 313 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 314 315 // Avoid stack access for these. 316 // TODO: Generalize to more vector types. 317 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 318 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 319 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 320 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 321 322 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 323 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 324 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 325 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 326 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 327 328 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 329 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 330 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 331 332 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 333 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 334 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 335 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 336 337 // Deal with vec3 vector operations when widened to vec4. 338 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 339 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 340 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 341 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 342 343 // Deal with vec5 vector operations when widened to vec8. 344 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 345 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 346 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 347 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 348 349 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 350 // and output demarshalling 351 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 352 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 353 354 // We can't return success/failure, only the old value, 355 // let LLVM add the comparison 356 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 357 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 358 359 if (Subtarget->hasFlatAddressSpace()) { 360 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 361 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 362 } 363 364 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 365 366 // FIXME: This should be narrowed to i32, but that only happens if i64 is 367 // illegal. 368 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 369 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 370 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 371 372 // On SI this is s_memtime and s_memrealtime on VI. 373 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 374 setOperationAction(ISD::TRAP, MVT::Other, Custom); 375 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 376 377 if (Subtarget->has16BitInsts()) { 378 setOperationAction(ISD::FPOW, MVT::f16, Promote); 379 setOperationAction(ISD::FLOG, MVT::f16, Custom); 380 setOperationAction(ISD::FEXP, MVT::f16, Custom); 381 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 382 } 383 384 // v_mad_f32 does not support denormals. We report it as unconditionally 385 // legal, and the context where it is formed will disallow it when fp32 386 // denormals are enabled. 387 setOperationAction(ISD::FMAD, MVT::f32, Legal); 388 389 if (!Subtarget->hasBFI()) { 390 // fcopysign can be done in a single instruction with BFI. 391 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 392 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 393 } 394 395 if (!Subtarget->hasBCNT(32)) 396 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 397 398 if (!Subtarget->hasBCNT(64)) 399 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 400 401 if (Subtarget->hasFFBH()) 402 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 403 404 if (Subtarget->hasFFBL()) 405 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 406 407 // We only really have 32-bit BFE instructions (and 16-bit on VI). 408 // 409 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 410 // effort to match them now. We want this to be false for i64 cases when the 411 // extraction isn't restricted to the upper or lower half. Ideally we would 412 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 413 // span the midpoint are probably relatively rare, so don't worry about them 414 // for now. 415 if (Subtarget->hasBFE()) 416 setHasExtractBitsInsn(true); 417 418 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 419 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 420 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 421 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 422 423 424 // These are really only legal for ieee_mode functions. We should be avoiding 425 // them for functions that don't have ieee_mode enabled, so just say they are 426 // legal. 427 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 428 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 429 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 430 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 431 432 433 if (Subtarget->haveRoundOpsF64()) { 434 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 435 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 436 setOperationAction(ISD::FRINT, MVT::f64, Legal); 437 } else { 438 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 439 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 440 setOperationAction(ISD::FRINT, MVT::f64, Custom); 441 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 442 } 443 444 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 445 446 setOperationAction(ISD::FSIN, MVT::f32, Custom); 447 setOperationAction(ISD::FCOS, MVT::f32, Custom); 448 setOperationAction(ISD::FDIV, MVT::f32, Custom); 449 setOperationAction(ISD::FDIV, MVT::f64, Custom); 450 451 if (Subtarget->has16BitInsts()) { 452 setOperationAction(ISD::Constant, MVT::i16, Legal); 453 454 setOperationAction(ISD::SMIN, MVT::i16, Legal); 455 setOperationAction(ISD::SMAX, MVT::i16, Legal); 456 457 setOperationAction(ISD::UMIN, MVT::i16, Legal); 458 setOperationAction(ISD::UMAX, MVT::i16, Legal); 459 460 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 461 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 462 463 setOperationAction(ISD::ROTR, MVT::i16, Promote); 464 setOperationAction(ISD::ROTL, MVT::i16, Promote); 465 466 setOperationAction(ISD::SDIV, MVT::i16, Promote); 467 setOperationAction(ISD::UDIV, MVT::i16, Promote); 468 setOperationAction(ISD::SREM, MVT::i16, Promote); 469 setOperationAction(ISD::UREM, MVT::i16, Promote); 470 471 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 472 473 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 474 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 475 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 476 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 477 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 478 479 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 480 481 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 482 483 setOperationAction(ISD::LOAD, MVT::i16, Custom); 484 485 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 486 487 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 488 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 489 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 490 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 491 492 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 493 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 494 495 // F16 - Constant Actions. 496 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 497 498 // F16 - Load/Store Actions. 499 setOperationAction(ISD::LOAD, MVT::f16, Promote); 500 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 501 setOperationAction(ISD::STORE, MVT::f16, Promote); 502 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 503 504 // F16 - VOP1 Actions. 505 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 506 setOperationAction(ISD::FCOS, MVT::f16, Custom); 507 setOperationAction(ISD::FSIN, MVT::f16, Custom); 508 509 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 510 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 511 512 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 513 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 514 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 515 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 516 setOperationAction(ISD::FROUND, MVT::f16, Custom); 517 518 // F16 - VOP2 Actions. 519 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 520 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 521 522 setOperationAction(ISD::FDIV, MVT::f16, Custom); 523 524 // F16 - VOP3 Actions. 525 setOperationAction(ISD::FMA, MVT::f16, Legal); 526 if (STI.hasMadF16()) 527 setOperationAction(ISD::FMAD, MVT::f16, Legal); 528 529 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 530 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 531 switch (Op) { 532 case ISD::LOAD: 533 case ISD::STORE: 534 case ISD::BUILD_VECTOR: 535 case ISD::BITCAST: 536 case ISD::EXTRACT_VECTOR_ELT: 537 case ISD::INSERT_VECTOR_ELT: 538 case ISD::INSERT_SUBVECTOR: 539 case ISD::EXTRACT_SUBVECTOR: 540 case ISD::SCALAR_TO_VECTOR: 541 break; 542 case ISD::CONCAT_VECTORS: 543 setOperationAction(Op, VT, Custom); 544 break; 545 default: 546 setOperationAction(Op, VT, Expand); 547 break; 548 } 549 } 550 } 551 552 // v_perm_b32 can handle either of these. 553 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 554 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 555 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 556 557 // XXX - Do these do anything? Vector constants turn into build_vector. 558 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 559 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 560 561 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 562 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 563 564 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 565 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 566 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 567 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 568 569 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 570 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 571 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 572 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 573 574 setOperationAction(ISD::AND, MVT::v2i16, Promote); 575 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 576 setOperationAction(ISD::OR, MVT::v2i16, Promote); 577 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 578 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 579 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 580 581 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 582 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 583 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 584 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 585 586 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 587 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 588 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 589 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 590 591 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 592 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 593 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 594 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 595 596 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 597 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 598 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 599 600 if (!Subtarget->hasVOP3PInsts()) { 601 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 602 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 603 } 604 605 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 606 // This isn't really legal, but this avoids the legalizer unrolling it (and 607 // allows matching fneg (fabs x) patterns) 608 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 609 610 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 611 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 612 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 613 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 614 615 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 616 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 617 618 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 619 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 620 } 621 622 if (Subtarget->hasVOP3PInsts()) { 623 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 624 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 625 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 626 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 627 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 628 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 629 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 630 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 631 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 632 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 633 634 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 635 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 636 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 637 638 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 639 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 640 641 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 642 643 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 644 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 645 646 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 647 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 648 649 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 650 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 651 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 652 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 653 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 654 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 655 656 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 657 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 658 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 659 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 660 661 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 662 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 663 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 664 665 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 666 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 667 668 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 669 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 670 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 671 672 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 673 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 674 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 675 } 676 677 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 678 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 679 680 if (Subtarget->has16BitInsts()) { 681 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 682 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 683 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 684 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 685 } else { 686 // Legalization hack. 687 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 688 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 689 690 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 691 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 692 } 693 694 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 695 setOperationAction(ISD::SELECT, VT, Custom); 696 } 697 698 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 699 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 700 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 701 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 702 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 703 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 704 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 705 706 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 707 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 708 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 709 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 710 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 711 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 712 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 713 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 714 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 715 716 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 717 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 718 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 719 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 720 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 721 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 722 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 723 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 724 725 setTargetDAGCombine(ISD::ADD); 726 setTargetDAGCombine(ISD::ADDCARRY); 727 setTargetDAGCombine(ISD::SUB); 728 setTargetDAGCombine(ISD::SUBCARRY); 729 setTargetDAGCombine(ISD::FADD); 730 setTargetDAGCombine(ISD::FSUB); 731 setTargetDAGCombine(ISD::FMINNUM); 732 setTargetDAGCombine(ISD::FMAXNUM); 733 setTargetDAGCombine(ISD::FMINNUM_IEEE); 734 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 735 setTargetDAGCombine(ISD::FMA); 736 setTargetDAGCombine(ISD::SMIN); 737 setTargetDAGCombine(ISD::SMAX); 738 setTargetDAGCombine(ISD::UMIN); 739 setTargetDAGCombine(ISD::UMAX); 740 setTargetDAGCombine(ISD::SETCC); 741 setTargetDAGCombine(ISD::AND); 742 setTargetDAGCombine(ISD::OR); 743 setTargetDAGCombine(ISD::XOR); 744 setTargetDAGCombine(ISD::SINT_TO_FP); 745 setTargetDAGCombine(ISD::UINT_TO_FP); 746 setTargetDAGCombine(ISD::FCANONICALIZE); 747 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 748 setTargetDAGCombine(ISD::ZERO_EXTEND); 749 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 750 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 751 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 752 753 // All memory operations. Some folding on the pointer operand is done to help 754 // matching the constant offsets in the addressing modes. 755 setTargetDAGCombine(ISD::LOAD); 756 setTargetDAGCombine(ISD::STORE); 757 setTargetDAGCombine(ISD::ATOMIC_LOAD); 758 setTargetDAGCombine(ISD::ATOMIC_STORE); 759 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 760 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 761 setTargetDAGCombine(ISD::ATOMIC_SWAP); 762 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 763 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 764 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 765 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 766 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 767 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 768 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 769 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 770 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 771 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 772 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 773 774 setSchedulingPreference(Sched::RegPressure); 775 } 776 777 const GCNSubtarget *SITargetLowering::getSubtarget() const { 778 return Subtarget; 779 } 780 781 //===----------------------------------------------------------------------===// 782 // TargetLowering queries 783 //===----------------------------------------------------------------------===// 784 785 // v_mad_mix* support a conversion from f16 to f32. 786 // 787 // There is only one special case when denormals are enabled we don't currently, 788 // where this is OK to use. 789 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 790 EVT DestVT, EVT SrcVT) const { 791 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 792 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 793 DestVT.getScalarType() == MVT::f32 && 794 SrcVT.getScalarType() == MVT::f16 && 795 // TODO: This probably only requires no input flushing? 796 !hasFP32Denormals(DAG.getMachineFunction()); 797 } 798 799 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 800 // SI has some legal vector types, but no legal vector operations. Say no 801 // shuffles are legal in order to prefer scalarizing some vector operations. 802 return false; 803 } 804 805 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 806 CallingConv::ID CC, 807 EVT VT) const { 808 if (CC == CallingConv::AMDGPU_KERNEL) 809 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 810 811 if (VT.isVector()) { 812 EVT ScalarVT = VT.getScalarType(); 813 unsigned Size = ScalarVT.getSizeInBits(); 814 if (Size == 32) 815 return ScalarVT.getSimpleVT(); 816 817 if (Size > 32) 818 return MVT::i32; 819 820 if (Size == 16 && Subtarget->has16BitInsts()) 821 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 822 } else if (VT.getSizeInBits() > 32) 823 return MVT::i32; 824 825 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 826 } 827 828 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 829 CallingConv::ID CC, 830 EVT VT) const { 831 if (CC == CallingConv::AMDGPU_KERNEL) 832 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 833 834 if (VT.isVector()) { 835 unsigned NumElts = VT.getVectorNumElements(); 836 EVT ScalarVT = VT.getScalarType(); 837 unsigned Size = ScalarVT.getSizeInBits(); 838 839 if (Size == 32) 840 return NumElts; 841 842 if (Size > 32) 843 return NumElts * ((Size + 31) / 32); 844 845 if (Size == 16 && Subtarget->has16BitInsts()) 846 return (NumElts + 1) / 2; 847 } else if (VT.getSizeInBits() > 32) 848 return (VT.getSizeInBits() + 31) / 32; 849 850 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 851 } 852 853 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 854 LLVMContext &Context, CallingConv::ID CC, 855 EVT VT, EVT &IntermediateVT, 856 unsigned &NumIntermediates, MVT &RegisterVT) const { 857 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 858 unsigned NumElts = VT.getVectorNumElements(); 859 EVT ScalarVT = VT.getScalarType(); 860 unsigned Size = ScalarVT.getSizeInBits(); 861 if (Size == 32) { 862 RegisterVT = ScalarVT.getSimpleVT(); 863 IntermediateVT = RegisterVT; 864 NumIntermediates = NumElts; 865 return NumIntermediates; 866 } 867 868 if (Size > 32) { 869 RegisterVT = MVT::i32; 870 IntermediateVT = RegisterVT; 871 NumIntermediates = NumElts * ((Size + 31) / 32); 872 return NumIntermediates; 873 } 874 875 // FIXME: We should fix the ABI to be the same on targets without 16-bit 876 // support, but unless we can properly handle 3-vectors, it will be still be 877 // inconsistent. 878 if (Size == 16 && Subtarget->has16BitInsts()) { 879 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 880 IntermediateVT = RegisterVT; 881 NumIntermediates = (NumElts + 1) / 2; 882 return NumIntermediates; 883 } 884 } 885 886 return TargetLowering::getVectorTypeBreakdownForCallingConv( 887 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 888 } 889 890 // Peek through TFE struct returns to only use the data size. 891 static EVT memVTFromImageReturn(Type *Ty) { 892 auto *ST = dyn_cast<StructType>(Ty); 893 if (!ST) 894 return EVT::getEVT(Ty, true); 895 896 // Some intrinsics return an aggregate type - special case to work out the 897 // correct memVT. 898 // 899 // Only limited forms of aggregate type currently expected. 900 if (ST->getNumContainedTypes() != 2 || 901 !ST->getContainedType(1)->isIntegerTy(32)) 902 return EVT(); 903 return EVT::getEVT(ST->getContainedType(0)); 904 } 905 906 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 907 const CallInst &CI, 908 MachineFunction &MF, 909 unsigned IntrID) const { 910 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 911 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 912 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 913 (Intrinsic::ID)IntrID); 914 if (Attr.hasFnAttribute(Attribute::ReadNone)) 915 return false; 916 917 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 918 919 if (RsrcIntr->IsImage) { 920 Info.ptrVal = MFI->getImagePSV( 921 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 922 CI.getArgOperand(RsrcIntr->RsrcArg)); 923 Info.align.reset(); 924 } else { 925 Info.ptrVal = MFI->getBufferPSV( 926 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 927 CI.getArgOperand(RsrcIntr->RsrcArg)); 928 } 929 930 Info.flags = MachineMemOperand::MODereferenceable; 931 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 932 Info.opc = ISD::INTRINSIC_W_CHAIN; 933 // TODO: Account for dmask reducing loaded size. 934 Info.memVT = memVTFromImageReturn(CI.getType()); 935 Info.flags |= MachineMemOperand::MOLoad; 936 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 937 Info.opc = ISD::INTRINSIC_VOID; 938 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 939 Info.flags |= MachineMemOperand::MOStore; 940 } else { 941 // Atomic 942 Info.opc = ISD::INTRINSIC_W_CHAIN; 943 Info.memVT = MVT::getVT(CI.getType()); 944 Info.flags = MachineMemOperand::MOLoad | 945 MachineMemOperand::MOStore | 946 MachineMemOperand::MODereferenceable; 947 948 // XXX - Should this be volatile without known ordering? 949 Info.flags |= MachineMemOperand::MOVolatile; 950 } 951 return true; 952 } 953 954 switch (IntrID) { 955 case Intrinsic::amdgcn_atomic_inc: 956 case Intrinsic::amdgcn_atomic_dec: 957 case Intrinsic::amdgcn_ds_ordered_add: 958 case Intrinsic::amdgcn_ds_ordered_swap: 959 case Intrinsic::amdgcn_ds_fadd: 960 case Intrinsic::amdgcn_ds_fmin: 961 case Intrinsic::amdgcn_ds_fmax: { 962 Info.opc = ISD::INTRINSIC_W_CHAIN; 963 Info.memVT = MVT::getVT(CI.getType()); 964 Info.ptrVal = CI.getOperand(0); 965 Info.align.reset(); 966 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 967 968 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 969 if (!Vol->isZero()) 970 Info.flags |= MachineMemOperand::MOVolatile; 971 972 return true; 973 } 974 case Intrinsic::amdgcn_buffer_atomic_fadd: { 975 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 976 977 Info.opc = ISD::INTRINSIC_VOID; 978 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 979 Info.ptrVal = MFI->getBufferPSV( 980 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 981 CI.getArgOperand(1)); 982 Info.align.reset(); 983 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 984 985 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 986 if (!Vol || !Vol->isZero()) 987 Info.flags |= MachineMemOperand::MOVolatile; 988 989 return true; 990 } 991 case Intrinsic::amdgcn_global_atomic_fadd: { 992 Info.opc = ISD::INTRINSIC_VOID; 993 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 994 ->getPointerElementType()); 995 Info.ptrVal = CI.getOperand(0); 996 Info.align.reset(); 997 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 998 999 return true; 1000 } 1001 case Intrinsic::amdgcn_ds_append: 1002 case Intrinsic::amdgcn_ds_consume: { 1003 Info.opc = ISD::INTRINSIC_W_CHAIN; 1004 Info.memVT = MVT::getVT(CI.getType()); 1005 Info.ptrVal = CI.getOperand(0); 1006 Info.align.reset(); 1007 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1008 1009 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1010 if (!Vol->isZero()) 1011 Info.flags |= MachineMemOperand::MOVolatile; 1012 1013 return true; 1014 } 1015 case Intrinsic::amdgcn_ds_gws_init: 1016 case Intrinsic::amdgcn_ds_gws_barrier: 1017 case Intrinsic::amdgcn_ds_gws_sema_v: 1018 case Intrinsic::amdgcn_ds_gws_sema_br: 1019 case Intrinsic::amdgcn_ds_gws_sema_p: 1020 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1021 Info.opc = ISD::INTRINSIC_VOID; 1022 1023 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1024 Info.ptrVal = 1025 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1026 1027 // This is an abstract access, but we need to specify a type and size. 1028 Info.memVT = MVT::i32; 1029 Info.size = 4; 1030 Info.align = Align(4); 1031 1032 Info.flags = MachineMemOperand::MOStore; 1033 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1034 Info.flags = MachineMemOperand::MOLoad; 1035 return true; 1036 } 1037 default: 1038 return false; 1039 } 1040 } 1041 1042 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1043 SmallVectorImpl<Value*> &Ops, 1044 Type *&AccessTy) const { 1045 switch (II->getIntrinsicID()) { 1046 case Intrinsic::amdgcn_atomic_inc: 1047 case Intrinsic::amdgcn_atomic_dec: 1048 case Intrinsic::amdgcn_ds_ordered_add: 1049 case Intrinsic::amdgcn_ds_ordered_swap: 1050 case Intrinsic::amdgcn_ds_fadd: 1051 case Intrinsic::amdgcn_ds_fmin: 1052 case Intrinsic::amdgcn_ds_fmax: { 1053 Value *Ptr = II->getArgOperand(0); 1054 AccessTy = II->getType(); 1055 Ops.push_back(Ptr); 1056 return true; 1057 } 1058 default: 1059 return false; 1060 } 1061 } 1062 1063 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1064 if (!Subtarget->hasFlatInstOffsets()) { 1065 // Flat instructions do not have offsets, and only have the register 1066 // address. 1067 return AM.BaseOffs == 0 && AM.Scale == 0; 1068 } 1069 1070 return AM.Scale == 0 && 1071 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1072 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1073 /*Signed=*/false)); 1074 } 1075 1076 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1077 if (Subtarget->hasFlatGlobalInsts()) 1078 return AM.Scale == 0 && 1079 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1080 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1081 /*Signed=*/true)); 1082 1083 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1084 // Assume the we will use FLAT for all global memory accesses 1085 // on VI. 1086 // FIXME: This assumption is currently wrong. On VI we still use 1087 // MUBUF instructions for the r + i addressing mode. As currently 1088 // implemented, the MUBUF instructions only work on buffer < 4GB. 1089 // It may be possible to support > 4GB buffers with MUBUF instructions, 1090 // by setting the stride value in the resource descriptor which would 1091 // increase the size limit to (stride * 4GB). However, this is risky, 1092 // because it has never been validated. 1093 return isLegalFlatAddressingMode(AM); 1094 } 1095 1096 return isLegalMUBUFAddressingMode(AM); 1097 } 1098 1099 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1100 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1101 // additionally can do r + r + i with addr64. 32-bit has more addressing 1102 // mode options. Depending on the resource constant, it can also do 1103 // (i64 r0) + (i32 r1) * (i14 i). 1104 // 1105 // Private arrays end up using a scratch buffer most of the time, so also 1106 // assume those use MUBUF instructions. Scratch loads / stores are currently 1107 // implemented as mubuf instructions with offen bit set, so slightly 1108 // different than the normal addr64. 1109 if (!isUInt<12>(AM.BaseOffs)) 1110 return false; 1111 1112 // FIXME: Since we can split immediate into soffset and immediate offset, 1113 // would it make sense to allow any immediate? 1114 1115 switch (AM.Scale) { 1116 case 0: // r + i or just i, depending on HasBaseReg. 1117 return true; 1118 case 1: 1119 return true; // We have r + r or r + i. 1120 case 2: 1121 if (AM.HasBaseReg) { 1122 // Reject 2 * r + r. 1123 return false; 1124 } 1125 1126 // Allow 2 * r as r + r 1127 // Or 2 * r + i is allowed as r + r + i. 1128 return true; 1129 default: // Don't allow n * r 1130 return false; 1131 } 1132 } 1133 1134 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1135 const AddrMode &AM, Type *Ty, 1136 unsigned AS, Instruction *I) const { 1137 // No global is ever allowed as a base. 1138 if (AM.BaseGV) 1139 return false; 1140 1141 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1142 return isLegalGlobalAddressingMode(AM); 1143 1144 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1145 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1146 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1147 // If the offset isn't a multiple of 4, it probably isn't going to be 1148 // correctly aligned. 1149 // FIXME: Can we get the real alignment here? 1150 if (AM.BaseOffs % 4 != 0) 1151 return isLegalMUBUFAddressingMode(AM); 1152 1153 // There are no SMRD extloads, so if we have to do a small type access we 1154 // will use a MUBUF load. 1155 // FIXME?: We also need to do this if unaligned, but we don't know the 1156 // alignment here. 1157 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1158 return isLegalGlobalAddressingMode(AM); 1159 1160 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1161 // SMRD instructions have an 8-bit, dword offset on SI. 1162 if (!isUInt<8>(AM.BaseOffs / 4)) 1163 return false; 1164 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1165 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1166 // in 8-bits, it can use a smaller encoding. 1167 if (!isUInt<32>(AM.BaseOffs / 4)) 1168 return false; 1169 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1170 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1171 if (!isUInt<20>(AM.BaseOffs)) 1172 return false; 1173 } else 1174 llvm_unreachable("unhandled generation"); 1175 1176 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1177 return true; 1178 1179 if (AM.Scale == 1 && AM.HasBaseReg) 1180 return true; 1181 1182 return false; 1183 1184 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1185 return isLegalMUBUFAddressingMode(AM); 1186 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1187 AS == AMDGPUAS::REGION_ADDRESS) { 1188 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1189 // field. 1190 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1191 // an 8-bit dword offset but we don't know the alignment here. 1192 if (!isUInt<16>(AM.BaseOffs)) 1193 return false; 1194 1195 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1196 return true; 1197 1198 if (AM.Scale == 1 && AM.HasBaseReg) 1199 return true; 1200 1201 return false; 1202 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1203 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1204 // For an unknown address space, this usually means that this is for some 1205 // reason being used for pure arithmetic, and not based on some addressing 1206 // computation. We don't have instructions that compute pointers with any 1207 // addressing modes, so treat them as having no offset like flat 1208 // instructions. 1209 return isLegalFlatAddressingMode(AM); 1210 } else { 1211 llvm_unreachable("unhandled address space"); 1212 } 1213 } 1214 1215 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1216 const SelectionDAG &DAG) const { 1217 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1218 return (MemVT.getSizeInBits() <= 4 * 32); 1219 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1220 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1221 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1222 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1223 return (MemVT.getSizeInBits() <= 2 * 32); 1224 } 1225 return true; 1226 } 1227 1228 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1229 unsigned Size, unsigned AddrSpace, unsigned Align, 1230 MachineMemOperand::Flags Flags, bool *IsFast) const { 1231 if (IsFast) 1232 *IsFast = false; 1233 1234 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1235 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1236 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1237 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1238 // with adjacent offsets. 1239 bool AlignedBy4 = (Align % 4 == 0); 1240 if (IsFast) 1241 *IsFast = AlignedBy4; 1242 1243 return AlignedBy4; 1244 } 1245 1246 // FIXME: We have to be conservative here and assume that flat operations 1247 // will access scratch. If we had access to the IR function, then we 1248 // could determine if any private memory was used in the function. 1249 if (!Subtarget->hasUnalignedScratchAccess() && 1250 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1251 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1252 bool AlignedBy4 = Align >= 4; 1253 if (IsFast) 1254 *IsFast = AlignedBy4; 1255 1256 return AlignedBy4; 1257 } 1258 1259 if (Subtarget->hasUnalignedBufferAccess()) { 1260 // If we have an uniform constant load, it still requires using a slow 1261 // buffer instruction if unaligned. 1262 if (IsFast) { 1263 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1264 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1265 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1266 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1267 Align >= 4 : Align != 2; 1268 } 1269 1270 return true; 1271 } 1272 1273 // Smaller than dword value must be aligned. 1274 if (Size < 32) 1275 return false; 1276 1277 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1278 // byte-address are ignored, thus forcing Dword alignment. 1279 // This applies to private, global, and constant memory. 1280 if (IsFast) 1281 *IsFast = true; 1282 1283 return Size >= 32 && Align >= 4; 1284 } 1285 1286 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1287 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1288 bool *IsFast) const { 1289 if (IsFast) 1290 *IsFast = false; 1291 1292 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1293 // which isn't a simple VT. 1294 // Until MVT is extended to handle this, simply check for the size and 1295 // rely on the condition below: allow accesses if the size is a multiple of 4. 1296 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1297 VT.getStoreSize() > 16)) { 1298 return false; 1299 } 1300 1301 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1302 Align, Flags, IsFast); 1303 } 1304 1305 EVT SITargetLowering::getOptimalMemOpType( 1306 const MemOp &Op, const AttributeList &FuncAttributes) const { 1307 // FIXME: Should account for address space here. 1308 1309 // The default fallback uses the private pointer size as a guess for a type to 1310 // use. Make sure we switch these to 64-bit accesses. 1311 1312 if (Op.size() >= 16 && 1313 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1314 return MVT::v4i32; 1315 1316 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1317 return MVT::v2i32; 1318 1319 // Use the default. 1320 return MVT::Other; 1321 } 1322 1323 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1324 unsigned DestAS) const { 1325 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1326 } 1327 1328 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1329 const MemSDNode *MemNode = cast<MemSDNode>(N); 1330 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1331 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1332 return I && I->getMetadata("amdgpu.noclobber"); 1333 } 1334 1335 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1336 unsigned DestAS) const { 1337 // Flat -> private/local is a simple truncate. 1338 // Flat -> global is no-op 1339 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1340 return true; 1341 1342 return isNoopAddrSpaceCast(SrcAS, DestAS); 1343 } 1344 1345 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1346 const MemSDNode *MemNode = cast<MemSDNode>(N); 1347 1348 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1349 } 1350 1351 TargetLoweringBase::LegalizeTypeAction 1352 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1353 int NumElts = VT.getVectorNumElements(); 1354 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1355 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1356 return TargetLoweringBase::getPreferredVectorAction(VT); 1357 } 1358 1359 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1360 Type *Ty) const { 1361 // FIXME: Could be smarter if called for vector constants. 1362 return true; 1363 } 1364 1365 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1366 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1367 switch (Op) { 1368 case ISD::LOAD: 1369 case ISD::STORE: 1370 1371 // These operations are done with 32-bit instructions anyway. 1372 case ISD::AND: 1373 case ISD::OR: 1374 case ISD::XOR: 1375 case ISD::SELECT: 1376 // TODO: Extensions? 1377 return true; 1378 default: 1379 return false; 1380 } 1381 } 1382 1383 // SimplifySetCC uses this function to determine whether or not it should 1384 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1385 if (VT == MVT::i1 && Op == ISD::SETCC) 1386 return false; 1387 1388 return TargetLowering::isTypeDesirableForOp(Op, VT); 1389 } 1390 1391 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1392 const SDLoc &SL, 1393 SDValue Chain, 1394 uint64_t Offset) const { 1395 const DataLayout &DL = DAG.getDataLayout(); 1396 MachineFunction &MF = DAG.getMachineFunction(); 1397 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1398 1399 const ArgDescriptor *InputPtrReg; 1400 const TargetRegisterClass *RC; 1401 1402 std::tie(InputPtrReg, RC) 1403 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1404 1405 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1406 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1407 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1408 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1409 1410 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1411 } 1412 1413 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1414 const SDLoc &SL) const { 1415 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1416 FIRST_IMPLICIT); 1417 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1418 } 1419 1420 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1421 const SDLoc &SL, SDValue Val, 1422 bool Signed, 1423 const ISD::InputArg *Arg) const { 1424 // First, if it is a widened vector, narrow it. 1425 if (VT.isVector() && 1426 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1427 EVT NarrowedVT = 1428 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1429 VT.getVectorNumElements()); 1430 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1431 DAG.getConstant(0, SL, MVT::i32)); 1432 } 1433 1434 // Then convert the vector elements or scalar value. 1435 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1436 VT.bitsLT(MemVT)) { 1437 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1438 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1439 } 1440 1441 if (MemVT.isFloatingPoint()) 1442 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT); 1443 else if (Signed) 1444 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1445 else 1446 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1447 1448 return Val; 1449 } 1450 1451 SDValue SITargetLowering::lowerKernargMemParameter( 1452 SelectionDAG &DAG, EVT VT, EVT MemVT, 1453 const SDLoc &SL, SDValue Chain, 1454 uint64_t Offset, unsigned Align, bool Signed, 1455 const ISD::InputArg *Arg) const { 1456 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1457 1458 // Try to avoid using an extload by loading earlier than the argument address, 1459 // and extracting the relevant bits. The load should hopefully be merged with 1460 // the previous argument. 1461 if (MemVT.getStoreSize() < 4 && Align < 4) { 1462 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1463 int64_t AlignDownOffset = alignDown(Offset, 4); 1464 int64_t OffsetDiff = Offset - AlignDownOffset; 1465 1466 EVT IntVT = MemVT.changeTypeToInteger(); 1467 1468 // TODO: If we passed in the base kernel offset we could have a better 1469 // alignment than 4, but we don't really need it. 1470 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1471 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1472 MachineMemOperand::MODereferenceable | 1473 MachineMemOperand::MOInvariant); 1474 1475 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1476 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1477 1478 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1479 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1480 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1481 1482 1483 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1484 } 1485 1486 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1487 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1488 MachineMemOperand::MODereferenceable | 1489 MachineMemOperand::MOInvariant); 1490 1491 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1492 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1493 } 1494 1495 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1496 const SDLoc &SL, SDValue Chain, 1497 const ISD::InputArg &Arg) const { 1498 MachineFunction &MF = DAG.getMachineFunction(); 1499 MachineFrameInfo &MFI = MF.getFrameInfo(); 1500 1501 if (Arg.Flags.isByVal()) { 1502 unsigned Size = Arg.Flags.getByValSize(); 1503 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1504 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1505 } 1506 1507 unsigned ArgOffset = VA.getLocMemOffset(); 1508 unsigned ArgSize = VA.getValVT().getStoreSize(); 1509 1510 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1511 1512 // Create load nodes to retrieve arguments from the stack. 1513 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1514 SDValue ArgValue; 1515 1516 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1517 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1518 MVT MemVT = VA.getValVT(); 1519 1520 switch (VA.getLocInfo()) { 1521 default: 1522 break; 1523 case CCValAssign::BCvt: 1524 MemVT = VA.getLocVT(); 1525 break; 1526 case CCValAssign::SExt: 1527 ExtType = ISD::SEXTLOAD; 1528 break; 1529 case CCValAssign::ZExt: 1530 ExtType = ISD::ZEXTLOAD; 1531 break; 1532 case CCValAssign::AExt: 1533 ExtType = ISD::EXTLOAD; 1534 break; 1535 } 1536 1537 ArgValue = DAG.getExtLoad( 1538 ExtType, SL, VA.getLocVT(), Chain, FIN, 1539 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1540 MemVT); 1541 return ArgValue; 1542 } 1543 1544 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1545 const SIMachineFunctionInfo &MFI, 1546 EVT VT, 1547 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1548 const ArgDescriptor *Reg; 1549 const TargetRegisterClass *RC; 1550 1551 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1552 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1553 } 1554 1555 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1556 CallingConv::ID CallConv, 1557 ArrayRef<ISD::InputArg> Ins, 1558 BitVector &Skipped, 1559 FunctionType *FType, 1560 SIMachineFunctionInfo *Info) { 1561 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1562 const ISD::InputArg *Arg = &Ins[I]; 1563 1564 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1565 "vector type argument should have been split"); 1566 1567 // First check if it's a PS input addr. 1568 if (CallConv == CallingConv::AMDGPU_PS && 1569 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1570 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1571 1572 // Inconveniently only the first part of the split is marked as isSplit, 1573 // so skip to the end. We only want to increment PSInputNum once for the 1574 // entire split argument. 1575 if (Arg->Flags.isSplit()) { 1576 while (!Arg->Flags.isSplitEnd()) { 1577 assert((!Arg->VT.isVector() || 1578 Arg->VT.getScalarSizeInBits() == 16) && 1579 "unexpected vector split in ps argument type"); 1580 if (!SkipArg) 1581 Splits.push_back(*Arg); 1582 Arg = &Ins[++I]; 1583 } 1584 } 1585 1586 if (SkipArg) { 1587 // We can safely skip PS inputs. 1588 Skipped.set(Arg->getOrigArgIndex()); 1589 ++PSInputNum; 1590 continue; 1591 } 1592 1593 Info->markPSInputAllocated(PSInputNum); 1594 if (Arg->Used) 1595 Info->markPSInputEnabled(PSInputNum); 1596 1597 ++PSInputNum; 1598 } 1599 1600 Splits.push_back(*Arg); 1601 } 1602 } 1603 1604 // Allocate special inputs passed in VGPRs. 1605 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1606 MachineFunction &MF, 1607 const SIRegisterInfo &TRI, 1608 SIMachineFunctionInfo &Info) const { 1609 const LLT S32 = LLT::scalar(32); 1610 MachineRegisterInfo &MRI = MF.getRegInfo(); 1611 1612 if (Info.hasWorkItemIDX()) { 1613 Register Reg = AMDGPU::VGPR0; 1614 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1615 1616 CCInfo.AllocateReg(Reg); 1617 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1618 } 1619 1620 if (Info.hasWorkItemIDY()) { 1621 Register Reg = AMDGPU::VGPR1; 1622 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1623 1624 CCInfo.AllocateReg(Reg); 1625 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1626 } 1627 1628 if (Info.hasWorkItemIDZ()) { 1629 Register Reg = AMDGPU::VGPR2; 1630 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1631 1632 CCInfo.AllocateReg(Reg); 1633 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1634 } 1635 } 1636 1637 // Try to allocate a VGPR at the end of the argument list, or if no argument 1638 // VGPRs are left allocating a stack slot. 1639 // If \p Mask is is given it indicates bitfield position in the register. 1640 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1641 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1642 ArgDescriptor Arg = ArgDescriptor()) { 1643 if (Arg.isSet()) 1644 return ArgDescriptor::createArg(Arg, Mask); 1645 1646 ArrayRef<MCPhysReg> ArgVGPRs 1647 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1648 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1649 if (RegIdx == ArgVGPRs.size()) { 1650 // Spill to stack required. 1651 int64_t Offset = CCInfo.AllocateStack(4, 4); 1652 1653 return ArgDescriptor::createStack(Offset, Mask); 1654 } 1655 1656 unsigned Reg = ArgVGPRs[RegIdx]; 1657 Reg = CCInfo.AllocateReg(Reg); 1658 assert(Reg != AMDGPU::NoRegister); 1659 1660 MachineFunction &MF = CCInfo.getMachineFunction(); 1661 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1662 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1663 return ArgDescriptor::createRegister(Reg, Mask); 1664 } 1665 1666 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1667 const TargetRegisterClass *RC, 1668 unsigned NumArgRegs) { 1669 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1670 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1671 if (RegIdx == ArgSGPRs.size()) 1672 report_fatal_error("ran out of SGPRs for arguments"); 1673 1674 unsigned Reg = ArgSGPRs[RegIdx]; 1675 Reg = CCInfo.AllocateReg(Reg); 1676 assert(Reg != AMDGPU::NoRegister); 1677 1678 MachineFunction &MF = CCInfo.getMachineFunction(); 1679 MF.addLiveIn(Reg, RC); 1680 return ArgDescriptor::createRegister(Reg); 1681 } 1682 1683 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1684 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1685 } 1686 1687 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1688 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1689 } 1690 1691 /// Allocate implicit function VGPR arguments at the end of allocated user 1692 /// arguments. 1693 void SITargetLowering::allocateSpecialInputVGPRs( 1694 CCState &CCInfo, MachineFunction &MF, 1695 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1696 const unsigned Mask = 0x3ff; 1697 ArgDescriptor Arg; 1698 1699 if (Info.hasWorkItemIDX()) { 1700 Arg = allocateVGPR32Input(CCInfo, Mask); 1701 Info.setWorkItemIDX(Arg); 1702 } 1703 1704 if (Info.hasWorkItemIDY()) { 1705 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1706 Info.setWorkItemIDY(Arg); 1707 } 1708 1709 if (Info.hasWorkItemIDZ()) 1710 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1711 } 1712 1713 /// Allocate implicit function VGPR arguments in fixed registers. 1714 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1715 CCState &CCInfo, MachineFunction &MF, 1716 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1717 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1718 if (!Reg) 1719 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1720 1721 const unsigned Mask = 0x3ff; 1722 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1723 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1724 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1725 } 1726 1727 void SITargetLowering::allocateSpecialInputSGPRs( 1728 CCState &CCInfo, 1729 MachineFunction &MF, 1730 const SIRegisterInfo &TRI, 1731 SIMachineFunctionInfo &Info) const { 1732 auto &ArgInfo = Info.getArgInfo(); 1733 1734 // TODO: Unify handling with private memory pointers. 1735 1736 if (Info.hasDispatchPtr()) 1737 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1738 1739 if (Info.hasQueuePtr()) 1740 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1741 1742 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1743 // constant offset from the kernarg segment. 1744 if (Info.hasImplicitArgPtr()) 1745 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1746 1747 if (Info.hasDispatchID()) 1748 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1749 1750 // flat_scratch_init is not applicable for non-kernel functions. 1751 1752 if (Info.hasWorkGroupIDX()) 1753 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1754 1755 if (Info.hasWorkGroupIDY()) 1756 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1757 1758 if (Info.hasWorkGroupIDZ()) 1759 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1760 } 1761 1762 // Allocate special inputs passed in user SGPRs. 1763 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1764 MachineFunction &MF, 1765 const SIRegisterInfo &TRI, 1766 SIMachineFunctionInfo &Info) const { 1767 if (Info.hasImplicitBufferPtr()) { 1768 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1769 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1770 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1771 } 1772 1773 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1774 if (Info.hasPrivateSegmentBuffer()) { 1775 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1776 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1777 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1778 } 1779 1780 if (Info.hasDispatchPtr()) { 1781 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1782 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1783 CCInfo.AllocateReg(DispatchPtrReg); 1784 } 1785 1786 if (Info.hasQueuePtr()) { 1787 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1788 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1789 CCInfo.AllocateReg(QueuePtrReg); 1790 } 1791 1792 if (Info.hasKernargSegmentPtr()) { 1793 MachineRegisterInfo &MRI = MF.getRegInfo(); 1794 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1795 CCInfo.AllocateReg(InputPtrReg); 1796 1797 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1798 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1799 } 1800 1801 if (Info.hasDispatchID()) { 1802 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1803 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1804 CCInfo.AllocateReg(DispatchIDReg); 1805 } 1806 1807 if (Info.hasFlatScratchInit()) { 1808 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1809 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1810 CCInfo.AllocateReg(FlatScratchInitReg); 1811 } 1812 1813 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1814 // these from the dispatch pointer. 1815 } 1816 1817 // Allocate special input registers that are initialized per-wave. 1818 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1819 MachineFunction &MF, 1820 SIMachineFunctionInfo &Info, 1821 CallingConv::ID CallConv, 1822 bool IsShader) const { 1823 if (Info.hasWorkGroupIDX()) { 1824 unsigned Reg = Info.addWorkGroupIDX(); 1825 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1826 CCInfo.AllocateReg(Reg); 1827 } 1828 1829 if (Info.hasWorkGroupIDY()) { 1830 unsigned Reg = Info.addWorkGroupIDY(); 1831 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1832 CCInfo.AllocateReg(Reg); 1833 } 1834 1835 if (Info.hasWorkGroupIDZ()) { 1836 unsigned Reg = Info.addWorkGroupIDZ(); 1837 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1838 CCInfo.AllocateReg(Reg); 1839 } 1840 1841 if (Info.hasWorkGroupInfo()) { 1842 unsigned Reg = Info.addWorkGroupInfo(); 1843 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1844 CCInfo.AllocateReg(Reg); 1845 } 1846 1847 if (Info.hasPrivateSegmentWaveByteOffset()) { 1848 // Scratch wave offset passed in system SGPR. 1849 unsigned PrivateSegmentWaveByteOffsetReg; 1850 1851 if (IsShader) { 1852 PrivateSegmentWaveByteOffsetReg = 1853 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1854 1855 // This is true if the scratch wave byte offset doesn't have a fixed 1856 // location. 1857 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1858 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1859 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1860 } 1861 } else 1862 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1863 1864 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1865 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1866 } 1867 } 1868 1869 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1870 MachineFunction &MF, 1871 const SIRegisterInfo &TRI, 1872 SIMachineFunctionInfo &Info) { 1873 // Now that we've figured out where the scratch register inputs are, see if 1874 // should reserve the arguments and use them directly. 1875 MachineFrameInfo &MFI = MF.getFrameInfo(); 1876 bool HasStackObjects = MFI.hasStackObjects(); 1877 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 1878 1879 // Record that we know we have non-spill stack objects so we don't need to 1880 // check all stack objects later. 1881 if (HasStackObjects) 1882 Info.setHasNonSpillStackObjects(true); 1883 1884 // Everything live out of a block is spilled with fast regalloc, so it's 1885 // almost certain that spilling will be required. 1886 if (TM.getOptLevel() == CodeGenOpt::None) 1887 HasStackObjects = true; 1888 1889 // For now assume stack access is needed in any callee functions, so we need 1890 // the scratch registers to pass in. 1891 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1892 1893 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 1894 // If we have stack objects, we unquestionably need the private buffer 1895 // resource. For the Code Object V2 ABI, this will be the first 4 user 1896 // SGPR inputs. We can reserve those and use them directly. 1897 1898 Register PrivateSegmentBufferReg = 1899 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 1900 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1901 } else { 1902 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1903 // We tentatively reserve the last registers (skipping the last registers 1904 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 1905 // we'll replace these with the ones immediately after those which were 1906 // really allocated. In the prologue copies will be inserted from the 1907 // argument to these reserved registers. 1908 1909 // Without HSA, relocations are used for the scratch pointer and the 1910 // buffer resource setup is always inserted in the prologue. Scratch wave 1911 // offset is still in an input SGPR. 1912 Info.setScratchRSrcReg(ReservedBufferReg); 1913 } 1914 1915 MachineRegisterInfo &MRI = MF.getRegInfo(); 1916 1917 // For entry functions we have to set up the stack pointer if we use it, 1918 // whereas non-entry functions get this "for free". This means there is no 1919 // intrinsic advantage to using S32 over S34 in cases where we do not have 1920 // calls but do need a frame pointer (i.e. if we are requested to have one 1921 // because frame pointer elimination is disabled). To keep things simple we 1922 // only ever use S32 as the call ABI stack pointer, and so using it does not 1923 // imply we need a separate frame pointer. 1924 // 1925 // Try to use s32 as the SP, but move it if it would interfere with input 1926 // arguments. This won't work with calls though. 1927 // 1928 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 1929 // registers. 1930 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 1931 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 1932 } else { 1933 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 1934 1935 if (MFI.hasCalls()) 1936 report_fatal_error("call in graphics shader with too many input SGPRs"); 1937 1938 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 1939 if (!MRI.isLiveIn(Reg)) { 1940 Info.setStackPtrOffsetReg(Reg); 1941 break; 1942 } 1943 } 1944 1945 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 1946 report_fatal_error("failed to find register for SP"); 1947 } 1948 1949 // hasFP should be accurate for entry functions even before the frame is 1950 // finalized, because it does not rely on the known stack size, only 1951 // properties like whether variable sized objects are present. 1952 if (ST.getFrameLowering()->hasFP(MF)) { 1953 Info.setFrameOffsetReg(AMDGPU::SGPR33); 1954 } 1955 } 1956 1957 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 1958 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 1959 return !Info->isEntryFunction(); 1960 } 1961 1962 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 1963 1964 } 1965 1966 void SITargetLowering::insertCopiesSplitCSR( 1967 MachineBasicBlock *Entry, 1968 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 1969 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1970 1971 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 1972 if (!IStart) 1973 return; 1974 1975 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1976 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 1977 MachineBasicBlock::iterator MBBI = Entry->begin(); 1978 for (const MCPhysReg *I = IStart; *I; ++I) { 1979 const TargetRegisterClass *RC = nullptr; 1980 if (AMDGPU::SReg_64RegClass.contains(*I)) 1981 RC = &AMDGPU::SGPR_64RegClass; 1982 else if (AMDGPU::SReg_32RegClass.contains(*I)) 1983 RC = &AMDGPU::SGPR_32RegClass; 1984 else 1985 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 1986 1987 Register NewVR = MRI->createVirtualRegister(RC); 1988 // Create copy from CSR to a virtual register. 1989 Entry->addLiveIn(*I); 1990 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 1991 .addReg(*I); 1992 1993 // Insert the copy-back instructions right before the terminator. 1994 for (auto *Exit : Exits) 1995 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 1996 TII->get(TargetOpcode::COPY), *I) 1997 .addReg(NewVR); 1998 } 1999 } 2000 2001 SDValue SITargetLowering::LowerFormalArguments( 2002 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2003 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2004 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2005 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2006 2007 MachineFunction &MF = DAG.getMachineFunction(); 2008 const Function &Fn = MF.getFunction(); 2009 FunctionType *FType = MF.getFunction().getFunctionType(); 2010 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2011 2012 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2013 DiagnosticInfoUnsupported NoGraphicsHSA( 2014 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2015 DAG.getContext()->diagnose(NoGraphicsHSA); 2016 return DAG.getEntryNode(); 2017 } 2018 2019 SmallVector<ISD::InputArg, 16> Splits; 2020 SmallVector<CCValAssign, 16> ArgLocs; 2021 BitVector Skipped(Ins.size()); 2022 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2023 *DAG.getContext()); 2024 2025 bool IsShader = AMDGPU::isShader(CallConv); 2026 bool IsKernel = AMDGPU::isKernel(CallConv); 2027 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2028 2029 if (IsShader) { 2030 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2031 2032 // At least one interpolation mode must be enabled or else the GPU will 2033 // hang. 2034 // 2035 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2036 // set PSInputAddr, the user wants to enable some bits after the compilation 2037 // based on run-time states. Since we can't know what the final PSInputEna 2038 // will look like, so we shouldn't do anything here and the user should take 2039 // responsibility for the correct programming. 2040 // 2041 // Otherwise, the following restrictions apply: 2042 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2043 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2044 // enabled too. 2045 if (CallConv == CallingConv::AMDGPU_PS) { 2046 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2047 ((Info->getPSInputAddr() & 0xF) == 0 && 2048 Info->isPSInputAllocated(11))) { 2049 CCInfo.AllocateReg(AMDGPU::VGPR0); 2050 CCInfo.AllocateReg(AMDGPU::VGPR1); 2051 Info->markPSInputAllocated(0); 2052 Info->markPSInputEnabled(0); 2053 } 2054 if (Subtarget->isAmdPalOS()) { 2055 // For isAmdPalOS, the user does not enable some bits after compilation 2056 // based on run-time states; the register values being generated here are 2057 // the final ones set in hardware. Therefore we need to apply the 2058 // workaround to PSInputAddr and PSInputEnable together. (The case where 2059 // a bit is set in PSInputAddr but not PSInputEnable is where the 2060 // frontend set up an input arg for a particular interpolation mode, but 2061 // nothing uses that input arg. Really we should have an earlier pass 2062 // that removes such an arg.) 2063 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2064 if ((PsInputBits & 0x7F) == 0 || 2065 ((PsInputBits & 0xF) == 0 && 2066 (PsInputBits >> 11 & 1))) 2067 Info->markPSInputEnabled( 2068 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2069 } 2070 } 2071 2072 assert(!Info->hasDispatchPtr() && 2073 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2074 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2075 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2076 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2077 !Info->hasWorkItemIDZ()); 2078 } else if (IsKernel) { 2079 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2080 } else { 2081 Splits.append(Ins.begin(), Ins.end()); 2082 } 2083 2084 if (IsEntryFunc) { 2085 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2086 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2087 } else { 2088 // For the fixed ABI, pass workitem IDs in the last argument register. 2089 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2090 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2091 } 2092 2093 if (IsKernel) { 2094 analyzeFormalArgumentsCompute(CCInfo, Ins); 2095 } else { 2096 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2097 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2098 } 2099 2100 SmallVector<SDValue, 16> Chains; 2101 2102 // FIXME: This is the minimum kernel argument alignment. We should improve 2103 // this to the maximum alignment of the arguments. 2104 // 2105 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2106 // kern arg offset. 2107 const unsigned KernelArgBaseAlign = 16; 2108 2109 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2110 const ISD::InputArg &Arg = Ins[i]; 2111 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2112 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2113 continue; 2114 } 2115 2116 CCValAssign &VA = ArgLocs[ArgIdx++]; 2117 MVT VT = VA.getLocVT(); 2118 2119 if (IsEntryFunc && VA.isMemLoc()) { 2120 VT = Ins[i].VT; 2121 EVT MemVT = VA.getLocVT(); 2122 2123 const uint64_t Offset = VA.getLocMemOffset(); 2124 unsigned Align = MinAlign(KernelArgBaseAlign, Offset); 2125 2126 SDValue Arg = lowerKernargMemParameter( 2127 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]); 2128 Chains.push_back(Arg.getValue(1)); 2129 2130 auto *ParamTy = 2131 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2132 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2133 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2134 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2135 // On SI local pointers are just offsets into LDS, so they are always 2136 // less than 16-bits. On CI and newer they could potentially be 2137 // real pointers, so we can't guarantee their size. 2138 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2139 DAG.getValueType(MVT::i16)); 2140 } 2141 2142 InVals.push_back(Arg); 2143 continue; 2144 } else if (!IsEntryFunc && VA.isMemLoc()) { 2145 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2146 InVals.push_back(Val); 2147 if (!Arg.Flags.isByVal()) 2148 Chains.push_back(Val.getValue(1)); 2149 continue; 2150 } 2151 2152 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2153 2154 Register Reg = VA.getLocReg(); 2155 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2156 EVT ValVT = VA.getValVT(); 2157 2158 Reg = MF.addLiveIn(Reg, RC); 2159 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2160 2161 if (Arg.Flags.isSRet()) { 2162 // The return object should be reasonably addressable. 2163 2164 // FIXME: This helps when the return is a real sret. If it is a 2165 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2166 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2167 unsigned NumBits 2168 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2169 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2170 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2171 } 2172 2173 // If this is an 8 or 16-bit value, it is really passed promoted 2174 // to 32 bits. Insert an assert[sz]ext to capture this, then 2175 // truncate to the right size. 2176 switch (VA.getLocInfo()) { 2177 case CCValAssign::Full: 2178 break; 2179 case CCValAssign::BCvt: 2180 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2181 break; 2182 case CCValAssign::SExt: 2183 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2184 DAG.getValueType(ValVT)); 2185 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2186 break; 2187 case CCValAssign::ZExt: 2188 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2189 DAG.getValueType(ValVT)); 2190 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2191 break; 2192 case CCValAssign::AExt: 2193 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2194 break; 2195 default: 2196 llvm_unreachable("Unknown loc info!"); 2197 } 2198 2199 InVals.push_back(Val); 2200 } 2201 2202 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2203 // Special inputs come after user arguments. 2204 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2205 } 2206 2207 // Start adding system SGPRs. 2208 if (IsEntryFunc) { 2209 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2210 } else { 2211 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2212 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2213 } 2214 2215 auto &ArgUsageInfo = 2216 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2217 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2218 2219 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2220 Info->setBytesInStackArgArea(StackArgSize); 2221 2222 return Chains.empty() ? Chain : 2223 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2224 } 2225 2226 // TODO: If return values can't fit in registers, we should return as many as 2227 // possible in registers before passing on stack. 2228 bool SITargetLowering::CanLowerReturn( 2229 CallingConv::ID CallConv, 2230 MachineFunction &MF, bool IsVarArg, 2231 const SmallVectorImpl<ISD::OutputArg> &Outs, 2232 LLVMContext &Context) const { 2233 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2234 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2235 // for shaders. Vector types should be explicitly handled by CC. 2236 if (AMDGPU::isEntryFunctionCC(CallConv)) 2237 return true; 2238 2239 SmallVector<CCValAssign, 16> RVLocs; 2240 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2241 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2242 } 2243 2244 SDValue 2245 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2246 bool isVarArg, 2247 const SmallVectorImpl<ISD::OutputArg> &Outs, 2248 const SmallVectorImpl<SDValue> &OutVals, 2249 const SDLoc &DL, SelectionDAG &DAG) const { 2250 MachineFunction &MF = DAG.getMachineFunction(); 2251 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2252 2253 if (AMDGPU::isKernel(CallConv)) { 2254 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2255 OutVals, DL, DAG); 2256 } 2257 2258 bool IsShader = AMDGPU::isShader(CallConv); 2259 2260 Info->setIfReturnsVoid(Outs.empty()); 2261 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2262 2263 // CCValAssign - represent the assignment of the return value to a location. 2264 SmallVector<CCValAssign, 48> RVLocs; 2265 SmallVector<ISD::OutputArg, 48> Splits; 2266 2267 // CCState - Info about the registers and stack slots. 2268 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2269 *DAG.getContext()); 2270 2271 // Analyze outgoing return values. 2272 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2273 2274 SDValue Flag; 2275 SmallVector<SDValue, 48> RetOps; 2276 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2277 2278 // Add return address for callable functions. 2279 if (!Info->isEntryFunction()) { 2280 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2281 SDValue ReturnAddrReg = CreateLiveInRegister( 2282 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2283 2284 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2285 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2286 MVT::i64); 2287 Chain = 2288 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2289 Flag = Chain.getValue(1); 2290 RetOps.push_back(ReturnAddrVirtualReg); 2291 } 2292 2293 // Copy the result values into the output registers. 2294 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2295 ++I, ++RealRVLocIdx) { 2296 CCValAssign &VA = RVLocs[I]; 2297 assert(VA.isRegLoc() && "Can only return in registers!"); 2298 // TODO: Partially return in registers if return values don't fit. 2299 SDValue Arg = OutVals[RealRVLocIdx]; 2300 2301 // Copied from other backends. 2302 switch (VA.getLocInfo()) { 2303 case CCValAssign::Full: 2304 break; 2305 case CCValAssign::BCvt: 2306 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2307 break; 2308 case CCValAssign::SExt: 2309 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2310 break; 2311 case CCValAssign::ZExt: 2312 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2313 break; 2314 case CCValAssign::AExt: 2315 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2316 break; 2317 default: 2318 llvm_unreachable("Unknown loc info!"); 2319 } 2320 2321 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2322 Flag = Chain.getValue(1); 2323 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2324 } 2325 2326 // FIXME: Does sret work properly? 2327 if (!Info->isEntryFunction()) { 2328 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2329 const MCPhysReg *I = 2330 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2331 if (I) { 2332 for (; *I; ++I) { 2333 if (AMDGPU::SReg_64RegClass.contains(*I)) 2334 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2335 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2336 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2337 else 2338 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2339 } 2340 } 2341 } 2342 2343 // Update chain and glue. 2344 RetOps[0] = Chain; 2345 if (Flag.getNode()) 2346 RetOps.push_back(Flag); 2347 2348 unsigned Opc = AMDGPUISD::ENDPGM; 2349 if (!IsWaveEnd) 2350 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2351 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2352 } 2353 2354 SDValue SITargetLowering::LowerCallResult( 2355 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2356 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2357 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2358 SDValue ThisVal) const { 2359 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2360 2361 // Assign locations to each value returned by this call. 2362 SmallVector<CCValAssign, 16> RVLocs; 2363 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2364 *DAG.getContext()); 2365 CCInfo.AnalyzeCallResult(Ins, RetCC); 2366 2367 // Copy all of the result registers out of their specified physreg. 2368 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2369 CCValAssign VA = RVLocs[i]; 2370 SDValue Val; 2371 2372 if (VA.isRegLoc()) { 2373 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2374 Chain = Val.getValue(1); 2375 InFlag = Val.getValue(2); 2376 } else if (VA.isMemLoc()) { 2377 report_fatal_error("TODO: return values in memory"); 2378 } else 2379 llvm_unreachable("unknown argument location type"); 2380 2381 switch (VA.getLocInfo()) { 2382 case CCValAssign::Full: 2383 break; 2384 case CCValAssign::BCvt: 2385 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2386 break; 2387 case CCValAssign::ZExt: 2388 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2389 DAG.getValueType(VA.getValVT())); 2390 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2391 break; 2392 case CCValAssign::SExt: 2393 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2394 DAG.getValueType(VA.getValVT())); 2395 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2396 break; 2397 case CCValAssign::AExt: 2398 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2399 break; 2400 default: 2401 llvm_unreachable("Unknown loc info!"); 2402 } 2403 2404 InVals.push_back(Val); 2405 } 2406 2407 return Chain; 2408 } 2409 2410 // Add code to pass special inputs required depending on used features separate 2411 // from the explicit user arguments present in the IR. 2412 void SITargetLowering::passSpecialInputs( 2413 CallLoweringInfo &CLI, 2414 CCState &CCInfo, 2415 const SIMachineFunctionInfo &Info, 2416 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2417 SmallVectorImpl<SDValue> &MemOpChains, 2418 SDValue Chain) const { 2419 // If we don't have a call site, this was a call inserted by 2420 // legalization. These can never use special inputs. 2421 if (!CLI.CS) 2422 return; 2423 2424 SelectionDAG &DAG = CLI.DAG; 2425 const SDLoc &DL = CLI.DL; 2426 2427 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2428 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2429 2430 const AMDGPUFunctionArgInfo *CalleeArgInfo 2431 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2432 if (const Function *CalleeFunc = CLI.CS.getCalledFunction()) { 2433 auto &ArgUsageInfo = 2434 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2435 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2436 } 2437 2438 // TODO: Unify with private memory register handling. This is complicated by 2439 // the fact that at least in kernels, the input argument is not necessarily 2440 // in the same location as the input. 2441 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2442 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2443 AMDGPUFunctionArgInfo::QUEUE_PTR, 2444 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2445 AMDGPUFunctionArgInfo::DISPATCH_ID, 2446 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2447 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2448 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2449 }; 2450 2451 for (auto InputID : InputRegs) { 2452 const ArgDescriptor *OutgoingArg; 2453 const TargetRegisterClass *ArgRC; 2454 2455 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID); 2456 if (!OutgoingArg) 2457 continue; 2458 2459 const ArgDescriptor *IncomingArg; 2460 const TargetRegisterClass *IncomingArgRC; 2461 std::tie(IncomingArg, IncomingArgRC) 2462 = CallerArgInfo.getPreloadedValue(InputID); 2463 assert(IncomingArgRC == ArgRC); 2464 2465 // All special arguments are ints for now. 2466 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2467 SDValue InputReg; 2468 2469 if (IncomingArg) { 2470 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2471 } else { 2472 // The implicit arg ptr is special because it doesn't have a corresponding 2473 // input for kernels, and is computed from the kernarg segment pointer. 2474 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2475 InputReg = getImplicitArgPtr(DAG, DL); 2476 } 2477 2478 if (OutgoingArg->isRegister()) { 2479 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2480 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2481 report_fatal_error("failed to allocate implicit input argument"); 2482 } else { 2483 unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4); 2484 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2485 SpecialArgOffset); 2486 MemOpChains.push_back(ArgStore); 2487 } 2488 } 2489 2490 // Pack workitem IDs into a single register or pass it as is if already 2491 // packed. 2492 const ArgDescriptor *OutgoingArg; 2493 const TargetRegisterClass *ArgRC; 2494 2495 std::tie(OutgoingArg, ArgRC) = 2496 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2497 if (!OutgoingArg) 2498 std::tie(OutgoingArg, ArgRC) = 2499 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2500 if (!OutgoingArg) 2501 std::tie(OutgoingArg, ArgRC) = 2502 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2503 if (!OutgoingArg) 2504 return; 2505 2506 const ArgDescriptor *IncomingArgX 2507 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first; 2508 const ArgDescriptor *IncomingArgY 2509 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first; 2510 const ArgDescriptor *IncomingArgZ 2511 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first; 2512 2513 SDValue InputReg; 2514 SDLoc SL; 2515 2516 // If incoming ids are not packed we need to pack them. 2517 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2518 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2519 2520 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2521 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2522 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2523 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2524 InputReg = InputReg.getNode() ? 2525 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2526 } 2527 2528 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2529 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2530 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2531 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2532 InputReg = InputReg.getNode() ? 2533 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2534 } 2535 2536 if (!InputReg.getNode()) { 2537 // Workitem ids are already packed, any of present incoming arguments 2538 // will carry all required fields. 2539 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2540 IncomingArgX ? *IncomingArgX : 2541 IncomingArgY ? *IncomingArgY : 2542 *IncomingArgZ, ~0u); 2543 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2544 } 2545 2546 if (OutgoingArg->isRegister()) { 2547 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2548 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2549 } else { 2550 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4); 2551 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2552 SpecialArgOffset); 2553 MemOpChains.push_back(ArgStore); 2554 } 2555 } 2556 2557 static bool canGuaranteeTCO(CallingConv::ID CC) { 2558 return CC == CallingConv::Fast; 2559 } 2560 2561 /// Return true if we might ever do TCO for calls with this calling convention. 2562 static bool mayTailCallThisCC(CallingConv::ID CC) { 2563 switch (CC) { 2564 case CallingConv::C: 2565 return true; 2566 default: 2567 return canGuaranteeTCO(CC); 2568 } 2569 } 2570 2571 bool SITargetLowering::isEligibleForTailCallOptimization( 2572 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2573 const SmallVectorImpl<ISD::OutputArg> &Outs, 2574 const SmallVectorImpl<SDValue> &OutVals, 2575 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2576 if (!mayTailCallThisCC(CalleeCC)) 2577 return false; 2578 2579 MachineFunction &MF = DAG.getMachineFunction(); 2580 const Function &CallerF = MF.getFunction(); 2581 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2582 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2583 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2584 2585 // Kernels aren't callable, and don't have a live in return address so it 2586 // doesn't make sense to do a tail call with entry functions. 2587 if (!CallerPreserved) 2588 return false; 2589 2590 bool CCMatch = CallerCC == CalleeCC; 2591 2592 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2593 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2594 return true; 2595 return false; 2596 } 2597 2598 // TODO: Can we handle var args? 2599 if (IsVarArg) 2600 return false; 2601 2602 for (const Argument &Arg : CallerF.args()) { 2603 if (Arg.hasByValAttr()) 2604 return false; 2605 } 2606 2607 LLVMContext &Ctx = *DAG.getContext(); 2608 2609 // Check that the call results are passed in the same way. 2610 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2611 CCAssignFnForCall(CalleeCC, IsVarArg), 2612 CCAssignFnForCall(CallerCC, IsVarArg))) 2613 return false; 2614 2615 // The callee has to preserve all registers the caller needs to preserve. 2616 if (!CCMatch) { 2617 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2618 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2619 return false; 2620 } 2621 2622 // Nothing more to check if the callee is taking no arguments. 2623 if (Outs.empty()) 2624 return true; 2625 2626 SmallVector<CCValAssign, 16> ArgLocs; 2627 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2628 2629 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2630 2631 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2632 // If the stack arguments for this call do not fit into our own save area then 2633 // the call cannot be made tail. 2634 // TODO: Is this really necessary? 2635 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2636 return false; 2637 2638 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2639 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2640 } 2641 2642 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2643 if (!CI->isTailCall()) 2644 return false; 2645 2646 const Function *ParentFn = CI->getParent()->getParent(); 2647 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2648 return false; 2649 return true; 2650 } 2651 2652 // The wave scratch offset register is used as the global base pointer. 2653 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2654 SmallVectorImpl<SDValue> &InVals) const { 2655 SelectionDAG &DAG = CLI.DAG; 2656 const SDLoc &DL = CLI.DL; 2657 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2658 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2659 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2660 SDValue Chain = CLI.Chain; 2661 SDValue Callee = CLI.Callee; 2662 bool &IsTailCall = CLI.IsTailCall; 2663 CallingConv::ID CallConv = CLI.CallConv; 2664 bool IsVarArg = CLI.IsVarArg; 2665 bool IsSibCall = false; 2666 bool IsThisReturn = false; 2667 MachineFunction &MF = DAG.getMachineFunction(); 2668 2669 if (Callee.isUndef() || isNullConstant(Callee)) { 2670 if (!CLI.IsTailCall) { 2671 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2672 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2673 } 2674 2675 return Chain; 2676 } 2677 2678 if (IsVarArg) { 2679 return lowerUnhandledCall(CLI, InVals, 2680 "unsupported call to variadic function "); 2681 } 2682 2683 if (!CLI.CS.getInstruction()) 2684 report_fatal_error("unsupported libcall legalization"); 2685 2686 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && !CLI.CS.getCalledFunction()) { 2687 return lowerUnhandledCall(CLI, InVals, 2688 "unsupported indirect call to function "); 2689 } 2690 2691 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2692 return lowerUnhandledCall(CLI, InVals, 2693 "unsupported required tail call to function "); 2694 } 2695 2696 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2697 // Note the issue is with the CC of the calling function, not of the call 2698 // itself. 2699 return lowerUnhandledCall(CLI, InVals, 2700 "unsupported call from graphics shader of function "); 2701 } 2702 2703 if (IsTailCall) { 2704 IsTailCall = isEligibleForTailCallOptimization( 2705 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2706 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) { 2707 report_fatal_error("failed to perform tail call elimination on a call " 2708 "site marked musttail"); 2709 } 2710 2711 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2712 2713 // A sibling call is one where we're under the usual C ABI and not planning 2714 // to change that but can still do a tail call: 2715 if (!TailCallOpt && IsTailCall) 2716 IsSibCall = true; 2717 2718 if (IsTailCall) 2719 ++NumTailCalls; 2720 } 2721 2722 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2723 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2724 SmallVector<SDValue, 8> MemOpChains; 2725 2726 // Analyze operands of the call, assigning locations to each operand. 2727 SmallVector<CCValAssign, 16> ArgLocs; 2728 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2729 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2730 2731 if (AMDGPUTargetMachine::EnableFixedFunctionABI) { 2732 // With a fixed ABI, allocate fixed registers before user arguments. 2733 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2734 } 2735 2736 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2737 2738 // Get a count of how many bytes are to be pushed on the stack. 2739 unsigned NumBytes = CCInfo.getNextStackOffset(); 2740 2741 if (IsSibCall) { 2742 // Since we're not changing the ABI to make this a tail call, the memory 2743 // operands are already available in the caller's incoming argument space. 2744 NumBytes = 0; 2745 } 2746 2747 // FPDiff is the byte offset of the call's argument area from the callee's. 2748 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2749 // by this amount for a tail call. In a sibling call it must be 0 because the 2750 // caller will deallocate the entire stack and the callee still expects its 2751 // arguments to begin at SP+0. Completely unused for non-tail calls. 2752 int32_t FPDiff = 0; 2753 MachineFrameInfo &MFI = MF.getFrameInfo(); 2754 2755 // Adjust the stack pointer for the new arguments... 2756 // These operations are automatically eliminated by the prolog/epilog pass 2757 if (!IsSibCall) { 2758 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2759 2760 SmallVector<SDValue, 4> CopyFromChains; 2761 2762 // In the HSA case, this should be an identity copy. 2763 SDValue ScratchRSrcReg 2764 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2765 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2766 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2767 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2768 } 2769 2770 MVT PtrVT = MVT::i32; 2771 2772 // Walk the register/memloc assignments, inserting copies/loads. 2773 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2774 CCValAssign &VA = ArgLocs[i]; 2775 SDValue Arg = OutVals[i]; 2776 2777 // Promote the value if needed. 2778 switch (VA.getLocInfo()) { 2779 case CCValAssign::Full: 2780 break; 2781 case CCValAssign::BCvt: 2782 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2783 break; 2784 case CCValAssign::ZExt: 2785 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2786 break; 2787 case CCValAssign::SExt: 2788 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2789 break; 2790 case CCValAssign::AExt: 2791 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2792 break; 2793 case CCValAssign::FPExt: 2794 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2795 break; 2796 default: 2797 llvm_unreachable("Unknown loc info!"); 2798 } 2799 2800 if (VA.isRegLoc()) { 2801 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2802 } else { 2803 assert(VA.isMemLoc()); 2804 2805 SDValue DstAddr; 2806 MachinePointerInfo DstInfo; 2807 2808 unsigned LocMemOffset = VA.getLocMemOffset(); 2809 int32_t Offset = LocMemOffset; 2810 2811 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2812 MaybeAlign Alignment; 2813 2814 if (IsTailCall) { 2815 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2816 unsigned OpSize = Flags.isByVal() ? 2817 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2818 2819 // FIXME: We can have better than the minimum byval required alignment. 2820 Alignment = 2821 Flags.isByVal() 2822 ? Flags.getNonZeroByValAlign() 2823 : commonAlignment(Subtarget->getStackAlignment(), Offset); 2824 2825 Offset = Offset + FPDiff; 2826 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2827 2828 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2829 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2830 2831 // Make sure any stack arguments overlapping with where we're storing 2832 // are loaded before this eventual operation. Otherwise they'll be 2833 // clobbered. 2834 2835 // FIXME: Why is this really necessary? This seems to just result in a 2836 // lot of code to copy the stack and write them back to the same 2837 // locations, which are supposed to be immutable? 2838 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2839 } else { 2840 DstAddr = PtrOff; 2841 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2842 Alignment = 2843 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 2844 } 2845 2846 if (Outs[i].Flags.isByVal()) { 2847 SDValue SizeNode = 2848 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2849 SDValue Cpy = 2850 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 2851 Outs[i].Flags.getNonZeroByValAlign(), 2852 /*isVol = */ false, /*AlwaysInline = */ true, 2853 /*isTailCall = */ false, DstInfo, 2854 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 2855 2856 MemOpChains.push_back(Cpy); 2857 } else { 2858 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 2859 Alignment ? Alignment->value() : 0); 2860 MemOpChains.push_back(Store); 2861 } 2862 } 2863 } 2864 2865 if (!AMDGPUTargetMachine::EnableFixedFunctionABI) { 2866 // Copy special input registers after user input arguments. 2867 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2868 } 2869 2870 if (!MemOpChains.empty()) 2871 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2872 2873 // Build a sequence of copy-to-reg nodes chained together with token chain 2874 // and flag operands which copy the outgoing args into the appropriate regs. 2875 SDValue InFlag; 2876 for (auto &RegToPass : RegsToPass) { 2877 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2878 RegToPass.second, InFlag); 2879 InFlag = Chain.getValue(1); 2880 } 2881 2882 2883 SDValue PhysReturnAddrReg; 2884 if (IsTailCall) { 2885 // Since the return is being combined with the call, we need to pass on the 2886 // return address. 2887 2888 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2889 SDValue ReturnAddrReg = CreateLiveInRegister( 2890 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2891 2892 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2893 MVT::i64); 2894 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2895 InFlag = Chain.getValue(1); 2896 } 2897 2898 // We don't usually want to end the call-sequence here because we would tidy 2899 // the frame up *after* the call, however in the ABI-changing tail-call case 2900 // we've carefully laid out the parameters so that when sp is reset they'll be 2901 // in the correct location. 2902 if (IsTailCall && !IsSibCall) { 2903 Chain = DAG.getCALLSEQ_END(Chain, 2904 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2905 DAG.getTargetConstant(0, DL, MVT::i32), 2906 InFlag, DL); 2907 InFlag = Chain.getValue(1); 2908 } 2909 2910 std::vector<SDValue> Ops; 2911 Ops.push_back(Chain); 2912 Ops.push_back(Callee); 2913 // Add a redundant copy of the callee global which will not be legalized, as 2914 // we need direct access to the callee later. 2915 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 2916 const GlobalValue *GV = GSD->getGlobal(); 2917 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 2918 } else { 2919 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 2920 } 2921 2922 if (IsTailCall) { 2923 // Each tail call may have to adjust the stack by a different amount, so 2924 // this information must travel along with the operation for eventual 2925 // consumption by emitEpilogue. 2926 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 2927 2928 Ops.push_back(PhysReturnAddrReg); 2929 } 2930 2931 // Add argument registers to the end of the list so that they are known live 2932 // into the call. 2933 for (auto &RegToPass : RegsToPass) { 2934 Ops.push_back(DAG.getRegister(RegToPass.first, 2935 RegToPass.second.getValueType())); 2936 } 2937 2938 // Add a register mask operand representing the call-preserved registers. 2939 2940 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 2941 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2942 assert(Mask && "Missing call preserved mask for calling convention"); 2943 Ops.push_back(DAG.getRegisterMask(Mask)); 2944 2945 if (InFlag.getNode()) 2946 Ops.push_back(InFlag); 2947 2948 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2949 2950 // If we're doing a tall call, use a TC_RETURN here rather than an 2951 // actual call instruction. 2952 if (IsTailCall) { 2953 MFI.setHasTailCall(); 2954 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 2955 } 2956 2957 // Returns a chain and a flag for retval copy to use. 2958 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 2959 Chain = Call.getValue(0); 2960 InFlag = Call.getValue(1); 2961 2962 uint64_t CalleePopBytes = NumBytes; 2963 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 2964 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 2965 InFlag, DL); 2966 if (!Ins.empty()) 2967 InFlag = Chain.getValue(1); 2968 2969 // Handle result values, copying them out of physregs into vregs that we 2970 // return. 2971 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 2972 InVals, IsThisReturn, 2973 IsThisReturn ? OutVals[0] : SDValue()); 2974 } 2975 2976 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 2977 const MachineFunction &MF) const { 2978 Register Reg = StringSwitch<Register>(RegName) 2979 .Case("m0", AMDGPU::M0) 2980 .Case("exec", AMDGPU::EXEC) 2981 .Case("exec_lo", AMDGPU::EXEC_LO) 2982 .Case("exec_hi", AMDGPU::EXEC_HI) 2983 .Case("flat_scratch", AMDGPU::FLAT_SCR) 2984 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 2985 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 2986 .Default(Register()); 2987 2988 if (Reg == AMDGPU::NoRegister) { 2989 report_fatal_error(Twine("invalid register name \"" 2990 + StringRef(RegName) + "\".")); 2991 2992 } 2993 2994 if (!Subtarget->hasFlatScrRegister() && 2995 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 2996 report_fatal_error(Twine("invalid register \"" 2997 + StringRef(RegName) + "\" for subtarget.")); 2998 } 2999 3000 switch (Reg) { 3001 case AMDGPU::M0: 3002 case AMDGPU::EXEC_LO: 3003 case AMDGPU::EXEC_HI: 3004 case AMDGPU::FLAT_SCR_LO: 3005 case AMDGPU::FLAT_SCR_HI: 3006 if (VT.getSizeInBits() == 32) 3007 return Reg; 3008 break; 3009 case AMDGPU::EXEC: 3010 case AMDGPU::FLAT_SCR: 3011 if (VT.getSizeInBits() == 64) 3012 return Reg; 3013 break; 3014 default: 3015 llvm_unreachable("missing register type checking"); 3016 } 3017 3018 report_fatal_error(Twine("invalid type for register \"" 3019 + StringRef(RegName) + "\".")); 3020 } 3021 3022 // If kill is not the last instruction, split the block so kill is always a 3023 // proper terminator. 3024 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3025 MachineBasicBlock *BB) const { 3026 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3027 3028 MachineBasicBlock::iterator SplitPoint(&MI); 3029 ++SplitPoint; 3030 3031 if (SplitPoint == BB->end()) { 3032 // Don't bother with a new block. 3033 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3034 return BB; 3035 } 3036 3037 MachineFunction *MF = BB->getParent(); 3038 MachineBasicBlock *SplitBB 3039 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3040 3041 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3042 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3043 3044 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3045 BB->addSuccessor(SplitBB); 3046 3047 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3048 return SplitBB; 3049 } 3050 3051 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3052 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3053 // be the first instruction in the remainder block. 3054 // 3055 /// \returns { LoopBody, Remainder } 3056 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3057 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3058 MachineFunction *MF = MBB.getParent(); 3059 MachineBasicBlock::iterator I(&MI); 3060 3061 // To insert the loop we need to split the block. Move everything after this 3062 // point to a new block, and insert a new empty block between the two. 3063 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3064 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3065 MachineFunction::iterator MBBI(MBB); 3066 ++MBBI; 3067 3068 MF->insert(MBBI, LoopBB); 3069 MF->insert(MBBI, RemainderBB); 3070 3071 LoopBB->addSuccessor(LoopBB); 3072 LoopBB->addSuccessor(RemainderBB); 3073 3074 // Move the rest of the block into a new block. 3075 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3076 3077 if (InstInLoop) { 3078 auto Next = std::next(I); 3079 3080 // Move instruction to loop body. 3081 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3082 3083 // Move the rest of the block. 3084 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3085 } else { 3086 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3087 } 3088 3089 MBB.addSuccessor(LoopBB); 3090 3091 return std::make_pair(LoopBB, RemainderBB); 3092 } 3093 3094 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3095 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3096 MachineBasicBlock *MBB = MI.getParent(); 3097 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3098 auto I = MI.getIterator(); 3099 auto E = std::next(I); 3100 3101 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3102 .addImm(0); 3103 3104 MIBundleBuilder Bundler(*MBB, I, E); 3105 finalizeBundle(*MBB, Bundler.begin()); 3106 } 3107 3108 MachineBasicBlock * 3109 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3110 MachineBasicBlock *BB) const { 3111 const DebugLoc &DL = MI.getDebugLoc(); 3112 3113 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3114 3115 MachineBasicBlock *LoopBB; 3116 MachineBasicBlock *RemainderBB; 3117 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3118 3119 // Apparently kill flags are only valid if the def is in the same block? 3120 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3121 Src->setIsKill(false); 3122 3123 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3124 3125 MachineBasicBlock::iterator I = LoopBB->end(); 3126 3127 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3128 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3129 3130 // Clear TRAP_STS.MEM_VIOL 3131 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3132 .addImm(0) 3133 .addImm(EncodedReg); 3134 3135 bundleInstWithWaitcnt(MI); 3136 3137 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3138 3139 // Load and check TRAP_STS.MEM_VIOL 3140 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3141 .addImm(EncodedReg); 3142 3143 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3144 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3145 .addReg(Reg, RegState::Kill) 3146 .addImm(0); 3147 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3148 .addMBB(LoopBB); 3149 3150 return RemainderBB; 3151 } 3152 3153 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3154 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3155 // will only do one iteration. In the worst case, this will loop 64 times. 3156 // 3157 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3158 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3159 const SIInstrInfo *TII, 3160 MachineRegisterInfo &MRI, 3161 MachineBasicBlock &OrigBB, 3162 MachineBasicBlock &LoopBB, 3163 const DebugLoc &DL, 3164 const MachineOperand &IdxReg, 3165 unsigned InitReg, 3166 unsigned ResultReg, 3167 unsigned PhiReg, 3168 unsigned InitSaveExecReg, 3169 int Offset, 3170 bool UseGPRIdxMode, 3171 bool IsIndirectSrc) { 3172 MachineFunction *MF = OrigBB.getParent(); 3173 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3174 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3175 MachineBasicBlock::iterator I = LoopBB.begin(); 3176 3177 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3178 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3179 Register NewExec = MRI.createVirtualRegister(BoolRC); 3180 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3181 Register CondReg = MRI.createVirtualRegister(BoolRC); 3182 3183 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3184 .addReg(InitReg) 3185 .addMBB(&OrigBB) 3186 .addReg(ResultReg) 3187 .addMBB(&LoopBB); 3188 3189 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3190 .addReg(InitSaveExecReg) 3191 .addMBB(&OrigBB) 3192 .addReg(NewExec) 3193 .addMBB(&LoopBB); 3194 3195 // Read the next variant <- also loop target. 3196 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3197 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3198 3199 // Compare the just read M0 value to all possible Idx values. 3200 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3201 .addReg(CurrentIdxReg) 3202 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3203 3204 // Update EXEC, save the original EXEC value to VCC. 3205 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3206 : AMDGPU::S_AND_SAVEEXEC_B64), 3207 NewExec) 3208 .addReg(CondReg, RegState::Kill); 3209 3210 MRI.setSimpleHint(NewExec, CondReg); 3211 3212 if (UseGPRIdxMode) { 3213 unsigned IdxReg; 3214 if (Offset == 0) { 3215 IdxReg = CurrentIdxReg; 3216 } else { 3217 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3218 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3219 .addReg(CurrentIdxReg, RegState::Kill) 3220 .addImm(Offset); 3221 } 3222 unsigned IdxMode = IsIndirectSrc ? 3223 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3224 MachineInstr *SetOn = 3225 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3226 .addReg(IdxReg, RegState::Kill) 3227 .addImm(IdxMode); 3228 SetOn->getOperand(3).setIsUndef(); 3229 } else { 3230 // Move index from VCC into M0 3231 if (Offset == 0) { 3232 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3233 .addReg(CurrentIdxReg, RegState::Kill); 3234 } else { 3235 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3236 .addReg(CurrentIdxReg, RegState::Kill) 3237 .addImm(Offset); 3238 } 3239 } 3240 3241 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3242 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3243 MachineInstr *InsertPt = 3244 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3245 : AMDGPU::S_XOR_B64_term), Exec) 3246 .addReg(Exec) 3247 .addReg(NewExec); 3248 3249 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3250 // s_cbranch_scc0? 3251 3252 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3253 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3254 .addMBB(&LoopBB); 3255 3256 return InsertPt->getIterator(); 3257 } 3258 3259 // This has slightly sub-optimal regalloc when the source vector is killed by 3260 // the read. The register allocator does not understand that the kill is 3261 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3262 // subregister from it, using 1 more VGPR than necessary. This was saved when 3263 // this was expanded after register allocation. 3264 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3265 MachineBasicBlock &MBB, 3266 MachineInstr &MI, 3267 unsigned InitResultReg, 3268 unsigned PhiReg, 3269 int Offset, 3270 bool UseGPRIdxMode, 3271 bool IsIndirectSrc) { 3272 MachineFunction *MF = MBB.getParent(); 3273 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3274 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3275 MachineRegisterInfo &MRI = MF->getRegInfo(); 3276 const DebugLoc &DL = MI.getDebugLoc(); 3277 MachineBasicBlock::iterator I(&MI); 3278 3279 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3280 Register DstReg = MI.getOperand(0).getReg(); 3281 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3282 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3283 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3284 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3285 3286 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3287 3288 // Save the EXEC mask 3289 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3290 .addReg(Exec); 3291 3292 MachineBasicBlock *LoopBB; 3293 MachineBasicBlock *RemainderBB; 3294 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3295 3296 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3297 3298 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3299 InitResultReg, DstReg, PhiReg, TmpExec, 3300 Offset, UseGPRIdxMode, IsIndirectSrc); 3301 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3302 MachineFunction::iterator MBBI(LoopBB); 3303 ++MBBI; 3304 MF->insert(MBBI, LandingPad); 3305 LoopBB->removeSuccessor(RemainderBB); 3306 LandingPad->addSuccessor(RemainderBB); 3307 LoopBB->addSuccessor(LandingPad); 3308 MachineBasicBlock::iterator First = LandingPad->begin(); 3309 BuildMI(*LandingPad, 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(SIRegisterInfo::getSubRegFromChannel(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 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 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 MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3463 MachineBasicBlock &MBB, 3464 const GCNSubtarget &ST) { 3465 const SIInstrInfo *TII = ST.getInstrInfo(); 3466 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3467 MachineFunction *MF = MBB.getParent(); 3468 MachineRegisterInfo &MRI = MF->getRegInfo(); 3469 3470 Register Dst = MI.getOperand(0).getReg(); 3471 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3472 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3473 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3474 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3475 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3476 3477 // This can be an immediate, but will be folded later. 3478 assert(Val->getReg()); 3479 3480 unsigned SubReg; 3481 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3482 SrcVec->getReg(), 3483 Offset); 3484 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3485 3486 if (Idx->getReg() == AMDGPU::NoRegister) { 3487 MachineBasicBlock::iterator I(&MI); 3488 const DebugLoc &DL = MI.getDebugLoc(); 3489 3490 assert(Offset == 0); 3491 3492 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3493 .add(*SrcVec) 3494 .add(*Val) 3495 .addImm(SubReg); 3496 3497 MI.eraseFromParent(); 3498 return &MBB; 3499 } 3500 3501 const MCInstrDesc &MovRelDesc 3502 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3503 3504 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3505 MachineBasicBlock::iterator I(&MI); 3506 const DebugLoc &DL = MI.getDebugLoc(); 3507 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3508 .addReg(SrcVec->getReg()) 3509 .add(*Val) 3510 .addImm(SubReg); 3511 if (UseGPRIdxMode) 3512 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3513 3514 MI.eraseFromParent(); 3515 return &MBB; 3516 } 3517 3518 if (Val->isReg()) 3519 MRI.clearKillFlags(Val->getReg()); 3520 3521 const DebugLoc &DL = MI.getDebugLoc(); 3522 3523 Register PhiReg = MRI.createVirtualRegister(VecRC); 3524 3525 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3526 Offset, UseGPRIdxMode, false); 3527 MachineBasicBlock *LoopBB = InsPt->getParent(); 3528 3529 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3530 .addReg(PhiReg) 3531 .add(*Val) 3532 .addImm(AMDGPU::sub0); 3533 if (UseGPRIdxMode) 3534 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3535 3536 MI.eraseFromParent(); 3537 return LoopBB; 3538 } 3539 3540 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3541 MachineInstr &MI, MachineBasicBlock *BB) const { 3542 3543 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3544 MachineFunction *MF = BB->getParent(); 3545 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3546 3547 if (TII->isMIMG(MI)) { 3548 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 3549 report_fatal_error("missing mem operand from MIMG instruction"); 3550 } 3551 // Add a memoperand for mimg instructions so that they aren't assumed to 3552 // be ordered memory instuctions. 3553 3554 return BB; 3555 } 3556 3557 switch (MI.getOpcode()) { 3558 case AMDGPU::S_ADD_U64_PSEUDO: 3559 case AMDGPU::S_SUB_U64_PSEUDO: { 3560 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3561 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3562 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3563 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3564 const DebugLoc &DL = MI.getDebugLoc(); 3565 3566 MachineOperand &Dest = MI.getOperand(0); 3567 MachineOperand &Src0 = MI.getOperand(1); 3568 MachineOperand &Src1 = MI.getOperand(2); 3569 3570 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3571 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3572 3573 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3574 Src0, BoolRC, AMDGPU::sub0, 3575 &AMDGPU::SReg_32RegClass); 3576 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3577 Src0, BoolRC, AMDGPU::sub1, 3578 &AMDGPU::SReg_32RegClass); 3579 3580 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3581 Src1, BoolRC, AMDGPU::sub0, 3582 &AMDGPU::SReg_32RegClass); 3583 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3584 Src1, BoolRC, AMDGPU::sub1, 3585 &AMDGPU::SReg_32RegClass); 3586 3587 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3588 3589 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3590 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3591 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3592 .add(Src0Sub0) 3593 .add(Src1Sub0); 3594 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3595 .add(Src0Sub1) 3596 .add(Src1Sub1); 3597 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3598 .addReg(DestSub0) 3599 .addImm(AMDGPU::sub0) 3600 .addReg(DestSub1) 3601 .addImm(AMDGPU::sub1); 3602 MI.eraseFromParent(); 3603 return BB; 3604 } 3605 case AMDGPU::SI_INIT_M0: { 3606 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3607 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3608 .add(MI.getOperand(0)); 3609 MI.eraseFromParent(); 3610 return BB; 3611 } 3612 case AMDGPU::SI_INIT_EXEC: 3613 // This should be before all vector instructions. 3614 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3615 AMDGPU::EXEC) 3616 .addImm(MI.getOperand(0).getImm()); 3617 MI.eraseFromParent(); 3618 return BB; 3619 3620 case AMDGPU::SI_INIT_EXEC_LO: 3621 // This should be before all vector instructions. 3622 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3623 AMDGPU::EXEC_LO) 3624 .addImm(MI.getOperand(0).getImm()); 3625 MI.eraseFromParent(); 3626 return BB; 3627 3628 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3629 // Extract the thread count from an SGPR input and set EXEC accordingly. 3630 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3631 // 3632 // S_BFE_U32 count, input, {shift, 7} 3633 // S_BFM_B64 exec, count, 0 3634 // S_CMP_EQ_U32 count, 64 3635 // S_CMOV_B64 exec, -1 3636 MachineInstr *FirstMI = &*BB->begin(); 3637 MachineRegisterInfo &MRI = MF->getRegInfo(); 3638 Register InputReg = MI.getOperand(0).getReg(); 3639 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3640 bool Found = false; 3641 3642 // Move the COPY of the input reg to the beginning, so that we can use it. 3643 for (auto I = BB->begin(); I != &MI; I++) { 3644 if (I->getOpcode() != TargetOpcode::COPY || 3645 I->getOperand(0).getReg() != InputReg) 3646 continue; 3647 3648 if (I == FirstMI) { 3649 FirstMI = &*++BB->begin(); 3650 } else { 3651 I->removeFromParent(); 3652 BB->insert(FirstMI, &*I); 3653 } 3654 Found = true; 3655 break; 3656 } 3657 assert(Found); 3658 (void)Found; 3659 3660 // This should be before all vector instructions. 3661 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3662 bool isWave32 = getSubtarget()->isWave32(); 3663 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3664 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3665 .addReg(InputReg) 3666 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3667 BuildMI(*BB, FirstMI, DebugLoc(), 3668 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3669 Exec) 3670 .addReg(CountReg) 3671 .addImm(0); 3672 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3673 .addReg(CountReg, RegState::Kill) 3674 .addImm(getSubtarget()->getWavefrontSize()); 3675 BuildMI(*BB, FirstMI, DebugLoc(), 3676 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3677 Exec) 3678 .addImm(-1); 3679 MI.eraseFromParent(); 3680 return BB; 3681 } 3682 3683 case AMDGPU::GET_GROUPSTATICSIZE: { 3684 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 3685 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 3686 DebugLoc DL = MI.getDebugLoc(); 3687 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3688 .add(MI.getOperand(0)) 3689 .addImm(MFI->getLDSSize()); 3690 MI.eraseFromParent(); 3691 return BB; 3692 } 3693 case AMDGPU::SI_INDIRECT_SRC_V1: 3694 case AMDGPU::SI_INDIRECT_SRC_V2: 3695 case AMDGPU::SI_INDIRECT_SRC_V4: 3696 case AMDGPU::SI_INDIRECT_SRC_V8: 3697 case AMDGPU::SI_INDIRECT_SRC_V16: 3698 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3699 case AMDGPU::SI_INDIRECT_DST_V1: 3700 case AMDGPU::SI_INDIRECT_DST_V2: 3701 case AMDGPU::SI_INDIRECT_DST_V4: 3702 case AMDGPU::SI_INDIRECT_DST_V8: 3703 case AMDGPU::SI_INDIRECT_DST_V16: 3704 return emitIndirectDst(MI, *BB, *getSubtarget()); 3705 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3706 case AMDGPU::SI_KILL_I1_PSEUDO: 3707 return splitKillBlock(MI, BB); 3708 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3709 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3710 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3711 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3712 3713 Register Dst = MI.getOperand(0).getReg(); 3714 Register Src0 = MI.getOperand(1).getReg(); 3715 Register Src1 = MI.getOperand(2).getReg(); 3716 const DebugLoc &DL = MI.getDebugLoc(); 3717 Register SrcCond = MI.getOperand(3).getReg(); 3718 3719 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3720 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3721 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3722 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 3723 3724 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3725 .addReg(SrcCond); 3726 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3727 .addImm(0) 3728 .addReg(Src0, 0, AMDGPU::sub0) 3729 .addImm(0) 3730 .addReg(Src1, 0, AMDGPU::sub0) 3731 .addReg(SrcCondCopy); 3732 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3733 .addImm(0) 3734 .addReg(Src0, 0, AMDGPU::sub1) 3735 .addImm(0) 3736 .addReg(Src1, 0, AMDGPU::sub1) 3737 .addReg(SrcCondCopy); 3738 3739 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3740 .addReg(DstLo) 3741 .addImm(AMDGPU::sub0) 3742 .addReg(DstHi) 3743 .addImm(AMDGPU::sub1); 3744 MI.eraseFromParent(); 3745 return BB; 3746 } 3747 case AMDGPU::SI_BR_UNDEF: { 3748 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3749 const DebugLoc &DL = MI.getDebugLoc(); 3750 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3751 .add(MI.getOperand(0)); 3752 Br->getOperand(1).setIsUndef(true); // read undef SCC 3753 MI.eraseFromParent(); 3754 return BB; 3755 } 3756 case AMDGPU::ADJCALLSTACKUP: 3757 case AMDGPU::ADJCALLSTACKDOWN: { 3758 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3759 MachineInstrBuilder MIB(*MF, &MI); 3760 3761 // Add an implicit use of the frame offset reg to prevent the restore copy 3762 // inserted after the call from being reorderd after stack operations in the 3763 // the caller's frame. 3764 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3765 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 3766 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 3767 return BB; 3768 } 3769 case AMDGPU::SI_CALL_ISEL: { 3770 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3771 const DebugLoc &DL = MI.getDebugLoc(); 3772 3773 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3774 3775 MachineInstrBuilder MIB; 3776 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 3777 3778 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 3779 MIB.add(MI.getOperand(I)); 3780 3781 MIB.cloneMemRefs(MI); 3782 MI.eraseFromParent(); 3783 return BB; 3784 } 3785 case AMDGPU::V_ADD_I32_e32: 3786 case AMDGPU::V_SUB_I32_e32: 3787 case AMDGPU::V_SUBREV_I32_e32: { 3788 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 3789 const DebugLoc &DL = MI.getDebugLoc(); 3790 unsigned Opc = MI.getOpcode(); 3791 3792 bool NeedClampOperand = false; 3793 if (TII->pseudoToMCOpcode(Opc) == -1) { 3794 Opc = AMDGPU::getVOPe64(Opc); 3795 NeedClampOperand = true; 3796 } 3797 3798 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 3799 if (TII->isVOP3(*I)) { 3800 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3801 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3802 I.addReg(TRI->getVCC(), RegState::Define); 3803 } 3804 I.add(MI.getOperand(1)) 3805 .add(MI.getOperand(2)); 3806 if (NeedClampOperand) 3807 I.addImm(0); // clamp bit for e64 encoding 3808 3809 TII->legalizeOperands(*I); 3810 3811 MI.eraseFromParent(); 3812 return BB; 3813 } 3814 case AMDGPU::DS_GWS_INIT: 3815 case AMDGPU::DS_GWS_SEMA_V: 3816 case AMDGPU::DS_GWS_SEMA_BR: 3817 case AMDGPU::DS_GWS_SEMA_P: 3818 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 3819 case AMDGPU::DS_GWS_BARRIER: 3820 // A s_waitcnt 0 is required to be the instruction immediately following. 3821 if (getSubtarget()->hasGWSAutoReplay()) { 3822 bundleInstWithWaitcnt(MI); 3823 return BB; 3824 } 3825 3826 return emitGWSMemViolTestLoop(MI, BB); 3827 default: 3828 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3829 } 3830 } 3831 3832 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 3833 return isTypeLegal(VT.getScalarType()); 3834 } 3835 3836 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3837 // This currently forces unfolding various combinations of fsub into fma with 3838 // free fneg'd operands. As long as we have fast FMA (controlled by 3839 // isFMAFasterThanFMulAndFAdd), we should perform these. 3840 3841 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3842 // most of these combines appear to be cycle neutral but save on instruction 3843 // count / code size. 3844 return true; 3845 } 3846 3847 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3848 EVT VT) const { 3849 if (!VT.isVector()) { 3850 return MVT::i1; 3851 } 3852 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3853 } 3854 3855 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3856 // TODO: Should i16 be used always if legal? For now it would force VALU 3857 // shifts. 3858 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3859 } 3860 3861 // Answering this is somewhat tricky and depends on the specific device which 3862 // have different rates for fma or all f64 operations. 3863 // 3864 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3865 // regardless of which device (although the number of cycles differs between 3866 // devices), so it is always profitable for f64. 3867 // 3868 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3869 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3870 // which we can always do even without fused FP ops since it returns the same 3871 // result as the separate operations and since it is always full 3872 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3873 // however does not support denormals, so we do report fma as faster if we have 3874 // a fast fma device and require denormals. 3875 // 3876 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 3877 EVT VT) const { 3878 VT = VT.getScalarType(); 3879 3880 switch (VT.getSimpleVT().SimpleTy) { 3881 case MVT::f32: { 3882 // This is as fast on some subtargets. However, we always have full rate f32 3883 // mad available which returns the same result as the separate operations 3884 // which we should prefer over fma. We can't use this if we want to support 3885 // denormals, so only report this in these cases. 3886 if (hasFP32Denormals(MF)) 3887 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 3888 3889 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 3890 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 3891 } 3892 case MVT::f64: 3893 return true; 3894 case MVT::f16: 3895 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 3896 default: 3897 break; 3898 } 3899 3900 return false; 3901 } 3902 3903 bool SITargetLowering::isFMADLegalForFAddFSub(const SelectionDAG &DAG, 3904 const SDNode *N) const { 3905 // TODO: Check future ftz flag 3906 // v_mad_f32/v_mac_f32 do not support denormals. 3907 EVT VT = N->getValueType(0); 3908 if (VT == MVT::f32) 3909 return !hasFP32Denormals(DAG.getMachineFunction()); 3910 if (VT == MVT::f16) { 3911 return Subtarget->hasMadF16() && 3912 !hasFP64FP16Denormals(DAG.getMachineFunction()); 3913 } 3914 3915 return false; 3916 } 3917 3918 //===----------------------------------------------------------------------===// 3919 // Custom DAG Lowering Operations 3920 //===----------------------------------------------------------------------===// 3921 3922 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3923 // wider vector type is legal. 3924 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 3925 SelectionDAG &DAG) const { 3926 unsigned Opc = Op.getOpcode(); 3927 EVT VT = Op.getValueType(); 3928 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 3929 3930 SDValue Lo, Hi; 3931 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 3932 3933 SDLoc SL(Op); 3934 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 3935 Op->getFlags()); 3936 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 3937 Op->getFlags()); 3938 3939 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3940 } 3941 3942 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3943 // wider vector type is legal. 3944 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 3945 SelectionDAG &DAG) const { 3946 unsigned Opc = Op.getOpcode(); 3947 EVT VT = Op.getValueType(); 3948 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 3949 3950 SDValue Lo0, Hi0; 3951 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 3952 SDValue Lo1, Hi1; 3953 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 3954 3955 SDLoc SL(Op); 3956 3957 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 3958 Op->getFlags()); 3959 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 3960 Op->getFlags()); 3961 3962 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3963 } 3964 3965 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 3966 SelectionDAG &DAG) const { 3967 unsigned Opc = Op.getOpcode(); 3968 EVT VT = Op.getValueType(); 3969 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 3970 3971 SDValue Lo0, Hi0; 3972 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 3973 SDValue Lo1, Hi1; 3974 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 3975 SDValue Lo2, Hi2; 3976 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 3977 3978 SDLoc SL(Op); 3979 3980 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 3981 Op->getFlags()); 3982 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 3983 Op->getFlags()); 3984 3985 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3986 } 3987 3988 3989 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 3990 switch (Op.getOpcode()) { 3991 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 3992 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 3993 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 3994 case ISD::LOAD: { 3995 SDValue Result = LowerLOAD(Op, DAG); 3996 assert((!Result.getNode() || 3997 Result.getNode()->getNumValues() == 2) && 3998 "Load should return a value and a chain"); 3999 return Result; 4000 } 4001 4002 case ISD::FSIN: 4003 case ISD::FCOS: 4004 return LowerTrig(Op, DAG); 4005 case ISD::SELECT: return LowerSELECT(Op, DAG); 4006 case ISD::FDIV: return LowerFDIV(Op, DAG); 4007 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4008 case ISD::STORE: return LowerSTORE(Op, DAG); 4009 case ISD::GlobalAddress: { 4010 MachineFunction &MF = DAG.getMachineFunction(); 4011 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4012 return LowerGlobalAddress(MFI, Op, DAG); 4013 } 4014 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4015 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4016 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4017 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4018 case ISD::INSERT_SUBVECTOR: 4019 return lowerINSERT_SUBVECTOR(Op, DAG); 4020 case ISD::INSERT_VECTOR_ELT: 4021 return lowerINSERT_VECTOR_ELT(Op, DAG); 4022 case ISD::EXTRACT_VECTOR_ELT: 4023 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4024 case ISD::VECTOR_SHUFFLE: 4025 return lowerVECTOR_SHUFFLE(Op, DAG); 4026 case ISD::BUILD_VECTOR: 4027 return lowerBUILD_VECTOR(Op, DAG); 4028 case ISD::FP_ROUND: 4029 return lowerFP_ROUND(Op, DAG); 4030 case ISD::TRAP: 4031 return lowerTRAP(Op, DAG); 4032 case ISD::DEBUGTRAP: 4033 return lowerDEBUGTRAP(Op, DAG); 4034 case ISD::FABS: 4035 case ISD::FNEG: 4036 case ISD::FCANONICALIZE: 4037 case ISD::BSWAP: 4038 return splitUnaryVectorOp(Op, DAG); 4039 case ISD::FMINNUM: 4040 case ISD::FMAXNUM: 4041 return lowerFMINNUM_FMAXNUM(Op, DAG); 4042 case ISD::FMA: 4043 return splitTernaryVectorOp(Op, DAG); 4044 case ISD::SHL: 4045 case ISD::SRA: 4046 case ISD::SRL: 4047 case ISD::ADD: 4048 case ISD::SUB: 4049 case ISD::MUL: 4050 case ISD::SMIN: 4051 case ISD::SMAX: 4052 case ISD::UMIN: 4053 case ISD::UMAX: 4054 case ISD::FADD: 4055 case ISD::FMUL: 4056 case ISD::FMINNUM_IEEE: 4057 case ISD::FMAXNUM_IEEE: 4058 return splitBinaryVectorOp(Op, DAG); 4059 } 4060 return SDValue(); 4061 } 4062 4063 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4064 const SDLoc &DL, 4065 SelectionDAG &DAG, bool Unpacked) { 4066 if (!LoadVT.isVector()) 4067 return Result; 4068 4069 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4070 // Truncate to v2i16/v4i16. 4071 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4072 4073 // Workaround legalizer not scalarizing truncate after vector op 4074 // legalization byt not creating intermediate vector trunc. 4075 SmallVector<SDValue, 4> Elts; 4076 DAG.ExtractVectorElements(Result, Elts); 4077 for (SDValue &Elt : Elts) 4078 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4079 4080 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4081 4082 // Bitcast to original type (v2f16/v4f16). 4083 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4084 } 4085 4086 // Cast back to the original packed type. 4087 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4088 } 4089 4090 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4091 MemSDNode *M, 4092 SelectionDAG &DAG, 4093 ArrayRef<SDValue> Ops, 4094 bool IsIntrinsic) const { 4095 SDLoc DL(M); 4096 4097 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4098 EVT LoadVT = M->getValueType(0); 4099 4100 EVT EquivLoadVT = LoadVT; 4101 if (Unpacked && LoadVT.isVector()) { 4102 EquivLoadVT = LoadVT.isVector() ? 4103 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4104 LoadVT.getVectorNumElements()) : LoadVT; 4105 } 4106 4107 // Change from v4f16/v2f16 to EquivLoadVT. 4108 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4109 4110 SDValue Load 4111 = DAG.getMemIntrinsicNode( 4112 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4113 VTList, Ops, M->getMemoryVT(), 4114 M->getMemOperand()); 4115 if (!Unpacked) // Just adjusted the opcode. 4116 return Load; 4117 4118 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4119 4120 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4121 } 4122 4123 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4124 SelectionDAG &DAG, 4125 ArrayRef<SDValue> Ops) const { 4126 SDLoc DL(M); 4127 EVT LoadVT = M->getValueType(0); 4128 EVT EltType = LoadVT.getScalarType(); 4129 EVT IntVT = LoadVT.changeTypeToInteger(); 4130 4131 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4132 4133 unsigned Opc = 4134 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4135 4136 if (IsD16) { 4137 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4138 } 4139 4140 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4141 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4142 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4143 4144 if (isTypeLegal(LoadVT)) { 4145 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4146 M->getMemOperand(), DAG); 4147 } 4148 4149 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4150 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4151 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4152 M->getMemOperand(), DAG); 4153 return DAG.getMergeValues( 4154 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4155 DL); 4156 } 4157 4158 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4159 SDNode *N, SelectionDAG &DAG) { 4160 EVT VT = N->getValueType(0); 4161 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4162 int CondCode = CD->getSExtValue(); 4163 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4164 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4165 return DAG.getUNDEF(VT); 4166 4167 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4168 4169 SDValue LHS = N->getOperand(1); 4170 SDValue RHS = N->getOperand(2); 4171 4172 SDLoc DL(N); 4173 4174 EVT CmpVT = LHS.getValueType(); 4175 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4176 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4177 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4178 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4179 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4180 } 4181 4182 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4183 4184 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4185 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4186 4187 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4188 DAG.getCondCode(CCOpcode)); 4189 if (VT.bitsEq(CCVT)) 4190 return SetCC; 4191 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4192 } 4193 4194 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4195 SDNode *N, SelectionDAG &DAG) { 4196 EVT VT = N->getValueType(0); 4197 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4198 4199 int CondCode = CD->getSExtValue(); 4200 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4201 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4202 return DAG.getUNDEF(VT); 4203 } 4204 4205 SDValue Src0 = N->getOperand(1); 4206 SDValue Src1 = N->getOperand(2); 4207 EVT CmpVT = Src0.getValueType(); 4208 SDLoc SL(N); 4209 4210 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4211 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4212 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4213 } 4214 4215 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4216 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4217 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4218 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4219 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4220 Src1, DAG.getCondCode(CCOpcode)); 4221 if (VT.bitsEq(CCVT)) 4222 return SetCC; 4223 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4224 } 4225 4226 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4227 SmallVectorImpl<SDValue> &Results, 4228 SelectionDAG &DAG) const { 4229 switch (N->getOpcode()) { 4230 case ISD::INSERT_VECTOR_ELT: { 4231 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4232 Results.push_back(Res); 4233 return; 4234 } 4235 case ISD::EXTRACT_VECTOR_ELT: { 4236 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4237 Results.push_back(Res); 4238 return; 4239 } 4240 case ISD::INTRINSIC_WO_CHAIN: { 4241 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4242 switch (IID) { 4243 case Intrinsic::amdgcn_cvt_pkrtz: { 4244 SDValue Src0 = N->getOperand(1); 4245 SDValue Src1 = N->getOperand(2); 4246 SDLoc SL(N); 4247 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4248 Src0, Src1); 4249 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4250 return; 4251 } 4252 case Intrinsic::amdgcn_cvt_pknorm_i16: 4253 case Intrinsic::amdgcn_cvt_pknorm_u16: 4254 case Intrinsic::amdgcn_cvt_pk_i16: 4255 case Intrinsic::amdgcn_cvt_pk_u16: { 4256 SDValue Src0 = N->getOperand(1); 4257 SDValue Src1 = N->getOperand(2); 4258 SDLoc SL(N); 4259 unsigned Opcode; 4260 4261 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4262 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4263 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4264 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4265 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4266 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4267 else 4268 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4269 4270 EVT VT = N->getValueType(0); 4271 if (isTypeLegal(VT)) 4272 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4273 else { 4274 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4275 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4276 } 4277 return; 4278 } 4279 } 4280 break; 4281 } 4282 case ISD::INTRINSIC_W_CHAIN: { 4283 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4284 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4285 // FIXME: Hacky 4286 Results.push_back(Res.getOperand(0)); 4287 Results.push_back(Res.getOperand(1)); 4288 } else { 4289 Results.push_back(Res); 4290 Results.push_back(Res.getValue(1)); 4291 } 4292 return; 4293 } 4294 4295 break; 4296 } 4297 case ISD::SELECT: { 4298 SDLoc SL(N); 4299 EVT VT = N->getValueType(0); 4300 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4301 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4302 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4303 4304 EVT SelectVT = NewVT; 4305 if (NewVT.bitsLT(MVT::i32)) { 4306 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4307 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4308 SelectVT = MVT::i32; 4309 } 4310 4311 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4312 N->getOperand(0), LHS, RHS); 4313 4314 if (NewVT != SelectVT) 4315 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4316 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4317 return; 4318 } 4319 case ISD::FNEG: { 4320 if (N->getValueType(0) != MVT::v2f16) 4321 break; 4322 4323 SDLoc SL(N); 4324 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4325 4326 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4327 BC, 4328 DAG.getConstant(0x80008000, SL, MVT::i32)); 4329 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4330 return; 4331 } 4332 case ISD::FABS: { 4333 if (N->getValueType(0) != MVT::v2f16) 4334 break; 4335 4336 SDLoc SL(N); 4337 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4338 4339 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4340 BC, 4341 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4342 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4343 return; 4344 } 4345 default: 4346 break; 4347 } 4348 } 4349 4350 /// Helper function for LowerBRCOND 4351 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4352 4353 SDNode *Parent = Value.getNode(); 4354 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4355 I != E; ++I) { 4356 4357 if (I.getUse().get() != Value) 4358 continue; 4359 4360 if (I->getOpcode() == Opcode) 4361 return *I; 4362 } 4363 return nullptr; 4364 } 4365 4366 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4367 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4368 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4369 case Intrinsic::amdgcn_if: 4370 return AMDGPUISD::IF; 4371 case Intrinsic::amdgcn_else: 4372 return AMDGPUISD::ELSE; 4373 case Intrinsic::amdgcn_loop: 4374 return AMDGPUISD::LOOP; 4375 case Intrinsic::amdgcn_end_cf: 4376 llvm_unreachable("should not occur"); 4377 default: 4378 return 0; 4379 } 4380 } 4381 4382 // break, if_break, else_break are all only used as inputs to loop, not 4383 // directly as branch conditions. 4384 return 0; 4385 } 4386 4387 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4388 const Triple &TT = getTargetMachine().getTargetTriple(); 4389 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4390 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4391 AMDGPU::shouldEmitConstantsToTextSection(TT); 4392 } 4393 4394 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4395 // FIXME: Either avoid relying on address space here or change the default 4396 // address space for functions to avoid the explicit check. 4397 return (GV->getValueType()->isFunctionTy() || 4398 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4399 !shouldEmitFixup(GV) && 4400 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4401 } 4402 4403 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4404 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4405 } 4406 4407 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4408 if (!GV->hasExternalLinkage()) 4409 return true; 4410 4411 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4412 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4413 } 4414 4415 /// This transforms the control flow intrinsics to get the branch destination as 4416 /// last parameter, also switches branch target with BR if the need arise 4417 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4418 SelectionDAG &DAG) const { 4419 SDLoc DL(BRCOND); 4420 4421 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4422 SDValue Target = BRCOND.getOperand(2); 4423 SDNode *BR = nullptr; 4424 SDNode *SetCC = nullptr; 4425 4426 if (Intr->getOpcode() == ISD::SETCC) { 4427 // As long as we negate the condition everything is fine 4428 SetCC = Intr; 4429 Intr = SetCC->getOperand(0).getNode(); 4430 4431 } else { 4432 // Get the target from BR if we don't negate the condition 4433 BR = findUser(BRCOND, ISD::BR); 4434 Target = BR->getOperand(1); 4435 } 4436 4437 // FIXME: This changes the types of the intrinsics instead of introducing new 4438 // nodes with the correct types. 4439 // e.g. llvm.amdgcn.loop 4440 4441 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 4442 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 4443 4444 unsigned CFNode = isCFIntrinsic(Intr); 4445 if (CFNode == 0) { 4446 // This is a uniform branch so we don't need to legalize. 4447 return BRCOND; 4448 } 4449 4450 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4451 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4452 4453 assert(!SetCC || 4454 (SetCC->getConstantOperandVal(1) == 1 && 4455 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4456 ISD::SETNE)); 4457 4458 // operands of the new intrinsic call 4459 SmallVector<SDValue, 4> Ops; 4460 if (HaveChain) 4461 Ops.push_back(BRCOND.getOperand(0)); 4462 4463 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4464 Ops.push_back(Target); 4465 4466 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4467 4468 // build the new intrinsic call 4469 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4470 4471 if (!HaveChain) { 4472 SDValue Ops[] = { 4473 SDValue(Result, 0), 4474 BRCOND.getOperand(0) 4475 }; 4476 4477 Result = DAG.getMergeValues(Ops, DL).getNode(); 4478 } 4479 4480 if (BR) { 4481 // Give the branch instruction our target 4482 SDValue Ops[] = { 4483 BR->getOperand(0), 4484 BRCOND.getOperand(2) 4485 }; 4486 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4487 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4488 BR = NewBR.getNode(); 4489 } 4490 4491 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4492 4493 // Copy the intrinsic results to registers 4494 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4495 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4496 if (!CopyToReg) 4497 continue; 4498 4499 Chain = DAG.getCopyToReg( 4500 Chain, DL, 4501 CopyToReg->getOperand(1), 4502 SDValue(Result, i - 1), 4503 SDValue()); 4504 4505 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4506 } 4507 4508 // Remove the old intrinsic from the chain 4509 DAG.ReplaceAllUsesOfValueWith( 4510 SDValue(Intr, Intr->getNumValues() - 1), 4511 Intr->getOperand(0)); 4512 4513 return Chain; 4514 } 4515 4516 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4517 SelectionDAG &DAG) const { 4518 MVT VT = Op.getSimpleValueType(); 4519 SDLoc DL(Op); 4520 // Checking the depth 4521 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4522 return DAG.getConstant(0, DL, VT); 4523 4524 MachineFunction &MF = DAG.getMachineFunction(); 4525 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4526 // Check for kernel and shader functions 4527 if (Info->isEntryFunction()) 4528 return DAG.getConstant(0, DL, VT); 4529 4530 MachineFrameInfo &MFI = MF.getFrameInfo(); 4531 // There is a call to @llvm.returnaddress in this function 4532 MFI.setReturnAddressIsTaken(true); 4533 4534 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4535 // Get the return address reg and mark it as an implicit live-in 4536 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4537 4538 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4539 } 4540 4541 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 4542 SDValue Op, 4543 const SDLoc &DL, 4544 EVT VT) const { 4545 return Op.getValueType().bitsLE(VT) ? 4546 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4547 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 4548 } 4549 4550 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4551 assert(Op.getValueType() == MVT::f16 && 4552 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4553 4554 SDValue Src = Op.getOperand(0); 4555 EVT SrcVT = Src.getValueType(); 4556 if (SrcVT != MVT::f64) 4557 return Op; 4558 4559 SDLoc DL(Op); 4560 4561 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4562 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4563 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4564 } 4565 4566 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4567 SelectionDAG &DAG) const { 4568 EVT VT = Op.getValueType(); 4569 const MachineFunction &MF = DAG.getMachineFunction(); 4570 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4571 bool IsIEEEMode = Info->getMode().IEEE; 4572 4573 // FIXME: Assert during eslection that this is only selected for 4574 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4575 // mode functions, but this happens to be OK since it's only done in cases 4576 // where there is known no sNaN. 4577 if (IsIEEEMode) 4578 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 4579 4580 if (VT == MVT::v4f16) 4581 return splitBinaryVectorOp(Op, DAG); 4582 return Op; 4583 } 4584 4585 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4586 SDLoc SL(Op); 4587 SDValue Chain = Op.getOperand(0); 4588 4589 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4590 !Subtarget->isTrapHandlerEnabled()) 4591 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4592 4593 MachineFunction &MF = DAG.getMachineFunction(); 4594 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4595 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4596 assert(UserSGPR != AMDGPU::NoRegister); 4597 SDValue QueuePtr = CreateLiveInRegister( 4598 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4599 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4600 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4601 QueuePtr, SDValue()); 4602 SDValue Ops[] = { 4603 ToReg, 4604 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 4605 SGPR01, 4606 ToReg.getValue(1) 4607 }; 4608 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4609 } 4610 4611 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 4612 SDLoc SL(Op); 4613 SDValue Chain = Op.getOperand(0); 4614 MachineFunction &MF = DAG.getMachineFunction(); 4615 4616 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4617 !Subtarget->isTrapHandlerEnabled()) { 4618 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4619 "debugtrap handler not supported", 4620 Op.getDebugLoc(), 4621 DS_Warning); 4622 LLVMContext &Ctx = MF.getFunction().getContext(); 4623 Ctx.diagnose(NoTrap); 4624 return Chain; 4625 } 4626 4627 SDValue Ops[] = { 4628 Chain, 4629 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 4630 }; 4631 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4632 } 4633 4634 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4635 SelectionDAG &DAG) const { 4636 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4637 if (Subtarget->hasApertureRegs()) { 4638 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 4639 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4640 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4641 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 4642 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4643 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4644 unsigned Encoding = 4645 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4646 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4647 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4648 4649 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4650 SDValue ApertureReg = SDValue( 4651 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4652 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4653 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4654 } 4655 4656 MachineFunction &MF = DAG.getMachineFunction(); 4657 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4658 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4659 assert(UserSGPR != AMDGPU::NoRegister); 4660 4661 SDValue QueuePtr = CreateLiveInRegister( 4662 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4663 4664 // Offset into amd_queue_t for group_segment_aperture_base_hi / 4665 // private_segment_aperture_base_hi. 4666 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 4667 4668 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 4669 4670 // TODO: Use custom target PseudoSourceValue. 4671 // TODO: We should use the value from the IR intrinsic call, but it might not 4672 // be available and how do we get it? 4673 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 4674 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4675 MinAlign(64, StructOffset), 4676 MachineMemOperand::MODereferenceable | 4677 MachineMemOperand::MOInvariant); 4678 } 4679 4680 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4681 SelectionDAG &DAG) const { 4682 SDLoc SL(Op); 4683 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4684 4685 SDValue Src = ASC->getOperand(0); 4686 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4687 4688 const AMDGPUTargetMachine &TM = 4689 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4690 4691 // flat -> local/private 4692 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4693 unsigned DestAS = ASC->getDestAddressSpace(); 4694 4695 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 4696 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 4697 unsigned NullVal = TM.getNullPointerValue(DestAS); 4698 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4699 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4700 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4701 4702 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4703 NonNull, Ptr, SegmentNullPtr); 4704 } 4705 } 4706 4707 // local/private -> flat 4708 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4709 unsigned SrcAS = ASC->getSrcAddressSpace(); 4710 4711 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 4712 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 4713 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4714 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4715 4716 SDValue NonNull 4717 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4718 4719 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4720 SDValue CvtPtr 4721 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4722 4723 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4724 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4725 FlatNullPtr); 4726 } 4727 } 4728 4729 // global <-> flat are no-ops and never emitted. 4730 4731 const MachineFunction &MF = DAG.getMachineFunction(); 4732 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 4733 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 4734 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 4735 4736 return DAG.getUNDEF(ASC->getValueType(0)); 4737 } 4738 4739 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 4740 // the small vector and inserting them into the big vector. That is better than 4741 // the default expansion of doing it via a stack slot. Even though the use of 4742 // the stack slot would be optimized away afterwards, the stack slot itself 4743 // remains. 4744 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4745 SelectionDAG &DAG) const { 4746 SDValue Vec = Op.getOperand(0); 4747 SDValue Ins = Op.getOperand(1); 4748 SDValue Idx = Op.getOperand(2); 4749 EVT VecVT = Vec.getValueType(); 4750 EVT InsVT = Ins.getValueType(); 4751 EVT EltVT = VecVT.getVectorElementType(); 4752 unsigned InsNumElts = InsVT.getVectorNumElements(); 4753 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 4754 SDLoc SL(Op); 4755 4756 for (unsigned I = 0; I != InsNumElts; ++I) { 4757 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 4758 DAG.getConstant(I, SL, MVT::i32)); 4759 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 4760 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 4761 } 4762 return Vec; 4763 } 4764 4765 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4766 SelectionDAG &DAG) const { 4767 SDValue Vec = Op.getOperand(0); 4768 SDValue InsVal = Op.getOperand(1); 4769 SDValue Idx = Op.getOperand(2); 4770 EVT VecVT = Vec.getValueType(); 4771 EVT EltVT = VecVT.getVectorElementType(); 4772 unsigned VecSize = VecVT.getSizeInBits(); 4773 unsigned EltSize = EltVT.getSizeInBits(); 4774 4775 4776 assert(VecSize <= 64); 4777 4778 unsigned NumElts = VecVT.getVectorNumElements(); 4779 SDLoc SL(Op); 4780 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 4781 4782 if (NumElts == 4 && EltSize == 16 && KIdx) { 4783 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 4784 4785 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4786 DAG.getConstant(0, SL, MVT::i32)); 4787 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4788 DAG.getConstant(1, SL, MVT::i32)); 4789 4790 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 4791 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 4792 4793 unsigned Idx = KIdx->getZExtValue(); 4794 bool InsertLo = Idx < 2; 4795 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 4796 InsertLo ? LoVec : HiVec, 4797 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 4798 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 4799 4800 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 4801 4802 SDValue Concat = InsertLo ? 4803 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 4804 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 4805 4806 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 4807 } 4808 4809 if (isa<ConstantSDNode>(Idx)) 4810 return SDValue(); 4811 4812 MVT IntVT = MVT::getIntegerVT(VecSize); 4813 4814 // Avoid stack access for dynamic indexing. 4815 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 4816 4817 // Create a congruent vector with the target value in each element so that 4818 // the required element can be masked and ORed into the target vector. 4819 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 4820 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 4821 4822 assert(isPowerOf2_32(EltSize)); 4823 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4824 4825 // Convert vector index to bit-index. 4826 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4827 4828 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4829 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 4830 DAG.getConstant(0xffff, SL, IntVT), 4831 ScaledIdx); 4832 4833 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 4834 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 4835 DAG.getNOT(SL, BFM, IntVT), BCVec); 4836 4837 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 4838 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 4839 } 4840 4841 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4842 SelectionDAG &DAG) const { 4843 SDLoc SL(Op); 4844 4845 EVT ResultVT = Op.getValueType(); 4846 SDValue Vec = Op.getOperand(0); 4847 SDValue Idx = Op.getOperand(1); 4848 EVT VecVT = Vec.getValueType(); 4849 unsigned VecSize = VecVT.getSizeInBits(); 4850 EVT EltVT = VecVT.getVectorElementType(); 4851 assert(VecSize <= 64); 4852 4853 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 4854 4855 // Make sure we do any optimizations that will make it easier to fold 4856 // source modifiers before obscuring it with bit operations. 4857 4858 // XXX - Why doesn't this get called when vector_shuffle is expanded? 4859 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 4860 return Combined; 4861 4862 unsigned EltSize = EltVT.getSizeInBits(); 4863 assert(isPowerOf2_32(EltSize)); 4864 4865 MVT IntVT = MVT::getIntegerVT(VecSize); 4866 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4867 4868 // Convert vector index to bit-index (* EltSize) 4869 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4870 4871 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4872 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 4873 4874 if (ResultVT == MVT::f16) { 4875 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 4876 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 4877 } 4878 4879 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 4880 } 4881 4882 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 4883 assert(Elt % 2 == 0); 4884 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 4885 } 4886 4887 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 4888 SelectionDAG &DAG) const { 4889 SDLoc SL(Op); 4890 EVT ResultVT = Op.getValueType(); 4891 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 4892 4893 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 4894 EVT EltVT = PackVT.getVectorElementType(); 4895 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 4896 4897 // vector_shuffle <0,1,6,7> lhs, rhs 4898 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 4899 // 4900 // vector_shuffle <6,7,2,3> lhs, rhs 4901 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 4902 // 4903 // vector_shuffle <6,7,0,1> lhs, rhs 4904 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 4905 4906 // Avoid scalarizing when both halves are reading from consecutive elements. 4907 SmallVector<SDValue, 4> Pieces; 4908 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 4909 if (elementPairIsContiguous(SVN->getMask(), I)) { 4910 const int Idx = SVN->getMaskElt(I); 4911 int VecIdx = Idx < SrcNumElts ? 0 : 1; 4912 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 4913 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 4914 PackVT, SVN->getOperand(VecIdx), 4915 DAG.getConstant(EltIdx, SL, MVT::i32)); 4916 Pieces.push_back(SubVec); 4917 } else { 4918 const int Idx0 = SVN->getMaskElt(I); 4919 const int Idx1 = SVN->getMaskElt(I + 1); 4920 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 4921 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 4922 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 4923 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 4924 4925 SDValue Vec0 = SVN->getOperand(VecIdx0); 4926 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4927 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 4928 4929 SDValue Vec1 = SVN->getOperand(VecIdx1); 4930 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4931 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 4932 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 4933 } 4934 } 4935 4936 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 4937 } 4938 4939 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 4940 SelectionDAG &DAG) const { 4941 SDLoc SL(Op); 4942 EVT VT = Op.getValueType(); 4943 4944 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 4945 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 4946 4947 // Turn into pair of packed build_vectors. 4948 // TODO: Special case for constants that can be materialized with s_mov_b64. 4949 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 4950 { Op.getOperand(0), Op.getOperand(1) }); 4951 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 4952 { Op.getOperand(2), Op.getOperand(3) }); 4953 4954 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 4955 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 4956 4957 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 4958 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 4959 } 4960 4961 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 4962 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 4963 4964 SDValue Lo = Op.getOperand(0); 4965 SDValue Hi = Op.getOperand(1); 4966 4967 // Avoid adding defined bits with the zero_extend. 4968 if (Hi.isUndef()) { 4969 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4970 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 4971 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 4972 } 4973 4974 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 4975 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 4976 4977 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 4978 DAG.getConstant(16, SL, MVT::i32)); 4979 if (Lo.isUndef()) 4980 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 4981 4982 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4983 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 4984 4985 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 4986 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 4987 } 4988 4989 bool 4990 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 4991 // We can fold offsets for anything that doesn't require a GOT relocation. 4992 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 4993 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4994 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4995 !shouldEmitGOTReloc(GA->getGlobal()); 4996 } 4997 4998 static SDValue 4999 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5000 const SDLoc &DL, unsigned Offset, EVT PtrVT, 5001 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5002 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5003 // lowered to the following code sequence: 5004 // 5005 // For constant address space: 5006 // s_getpc_b64 s[0:1] 5007 // s_add_u32 s0, s0, $symbol 5008 // s_addc_u32 s1, s1, 0 5009 // 5010 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5011 // a fixup or relocation is emitted to replace $symbol with a literal 5012 // constant, which is a pc-relative offset from the encoding of the $symbol 5013 // operand to the global variable. 5014 // 5015 // For global address space: 5016 // s_getpc_b64 s[0:1] 5017 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5018 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5019 // 5020 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5021 // fixups or relocations are emitted to replace $symbol@*@lo and 5022 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5023 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5024 // operand to the global variable. 5025 // 5026 // What we want here is an offset from the value returned by s_getpc 5027 // (which is the address of the s_add_u32 instruction) to the global 5028 // variable, but since the encoding of $symbol starts 4 bytes after the start 5029 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5030 // small. This requires us to add 4 to the global variable offset in order to 5031 // compute the correct address. 5032 SDValue PtrLo = 5033 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5034 SDValue PtrHi; 5035 if (GAFlags == SIInstrInfo::MO_NONE) { 5036 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5037 } else { 5038 PtrHi = 5039 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5040 } 5041 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5042 } 5043 5044 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5045 SDValue Op, 5046 SelectionDAG &DAG) const { 5047 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5048 const GlobalValue *GV = GSD->getGlobal(); 5049 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5050 shouldUseLDSConstAddress(GV)) || 5051 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5052 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5053 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5054 5055 SDLoc DL(GSD); 5056 EVT PtrVT = Op.getValueType(); 5057 5058 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5059 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5060 SIInstrInfo::MO_ABS32_LO); 5061 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5062 } 5063 5064 if (shouldEmitFixup(GV)) 5065 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5066 else if (shouldEmitPCReloc(GV)) 5067 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5068 SIInstrInfo::MO_REL32); 5069 5070 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5071 SIInstrInfo::MO_GOTPCREL32); 5072 5073 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5074 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5075 const DataLayout &DataLayout = DAG.getDataLayout(); 5076 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 5077 MachinePointerInfo PtrInfo 5078 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5079 5080 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 5081 MachineMemOperand::MODereferenceable | 5082 MachineMemOperand::MOInvariant); 5083 } 5084 5085 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5086 const SDLoc &DL, SDValue V) const { 5087 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5088 // the destination register. 5089 // 5090 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5091 // so we will end up with redundant moves to m0. 5092 // 5093 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5094 5095 // A Null SDValue creates a glue result. 5096 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5097 V, Chain); 5098 return SDValue(M0, 0); 5099 } 5100 5101 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5102 SDValue Op, 5103 MVT VT, 5104 unsigned Offset) const { 5105 SDLoc SL(Op); 5106 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 5107 DAG.getEntryNode(), Offset, 4, false); 5108 // The local size values will have the hi 16-bits as zero. 5109 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5110 DAG.getValueType(VT)); 5111 } 5112 5113 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5114 EVT VT) { 5115 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5116 "non-hsa intrinsic with hsa target", 5117 DL.getDebugLoc()); 5118 DAG.getContext()->diagnose(BadIntrin); 5119 return DAG.getUNDEF(VT); 5120 } 5121 5122 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5123 EVT VT) { 5124 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5125 "intrinsic not supported on subtarget", 5126 DL.getDebugLoc()); 5127 DAG.getContext()->diagnose(BadIntrin); 5128 return DAG.getUNDEF(VT); 5129 } 5130 5131 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5132 ArrayRef<SDValue> Elts) { 5133 assert(!Elts.empty()); 5134 MVT Type; 5135 unsigned NumElts; 5136 5137 if (Elts.size() == 1) { 5138 Type = MVT::f32; 5139 NumElts = 1; 5140 } else if (Elts.size() == 2) { 5141 Type = MVT::v2f32; 5142 NumElts = 2; 5143 } else if (Elts.size() == 3) { 5144 Type = MVT::v3f32; 5145 NumElts = 3; 5146 } else if (Elts.size() <= 4) { 5147 Type = MVT::v4f32; 5148 NumElts = 4; 5149 } else if (Elts.size() <= 8) { 5150 Type = MVT::v8f32; 5151 NumElts = 8; 5152 } else { 5153 assert(Elts.size() <= 16); 5154 Type = MVT::v16f32; 5155 NumElts = 16; 5156 } 5157 5158 SmallVector<SDValue, 16> VecElts(NumElts); 5159 for (unsigned i = 0; i < Elts.size(); ++i) { 5160 SDValue Elt = Elts[i]; 5161 if (Elt.getValueType() != MVT::f32) 5162 Elt = DAG.getBitcast(MVT::f32, Elt); 5163 VecElts[i] = Elt; 5164 } 5165 for (unsigned i = Elts.size(); i < NumElts; ++i) 5166 VecElts[i] = DAG.getUNDEF(MVT::f32); 5167 5168 if (NumElts == 1) 5169 return VecElts[0]; 5170 return DAG.getBuildVector(Type, DL, VecElts); 5171 } 5172 5173 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5174 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5175 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5176 5177 uint64_t Value = CachePolicyConst->getZExtValue(); 5178 SDLoc DL(CachePolicy); 5179 if (GLC) { 5180 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5181 Value &= ~(uint64_t)0x1; 5182 } 5183 if (SLC) { 5184 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5185 Value &= ~(uint64_t)0x2; 5186 } 5187 if (DLC) { 5188 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5189 Value &= ~(uint64_t)0x4; 5190 } 5191 5192 return Value == 0; 5193 } 5194 5195 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5196 SDValue Src, int ExtraElts) { 5197 EVT SrcVT = Src.getValueType(); 5198 5199 SmallVector<SDValue, 8> Elts; 5200 5201 if (SrcVT.isVector()) 5202 DAG.ExtractVectorElements(Src, Elts); 5203 else 5204 Elts.push_back(Src); 5205 5206 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5207 while (ExtraElts--) 5208 Elts.push_back(Undef); 5209 5210 return DAG.getBuildVector(CastVT, DL, Elts); 5211 } 5212 5213 // Re-construct the required return value for a image load intrinsic. 5214 // This is more complicated due to the optional use TexFailCtrl which means the required 5215 // return type is an aggregate 5216 static SDValue constructRetValue(SelectionDAG &DAG, 5217 MachineSDNode *Result, 5218 ArrayRef<EVT> ResultTypes, 5219 bool IsTexFail, bool Unpacked, bool IsD16, 5220 int DMaskPop, int NumVDataDwords, 5221 const SDLoc &DL, LLVMContext &Context) { 5222 // Determine the required return type. This is the same regardless of IsTexFail flag 5223 EVT ReqRetVT = ResultTypes[0]; 5224 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5225 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5226 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5227 5228 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5229 DMaskPop : (DMaskPop + 1) / 2; 5230 5231 MVT DataDwordVT = NumDataDwords == 1 ? 5232 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5233 5234 MVT MaskPopVT = MaskPopDwords == 1 ? 5235 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5236 5237 SDValue Data(Result, 0); 5238 SDValue TexFail; 5239 5240 if (IsTexFail) { 5241 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5242 if (MaskPopVT.isVector()) { 5243 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5244 SDValue(Result, 0), ZeroIdx); 5245 } else { 5246 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5247 SDValue(Result, 0), ZeroIdx); 5248 } 5249 5250 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5251 SDValue(Result, 0), 5252 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5253 } 5254 5255 if (DataDwordVT.isVector()) 5256 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5257 NumDataDwords - MaskPopDwords); 5258 5259 if (IsD16) 5260 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5261 5262 if (!ReqRetVT.isVector()) 5263 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5264 5265 Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data); 5266 5267 if (TexFail) 5268 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5269 5270 if (Result->getNumValues() == 1) 5271 return Data; 5272 5273 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5274 } 5275 5276 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5277 SDValue *LWE, bool &IsTexFail) { 5278 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5279 5280 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5281 if (Value) { 5282 IsTexFail = true; 5283 } 5284 5285 SDLoc DL(TexFailCtrlConst); 5286 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5287 Value &= ~(uint64_t)0x1; 5288 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5289 Value &= ~(uint64_t)0x2; 5290 5291 return Value == 0; 5292 } 5293 5294 SDValue SITargetLowering::lowerImage(SDValue Op, 5295 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5296 SelectionDAG &DAG) const { 5297 SDLoc DL(Op); 5298 MachineFunction &MF = DAG.getMachineFunction(); 5299 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5300 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5301 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5302 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5303 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5304 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5305 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5306 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5307 unsigned IntrOpcode = Intr->BaseOpcode; 5308 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5309 5310 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5311 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5312 bool IsD16 = false; 5313 bool IsA16 = false; 5314 SDValue VData; 5315 int NumVDataDwords; 5316 bool AdjustRetType = false; 5317 5318 unsigned AddrIdx; // Index of first address argument 5319 unsigned DMask; 5320 unsigned DMaskLanes = 0; 5321 5322 if (BaseOpcode->Atomic) { 5323 VData = Op.getOperand(2); 5324 5325 bool Is64Bit = VData.getValueType() == MVT::i64; 5326 if (BaseOpcode->AtomicX2) { 5327 SDValue VData2 = Op.getOperand(3); 5328 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5329 {VData, VData2}); 5330 if (Is64Bit) 5331 VData = DAG.getBitcast(MVT::v4i32, VData); 5332 5333 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5334 DMask = Is64Bit ? 0xf : 0x3; 5335 NumVDataDwords = Is64Bit ? 4 : 2; 5336 AddrIdx = 4; 5337 } else { 5338 DMask = Is64Bit ? 0x3 : 0x1; 5339 NumVDataDwords = Is64Bit ? 2 : 1; 5340 AddrIdx = 3; 5341 } 5342 } else { 5343 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5344 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5345 DMask = DMaskConst->getZExtValue(); 5346 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5347 5348 if (BaseOpcode->Store) { 5349 VData = Op.getOperand(2); 5350 5351 MVT StoreVT = VData.getSimpleValueType(); 5352 if (StoreVT.getScalarType() == MVT::f16) { 5353 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5354 return Op; // D16 is unsupported for this instruction 5355 5356 IsD16 = true; 5357 VData = handleD16VData(VData, DAG); 5358 } 5359 5360 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5361 } else { 5362 // Work out the num dwords based on the dmask popcount and underlying type 5363 // and whether packing is supported. 5364 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5365 if (LoadVT.getScalarType() == MVT::f16) { 5366 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5367 return Op; // D16 is unsupported for this instruction 5368 5369 IsD16 = true; 5370 } 5371 5372 // Confirm that the return type is large enough for the dmask specified 5373 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5374 (!LoadVT.isVector() && DMaskLanes > 1)) 5375 return Op; 5376 5377 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5378 NumVDataDwords = (DMaskLanes + 1) / 2; 5379 else 5380 NumVDataDwords = DMaskLanes; 5381 5382 AdjustRetType = true; 5383 } 5384 5385 AddrIdx = DMaskIdx + 1; 5386 } 5387 5388 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5389 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5390 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5391 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5392 NumCoords + NumLCM; 5393 unsigned NumMIVAddrs = NumVAddrs; 5394 5395 SmallVector<SDValue, 4> VAddrs; 5396 5397 // Optimize _L to _LZ when _L is zero 5398 if (LZMappingInfo) { 5399 if (auto ConstantLod = 5400 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5401 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5402 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5403 NumMIVAddrs--; // remove 'lod' 5404 } 5405 } 5406 } 5407 5408 // Optimize _mip away, when 'lod' is zero 5409 if (MIPMappingInfo) { 5410 if (auto ConstantLod = 5411 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5412 if (ConstantLod->isNullValue()) { 5413 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5414 NumMIVAddrs--; // remove 'lod' 5415 } 5416 } 5417 } 5418 5419 // Check for 16 bit addresses and pack if true. 5420 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5421 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5422 const MVT VAddrScalarVT = VAddrVT.getScalarType(); 5423 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) { 5424 // Illegal to use a16 images 5425 if (!ST->hasFeature(AMDGPU::FeatureR128A16) && !ST->hasFeature(AMDGPU::FeatureGFX10A16)) 5426 return Op; 5427 5428 IsA16 = true; 5429 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5430 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) { 5431 SDValue AddrLo; 5432 // Push back extra arguments. 5433 if (i < DimIdx) { 5434 AddrLo = Op.getOperand(i); 5435 } else { 5436 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, 5437 // in 1D, derivatives dx/dh and dx/dv are packed with undef. 5438 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) || 5439 ((NumGradients / 2) % 2 == 1 && 5440 (i == DimIdx + (NumGradients / 2) - 1 || 5441 i == DimIdx + NumGradients - 1))) { 5442 AddrLo = Op.getOperand(i); 5443 if (AddrLo.getValueType() != MVT::i16) 5444 AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i)); 5445 AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo); 5446 } else { 5447 AddrLo = DAG.getBuildVector(VectorVT, DL, 5448 {Op.getOperand(i), Op.getOperand(i + 1)}); 5449 i++; 5450 } 5451 AddrLo = DAG.getBitcast(MVT::f32, AddrLo); 5452 } 5453 VAddrs.push_back(AddrLo); 5454 } 5455 } else { 5456 for (unsigned i = 0; i < NumMIVAddrs; ++i) 5457 VAddrs.push_back(Op.getOperand(AddrIdx + i)); 5458 } 5459 5460 // If the register allocator cannot place the address registers contiguously 5461 // without introducing moves, then using the non-sequential address encoding 5462 // is always preferable, since it saves VALU instructions and is usually a 5463 // wash in terms of code size or even better. 5464 // 5465 // However, we currently have no way of hinting to the register allocator that 5466 // MIMG addresses should be placed contiguously when it is possible to do so, 5467 // so force non-NSA for the common 2-address case as a heuristic. 5468 // 5469 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5470 // allocation when possible. 5471 bool UseNSA = 5472 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5473 SDValue VAddr; 5474 if (!UseNSA) 5475 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5476 5477 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5478 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5479 unsigned CtrlIdx; // Index of texfailctrl argument 5480 SDValue Unorm; 5481 if (!BaseOpcode->Sampler) { 5482 Unorm = True; 5483 CtrlIdx = AddrIdx + NumVAddrs + 1; 5484 } else { 5485 auto UnormConst = 5486 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 5487 5488 Unorm = UnormConst->getZExtValue() ? True : False; 5489 CtrlIdx = AddrIdx + NumVAddrs + 3; 5490 } 5491 5492 SDValue TFE; 5493 SDValue LWE; 5494 SDValue TexFail = Op.getOperand(CtrlIdx); 5495 bool IsTexFail = false; 5496 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 5497 return Op; 5498 5499 if (IsTexFail) { 5500 if (!DMaskLanes) { 5501 // Expecting to get an error flag since TFC is on - and dmask is 0 5502 // Force dmask to be at least 1 otherwise the instruction will fail 5503 DMask = 0x1; 5504 DMaskLanes = 1; 5505 NumVDataDwords = 1; 5506 } 5507 NumVDataDwords += 1; 5508 AdjustRetType = true; 5509 } 5510 5511 // Has something earlier tagged that the return type needs adjusting 5512 // This happens if the instruction is a load or has set TexFailCtrl flags 5513 if (AdjustRetType) { 5514 // NumVDataDwords reflects the true number of dwords required in the return type 5515 if (DMaskLanes == 0 && !BaseOpcode->Store) { 5516 // This is a no-op load. This can be eliminated 5517 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 5518 if (isa<MemSDNode>(Op)) 5519 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 5520 return Undef; 5521 } 5522 5523 EVT NewVT = NumVDataDwords > 1 ? 5524 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 5525 : MVT::i32; 5526 5527 ResultTypes[0] = NewVT; 5528 if (ResultTypes.size() == 3) { 5529 // Original result was aggregate type used for TexFailCtrl results 5530 // The actual instruction returns as a vector type which has now been 5531 // created. Remove the aggregate result. 5532 ResultTypes.erase(&ResultTypes[1]); 5533 } 5534 } 5535 5536 SDValue GLC; 5537 SDValue SLC; 5538 SDValue DLC; 5539 if (BaseOpcode->Atomic) { 5540 GLC = True; // TODO no-return optimization 5541 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 5542 IsGFX10 ? &DLC : nullptr)) 5543 return Op; 5544 } else { 5545 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 5546 IsGFX10 ? &DLC : nullptr)) 5547 return Op; 5548 } 5549 5550 SmallVector<SDValue, 26> Ops; 5551 if (BaseOpcode->Store || BaseOpcode->Atomic) 5552 Ops.push_back(VData); // vdata 5553 if (UseNSA) { 5554 for (const SDValue &Addr : VAddrs) 5555 Ops.push_back(Addr); 5556 } else { 5557 Ops.push_back(VAddr); 5558 } 5559 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 5560 if (BaseOpcode->Sampler) 5561 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 5562 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 5563 if (IsGFX10) 5564 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 5565 Ops.push_back(Unorm); 5566 if (IsGFX10) 5567 Ops.push_back(DLC); 5568 Ops.push_back(GLC); 5569 Ops.push_back(SLC); 5570 Ops.push_back(IsA16 && // r128, a16 for gfx9 5571 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 5572 if (IsGFX10) 5573 Ops.push_back(IsA16 ? True : False); 5574 Ops.push_back(TFE); 5575 Ops.push_back(LWE); 5576 if (!IsGFX10) 5577 Ops.push_back(DimInfo->DA ? True : False); 5578 if (BaseOpcode->HasD16) 5579 Ops.push_back(IsD16 ? True : False); 5580 if (isa<MemSDNode>(Op)) 5581 Ops.push_back(Op.getOperand(0)); // chain 5582 5583 int NumVAddrDwords = 5584 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 5585 int Opcode = -1; 5586 5587 if (IsGFX10) { 5588 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 5589 UseNSA ? AMDGPU::MIMGEncGfx10NSA 5590 : AMDGPU::MIMGEncGfx10Default, 5591 NumVDataDwords, NumVAddrDwords); 5592 } else { 5593 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5594 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 5595 NumVDataDwords, NumVAddrDwords); 5596 if (Opcode == -1) 5597 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 5598 NumVDataDwords, NumVAddrDwords); 5599 } 5600 assert(Opcode != -1); 5601 5602 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 5603 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 5604 MachineMemOperand *MemRef = MemOp->getMemOperand(); 5605 DAG.setNodeMemRefs(NewNode, {MemRef}); 5606 } 5607 5608 if (BaseOpcode->AtomicX2) { 5609 SmallVector<SDValue, 1> Elt; 5610 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 5611 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 5612 } else if (!BaseOpcode->Store) { 5613 return constructRetValue(DAG, NewNode, 5614 OrigResultTypes, IsTexFail, 5615 Subtarget->hasUnpackedD16VMem(), IsD16, 5616 DMaskLanes, NumVDataDwords, DL, 5617 *DAG.getContext()); 5618 } 5619 5620 return SDValue(NewNode, 0); 5621 } 5622 5623 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 5624 SDValue Offset, SDValue CachePolicy, 5625 SelectionDAG &DAG) const { 5626 MachineFunction &MF = DAG.getMachineFunction(); 5627 5628 const DataLayout &DataLayout = DAG.getDataLayout(); 5629 unsigned Align = 5630 DataLayout.getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 5631 5632 MachineMemOperand *MMO = MF.getMachineMemOperand( 5633 MachinePointerInfo(), 5634 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 5635 MachineMemOperand::MOInvariant, 5636 VT.getStoreSize(), Align); 5637 5638 if (!Offset->isDivergent()) { 5639 SDValue Ops[] = { 5640 Rsrc, 5641 Offset, // Offset 5642 CachePolicy 5643 }; 5644 5645 // Widen vec3 load to vec4. 5646 if (VT.isVector() && VT.getVectorNumElements() == 3) { 5647 EVT WidenedVT = 5648 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 5649 auto WidenedOp = DAG.getMemIntrinsicNode( 5650 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 5651 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 5652 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 5653 DAG.getVectorIdxConstant(0, DL)); 5654 return Subvector; 5655 } 5656 5657 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 5658 DAG.getVTList(VT), Ops, VT, MMO); 5659 } 5660 5661 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 5662 // assume that the buffer is unswizzled. 5663 SmallVector<SDValue, 4> Loads; 5664 unsigned NumLoads = 1; 5665 MVT LoadVT = VT.getSimpleVT(); 5666 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 5667 assert((LoadVT.getScalarType() == MVT::i32 || 5668 LoadVT.getScalarType() == MVT::f32)); 5669 5670 if (NumElts == 8 || NumElts == 16) { 5671 NumLoads = NumElts / 4; 5672 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 5673 } 5674 5675 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 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 CachePolicy, // 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(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 5695 LoadVT, MMO, DAG)); 5696 } 5697 5698 if (NumElts == 8 || NumElts == 16) 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 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 5744 // This only makes sense to call in a kernel, so just lower to null. 5745 return DAG.getConstant(0, DL, VT); 5746 } 5747 5748 return getPreloadedValue(DAG, *MFI, VT, 5749 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 5750 } 5751 case Intrinsic::amdgcn_dispatch_id: { 5752 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 5753 } 5754 case Intrinsic::amdgcn_rcp: 5755 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 5756 case Intrinsic::amdgcn_rsq: 5757 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5758 case Intrinsic::amdgcn_rsq_legacy: 5759 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5760 return emitRemovedIntrinsicError(DAG, DL, VT); 5761 5762 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 5763 case Intrinsic::amdgcn_rcp_legacy: 5764 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5765 return emitRemovedIntrinsicError(DAG, DL, VT); 5766 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 5767 case Intrinsic::amdgcn_rsq_clamp: { 5768 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5769 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 5770 5771 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 5772 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 5773 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 5774 5775 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5776 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 5777 DAG.getConstantFP(Max, DL, VT)); 5778 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 5779 DAG.getConstantFP(Min, DL, VT)); 5780 } 5781 case Intrinsic::r600_read_ngroups_x: 5782 if (Subtarget->isAmdHsaOS()) 5783 return emitNonHSAIntrinsicError(DAG, DL, VT); 5784 5785 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5786 SI::KernelInputOffsets::NGROUPS_X, 4, false); 5787 case Intrinsic::r600_read_ngroups_y: 5788 if (Subtarget->isAmdHsaOS()) 5789 return emitNonHSAIntrinsicError(DAG, DL, VT); 5790 5791 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5792 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 5793 case Intrinsic::r600_read_ngroups_z: 5794 if (Subtarget->isAmdHsaOS()) 5795 return emitNonHSAIntrinsicError(DAG, DL, VT); 5796 5797 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5798 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 5799 case Intrinsic::r600_read_global_size_x: 5800 if (Subtarget->isAmdHsaOS()) 5801 return emitNonHSAIntrinsicError(DAG, DL, VT); 5802 5803 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5804 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 5805 case Intrinsic::r600_read_global_size_y: 5806 if (Subtarget->isAmdHsaOS()) 5807 return emitNonHSAIntrinsicError(DAG, DL, VT); 5808 5809 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5810 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 5811 case Intrinsic::r600_read_global_size_z: 5812 if (Subtarget->isAmdHsaOS()) 5813 return emitNonHSAIntrinsicError(DAG, DL, VT); 5814 5815 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5816 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 5817 case Intrinsic::r600_read_local_size_x: 5818 if (Subtarget->isAmdHsaOS()) 5819 return emitNonHSAIntrinsicError(DAG, DL, VT); 5820 5821 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5822 SI::KernelInputOffsets::LOCAL_SIZE_X); 5823 case Intrinsic::r600_read_local_size_y: 5824 if (Subtarget->isAmdHsaOS()) 5825 return emitNonHSAIntrinsicError(DAG, DL, VT); 5826 5827 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5828 SI::KernelInputOffsets::LOCAL_SIZE_Y); 5829 case Intrinsic::r600_read_local_size_z: 5830 if (Subtarget->isAmdHsaOS()) 5831 return emitNonHSAIntrinsicError(DAG, DL, VT); 5832 5833 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5834 SI::KernelInputOffsets::LOCAL_SIZE_Z); 5835 case Intrinsic::amdgcn_workgroup_id_x: 5836 return getPreloadedValue(DAG, *MFI, VT, 5837 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 5838 case Intrinsic::amdgcn_workgroup_id_y: 5839 return getPreloadedValue(DAG, *MFI, VT, 5840 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 5841 case Intrinsic::amdgcn_workgroup_id_z: 5842 return getPreloadedValue(DAG, *MFI, VT, 5843 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 5844 case Intrinsic::amdgcn_workitem_id_x: 5845 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5846 SDLoc(DAG.getEntryNode()), 5847 MFI->getArgInfo().WorkItemIDX); 5848 case Intrinsic::amdgcn_workitem_id_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 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5854 SDLoc(DAG.getEntryNode()), 5855 MFI->getArgInfo().WorkItemIDZ); 5856 case Intrinsic::amdgcn_wavefrontsize: 5857 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 5858 SDLoc(Op), MVT::i32); 5859 case Intrinsic::amdgcn_s_buffer_load: { 5860 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5861 SDValue GLC; 5862 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 5863 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 5864 IsGFX10 ? &DLC : nullptr)) 5865 return Op; 5866 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5867 DAG); 5868 } 5869 case Intrinsic::amdgcn_fdiv_fast: 5870 return lowerFDIV_FAST(Op, DAG); 5871 case Intrinsic::amdgcn_sin: 5872 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 5873 5874 case Intrinsic::amdgcn_cos: 5875 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 5876 5877 case Intrinsic::amdgcn_mul_u24: 5878 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5879 case Intrinsic::amdgcn_mul_i24: 5880 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5881 5882 case Intrinsic::amdgcn_log_clamp: { 5883 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5884 return SDValue(); 5885 5886 DiagnosticInfoUnsupported BadIntrin( 5887 MF.getFunction(), "intrinsic not supported on subtarget", 5888 DL.getDebugLoc()); 5889 DAG.getContext()->diagnose(BadIntrin); 5890 return DAG.getUNDEF(VT); 5891 } 5892 case Intrinsic::amdgcn_ldexp: 5893 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 5894 Op.getOperand(1), Op.getOperand(2)); 5895 5896 case Intrinsic::amdgcn_fract: 5897 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 5898 5899 case Intrinsic::amdgcn_class: 5900 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 5901 Op.getOperand(1), Op.getOperand(2)); 5902 case Intrinsic::amdgcn_div_fmas: 5903 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 5904 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5905 Op.getOperand(4)); 5906 5907 case Intrinsic::amdgcn_div_fixup: 5908 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 5909 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5910 5911 case Intrinsic::amdgcn_trig_preop: 5912 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 5913 Op.getOperand(1), Op.getOperand(2)); 5914 case Intrinsic::amdgcn_div_scale: { 5915 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 5916 5917 // Translate to the operands expected by the machine instruction. The 5918 // first parameter must be the same as the first instruction. 5919 SDValue Numerator = Op.getOperand(1); 5920 SDValue Denominator = Op.getOperand(2); 5921 5922 // Note this order is opposite of the machine instruction's operations, 5923 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 5924 // intrinsic has the numerator as the first operand to match a normal 5925 // division operation. 5926 5927 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 5928 5929 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 5930 Denominator, Numerator); 5931 } 5932 case Intrinsic::amdgcn_icmp: { 5933 // There is a Pat that handles this variant, so return it as-is. 5934 if (Op.getOperand(1).getValueType() == MVT::i1 && 5935 Op.getConstantOperandVal(2) == 0 && 5936 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 5937 return Op; 5938 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 5939 } 5940 case Intrinsic::amdgcn_fcmp: { 5941 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 5942 } 5943 case Intrinsic::amdgcn_fmed3: 5944 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 5945 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5946 case Intrinsic::amdgcn_fdot2: 5947 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 5948 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5949 Op.getOperand(4)); 5950 case Intrinsic::amdgcn_fmul_legacy: 5951 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 5952 Op.getOperand(1), Op.getOperand(2)); 5953 case Intrinsic::amdgcn_sffbh: 5954 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 5955 case Intrinsic::amdgcn_sbfe: 5956 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 5957 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5958 case Intrinsic::amdgcn_ubfe: 5959 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 5960 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5961 case Intrinsic::amdgcn_cvt_pkrtz: 5962 case Intrinsic::amdgcn_cvt_pknorm_i16: 5963 case Intrinsic::amdgcn_cvt_pknorm_u16: 5964 case Intrinsic::amdgcn_cvt_pk_i16: 5965 case Intrinsic::amdgcn_cvt_pk_u16: { 5966 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 5967 EVT VT = Op.getValueType(); 5968 unsigned Opcode; 5969 5970 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 5971 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 5972 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 5973 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 5974 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 5975 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 5976 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 5977 Opcode = AMDGPUISD::CVT_PK_I16_I32; 5978 else 5979 Opcode = AMDGPUISD::CVT_PK_U16_U32; 5980 5981 if (isTypeLegal(VT)) 5982 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5983 5984 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 5985 Op.getOperand(1), Op.getOperand(2)); 5986 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 5987 } 5988 case Intrinsic::amdgcn_fmad_ftz: 5989 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 5990 Op.getOperand(2), Op.getOperand(3)); 5991 5992 case Intrinsic::amdgcn_if_break: 5993 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 5994 Op->getOperand(1), Op->getOperand(2)), 0); 5995 5996 case Intrinsic::amdgcn_groupstaticsize: { 5997 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 5998 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 5999 return Op; 6000 6001 const Module *M = MF.getFunction().getParent(); 6002 const GlobalValue *GV = 6003 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6004 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6005 SIInstrInfo::MO_ABS32_LO); 6006 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6007 } 6008 case Intrinsic::amdgcn_is_shared: 6009 case Intrinsic::amdgcn_is_private: { 6010 SDLoc SL(Op); 6011 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6012 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6013 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6014 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6015 Op.getOperand(1)); 6016 6017 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6018 DAG.getConstant(1, SL, MVT::i32)); 6019 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6020 } 6021 case Intrinsic::amdgcn_alignbit: 6022 return DAG.getNode(ISD::FSHR, DL, VT, 6023 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6024 default: 6025 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6026 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6027 return lowerImage(Op, ImageDimIntr, DAG); 6028 6029 return Op; 6030 } 6031 } 6032 6033 // This function computes an appropriate offset to pass to 6034 // MachineMemOperand::setOffset() based on the offset inputs to 6035 // an intrinsic. If any of the offsets are non-contstant or 6036 // if VIndex is non-zero then this function returns 0. Otherwise, 6037 // it returns the sum of VOffset, SOffset, and Offset. 6038 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6039 SDValue SOffset, 6040 SDValue Offset, 6041 SDValue VIndex = SDValue()) { 6042 6043 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6044 !isa<ConstantSDNode>(Offset)) 6045 return 0; 6046 6047 if (VIndex) { 6048 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6049 return 0; 6050 } 6051 6052 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6053 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6054 cast<ConstantSDNode>(Offset)->getSExtValue(); 6055 } 6056 6057 static unsigned getDSShaderTypeValue(const MachineFunction &MF) { 6058 switch (MF.getFunction().getCallingConv()) { 6059 case CallingConv::AMDGPU_PS: 6060 return 1; 6061 case CallingConv::AMDGPU_VS: 6062 return 2; 6063 case CallingConv::AMDGPU_GS: 6064 return 3; 6065 case CallingConv::AMDGPU_HS: 6066 case CallingConv::AMDGPU_LS: 6067 case CallingConv::AMDGPU_ES: 6068 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6069 case CallingConv::AMDGPU_CS: 6070 case CallingConv::AMDGPU_KERNEL: 6071 case CallingConv::C: 6072 case CallingConv::Fast: 6073 default: 6074 // Assume other calling conventions are various compute callable functions 6075 return 0; 6076 } 6077 } 6078 6079 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6080 SelectionDAG &DAG) const { 6081 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6082 SDLoc DL(Op); 6083 6084 switch (IntrID) { 6085 case Intrinsic::amdgcn_ds_ordered_add: 6086 case Intrinsic::amdgcn_ds_ordered_swap: { 6087 MemSDNode *M = cast<MemSDNode>(Op); 6088 SDValue Chain = M->getOperand(0); 6089 SDValue M0 = M->getOperand(2); 6090 SDValue Value = M->getOperand(3); 6091 unsigned IndexOperand = M->getConstantOperandVal(7); 6092 unsigned WaveRelease = M->getConstantOperandVal(8); 6093 unsigned WaveDone = M->getConstantOperandVal(9); 6094 6095 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6096 IndexOperand &= ~0x3f; 6097 unsigned CountDw = 0; 6098 6099 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6100 CountDw = (IndexOperand >> 24) & 0xf; 6101 IndexOperand &= ~(0xf << 24); 6102 6103 if (CountDw < 1 || CountDw > 4) { 6104 report_fatal_error( 6105 "ds_ordered_count: dword count must be between 1 and 4"); 6106 } 6107 } 6108 6109 if (IndexOperand) 6110 report_fatal_error("ds_ordered_count: bad index operand"); 6111 6112 if (WaveDone && !WaveRelease) 6113 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6114 6115 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6116 unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction()); 6117 unsigned Offset0 = OrderedCountIndex << 2; 6118 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6119 (Instruction << 4); 6120 6121 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6122 Offset1 |= (CountDw - 1) << 6; 6123 6124 unsigned Offset = Offset0 | (Offset1 << 8); 6125 6126 SDValue Ops[] = { 6127 Chain, 6128 Value, 6129 DAG.getTargetConstant(Offset, DL, MVT::i16), 6130 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6131 }; 6132 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6133 M->getVTList(), Ops, M->getMemoryVT(), 6134 M->getMemOperand()); 6135 } 6136 case Intrinsic::amdgcn_ds_fadd: { 6137 MemSDNode *M = cast<MemSDNode>(Op); 6138 unsigned Opc; 6139 switch (IntrID) { 6140 case Intrinsic::amdgcn_ds_fadd: 6141 Opc = ISD::ATOMIC_LOAD_FADD; 6142 break; 6143 } 6144 6145 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6146 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6147 M->getMemOperand()); 6148 } 6149 case Intrinsic::amdgcn_atomic_inc: 6150 case Intrinsic::amdgcn_atomic_dec: 6151 case Intrinsic::amdgcn_ds_fmin: 6152 case Intrinsic::amdgcn_ds_fmax: { 6153 MemSDNode *M = cast<MemSDNode>(Op); 6154 unsigned Opc; 6155 switch (IntrID) { 6156 case Intrinsic::amdgcn_atomic_inc: 6157 Opc = AMDGPUISD::ATOMIC_INC; 6158 break; 6159 case Intrinsic::amdgcn_atomic_dec: 6160 Opc = AMDGPUISD::ATOMIC_DEC; 6161 break; 6162 case Intrinsic::amdgcn_ds_fmin: 6163 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6164 break; 6165 case Intrinsic::amdgcn_ds_fmax: 6166 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6167 break; 6168 default: 6169 llvm_unreachable("Unknown intrinsic!"); 6170 } 6171 SDValue Ops[] = { 6172 M->getOperand(0), // Chain 6173 M->getOperand(2), // Ptr 6174 M->getOperand(3) // Value 6175 }; 6176 6177 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6178 M->getMemoryVT(), M->getMemOperand()); 6179 } 6180 case Intrinsic::amdgcn_buffer_load: 6181 case Intrinsic::amdgcn_buffer_load_format: { 6182 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6183 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6184 unsigned IdxEn = 1; 6185 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6186 IdxEn = Idx->getZExtValue() != 0; 6187 SDValue Ops[] = { 6188 Op.getOperand(0), // Chain 6189 Op.getOperand(2), // rsrc 6190 Op.getOperand(3), // vindex 6191 SDValue(), // voffset -- will be set by setBufferOffsets 6192 SDValue(), // soffset -- will be set by setBufferOffsets 6193 SDValue(), // offset -- will be set by setBufferOffsets 6194 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6195 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6196 }; 6197 6198 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6199 // We don't know the offset if vindex is non-zero, so clear it. 6200 if (IdxEn) 6201 Offset = 0; 6202 6203 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6204 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6205 6206 EVT VT = Op.getValueType(); 6207 EVT IntVT = VT.changeTypeToInteger(); 6208 auto *M = cast<MemSDNode>(Op); 6209 M->getMemOperand()->setOffset(Offset); 6210 EVT LoadVT = Op.getValueType(); 6211 6212 if (LoadVT.getScalarType() == MVT::f16) 6213 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6214 M, DAG, Ops); 6215 6216 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6217 if (LoadVT.getScalarType() == MVT::i8 || 6218 LoadVT.getScalarType() == MVT::i16) 6219 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6220 6221 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6222 M->getMemOperand(), DAG); 6223 } 6224 case Intrinsic::amdgcn_raw_buffer_load: 6225 case Intrinsic::amdgcn_raw_buffer_load_format: { 6226 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6227 6228 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6229 SDValue Ops[] = { 6230 Op.getOperand(0), // Chain 6231 Op.getOperand(2), // rsrc 6232 DAG.getConstant(0, DL, MVT::i32), // vindex 6233 Offsets.first, // voffset 6234 Op.getOperand(4), // soffset 6235 Offsets.second, // offset 6236 Op.getOperand(5), // cachepolicy, swizzled buffer 6237 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6238 }; 6239 6240 auto *M = cast<MemSDNode>(Op); 6241 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6242 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6243 } 6244 case Intrinsic::amdgcn_struct_buffer_load: 6245 case Intrinsic::amdgcn_struct_buffer_load_format: { 6246 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6247 6248 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6249 SDValue Ops[] = { 6250 Op.getOperand(0), // Chain 6251 Op.getOperand(2), // rsrc 6252 Op.getOperand(3), // vindex 6253 Offsets.first, // voffset 6254 Op.getOperand(5), // soffset 6255 Offsets.second, // offset 6256 Op.getOperand(6), // cachepolicy, swizzled buffer 6257 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6258 }; 6259 6260 auto *M = cast<MemSDNode>(Op); 6261 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6262 Ops[2])); 6263 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6264 } 6265 case Intrinsic::amdgcn_tbuffer_load: { 6266 MemSDNode *M = cast<MemSDNode>(Op); 6267 EVT LoadVT = Op.getValueType(); 6268 6269 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6270 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6271 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6272 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6273 unsigned IdxEn = 1; 6274 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6275 IdxEn = Idx->getZExtValue() != 0; 6276 SDValue Ops[] = { 6277 Op.getOperand(0), // Chain 6278 Op.getOperand(2), // rsrc 6279 Op.getOperand(3), // vindex 6280 Op.getOperand(4), // voffset 6281 Op.getOperand(5), // soffset 6282 Op.getOperand(6), // offset 6283 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6284 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6285 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6286 }; 6287 6288 if (LoadVT.getScalarType() == MVT::f16) 6289 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6290 M, DAG, Ops); 6291 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6292 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6293 DAG); 6294 } 6295 case Intrinsic::amdgcn_raw_tbuffer_load: { 6296 MemSDNode *M = cast<MemSDNode>(Op); 6297 EVT LoadVT = Op.getValueType(); 6298 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6299 6300 SDValue Ops[] = { 6301 Op.getOperand(0), // Chain 6302 Op.getOperand(2), // rsrc 6303 DAG.getConstant(0, DL, MVT::i32), // vindex 6304 Offsets.first, // voffset 6305 Op.getOperand(4), // soffset 6306 Offsets.second, // offset 6307 Op.getOperand(5), // format 6308 Op.getOperand(6), // cachepolicy, swizzled buffer 6309 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6310 }; 6311 6312 if (LoadVT.getScalarType() == MVT::f16) 6313 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6314 M, DAG, Ops); 6315 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6316 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6317 DAG); 6318 } 6319 case Intrinsic::amdgcn_struct_tbuffer_load: { 6320 MemSDNode *M = cast<MemSDNode>(Op); 6321 EVT LoadVT = Op.getValueType(); 6322 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6323 6324 SDValue Ops[] = { 6325 Op.getOperand(0), // Chain 6326 Op.getOperand(2), // rsrc 6327 Op.getOperand(3), // vindex 6328 Offsets.first, // voffset 6329 Op.getOperand(5), // soffset 6330 Offsets.second, // offset 6331 Op.getOperand(6), // format 6332 Op.getOperand(7), // cachepolicy, swizzled buffer 6333 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6334 }; 6335 6336 if (LoadVT.getScalarType() == MVT::f16) 6337 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6338 M, DAG, Ops); 6339 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6340 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6341 DAG); 6342 } 6343 case Intrinsic::amdgcn_buffer_atomic_swap: 6344 case Intrinsic::amdgcn_buffer_atomic_add: 6345 case Intrinsic::amdgcn_buffer_atomic_sub: 6346 case Intrinsic::amdgcn_buffer_atomic_smin: 6347 case Intrinsic::amdgcn_buffer_atomic_umin: 6348 case Intrinsic::amdgcn_buffer_atomic_smax: 6349 case Intrinsic::amdgcn_buffer_atomic_umax: 6350 case Intrinsic::amdgcn_buffer_atomic_and: 6351 case Intrinsic::amdgcn_buffer_atomic_or: 6352 case Intrinsic::amdgcn_buffer_atomic_xor: { 6353 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6354 unsigned IdxEn = 1; 6355 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6356 IdxEn = Idx->getZExtValue() != 0; 6357 SDValue Ops[] = { 6358 Op.getOperand(0), // Chain 6359 Op.getOperand(2), // vdata 6360 Op.getOperand(3), // rsrc 6361 Op.getOperand(4), // vindex 6362 SDValue(), // voffset -- will be set by setBufferOffsets 6363 SDValue(), // soffset -- will be set by setBufferOffsets 6364 SDValue(), // offset -- will be set by setBufferOffsets 6365 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6366 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6367 }; 6368 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6369 // We don't know the offset if vindex is non-zero, so clear it. 6370 if (IdxEn) 6371 Offset = 0; 6372 EVT VT = Op.getValueType(); 6373 6374 auto *M = cast<MemSDNode>(Op); 6375 M->getMemOperand()->setOffset(Offset); 6376 unsigned Opcode = 0; 6377 6378 switch (IntrID) { 6379 case Intrinsic::amdgcn_buffer_atomic_swap: 6380 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6381 break; 6382 case Intrinsic::amdgcn_buffer_atomic_add: 6383 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6384 break; 6385 case Intrinsic::amdgcn_buffer_atomic_sub: 6386 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6387 break; 6388 case Intrinsic::amdgcn_buffer_atomic_smin: 6389 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6390 break; 6391 case Intrinsic::amdgcn_buffer_atomic_umin: 6392 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6393 break; 6394 case Intrinsic::amdgcn_buffer_atomic_smax: 6395 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6396 break; 6397 case Intrinsic::amdgcn_buffer_atomic_umax: 6398 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6399 break; 6400 case Intrinsic::amdgcn_buffer_atomic_and: 6401 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6402 break; 6403 case Intrinsic::amdgcn_buffer_atomic_or: 6404 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6405 break; 6406 case Intrinsic::amdgcn_buffer_atomic_xor: 6407 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6408 break; 6409 default: 6410 llvm_unreachable("unhandled atomic opcode"); 6411 } 6412 6413 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6414 M->getMemOperand()); 6415 } 6416 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6417 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6418 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6419 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6420 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6421 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6422 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6423 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6424 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6425 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6426 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6427 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 6428 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6429 SDValue Ops[] = { 6430 Op.getOperand(0), // Chain 6431 Op.getOperand(2), // vdata 6432 Op.getOperand(3), // rsrc 6433 DAG.getConstant(0, DL, MVT::i32), // vindex 6434 Offsets.first, // voffset 6435 Op.getOperand(5), // soffset 6436 Offsets.second, // offset 6437 Op.getOperand(6), // cachepolicy 6438 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6439 }; 6440 EVT VT = Op.getValueType(); 6441 6442 auto *M = cast<MemSDNode>(Op); 6443 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6444 unsigned Opcode = 0; 6445 6446 switch (IntrID) { 6447 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6448 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6449 break; 6450 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6451 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6452 break; 6453 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6454 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6455 break; 6456 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6457 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6458 break; 6459 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6460 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6461 break; 6462 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6463 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6464 break; 6465 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6466 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6467 break; 6468 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6469 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6470 break; 6471 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6472 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6473 break; 6474 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6475 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6476 break; 6477 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6478 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6479 break; 6480 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 6481 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6482 break; 6483 default: 6484 llvm_unreachable("unhandled atomic opcode"); 6485 } 6486 6487 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6488 M->getMemOperand()); 6489 } 6490 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6491 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6492 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6493 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6494 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6495 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6496 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6497 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6498 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6499 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6500 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6501 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 6502 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6503 SDValue Ops[] = { 6504 Op.getOperand(0), // Chain 6505 Op.getOperand(2), // vdata 6506 Op.getOperand(3), // rsrc 6507 Op.getOperand(4), // vindex 6508 Offsets.first, // voffset 6509 Op.getOperand(6), // soffset 6510 Offsets.second, // offset 6511 Op.getOperand(7), // cachepolicy 6512 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6513 }; 6514 EVT VT = Op.getValueType(); 6515 6516 auto *M = cast<MemSDNode>(Op); 6517 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6518 Ops[3])); 6519 unsigned Opcode = 0; 6520 6521 switch (IntrID) { 6522 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6523 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6524 break; 6525 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6526 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6527 break; 6528 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6529 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6530 break; 6531 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6532 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6533 break; 6534 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6535 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6536 break; 6537 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6538 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6539 break; 6540 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6541 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6542 break; 6543 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6544 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6545 break; 6546 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6547 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6548 break; 6549 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6550 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6551 break; 6552 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6553 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6554 break; 6555 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 6556 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6557 break; 6558 default: 6559 llvm_unreachable("unhandled atomic opcode"); 6560 } 6561 6562 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6563 M->getMemOperand()); 6564 } 6565 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 6566 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6567 unsigned IdxEn = 1; 6568 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 6569 IdxEn = Idx->getZExtValue() != 0; 6570 SDValue Ops[] = { 6571 Op.getOperand(0), // Chain 6572 Op.getOperand(2), // src 6573 Op.getOperand(3), // cmp 6574 Op.getOperand(4), // rsrc 6575 Op.getOperand(5), // vindex 6576 SDValue(), // voffset -- will be set by setBufferOffsets 6577 SDValue(), // soffset -- will be set by setBufferOffsets 6578 SDValue(), // offset -- will be set by setBufferOffsets 6579 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6580 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6581 }; 6582 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 6583 // We don't know the offset if vindex is non-zero, so clear it. 6584 if (IdxEn) 6585 Offset = 0; 6586 EVT VT = Op.getValueType(); 6587 auto *M = cast<MemSDNode>(Op); 6588 M->getMemOperand()->setOffset(Offset); 6589 6590 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6591 Op->getVTList(), Ops, VT, M->getMemOperand()); 6592 } 6593 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 6594 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6595 SDValue Ops[] = { 6596 Op.getOperand(0), // Chain 6597 Op.getOperand(2), // src 6598 Op.getOperand(3), // cmp 6599 Op.getOperand(4), // rsrc 6600 DAG.getConstant(0, DL, MVT::i32), // vindex 6601 Offsets.first, // voffset 6602 Op.getOperand(6), // soffset 6603 Offsets.second, // offset 6604 Op.getOperand(7), // cachepolicy 6605 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6606 }; 6607 EVT VT = Op.getValueType(); 6608 auto *M = cast<MemSDNode>(Op); 6609 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 6610 6611 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6612 Op->getVTList(), Ops, VT, M->getMemOperand()); 6613 } 6614 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 6615 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 6616 SDValue Ops[] = { 6617 Op.getOperand(0), // Chain 6618 Op.getOperand(2), // src 6619 Op.getOperand(3), // cmp 6620 Op.getOperand(4), // rsrc 6621 Op.getOperand(5), // vindex 6622 Offsets.first, // voffset 6623 Op.getOperand(7), // soffset 6624 Offsets.second, // offset 6625 Op.getOperand(8), // cachepolicy 6626 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6627 }; 6628 EVT VT = Op.getValueType(); 6629 auto *M = cast<MemSDNode>(Op); 6630 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 6631 Ops[4])); 6632 6633 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6634 Op->getVTList(), Ops, VT, M->getMemOperand()); 6635 } 6636 6637 default: 6638 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6639 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 6640 return lowerImage(Op, ImageDimIntr, DAG); 6641 6642 return SDValue(); 6643 } 6644 } 6645 6646 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 6647 // dwordx4 if on SI. 6648 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 6649 SDVTList VTList, 6650 ArrayRef<SDValue> Ops, EVT MemVT, 6651 MachineMemOperand *MMO, 6652 SelectionDAG &DAG) const { 6653 EVT VT = VTList.VTs[0]; 6654 EVT WidenedVT = VT; 6655 EVT WidenedMemVT = MemVT; 6656 if (!Subtarget->hasDwordx3LoadStores() && 6657 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 6658 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 6659 WidenedVT.getVectorElementType(), 4); 6660 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 6661 WidenedMemVT.getVectorElementType(), 4); 6662 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 6663 } 6664 6665 assert(VTList.NumVTs == 2); 6666 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 6667 6668 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 6669 WidenedMemVT, MMO); 6670 if (WidenedVT != VT) { 6671 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 6672 DAG.getVectorIdxConstant(0, DL)); 6673 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 6674 } 6675 return NewOp; 6676 } 6677 6678 SDValue SITargetLowering::handleD16VData(SDValue VData, 6679 SelectionDAG &DAG) const { 6680 EVT StoreVT = VData.getValueType(); 6681 6682 // No change for f16 and legal vector D16 types. 6683 if (!StoreVT.isVector()) 6684 return VData; 6685 6686 SDLoc DL(VData); 6687 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 6688 6689 if (Subtarget->hasUnpackedD16VMem()) { 6690 // We need to unpack the packed data to store. 6691 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 6692 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 6693 6694 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 6695 StoreVT.getVectorNumElements()); 6696 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 6697 return DAG.UnrollVectorOp(ZExt.getNode()); 6698 } 6699 6700 assert(isTypeLegal(StoreVT)); 6701 return VData; 6702 } 6703 6704 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 6705 SelectionDAG &DAG) const { 6706 SDLoc DL(Op); 6707 SDValue Chain = Op.getOperand(0); 6708 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6709 MachineFunction &MF = DAG.getMachineFunction(); 6710 6711 switch (IntrinsicID) { 6712 case Intrinsic::amdgcn_exp_compr: { 6713 SDValue Src0 = Op.getOperand(4); 6714 SDValue Src1 = Op.getOperand(5); 6715 // Hack around illegal type on SI by directly selecting it. 6716 if (isTypeLegal(Src0.getValueType())) 6717 return SDValue(); 6718 6719 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 6720 SDValue Undef = DAG.getUNDEF(MVT::f32); 6721 const SDValue Ops[] = { 6722 Op.getOperand(2), // tgt 6723 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 6724 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 6725 Undef, // src2 6726 Undef, // src3 6727 Op.getOperand(7), // vm 6728 DAG.getTargetConstant(1, DL, MVT::i1), // compr 6729 Op.getOperand(3), // en 6730 Op.getOperand(0) // Chain 6731 }; 6732 6733 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 6734 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 6735 } 6736 case Intrinsic::amdgcn_s_barrier: { 6737 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 6738 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 6739 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 6740 if (WGSize <= ST.getWavefrontSize()) 6741 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 6742 Op.getOperand(0)), 0); 6743 } 6744 return SDValue(); 6745 }; 6746 case Intrinsic::amdgcn_tbuffer_store: { 6747 SDValue VData = Op.getOperand(2); 6748 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6749 if (IsD16) 6750 VData = handleD16VData(VData, DAG); 6751 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6752 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6753 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6754 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 6755 unsigned IdxEn = 1; 6756 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6757 IdxEn = Idx->getZExtValue() != 0; 6758 SDValue Ops[] = { 6759 Chain, 6760 VData, // vdata 6761 Op.getOperand(3), // rsrc 6762 Op.getOperand(4), // vindex 6763 Op.getOperand(5), // voffset 6764 Op.getOperand(6), // soffset 6765 Op.getOperand(7), // offset 6766 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6767 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6768 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 6769 }; 6770 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6771 AMDGPUISD::TBUFFER_STORE_FORMAT; 6772 MemSDNode *M = cast<MemSDNode>(Op); 6773 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6774 M->getMemoryVT(), M->getMemOperand()); 6775 } 6776 6777 case Intrinsic::amdgcn_struct_tbuffer_store: { 6778 SDValue VData = Op.getOperand(2); 6779 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6780 if (IsD16) 6781 VData = handleD16VData(VData, DAG); 6782 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6783 SDValue Ops[] = { 6784 Chain, 6785 VData, // vdata 6786 Op.getOperand(3), // rsrc 6787 Op.getOperand(4), // vindex 6788 Offsets.first, // voffset 6789 Op.getOperand(6), // soffset 6790 Offsets.second, // offset 6791 Op.getOperand(7), // format 6792 Op.getOperand(8), // cachepolicy, swizzled buffer 6793 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 6794 }; 6795 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6796 AMDGPUISD::TBUFFER_STORE_FORMAT; 6797 MemSDNode *M = cast<MemSDNode>(Op); 6798 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6799 M->getMemoryVT(), M->getMemOperand()); 6800 } 6801 6802 case Intrinsic::amdgcn_raw_tbuffer_store: { 6803 SDValue VData = Op.getOperand(2); 6804 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6805 if (IsD16) 6806 VData = handleD16VData(VData, DAG); 6807 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6808 SDValue Ops[] = { 6809 Chain, 6810 VData, // vdata 6811 Op.getOperand(3), // rsrc 6812 DAG.getConstant(0, DL, MVT::i32), // vindex 6813 Offsets.first, // voffset 6814 Op.getOperand(5), // soffset 6815 Offsets.second, // offset 6816 Op.getOperand(6), // format 6817 Op.getOperand(7), // cachepolicy, swizzled buffer 6818 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 6819 }; 6820 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6821 AMDGPUISD::TBUFFER_STORE_FORMAT; 6822 MemSDNode *M = cast<MemSDNode>(Op); 6823 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6824 M->getMemoryVT(), M->getMemOperand()); 6825 } 6826 6827 case Intrinsic::amdgcn_buffer_store: 6828 case Intrinsic::amdgcn_buffer_store_format: { 6829 SDValue VData = Op.getOperand(2); 6830 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6831 if (IsD16) 6832 VData = handleD16VData(VData, DAG); 6833 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6834 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6835 unsigned IdxEn = 1; 6836 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6837 IdxEn = Idx->getZExtValue() != 0; 6838 SDValue Ops[] = { 6839 Chain, 6840 VData, 6841 Op.getOperand(3), // rsrc 6842 Op.getOperand(4), // vindex 6843 SDValue(), // voffset -- will be set by setBufferOffsets 6844 SDValue(), // soffset -- will be set by setBufferOffsets 6845 SDValue(), // offset -- will be set by setBufferOffsets 6846 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6847 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6848 }; 6849 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6850 // We don't know the offset if vindex is non-zero, so clear it. 6851 if (IdxEn) 6852 Offset = 0; 6853 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 6854 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6855 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6856 MemSDNode *M = cast<MemSDNode>(Op); 6857 M->getMemOperand()->setOffset(Offset); 6858 6859 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6860 EVT VDataType = VData.getValueType().getScalarType(); 6861 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6862 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6863 6864 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6865 M->getMemoryVT(), M->getMemOperand()); 6866 } 6867 6868 case Intrinsic::amdgcn_raw_buffer_store: 6869 case Intrinsic::amdgcn_raw_buffer_store_format: { 6870 const bool IsFormat = 6871 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 6872 6873 SDValue VData = Op.getOperand(2); 6874 EVT VDataVT = VData.getValueType(); 6875 EVT EltType = VDataVT.getScalarType(); 6876 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 6877 if (IsD16) 6878 VData = handleD16VData(VData, DAG); 6879 6880 if (!isTypeLegal(VDataVT)) { 6881 VData = 6882 DAG.getNode(ISD::BITCAST, DL, 6883 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 6884 } 6885 6886 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6887 SDValue Ops[] = { 6888 Chain, 6889 VData, 6890 Op.getOperand(3), // rsrc 6891 DAG.getConstant(0, DL, MVT::i32), // vindex 6892 Offsets.first, // voffset 6893 Op.getOperand(5), // soffset 6894 Offsets.second, // offset 6895 Op.getOperand(6), // cachepolicy, swizzled buffer 6896 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6897 }; 6898 unsigned Opc = 6899 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 6900 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6901 MemSDNode *M = cast<MemSDNode>(Op); 6902 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6903 6904 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6905 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 6906 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 6907 6908 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6909 M->getMemoryVT(), M->getMemOperand()); 6910 } 6911 6912 case Intrinsic::amdgcn_struct_buffer_store: 6913 case Intrinsic::amdgcn_struct_buffer_store_format: { 6914 const bool IsFormat = 6915 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 6916 6917 SDValue VData = Op.getOperand(2); 6918 EVT VDataVT = VData.getValueType(); 6919 EVT EltType = VDataVT.getScalarType(); 6920 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 6921 6922 if (IsD16) 6923 VData = handleD16VData(VData, DAG); 6924 6925 if (!isTypeLegal(VDataVT)) { 6926 VData = 6927 DAG.getNode(ISD::BITCAST, DL, 6928 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 6929 } 6930 6931 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6932 SDValue Ops[] = { 6933 Chain, 6934 VData, 6935 Op.getOperand(3), // rsrc 6936 Op.getOperand(4), // vindex 6937 Offsets.first, // voffset 6938 Op.getOperand(6), // soffset 6939 Offsets.second, // offset 6940 Op.getOperand(7), // cachepolicy, swizzled buffer 6941 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6942 }; 6943 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 6944 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6945 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6946 MemSDNode *M = cast<MemSDNode>(Op); 6947 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6948 Ops[3])); 6949 6950 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6951 EVT VDataType = VData.getValueType().getScalarType(); 6952 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 6953 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6954 6955 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6956 M->getMemoryVT(), M->getMemOperand()); 6957 } 6958 6959 case Intrinsic::amdgcn_buffer_atomic_fadd: { 6960 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6961 unsigned IdxEn = 1; 6962 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6963 IdxEn = Idx->getZExtValue() != 0; 6964 SDValue Ops[] = { 6965 Chain, 6966 Op.getOperand(2), // vdata 6967 Op.getOperand(3), // rsrc 6968 Op.getOperand(4), // vindex 6969 SDValue(), // voffset -- will be set by setBufferOffsets 6970 SDValue(), // soffset -- will be set by setBufferOffsets 6971 SDValue(), // offset -- will be set by setBufferOffsets 6972 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6973 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6974 }; 6975 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6976 // We don't know the offset if vindex is non-zero, so clear it. 6977 if (IdxEn) 6978 Offset = 0; 6979 EVT VT = Op.getOperand(2).getValueType(); 6980 6981 auto *M = cast<MemSDNode>(Op); 6982 M->getMemOperand()->setOffset(Offset); 6983 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 6984 : AMDGPUISD::BUFFER_ATOMIC_FADD; 6985 6986 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6987 M->getMemOperand()); 6988 } 6989 6990 case Intrinsic::amdgcn_global_atomic_fadd: { 6991 SDValue Ops[] = { 6992 Chain, 6993 Op.getOperand(2), // ptr 6994 Op.getOperand(3) // vdata 6995 }; 6996 EVT VT = Op.getOperand(3).getValueType(); 6997 6998 auto *M = cast<MemSDNode>(Op); 6999 if (VT.isVector()) { 7000 return DAG.getMemIntrinsicNode( 7001 AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT, 7002 M->getMemOperand()); 7003 } 7004 7005 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7006 DAG.getVTList(VT, MVT::Other), Ops, 7007 M->getMemOperand()).getValue(1); 7008 } 7009 case Intrinsic::amdgcn_end_cf: 7010 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7011 Op->getOperand(2), Chain), 0); 7012 7013 default: { 7014 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7015 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7016 return lowerImage(Op, ImageDimIntr, DAG); 7017 7018 return Op; 7019 } 7020 } 7021 } 7022 7023 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7024 // offset (the offset that is included in bounds checking and swizzling, to be 7025 // split between the instruction's voffset and immoffset fields) and soffset 7026 // (the offset that is excluded from bounds checking and swizzling, to go in 7027 // the instruction's soffset field). This function takes the first kind of 7028 // offset and figures out how to split it between voffset and immoffset. 7029 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7030 SDValue Offset, SelectionDAG &DAG) const { 7031 SDLoc DL(Offset); 7032 const unsigned MaxImm = 4095; 7033 SDValue N0 = Offset; 7034 ConstantSDNode *C1 = nullptr; 7035 7036 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7037 N0 = SDValue(); 7038 else if (DAG.isBaseWithConstantOffset(N0)) { 7039 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7040 N0 = N0.getOperand(0); 7041 } 7042 7043 if (C1) { 7044 unsigned ImmOffset = C1->getZExtValue(); 7045 // If the immediate value is too big for the immoffset field, put the value 7046 // and -4096 into the immoffset field so that the value that is copied/added 7047 // for the voffset field is a multiple of 4096, and it stands more chance 7048 // of being CSEd with the copy/add for another similar load/store. 7049 // However, do not do that rounding down to a multiple of 4096 if that is a 7050 // negative number, as it appears to be illegal to have a negative offset 7051 // in the vgpr, even if adding the immediate offset makes it positive. 7052 unsigned Overflow = ImmOffset & ~MaxImm; 7053 ImmOffset -= Overflow; 7054 if ((int32_t)Overflow < 0) { 7055 Overflow += ImmOffset; 7056 ImmOffset = 0; 7057 } 7058 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7059 if (Overflow) { 7060 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7061 if (!N0) 7062 N0 = OverflowVal; 7063 else { 7064 SDValue Ops[] = { N0, OverflowVal }; 7065 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7066 } 7067 } 7068 } 7069 if (!N0) 7070 N0 = DAG.getConstant(0, DL, MVT::i32); 7071 if (!C1) 7072 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7073 return {N0, SDValue(C1, 0)}; 7074 } 7075 7076 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7077 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7078 // pointed to by Offsets. 7079 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7080 SelectionDAG &DAG, SDValue *Offsets, 7081 unsigned Align) const { 7082 SDLoc DL(CombinedOffset); 7083 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7084 uint32_t Imm = C->getZExtValue(); 7085 uint32_t SOffset, ImmOffset; 7086 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 7087 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7088 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7089 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7090 return SOffset + ImmOffset; 7091 } 7092 } 7093 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7094 SDValue N0 = CombinedOffset.getOperand(0); 7095 SDValue N1 = CombinedOffset.getOperand(1); 7096 uint32_t SOffset, ImmOffset; 7097 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7098 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7099 Subtarget, Align)) { 7100 Offsets[0] = N0; 7101 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7102 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7103 return 0; 7104 } 7105 } 7106 Offsets[0] = CombinedOffset; 7107 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7108 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7109 return 0; 7110 } 7111 7112 // Handle 8 bit and 16 bit buffer loads 7113 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7114 EVT LoadVT, SDLoc DL, 7115 ArrayRef<SDValue> Ops, 7116 MemSDNode *M) const { 7117 EVT IntVT = LoadVT.changeTypeToInteger(); 7118 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7119 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7120 7121 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7122 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7123 Ops, IntVT, 7124 M->getMemOperand()); 7125 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7126 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7127 7128 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7129 } 7130 7131 // Handle 8 bit and 16 bit buffer stores 7132 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7133 EVT VDataType, SDLoc DL, 7134 SDValue Ops[], 7135 MemSDNode *M) const { 7136 if (VDataType == MVT::f16) 7137 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7138 7139 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7140 Ops[1] = BufferStoreExt; 7141 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7142 AMDGPUISD::BUFFER_STORE_SHORT; 7143 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7144 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7145 M->getMemOperand()); 7146 } 7147 7148 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7149 ISD::LoadExtType ExtType, SDValue Op, 7150 const SDLoc &SL, EVT VT) { 7151 if (VT.bitsLT(Op.getValueType())) 7152 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7153 7154 switch (ExtType) { 7155 case ISD::SEXTLOAD: 7156 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7157 case ISD::ZEXTLOAD: 7158 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7159 case ISD::EXTLOAD: 7160 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7161 case ISD::NON_EXTLOAD: 7162 return Op; 7163 } 7164 7165 llvm_unreachable("invalid ext type"); 7166 } 7167 7168 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7169 SelectionDAG &DAG = DCI.DAG; 7170 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7171 return SDValue(); 7172 7173 // FIXME: Constant loads should all be marked invariant. 7174 unsigned AS = Ld->getAddressSpace(); 7175 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7176 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7177 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7178 return SDValue(); 7179 7180 // Don't do this early, since it may interfere with adjacent load merging for 7181 // illegal types. We can avoid losing alignment information for exotic types 7182 // pre-legalize. 7183 EVT MemVT = Ld->getMemoryVT(); 7184 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7185 MemVT.getSizeInBits() >= 32) 7186 return SDValue(); 7187 7188 SDLoc SL(Ld); 7189 7190 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7191 "unexpected vector extload"); 7192 7193 // TODO: Drop only high part of range. 7194 SDValue Ptr = Ld->getBasePtr(); 7195 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7196 MVT::i32, SL, Ld->getChain(), Ptr, 7197 Ld->getOffset(), 7198 Ld->getPointerInfo(), MVT::i32, 7199 Ld->getAlignment(), 7200 Ld->getMemOperand()->getFlags(), 7201 Ld->getAAInfo(), 7202 nullptr); // Drop ranges 7203 7204 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7205 if (MemVT.isFloatingPoint()) { 7206 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7207 "unexpected fp extload"); 7208 TruncVT = MemVT.changeTypeToInteger(); 7209 } 7210 7211 SDValue Cvt = NewLoad; 7212 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7213 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7214 DAG.getValueType(TruncVT)); 7215 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7216 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7217 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7218 } else { 7219 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7220 } 7221 7222 EVT VT = Ld->getValueType(0); 7223 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7224 7225 DCI.AddToWorklist(Cvt.getNode()); 7226 7227 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7228 // the appropriate extension from the 32-bit load. 7229 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7230 DCI.AddToWorklist(Cvt.getNode()); 7231 7232 // Handle conversion back to floating point if necessary. 7233 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7234 7235 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7236 } 7237 7238 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7239 SDLoc DL(Op); 7240 LoadSDNode *Load = cast<LoadSDNode>(Op); 7241 ISD::LoadExtType ExtType = Load->getExtensionType(); 7242 EVT MemVT = Load->getMemoryVT(); 7243 7244 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7245 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7246 return SDValue(); 7247 7248 // FIXME: Copied from PPC 7249 // First, load into 32 bits, then truncate to 1 bit. 7250 7251 SDValue Chain = Load->getChain(); 7252 SDValue BasePtr = Load->getBasePtr(); 7253 MachineMemOperand *MMO = Load->getMemOperand(); 7254 7255 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7256 7257 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7258 BasePtr, RealMemVT, MMO); 7259 7260 if (!MemVT.isVector()) { 7261 SDValue Ops[] = { 7262 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7263 NewLD.getValue(1) 7264 }; 7265 7266 return DAG.getMergeValues(Ops, DL); 7267 } 7268 7269 SmallVector<SDValue, 3> Elts; 7270 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7271 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7272 DAG.getConstant(I, DL, MVT::i32)); 7273 7274 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7275 } 7276 7277 SDValue Ops[] = { 7278 DAG.getBuildVector(MemVT, DL, Elts), 7279 NewLD.getValue(1) 7280 }; 7281 7282 return DAG.getMergeValues(Ops, DL); 7283 } 7284 7285 if (!MemVT.isVector()) 7286 return SDValue(); 7287 7288 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7289 "Custom lowering for non-i32 vectors hasn't been implemented."); 7290 7291 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7292 MemVT, *Load->getMemOperand())) { 7293 SDValue Ops[2]; 7294 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7295 return DAG.getMergeValues(Ops, DL); 7296 } 7297 7298 unsigned Alignment = Load->getAlignment(); 7299 unsigned AS = Load->getAddressSpace(); 7300 if (Subtarget->hasLDSMisalignedBug() && 7301 AS == AMDGPUAS::FLAT_ADDRESS && 7302 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7303 return SplitVectorLoad(Op, DAG); 7304 } 7305 7306 MachineFunction &MF = DAG.getMachineFunction(); 7307 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7308 // If there is a possibilty that flat instruction access scratch memory 7309 // then we need to use the same legalization rules we use for private. 7310 if (AS == AMDGPUAS::FLAT_ADDRESS && 7311 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7312 AS = MFI->hasFlatScratchInit() ? 7313 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7314 7315 unsigned NumElements = MemVT.getVectorNumElements(); 7316 7317 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7318 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7319 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7320 if (MemVT.isPow2VectorType()) 7321 return SDValue(); 7322 if (NumElements == 3) 7323 return WidenVectorLoad(Op, DAG); 7324 return SplitVectorLoad(Op, DAG); 7325 } 7326 // Non-uniform loads will be selected to MUBUF instructions, so they 7327 // have the same legalization requirements as global and private 7328 // loads. 7329 // 7330 } 7331 7332 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7333 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7334 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7335 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7336 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 7337 Alignment >= 4 && NumElements < 32) { 7338 if (MemVT.isPow2VectorType()) 7339 return SDValue(); 7340 if (NumElements == 3) 7341 return WidenVectorLoad(Op, DAG); 7342 return SplitVectorLoad(Op, DAG); 7343 } 7344 // Non-uniform loads will be selected to MUBUF instructions, so they 7345 // have the same legalization requirements as global and private 7346 // loads. 7347 // 7348 } 7349 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7350 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7351 AS == AMDGPUAS::GLOBAL_ADDRESS || 7352 AS == AMDGPUAS::FLAT_ADDRESS) { 7353 if (NumElements > 4) 7354 return SplitVectorLoad(Op, DAG); 7355 // v3 loads not supported on SI. 7356 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7357 return WidenVectorLoad(Op, DAG); 7358 // v3 and v4 loads are supported for private and global memory. 7359 return SDValue(); 7360 } 7361 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7362 // Depending on the setting of the private_element_size field in the 7363 // resource descriptor, we can only make private accesses up to a certain 7364 // size. 7365 switch (Subtarget->getMaxPrivateElementSize()) { 7366 case 4: { 7367 SDValue Ops[2]; 7368 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7369 return DAG.getMergeValues(Ops, DL); 7370 } 7371 case 8: 7372 if (NumElements > 2) 7373 return SplitVectorLoad(Op, DAG); 7374 return SDValue(); 7375 case 16: 7376 // Same as global/flat 7377 if (NumElements > 4) 7378 return SplitVectorLoad(Op, DAG); 7379 // v3 loads not supported on SI. 7380 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7381 return WidenVectorLoad(Op, DAG); 7382 return SDValue(); 7383 default: 7384 llvm_unreachable("unsupported private_element_size"); 7385 } 7386 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7387 // Use ds_read_b128 if possible. 7388 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7389 MemVT.getStoreSize() == 16) 7390 return SDValue(); 7391 7392 if (NumElements > 2) 7393 return SplitVectorLoad(Op, DAG); 7394 7395 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7396 // address is negative, then the instruction is incorrectly treated as 7397 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7398 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7399 // load later in the SILoadStoreOptimizer. 7400 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7401 NumElements == 2 && MemVT.getStoreSize() == 8 && 7402 Load->getAlignment() < 8) { 7403 return SplitVectorLoad(Op, DAG); 7404 } 7405 } 7406 return SDValue(); 7407 } 7408 7409 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7410 EVT VT = Op.getValueType(); 7411 assert(VT.getSizeInBits() == 64); 7412 7413 SDLoc DL(Op); 7414 SDValue Cond = Op.getOperand(0); 7415 7416 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7417 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7418 7419 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7420 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7421 7422 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7423 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7424 7425 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7426 7427 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7428 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7429 7430 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7431 7432 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7433 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7434 } 7435 7436 // Catch division cases where we can use shortcuts with rcp and rsq 7437 // instructions. 7438 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7439 SelectionDAG &DAG) const { 7440 SDLoc SL(Op); 7441 SDValue LHS = Op.getOperand(0); 7442 SDValue RHS = Op.getOperand(1); 7443 EVT VT = Op.getValueType(); 7444 const SDNodeFlags Flags = Op->getFlags(); 7445 7446 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 7447 Flags.hasApproximateFuncs(); 7448 7449 // Without !fpmath accuracy information, we can't do more because we don't 7450 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 7451 if (!AllowInaccurateRcp) 7452 return SDValue(); 7453 7454 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7455 if (CLHS->isExactlyValue(1.0)) { 7456 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7457 // the CI documentation has a worst case error of 1 ulp. 7458 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7459 // use it as long as we aren't trying to use denormals. 7460 // 7461 // v_rcp_f16 and v_rsq_f16 DO support denormals. 7462 7463 // 1.0 / sqrt(x) -> rsq(x) 7464 7465 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 7466 // error seems really high at 2^29 ULP. 7467 if (RHS.getOpcode() == ISD::FSQRT) 7468 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 7469 7470 // 1.0 / x -> rcp(x) 7471 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7472 } 7473 7474 // Same as for 1.0, but expand the sign out of the constant. 7475 if (CLHS->isExactlyValue(-1.0)) { 7476 // -1.0 / x -> rcp (fneg x) 7477 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7478 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 7479 } 7480 } 7481 7482 // Turn into multiply by the reciprocal. 7483 // x / y -> x * (1.0 / y) 7484 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7485 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 7486 } 7487 7488 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7489 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 7490 if (GlueChain->getNumValues() <= 1) { 7491 return DAG.getNode(Opcode, SL, VT, A, B); 7492 } 7493 7494 assert(GlueChain->getNumValues() == 3); 7495 7496 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7497 switch (Opcode) { 7498 default: llvm_unreachable("no chain equivalent for opcode"); 7499 case ISD::FMUL: 7500 Opcode = AMDGPUISD::FMUL_W_CHAIN; 7501 break; 7502 } 7503 7504 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 7505 GlueChain.getValue(2)); 7506 } 7507 7508 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7509 EVT VT, SDValue A, SDValue B, SDValue C, 7510 SDValue GlueChain) { 7511 if (GlueChain->getNumValues() <= 1) { 7512 return DAG.getNode(Opcode, SL, VT, A, B, C); 7513 } 7514 7515 assert(GlueChain->getNumValues() == 3); 7516 7517 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7518 switch (Opcode) { 7519 default: llvm_unreachable("no chain equivalent for opcode"); 7520 case ISD::FMA: 7521 Opcode = AMDGPUISD::FMA_W_CHAIN; 7522 break; 7523 } 7524 7525 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 7526 GlueChain.getValue(2)); 7527 } 7528 7529 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 7530 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7531 return FastLowered; 7532 7533 SDLoc SL(Op); 7534 SDValue Src0 = Op.getOperand(0); 7535 SDValue Src1 = Op.getOperand(1); 7536 7537 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 7538 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 7539 7540 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 7541 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 7542 7543 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 7544 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 7545 7546 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 7547 } 7548 7549 // Faster 2.5 ULP division that does not support denormals. 7550 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 7551 SDLoc SL(Op); 7552 SDValue LHS = Op.getOperand(1); 7553 SDValue RHS = Op.getOperand(2); 7554 7555 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 7556 7557 const APFloat K0Val(BitsToFloat(0x6f800000)); 7558 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 7559 7560 const APFloat K1Val(BitsToFloat(0x2f800000)); 7561 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 7562 7563 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7564 7565 EVT SetCCVT = 7566 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 7567 7568 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 7569 7570 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 7571 7572 // TODO: Should this propagate fast-math-flags? 7573 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 7574 7575 // rcp does not support denormals. 7576 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 7577 7578 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 7579 7580 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 7581 } 7582 7583 // Returns immediate value for setting the F32 denorm mode when using the 7584 // S_DENORM_MODE instruction. 7585 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 7586 const SDLoc &SL, const GCNSubtarget *ST) { 7587 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 7588 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 7589 ? FP_DENORM_FLUSH_NONE 7590 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 7591 7592 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 7593 return DAG.getTargetConstant(Mode, SL, MVT::i32); 7594 } 7595 7596 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 7597 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7598 return FastLowered; 7599 7600 SDLoc SL(Op); 7601 SDValue LHS = Op.getOperand(0); 7602 SDValue RHS = Op.getOperand(1); 7603 7604 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7605 7606 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 7607 7608 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7609 RHS, RHS, LHS); 7610 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7611 LHS, RHS, LHS); 7612 7613 // Denominator is scaled to not be denormal, so using rcp is ok. 7614 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 7615 DenominatorScaled); 7616 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 7617 DenominatorScaled); 7618 7619 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 7620 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 7621 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 7622 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 7623 7624 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 7625 7626 if (!HasFP32Denormals) { 7627 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 7628 7629 SDValue EnableDenorm; 7630 if (Subtarget->hasDenormModeInst()) { 7631 const SDValue EnableDenormValue = 7632 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 7633 7634 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 7635 DAG.getEntryNode(), EnableDenormValue); 7636 } else { 7637 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 7638 SL, MVT::i32); 7639 EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 7640 DAG.getEntryNode(), EnableDenormValue, 7641 BitField); 7642 } 7643 7644 SDValue Ops[3] = { 7645 NegDivScale0, 7646 EnableDenorm.getValue(0), 7647 EnableDenorm.getValue(1) 7648 }; 7649 7650 NegDivScale0 = DAG.getMergeValues(Ops, SL); 7651 } 7652 7653 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 7654 ApproxRcp, One, NegDivScale0); 7655 7656 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 7657 ApproxRcp, Fma0); 7658 7659 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 7660 Fma1, Fma1); 7661 7662 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 7663 NumeratorScaled, Mul); 7664 7665 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 7666 7667 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 7668 NumeratorScaled, Fma3); 7669 7670 if (!HasFP32Denormals) { 7671 SDValue DisableDenorm; 7672 if (Subtarget->hasDenormModeInst()) { 7673 const SDValue DisableDenormValue = 7674 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 7675 7676 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 7677 Fma4.getValue(1), DisableDenormValue, 7678 Fma4.getValue(2)); 7679 } else { 7680 const SDValue DisableDenormValue = 7681 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 7682 7683 DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 7684 Fma4.getValue(1), DisableDenormValue, 7685 BitField, Fma4.getValue(2)); 7686 } 7687 7688 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 7689 DisableDenorm, DAG.getRoot()); 7690 DAG.setRoot(OutputChain); 7691 } 7692 7693 SDValue Scale = NumeratorScaled.getValue(1); 7694 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 7695 Fma4, Fma1, Fma3, Scale); 7696 7697 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 7698 } 7699 7700 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 7701 if (DAG.getTarget().Options.UnsafeFPMath) 7702 return lowerFastUnsafeFDIV(Op, DAG); 7703 7704 SDLoc SL(Op); 7705 SDValue X = Op.getOperand(0); 7706 SDValue Y = Op.getOperand(1); 7707 7708 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 7709 7710 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 7711 7712 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 7713 7714 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 7715 7716 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 7717 7718 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 7719 7720 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 7721 7722 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 7723 7724 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 7725 7726 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 7727 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 7728 7729 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 7730 NegDivScale0, Mul, DivScale1); 7731 7732 SDValue Scale; 7733 7734 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 7735 // Workaround a hardware bug on SI where the condition output from div_scale 7736 // is not usable. 7737 7738 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 7739 7740 // Figure out if the scale to use for div_fmas. 7741 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 7742 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 7743 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 7744 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 7745 7746 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 7747 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 7748 7749 SDValue Scale0Hi 7750 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 7751 SDValue Scale1Hi 7752 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 7753 7754 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 7755 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 7756 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 7757 } else { 7758 Scale = DivScale1.getValue(1); 7759 } 7760 7761 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 7762 Fma4, Fma3, Mul, Scale); 7763 7764 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 7765 } 7766 7767 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 7768 EVT VT = Op.getValueType(); 7769 7770 if (VT == MVT::f32) 7771 return LowerFDIV32(Op, DAG); 7772 7773 if (VT == MVT::f64) 7774 return LowerFDIV64(Op, DAG); 7775 7776 if (VT == MVT::f16) 7777 return LowerFDIV16(Op, DAG); 7778 7779 llvm_unreachable("Unexpected type for fdiv"); 7780 } 7781 7782 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7783 SDLoc DL(Op); 7784 StoreSDNode *Store = cast<StoreSDNode>(Op); 7785 EVT VT = Store->getMemoryVT(); 7786 7787 if (VT == MVT::i1) { 7788 return DAG.getTruncStore(Store->getChain(), DL, 7789 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 7790 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 7791 } 7792 7793 assert(VT.isVector() && 7794 Store->getValue().getValueType().getScalarType() == MVT::i32); 7795 7796 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7797 VT, *Store->getMemOperand())) { 7798 return expandUnalignedStore(Store, DAG); 7799 } 7800 7801 unsigned AS = Store->getAddressSpace(); 7802 if (Subtarget->hasLDSMisalignedBug() && 7803 AS == AMDGPUAS::FLAT_ADDRESS && 7804 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 7805 return SplitVectorStore(Op, DAG); 7806 } 7807 7808 MachineFunction &MF = DAG.getMachineFunction(); 7809 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7810 // If there is a possibilty that flat instruction access scratch memory 7811 // then we need to use the same legalization rules we use for private. 7812 if (AS == AMDGPUAS::FLAT_ADDRESS && 7813 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7814 AS = MFI->hasFlatScratchInit() ? 7815 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7816 7817 unsigned NumElements = VT.getVectorNumElements(); 7818 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 7819 AS == AMDGPUAS::FLAT_ADDRESS) { 7820 if (NumElements > 4) 7821 return SplitVectorStore(Op, DAG); 7822 // v3 stores not supported on SI. 7823 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7824 return SplitVectorStore(Op, DAG); 7825 return SDValue(); 7826 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7827 switch (Subtarget->getMaxPrivateElementSize()) { 7828 case 4: 7829 return scalarizeVectorStore(Store, DAG); 7830 case 8: 7831 if (NumElements > 2) 7832 return SplitVectorStore(Op, DAG); 7833 return SDValue(); 7834 case 16: 7835 if (NumElements > 4 || NumElements == 3) 7836 return SplitVectorStore(Op, DAG); 7837 return SDValue(); 7838 default: 7839 llvm_unreachable("unsupported private_element_size"); 7840 } 7841 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7842 // Use ds_write_b128 if possible. 7843 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 7844 VT.getStoreSize() == 16 && NumElements != 3) 7845 return SDValue(); 7846 7847 if (NumElements > 2) 7848 return SplitVectorStore(Op, DAG); 7849 7850 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7851 // address is negative, then the instruction is incorrectly treated as 7852 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7853 // stores here to avoid emitting ds_write2_b32. We may re-combine the 7854 // store later in the SILoadStoreOptimizer. 7855 if (!Subtarget->hasUsableDSOffset() && 7856 NumElements == 2 && VT.getStoreSize() == 8 && 7857 Store->getAlignment() < 8) { 7858 return SplitVectorStore(Op, DAG); 7859 } 7860 7861 return SDValue(); 7862 } else { 7863 llvm_unreachable("unhandled address space"); 7864 } 7865 } 7866 7867 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 7868 SDLoc DL(Op); 7869 EVT VT = Op.getValueType(); 7870 SDValue Arg = Op.getOperand(0); 7871 SDValue TrigVal; 7872 7873 // TODO: Should this propagate fast-math-flags? 7874 7875 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT); 7876 7877 if (Subtarget->hasTrigReducedRange()) { 7878 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7879 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal); 7880 } else { 7881 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7882 } 7883 7884 switch (Op.getOpcode()) { 7885 case ISD::FCOS: 7886 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal); 7887 case ISD::FSIN: 7888 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal); 7889 default: 7890 llvm_unreachable("Wrong trig opcode"); 7891 } 7892 } 7893 7894 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 7895 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 7896 assert(AtomicNode->isCompareAndSwap()); 7897 unsigned AS = AtomicNode->getAddressSpace(); 7898 7899 // No custom lowering required for local address space 7900 if (!isFlatGlobalAddrSpace(AS)) 7901 return Op; 7902 7903 // Non-local address space requires custom lowering for atomic compare 7904 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 7905 SDLoc DL(Op); 7906 SDValue ChainIn = Op.getOperand(0); 7907 SDValue Addr = Op.getOperand(1); 7908 SDValue Old = Op.getOperand(2); 7909 SDValue New = Op.getOperand(3); 7910 EVT VT = Op.getValueType(); 7911 MVT SimpleVT = VT.getSimpleVT(); 7912 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 7913 7914 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 7915 SDValue Ops[] = { ChainIn, Addr, NewOld }; 7916 7917 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 7918 Ops, VT, AtomicNode->getMemOperand()); 7919 } 7920 7921 //===----------------------------------------------------------------------===// 7922 // Custom DAG optimizations 7923 //===----------------------------------------------------------------------===// 7924 7925 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 7926 DAGCombinerInfo &DCI) const { 7927 EVT VT = N->getValueType(0); 7928 EVT ScalarVT = VT.getScalarType(); 7929 if (ScalarVT != MVT::f32) 7930 return SDValue(); 7931 7932 SelectionDAG &DAG = DCI.DAG; 7933 SDLoc DL(N); 7934 7935 SDValue Src = N->getOperand(0); 7936 EVT SrcVT = Src.getValueType(); 7937 7938 // TODO: We could try to match extracting the higher bytes, which would be 7939 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 7940 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 7941 // about in practice. 7942 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 7943 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 7944 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 7945 DCI.AddToWorklist(Cvt.getNode()); 7946 return Cvt; 7947 } 7948 } 7949 7950 return SDValue(); 7951 } 7952 7953 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 7954 7955 // This is a variant of 7956 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 7957 // 7958 // The normal DAG combiner will do this, but only if the add has one use since 7959 // that would increase the number of instructions. 7960 // 7961 // This prevents us from seeing a constant offset that can be folded into a 7962 // memory instruction's addressing mode. If we know the resulting add offset of 7963 // a pointer can be folded into an addressing offset, we can replace the pointer 7964 // operand with the add of new constant offset. This eliminates one of the uses, 7965 // and may allow the remaining use to also be simplified. 7966 // 7967 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 7968 unsigned AddrSpace, 7969 EVT MemVT, 7970 DAGCombinerInfo &DCI) const { 7971 SDValue N0 = N->getOperand(0); 7972 SDValue N1 = N->getOperand(1); 7973 7974 // We only do this to handle cases where it's profitable when there are 7975 // multiple uses of the add, so defer to the standard combine. 7976 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 7977 N0->hasOneUse()) 7978 return SDValue(); 7979 7980 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 7981 if (!CN1) 7982 return SDValue(); 7983 7984 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7985 if (!CAdd) 7986 return SDValue(); 7987 7988 // If the resulting offset is too large, we can't fold it into the addressing 7989 // mode offset. 7990 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 7991 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 7992 7993 AddrMode AM; 7994 AM.HasBaseReg = true; 7995 AM.BaseOffs = Offset.getSExtValue(); 7996 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 7997 return SDValue(); 7998 7999 SelectionDAG &DAG = DCI.DAG; 8000 SDLoc SL(N); 8001 EVT VT = N->getValueType(0); 8002 8003 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8004 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 8005 8006 SDNodeFlags Flags; 8007 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8008 (N0.getOpcode() == ISD::OR || 8009 N0->getFlags().hasNoUnsignedWrap())); 8010 8011 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8012 } 8013 8014 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8015 DAGCombinerInfo &DCI) const { 8016 SDValue Ptr = N->getBasePtr(); 8017 SelectionDAG &DAG = DCI.DAG; 8018 SDLoc SL(N); 8019 8020 // TODO: We could also do this for multiplies. 8021 if (Ptr.getOpcode() == ISD::SHL) { 8022 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8023 N->getMemoryVT(), DCI); 8024 if (NewPtr) { 8025 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8026 8027 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8028 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8029 } 8030 } 8031 8032 return SDValue(); 8033 } 8034 8035 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8036 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8037 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8038 (Opc == ISD::XOR && Val == 0); 8039 } 8040 8041 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8042 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8043 // integer combine opportunities since most 64-bit operations are decomposed 8044 // this way. TODO: We won't want this for SALU especially if it is an inline 8045 // immediate. 8046 SDValue SITargetLowering::splitBinaryBitConstantOp( 8047 DAGCombinerInfo &DCI, 8048 const SDLoc &SL, 8049 unsigned Opc, SDValue LHS, 8050 const ConstantSDNode *CRHS) const { 8051 uint64_t Val = CRHS->getZExtValue(); 8052 uint32_t ValLo = Lo_32(Val); 8053 uint32_t ValHi = Hi_32(Val); 8054 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8055 8056 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8057 bitOpWithConstantIsReducible(Opc, ValHi)) || 8058 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8059 // If we need to materialize a 64-bit immediate, it will be split up later 8060 // anyway. Avoid creating the harder to understand 64-bit immediate 8061 // materialization. 8062 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8063 } 8064 8065 return SDValue(); 8066 } 8067 8068 // Returns true if argument is a boolean value which is not serialized into 8069 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8070 static bool isBoolSGPR(SDValue V) { 8071 if (V.getValueType() != MVT::i1) 8072 return false; 8073 switch (V.getOpcode()) { 8074 default: break; 8075 case ISD::SETCC: 8076 case ISD::AND: 8077 case ISD::OR: 8078 case ISD::XOR: 8079 case AMDGPUISD::FP_CLASS: 8080 return true; 8081 } 8082 return false; 8083 } 8084 8085 // If a constant has all zeroes or all ones within each byte return it. 8086 // Otherwise return 0. 8087 static uint32_t getConstantPermuteMask(uint32_t C) { 8088 // 0xff for any zero byte in the mask 8089 uint32_t ZeroByteMask = 0; 8090 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8091 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8092 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8093 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8094 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8095 if ((NonZeroByteMask & C) != NonZeroByteMask) 8096 return 0; // Partial bytes selected. 8097 return C; 8098 } 8099 8100 // Check if a node selects whole bytes from its operand 0 starting at a byte 8101 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8102 // or -1 if not succeeded. 8103 // Note byte select encoding: 8104 // value 0-3 selects corresponding source byte; 8105 // value 0xc selects zero; 8106 // value 0xff selects 0xff. 8107 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8108 assert(V.getValueSizeInBits() == 32); 8109 8110 if (V.getNumOperands() != 2) 8111 return ~0; 8112 8113 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8114 if (!N1) 8115 return ~0; 8116 8117 uint32_t C = N1->getZExtValue(); 8118 8119 switch (V.getOpcode()) { 8120 default: 8121 break; 8122 case ISD::AND: 8123 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8124 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8125 } 8126 break; 8127 8128 case ISD::OR: 8129 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8130 return (0x03020100 & ~ConstMask) | ConstMask; 8131 } 8132 break; 8133 8134 case ISD::SHL: 8135 if (C % 8) 8136 return ~0; 8137 8138 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8139 8140 case ISD::SRL: 8141 if (C % 8) 8142 return ~0; 8143 8144 return uint32_t(0x0c0c0c0c03020100ull >> C); 8145 } 8146 8147 return ~0; 8148 } 8149 8150 SDValue SITargetLowering::performAndCombine(SDNode *N, 8151 DAGCombinerInfo &DCI) const { 8152 if (DCI.isBeforeLegalize()) 8153 return SDValue(); 8154 8155 SelectionDAG &DAG = DCI.DAG; 8156 EVT VT = N->getValueType(0); 8157 SDValue LHS = N->getOperand(0); 8158 SDValue RHS = N->getOperand(1); 8159 8160 8161 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8162 if (VT == MVT::i64 && CRHS) { 8163 if (SDValue Split 8164 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8165 return Split; 8166 } 8167 8168 if (CRHS && VT == MVT::i32) { 8169 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8170 // nb = number of trailing zeroes in mask 8171 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8172 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8173 uint64_t Mask = CRHS->getZExtValue(); 8174 unsigned Bits = countPopulation(Mask); 8175 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8176 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8177 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8178 unsigned Shift = CShift->getZExtValue(); 8179 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8180 unsigned Offset = NB + Shift; 8181 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8182 SDLoc SL(N); 8183 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8184 LHS->getOperand(0), 8185 DAG.getConstant(Offset, SL, MVT::i32), 8186 DAG.getConstant(Bits, SL, MVT::i32)); 8187 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8188 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8189 DAG.getValueType(NarrowVT)); 8190 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8191 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8192 return Shl; 8193 } 8194 } 8195 } 8196 8197 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8198 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8199 isa<ConstantSDNode>(LHS.getOperand(2))) { 8200 uint32_t Sel = getConstantPermuteMask(Mask); 8201 if (!Sel) 8202 return SDValue(); 8203 8204 // Select 0xc for all zero bytes 8205 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8206 SDLoc DL(N); 8207 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8208 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8209 } 8210 } 8211 8212 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8213 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8214 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8215 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8216 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8217 8218 SDValue X = LHS.getOperand(0); 8219 SDValue Y = RHS.getOperand(0); 8220 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8221 return SDValue(); 8222 8223 if (LCC == ISD::SETO) { 8224 if (X != LHS.getOperand(1)) 8225 return SDValue(); 8226 8227 if (RCC == ISD::SETUNE) { 8228 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8229 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8230 return SDValue(); 8231 8232 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8233 SIInstrFlags::N_SUBNORMAL | 8234 SIInstrFlags::N_ZERO | 8235 SIInstrFlags::P_ZERO | 8236 SIInstrFlags::P_SUBNORMAL | 8237 SIInstrFlags::P_NORMAL; 8238 8239 static_assert(((~(SIInstrFlags::S_NAN | 8240 SIInstrFlags::Q_NAN | 8241 SIInstrFlags::N_INFINITY | 8242 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8243 "mask not equal"); 8244 8245 SDLoc DL(N); 8246 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8247 X, DAG.getConstant(Mask, DL, MVT::i32)); 8248 } 8249 } 8250 } 8251 8252 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8253 std::swap(LHS, RHS); 8254 8255 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8256 RHS.hasOneUse()) { 8257 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8258 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8259 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8260 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8261 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8262 (RHS.getOperand(0) == LHS.getOperand(0) && 8263 LHS.getOperand(0) == LHS.getOperand(1))) { 8264 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8265 unsigned NewMask = LCC == ISD::SETO ? 8266 Mask->getZExtValue() & ~OrdMask : 8267 Mask->getZExtValue() & OrdMask; 8268 8269 SDLoc DL(N); 8270 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8271 DAG.getConstant(NewMask, DL, MVT::i32)); 8272 } 8273 } 8274 8275 if (VT == MVT::i32 && 8276 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8277 // and x, (sext cc from i1) => select cc, x, 0 8278 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8279 std::swap(LHS, RHS); 8280 if (isBoolSGPR(RHS.getOperand(0))) 8281 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8282 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8283 } 8284 8285 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8286 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8287 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8288 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8289 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8290 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8291 if (LHSMask != ~0u && RHSMask != ~0u) { 8292 // Canonicalize the expression in an attempt to have fewer unique masks 8293 // and therefore fewer registers used to hold the masks. 8294 if (LHSMask > RHSMask) { 8295 std::swap(LHSMask, RHSMask); 8296 std::swap(LHS, RHS); 8297 } 8298 8299 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8300 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8301 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8302 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8303 8304 // Check of we need to combine values from two sources within a byte. 8305 if (!(LHSUsedLanes & RHSUsedLanes) && 8306 // If we select high and lower word keep it for SDWA. 8307 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8308 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8309 // Each byte in each mask is either selector mask 0-3, or has higher 8310 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8311 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8312 // mask which is not 0xff wins. By anding both masks we have a correct 8313 // result except that 0x0c shall be corrected to give 0x0c only. 8314 uint32_t Mask = LHSMask & RHSMask; 8315 for (unsigned I = 0; I < 32; I += 8) { 8316 uint32_t ByteSel = 0xff << I; 8317 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8318 Mask &= (0x0c << I) & 0xffffffff; 8319 } 8320 8321 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8322 // or 0x0c. 8323 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8324 SDLoc DL(N); 8325 8326 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8327 LHS.getOperand(0), RHS.getOperand(0), 8328 DAG.getConstant(Sel, DL, MVT::i32)); 8329 } 8330 } 8331 } 8332 8333 return SDValue(); 8334 } 8335 8336 SDValue SITargetLowering::performOrCombine(SDNode *N, 8337 DAGCombinerInfo &DCI) const { 8338 SelectionDAG &DAG = DCI.DAG; 8339 SDValue LHS = N->getOperand(0); 8340 SDValue RHS = N->getOperand(1); 8341 8342 EVT VT = N->getValueType(0); 8343 if (VT == MVT::i1) { 8344 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8345 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8346 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8347 SDValue Src = LHS.getOperand(0); 8348 if (Src != RHS.getOperand(0)) 8349 return SDValue(); 8350 8351 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8352 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8353 if (!CLHS || !CRHS) 8354 return SDValue(); 8355 8356 // Only 10 bits are used. 8357 static const uint32_t MaxMask = 0x3ff; 8358 8359 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8360 SDLoc DL(N); 8361 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8362 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8363 } 8364 8365 return SDValue(); 8366 } 8367 8368 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8369 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8370 LHS.getOpcode() == AMDGPUISD::PERM && 8371 isa<ConstantSDNode>(LHS.getOperand(2))) { 8372 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8373 if (!Sel) 8374 return SDValue(); 8375 8376 Sel |= LHS.getConstantOperandVal(2); 8377 SDLoc DL(N); 8378 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8379 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8380 } 8381 8382 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8383 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8384 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8385 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8386 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8387 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8388 if (LHSMask != ~0u && RHSMask != ~0u) { 8389 // Canonicalize the expression in an attempt to have fewer unique masks 8390 // and therefore fewer registers used to hold the masks. 8391 if (LHSMask > RHSMask) { 8392 std::swap(LHSMask, RHSMask); 8393 std::swap(LHS, RHS); 8394 } 8395 8396 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8397 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8398 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8399 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8400 8401 // Check of we need to combine values from two sources within a byte. 8402 if (!(LHSUsedLanes & RHSUsedLanes) && 8403 // If we select high and lower word keep it for SDWA. 8404 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8405 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8406 // Kill zero bytes selected by other mask. Zero value is 0xc. 8407 LHSMask &= ~RHSUsedLanes; 8408 RHSMask &= ~LHSUsedLanes; 8409 // Add 4 to each active LHS lane 8410 LHSMask |= LHSUsedLanes & 0x04040404; 8411 // Combine masks 8412 uint32_t Sel = LHSMask | RHSMask; 8413 SDLoc DL(N); 8414 8415 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8416 LHS.getOperand(0), RHS.getOperand(0), 8417 DAG.getConstant(Sel, DL, MVT::i32)); 8418 } 8419 } 8420 } 8421 8422 if (VT != MVT::i64) 8423 return SDValue(); 8424 8425 // TODO: This could be a generic combine with a predicate for extracting the 8426 // high half of an integer being free. 8427 8428 // (or i64:x, (zero_extend i32:y)) -> 8429 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8430 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8431 RHS.getOpcode() != ISD::ZERO_EXTEND) 8432 std::swap(LHS, RHS); 8433 8434 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8435 SDValue ExtSrc = RHS.getOperand(0); 8436 EVT SrcVT = ExtSrc.getValueType(); 8437 if (SrcVT == MVT::i32) { 8438 SDLoc SL(N); 8439 SDValue LowLHS, HiBits; 8440 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 8441 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 8442 8443 DCI.AddToWorklist(LowOr.getNode()); 8444 DCI.AddToWorklist(HiBits.getNode()); 8445 8446 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 8447 LowOr, HiBits); 8448 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 8449 } 8450 } 8451 8452 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8453 if (CRHS) { 8454 if (SDValue Split 8455 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 8456 return Split; 8457 } 8458 8459 return SDValue(); 8460 } 8461 8462 SDValue SITargetLowering::performXorCombine(SDNode *N, 8463 DAGCombinerInfo &DCI) const { 8464 EVT VT = N->getValueType(0); 8465 if (VT != MVT::i64) 8466 return SDValue(); 8467 8468 SDValue LHS = N->getOperand(0); 8469 SDValue RHS = N->getOperand(1); 8470 8471 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8472 if (CRHS) { 8473 if (SDValue Split 8474 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 8475 return Split; 8476 } 8477 8478 return SDValue(); 8479 } 8480 8481 // Instructions that will be lowered with a final instruction that zeros the 8482 // high result bits. 8483 // XXX - probably only need to list legal operations. 8484 static bool fp16SrcZerosHighBits(unsigned Opc) { 8485 switch (Opc) { 8486 case ISD::FADD: 8487 case ISD::FSUB: 8488 case ISD::FMUL: 8489 case ISD::FDIV: 8490 case ISD::FREM: 8491 case ISD::FMA: 8492 case ISD::FMAD: 8493 case ISD::FCANONICALIZE: 8494 case ISD::FP_ROUND: 8495 case ISD::UINT_TO_FP: 8496 case ISD::SINT_TO_FP: 8497 case ISD::FABS: 8498 // Fabs is lowered to a bit operation, but it's an and which will clear the 8499 // high bits anyway. 8500 case ISD::FSQRT: 8501 case ISD::FSIN: 8502 case ISD::FCOS: 8503 case ISD::FPOWI: 8504 case ISD::FPOW: 8505 case ISD::FLOG: 8506 case ISD::FLOG2: 8507 case ISD::FLOG10: 8508 case ISD::FEXP: 8509 case ISD::FEXP2: 8510 case ISD::FCEIL: 8511 case ISD::FTRUNC: 8512 case ISD::FRINT: 8513 case ISD::FNEARBYINT: 8514 case ISD::FROUND: 8515 case ISD::FFLOOR: 8516 case ISD::FMINNUM: 8517 case ISD::FMAXNUM: 8518 case AMDGPUISD::FRACT: 8519 case AMDGPUISD::CLAMP: 8520 case AMDGPUISD::COS_HW: 8521 case AMDGPUISD::SIN_HW: 8522 case AMDGPUISD::FMIN3: 8523 case AMDGPUISD::FMAX3: 8524 case AMDGPUISD::FMED3: 8525 case AMDGPUISD::FMAD_FTZ: 8526 case AMDGPUISD::RCP: 8527 case AMDGPUISD::RSQ: 8528 case AMDGPUISD::RCP_IFLAG: 8529 case AMDGPUISD::LDEXP: 8530 return true; 8531 default: 8532 // fcopysign, select and others may be lowered to 32-bit bit operations 8533 // which don't zero the high bits. 8534 return false; 8535 } 8536 } 8537 8538 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 8539 DAGCombinerInfo &DCI) const { 8540 if (!Subtarget->has16BitInsts() || 8541 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8542 return SDValue(); 8543 8544 EVT VT = N->getValueType(0); 8545 if (VT != MVT::i32) 8546 return SDValue(); 8547 8548 SDValue Src = N->getOperand(0); 8549 if (Src.getValueType() != MVT::i16) 8550 return SDValue(); 8551 8552 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 8553 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 8554 if (Src.getOpcode() == ISD::BITCAST) { 8555 SDValue BCSrc = Src.getOperand(0); 8556 if (BCSrc.getValueType() == MVT::f16 && 8557 fp16SrcZerosHighBits(BCSrc.getOpcode())) 8558 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 8559 } 8560 8561 return SDValue(); 8562 } 8563 8564 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 8565 DAGCombinerInfo &DCI) 8566 const { 8567 SDValue Src = N->getOperand(0); 8568 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 8569 8570 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 8571 VTSign->getVT() == MVT::i8) || 8572 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 8573 VTSign->getVT() == MVT::i16)) && 8574 Src.hasOneUse()) { 8575 auto *M = cast<MemSDNode>(Src); 8576 SDValue Ops[] = { 8577 Src.getOperand(0), // Chain 8578 Src.getOperand(1), // rsrc 8579 Src.getOperand(2), // vindex 8580 Src.getOperand(3), // voffset 8581 Src.getOperand(4), // soffset 8582 Src.getOperand(5), // offset 8583 Src.getOperand(6), 8584 Src.getOperand(7) 8585 }; 8586 // replace with BUFFER_LOAD_BYTE/SHORT 8587 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 8588 Src.getOperand(0).getValueType()); 8589 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 8590 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 8591 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 8592 ResList, 8593 Ops, M->getMemoryVT(), 8594 M->getMemOperand()); 8595 return DCI.DAG.getMergeValues({BufferLoadSignExt, 8596 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 8597 } 8598 return SDValue(); 8599 } 8600 8601 SDValue SITargetLowering::performClassCombine(SDNode *N, 8602 DAGCombinerInfo &DCI) const { 8603 SelectionDAG &DAG = DCI.DAG; 8604 SDValue Mask = N->getOperand(1); 8605 8606 // fp_class x, 0 -> false 8607 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 8608 if (CMask->isNullValue()) 8609 return DAG.getConstant(0, SDLoc(N), MVT::i1); 8610 } 8611 8612 if (N->getOperand(0).isUndef()) 8613 return DAG.getUNDEF(MVT::i1); 8614 8615 return SDValue(); 8616 } 8617 8618 SDValue SITargetLowering::performRcpCombine(SDNode *N, 8619 DAGCombinerInfo &DCI) const { 8620 EVT VT = N->getValueType(0); 8621 SDValue N0 = N->getOperand(0); 8622 8623 if (N0.isUndef()) 8624 return N0; 8625 8626 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 8627 N0.getOpcode() == ISD::SINT_TO_FP)) { 8628 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 8629 N->getFlags()); 8630 } 8631 8632 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 8633 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 8634 N0.getOperand(0), N->getFlags()); 8635 } 8636 8637 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 8638 } 8639 8640 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 8641 unsigned MaxDepth) const { 8642 unsigned Opcode = Op.getOpcode(); 8643 if (Opcode == ISD::FCANONICALIZE) 8644 return true; 8645 8646 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8647 auto F = CFP->getValueAPF(); 8648 if (F.isNaN() && F.isSignaling()) 8649 return false; 8650 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 8651 } 8652 8653 // If source is a result of another standard FP operation it is already in 8654 // canonical form. 8655 if (MaxDepth == 0) 8656 return false; 8657 8658 switch (Opcode) { 8659 // These will flush denorms if required. 8660 case ISD::FADD: 8661 case ISD::FSUB: 8662 case ISD::FMUL: 8663 case ISD::FCEIL: 8664 case ISD::FFLOOR: 8665 case ISD::FMA: 8666 case ISD::FMAD: 8667 case ISD::FSQRT: 8668 case ISD::FDIV: 8669 case ISD::FREM: 8670 case ISD::FP_ROUND: 8671 case ISD::FP_EXTEND: 8672 case AMDGPUISD::FMUL_LEGACY: 8673 case AMDGPUISD::FMAD_FTZ: 8674 case AMDGPUISD::RCP: 8675 case AMDGPUISD::RSQ: 8676 case AMDGPUISD::RSQ_CLAMP: 8677 case AMDGPUISD::RCP_LEGACY: 8678 case AMDGPUISD::RSQ_LEGACY: 8679 case AMDGPUISD::RCP_IFLAG: 8680 case AMDGPUISD::TRIG_PREOP: 8681 case AMDGPUISD::DIV_SCALE: 8682 case AMDGPUISD::DIV_FMAS: 8683 case AMDGPUISD::DIV_FIXUP: 8684 case AMDGPUISD::FRACT: 8685 case AMDGPUISD::LDEXP: 8686 case AMDGPUISD::CVT_PKRTZ_F16_F32: 8687 case AMDGPUISD::CVT_F32_UBYTE0: 8688 case AMDGPUISD::CVT_F32_UBYTE1: 8689 case AMDGPUISD::CVT_F32_UBYTE2: 8690 case AMDGPUISD::CVT_F32_UBYTE3: 8691 return true; 8692 8693 // It can/will be lowered or combined as a bit operation. 8694 // Need to check their input recursively to handle. 8695 case ISD::FNEG: 8696 case ISD::FABS: 8697 case ISD::FCOPYSIGN: 8698 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8699 8700 case ISD::FSIN: 8701 case ISD::FCOS: 8702 case ISD::FSINCOS: 8703 return Op.getValueType().getScalarType() != MVT::f16; 8704 8705 case ISD::FMINNUM: 8706 case ISD::FMAXNUM: 8707 case ISD::FMINNUM_IEEE: 8708 case ISD::FMAXNUM_IEEE: 8709 case AMDGPUISD::CLAMP: 8710 case AMDGPUISD::FMED3: 8711 case AMDGPUISD::FMAX3: 8712 case AMDGPUISD::FMIN3: { 8713 // FIXME: Shouldn't treat the generic operations different based these. 8714 // However, we aren't really required to flush the result from 8715 // minnum/maxnum.. 8716 8717 // snans will be quieted, so we only need to worry about denormals. 8718 if (Subtarget->supportsMinMaxDenormModes() || 8719 denormalsEnabledForType(DAG, Op.getValueType())) 8720 return true; 8721 8722 // Flushing may be required. 8723 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 8724 // targets need to check their input recursively. 8725 8726 // FIXME: Does this apply with clamp? It's implemented with max. 8727 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 8728 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 8729 return false; 8730 } 8731 8732 return true; 8733 } 8734 case ISD::SELECT: { 8735 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 8736 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 8737 } 8738 case ISD::BUILD_VECTOR: { 8739 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 8740 SDValue SrcOp = Op.getOperand(i); 8741 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 8742 return false; 8743 } 8744 8745 return true; 8746 } 8747 case ISD::EXTRACT_VECTOR_ELT: 8748 case ISD::EXTRACT_SUBVECTOR: { 8749 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8750 } 8751 case ISD::INSERT_VECTOR_ELT: { 8752 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 8753 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 8754 } 8755 case ISD::UNDEF: 8756 // Could be anything. 8757 return false; 8758 8759 case ISD::BITCAST: { 8760 // Hack round the mess we make when legalizing extract_vector_elt 8761 SDValue Src = Op.getOperand(0); 8762 if (Src.getValueType() == MVT::i16 && 8763 Src.getOpcode() == ISD::TRUNCATE) { 8764 SDValue TruncSrc = Src.getOperand(0); 8765 if (TruncSrc.getValueType() == MVT::i32 && 8766 TruncSrc.getOpcode() == ISD::BITCAST && 8767 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 8768 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 8769 } 8770 } 8771 8772 return false; 8773 } 8774 case ISD::INTRINSIC_WO_CHAIN: { 8775 unsigned IntrinsicID 8776 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8777 // TODO: Handle more intrinsics 8778 switch (IntrinsicID) { 8779 case Intrinsic::amdgcn_cvt_pkrtz: 8780 case Intrinsic::amdgcn_cubeid: 8781 case Intrinsic::amdgcn_frexp_mant: 8782 case Intrinsic::amdgcn_fdot2: 8783 return true; 8784 default: 8785 break; 8786 } 8787 8788 LLVM_FALLTHROUGH; 8789 } 8790 default: 8791 return denormalsEnabledForType(DAG, Op.getValueType()) && 8792 DAG.isKnownNeverSNaN(Op); 8793 } 8794 8795 llvm_unreachable("invalid operation"); 8796 } 8797 8798 // Constant fold canonicalize. 8799 SDValue SITargetLowering::getCanonicalConstantFP( 8800 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 8801 // Flush denormals to 0 if not enabled. 8802 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 8803 return DAG.getConstantFP(0.0, SL, VT); 8804 8805 if (C.isNaN()) { 8806 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 8807 if (C.isSignaling()) { 8808 // Quiet a signaling NaN. 8809 // FIXME: Is this supposed to preserve payload bits? 8810 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8811 } 8812 8813 // Make sure it is the canonical NaN bitpattern. 8814 // 8815 // TODO: Can we use -1 as the canonical NaN value since it's an inline 8816 // immediate? 8817 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 8818 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8819 } 8820 8821 // Already canonical. 8822 return DAG.getConstantFP(C, SL, VT); 8823 } 8824 8825 static bool vectorEltWillFoldAway(SDValue Op) { 8826 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 8827 } 8828 8829 SDValue SITargetLowering::performFCanonicalizeCombine( 8830 SDNode *N, 8831 DAGCombinerInfo &DCI) const { 8832 SelectionDAG &DAG = DCI.DAG; 8833 SDValue N0 = N->getOperand(0); 8834 EVT VT = N->getValueType(0); 8835 8836 // fcanonicalize undef -> qnan 8837 if (N0.isUndef()) { 8838 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 8839 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 8840 } 8841 8842 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 8843 EVT VT = N->getValueType(0); 8844 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 8845 } 8846 8847 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 8848 // (fcanonicalize k) 8849 // 8850 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 8851 8852 // TODO: This could be better with wider vectors that will be split to v2f16, 8853 // and to consider uses since there aren't that many packed operations. 8854 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 8855 isTypeLegal(MVT::v2f16)) { 8856 SDLoc SL(N); 8857 SDValue NewElts[2]; 8858 SDValue Lo = N0.getOperand(0); 8859 SDValue Hi = N0.getOperand(1); 8860 EVT EltVT = Lo.getValueType(); 8861 8862 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 8863 for (unsigned I = 0; I != 2; ++I) { 8864 SDValue Op = N0.getOperand(I); 8865 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8866 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 8867 CFP->getValueAPF()); 8868 } else if (Op.isUndef()) { 8869 // Handled below based on what the other operand is. 8870 NewElts[I] = Op; 8871 } else { 8872 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 8873 } 8874 } 8875 8876 // If one half is undef, and one is constant, perfer a splat vector rather 8877 // than the normal qNaN. If it's a register, prefer 0.0 since that's 8878 // cheaper to use and may be free with a packed operation. 8879 if (NewElts[0].isUndef()) { 8880 if (isa<ConstantFPSDNode>(NewElts[1])) 8881 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 8882 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 8883 } 8884 8885 if (NewElts[1].isUndef()) { 8886 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 8887 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 8888 } 8889 8890 return DAG.getBuildVector(VT, SL, NewElts); 8891 } 8892 } 8893 8894 unsigned SrcOpc = N0.getOpcode(); 8895 8896 // If it's free to do so, push canonicalizes further up the source, which may 8897 // find a canonical source. 8898 // 8899 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 8900 // sNaNs. 8901 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 8902 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 8903 if (CRHS && N0.hasOneUse()) { 8904 SDLoc SL(N); 8905 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 8906 N0.getOperand(0)); 8907 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 8908 DCI.AddToWorklist(Canon0.getNode()); 8909 8910 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 8911 } 8912 } 8913 8914 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 8915 } 8916 8917 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 8918 switch (Opc) { 8919 case ISD::FMAXNUM: 8920 case ISD::FMAXNUM_IEEE: 8921 return AMDGPUISD::FMAX3; 8922 case ISD::SMAX: 8923 return AMDGPUISD::SMAX3; 8924 case ISD::UMAX: 8925 return AMDGPUISD::UMAX3; 8926 case ISD::FMINNUM: 8927 case ISD::FMINNUM_IEEE: 8928 return AMDGPUISD::FMIN3; 8929 case ISD::SMIN: 8930 return AMDGPUISD::SMIN3; 8931 case ISD::UMIN: 8932 return AMDGPUISD::UMIN3; 8933 default: 8934 llvm_unreachable("Not a min/max opcode"); 8935 } 8936 } 8937 8938 SDValue SITargetLowering::performIntMed3ImmCombine( 8939 SelectionDAG &DAG, const SDLoc &SL, 8940 SDValue Op0, SDValue Op1, bool Signed) const { 8941 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 8942 if (!K1) 8943 return SDValue(); 8944 8945 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 8946 if (!K0) 8947 return SDValue(); 8948 8949 if (Signed) { 8950 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 8951 return SDValue(); 8952 } else { 8953 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 8954 return SDValue(); 8955 } 8956 8957 EVT VT = K0->getValueType(0); 8958 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 8959 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 8960 return DAG.getNode(Med3Opc, SL, VT, 8961 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 8962 } 8963 8964 // If there isn't a 16-bit med3 operation, convert to 32-bit. 8965 MVT NVT = MVT::i32; 8966 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8967 8968 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 8969 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 8970 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 8971 8972 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 8973 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 8974 } 8975 8976 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 8977 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 8978 return C; 8979 8980 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 8981 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 8982 return C; 8983 } 8984 8985 return nullptr; 8986 } 8987 8988 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 8989 const SDLoc &SL, 8990 SDValue Op0, 8991 SDValue Op1) const { 8992 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 8993 if (!K1) 8994 return SDValue(); 8995 8996 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 8997 if (!K0) 8998 return SDValue(); 8999 9000 // Ordered >= (although NaN inputs should have folded away by now). 9001 if (K0->getValueAPF() > K1->getValueAPF()) 9002 return SDValue(); 9003 9004 const MachineFunction &MF = DAG.getMachineFunction(); 9005 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9006 9007 // TODO: Check IEEE bit enabled? 9008 EVT VT = Op0.getValueType(); 9009 if (Info->getMode().DX10Clamp) { 9010 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9011 // hardware fmed3 behavior converting to a min. 9012 // FIXME: Should this be allowing -0.0? 9013 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9014 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9015 } 9016 9017 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9018 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9019 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9020 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9021 // then give the other result, which is different from med3 with a NaN 9022 // input. 9023 SDValue Var = Op0.getOperand(0); 9024 if (!DAG.isKnownNeverSNaN(Var)) 9025 return SDValue(); 9026 9027 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9028 9029 if ((!K0->hasOneUse() || 9030 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9031 (!K1->hasOneUse() || 9032 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9033 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9034 Var, SDValue(K0, 0), SDValue(K1, 0)); 9035 } 9036 } 9037 9038 return SDValue(); 9039 } 9040 9041 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9042 DAGCombinerInfo &DCI) const { 9043 SelectionDAG &DAG = DCI.DAG; 9044 9045 EVT VT = N->getValueType(0); 9046 unsigned Opc = N->getOpcode(); 9047 SDValue Op0 = N->getOperand(0); 9048 SDValue Op1 = N->getOperand(1); 9049 9050 // Only do this if the inner op has one use since this will just increases 9051 // register pressure for no benefit. 9052 9053 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9054 !VT.isVector() && 9055 (VT == MVT::i32 || VT == MVT::f32 || 9056 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9057 // max(max(a, b), c) -> max3(a, b, c) 9058 // min(min(a, b), c) -> min3(a, b, c) 9059 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9060 SDLoc DL(N); 9061 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9062 DL, 9063 N->getValueType(0), 9064 Op0.getOperand(0), 9065 Op0.getOperand(1), 9066 Op1); 9067 } 9068 9069 // Try commuted. 9070 // max(a, max(b, c)) -> max3(a, b, c) 9071 // min(a, min(b, c)) -> min3(a, b, c) 9072 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9073 SDLoc DL(N); 9074 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9075 DL, 9076 N->getValueType(0), 9077 Op0, 9078 Op1.getOperand(0), 9079 Op1.getOperand(1)); 9080 } 9081 } 9082 9083 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9084 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9085 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9086 return Med3; 9087 } 9088 9089 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9090 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9091 return Med3; 9092 } 9093 9094 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9095 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9096 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9097 (Opc == AMDGPUISD::FMIN_LEGACY && 9098 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9099 (VT == MVT::f32 || VT == MVT::f64 || 9100 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9101 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9102 Op0.hasOneUse()) { 9103 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9104 return Res; 9105 } 9106 9107 return SDValue(); 9108 } 9109 9110 static bool isClampZeroToOne(SDValue A, SDValue B) { 9111 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9112 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9113 // FIXME: Should this be allowing -0.0? 9114 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9115 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9116 } 9117 } 9118 9119 return false; 9120 } 9121 9122 // FIXME: Should only worry about snans for version with chain. 9123 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9124 DAGCombinerInfo &DCI) const { 9125 EVT VT = N->getValueType(0); 9126 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9127 // NaNs. With a NaN input, the order of the operands may change the result. 9128 9129 SelectionDAG &DAG = DCI.DAG; 9130 SDLoc SL(N); 9131 9132 SDValue Src0 = N->getOperand(0); 9133 SDValue Src1 = N->getOperand(1); 9134 SDValue Src2 = N->getOperand(2); 9135 9136 if (isClampZeroToOne(Src0, Src1)) { 9137 // const_a, const_b, x -> clamp is safe in all cases including signaling 9138 // nans. 9139 // FIXME: Should this be allowing -0.0? 9140 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9141 } 9142 9143 const MachineFunction &MF = DAG.getMachineFunction(); 9144 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9145 9146 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9147 // handling no dx10-clamp? 9148 if (Info->getMode().DX10Clamp) { 9149 // If NaNs is clamped to 0, we are free to reorder the inputs. 9150 9151 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9152 std::swap(Src0, Src1); 9153 9154 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9155 std::swap(Src1, Src2); 9156 9157 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9158 std::swap(Src0, Src1); 9159 9160 if (isClampZeroToOne(Src1, Src2)) 9161 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9162 } 9163 9164 return SDValue(); 9165 } 9166 9167 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9168 DAGCombinerInfo &DCI) const { 9169 SDValue Src0 = N->getOperand(0); 9170 SDValue Src1 = N->getOperand(1); 9171 if (Src0.isUndef() && Src1.isUndef()) 9172 return DCI.DAG.getUNDEF(N->getValueType(0)); 9173 return SDValue(); 9174 } 9175 9176 SDValue SITargetLowering::performExtractVectorEltCombine( 9177 SDNode *N, DAGCombinerInfo &DCI) const { 9178 SDValue Vec = N->getOperand(0); 9179 SelectionDAG &DAG = DCI.DAG; 9180 9181 EVT VecVT = Vec.getValueType(); 9182 EVT EltVT = VecVT.getVectorElementType(); 9183 9184 if ((Vec.getOpcode() == ISD::FNEG || 9185 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9186 SDLoc SL(N); 9187 EVT EltVT = N->getValueType(0); 9188 SDValue Idx = N->getOperand(1); 9189 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9190 Vec.getOperand(0), Idx); 9191 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9192 } 9193 9194 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9195 // => 9196 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9197 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9198 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9199 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9200 SDLoc SL(N); 9201 EVT EltVT = N->getValueType(0); 9202 SDValue Idx = N->getOperand(1); 9203 unsigned Opc = Vec.getOpcode(); 9204 9205 switch(Opc) { 9206 default: 9207 break; 9208 // TODO: Support other binary operations. 9209 case ISD::FADD: 9210 case ISD::FSUB: 9211 case ISD::FMUL: 9212 case ISD::ADD: 9213 case ISD::UMIN: 9214 case ISD::UMAX: 9215 case ISD::SMIN: 9216 case ISD::SMAX: 9217 case ISD::FMAXNUM: 9218 case ISD::FMINNUM: 9219 case ISD::FMAXNUM_IEEE: 9220 case ISD::FMINNUM_IEEE: { 9221 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9222 Vec.getOperand(0), Idx); 9223 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9224 Vec.getOperand(1), Idx); 9225 9226 DCI.AddToWorklist(Elt0.getNode()); 9227 DCI.AddToWorklist(Elt1.getNode()); 9228 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9229 } 9230 } 9231 } 9232 9233 unsigned VecSize = VecVT.getSizeInBits(); 9234 unsigned EltSize = EltVT.getSizeInBits(); 9235 9236 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9237 // This elminates non-constant index and subsequent movrel or scratch access. 9238 // Sub-dword vectors of size 2 dword or less have better implementation. 9239 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9240 // instructions. 9241 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) && 9242 !isa<ConstantSDNode>(N->getOperand(1))) { 9243 SDLoc SL(N); 9244 SDValue Idx = N->getOperand(1); 9245 SDValue V; 9246 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9247 SDValue IC = DAG.getVectorIdxConstant(I, SL); 9248 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9249 if (I == 0) 9250 V = Elt; 9251 else 9252 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9253 } 9254 return V; 9255 } 9256 9257 if (!DCI.isBeforeLegalize()) 9258 return SDValue(); 9259 9260 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9261 // elements. This exposes more load reduction opportunities by replacing 9262 // multiple small extract_vector_elements with a single 32-bit extract. 9263 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9264 if (isa<MemSDNode>(Vec) && 9265 EltSize <= 16 && 9266 EltVT.isByteSized() && 9267 VecSize > 32 && 9268 VecSize % 32 == 0 && 9269 Idx) { 9270 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9271 9272 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9273 unsigned EltIdx = BitIndex / 32; 9274 unsigned LeftoverBitIdx = BitIndex % 32; 9275 SDLoc SL(N); 9276 9277 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9278 DCI.AddToWorklist(Cast.getNode()); 9279 9280 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9281 DAG.getConstant(EltIdx, SL, MVT::i32)); 9282 DCI.AddToWorklist(Elt.getNode()); 9283 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9284 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9285 DCI.AddToWorklist(Srl.getNode()); 9286 9287 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9288 DCI.AddToWorklist(Trunc.getNode()); 9289 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9290 } 9291 9292 return SDValue(); 9293 } 9294 9295 SDValue 9296 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9297 DAGCombinerInfo &DCI) const { 9298 SDValue Vec = N->getOperand(0); 9299 SDValue Idx = N->getOperand(2); 9300 EVT VecVT = Vec.getValueType(); 9301 EVT EltVT = VecVT.getVectorElementType(); 9302 unsigned VecSize = VecVT.getSizeInBits(); 9303 unsigned EltSize = EltVT.getSizeInBits(); 9304 9305 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9306 // => BUILD_VECTOR n x select (e, const-idx) 9307 // This elminates non-constant index and subsequent movrel or scratch access. 9308 // Sub-dword vectors of size 2 dword or less have better implementation. 9309 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9310 // instructions. 9311 if (isa<ConstantSDNode>(Idx) || 9312 VecSize > 256 || (VecSize <= 64 && EltSize < 32)) 9313 return SDValue(); 9314 9315 SelectionDAG &DAG = DCI.DAG; 9316 SDLoc SL(N); 9317 SDValue Ins = N->getOperand(1); 9318 EVT IdxVT = Idx.getValueType(); 9319 9320 SmallVector<SDValue, 16> Ops; 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 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9325 Ops.push_back(V); 9326 } 9327 9328 return DAG.getBuildVector(VecVT, SL, Ops); 9329 } 9330 9331 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9332 const SDNode *N0, 9333 const SDNode *N1) const { 9334 EVT VT = N0->getValueType(0); 9335 9336 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9337 // support denormals ever. 9338 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9339 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9340 getSubtarget()->hasMadF16())) && 9341 isOperationLegal(ISD::FMAD, VT)) 9342 return ISD::FMAD; 9343 9344 const TargetOptions &Options = DAG.getTarget().Options; 9345 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9346 (N0->getFlags().hasAllowContract() && 9347 N1->getFlags().hasAllowContract())) && 9348 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 9349 return ISD::FMA; 9350 } 9351 9352 return 0; 9353 } 9354 9355 // For a reassociatable opcode perform: 9356 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9357 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9358 SelectionDAG &DAG) const { 9359 EVT VT = N->getValueType(0); 9360 if (VT != MVT::i32 && VT != MVT::i64) 9361 return SDValue(); 9362 9363 unsigned Opc = N->getOpcode(); 9364 SDValue Op0 = N->getOperand(0); 9365 SDValue Op1 = N->getOperand(1); 9366 9367 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9368 return SDValue(); 9369 9370 if (Op0->isDivergent()) 9371 std::swap(Op0, Op1); 9372 9373 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9374 return SDValue(); 9375 9376 SDValue Op2 = Op1.getOperand(1); 9377 Op1 = Op1.getOperand(0); 9378 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9379 return SDValue(); 9380 9381 if (Op1->isDivergent()) 9382 std::swap(Op1, Op2); 9383 9384 // If either operand is constant this will conflict with 9385 // DAGCombiner::ReassociateOps(). 9386 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9387 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9388 return SDValue(); 9389 9390 SDLoc SL(N); 9391 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9392 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9393 } 9394 9395 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9396 EVT VT, 9397 SDValue N0, SDValue N1, SDValue N2, 9398 bool Signed) { 9399 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9400 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9401 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 9402 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 9403 } 9404 9405 SDValue SITargetLowering::performAddCombine(SDNode *N, 9406 DAGCombinerInfo &DCI) const { 9407 SelectionDAG &DAG = DCI.DAG; 9408 EVT VT = N->getValueType(0); 9409 SDLoc SL(N); 9410 SDValue LHS = N->getOperand(0); 9411 SDValue RHS = N->getOperand(1); 9412 9413 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 9414 && Subtarget->hasMad64_32() && 9415 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 9416 VT.getScalarSizeInBits() <= 64) { 9417 if (LHS.getOpcode() != ISD::MUL) 9418 std::swap(LHS, RHS); 9419 9420 SDValue MulLHS = LHS.getOperand(0); 9421 SDValue MulRHS = LHS.getOperand(1); 9422 SDValue AddRHS = RHS; 9423 9424 // TODO: Maybe restrict if SGPR inputs. 9425 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 9426 numBitsUnsigned(MulRHS, DAG) <= 32) { 9427 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 9428 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 9429 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 9430 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 9431 } 9432 9433 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 9434 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 9435 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 9436 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 9437 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 9438 } 9439 9440 return SDValue(); 9441 } 9442 9443 if (SDValue V = reassociateScalarOps(N, DAG)) { 9444 return V; 9445 } 9446 9447 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 9448 return SDValue(); 9449 9450 // add x, zext (setcc) => addcarry x, 0, setcc 9451 // add x, sext (setcc) => subcarry x, 0, setcc 9452 unsigned Opc = LHS.getOpcode(); 9453 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9454 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 9455 std::swap(RHS, LHS); 9456 9457 Opc = RHS.getOpcode(); 9458 switch (Opc) { 9459 default: break; 9460 case ISD::ZERO_EXTEND: 9461 case ISD::SIGN_EXTEND: 9462 case ISD::ANY_EXTEND: { 9463 auto Cond = RHS.getOperand(0); 9464 // If this won't be a real VOPC output, we would still need to insert an 9465 // extra instruction anyway. 9466 if (!isBoolSGPR(Cond)) 9467 break; 9468 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9469 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9470 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9471 return DAG.getNode(Opc, SL, VTList, Args); 9472 } 9473 case ISD::ADDCARRY: { 9474 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 9475 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9476 if (!C || C->getZExtValue() != 0) break; 9477 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 9478 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 9479 } 9480 } 9481 return SDValue(); 9482 } 9483 9484 SDValue SITargetLowering::performSubCombine(SDNode *N, 9485 DAGCombinerInfo &DCI) const { 9486 SelectionDAG &DAG = DCI.DAG; 9487 EVT VT = N->getValueType(0); 9488 9489 if (VT != MVT::i32) 9490 return SDValue(); 9491 9492 SDLoc SL(N); 9493 SDValue LHS = N->getOperand(0); 9494 SDValue RHS = N->getOperand(1); 9495 9496 // sub x, zext (setcc) => subcarry x, 0, setcc 9497 // sub x, sext (setcc) => addcarry x, 0, setcc 9498 unsigned Opc = RHS.getOpcode(); 9499 switch (Opc) { 9500 default: break; 9501 case ISD::ZERO_EXTEND: 9502 case ISD::SIGN_EXTEND: 9503 case ISD::ANY_EXTEND: { 9504 auto Cond = RHS.getOperand(0); 9505 // If this won't be a real VOPC output, we would still need to insert an 9506 // extra instruction anyway. 9507 if (!isBoolSGPR(Cond)) 9508 break; 9509 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9510 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9511 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 9512 return DAG.getNode(Opc, SL, VTList, Args); 9513 } 9514 } 9515 9516 if (LHS.getOpcode() == ISD::SUBCARRY) { 9517 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 9518 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9519 if (!C || !C->isNullValue()) 9520 return SDValue(); 9521 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 9522 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 9523 } 9524 return SDValue(); 9525 } 9526 9527 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 9528 DAGCombinerInfo &DCI) const { 9529 9530 if (N->getValueType(0) != MVT::i32) 9531 return SDValue(); 9532 9533 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9534 if (!C || C->getZExtValue() != 0) 9535 return SDValue(); 9536 9537 SelectionDAG &DAG = DCI.DAG; 9538 SDValue LHS = N->getOperand(0); 9539 9540 // addcarry (add x, y), 0, cc => addcarry x, y, cc 9541 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 9542 unsigned LHSOpc = LHS.getOpcode(); 9543 unsigned Opc = N->getOpcode(); 9544 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 9545 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 9546 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 9547 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 9548 } 9549 return SDValue(); 9550 } 9551 9552 SDValue SITargetLowering::performFAddCombine(SDNode *N, 9553 DAGCombinerInfo &DCI) const { 9554 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9555 return SDValue(); 9556 9557 SelectionDAG &DAG = DCI.DAG; 9558 EVT VT = N->getValueType(0); 9559 9560 SDLoc SL(N); 9561 SDValue LHS = N->getOperand(0); 9562 SDValue RHS = N->getOperand(1); 9563 9564 // These should really be instruction patterns, but writing patterns with 9565 // source modiifiers is a pain. 9566 9567 // fadd (fadd (a, a), b) -> mad 2.0, a, b 9568 if (LHS.getOpcode() == ISD::FADD) { 9569 SDValue A = LHS.getOperand(0); 9570 if (A == LHS.getOperand(1)) { 9571 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9572 if (FusedOp != 0) { 9573 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9574 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 9575 } 9576 } 9577 } 9578 9579 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 9580 if (RHS.getOpcode() == ISD::FADD) { 9581 SDValue A = RHS.getOperand(0); 9582 if (A == RHS.getOperand(1)) { 9583 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9584 if (FusedOp != 0) { 9585 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9586 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 9587 } 9588 } 9589 } 9590 9591 return SDValue(); 9592 } 9593 9594 SDValue SITargetLowering::performFSubCombine(SDNode *N, 9595 DAGCombinerInfo &DCI) const { 9596 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9597 return SDValue(); 9598 9599 SelectionDAG &DAG = DCI.DAG; 9600 SDLoc SL(N); 9601 EVT VT = N->getValueType(0); 9602 assert(!VT.isVector()); 9603 9604 // Try to get the fneg to fold into the source modifier. This undoes generic 9605 // DAG combines and folds them into the mad. 9606 // 9607 // Only do this if we are not trying to support denormals. v_mad_f32 does 9608 // not support denormals ever. 9609 SDValue LHS = N->getOperand(0); 9610 SDValue RHS = N->getOperand(1); 9611 if (LHS.getOpcode() == ISD::FADD) { 9612 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 9613 SDValue A = LHS.getOperand(0); 9614 if (A == LHS.getOperand(1)) { 9615 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9616 if (FusedOp != 0){ 9617 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9618 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 9619 9620 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 9621 } 9622 } 9623 } 9624 9625 if (RHS.getOpcode() == ISD::FADD) { 9626 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 9627 9628 SDValue A = RHS.getOperand(0); 9629 if (A == RHS.getOperand(1)) { 9630 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9631 if (FusedOp != 0){ 9632 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 9633 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 9634 } 9635 } 9636 } 9637 9638 return SDValue(); 9639 } 9640 9641 SDValue SITargetLowering::performFMACombine(SDNode *N, 9642 DAGCombinerInfo &DCI) const { 9643 SelectionDAG &DAG = DCI.DAG; 9644 EVT VT = N->getValueType(0); 9645 SDLoc SL(N); 9646 9647 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 9648 return SDValue(); 9649 9650 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 9651 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 9652 SDValue Op1 = N->getOperand(0); 9653 SDValue Op2 = N->getOperand(1); 9654 SDValue FMA = N->getOperand(2); 9655 9656 if (FMA.getOpcode() != ISD::FMA || 9657 Op1.getOpcode() != ISD::FP_EXTEND || 9658 Op2.getOpcode() != ISD::FP_EXTEND) 9659 return SDValue(); 9660 9661 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 9662 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 9663 // is sufficient to allow generaing fdot2. 9664 const TargetOptions &Options = DAG.getTarget().Options; 9665 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9666 (N->getFlags().hasAllowContract() && 9667 FMA->getFlags().hasAllowContract())) { 9668 Op1 = Op1.getOperand(0); 9669 Op2 = Op2.getOperand(0); 9670 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9671 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9672 return SDValue(); 9673 9674 SDValue Vec1 = Op1.getOperand(0); 9675 SDValue Idx1 = Op1.getOperand(1); 9676 SDValue Vec2 = Op2.getOperand(0); 9677 9678 SDValue FMAOp1 = FMA.getOperand(0); 9679 SDValue FMAOp2 = FMA.getOperand(1); 9680 SDValue FMAAcc = FMA.getOperand(2); 9681 9682 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 9683 FMAOp2.getOpcode() != ISD::FP_EXTEND) 9684 return SDValue(); 9685 9686 FMAOp1 = FMAOp1.getOperand(0); 9687 FMAOp2 = FMAOp2.getOperand(0); 9688 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9689 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9690 return SDValue(); 9691 9692 SDValue Vec3 = FMAOp1.getOperand(0); 9693 SDValue Vec4 = FMAOp2.getOperand(0); 9694 SDValue Idx2 = FMAOp1.getOperand(1); 9695 9696 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 9697 // Idx1 and Idx2 cannot be the same. 9698 Idx1 == Idx2) 9699 return SDValue(); 9700 9701 if (Vec1 == Vec2 || Vec3 == Vec4) 9702 return SDValue(); 9703 9704 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 9705 return SDValue(); 9706 9707 if ((Vec1 == Vec3 && Vec2 == Vec4) || 9708 (Vec1 == Vec4 && Vec2 == Vec3)) { 9709 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 9710 DAG.getTargetConstant(0, SL, MVT::i1)); 9711 } 9712 } 9713 return SDValue(); 9714 } 9715 9716 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 9717 DAGCombinerInfo &DCI) const { 9718 SelectionDAG &DAG = DCI.DAG; 9719 SDLoc SL(N); 9720 9721 SDValue LHS = N->getOperand(0); 9722 SDValue RHS = N->getOperand(1); 9723 EVT VT = LHS.getValueType(); 9724 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 9725 9726 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 9727 if (!CRHS) { 9728 CRHS = dyn_cast<ConstantSDNode>(LHS); 9729 if (CRHS) { 9730 std::swap(LHS, RHS); 9731 CC = getSetCCSwappedOperands(CC); 9732 } 9733 } 9734 9735 if (CRHS) { 9736 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 9737 isBoolSGPR(LHS.getOperand(0))) { 9738 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 9739 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 9740 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 9741 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 9742 if ((CRHS->isAllOnesValue() && 9743 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 9744 (CRHS->isNullValue() && 9745 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 9746 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9747 DAG.getConstant(-1, SL, MVT::i1)); 9748 if ((CRHS->isAllOnesValue() && 9749 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 9750 (CRHS->isNullValue() && 9751 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 9752 return LHS.getOperand(0); 9753 } 9754 9755 uint64_t CRHSVal = CRHS->getZExtValue(); 9756 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 9757 LHS.getOpcode() == ISD::SELECT && 9758 isa<ConstantSDNode>(LHS.getOperand(1)) && 9759 isa<ConstantSDNode>(LHS.getOperand(2)) && 9760 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 9761 isBoolSGPR(LHS.getOperand(0))) { 9762 // Given CT != FT: 9763 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 9764 // setcc (select cc, CT, CF), CF, ne => cc 9765 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 9766 // setcc (select cc, CT, CF), CT, eq => cc 9767 uint64_t CT = LHS.getConstantOperandVal(1); 9768 uint64_t CF = LHS.getConstantOperandVal(2); 9769 9770 if ((CF == CRHSVal && CC == ISD::SETEQ) || 9771 (CT == CRHSVal && CC == ISD::SETNE)) 9772 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9773 DAG.getConstant(-1, SL, MVT::i1)); 9774 if ((CF == CRHSVal && CC == ISD::SETNE) || 9775 (CT == CRHSVal && CC == ISD::SETEQ)) 9776 return LHS.getOperand(0); 9777 } 9778 } 9779 9780 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 9781 VT != MVT::f16)) 9782 return SDValue(); 9783 9784 // Match isinf/isfinite pattern 9785 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 9786 // (fcmp one (fabs x), inf) -> (fp_class x, 9787 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 9788 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 9789 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 9790 if (!CRHS) 9791 return SDValue(); 9792 9793 const APFloat &APF = CRHS->getValueAPF(); 9794 if (APF.isInfinity() && !APF.isNegative()) { 9795 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 9796 SIInstrFlags::N_INFINITY; 9797 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 9798 SIInstrFlags::P_ZERO | 9799 SIInstrFlags::N_NORMAL | 9800 SIInstrFlags::P_NORMAL | 9801 SIInstrFlags::N_SUBNORMAL | 9802 SIInstrFlags::P_SUBNORMAL; 9803 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 9804 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 9805 DAG.getConstant(Mask, SL, MVT::i32)); 9806 } 9807 } 9808 9809 return SDValue(); 9810 } 9811 9812 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 9813 DAGCombinerInfo &DCI) const { 9814 SelectionDAG &DAG = DCI.DAG; 9815 SDLoc SL(N); 9816 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 9817 9818 SDValue Src = N->getOperand(0); 9819 SDValue Shift = N->getOperand(0); 9820 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 9821 Shift = Shift.getOperand(0); 9822 9823 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 9824 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 9825 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 9826 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 9827 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 9828 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 9829 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 9830 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 9831 SDLoc(Shift.getOperand(0)), MVT::i32); 9832 9833 unsigned ShiftOffset = 8 * Offset; 9834 if (Shift.getOpcode() == ISD::SHL) 9835 ShiftOffset -= C->getZExtValue(); 9836 else 9837 ShiftOffset += C->getZExtValue(); 9838 9839 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 9840 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 9841 MVT::f32, Shift); 9842 } 9843 } 9844 } 9845 9846 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9847 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 9848 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 9849 // We simplified Src. If this node is not dead, visit it again so it is 9850 // folded properly. 9851 if (N->getOpcode() != ISD::DELETED_NODE) 9852 DCI.AddToWorklist(N); 9853 return SDValue(N, 0); 9854 } 9855 9856 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 9857 if (SDValue DemandedSrc = 9858 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 9859 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 9860 9861 return SDValue(); 9862 } 9863 9864 SDValue SITargetLowering::performClampCombine(SDNode *N, 9865 DAGCombinerInfo &DCI) const { 9866 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 9867 if (!CSrc) 9868 return SDValue(); 9869 9870 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 9871 const APFloat &F = CSrc->getValueAPF(); 9872 APFloat Zero = APFloat::getZero(F.getSemantics()); 9873 if (F < Zero || 9874 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 9875 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 9876 } 9877 9878 APFloat One(F.getSemantics(), "1.0"); 9879 if (F > One) 9880 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 9881 9882 return SDValue(CSrc, 0); 9883 } 9884 9885 9886 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 9887 DAGCombinerInfo &DCI) const { 9888 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 9889 return SDValue(); 9890 switch (N->getOpcode()) { 9891 default: 9892 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9893 case ISD::ADD: 9894 return performAddCombine(N, DCI); 9895 case ISD::SUB: 9896 return performSubCombine(N, DCI); 9897 case ISD::ADDCARRY: 9898 case ISD::SUBCARRY: 9899 return performAddCarrySubCarryCombine(N, DCI); 9900 case ISD::FADD: 9901 return performFAddCombine(N, DCI); 9902 case ISD::FSUB: 9903 return performFSubCombine(N, DCI); 9904 case ISD::SETCC: 9905 return performSetCCCombine(N, DCI); 9906 case ISD::FMAXNUM: 9907 case ISD::FMINNUM: 9908 case ISD::FMAXNUM_IEEE: 9909 case ISD::FMINNUM_IEEE: 9910 case ISD::SMAX: 9911 case ISD::SMIN: 9912 case ISD::UMAX: 9913 case ISD::UMIN: 9914 case AMDGPUISD::FMIN_LEGACY: 9915 case AMDGPUISD::FMAX_LEGACY: 9916 return performMinMaxCombine(N, DCI); 9917 case ISD::FMA: 9918 return performFMACombine(N, DCI); 9919 case ISD::LOAD: { 9920 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 9921 return Widended; 9922 LLVM_FALLTHROUGH; 9923 } 9924 case ISD::STORE: 9925 case ISD::ATOMIC_LOAD: 9926 case ISD::ATOMIC_STORE: 9927 case ISD::ATOMIC_CMP_SWAP: 9928 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 9929 case ISD::ATOMIC_SWAP: 9930 case ISD::ATOMIC_LOAD_ADD: 9931 case ISD::ATOMIC_LOAD_SUB: 9932 case ISD::ATOMIC_LOAD_AND: 9933 case ISD::ATOMIC_LOAD_OR: 9934 case ISD::ATOMIC_LOAD_XOR: 9935 case ISD::ATOMIC_LOAD_NAND: 9936 case ISD::ATOMIC_LOAD_MIN: 9937 case ISD::ATOMIC_LOAD_MAX: 9938 case ISD::ATOMIC_LOAD_UMIN: 9939 case ISD::ATOMIC_LOAD_UMAX: 9940 case ISD::ATOMIC_LOAD_FADD: 9941 case AMDGPUISD::ATOMIC_INC: 9942 case AMDGPUISD::ATOMIC_DEC: 9943 case AMDGPUISD::ATOMIC_LOAD_FMIN: 9944 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 9945 if (DCI.isBeforeLegalize()) 9946 break; 9947 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 9948 case ISD::AND: 9949 return performAndCombine(N, DCI); 9950 case ISD::OR: 9951 return performOrCombine(N, DCI); 9952 case ISD::XOR: 9953 return performXorCombine(N, DCI); 9954 case ISD::ZERO_EXTEND: 9955 return performZeroExtendCombine(N, DCI); 9956 case ISD::SIGN_EXTEND_INREG: 9957 return performSignExtendInRegCombine(N , DCI); 9958 case AMDGPUISD::FP_CLASS: 9959 return performClassCombine(N, DCI); 9960 case ISD::FCANONICALIZE: 9961 return performFCanonicalizeCombine(N, DCI); 9962 case AMDGPUISD::RCP: 9963 return performRcpCombine(N, DCI); 9964 case AMDGPUISD::FRACT: 9965 case AMDGPUISD::RSQ: 9966 case AMDGPUISD::RCP_LEGACY: 9967 case AMDGPUISD::RSQ_LEGACY: 9968 case AMDGPUISD::RCP_IFLAG: 9969 case AMDGPUISD::RSQ_CLAMP: 9970 case AMDGPUISD::LDEXP: { 9971 SDValue Src = N->getOperand(0); 9972 if (Src.isUndef()) 9973 return Src; 9974 break; 9975 } 9976 case ISD::SINT_TO_FP: 9977 case ISD::UINT_TO_FP: 9978 return performUCharToFloatCombine(N, DCI); 9979 case AMDGPUISD::CVT_F32_UBYTE0: 9980 case AMDGPUISD::CVT_F32_UBYTE1: 9981 case AMDGPUISD::CVT_F32_UBYTE2: 9982 case AMDGPUISD::CVT_F32_UBYTE3: 9983 return performCvtF32UByteNCombine(N, DCI); 9984 case AMDGPUISD::FMED3: 9985 return performFMed3Combine(N, DCI); 9986 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9987 return performCvtPkRTZCombine(N, DCI); 9988 case AMDGPUISD::CLAMP: 9989 return performClampCombine(N, DCI); 9990 case ISD::SCALAR_TO_VECTOR: { 9991 SelectionDAG &DAG = DCI.DAG; 9992 EVT VT = N->getValueType(0); 9993 9994 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 9995 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 9996 SDLoc SL(N); 9997 SDValue Src = N->getOperand(0); 9998 EVT EltVT = Src.getValueType(); 9999 if (EltVT == MVT::f16) 10000 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10001 10002 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10003 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10004 } 10005 10006 break; 10007 } 10008 case ISD::EXTRACT_VECTOR_ELT: 10009 return performExtractVectorEltCombine(N, DCI); 10010 case ISD::INSERT_VECTOR_ELT: 10011 return performInsertVectorEltCombine(N, DCI); 10012 } 10013 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10014 } 10015 10016 /// Helper function for adjustWritemask 10017 static unsigned SubIdx2Lane(unsigned Idx) { 10018 switch (Idx) { 10019 default: return 0; 10020 case AMDGPU::sub0: return 0; 10021 case AMDGPU::sub1: return 1; 10022 case AMDGPU::sub2: return 2; 10023 case AMDGPU::sub3: return 3; 10024 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10025 } 10026 } 10027 10028 /// Adjust the writemask of MIMG instructions 10029 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10030 SelectionDAG &DAG) const { 10031 unsigned Opcode = Node->getMachineOpcode(); 10032 10033 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10034 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10035 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10036 return Node; // not implemented for D16 10037 10038 SDNode *Users[5] = { nullptr }; 10039 unsigned Lane = 0; 10040 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10041 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10042 unsigned NewDmask = 0; 10043 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10044 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10045 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10046 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10047 unsigned TFCLane = 0; 10048 bool HasChain = Node->getNumValues() > 1; 10049 10050 if (OldDmask == 0) { 10051 // These are folded out, but on the chance it happens don't assert. 10052 return Node; 10053 } 10054 10055 unsigned OldBitsSet = countPopulation(OldDmask); 10056 // Work out which is the TFE/LWE lane if that is enabled. 10057 if (UsesTFC) { 10058 TFCLane = OldBitsSet; 10059 } 10060 10061 // Try to figure out the used register components 10062 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10063 I != E; ++I) { 10064 10065 // Don't look at users of the chain. 10066 if (I.getUse().getResNo() != 0) 10067 continue; 10068 10069 // Abort if we can't understand the usage 10070 if (!I->isMachineOpcode() || 10071 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10072 return Node; 10073 10074 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10075 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10076 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10077 // set, etc. 10078 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10079 10080 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10081 if (UsesTFC && Lane == TFCLane) { 10082 Users[Lane] = *I; 10083 } else { 10084 // Set which texture component corresponds to the lane. 10085 unsigned Comp; 10086 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10087 Comp = countTrailingZeros(Dmask); 10088 Dmask &= ~(1 << Comp); 10089 } 10090 10091 // Abort if we have more than one user per component. 10092 if (Users[Lane]) 10093 return Node; 10094 10095 Users[Lane] = *I; 10096 NewDmask |= 1 << Comp; 10097 } 10098 } 10099 10100 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10101 bool NoChannels = !NewDmask; 10102 if (NoChannels) { 10103 if (!UsesTFC) { 10104 // No uses of the result and not using TFC. Then do nothing. 10105 return Node; 10106 } 10107 // If the original dmask has one channel - then nothing to do 10108 if (OldBitsSet == 1) 10109 return Node; 10110 // Use an arbitrary dmask - required for the instruction to work 10111 NewDmask = 1; 10112 } 10113 // Abort if there's no change 10114 if (NewDmask == OldDmask) 10115 return Node; 10116 10117 unsigned BitsSet = countPopulation(NewDmask); 10118 10119 // Check for TFE or LWE - increase the number of channels by one to account 10120 // for the extra return value 10121 // This will need adjustment for D16 if this is also included in 10122 // adjustWriteMask (this function) but at present D16 are excluded. 10123 unsigned NewChannels = BitsSet + UsesTFC; 10124 10125 int NewOpcode = 10126 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10127 assert(NewOpcode != -1 && 10128 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10129 "failed to find equivalent MIMG op"); 10130 10131 // Adjust the writemask in the node 10132 SmallVector<SDValue, 12> Ops; 10133 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10134 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10135 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10136 10137 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10138 10139 MVT ResultVT = NewChannels == 1 ? 10140 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10141 NewChannels == 5 ? 8 : NewChannels); 10142 SDVTList NewVTList = HasChain ? 10143 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10144 10145 10146 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10147 NewVTList, Ops); 10148 10149 if (HasChain) { 10150 // Update chain. 10151 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10152 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10153 } 10154 10155 if (NewChannels == 1) { 10156 assert(Node->hasNUsesOfValue(1, 0)); 10157 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10158 SDLoc(Node), Users[Lane]->getValueType(0), 10159 SDValue(NewNode, 0)); 10160 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10161 return nullptr; 10162 } 10163 10164 // Update the users of the node with the new indices 10165 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10166 SDNode *User = Users[i]; 10167 if (!User) { 10168 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10169 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10170 if (i || !NoChannels) 10171 continue; 10172 } else { 10173 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10174 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10175 } 10176 10177 switch (Idx) { 10178 default: break; 10179 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10180 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10181 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10182 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10183 } 10184 } 10185 10186 DAG.RemoveDeadNode(Node); 10187 return nullptr; 10188 } 10189 10190 static bool isFrameIndexOp(SDValue Op) { 10191 if (Op.getOpcode() == ISD::AssertZext) 10192 Op = Op.getOperand(0); 10193 10194 return isa<FrameIndexSDNode>(Op); 10195 } 10196 10197 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10198 /// with frame index operands. 10199 /// LLVM assumes that inputs are to these instructions are registers. 10200 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10201 SelectionDAG &DAG) const { 10202 if (Node->getOpcode() == ISD::CopyToReg) { 10203 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10204 SDValue SrcVal = Node->getOperand(2); 10205 10206 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10207 // to try understanding copies to physical registers. 10208 if (SrcVal.getValueType() == MVT::i1 && 10209 Register::isPhysicalRegister(DestReg->getReg())) { 10210 SDLoc SL(Node); 10211 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10212 SDValue VReg = DAG.getRegister( 10213 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10214 10215 SDNode *Glued = Node->getGluedNode(); 10216 SDValue ToVReg 10217 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10218 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10219 SDValue ToResultReg 10220 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10221 VReg, ToVReg.getValue(1)); 10222 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10223 DAG.RemoveDeadNode(Node); 10224 return ToResultReg.getNode(); 10225 } 10226 } 10227 10228 SmallVector<SDValue, 8> Ops; 10229 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10230 if (!isFrameIndexOp(Node->getOperand(i))) { 10231 Ops.push_back(Node->getOperand(i)); 10232 continue; 10233 } 10234 10235 SDLoc DL(Node); 10236 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10237 Node->getOperand(i).getValueType(), 10238 Node->getOperand(i)), 0)); 10239 } 10240 10241 return DAG.UpdateNodeOperands(Node, Ops); 10242 } 10243 10244 /// Fold the instructions after selecting them. 10245 /// Returns null if users were already updated. 10246 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10247 SelectionDAG &DAG) const { 10248 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10249 unsigned Opcode = Node->getMachineOpcode(); 10250 10251 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10252 !TII->isGather4(Opcode)) { 10253 return adjustWritemask(Node, DAG); 10254 } 10255 10256 if (Opcode == AMDGPU::INSERT_SUBREG || 10257 Opcode == AMDGPU::REG_SEQUENCE) { 10258 legalizeTargetIndependentNode(Node, DAG); 10259 return Node; 10260 } 10261 10262 switch (Opcode) { 10263 case AMDGPU::V_DIV_SCALE_F32: 10264 case AMDGPU::V_DIV_SCALE_F64: { 10265 // Satisfy the operand register constraint when one of the inputs is 10266 // undefined. Ordinarily each undef value will have its own implicit_def of 10267 // a vreg, so force these to use a single register. 10268 SDValue Src0 = Node->getOperand(0); 10269 SDValue Src1 = Node->getOperand(1); 10270 SDValue Src2 = Node->getOperand(2); 10271 10272 if ((Src0.isMachineOpcode() && 10273 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10274 (Src0 == Src1 || Src0 == Src2)) 10275 break; 10276 10277 MVT VT = Src0.getValueType().getSimpleVT(); 10278 const TargetRegisterClass *RC = 10279 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10280 10281 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10282 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10283 10284 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10285 UndefReg, Src0, SDValue()); 10286 10287 // src0 must be the same register as src1 or src2, even if the value is 10288 // undefined, so make sure we don't violate this constraint. 10289 if (Src0.isMachineOpcode() && 10290 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10291 if (Src1.isMachineOpcode() && 10292 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10293 Src0 = Src1; 10294 else if (Src2.isMachineOpcode() && 10295 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10296 Src0 = Src2; 10297 else { 10298 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10299 Src0 = UndefReg; 10300 Src1 = UndefReg; 10301 } 10302 } else 10303 break; 10304 10305 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10306 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10307 Ops.push_back(Node->getOperand(I)); 10308 10309 Ops.push_back(ImpDef.getValue(1)); 10310 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10311 } 10312 default: 10313 break; 10314 } 10315 10316 return Node; 10317 } 10318 10319 /// Assign the register class depending on the number of 10320 /// bits set in the writemask 10321 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10322 SDNode *Node) const { 10323 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10324 10325 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10326 10327 if (TII->isVOP3(MI.getOpcode())) { 10328 // Make sure constant bus requirements are respected. 10329 TII->legalizeOperandsVOP3(MRI, MI); 10330 10331 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10332 // This saves a chain-copy of registers and better ballance register 10333 // use between vgpr and agpr as agpr tuples tend to be big. 10334 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10335 unsigned Opc = MI.getOpcode(); 10336 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10337 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10338 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10339 if (I == -1) 10340 break; 10341 MachineOperand &Op = MI.getOperand(I); 10342 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10343 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10344 !Register::isVirtualRegister(Op.getReg()) || 10345 !TRI->isAGPR(MRI, Op.getReg())) 10346 continue; 10347 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10348 if (!Src || !Src->isCopy() || 10349 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10350 continue; 10351 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10352 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10353 // All uses of agpr64 and agpr32 can also accept vgpr except for 10354 // v_accvgpr_read, but we do not produce agpr reads during selection, 10355 // so no use checks are needed. 10356 MRI.setRegClass(Op.getReg(), NewRC); 10357 } 10358 } 10359 10360 return; 10361 } 10362 10363 // Replace unused atomics with the no return version. 10364 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10365 if (NoRetAtomicOp != -1) { 10366 if (!Node->hasAnyUseOfValue(0)) { 10367 MI.setDesc(TII->get(NoRetAtomicOp)); 10368 MI.RemoveOperand(0); 10369 return; 10370 } 10371 10372 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10373 // instruction, because the return type of these instructions is a vec2 of 10374 // the memory type, so it can be tied to the input operand. 10375 // This means these instructions always have a use, so we need to add a 10376 // special case to check if the atomic has only one extract_subreg use, 10377 // which itself has no uses. 10378 if ((Node->hasNUsesOfValue(1, 0) && 10379 Node->use_begin()->isMachineOpcode() && 10380 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10381 !Node->use_begin()->hasAnyUseOfValue(0))) { 10382 Register Def = MI.getOperand(0).getReg(); 10383 10384 // Change this into a noret atomic. 10385 MI.setDesc(TII->get(NoRetAtomicOp)); 10386 MI.RemoveOperand(0); 10387 10388 // If we only remove the def operand from the atomic instruction, the 10389 // extract_subreg will be left with a use of a vreg without a def. 10390 // So we need to insert an implicit_def to avoid machine verifier 10391 // errors. 10392 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10393 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10394 } 10395 return; 10396 } 10397 } 10398 10399 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 10400 uint64_t Val) { 10401 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 10402 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 10403 } 10404 10405 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 10406 const SDLoc &DL, 10407 SDValue Ptr) const { 10408 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10409 10410 // Build the half of the subregister with the constants before building the 10411 // full 128-bit register. If we are building multiple resource descriptors, 10412 // this will allow CSEing of the 2-component register. 10413 const SDValue Ops0[] = { 10414 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 10415 buildSMovImm32(DAG, DL, 0), 10416 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10417 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 10418 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 10419 }; 10420 10421 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 10422 MVT::v2i32, Ops0), 0); 10423 10424 // Combine the constants and the pointer. 10425 const SDValue Ops1[] = { 10426 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10427 Ptr, 10428 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 10429 SubRegHi, 10430 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 10431 }; 10432 10433 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 10434 } 10435 10436 /// Return a resource descriptor with the 'Add TID' bit enabled 10437 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 10438 /// of the resource descriptor) to create an offset, which is added to 10439 /// the resource pointer. 10440 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 10441 SDValue Ptr, uint32_t RsrcDword1, 10442 uint64_t RsrcDword2And3) const { 10443 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 10444 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 10445 if (RsrcDword1) { 10446 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 10447 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 10448 0); 10449 } 10450 10451 SDValue DataLo = buildSMovImm32(DAG, DL, 10452 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 10453 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 10454 10455 const SDValue Ops[] = { 10456 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10457 PtrLo, 10458 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10459 PtrHi, 10460 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 10461 DataLo, 10462 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 10463 DataHi, 10464 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 10465 }; 10466 10467 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 10468 } 10469 10470 //===----------------------------------------------------------------------===// 10471 // SI Inline Assembly Support 10472 //===----------------------------------------------------------------------===// 10473 10474 std::pair<unsigned, const TargetRegisterClass *> 10475 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10476 StringRef Constraint, 10477 MVT VT) const { 10478 const TargetRegisterClass *RC = nullptr; 10479 if (Constraint.size() == 1) { 10480 switch (Constraint[0]) { 10481 default: 10482 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10483 case 's': 10484 case 'r': 10485 switch (VT.getSizeInBits()) { 10486 default: 10487 return std::make_pair(0U, nullptr); 10488 case 32: 10489 case 16: 10490 RC = &AMDGPU::SReg_32RegClass; 10491 break; 10492 case 64: 10493 RC = &AMDGPU::SGPR_64RegClass; 10494 break; 10495 case 96: 10496 RC = &AMDGPU::SReg_96RegClass; 10497 break; 10498 case 128: 10499 RC = &AMDGPU::SGPR_128RegClass; 10500 break; 10501 case 160: 10502 RC = &AMDGPU::SReg_160RegClass; 10503 break; 10504 case 256: 10505 RC = &AMDGPU::SReg_256RegClass; 10506 break; 10507 case 512: 10508 RC = &AMDGPU::SReg_512RegClass; 10509 break; 10510 } 10511 break; 10512 case 'v': 10513 switch (VT.getSizeInBits()) { 10514 default: 10515 return std::make_pair(0U, nullptr); 10516 case 32: 10517 case 16: 10518 RC = &AMDGPU::VGPR_32RegClass; 10519 break; 10520 case 64: 10521 RC = &AMDGPU::VReg_64RegClass; 10522 break; 10523 case 96: 10524 RC = &AMDGPU::VReg_96RegClass; 10525 break; 10526 case 128: 10527 RC = &AMDGPU::VReg_128RegClass; 10528 break; 10529 case 160: 10530 RC = &AMDGPU::VReg_160RegClass; 10531 break; 10532 case 256: 10533 RC = &AMDGPU::VReg_256RegClass; 10534 break; 10535 case 512: 10536 RC = &AMDGPU::VReg_512RegClass; 10537 break; 10538 } 10539 break; 10540 case 'a': 10541 if (!Subtarget->hasMAIInsts()) 10542 break; 10543 switch (VT.getSizeInBits()) { 10544 default: 10545 return std::make_pair(0U, nullptr); 10546 case 32: 10547 case 16: 10548 RC = &AMDGPU::AGPR_32RegClass; 10549 break; 10550 case 64: 10551 RC = &AMDGPU::AReg_64RegClass; 10552 break; 10553 case 128: 10554 RC = &AMDGPU::AReg_128RegClass; 10555 break; 10556 case 512: 10557 RC = &AMDGPU::AReg_512RegClass; 10558 break; 10559 case 1024: 10560 RC = &AMDGPU::AReg_1024RegClass; 10561 // v32 types are not legal but we support them here. 10562 return std::make_pair(0U, RC); 10563 } 10564 break; 10565 } 10566 // We actually support i128, i16 and f16 as inline parameters 10567 // even if they are not reported as legal 10568 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 10569 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 10570 return std::make_pair(0U, RC); 10571 } 10572 10573 if (Constraint.size() > 1) { 10574 if (Constraint[1] == 'v') { 10575 RC = &AMDGPU::VGPR_32RegClass; 10576 } else if (Constraint[1] == 's') { 10577 RC = &AMDGPU::SGPR_32RegClass; 10578 } else if (Constraint[1] == 'a') { 10579 RC = &AMDGPU::AGPR_32RegClass; 10580 } 10581 10582 if (RC) { 10583 uint32_t Idx; 10584 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 10585 if (!Failed && Idx < RC->getNumRegs()) 10586 return std::make_pair(RC->getRegister(Idx), RC); 10587 } 10588 } 10589 10590 // FIXME: Returns VS_32 for physical SGPR constraints 10591 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10592 } 10593 10594 SITargetLowering::ConstraintType 10595 SITargetLowering::getConstraintType(StringRef Constraint) const { 10596 if (Constraint.size() == 1) { 10597 switch (Constraint[0]) { 10598 default: break; 10599 case 's': 10600 case 'v': 10601 case 'a': 10602 return C_RegisterClass; 10603 } 10604 } 10605 return TargetLowering::getConstraintType(Constraint); 10606 } 10607 10608 // Figure out which registers should be reserved for stack access. Only after 10609 // the function is legalized do we know all of the non-spill stack objects or if 10610 // calls are present. 10611 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 10612 MachineRegisterInfo &MRI = MF.getRegInfo(); 10613 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10614 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 10615 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10616 10617 if (Info->isEntryFunction()) { 10618 // Callable functions have fixed registers used for stack access. 10619 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 10620 } 10621 10622 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 10623 Info->getStackPtrOffsetReg())); 10624 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 10625 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 10626 10627 // We need to worry about replacing the default register with itself in case 10628 // of MIR testcases missing the MFI. 10629 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 10630 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 10631 10632 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 10633 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 10634 10635 Info->limitOccupancy(MF); 10636 10637 if (ST.isWave32() && !MF.empty()) { 10638 // Add VCC_HI def because many instructions marked as imp-use VCC where 10639 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 10640 // having a use of undef. 10641 10642 const SIInstrInfo *TII = ST.getInstrInfo(); 10643 DebugLoc DL; 10644 10645 MachineBasicBlock &MBB = MF.front(); 10646 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 10647 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 10648 10649 for (auto &MBB : MF) { 10650 for (auto &MI : MBB) { 10651 TII->fixImplicitOperands(MI); 10652 } 10653 } 10654 } 10655 10656 TargetLoweringBase::finalizeLowering(MF); 10657 } 10658 10659 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 10660 KnownBits &Known, 10661 const APInt &DemandedElts, 10662 const SelectionDAG &DAG, 10663 unsigned Depth) const { 10664 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 10665 DAG, Depth); 10666 10667 // Set the high bits to zero based on the maximum allowed scratch size per 10668 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 10669 // calculation won't overflow, so assume the sign bit is never set. 10670 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 10671 } 10672 10673 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 10674 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 10675 const Align CacheLineAlign = Align(64); 10676 10677 // Pre-GFX10 target did not benefit from loop alignment 10678 if (!ML || DisableLoopAlignment || 10679 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 10680 getSubtarget()->hasInstFwdPrefetchBug()) 10681 return PrefAlign; 10682 10683 // On GFX10 I$ is 4 x 64 bytes cache lines. 10684 // By default prefetcher keeps one cache line behind and reads two ahead. 10685 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 10686 // behind and one ahead. 10687 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 10688 // If loop fits 64 bytes it always spans no more than two cache lines and 10689 // does not need an alignment. 10690 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 10691 // Else if loop is less or equal 192 bytes we need two lines behind. 10692 10693 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10694 const MachineBasicBlock *Header = ML->getHeader(); 10695 if (Header->getAlignment() != PrefAlign) 10696 return Header->getAlignment(); // Already processed. 10697 10698 unsigned LoopSize = 0; 10699 for (const MachineBasicBlock *MBB : ML->blocks()) { 10700 // If inner loop block is aligned assume in average half of the alignment 10701 // size to be added as nops. 10702 if (MBB != Header) 10703 LoopSize += MBB->getAlignment().value() / 2; 10704 10705 for (const MachineInstr &MI : *MBB) { 10706 LoopSize += TII->getInstSizeInBytes(MI); 10707 if (LoopSize > 192) 10708 return PrefAlign; 10709 } 10710 } 10711 10712 if (LoopSize <= 64) 10713 return PrefAlign; 10714 10715 if (LoopSize <= 128) 10716 return CacheLineAlign; 10717 10718 // If any of parent loops is surrounded by prefetch instructions do not 10719 // insert new for inner loop, which would reset parent's settings. 10720 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 10721 if (MachineBasicBlock *Exit = P->getExitBlock()) { 10722 auto I = Exit->getFirstNonDebugInstr(); 10723 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 10724 return CacheLineAlign; 10725 } 10726 } 10727 10728 MachineBasicBlock *Pre = ML->getLoopPreheader(); 10729 MachineBasicBlock *Exit = ML->getExitBlock(); 10730 10731 if (Pre && Exit) { 10732 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 10733 TII->get(AMDGPU::S_INST_PREFETCH)) 10734 .addImm(1); // prefetch 2 lines behind PC 10735 10736 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 10737 TII->get(AMDGPU::S_INST_PREFETCH)) 10738 .addImm(2); // prefetch 1 line behind PC 10739 } 10740 10741 return CacheLineAlign; 10742 } 10743 10744 LLVM_ATTRIBUTE_UNUSED 10745 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 10746 assert(N->getOpcode() == ISD::CopyFromReg); 10747 do { 10748 // Follow the chain until we find an INLINEASM node. 10749 N = N->getOperand(0).getNode(); 10750 if (N->getOpcode() == ISD::INLINEASM || 10751 N->getOpcode() == ISD::INLINEASM_BR) 10752 return true; 10753 } while (N->getOpcode() == ISD::CopyFromReg); 10754 return false; 10755 } 10756 10757 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 10758 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 10759 { 10760 switch (N->getOpcode()) { 10761 case ISD::CopyFromReg: 10762 { 10763 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 10764 const MachineFunction * MF = FLI->MF; 10765 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 10766 const MachineRegisterInfo &MRI = MF->getRegInfo(); 10767 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo(); 10768 unsigned Reg = R->getReg(); 10769 if (Register::isPhysicalRegister(Reg)) 10770 return !TRI.isSGPRReg(MRI, Reg); 10771 10772 if (MRI.isLiveIn(Reg)) { 10773 // workitem.id.x workitem.id.y workitem.id.z 10774 // Any VGPR formal argument is also considered divergent 10775 if (!TRI.isSGPRReg(MRI, Reg)) 10776 return true; 10777 // Formal arguments of non-entry functions 10778 // are conservatively considered divergent 10779 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv())) 10780 return true; 10781 return false; 10782 } 10783 const Value *V = FLI->getValueFromVirtualReg(Reg); 10784 if (V) 10785 return KDA->isDivergent(V); 10786 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 10787 return !TRI.isSGPRReg(MRI, Reg); 10788 } 10789 break; 10790 case ISD::LOAD: { 10791 const LoadSDNode *L = cast<LoadSDNode>(N); 10792 unsigned AS = L->getAddressSpace(); 10793 // A flat load may access private memory. 10794 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 10795 } break; 10796 case ISD::CALLSEQ_END: 10797 return true; 10798 break; 10799 case ISD::INTRINSIC_WO_CHAIN: 10800 { 10801 10802 } 10803 return AMDGPU::isIntrinsicSourceOfDivergence( 10804 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 10805 case ISD::INTRINSIC_W_CHAIN: 10806 return AMDGPU::isIntrinsicSourceOfDivergence( 10807 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 10808 } 10809 return false; 10810 } 10811 10812 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 10813 EVT VT) const { 10814 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 10815 case MVT::f32: 10816 return hasFP32Denormals(DAG.getMachineFunction()); 10817 case MVT::f64: 10818 case MVT::f16: 10819 return hasFP64FP16Denormals(DAG.getMachineFunction()); 10820 default: 10821 return false; 10822 } 10823 } 10824 10825 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 10826 const SelectionDAG &DAG, 10827 bool SNaN, 10828 unsigned Depth) const { 10829 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 10830 const MachineFunction &MF = DAG.getMachineFunction(); 10831 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10832 10833 if (Info->getMode().DX10Clamp) 10834 return true; // Clamped to 0. 10835 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 10836 } 10837 10838 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 10839 SNaN, Depth); 10840 } 10841 10842 TargetLowering::AtomicExpansionKind 10843 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 10844 switch (RMW->getOperation()) { 10845 case AtomicRMWInst::FAdd: { 10846 Type *Ty = RMW->getType(); 10847 10848 // We don't have a way to support 16-bit atomics now, so just leave them 10849 // as-is. 10850 if (Ty->isHalfTy()) 10851 return AtomicExpansionKind::None; 10852 10853 if (!Ty->isFloatTy()) 10854 return AtomicExpansionKind::CmpXChg; 10855 10856 // TODO: Do have these for flat. Older targets also had them for buffers. 10857 unsigned AS = RMW->getPointerAddressSpace(); 10858 10859 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 10860 return RMW->use_empty() ? AtomicExpansionKind::None : 10861 AtomicExpansionKind::CmpXChg; 10862 } 10863 10864 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 10865 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 10866 } 10867 default: 10868 break; 10869 } 10870 10871 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 10872 } 10873 10874 const TargetRegisterClass * 10875 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 10876 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 10877 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10878 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 10879 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 10880 : &AMDGPU::SReg_32RegClass; 10881 if (!TRI->isSGPRClass(RC) && !isDivergent) 10882 return TRI->getEquivalentSGPRClass(RC); 10883 else if (TRI->isSGPRClass(RC) && isDivergent) 10884 return TRI->getEquivalentVGPRClass(RC); 10885 10886 return RC; 10887 } 10888 10889 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 10890 unsigned WaveSize) { 10891 // FIXME: We asssume we never cast the mask results of a control flow 10892 // intrinsic. 10893 // Early exit if the type won't be consistent as a compile time hack. 10894 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 10895 if (!IT || IT->getBitWidth() != WaveSize) 10896 return false; 10897 10898 if (!isa<Instruction>(V)) 10899 return false; 10900 if (!Visited.insert(V).second) 10901 return false; 10902 bool Result = false; 10903 for (auto U : V->users()) { 10904 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 10905 if (V == U->getOperand(1)) { 10906 switch (Intrinsic->getIntrinsicID()) { 10907 default: 10908 Result = false; 10909 break; 10910 case Intrinsic::amdgcn_if_break: 10911 case Intrinsic::amdgcn_if: 10912 case Intrinsic::amdgcn_else: 10913 Result = true; 10914 break; 10915 } 10916 } 10917 if (V == U->getOperand(0)) { 10918 switch (Intrinsic->getIntrinsicID()) { 10919 default: 10920 Result = false; 10921 break; 10922 case Intrinsic::amdgcn_end_cf: 10923 case Intrinsic::amdgcn_loop: 10924 Result = true; 10925 break; 10926 } 10927 } 10928 } else { 10929 Result = hasCFUser(U, Visited, WaveSize); 10930 } 10931 if (Result) 10932 break; 10933 } 10934 return Result; 10935 } 10936 10937 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 10938 const Value *V) const { 10939 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) { 10940 switch (Intrinsic->getIntrinsicID()) { 10941 default: 10942 return false; 10943 case Intrinsic::amdgcn_if_break: 10944 return true; 10945 } 10946 } 10947 if (const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V)) { 10948 if (const IntrinsicInst *Intrinsic = 10949 dyn_cast<IntrinsicInst>(ExtValue->getOperand(0))) { 10950 switch (Intrinsic->getIntrinsicID()) { 10951 default: 10952 return false; 10953 case Intrinsic::amdgcn_if: 10954 case Intrinsic::amdgcn_else: { 10955 ArrayRef<unsigned> Indices = ExtValue->getIndices(); 10956 if (Indices.size() == 1 && Indices[0] == 1) { 10957 return true; 10958 } 10959 } 10960 } 10961 } 10962 } 10963 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 10964 if (isa<InlineAsm>(CI->getCalledValue())) { 10965 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 10966 ImmutableCallSite CS(CI); 10967 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 10968 MF.getDataLayout(), Subtarget->getRegisterInfo(), CS); 10969 for (auto &TC : TargetConstraints) { 10970 if (TC.Type == InlineAsm::isOutput) { 10971 ComputeConstraintToUse(TC, SDValue()); 10972 unsigned AssignedReg; 10973 const TargetRegisterClass *RC; 10974 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 10975 SIRI, TC.ConstraintCode, TC.ConstraintVT); 10976 if (RC) { 10977 MachineRegisterInfo &MRI = MF.getRegInfo(); 10978 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 10979 return true; 10980 else if (SIRI->isSGPRClass(RC)) 10981 return true; 10982 } 10983 } 10984 } 10985 } 10986 } 10987 SmallPtrSet<const Value *, 16> Visited; 10988 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 10989 } 10990