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::SGPR_256RegClass); 145 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 146 147 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_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 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 206 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 207 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 208 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 209 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 210 211 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 212 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 213 214 setOperationAction(ISD::SELECT, MVT::i1, Promote); 215 setOperationAction(ISD::SELECT, MVT::i64, Custom); 216 setOperationAction(ISD::SELECT, MVT::f64, Promote); 217 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 218 219 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 220 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 221 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 222 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 223 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 224 225 setOperationAction(ISD::SETCC, MVT::i1, Promote); 226 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 227 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 228 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 229 230 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 231 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 232 233 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 234 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 235 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 236 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 237 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 238 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 239 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 240 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 241 242 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 243 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 244 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 245 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 246 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 247 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 248 249 setOperationAction(ISD::UADDO, MVT::i32, Legal); 250 setOperationAction(ISD::USUBO, MVT::i32, Legal); 251 252 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 253 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 254 255 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 256 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 257 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 258 259 #if 0 260 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 261 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 262 #endif 263 264 // We only support LOAD/STORE and vector manipulation ops for vectors 265 // with > 4 elements. 266 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 267 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 268 MVT::v32i32, MVT::v32f32 }) { 269 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 270 switch (Op) { 271 case ISD::LOAD: 272 case ISD::STORE: 273 case ISD::BUILD_VECTOR: 274 case ISD::BITCAST: 275 case ISD::EXTRACT_VECTOR_ELT: 276 case ISD::INSERT_VECTOR_ELT: 277 case ISD::INSERT_SUBVECTOR: 278 case ISD::EXTRACT_SUBVECTOR: 279 case ISD::SCALAR_TO_VECTOR: 280 break; 281 case ISD::CONCAT_VECTORS: 282 setOperationAction(Op, VT, Custom); 283 break; 284 default: 285 setOperationAction(Op, VT, Expand); 286 break; 287 } 288 } 289 } 290 291 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 292 293 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 294 // is expanded to avoid having two separate loops in case the index is a VGPR. 295 296 // Most operations are naturally 32-bit vector operations. We only support 297 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 298 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 299 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 300 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 301 302 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 303 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 304 305 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 306 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 307 308 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 309 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 310 } 311 312 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 313 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 314 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 315 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 316 317 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 318 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 319 320 // Avoid stack access for these. 321 // TODO: Generalize to more vector types. 322 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 323 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 324 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 325 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 326 327 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 328 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 329 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 330 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 331 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 332 333 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 334 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 335 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 336 337 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 338 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 339 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 340 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 341 342 // Deal with vec3 vector operations when widened to vec4. 343 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 344 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 345 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 346 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 347 348 // Deal with vec5 vector operations when widened to vec8. 349 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 350 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 351 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 352 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 353 354 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 355 // and output demarshalling 356 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 357 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 358 359 // We can't return success/failure, only the old value, 360 // let LLVM add the comparison 361 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 362 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 363 364 if (Subtarget->hasFlatAddressSpace()) { 365 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 366 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 367 } 368 369 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 370 371 // FIXME: This should be narrowed to i32, but that only happens if i64 is 372 // illegal. 373 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 374 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 375 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 376 377 // On SI this is s_memtime and s_memrealtime on VI. 378 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 379 setOperationAction(ISD::TRAP, MVT::Other, Custom); 380 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 381 382 if (Subtarget->has16BitInsts()) { 383 setOperationAction(ISD::FPOW, MVT::f16, Promote); 384 setOperationAction(ISD::FLOG, MVT::f16, Custom); 385 setOperationAction(ISD::FEXP, MVT::f16, Custom); 386 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 387 } 388 389 // v_mad_f32 does not support denormals. We report it as unconditionally 390 // legal, and the context where it is formed will disallow it when fp32 391 // denormals are enabled. 392 setOperationAction(ISD::FMAD, MVT::f32, Legal); 393 394 if (!Subtarget->hasBFI()) { 395 // fcopysign can be done in a single instruction with BFI. 396 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 397 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 398 } 399 400 if (!Subtarget->hasBCNT(32)) 401 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 402 403 if (!Subtarget->hasBCNT(64)) 404 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 405 406 if (Subtarget->hasFFBH()) 407 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 408 409 if (Subtarget->hasFFBL()) 410 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 411 412 // We only really have 32-bit BFE instructions (and 16-bit on VI). 413 // 414 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 415 // effort to match them now. We want this to be false for i64 cases when the 416 // extraction isn't restricted to the upper or lower half. Ideally we would 417 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 418 // span the midpoint are probably relatively rare, so don't worry about them 419 // for now. 420 if (Subtarget->hasBFE()) 421 setHasExtractBitsInsn(true); 422 423 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 424 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 425 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 426 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 427 428 429 // These are really only legal for ieee_mode functions. We should be avoiding 430 // them for functions that don't have ieee_mode enabled, so just say they are 431 // legal. 432 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 433 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 434 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 435 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 436 437 438 if (Subtarget->haveRoundOpsF64()) { 439 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 440 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 441 setOperationAction(ISD::FRINT, MVT::f64, Legal); 442 } else { 443 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 444 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 445 setOperationAction(ISD::FRINT, MVT::f64, Custom); 446 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 447 } 448 449 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 450 451 setOperationAction(ISD::FSIN, MVT::f32, Custom); 452 setOperationAction(ISD::FCOS, MVT::f32, Custom); 453 setOperationAction(ISD::FDIV, MVT::f32, Custom); 454 setOperationAction(ISD::FDIV, MVT::f64, Custom); 455 456 if (Subtarget->has16BitInsts()) { 457 setOperationAction(ISD::Constant, MVT::i16, Legal); 458 459 setOperationAction(ISD::SMIN, MVT::i16, Legal); 460 setOperationAction(ISD::SMAX, MVT::i16, Legal); 461 462 setOperationAction(ISD::UMIN, MVT::i16, Legal); 463 setOperationAction(ISD::UMAX, MVT::i16, Legal); 464 465 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 466 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 467 468 setOperationAction(ISD::ROTR, MVT::i16, Promote); 469 setOperationAction(ISD::ROTL, MVT::i16, Promote); 470 471 setOperationAction(ISD::SDIV, MVT::i16, Promote); 472 setOperationAction(ISD::UDIV, MVT::i16, Promote); 473 setOperationAction(ISD::SREM, MVT::i16, Promote); 474 setOperationAction(ISD::UREM, MVT::i16, Promote); 475 476 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 477 478 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 479 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 480 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 481 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 482 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 483 484 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 485 486 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 487 488 setOperationAction(ISD::LOAD, MVT::i16, Custom); 489 490 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 491 492 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 493 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 494 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 495 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 496 497 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 498 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 499 500 // F16 - Constant Actions. 501 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 502 503 // F16 - Load/Store Actions. 504 setOperationAction(ISD::LOAD, MVT::f16, Promote); 505 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 506 setOperationAction(ISD::STORE, MVT::f16, Promote); 507 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 508 509 // F16 - VOP1 Actions. 510 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 511 setOperationAction(ISD::FCOS, MVT::f16, Custom); 512 setOperationAction(ISD::FSIN, MVT::f16, Custom); 513 514 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 515 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 516 517 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 518 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 519 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 520 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 521 setOperationAction(ISD::FROUND, MVT::f16, Custom); 522 523 // F16 - VOP2 Actions. 524 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 525 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 526 527 setOperationAction(ISD::FDIV, MVT::f16, Custom); 528 529 // F16 - VOP3 Actions. 530 setOperationAction(ISD::FMA, MVT::f16, Legal); 531 if (STI.hasMadF16()) 532 setOperationAction(ISD::FMAD, MVT::f16, Legal); 533 534 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 535 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 536 switch (Op) { 537 case ISD::LOAD: 538 case ISD::STORE: 539 case ISD::BUILD_VECTOR: 540 case ISD::BITCAST: 541 case ISD::EXTRACT_VECTOR_ELT: 542 case ISD::INSERT_VECTOR_ELT: 543 case ISD::INSERT_SUBVECTOR: 544 case ISD::EXTRACT_SUBVECTOR: 545 case ISD::SCALAR_TO_VECTOR: 546 break; 547 case ISD::CONCAT_VECTORS: 548 setOperationAction(Op, VT, Custom); 549 break; 550 default: 551 setOperationAction(Op, VT, Expand); 552 break; 553 } 554 } 555 } 556 557 // v_perm_b32 can handle either of these. 558 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 559 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 560 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 561 562 // XXX - Do these do anything? Vector constants turn into build_vector. 563 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 564 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 565 566 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 567 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 568 569 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 570 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 571 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 572 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 573 574 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 575 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 576 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 577 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 578 579 setOperationAction(ISD::AND, MVT::v2i16, Promote); 580 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 581 setOperationAction(ISD::OR, MVT::v2i16, Promote); 582 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 583 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 584 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 585 586 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 587 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 588 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 589 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 590 591 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 592 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 593 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 594 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 595 596 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 597 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 598 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 599 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 600 601 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 602 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 603 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 604 605 if (!Subtarget->hasVOP3PInsts()) { 606 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 607 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 608 } 609 610 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 611 // This isn't really legal, but this avoids the legalizer unrolling it (and 612 // allows matching fneg (fabs x) patterns) 613 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 614 615 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 616 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 617 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 618 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 619 620 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 621 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 622 623 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 624 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 625 } 626 627 if (Subtarget->hasVOP3PInsts()) { 628 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 629 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 630 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 631 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 632 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 633 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 634 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 635 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 636 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 637 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 638 639 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 640 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 641 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 642 643 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 644 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 645 646 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 647 648 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 649 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 650 651 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 652 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 653 654 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 655 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 656 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 657 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 658 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 659 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 660 661 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 662 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 663 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 664 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 665 666 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 667 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 668 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 669 670 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 671 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 672 673 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 674 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 675 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 676 677 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 678 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 679 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 680 } 681 682 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 683 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 684 685 if (Subtarget->has16BitInsts()) { 686 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 687 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 688 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 689 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 690 } else { 691 // Legalization hack. 692 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 693 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 694 695 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 696 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 697 } 698 699 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 700 setOperationAction(ISD::SELECT, VT, Custom); 701 } 702 703 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 704 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 705 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 706 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 707 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 708 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 709 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 710 711 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 712 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 713 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 714 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 715 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 716 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 717 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 718 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 719 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 720 721 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 722 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 723 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 724 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 725 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 726 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 727 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 728 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 729 730 setTargetDAGCombine(ISD::ADD); 731 setTargetDAGCombine(ISD::ADDCARRY); 732 setTargetDAGCombine(ISD::SUB); 733 setTargetDAGCombine(ISD::SUBCARRY); 734 setTargetDAGCombine(ISD::FADD); 735 setTargetDAGCombine(ISD::FSUB); 736 setTargetDAGCombine(ISD::FMINNUM); 737 setTargetDAGCombine(ISD::FMAXNUM); 738 setTargetDAGCombine(ISD::FMINNUM_IEEE); 739 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 740 setTargetDAGCombine(ISD::FMA); 741 setTargetDAGCombine(ISD::SMIN); 742 setTargetDAGCombine(ISD::SMAX); 743 setTargetDAGCombine(ISD::UMIN); 744 setTargetDAGCombine(ISD::UMAX); 745 setTargetDAGCombine(ISD::SETCC); 746 setTargetDAGCombine(ISD::AND); 747 setTargetDAGCombine(ISD::OR); 748 setTargetDAGCombine(ISD::XOR); 749 setTargetDAGCombine(ISD::SINT_TO_FP); 750 setTargetDAGCombine(ISD::UINT_TO_FP); 751 setTargetDAGCombine(ISD::FCANONICALIZE); 752 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 753 setTargetDAGCombine(ISD::ZERO_EXTEND); 754 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 755 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 756 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 757 758 // All memory operations. Some folding on the pointer operand is done to help 759 // matching the constant offsets in the addressing modes. 760 setTargetDAGCombine(ISD::LOAD); 761 setTargetDAGCombine(ISD::STORE); 762 setTargetDAGCombine(ISD::ATOMIC_LOAD); 763 setTargetDAGCombine(ISD::ATOMIC_STORE); 764 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 765 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 766 setTargetDAGCombine(ISD::ATOMIC_SWAP); 767 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 768 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 769 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 770 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 771 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 772 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 773 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 774 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 775 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 776 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 777 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 778 779 setSchedulingPreference(Sched::RegPressure); 780 } 781 782 const GCNSubtarget *SITargetLowering::getSubtarget() const { 783 return Subtarget; 784 } 785 786 //===----------------------------------------------------------------------===// 787 // TargetLowering queries 788 //===----------------------------------------------------------------------===// 789 790 // v_mad_mix* support a conversion from f16 to f32. 791 // 792 // There is only one special case when denormals are enabled we don't currently, 793 // where this is OK to use. 794 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 795 EVT DestVT, EVT SrcVT) const { 796 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 797 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 798 DestVT.getScalarType() == MVT::f32 && 799 SrcVT.getScalarType() == MVT::f16 && 800 // TODO: This probably only requires no input flushing? 801 !hasFP32Denormals(DAG.getMachineFunction()); 802 } 803 804 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 805 // SI has some legal vector types, but no legal vector operations. Say no 806 // shuffles are legal in order to prefer scalarizing some vector operations. 807 return false; 808 } 809 810 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 811 CallingConv::ID CC, 812 EVT VT) const { 813 if (CC == CallingConv::AMDGPU_KERNEL) 814 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 815 816 if (VT.isVector()) { 817 EVT ScalarVT = VT.getScalarType(); 818 unsigned Size = ScalarVT.getSizeInBits(); 819 if (Size == 32) 820 return ScalarVT.getSimpleVT(); 821 822 if (Size > 32) 823 return MVT::i32; 824 825 if (Size == 16 && Subtarget->has16BitInsts()) 826 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 827 } else if (VT.getSizeInBits() > 32) 828 return MVT::i32; 829 830 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 831 } 832 833 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 834 CallingConv::ID CC, 835 EVT VT) const { 836 if (CC == CallingConv::AMDGPU_KERNEL) 837 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 838 839 if (VT.isVector()) { 840 unsigned NumElts = VT.getVectorNumElements(); 841 EVT ScalarVT = VT.getScalarType(); 842 unsigned Size = ScalarVT.getSizeInBits(); 843 844 if (Size == 32) 845 return NumElts; 846 847 if (Size > 32) 848 return NumElts * ((Size + 31) / 32); 849 850 if (Size == 16 && Subtarget->has16BitInsts()) 851 return (NumElts + 1) / 2; 852 } else if (VT.getSizeInBits() > 32) 853 return (VT.getSizeInBits() + 31) / 32; 854 855 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 856 } 857 858 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 859 LLVMContext &Context, CallingConv::ID CC, 860 EVT VT, EVT &IntermediateVT, 861 unsigned &NumIntermediates, MVT &RegisterVT) const { 862 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 863 unsigned NumElts = VT.getVectorNumElements(); 864 EVT ScalarVT = VT.getScalarType(); 865 unsigned Size = ScalarVT.getSizeInBits(); 866 if (Size == 32) { 867 RegisterVT = ScalarVT.getSimpleVT(); 868 IntermediateVT = RegisterVT; 869 NumIntermediates = NumElts; 870 return NumIntermediates; 871 } 872 873 if (Size > 32) { 874 RegisterVT = MVT::i32; 875 IntermediateVT = RegisterVT; 876 NumIntermediates = NumElts * ((Size + 31) / 32); 877 return NumIntermediates; 878 } 879 880 // FIXME: We should fix the ABI to be the same on targets without 16-bit 881 // support, but unless we can properly handle 3-vectors, it will be still be 882 // inconsistent. 883 if (Size == 16 && Subtarget->has16BitInsts()) { 884 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 885 IntermediateVT = RegisterVT; 886 NumIntermediates = (NumElts + 1) / 2; 887 return NumIntermediates; 888 } 889 } 890 891 return TargetLowering::getVectorTypeBreakdownForCallingConv( 892 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 893 } 894 895 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 896 assert(DMaskLanes != 0); 897 898 if (auto *VT = dyn_cast<VectorType>(Ty)) { 899 unsigned NumElts = std::min(DMaskLanes, 900 static_cast<unsigned>(VT->getNumElements())); 901 return EVT::getVectorVT(Ty->getContext(), 902 EVT::getEVT(VT->getElementType()), 903 NumElts); 904 } 905 906 return EVT::getEVT(Ty); 907 } 908 909 // Peek through TFE struct returns to only use the data size. 910 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 911 auto *ST = dyn_cast<StructType>(Ty); 912 if (!ST) 913 return memVTFromImageData(Ty, DMaskLanes); 914 915 // Some intrinsics return an aggregate type - special case to work out the 916 // correct memVT. 917 // 918 // Only limited forms of aggregate type currently expected. 919 if (ST->getNumContainedTypes() != 2 || 920 !ST->getContainedType(1)->isIntegerTy(32)) 921 return EVT(); 922 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 923 } 924 925 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 926 const CallInst &CI, 927 MachineFunction &MF, 928 unsigned IntrID) const { 929 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 930 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 931 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 932 (Intrinsic::ID)IntrID); 933 if (Attr.hasFnAttribute(Attribute::ReadNone)) 934 return false; 935 936 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 937 938 if (RsrcIntr->IsImage) { 939 Info.ptrVal = MFI->getImagePSV( 940 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 941 CI.getArgOperand(RsrcIntr->RsrcArg)); 942 Info.align.reset(); 943 } else { 944 Info.ptrVal = MFI->getBufferPSV( 945 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 946 CI.getArgOperand(RsrcIntr->RsrcArg)); 947 } 948 949 Info.flags = MachineMemOperand::MODereferenceable; 950 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 951 unsigned DMaskLanes = 4; 952 953 if (RsrcIntr->IsImage) { 954 const AMDGPU::ImageDimIntrinsicInfo *Intr 955 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 956 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 957 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 958 959 if (!BaseOpcode->Gather4) { 960 // If this isn't a gather, we may have excess loaded elements in the 961 // IR type. Check the dmask for the real number of elements loaded. 962 unsigned DMask 963 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 964 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 965 } 966 967 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 968 } else 969 Info.memVT = EVT::getEVT(CI.getType()); 970 971 // FIXME: What does alignment mean for an image? 972 Info.opc = ISD::INTRINSIC_W_CHAIN; 973 Info.flags |= MachineMemOperand::MOLoad; 974 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 975 Info.opc = ISD::INTRINSIC_VOID; 976 977 Type *DataTy = CI.getArgOperand(0)->getType(); 978 if (RsrcIntr->IsImage) { 979 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 980 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 981 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 982 } else 983 Info.memVT = EVT::getEVT(DataTy); 984 985 Info.flags |= MachineMemOperand::MOStore; 986 } else { 987 // Atomic 988 Info.opc = ISD::INTRINSIC_W_CHAIN; 989 Info.memVT = MVT::getVT(CI.getType()); 990 Info.flags = MachineMemOperand::MOLoad | 991 MachineMemOperand::MOStore | 992 MachineMemOperand::MODereferenceable; 993 994 // XXX - Should this be volatile without known ordering? 995 Info.flags |= MachineMemOperand::MOVolatile; 996 } 997 return true; 998 } 999 1000 switch (IntrID) { 1001 case Intrinsic::amdgcn_atomic_inc: 1002 case Intrinsic::amdgcn_atomic_dec: 1003 case Intrinsic::amdgcn_ds_ordered_add: 1004 case Intrinsic::amdgcn_ds_ordered_swap: 1005 case Intrinsic::amdgcn_ds_fadd: 1006 case Intrinsic::amdgcn_ds_fmin: 1007 case Intrinsic::amdgcn_ds_fmax: { 1008 Info.opc = ISD::INTRINSIC_W_CHAIN; 1009 Info.memVT = MVT::getVT(CI.getType()); 1010 Info.ptrVal = CI.getOperand(0); 1011 Info.align.reset(); 1012 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1013 1014 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1015 if (!Vol->isZero()) 1016 Info.flags |= MachineMemOperand::MOVolatile; 1017 1018 return true; 1019 } 1020 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1021 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1022 1023 Info.opc = ISD::INTRINSIC_VOID; 1024 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1025 Info.ptrVal = MFI->getBufferPSV( 1026 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1027 CI.getArgOperand(1)); 1028 Info.align.reset(); 1029 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1030 1031 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1032 if (!Vol || !Vol->isZero()) 1033 Info.flags |= MachineMemOperand::MOVolatile; 1034 1035 return true; 1036 } 1037 case Intrinsic::amdgcn_global_atomic_fadd: { 1038 Info.opc = ISD::INTRINSIC_VOID; 1039 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 1040 ->getPointerElementType()); 1041 Info.ptrVal = CI.getOperand(0); 1042 Info.align.reset(); 1043 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1044 1045 return true; 1046 } 1047 case Intrinsic::amdgcn_ds_append: 1048 case Intrinsic::amdgcn_ds_consume: { 1049 Info.opc = ISD::INTRINSIC_W_CHAIN; 1050 Info.memVT = MVT::getVT(CI.getType()); 1051 Info.ptrVal = CI.getOperand(0); 1052 Info.align.reset(); 1053 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1054 1055 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1056 if (!Vol->isZero()) 1057 Info.flags |= MachineMemOperand::MOVolatile; 1058 1059 return true; 1060 } 1061 case Intrinsic::amdgcn_ds_gws_init: 1062 case Intrinsic::amdgcn_ds_gws_barrier: 1063 case Intrinsic::amdgcn_ds_gws_sema_v: 1064 case Intrinsic::amdgcn_ds_gws_sema_br: 1065 case Intrinsic::amdgcn_ds_gws_sema_p: 1066 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1067 Info.opc = ISD::INTRINSIC_VOID; 1068 1069 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1070 Info.ptrVal = 1071 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1072 1073 // This is an abstract access, but we need to specify a type and size. 1074 Info.memVT = MVT::i32; 1075 Info.size = 4; 1076 Info.align = Align(4); 1077 1078 Info.flags = MachineMemOperand::MOStore; 1079 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1080 Info.flags = MachineMemOperand::MOLoad; 1081 return true; 1082 } 1083 default: 1084 return false; 1085 } 1086 } 1087 1088 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1089 SmallVectorImpl<Value*> &Ops, 1090 Type *&AccessTy) const { 1091 switch (II->getIntrinsicID()) { 1092 case Intrinsic::amdgcn_atomic_inc: 1093 case Intrinsic::amdgcn_atomic_dec: 1094 case Intrinsic::amdgcn_ds_ordered_add: 1095 case Intrinsic::amdgcn_ds_ordered_swap: 1096 case Intrinsic::amdgcn_ds_fadd: 1097 case Intrinsic::amdgcn_ds_fmin: 1098 case Intrinsic::amdgcn_ds_fmax: { 1099 Value *Ptr = II->getArgOperand(0); 1100 AccessTy = II->getType(); 1101 Ops.push_back(Ptr); 1102 return true; 1103 } 1104 default: 1105 return false; 1106 } 1107 } 1108 1109 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1110 if (!Subtarget->hasFlatInstOffsets()) { 1111 // Flat instructions do not have offsets, and only have the register 1112 // address. 1113 return AM.BaseOffs == 0 && AM.Scale == 0; 1114 } 1115 1116 return AM.Scale == 0 && 1117 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1118 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1119 /*Signed=*/false)); 1120 } 1121 1122 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1123 if (Subtarget->hasFlatGlobalInsts()) 1124 return AM.Scale == 0 && 1125 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1126 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1127 /*Signed=*/true)); 1128 1129 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1130 // Assume the we will use FLAT for all global memory accesses 1131 // on VI. 1132 // FIXME: This assumption is currently wrong. On VI we still use 1133 // MUBUF instructions for the r + i addressing mode. As currently 1134 // implemented, the MUBUF instructions only work on buffer < 4GB. 1135 // It may be possible to support > 4GB buffers with MUBUF instructions, 1136 // by setting the stride value in the resource descriptor which would 1137 // increase the size limit to (stride * 4GB). However, this is risky, 1138 // because it has never been validated. 1139 return isLegalFlatAddressingMode(AM); 1140 } 1141 1142 return isLegalMUBUFAddressingMode(AM); 1143 } 1144 1145 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1146 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1147 // additionally can do r + r + i with addr64. 32-bit has more addressing 1148 // mode options. Depending on the resource constant, it can also do 1149 // (i64 r0) + (i32 r1) * (i14 i). 1150 // 1151 // Private arrays end up using a scratch buffer most of the time, so also 1152 // assume those use MUBUF instructions. Scratch loads / stores are currently 1153 // implemented as mubuf instructions with offen bit set, so slightly 1154 // different than the normal addr64. 1155 if (!isUInt<12>(AM.BaseOffs)) 1156 return false; 1157 1158 // FIXME: Since we can split immediate into soffset and immediate offset, 1159 // would it make sense to allow any immediate? 1160 1161 switch (AM.Scale) { 1162 case 0: // r + i or just i, depending on HasBaseReg. 1163 return true; 1164 case 1: 1165 return true; // We have r + r or r + i. 1166 case 2: 1167 if (AM.HasBaseReg) { 1168 // Reject 2 * r + r. 1169 return false; 1170 } 1171 1172 // Allow 2 * r as r + r 1173 // Or 2 * r + i is allowed as r + r + i. 1174 return true; 1175 default: // Don't allow n * r 1176 return false; 1177 } 1178 } 1179 1180 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1181 const AddrMode &AM, Type *Ty, 1182 unsigned AS, Instruction *I) const { 1183 // No global is ever allowed as a base. 1184 if (AM.BaseGV) 1185 return false; 1186 1187 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1188 return isLegalGlobalAddressingMode(AM); 1189 1190 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1191 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1192 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1193 // If the offset isn't a multiple of 4, it probably isn't going to be 1194 // correctly aligned. 1195 // FIXME: Can we get the real alignment here? 1196 if (AM.BaseOffs % 4 != 0) 1197 return isLegalMUBUFAddressingMode(AM); 1198 1199 // There are no SMRD extloads, so if we have to do a small type access we 1200 // will use a MUBUF load. 1201 // FIXME?: We also need to do this if unaligned, but we don't know the 1202 // alignment here. 1203 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1204 return isLegalGlobalAddressingMode(AM); 1205 1206 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1207 // SMRD instructions have an 8-bit, dword offset on SI. 1208 if (!isUInt<8>(AM.BaseOffs / 4)) 1209 return false; 1210 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1211 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1212 // in 8-bits, it can use a smaller encoding. 1213 if (!isUInt<32>(AM.BaseOffs / 4)) 1214 return false; 1215 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1216 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1217 if (!isUInt<20>(AM.BaseOffs)) 1218 return false; 1219 } else 1220 llvm_unreachable("unhandled generation"); 1221 1222 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1223 return true; 1224 1225 if (AM.Scale == 1 && AM.HasBaseReg) 1226 return true; 1227 1228 return false; 1229 1230 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1231 return isLegalMUBUFAddressingMode(AM); 1232 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1233 AS == AMDGPUAS::REGION_ADDRESS) { 1234 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1235 // field. 1236 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1237 // an 8-bit dword offset but we don't know the alignment here. 1238 if (!isUInt<16>(AM.BaseOffs)) 1239 return false; 1240 1241 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1242 return true; 1243 1244 if (AM.Scale == 1 && AM.HasBaseReg) 1245 return true; 1246 1247 return false; 1248 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1249 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1250 // For an unknown address space, this usually means that this is for some 1251 // reason being used for pure arithmetic, and not based on some addressing 1252 // computation. We don't have instructions that compute pointers with any 1253 // addressing modes, so treat them as having no offset like flat 1254 // instructions. 1255 return isLegalFlatAddressingMode(AM); 1256 } else { 1257 llvm_unreachable("unhandled address space"); 1258 } 1259 } 1260 1261 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1262 const SelectionDAG &DAG) const { 1263 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1264 return (MemVT.getSizeInBits() <= 4 * 32); 1265 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1266 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1267 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1268 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1269 return (MemVT.getSizeInBits() <= 2 * 32); 1270 } 1271 return true; 1272 } 1273 1274 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1275 unsigned Size, unsigned AddrSpace, unsigned Align, 1276 MachineMemOperand::Flags Flags, bool *IsFast) const { 1277 if (IsFast) 1278 *IsFast = false; 1279 1280 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1281 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1282 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1283 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1284 // with adjacent offsets. 1285 bool AlignedBy4 = (Align % 4 == 0); 1286 if (IsFast) 1287 *IsFast = AlignedBy4; 1288 1289 return AlignedBy4; 1290 } 1291 1292 // FIXME: We have to be conservative here and assume that flat operations 1293 // will access scratch. If we had access to the IR function, then we 1294 // could determine if any private memory was used in the function. 1295 if (!Subtarget->hasUnalignedScratchAccess() && 1296 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1297 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1298 bool AlignedBy4 = Align >= 4; 1299 if (IsFast) 1300 *IsFast = AlignedBy4; 1301 1302 return AlignedBy4; 1303 } 1304 1305 if (Subtarget->hasUnalignedBufferAccess()) { 1306 // If we have an uniform constant load, it still requires using a slow 1307 // buffer instruction if unaligned. 1308 if (IsFast) { 1309 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1310 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1311 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1312 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1313 Align >= 4 : Align != 2; 1314 } 1315 1316 return true; 1317 } 1318 1319 // Smaller than dword value must be aligned. 1320 if (Size < 32) 1321 return false; 1322 1323 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1324 // byte-address are ignored, thus forcing Dword alignment. 1325 // This applies to private, global, and constant memory. 1326 if (IsFast) 1327 *IsFast = true; 1328 1329 return Size >= 32 && Align >= 4; 1330 } 1331 1332 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1333 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1334 bool *IsFast) const { 1335 if (IsFast) 1336 *IsFast = false; 1337 1338 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1339 // which isn't a simple VT. 1340 // Until MVT is extended to handle this, simply check for the size and 1341 // rely on the condition below: allow accesses if the size is a multiple of 4. 1342 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1343 VT.getStoreSize() > 16)) { 1344 return false; 1345 } 1346 1347 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1348 Align, Flags, IsFast); 1349 } 1350 1351 EVT SITargetLowering::getOptimalMemOpType( 1352 const MemOp &Op, const AttributeList &FuncAttributes) const { 1353 // FIXME: Should account for address space here. 1354 1355 // The default fallback uses the private pointer size as a guess for a type to 1356 // use. Make sure we switch these to 64-bit accesses. 1357 1358 if (Op.size() >= 16 && 1359 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1360 return MVT::v4i32; 1361 1362 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1363 return MVT::v2i32; 1364 1365 // Use the default. 1366 return MVT::Other; 1367 } 1368 1369 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1370 unsigned DestAS) const { 1371 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1372 } 1373 1374 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1375 const MemSDNode *MemNode = cast<MemSDNode>(N); 1376 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1377 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1378 return I && I->getMetadata("amdgpu.noclobber"); 1379 } 1380 1381 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1382 unsigned DestAS) const { 1383 // Flat -> private/local is a simple truncate. 1384 // Flat -> global is no-op 1385 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1386 return true; 1387 1388 return isNoopAddrSpaceCast(SrcAS, DestAS); 1389 } 1390 1391 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1392 const MemSDNode *MemNode = cast<MemSDNode>(N); 1393 1394 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1395 } 1396 1397 TargetLoweringBase::LegalizeTypeAction 1398 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1399 int NumElts = VT.getVectorNumElements(); 1400 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1401 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1402 return TargetLoweringBase::getPreferredVectorAction(VT); 1403 } 1404 1405 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1406 Type *Ty) const { 1407 // FIXME: Could be smarter if called for vector constants. 1408 return true; 1409 } 1410 1411 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1412 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1413 switch (Op) { 1414 case ISD::LOAD: 1415 case ISD::STORE: 1416 1417 // These operations are done with 32-bit instructions anyway. 1418 case ISD::AND: 1419 case ISD::OR: 1420 case ISD::XOR: 1421 case ISD::SELECT: 1422 // TODO: Extensions? 1423 return true; 1424 default: 1425 return false; 1426 } 1427 } 1428 1429 // SimplifySetCC uses this function to determine whether or not it should 1430 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1431 if (VT == MVT::i1 && Op == ISD::SETCC) 1432 return false; 1433 1434 return TargetLowering::isTypeDesirableForOp(Op, VT); 1435 } 1436 1437 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1438 const SDLoc &SL, 1439 SDValue Chain, 1440 uint64_t Offset) const { 1441 const DataLayout &DL = DAG.getDataLayout(); 1442 MachineFunction &MF = DAG.getMachineFunction(); 1443 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1444 1445 const ArgDescriptor *InputPtrReg; 1446 const TargetRegisterClass *RC; 1447 1448 std::tie(InputPtrReg, RC) 1449 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1450 1451 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1452 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1453 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1454 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1455 1456 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1457 } 1458 1459 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1460 const SDLoc &SL) const { 1461 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1462 FIRST_IMPLICIT); 1463 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1464 } 1465 1466 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1467 const SDLoc &SL, SDValue Val, 1468 bool Signed, 1469 const ISD::InputArg *Arg) const { 1470 // First, if it is a widened vector, narrow it. 1471 if (VT.isVector() && 1472 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1473 EVT NarrowedVT = 1474 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1475 VT.getVectorNumElements()); 1476 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1477 DAG.getConstant(0, SL, MVT::i32)); 1478 } 1479 1480 // Then convert the vector elements or scalar value. 1481 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1482 VT.bitsLT(MemVT)) { 1483 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1484 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1485 } 1486 1487 if (MemVT.isFloatingPoint()) 1488 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1489 else if (Signed) 1490 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1491 else 1492 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1493 1494 return Val; 1495 } 1496 1497 SDValue SITargetLowering::lowerKernargMemParameter( 1498 SelectionDAG &DAG, EVT VT, EVT MemVT, 1499 const SDLoc &SL, SDValue Chain, 1500 uint64_t Offset, unsigned Align, bool Signed, 1501 const ISD::InputArg *Arg) const { 1502 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1503 1504 // Try to avoid using an extload by loading earlier than the argument address, 1505 // and extracting the relevant bits. The load should hopefully be merged with 1506 // the previous argument. 1507 if (MemVT.getStoreSize() < 4 && Align < 4) { 1508 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1509 int64_t AlignDownOffset = alignDown(Offset, 4); 1510 int64_t OffsetDiff = Offset - AlignDownOffset; 1511 1512 EVT IntVT = MemVT.changeTypeToInteger(); 1513 1514 // TODO: If we passed in the base kernel offset we could have a better 1515 // alignment than 4, but we don't really need it. 1516 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1517 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1518 MachineMemOperand::MODereferenceable | 1519 MachineMemOperand::MOInvariant); 1520 1521 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1522 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1523 1524 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1525 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1526 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1527 1528 1529 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1530 } 1531 1532 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1533 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1534 MachineMemOperand::MODereferenceable | 1535 MachineMemOperand::MOInvariant); 1536 1537 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1538 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1539 } 1540 1541 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1542 const SDLoc &SL, SDValue Chain, 1543 const ISD::InputArg &Arg) const { 1544 MachineFunction &MF = DAG.getMachineFunction(); 1545 MachineFrameInfo &MFI = MF.getFrameInfo(); 1546 1547 if (Arg.Flags.isByVal()) { 1548 unsigned Size = Arg.Flags.getByValSize(); 1549 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1550 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1551 } 1552 1553 unsigned ArgOffset = VA.getLocMemOffset(); 1554 unsigned ArgSize = VA.getValVT().getStoreSize(); 1555 1556 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1557 1558 // Create load nodes to retrieve arguments from the stack. 1559 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1560 SDValue ArgValue; 1561 1562 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1563 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1564 MVT MemVT = VA.getValVT(); 1565 1566 switch (VA.getLocInfo()) { 1567 default: 1568 break; 1569 case CCValAssign::BCvt: 1570 MemVT = VA.getLocVT(); 1571 break; 1572 case CCValAssign::SExt: 1573 ExtType = ISD::SEXTLOAD; 1574 break; 1575 case CCValAssign::ZExt: 1576 ExtType = ISD::ZEXTLOAD; 1577 break; 1578 case CCValAssign::AExt: 1579 ExtType = ISD::EXTLOAD; 1580 break; 1581 } 1582 1583 ArgValue = DAG.getExtLoad( 1584 ExtType, SL, VA.getLocVT(), Chain, FIN, 1585 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1586 MemVT); 1587 return ArgValue; 1588 } 1589 1590 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1591 const SIMachineFunctionInfo &MFI, 1592 EVT VT, 1593 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1594 const ArgDescriptor *Reg; 1595 const TargetRegisterClass *RC; 1596 1597 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1598 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1599 } 1600 1601 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1602 CallingConv::ID CallConv, 1603 ArrayRef<ISD::InputArg> Ins, 1604 BitVector &Skipped, 1605 FunctionType *FType, 1606 SIMachineFunctionInfo *Info) { 1607 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1608 const ISD::InputArg *Arg = &Ins[I]; 1609 1610 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1611 "vector type argument should have been split"); 1612 1613 // First check if it's a PS input addr. 1614 if (CallConv == CallingConv::AMDGPU_PS && 1615 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1616 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1617 1618 // Inconveniently only the first part of the split is marked as isSplit, 1619 // so skip to the end. We only want to increment PSInputNum once for the 1620 // entire split argument. 1621 if (Arg->Flags.isSplit()) { 1622 while (!Arg->Flags.isSplitEnd()) { 1623 assert((!Arg->VT.isVector() || 1624 Arg->VT.getScalarSizeInBits() == 16) && 1625 "unexpected vector split in ps argument type"); 1626 if (!SkipArg) 1627 Splits.push_back(*Arg); 1628 Arg = &Ins[++I]; 1629 } 1630 } 1631 1632 if (SkipArg) { 1633 // We can safely skip PS inputs. 1634 Skipped.set(Arg->getOrigArgIndex()); 1635 ++PSInputNum; 1636 continue; 1637 } 1638 1639 Info->markPSInputAllocated(PSInputNum); 1640 if (Arg->Used) 1641 Info->markPSInputEnabled(PSInputNum); 1642 1643 ++PSInputNum; 1644 } 1645 1646 Splits.push_back(*Arg); 1647 } 1648 } 1649 1650 // Allocate special inputs passed in VGPRs. 1651 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1652 MachineFunction &MF, 1653 const SIRegisterInfo &TRI, 1654 SIMachineFunctionInfo &Info) const { 1655 const LLT S32 = LLT::scalar(32); 1656 MachineRegisterInfo &MRI = MF.getRegInfo(); 1657 1658 if (Info.hasWorkItemIDX()) { 1659 Register Reg = AMDGPU::VGPR0; 1660 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1661 1662 CCInfo.AllocateReg(Reg); 1663 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1664 } 1665 1666 if (Info.hasWorkItemIDY()) { 1667 Register Reg = AMDGPU::VGPR1; 1668 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1669 1670 CCInfo.AllocateReg(Reg); 1671 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1672 } 1673 1674 if (Info.hasWorkItemIDZ()) { 1675 Register Reg = AMDGPU::VGPR2; 1676 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1677 1678 CCInfo.AllocateReg(Reg); 1679 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1680 } 1681 } 1682 1683 // Try to allocate a VGPR at the end of the argument list, or if no argument 1684 // VGPRs are left allocating a stack slot. 1685 // If \p Mask is is given it indicates bitfield position in the register. 1686 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1687 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1688 ArgDescriptor Arg = ArgDescriptor()) { 1689 if (Arg.isSet()) 1690 return ArgDescriptor::createArg(Arg, Mask); 1691 1692 ArrayRef<MCPhysReg> ArgVGPRs 1693 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1694 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1695 if (RegIdx == ArgVGPRs.size()) { 1696 // Spill to stack required. 1697 int64_t Offset = CCInfo.AllocateStack(4, 4); 1698 1699 return ArgDescriptor::createStack(Offset, Mask); 1700 } 1701 1702 unsigned Reg = ArgVGPRs[RegIdx]; 1703 Reg = CCInfo.AllocateReg(Reg); 1704 assert(Reg != AMDGPU::NoRegister); 1705 1706 MachineFunction &MF = CCInfo.getMachineFunction(); 1707 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1708 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1709 return ArgDescriptor::createRegister(Reg, Mask); 1710 } 1711 1712 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1713 const TargetRegisterClass *RC, 1714 unsigned NumArgRegs) { 1715 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1716 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1717 if (RegIdx == ArgSGPRs.size()) 1718 report_fatal_error("ran out of SGPRs for arguments"); 1719 1720 unsigned Reg = ArgSGPRs[RegIdx]; 1721 Reg = CCInfo.AllocateReg(Reg); 1722 assert(Reg != AMDGPU::NoRegister); 1723 1724 MachineFunction &MF = CCInfo.getMachineFunction(); 1725 MF.addLiveIn(Reg, RC); 1726 return ArgDescriptor::createRegister(Reg); 1727 } 1728 1729 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1730 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1731 } 1732 1733 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1734 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1735 } 1736 1737 /// Allocate implicit function VGPR arguments at the end of allocated user 1738 /// arguments. 1739 void SITargetLowering::allocateSpecialInputVGPRs( 1740 CCState &CCInfo, MachineFunction &MF, 1741 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1742 const unsigned Mask = 0x3ff; 1743 ArgDescriptor Arg; 1744 1745 if (Info.hasWorkItemIDX()) { 1746 Arg = allocateVGPR32Input(CCInfo, Mask); 1747 Info.setWorkItemIDX(Arg); 1748 } 1749 1750 if (Info.hasWorkItemIDY()) { 1751 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1752 Info.setWorkItemIDY(Arg); 1753 } 1754 1755 if (Info.hasWorkItemIDZ()) 1756 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1757 } 1758 1759 /// Allocate implicit function VGPR arguments in fixed registers. 1760 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1761 CCState &CCInfo, MachineFunction &MF, 1762 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1763 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1764 if (!Reg) 1765 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1766 1767 const unsigned Mask = 0x3ff; 1768 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1769 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1770 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1771 } 1772 1773 void SITargetLowering::allocateSpecialInputSGPRs( 1774 CCState &CCInfo, 1775 MachineFunction &MF, 1776 const SIRegisterInfo &TRI, 1777 SIMachineFunctionInfo &Info) const { 1778 auto &ArgInfo = Info.getArgInfo(); 1779 1780 // TODO: Unify handling with private memory pointers. 1781 1782 if (Info.hasDispatchPtr()) 1783 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1784 1785 if (Info.hasQueuePtr()) 1786 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1787 1788 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1789 // constant offset from the kernarg segment. 1790 if (Info.hasImplicitArgPtr()) 1791 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1792 1793 if (Info.hasDispatchID()) 1794 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1795 1796 // flat_scratch_init is not applicable for non-kernel functions. 1797 1798 if (Info.hasWorkGroupIDX()) 1799 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1800 1801 if (Info.hasWorkGroupIDY()) 1802 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1803 1804 if (Info.hasWorkGroupIDZ()) 1805 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1806 } 1807 1808 // Allocate special inputs passed in user SGPRs. 1809 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1810 MachineFunction &MF, 1811 const SIRegisterInfo &TRI, 1812 SIMachineFunctionInfo &Info) const { 1813 if (Info.hasImplicitBufferPtr()) { 1814 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1815 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1816 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1817 } 1818 1819 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1820 if (Info.hasPrivateSegmentBuffer()) { 1821 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1822 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1823 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1824 } 1825 1826 if (Info.hasDispatchPtr()) { 1827 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1828 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1829 CCInfo.AllocateReg(DispatchPtrReg); 1830 } 1831 1832 if (Info.hasQueuePtr()) { 1833 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1834 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1835 CCInfo.AllocateReg(QueuePtrReg); 1836 } 1837 1838 if (Info.hasKernargSegmentPtr()) { 1839 MachineRegisterInfo &MRI = MF.getRegInfo(); 1840 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1841 CCInfo.AllocateReg(InputPtrReg); 1842 1843 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1844 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1845 } 1846 1847 if (Info.hasDispatchID()) { 1848 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1849 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1850 CCInfo.AllocateReg(DispatchIDReg); 1851 } 1852 1853 if (Info.hasFlatScratchInit()) { 1854 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1855 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1856 CCInfo.AllocateReg(FlatScratchInitReg); 1857 } 1858 1859 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1860 // these from the dispatch pointer. 1861 } 1862 1863 // Allocate special input registers that are initialized per-wave. 1864 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1865 MachineFunction &MF, 1866 SIMachineFunctionInfo &Info, 1867 CallingConv::ID CallConv, 1868 bool IsShader) const { 1869 if (Info.hasWorkGroupIDX()) { 1870 unsigned Reg = Info.addWorkGroupIDX(); 1871 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1872 CCInfo.AllocateReg(Reg); 1873 } 1874 1875 if (Info.hasWorkGroupIDY()) { 1876 unsigned Reg = Info.addWorkGroupIDY(); 1877 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1878 CCInfo.AllocateReg(Reg); 1879 } 1880 1881 if (Info.hasWorkGroupIDZ()) { 1882 unsigned Reg = Info.addWorkGroupIDZ(); 1883 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1884 CCInfo.AllocateReg(Reg); 1885 } 1886 1887 if (Info.hasWorkGroupInfo()) { 1888 unsigned Reg = Info.addWorkGroupInfo(); 1889 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1890 CCInfo.AllocateReg(Reg); 1891 } 1892 1893 if (Info.hasPrivateSegmentWaveByteOffset()) { 1894 // Scratch wave offset passed in system SGPR. 1895 unsigned PrivateSegmentWaveByteOffsetReg; 1896 1897 if (IsShader) { 1898 PrivateSegmentWaveByteOffsetReg = 1899 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1900 1901 // This is true if the scratch wave byte offset doesn't have a fixed 1902 // location. 1903 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1904 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1905 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1906 } 1907 } else 1908 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1909 1910 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1911 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1912 } 1913 } 1914 1915 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1916 MachineFunction &MF, 1917 const SIRegisterInfo &TRI, 1918 SIMachineFunctionInfo &Info) { 1919 // Now that we've figured out where the scratch register inputs are, see if 1920 // should reserve the arguments and use them directly. 1921 MachineFrameInfo &MFI = MF.getFrameInfo(); 1922 bool HasStackObjects = MFI.hasStackObjects(); 1923 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 1924 1925 // Record that we know we have non-spill stack objects so we don't need to 1926 // check all stack objects later. 1927 if (HasStackObjects) 1928 Info.setHasNonSpillStackObjects(true); 1929 1930 // Everything live out of a block is spilled with fast regalloc, so it's 1931 // almost certain that spilling will be required. 1932 if (TM.getOptLevel() == CodeGenOpt::None) 1933 HasStackObjects = true; 1934 1935 // For now assume stack access is needed in any callee functions, so we need 1936 // the scratch registers to pass in. 1937 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1938 1939 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 1940 // If we have stack objects, we unquestionably need the private buffer 1941 // resource. For the Code Object V2 ABI, this will be the first 4 user 1942 // SGPR inputs. We can reserve those and use them directly. 1943 1944 Register PrivateSegmentBufferReg = 1945 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 1946 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1947 } else { 1948 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1949 // We tentatively reserve the last registers (skipping the last registers 1950 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 1951 // we'll replace these with the ones immediately after those which were 1952 // really allocated. In the prologue copies will be inserted from the 1953 // argument to these reserved registers. 1954 1955 // Without HSA, relocations are used for the scratch pointer and the 1956 // buffer resource setup is always inserted in the prologue. Scratch wave 1957 // offset is still in an input SGPR. 1958 Info.setScratchRSrcReg(ReservedBufferReg); 1959 } 1960 1961 MachineRegisterInfo &MRI = MF.getRegInfo(); 1962 1963 // For entry functions we have to set up the stack pointer if we use it, 1964 // whereas non-entry functions get this "for free". This means there is no 1965 // intrinsic advantage to using S32 over S34 in cases where we do not have 1966 // calls but do need a frame pointer (i.e. if we are requested to have one 1967 // because frame pointer elimination is disabled). To keep things simple we 1968 // only ever use S32 as the call ABI stack pointer, and so using it does not 1969 // imply we need a separate frame pointer. 1970 // 1971 // Try to use s32 as the SP, but move it if it would interfere with input 1972 // arguments. This won't work with calls though. 1973 // 1974 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 1975 // registers. 1976 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 1977 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 1978 } else { 1979 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 1980 1981 if (MFI.hasCalls()) 1982 report_fatal_error("call in graphics shader with too many input SGPRs"); 1983 1984 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 1985 if (!MRI.isLiveIn(Reg)) { 1986 Info.setStackPtrOffsetReg(Reg); 1987 break; 1988 } 1989 } 1990 1991 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 1992 report_fatal_error("failed to find register for SP"); 1993 } 1994 1995 // hasFP should be accurate for entry functions even before the frame is 1996 // finalized, because it does not rely on the known stack size, only 1997 // properties like whether variable sized objects are present. 1998 if (ST.getFrameLowering()->hasFP(MF)) { 1999 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2000 } 2001 } 2002 2003 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2004 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2005 return !Info->isEntryFunction(); 2006 } 2007 2008 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2009 2010 } 2011 2012 void SITargetLowering::insertCopiesSplitCSR( 2013 MachineBasicBlock *Entry, 2014 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2015 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2016 2017 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2018 if (!IStart) 2019 return; 2020 2021 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2022 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2023 MachineBasicBlock::iterator MBBI = Entry->begin(); 2024 for (const MCPhysReg *I = IStart; *I; ++I) { 2025 const TargetRegisterClass *RC = nullptr; 2026 if (AMDGPU::SReg_64RegClass.contains(*I)) 2027 RC = &AMDGPU::SGPR_64RegClass; 2028 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2029 RC = &AMDGPU::SGPR_32RegClass; 2030 else 2031 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2032 2033 Register NewVR = MRI->createVirtualRegister(RC); 2034 // Create copy from CSR to a virtual register. 2035 Entry->addLiveIn(*I); 2036 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2037 .addReg(*I); 2038 2039 // Insert the copy-back instructions right before the terminator. 2040 for (auto *Exit : Exits) 2041 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2042 TII->get(TargetOpcode::COPY), *I) 2043 .addReg(NewVR); 2044 } 2045 } 2046 2047 SDValue SITargetLowering::LowerFormalArguments( 2048 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2049 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2050 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2051 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2052 2053 MachineFunction &MF = DAG.getMachineFunction(); 2054 const Function &Fn = MF.getFunction(); 2055 FunctionType *FType = MF.getFunction().getFunctionType(); 2056 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2057 2058 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2059 DiagnosticInfoUnsupported NoGraphicsHSA( 2060 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2061 DAG.getContext()->diagnose(NoGraphicsHSA); 2062 return DAG.getEntryNode(); 2063 } 2064 2065 SmallVector<ISD::InputArg, 16> Splits; 2066 SmallVector<CCValAssign, 16> ArgLocs; 2067 BitVector Skipped(Ins.size()); 2068 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2069 *DAG.getContext()); 2070 2071 bool IsShader = AMDGPU::isShader(CallConv); 2072 bool IsKernel = AMDGPU::isKernel(CallConv); 2073 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2074 2075 if (IsShader) { 2076 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2077 2078 // At least one interpolation mode must be enabled or else the GPU will 2079 // hang. 2080 // 2081 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2082 // set PSInputAddr, the user wants to enable some bits after the compilation 2083 // based on run-time states. Since we can't know what the final PSInputEna 2084 // will look like, so we shouldn't do anything here and the user should take 2085 // responsibility for the correct programming. 2086 // 2087 // Otherwise, the following restrictions apply: 2088 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2089 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2090 // enabled too. 2091 if (CallConv == CallingConv::AMDGPU_PS) { 2092 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2093 ((Info->getPSInputAddr() & 0xF) == 0 && 2094 Info->isPSInputAllocated(11))) { 2095 CCInfo.AllocateReg(AMDGPU::VGPR0); 2096 CCInfo.AllocateReg(AMDGPU::VGPR1); 2097 Info->markPSInputAllocated(0); 2098 Info->markPSInputEnabled(0); 2099 } 2100 if (Subtarget->isAmdPalOS()) { 2101 // For isAmdPalOS, the user does not enable some bits after compilation 2102 // based on run-time states; the register values being generated here are 2103 // the final ones set in hardware. Therefore we need to apply the 2104 // workaround to PSInputAddr and PSInputEnable together. (The case where 2105 // a bit is set in PSInputAddr but not PSInputEnable is where the 2106 // frontend set up an input arg for a particular interpolation mode, but 2107 // nothing uses that input arg. Really we should have an earlier pass 2108 // that removes such an arg.) 2109 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2110 if ((PsInputBits & 0x7F) == 0 || 2111 ((PsInputBits & 0xF) == 0 && 2112 (PsInputBits >> 11 & 1))) 2113 Info->markPSInputEnabled( 2114 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2115 } 2116 } 2117 2118 assert(!Info->hasDispatchPtr() && 2119 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2120 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2121 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2122 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2123 !Info->hasWorkItemIDZ()); 2124 } else if (IsKernel) { 2125 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2126 } else { 2127 Splits.append(Ins.begin(), Ins.end()); 2128 } 2129 2130 if (IsEntryFunc) { 2131 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2132 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2133 } else { 2134 // For the fixed ABI, pass workitem IDs in the last argument register. 2135 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2136 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2137 } 2138 2139 if (IsKernel) { 2140 analyzeFormalArgumentsCompute(CCInfo, Ins); 2141 } else { 2142 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2143 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2144 } 2145 2146 SmallVector<SDValue, 16> Chains; 2147 2148 // FIXME: This is the minimum kernel argument alignment. We should improve 2149 // this to the maximum alignment of the arguments. 2150 // 2151 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2152 // kern arg offset. 2153 const unsigned KernelArgBaseAlign = 16; 2154 2155 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2156 const ISD::InputArg &Arg = Ins[i]; 2157 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2158 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2159 continue; 2160 } 2161 2162 CCValAssign &VA = ArgLocs[ArgIdx++]; 2163 MVT VT = VA.getLocVT(); 2164 2165 if (IsEntryFunc && VA.isMemLoc()) { 2166 VT = Ins[i].VT; 2167 EVT MemVT = VA.getLocVT(); 2168 2169 const uint64_t Offset = VA.getLocMemOffset(); 2170 unsigned Align = MinAlign(KernelArgBaseAlign, Offset); 2171 2172 SDValue Arg = lowerKernargMemParameter( 2173 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]); 2174 Chains.push_back(Arg.getValue(1)); 2175 2176 auto *ParamTy = 2177 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2178 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2179 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2180 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2181 // On SI local pointers are just offsets into LDS, so they are always 2182 // less than 16-bits. On CI and newer they could potentially be 2183 // real pointers, so we can't guarantee their size. 2184 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2185 DAG.getValueType(MVT::i16)); 2186 } 2187 2188 InVals.push_back(Arg); 2189 continue; 2190 } else if (!IsEntryFunc && VA.isMemLoc()) { 2191 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2192 InVals.push_back(Val); 2193 if (!Arg.Flags.isByVal()) 2194 Chains.push_back(Val.getValue(1)); 2195 continue; 2196 } 2197 2198 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2199 2200 Register Reg = VA.getLocReg(); 2201 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2202 EVT ValVT = VA.getValVT(); 2203 2204 Reg = MF.addLiveIn(Reg, RC); 2205 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2206 2207 if (Arg.Flags.isSRet()) { 2208 // The return object should be reasonably addressable. 2209 2210 // FIXME: This helps when the return is a real sret. If it is a 2211 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2212 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2213 unsigned NumBits 2214 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2215 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2216 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2217 } 2218 2219 // If this is an 8 or 16-bit value, it is really passed promoted 2220 // to 32 bits. Insert an assert[sz]ext to capture this, then 2221 // truncate to the right size. 2222 switch (VA.getLocInfo()) { 2223 case CCValAssign::Full: 2224 break; 2225 case CCValAssign::BCvt: 2226 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2227 break; 2228 case CCValAssign::SExt: 2229 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2230 DAG.getValueType(ValVT)); 2231 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2232 break; 2233 case CCValAssign::ZExt: 2234 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2235 DAG.getValueType(ValVT)); 2236 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2237 break; 2238 case CCValAssign::AExt: 2239 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2240 break; 2241 default: 2242 llvm_unreachable("Unknown loc info!"); 2243 } 2244 2245 InVals.push_back(Val); 2246 } 2247 2248 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2249 // Special inputs come after user arguments. 2250 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2251 } 2252 2253 // Start adding system SGPRs. 2254 if (IsEntryFunc) { 2255 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2256 } else { 2257 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2258 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2259 } 2260 2261 auto &ArgUsageInfo = 2262 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2263 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2264 2265 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2266 Info->setBytesInStackArgArea(StackArgSize); 2267 2268 return Chains.empty() ? Chain : 2269 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2270 } 2271 2272 // TODO: If return values can't fit in registers, we should return as many as 2273 // possible in registers before passing on stack. 2274 bool SITargetLowering::CanLowerReturn( 2275 CallingConv::ID CallConv, 2276 MachineFunction &MF, bool IsVarArg, 2277 const SmallVectorImpl<ISD::OutputArg> &Outs, 2278 LLVMContext &Context) const { 2279 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2280 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2281 // for shaders. Vector types should be explicitly handled by CC. 2282 if (AMDGPU::isEntryFunctionCC(CallConv)) 2283 return true; 2284 2285 SmallVector<CCValAssign, 16> RVLocs; 2286 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2287 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2288 } 2289 2290 SDValue 2291 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2292 bool isVarArg, 2293 const SmallVectorImpl<ISD::OutputArg> &Outs, 2294 const SmallVectorImpl<SDValue> &OutVals, 2295 const SDLoc &DL, SelectionDAG &DAG) const { 2296 MachineFunction &MF = DAG.getMachineFunction(); 2297 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2298 2299 if (AMDGPU::isKernel(CallConv)) { 2300 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2301 OutVals, DL, DAG); 2302 } 2303 2304 bool IsShader = AMDGPU::isShader(CallConv); 2305 2306 Info->setIfReturnsVoid(Outs.empty()); 2307 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2308 2309 // CCValAssign - represent the assignment of the return value to a location. 2310 SmallVector<CCValAssign, 48> RVLocs; 2311 SmallVector<ISD::OutputArg, 48> Splits; 2312 2313 // CCState - Info about the registers and stack slots. 2314 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2315 *DAG.getContext()); 2316 2317 // Analyze outgoing return values. 2318 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2319 2320 SDValue Flag; 2321 SmallVector<SDValue, 48> RetOps; 2322 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2323 2324 // Add return address for callable functions. 2325 if (!Info->isEntryFunction()) { 2326 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2327 SDValue ReturnAddrReg = CreateLiveInRegister( 2328 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2329 2330 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2331 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2332 MVT::i64); 2333 Chain = 2334 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2335 Flag = Chain.getValue(1); 2336 RetOps.push_back(ReturnAddrVirtualReg); 2337 } 2338 2339 // Copy the result values into the output registers. 2340 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2341 ++I, ++RealRVLocIdx) { 2342 CCValAssign &VA = RVLocs[I]; 2343 assert(VA.isRegLoc() && "Can only return in registers!"); 2344 // TODO: Partially return in registers if return values don't fit. 2345 SDValue Arg = OutVals[RealRVLocIdx]; 2346 2347 // Copied from other backends. 2348 switch (VA.getLocInfo()) { 2349 case CCValAssign::Full: 2350 break; 2351 case CCValAssign::BCvt: 2352 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2353 break; 2354 case CCValAssign::SExt: 2355 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2356 break; 2357 case CCValAssign::ZExt: 2358 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2359 break; 2360 case CCValAssign::AExt: 2361 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2362 break; 2363 default: 2364 llvm_unreachable("Unknown loc info!"); 2365 } 2366 2367 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2368 Flag = Chain.getValue(1); 2369 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2370 } 2371 2372 // FIXME: Does sret work properly? 2373 if (!Info->isEntryFunction()) { 2374 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2375 const MCPhysReg *I = 2376 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2377 if (I) { 2378 for (; *I; ++I) { 2379 if (AMDGPU::SReg_64RegClass.contains(*I)) 2380 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2381 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2382 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2383 else 2384 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2385 } 2386 } 2387 } 2388 2389 // Update chain and glue. 2390 RetOps[0] = Chain; 2391 if (Flag.getNode()) 2392 RetOps.push_back(Flag); 2393 2394 unsigned Opc = AMDGPUISD::ENDPGM; 2395 if (!IsWaveEnd) 2396 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2397 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2398 } 2399 2400 SDValue SITargetLowering::LowerCallResult( 2401 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2402 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2403 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2404 SDValue ThisVal) const { 2405 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2406 2407 // Assign locations to each value returned by this call. 2408 SmallVector<CCValAssign, 16> RVLocs; 2409 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2410 *DAG.getContext()); 2411 CCInfo.AnalyzeCallResult(Ins, RetCC); 2412 2413 // Copy all of the result registers out of their specified physreg. 2414 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2415 CCValAssign VA = RVLocs[i]; 2416 SDValue Val; 2417 2418 if (VA.isRegLoc()) { 2419 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2420 Chain = Val.getValue(1); 2421 InFlag = Val.getValue(2); 2422 } else if (VA.isMemLoc()) { 2423 report_fatal_error("TODO: return values in memory"); 2424 } else 2425 llvm_unreachable("unknown argument location type"); 2426 2427 switch (VA.getLocInfo()) { 2428 case CCValAssign::Full: 2429 break; 2430 case CCValAssign::BCvt: 2431 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2432 break; 2433 case CCValAssign::ZExt: 2434 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2435 DAG.getValueType(VA.getValVT())); 2436 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2437 break; 2438 case CCValAssign::SExt: 2439 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2440 DAG.getValueType(VA.getValVT())); 2441 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2442 break; 2443 case CCValAssign::AExt: 2444 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2445 break; 2446 default: 2447 llvm_unreachable("Unknown loc info!"); 2448 } 2449 2450 InVals.push_back(Val); 2451 } 2452 2453 return Chain; 2454 } 2455 2456 // Add code to pass special inputs required depending on used features separate 2457 // from the explicit user arguments present in the IR. 2458 void SITargetLowering::passSpecialInputs( 2459 CallLoweringInfo &CLI, 2460 CCState &CCInfo, 2461 const SIMachineFunctionInfo &Info, 2462 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2463 SmallVectorImpl<SDValue> &MemOpChains, 2464 SDValue Chain) const { 2465 // If we don't have a call site, this was a call inserted by 2466 // legalization. These can never use special inputs. 2467 if (!CLI.CB) 2468 return; 2469 2470 SelectionDAG &DAG = CLI.DAG; 2471 const SDLoc &DL = CLI.DL; 2472 2473 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2474 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2475 2476 const AMDGPUFunctionArgInfo *CalleeArgInfo 2477 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2478 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2479 auto &ArgUsageInfo = 2480 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2481 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2482 } 2483 2484 // TODO: Unify with private memory register handling. This is complicated by 2485 // the fact that at least in kernels, the input argument is not necessarily 2486 // in the same location as the input. 2487 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2488 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2489 AMDGPUFunctionArgInfo::QUEUE_PTR, 2490 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2491 AMDGPUFunctionArgInfo::DISPATCH_ID, 2492 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2493 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2494 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2495 }; 2496 2497 for (auto InputID : InputRegs) { 2498 const ArgDescriptor *OutgoingArg; 2499 const TargetRegisterClass *ArgRC; 2500 2501 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID); 2502 if (!OutgoingArg) 2503 continue; 2504 2505 const ArgDescriptor *IncomingArg; 2506 const TargetRegisterClass *IncomingArgRC; 2507 std::tie(IncomingArg, IncomingArgRC) 2508 = CallerArgInfo.getPreloadedValue(InputID); 2509 assert(IncomingArgRC == ArgRC); 2510 2511 // All special arguments are ints for now. 2512 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2513 SDValue InputReg; 2514 2515 if (IncomingArg) { 2516 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2517 } else { 2518 // The implicit arg ptr is special because it doesn't have a corresponding 2519 // input for kernels, and is computed from the kernarg segment pointer. 2520 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2521 InputReg = getImplicitArgPtr(DAG, DL); 2522 } 2523 2524 if (OutgoingArg->isRegister()) { 2525 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2526 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2527 report_fatal_error("failed to allocate implicit input argument"); 2528 } else { 2529 unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4); 2530 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2531 SpecialArgOffset); 2532 MemOpChains.push_back(ArgStore); 2533 } 2534 } 2535 2536 // Pack workitem IDs into a single register or pass it as is if already 2537 // packed. 2538 const ArgDescriptor *OutgoingArg; 2539 const TargetRegisterClass *ArgRC; 2540 2541 std::tie(OutgoingArg, ArgRC) = 2542 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2543 if (!OutgoingArg) 2544 std::tie(OutgoingArg, ArgRC) = 2545 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2546 if (!OutgoingArg) 2547 std::tie(OutgoingArg, ArgRC) = 2548 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2549 if (!OutgoingArg) 2550 return; 2551 2552 const ArgDescriptor *IncomingArgX 2553 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first; 2554 const ArgDescriptor *IncomingArgY 2555 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first; 2556 const ArgDescriptor *IncomingArgZ 2557 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first; 2558 2559 SDValue InputReg; 2560 SDLoc SL; 2561 2562 // If incoming ids are not packed we need to pack them. 2563 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2564 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2565 2566 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2567 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2568 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2569 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2570 InputReg = InputReg.getNode() ? 2571 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2572 } 2573 2574 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2575 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2576 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2577 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2578 InputReg = InputReg.getNode() ? 2579 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2580 } 2581 2582 if (!InputReg.getNode()) { 2583 // Workitem ids are already packed, any of present incoming arguments 2584 // will carry all required fields. 2585 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2586 IncomingArgX ? *IncomingArgX : 2587 IncomingArgY ? *IncomingArgY : 2588 *IncomingArgZ, ~0u); 2589 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2590 } 2591 2592 if (OutgoingArg->isRegister()) { 2593 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2594 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2595 } else { 2596 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4); 2597 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2598 SpecialArgOffset); 2599 MemOpChains.push_back(ArgStore); 2600 } 2601 } 2602 2603 static bool canGuaranteeTCO(CallingConv::ID CC) { 2604 return CC == CallingConv::Fast; 2605 } 2606 2607 /// Return true if we might ever do TCO for calls with this calling convention. 2608 static bool mayTailCallThisCC(CallingConv::ID CC) { 2609 switch (CC) { 2610 case CallingConv::C: 2611 return true; 2612 default: 2613 return canGuaranteeTCO(CC); 2614 } 2615 } 2616 2617 bool SITargetLowering::isEligibleForTailCallOptimization( 2618 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2619 const SmallVectorImpl<ISD::OutputArg> &Outs, 2620 const SmallVectorImpl<SDValue> &OutVals, 2621 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2622 if (!mayTailCallThisCC(CalleeCC)) 2623 return false; 2624 2625 MachineFunction &MF = DAG.getMachineFunction(); 2626 const Function &CallerF = MF.getFunction(); 2627 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2628 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2629 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2630 2631 // Kernels aren't callable, and don't have a live in return address so it 2632 // doesn't make sense to do a tail call with entry functions. 2633 if (!CallerPreserved) 2634 return false; 2635 2636 bool CCMatch = CallerCC == CalleeCC; 2637 2638 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2639 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2640 return true; 2641 return false; 2642 } 2643 2644 // TODO: Can we handle var args? 2645 if (IsVarArg) 2646 return false; 2647 2648 for (const Argument &Arg : CallerF.args()) { 2649 if (Arg.hasByValAttr()) 2650 return false; 2651 } 2652 2653 LLVMContext &Ctx = *DAG.getContext(); 2654 2655 // Check that the call results are passed in the same way. 2656 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2657 CCAssignFnForCall(CalleeCC, IsVarArg), 2658 CCAssignFnForCall(CallerCC, IsVarArg))) 2659 return false; 2660 2661 // The callee has to preserve all registers the caller needs to preserve. 2662 if (!CCMatch) { 2663 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2664 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2665 return false; 2666 } 2667 2668 // Nothing more to check if the callee is taking no arguments. 2669 if (Outs.empty()) 2670 return true; 2671 2672 SmallVector<CCValAssign, 16> ArgLocs; 2673 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2674 2675 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2676 2677 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2678 // If the stack arguments for this call do not fit into our own save area then 2679 // the call cannot be made tail. 2680 // TODO: Is this really necessary? 2681 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2682 return false; 2683 2684 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2685 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2686 } 2687 2688 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2689 if (!CI->isTailCall()) 2690 return false; 2691 2692 const Function *ParentFn = CI->getParent()->getParent(); 2693 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2694 return false; 2695 return true; 2696 } 2697 2698 // The wave scratch offset register is used as the global base pointer. 2699 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2700 SmallVectorImpl<SDValue> &InVals) const { 2701 SelectionDAG &DAG = CLI.DAG; 2702 const SDLoc &DL = CLI.DL; 2703 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2704 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2705 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2706 SDValue Chain = CLI.Chain; 2707 SDValue Callee = CLI.Callee; 2708 bool &IsTailCall = CLI.IsTailCall; 2709 CallingConv::ID CallConv = CLI.CallConv; 2710 bool IsVarArg = CLI.IsVarArg; 2711 bool IsSibCall = false; 2712 bool IsThisReturn = false; 2713 MachineFunction &MF = DAG.getMachineFunction(); 2714 2715 if (Callee.isUndef() || isNullConstant(Callee)) { 2716 if (!CLI.IsTailCall) { 2717 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2718 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2719 } 2720 2721 return Chain; 2722 } 2723 2724 if (IsVarArg) { 2725 return lowerUnhandledCall(CLI, InVals, 2726 "unsupported call to variadic function "); 2727 } 2728 2729 if (!CLI.CB) 2730 report_fatal_error("unsupported libcall legalization"); 2731 2732 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2733 !CLI.CB->getCalledFunction()) { 2734 return lowerUnhandledCall(CLI, InVals, 2735 "unsupported indirect call to function "); 2736 } 2737 2738 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2739 return lowerUnhandledCall(CLI, InVals, 2740 "unsupported required tail call to function "); 2741 } 2742 2743 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2744 // Note the issue is with the CC of the calling function, not of the call 2745 // itself. 2746 return lowerUnhandledCall(CLI, InVals, 2747 "unsupported call from graphics shader of function "); 2748 } 2749 2750 if (IsTailCall) { 2751 IsTailCall = isEligibleForTailCallOptimization( 2752 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2753 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2754 report_fatal_error("failed to perform tail call elimination on a call " 2755 "site marked musttail"); 2756 } 2757 2758 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2759 2760 // A sibling call is one where we're under the usual C ABI and not planning 2761 // to change that but can still do a tail call: 2762 if (!TailCallOpt && IsTailCall) 2763 IsSibCall = true; 2764 2765 if (IsTailCall) 2766 ++NumTailCalls; 2767 } 2768 2769 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2770 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2771 SmallVector<SDValue, 8> MemOpChains; 2772 2773 // Analyze operands of the call, assigning locations to each operand. 2774 SmallVector<CCValAssign, 16> ArgLocs; 2775 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2776 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2777 2778 if (AMDGPUTargetMachine::EnableFixedFunctionABI) { 2779 // With a fixed ABI, allocate fixed registers before user arguments. 2780 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2781 } 2782 2783 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2784 2785 // Get a count of how many bytes are to be pushed on the stack. 2786 unsigned NumBytes = CCInfo.getNextStackOffset(); 2787 2788 if (IsSibCall) { 2789 // Since we're not changing the ABI to make this a tail call, the memory 2790 // operands are already available in the caller's incoming argument space. 2791 NumBytes = 0; 2792 } 2793 2794 // FPDiff is the byte offset of the call's argument area from the callee's. 2795 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2796 // by this amount for a tail call. In a sibling call it must be 0 because the 2797 // caller will deallocate the entire stack and the callee still expects its 2798 // arguments to begin at SP+0. Completely unused for non-tail calls. 2799 int32_t FPDiff = 0; 2800 MachineFrameInfo &MFI = MF.getFrameInfo(); 2801 2802 // Adjust the stack pointer for the new arguments... 2803 // These operations are automatically eliminated by the prolog/epilog pass 2804 if (!IsSibCall) { 2805 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2806 2807 SmallVector<SDValue, 4> CopyFromChains; 2808 2809 // In the HSA case, this should be an identity copy. 2810 SDValue ScratchRSrcReg 2811 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2812 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2813 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2814 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2815 } 2816 2817 MVT PtrVT = MVT::i32; 2818 2819 // Walk the register/memloc assignments, inserting copies/loads. 2820 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2821 CCValAssign &VA = ArgLocs[i]; 2822 SDValue Arg = OutVals[i]; 2823 2824 // Promote the value if needed. 2825 switch (VA.getLocInfo()) { 2826 case CCValAssign::Full: 2827 break; 2828 case CCValAssign::BCvt: 2829 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2830 break; 2831 case CCValAssign::ZExt: 2832 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2833 break; 2834 case CCValAssign::SExt: 2835 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2836 break; 2837 case CCValAssign::AExt: 2838 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2839 break; 2840 case CCValAssign::FPExt: 2841 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2842 break; 2843 default: 2844 llvm_unreachable("Unknown loc info!"); 2845 } 2846 2847 if (VA.isRegLoc()) { 2848 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2849 } else { 2850 assert(VA.isMemLoc()); 2851 2852 SDValue DstAddr; 2853 MachinePointerInfo DstInfo; 2854 2855 unsigned LocMemOffset = VA.getLocMemOffset(); 2856 int32_t Offset = LocMemOffset; 2857 2858 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2859 MaybeAlign Alignment; 2860 2861 if (IsTailCall) { 2862 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2863 unsigned OpSize = Flags.isByVal() ? 2864 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2865 2866 // FIXME: We can have better than the minimum byval required alignment. 2867 Alignment = 2868 Flags.isByVal() 2869 ? Flags.getNonZeroByValAlign() 2870 : commonAlignment(Subtarget->getStackAlignment(), Offset); 2871 2872 Offset = Offset + FPDiff; 2873 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2874 2875 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2876 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2877 2878 // Make sure any stack arguments overlapping with where we're storing 2879 // are loaded before this eventual operation. Otherwise they'll be 2880 // clobbered. 2881 2882 // FIXME: Why is this really necessary? This seems to just result in a 2883 // lot of code to copy the stack and write them back to the same 2884 // locations, which are supposed to be immutable? 2885 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2886 } else { 2887 DstAddr = PtrOff; 2888 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2889 Alignment = 2890 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 2891 } 2892 2893 if (Outs[i].Flags.isByVal()) { 2894 SDValue SizeNode = 2895 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2896 SDValue Cpy = 2897 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 2898 Outs[i].Flags.getNonZeroByValAlign(), 2899 /*isVol = */ false, /*AlwaysInline = */ true, 2900 /*isTailCall = */ false, DstInfo, 2901 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 2902 2903 MemOpChains.push_back(Cpy); 2904 } else { 2905 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 2906 Alignment ? Alignment->value() : 0); 2907 MemOpChains.push_back(Store); 2908 } 2909 } 2910 } 2911 2912 if (!AMDGPUTargetMachine::EnableFixedFunctionABI) { 2913 // Copy special input registers after user input arguments. 2914 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2915 } 2916 2917 if (!MemOpChains.empty()) 2918 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2919 2920 // Build a sequence of copy-to-reg nodes chained together with token chain 2921 // and flag operands which copy the outgoing args into the appropriate regs. 2922 SDValue InFlag; 2923 for (auto &RegToPass : RegsToPass) { 2924 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2925 RegToPass.second, InFlag); 2926 InFlag = Chain.getValue(1); 2927 } 2928 2929 2930 SDValue PhysReturnAddrReg; 2931 if (IsTailCall) { 2932 // Since the return is being combined with the call, we need to pass on the 2933 // return address. 2934 2935 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2936 SDValue ReturnAddrReg = CreateLiveInRegister( 2937 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2938 2939 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2940 MVT::i64); 2941 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2942 InFlag = Chain.getValue(1); 2943 } 2944 2945 // We don't usually want to end the call-sequence here because we would tidy 2946 // the frame up *after* the call, however in the ABI-changing tail-call case 2947 // we've carefully laid out the parameters so that when sp is reset they'll be 2948 // in the correct location. 2949 if (IsTailCall && !IsSibCall) { 2950 Chain = DAG.getCALLSEQ_END(Chain, 2951 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2952 DAG.getTargetConstant(0, DL, MVT::i32), 2953 InFlag, DL); 2954 InFlag = Chain.getValue(1); 2955 } 2956 2957 std::vector<SDValue> Ops; 2958 Ops.push_back(Chain); 2959 Ops.push_back(Callee); 2960 // Add a redundant copy of the callee global which will not be legalized, as 2961 // we need direct access to the callee later. 2962 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 2963 const GlobalValue *GV = GSD->getGlobal(); 2964 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 2965 } else { 2966 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 2967 } 2968 2969 if (IsTailCall) { 2970 // Each tail call may have to adjust the stack by a different amount, so 2971 // this information must travel along with the operation for eventual 2972 // consumption by emitEpilogue. 2973 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 2974 2975 Ops.push_back(PhysReturnAddrReg); 2976 } 2977 2978 // Add argument registers to the end of the list so that they are known live 2979 // into the call. 2980 for (auto &RegToPass : RegsToPass) { 2981 Ops.push_back(DAG.getRegister(RegToPass.first, 2982 RegToPass.second.getValueType())); 2983 } 2984 2985 // Add a register mask operand representing the call-preserved registers. 2986 2987 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 2988 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2989 assert(Mask && "Missing call preserved mask for calling convention"); 2990 Ops.push_back(DAG.getRegisterMask(Mask)); 2991 2992 if (InFlag.getNode()) 2993 Ops.push_back(InFlag); 2994 2995 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2996 2997 // If we're doing a tall call, use a TC_RETURN here rather than an 2998 // actual call instruction. 2999 if (IsTailCall) { 3000 MFI.setHasTailCall(); 3001 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3002 } 3003 3004 // Returns a chain and a flag for retval copy to use. 3005 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3006 Chain = Call.getValue(0); 3007 InFlag = Call.getValue(1); 3008 3009 uint64_t CalleePopBytes = NumBytes; 3010 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3011 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3012 InFlag, DL); 3013 if (!Ins.empty()) 3014 InFlag = Chain.getValue(1); 3015 3016 // Handle result values, copying them out of physregs into vregs that we 3017 // return. 3018 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3019 InVals, IsThisReturn, 3020 IsThisReturn ? OutVals[0] : SDValue()); 3021 } 3022 3023 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3024 const MachineFunction &MF) const { 3025 Register Reg = StringSwitch<Register>(RegName) 3026 .Case("m0", AMDGPU::M0) 3027 .Case("exec", AMDGPU::EXEC) 3028 .Case("exec_lo", AMDGPU::EXEC_LO) 3029 .Case("exec_hi", AMDGPU::EXEC_HI) 3030 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3031 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3032 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3033 .Default(Register()); 3034 3035 if (Reg == AMDGPU::NoRegister) { 3036 report_fatal_error(Twine("invalid register name \"" 3037 + StringRef(RegName) + "\".")); 3038 3039 } 3040 3041 if (!Subtarget->hasFlatScrRegister() && 3042 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3043 report_fatal_error(Twine("invalid register \"" 3044 + StringRef(RegName) + "\" for subtarget.")); 3045 } 3046 3047 switch (Reg) { 3048 case AMDGPU::M0: 3049 case AMDGPU::EXEC_LO: 3050 case AMDGPU::EXEC_HI: 3051 case AMDGPU::FLAT_SCR_LO: 3052 case AMDGPU::FLAT_SCR_HI: 3053 if (VT.getSizeInBits() == 32) 3054 return Reg; 3055 break; 3056 case AMDGPU::EXEC: 3057 case AMDGPU::FLAT_SCR: 3058 if (VT.getSizeInBits() == 64) 3059 return Reg; 3060 break; 3061 default: 3062 llvm_unreachable("missing register type checking"); 3063 } 3064 3065 report_fatal_error(Twine("invalid type for register \"" 3066 + StringRef(RegName) + "\".")); 3067 } 3068 3069 // If kill is not the last instruction, split the block so kill is always a 3070 // proper terminator. 3071 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3072 MachineBasicBlock *BB) const { 3073 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3074 3075 MachineBasicBlock::iterator SplitPoint(&MI); 3076 ++SplitPoint; 3077 3078 if (SplitPoint == BB->end()) { 3079 // Don't bother with a new block. 3080 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3081 return BB; 3082 } 3083 3084 MachineFunction *MF = BB->getParent(); 3085 MachineBasicBlock *SplitBB 3086 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3087 3088 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3089 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3090 3091 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3092 BB->addSuccessor(SplitBB); 3093 3094 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3095 return SplitBB; 3096 } 3097 3098 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3099 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3100 // be the first instruction in the remainder block. 3101 // 3102 /// \returns { LoopBody, Remainder } 3103 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3104 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3105 MachineFunction *MF = MBB.getParent(); 3106 MachineBasicBlock::iterator I(&MI); 3107 3108 // To insert the loop we need to split the block. Move everything after this 3109 // point to a new block, and insert a new empty block between the two. 3110 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3111 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3112 MachineFunction::iterator MBBI(MBB); 3113 ++MBBI; 3114 3115 MF->insert(MBBI, LoopBB); 3116 MF->insert(MBBI, RemainderBB); 3117 3118 LoopBB->addSuccessor(LoopBB); 3119 LoopBB->addSuccessor(RemainderBB); 3120 3121 // Move the rest of the block into a new block. 3122 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3123 3124 if (InstInLoop) { 3125 auto Next = std::next(I); 3126 3127 // Move instruction to loop body. 3128 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3129 3130 // Move the rest of the block. 3131 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3132 } else { 3133 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3134 } 3135 3136 MBB.addSuccessor(LoopBB); 3137 3138 return std::make_pair(LoopBB, RemainderBB); 3139 } 3140 3141 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3142 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3143 MachineBasicBlock *MBB = MI.getParent(); 3144 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3145 auto I = MI.getIterator(); 3146 auto E = std::next(I); 3147 3148 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3149 .addImm(0); 3150 3151 MIBundleBuilder Bundler(*MBB, I, E); 3152 finalizeBundle(*MBB, Bundler.begin()); 3153 } 3154 3155 MachineBasicBlock * 3156 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3157 MachineBasicBlock *BB) const { 3158 const DebugLoc &DL = MI.getDebugLoc(); 3159 3160 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3161 3162 MachineBasicBlock *LoopBB; 3163 MachineBasicBlock *RemainderBB; 3164 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3165 3166 // Apparently kill flags are only valid if the def is in the same block? 3167 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3168 Src->setIsKill(false); 3169 3170 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3171 3172 MachineBasicBlock::iterator I = LoopBB->end(); 3173 3174 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3175 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3176 3177 // Clear TRAP_STS.MEM_VIOL 3178 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3179 .addImm(0) 3180 .addImm(EncodedReg); 3181 3182 bundleInstWithWaitcnt(MI); 3183 3184 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3185 3186 // Load and check TRAP_STS.MEM_VIOL 3187 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3188 .addImm(EncodedReg); 3189 3190 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3191 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3192 .addReg(Reg, RegState::Kill) 3193 .addImm(0); 3194 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3195 .addMBB(LoopBB); 3196 3197 return RemainderBB; 3198 } 3199 3200 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3201 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3202 // will only do one iteration. In the worst case, this will loop 64 times. 3203 // 3204 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3205 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3206 const SIInstrInfo *TII, 3207 MachineRegisterInfo &MRI, 3208 MachineBasicBlock &OrigBB, 3209 MachineBasicBlock &LoopBB, 3210 const DebugLoc &DL, 3211 const MachineOperand &IdxReg, 3212 unsigned InitReg, 3213 unsigned ResultReg, 3214 unsigned PhiReg, 3215 unsigned InitSaveExecReg, 3216 int Offset, 3217 bool UseGPRIdxMode, 3218 bool IsIndirectSrc) { 3219 MachineFunction *MF = OrigBB.getParent(); 3220 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3221 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3222 MachineBasicBlock::iterator I = LoopBB.begin(); 3223 3224 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3225 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3226 Register NewExec = MRI.createVirtualRegister(BoolRC); 3227 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3228 Register CondReg = MRI.createVirtualRegister(BoolRC); 3229 3230 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3231 .addReg(InitReg) 3232 .addMBB(&OrigBB) 3233 .addReg(ResultReg) 3234 .addMBB(&LoopBB); 3235 3236 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3237 .addReg(InitSaveExecReg) 3238 .addMBB(&OrigBB) 3239 .addReg(NewExec) 3240 .addMBB(&LoopBB); 3241 3242 // Read the next variant <- also loop target. 3243 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3244 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3245 3246 // Compare the just read M0 value to all possible Idx values. 3247 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3248 .addReg(CurrentIdxReg) 3249 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3250 3251 // Update EXEC, save the original EXEC value to VCC. 3252 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3253 : AMDGPU::S_AND_SAVEEXEC_B64), 3254 NewExec) 3255 .addReg(CondReg, RegState::Kill); 3256 3257 MRI.setSimpleHint(NewExec, CondReg); 3258 3259 if (UseGPRIdxMode) { 3260 unsigned IdxReg; 3261 if (Offset == 0) { 3262 IdxReg = CurrentIdxReg; 3263 } else { 3264 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3265 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3266 .addReg(CurrentIdxReg, RegState::Kill) 3267 .addImm(Offset); 3268 } 3269 unsigned IdxMode = IsIndirectSrc ? 3270 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3271 MachineInstr *SetOn = 3272 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3273 .addReg(IdxReg, RegState::Kill) 3274 .addImm(IdxMode); 3275 SetOn->getOperand(3).setIsUndef(); 3276 } else { 3277 // Move index from VCC into M0 3278 if (Offset == 0) { 3279 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3280 .addReg(CurrentIdxReg, RegState::Kill); 3281 } else { 3282 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3283 .addReg(CurrentIdxReg, RegState::Kill) 3284 .addImm(Offset); 3285 } 3286 } 3287 3288 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3289 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3290 MachineInstr *InsertPt = 3291 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3292 : AMDGPU::S_XOR_B64_term), Exec) 3293 .addReg(Exec) 3294 .addReg(NewExec); 3295 3296 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3297 // s_cbranch_scc0? 3298 3299 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3300 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3301 .addMBB(&LoopBB); 3302 3303 return InsertPt->getIterator(); 3304 } 3305 3306 // This has slightly sub-optimal regalloc when the source vector is killed by 3307 // the read. The register allocator does not understand that the kill is 3308 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3309 // subregister from it, using 1 more VGPR than necessary. This was saved when 3310 // this was expanded after register allocation. 3311 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3312 MachineBasicBlock &MBB, 3313 MachineInstr &MI, 3314 unsigned InitResultReg, 3315 unsigned PhiReg, 3316 int Offset, 3317 bool UseGPRIdxMode, 3318 bool IsIndirectSrc) { 3319 MachineFunction *MF = MBB.getParent(); 3320 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3321 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3322 MachineRegisterInfo &MRI = MF->getRegInfo(); 3323 const DebugLoc &DL = MI.getDebugLoc(); 3324 MachineBasicBlock::iterator I(&MI); 3325 3326 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3327 Register DstReg = MI.getOperand(0).getReg(); 3328 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3329 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3330 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3331 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3332 3333 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3334 3335 // Save the EXEC mask 3336 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3337 .addReg(Exec); 3338 3339 MachineBasicBlock *LoopBB; 3340 MachineBasicBlock *RemainderBB; 3341 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3342 3343 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3344 3345 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3346 InitResultReg, DstReg, PhiReg, TmpExec, 3347 Offset, UseGPRIdxMode, IsIndirectSrc); 3348 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3349 MachineFunction::iterator MBBI(LoopBB); 3350 ++MBBI; 3351 MF->insert(MBBI, LandingPad); 3352 LoopBB->removeSuccessor(RemainderBB); 3353 LandingPad->addSuccessor(RemainderBB); 3354 LoopBB->addSuccessor(LandingPad); 3355 MachineBasicBlock::iterator First = LandingPad->begin(); 3356 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3357 .addReg(SaveExec); 3358 3359 return InsPt; 3360 } 3361 3362 // Returns subreg index, offset 3363 static std::pair<unsigned, int> 3364 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3365 const TargetRegisterClass *SuperRC, 3366 unsigned VecReg, 3367 int Offset) { 3368 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3369 3370 // Skip out of bounds offsets, or else we would end up using an undefined 3371 // register. 3372 if (Offset >= NumElts || Offset < 0) 3373 return std::make_pair(AMDGPU::sub0, Offset); 3374 3375 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3376 } 3377 3378 // Return true if the index is an SGPR and was set. 3379 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3380 MachineRegisterInfo &MRI, 3381 MachineInstr &MI, 3382 int Offset, 3383 bool UseGPRIdxMode, 3384 bool IsIndirectSrc) { 3385 MachineBasicBlock *MBB = MI.getParent(); 3386 const DebugLoc &DL = MI.getDebugLoc(); 3387 MachineBasicBlock::iterator I(&MI); 3388 3389 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3390 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3391 3392 assert(Idx->getReg() != AMDGPU::NoRegister); 3393 3394 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3395 return false; 3396 3397 if (UseGPRIdxMode) { 3398 unsigned IdxMode = IsIndirectSrc ? 3399 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3400 if (Offset == 0) { 3401 MachineInstr *SetOn = 3402 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3403 .add(*Idx) 3404 .addImm(IdxMode); 3405 3406 SetOn->getOperand(3).setIsUndef(); 3407 } else { 3408 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3409 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3410 .add(*Idx) 3411 .addImm(Offset); 3412 MachineInstr *SetOn = 3413 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3414 .addReg(Tmp, RegState::Kill) 3415 .addImm(IdxMode); 3416 3417 SetOn->getOperand(3).setIsUndef(); 3418 } 3419 3420 return true; 3421 } 3422 3423 if (Offset == 0) { 3424 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3425 .add(*Idx); 3426 } else { 3427 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3428 .add(*Idx) 3429 .addImm(Offset); 3430 } 3431 3432 return true; 3433 } 3434 3435 // Control flow needs to be inserted if indexing with a VGPR. 3436 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3437 MachineBasicBlock &MBB, 3438 const GCNSubtarget &ST) { 3439 const SIInstrInfo *TII = ST.getInstrInfo(); 3440 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3441 MachineFunction *MF = MBB.getParent(); 3442 MachineRegisterInfo &MRI = MF->getRegInfo(); 3443 3444 Register Dst = MI.getOperand(0).getReg(); 3445 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3446 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3447 3448 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3449 3450 unsigned SubReg; 3451 std::tie(SubReg, Offset) 3452 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3453 3454 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3455 3456 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3457 MachineBasicBlock::iterator I(&MI); 3458 const DebugLoc &DL = MI.getDebugLoc(); 3459 3460 if (UseGPRIdxMode) { 3461 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3462 // to avoid interfering with other uses, so probably requires a new 3463 // optimization pass. 3464 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3465 .addReg(SrcReg, RegState::Undef, SubReg) 3466 .addReg(SrcReg, RegState::Implicit) 3467 .addReg(AMDGPU::M0, RegState::Implicit); 3468 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3469 } else { 3470 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3471 .addReg(SrcReg, RegState::Undef, SubReg) 3472 .addReg(SrcReg, RegState::Implicit); 3473 } 3474 3475 MI.eraseFromParent(); 3476 3477 return &MBB; 3478 } 3479 3480 const DebugLoc &DL = MI.getDebugLoc(); 3481 MachineBasicBlock::iterator I(&MI); 3482 3483 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3484 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3485 3486 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3487 3488 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3489 Offset, UseGPRIdxMode, true); 3490 MachineBasicBlock *LoopBB = InsPt->getParent(); 3491 3492 if (UseGPRIdxMode) { 3493 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3494 .addReg(SrcReg, RegState::Undef, SubReg) 3495 .addReg(SrcReg, RegState::Implicit) 3496 .addReg(AMDGPU::M0, RegState::Implicit); 3497 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3498 } else { 3499 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3500 .addReg(SrcReg, RegState::Undef, SubReg) 3501 .addReg(SrcReg, RegState::Implicit); 3502 } 3503 3504 MI.eraseFromParent(); 3505 3506 return LoopBB; 3507 } 3508 3509 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3510 MachineBasicBlock &MBB, 3511 const GCNSubtarget &ST) { 3512 const SIInstrInfo *TII = ST.getInstrInfo(); 3513 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3514 MachineFunction *MF = MBB.getParent(); 3515 MachineRegisterInfo &MRI = MF->getRegInfo(); 3516 3517 Register Dst = MI.getOperand(0).getReg(); 3518 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3519 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3520 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3521 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3522 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3523 3524 // This can be an immediate, but will be folded later. 3525 assert(Val->getReg()); 3526 3527 unsigned SubReg; 3528 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3529 SrcVec->getReg(), 3530 Offset); 3531 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3532 3533 if (Idx->getReg() == AMDGPU::NoRegister) { 3534 MachineBasicBlock::iterator I(&MI); 3535 const DebugLoc &DL = MI.getDebugLoc(); 3536 3537 assert(Offset == 0); 3538 3539 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3540 .add(*SrcVec) 3541 .add(*Val) 3542 .addImm(SubReg); 3543 3544 MI.eraseFromParent(); 3545 return &MBB; 3546 } 3547 3548 const MCInstrDesc &MovRelDesc 3549 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3550 3551 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3552 MachineBasicBlock::iterator I(&MI); 3553 const DebugLoc &DL = MI.getDebugLoc(); 3554 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3555 .addReg(SrcVec->getReg()) 3556 .add(*Val) 3557 .addImm(SubReg); 3558 if (UseGPRIdxMode) 3559 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3560 3561 MI.eraseFromParent(); 3562 return &MBB; 3563 } 3564 3565 if (Val->isReg()) 3566 MRI.clearKillFlags(Val->getReg()); 3567 3568 const DebugLoc &DL = MI.getDebugLoc(); 3569 3570 Register PhiReg = MRI.createVirtualRegister(VecRC); 3571 3572 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3573 Offset, UseGPRIdxMode, false); 3574 MachineBasicBlock *LoopBB = InsPt->getParent(); 3575 3576 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3577 .addReg(PhiReg) 3578 .add(*Val) 3579 .addImm(AMDGPU::sub0); 3580 if (UseGPRIdxMode) 3581 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3582 3583 MI.eraseFromParent(); 3584 return LoopBB; 3585 } 3586 3587 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3588 MachineInstr &MI, MachineBasicBlock *BB) const { 3589 3590 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3591 MachineFunction *MF = BB->getParent(); 3592 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3593 3594 if (TII->isMIMG(MI)) { 3595 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 3596 report_fatal_error("missing mem operand from MIMG instruction"); 3597 } 3598 // Add a memoperand for mimg instructions so that they aren't assumed to 3599 // be ordered memory instuctions. 3600 3601 return BB; 3602 } 3603 3604 switch (MI.getOpcode()) { 3605 case AMDGPU::S_UADDO_PSEUDO: 3606 case AMDGPU::S_USUBO_PSEUDO: { 3607 const DebugLoc &DL = MI.getDebugLoc(); 3608 MachineOperand &Dest0 = MI.getOperand(0); 3609 MachineOperand &Dest1 = MI.getOperand(1); 3610 MachineOperand &Src0 = MI.getOperand(2); 3611 MachineOperand &Src1 = MI.getOperand(3); 3612 3613 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3614 ? AMDGPU::S_ADD_I32 3615 : AMDGPU::S_SUB_I32; 3616 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3617 3618 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3619 .addImm(1) 3620 .addImm(0); 3621 3622 MI.eraseFromParent(); 3623 return BB; 3624 } 3625 case AMDGPU::S_ADD_U64_PSEUDO: 3626 case AMDGPU::S_SUB_U64_PSEUDO: { 3627 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3628 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3629 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3630 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3631 const DebugLoc &DL = MI.getDebugLoc(); 3632 3633 MachineOperand &Dest = MI.getOperand(0); 3634 MachineOperand &Src0 = MI.getOperand(1); 3635 MachineOperand &Src1 = MI.getOperand(2); 3636 3637 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3638 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3639 3640 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3641 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3642 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3643 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3644 3645 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3646 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3647 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3648 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3649 3650 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3651 3652 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3653 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3654 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3655 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3656 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3657 .addReg(DestSub0) 3658 .addImm(AMDGPU::sub0) 3659 .addReg(DestSub1) 3660 .addImm(AMDGPU::sub1); 3661 MI.eraseFromParent(); 3662 return BB; 3663 } 3664 case AMDGPU::V_ADD_U64_PSEUDO: 3665 case AMDGPU::V_SUB_U64_PSEUDO: { 3666 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3667 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3668 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3669 const DebugLoc &DL = MI.getDebugLoc(); 3670 3671 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3672 3673 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3674 3675 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3676 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3677 3678 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3679 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3680 3681 MachineOperand &Dest = MI.getOperand(0); 3682 MachineOperand &Src0 = MI.getOperand(1); 3683 MachineOperand &Src1 = MI.getOperand(2); 3684 3685 const TargetRegisterClass *Src0RC = Src0.isReg() 3686 ? MRI.getRegClass(Src0.getReg()) 3687 : &AMDGPU::VReg_64RegClass; 3688 const TargetRegisterClass *Src1RC = Src1.isReg() 3689 ? MRI.getRegClass(Src1.getReg()) 3690 : &AMDGPU::VReg_64RegClass; 3691 3692 const TargetRegisterClass *Src0SubRC = 3693 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3694 const TargetRegisterClass *Src1SubRC = 3695 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3696 3697 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3698 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3699 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3700 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3701 3702 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3703 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3704 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3705 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3706 3707 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64; 3708 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3709 .addReg(CarryReg, RegState::Define) 3710 .add(SrcReg0Sub0) 3711 .add(SrcReg1Sub0) 3712 .addImm(0); // clamp bit 3713 3714 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3715 MachineInstr *HiHalf = 3716 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3717 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3718 .add(SrcReg0Sub1) 3719 .add(SrcReg1Sub1) 3720 .addReg(CarryReg, RegState::Kill) 3721 .addImm(0); // clamp bit 3722 3723 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3724 .addReg(DestSub0) 3725 .addImm(AMDGPU::sub0) 3726 .addReg(DestSub1) 3727 .addImm(AMDGPU::sub1); 3728 TII->legalizeOperands(*LoHalf); 3729 TII->legalizeOperands(*HiHalf); 3730 MI.eraseFromParent(); 3731 return BB; 3732 } 3733 case AMDGPU::S_ADD_CO_PSEUDO: 3734 case AMDGPU::S_SUB_CO_PSEUDO: { 3735 // This pseudo has a chance to be selected 3736 // only from uniform add/subcarry node. All the VGPR operands 3737 // therefore assumed to be splat vectors. 3738 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3739 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3740 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3741 MachineBasicBlock::iterator MII = MI; 3742 const DebugLoc &DL = MI.getDebugLoc(); 3743 MachineOperand &Dest = MI.getOperand(0); 3744 MachineOperand &Src0 = MI.getOperand(2); 3745 MachineOperand &Src1 = MI.getOperand(3); 3746 MachineOperand &Src2 = MI.getOperand(4); 3747 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 3748 ? AMDGPU::S_ADDC_U32 3749 : AMDGPU::S_SUBB_U32; 3750 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 3751 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3752 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 3753 .addReg(Src0.getReg()); 3754 Src0.setReg(RegOp0); 3755 } 3756 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 3757 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3758 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 3759 .addReg(Src1.getReg()); 3760 Src1.setReg(RegOp1); 3761 } 3762 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3763 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 3764 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 3765 .addReg(Src2.getReg()); 3766 Src2.setReg(RegOp2); 3767 } 3768 3769 if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) { 3770 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 3771 .addReg(Src2.getReg()) 3772 .addImm(0); 3773 } else { 3774 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 3775 .addReg(Src2.getReg()) 3776 .addImm(0); 3777 } 3778 3779 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 3780 MI.eraseFromParent(); 3781 return BB; 3782 } 3783 case AMDGPU::SI_INIT_M0: { 3784 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3785 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3786 .add(MI.getOperand(0)); 3787 MI.eraseFromParent(); 3788 return BB; 3789 } 3790 case AMDGPU::SI_INIT_EXEC: 3791 // This should be before all vector instructions. 3792 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3793 AMDGPU::EXEC) 3794 .addImm(MI.getOperand(0).getImm()); 3795 MI.eraseFromParent(); 3796 return BB; 3797 3798 case AMDGPU::SI_INIT_EXEC_LO: 3799 // This should be before all vector instructions. 3800 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3801 AMDGPU::EXEC_LO) 3802 .addImm(MI.getOperand(0).getImm()); 3803 MI.eraseFromParent(); 3804 return BB; 3805 3806 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3807 // Extract the thread count from an SGPR input and set EXEC accordingly. 3808 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3809 // 3810 // S_BFE_U32 count, input, {shift, 7} 3811 // S_BFM_B64 exec, count, 0 3812 // S_CMP_EQ_U32 count, 64 3813 // S_CMOV_B64 exec, -1 3814 MachineInstr *FirstMI = &*BB->begin(); 3815 MachineRegisterInfo &MRI = MF->getRegInfo(); 3816 Register InputReg = MI.getOperand(0).getReg(); 3817 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3818 bool Found = false; 3819 3820 // Move the COPY of the input reg to the beginning, so that we can use it. 3821 for (auto I = BB->begin(); I != &MI; I++) { 3822 if (I->getOpcode() != TargetOpcode::COPY || 3823 I->getOperand(0).getReg() != InputReg) 3824 continue; 3825 3826 if (I == FirstMI) { 3827 FirstMI = &*++BB->begin(); 3828 } else { 3829 I->removeFromParent(); 3830 BB->insert(FirstMI, &*I); 3831 } 3832 Found = true; 3833 break; 3834 } 3835 assert(Found); 3836 (void)Found; 3837 3838 // This should be before all vector instructions. 3839 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3840 bool isWave32 = getSubtarget()->isWave32(); 3841 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3842 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3843 .addReg(InputReg) 3844 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3845 BuildMI(*BB, FirstMI, DebugLoc(), 3846 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3847 Exec) 3848 .addReg(CountReg) 3849 .addImm(0); 3850 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3851 .addReg(CountReg, RegState::Kill) 3852 .addImm(getSubtarget()->getWavefrontSize()); 3853 BuildMI(*BB, FirstMI, DebugLoc(), 3854 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3855 Exec) 3856 .addImm(-1); 3857 MI.eraseFromParent(); 3858 return BB; 3859 } 3860 3861 case AMDGPU::GET_GROUPSTATICSIZE: { 3862 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 3863 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 3864 DebugLoc DL = MI.getDebugLoc(); 3865 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3866 .add(MI.getOperand(0)) 3867 .addImm(MFI->getLDSSize()); 3868 MI.eraseFromParent(); 3869 return BB; 3870 } 3871 case AMDGPU::SI_INDIRECT_SRC_V1: 3872 case AMDGPU::SI_INDIRECT_SRC_V2: 3873 case AMDGPU::SI_INDIRECT_SRC_V4: 3874 case AMDGPU::SI_INDIRECT_SRC_V8: 3875 case AMDGPU::SI_INDIRECT_SRC_V16: 3876 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3877 case AMDGPU::SI_INDIRECT_DST_V1: 3878 case AMDGPU::SI_INDIRECT_DST_V2: 3879 case AMDGPU::SI_INDIRECT_DST_V4: 3880 case AMDGPU::SI_INDIRECT_DST_V8: 3881 case AMDGPU::SI_INDIRECT_DST_V16: 3882 return emitIndirectDst(MI, *BB, *getSubtarget()); 3883 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3884 case AMDGPU::SI_KILL_I1_PSEUDO: 3885 return splitKillBlock(MI, BB); 3886 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3887 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3888 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3889 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3890 3891 Register Dst = MI.getOperand(0).getReg(); 3892 Register Src0 = MI.getOperand(1).getReg(); 3893 Register Src1 = MI.getOperand(2).getReg(); 3894 const DebugLoc &DL = MI.getDebugLoc(); 3895 Register SrcCond = MI.getOperand(3).getReg(); 3896 3897 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3898 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3899 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3900 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 3901 3902 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3903 .addReg(SrcCond); 3904 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3905 .addImm(0) 3906 .addReg(Src0, 0, AMDGPU::sub0) 3907 .addImm(0) 3908 .addReg(Src1, 0, AMDGPU::sub0) 3909 .addReg(SrcCondCopy); 3910 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3911 .addImm(0) 3912 .addReg(Src0, 0, AMDGPU::sub1) 3913 .addImm(0) 3914 .addReg(Src1, 0, AMDGPU::sub1) 3915 .addReg(SrcCondCopy); 3916 3917 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3918 .addReg(DstLo) 3919 .addImm(AMDGPU::sub0) 3920 .addReg(DstHi) 3921 .addImm(AMDGPU::sub1); 3922 MI.eraseFromParent(); 3923 return BB; 3924 } 3925 case AMDGPU::SI_BR_UNDEF: { 3926 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3927 const DebugLoc &DL = MI.getDebugLoc(); 3928 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3929 .add(MI.getOperand(0)); 3930 Br->getOperand(1).setIsUndef(true); // read undef SCC 3931 MI.eraseFromParent(); 3932 return BB; 3933 } 3934 case AMDGPU::ADJCALLSTACKUP: 3935 case AMDGPU::ADJCALLSTACKDOWN: { 3936 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3937 MachineInstrBuilder MIB(*MF, &MI); 3938 3939 // Add an implicit use of the frame offset reg to prevent the restore copy 3940 // inserted after the call from being reorderd after stack operations in the 3941 // the caller's frame. 3942 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3943 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 3944 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 3945 return BB; 3946 } 3947 case AMDGPU::SI_CALL_ISEL: { 3948 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3949 const DebugLoc &DL = MI.getDebugLoc(); 3950 3951 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3952 3953 MachineInstrBuilder MIB; 3954 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 3955 3956 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 3957 MIB.add(MI.getOperand(I)); 3958 3959 MIB.cloneMemRefs(MI); 3960 MI.eraseFromParent(); 3961 return BB; 3962 } 3963 case AMDGPU::V_ADD_I32_e32: 3964 case AMDGPU::V_SUB_I32_e32: 3965 case AMDGPU::V_SUBREV_I32_e32: { 3966 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 3967 const DebugLoc &DL = MI.getDebugLoc(); 3968 unsigned Opc = MI.getOpcode(); 3969 3970 bool NeedClampOperand = false; 3971 if (TII->pseudoToMCOpcode(Opc) == -1) { 3972 Opc = AMDGPU::getVOPe64(Opc); 3973 NeedClampOperand = true; 3974 } 3975 3976 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 3977 if (TII->isVOP3(*I)) { 3978 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3979 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3980 I.addReg(TRI->getVCC(), RegState::Define); 3981 } 3982 I.add(MI.getOperand(1)) 3983 .add(MI.getOperand(2)); 3984 if (NeedClampOperand) 3985 I.addImm(0); // clamp bit for e64 encoding 3986 3987 TII->legalizeOperands(*I); 3988 3989 MI.eraseFromParent(); 3990 return BB; 3991 } 3992 case AMDGPU::DS_GWS_INIT: 3993 case AMDGPU::DS_GWS_SEMA_V: 3994 case AMDGPU::DS_GWS_SEMA_BR: 3995 case AMDGPU::DS_GWS_SEMA_P: 3996 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 3997 case AMDGPU::DS_GWS_BARRIER: 3998 // A s_waitcnt 0 is required to be the instruction immediately following. 3999 if (getSubtarget()->hasGWSAutoReplay()) { 4000 bundleInstWithWaitcnt(MI); 4001 return BB; 4002 } 4003 4004 return emitGWSMemViolTestLoop(MI, BB); 4005 default: 4006 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4007 } 4008 } 4009 4010 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4011 return isTypeLegal(VT.getScalarType()); 4012 } 4013 4014 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4015 // This currently forces unfolding various combinations of fsub into fma with 4016 // free fneg'd operands. As long as we have fast FMA (controlled by 4017 // isFMAFasterThanFMulAndFAdd), we should perform these. 4018 4019 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4020 // most of these combines appear to be cycle neutral but save on instruction 4021 // count / code size. 4022 return true; 4023 } 4024 4025 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4026 EVT VT) const { 4027 if (!VT.isVector()) { 4028 return MVT::i1; 4029 } 4030 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4031 } 4032 4033 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4034 // TODO: Should i16 be used always if legal? For now it would force VALU 4035 // shifts. 4036 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4037 } 4038 4039 // Answering this is somewhat tricky and depends on the specific device which 4040 // have different rates for fma or all f64 operations. 4041 // 4042 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4043 // regardless of which device (although the number of cycles differs between 4044 // devices), so it is always profitable for f64. 4045 // 4046 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4047 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4048 // which we can always do even without fused FP ops since it returns the same 4049 // result as the separate operations and since it is always full 4050 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4051 // however does not support denormals, so we do report fma as faster if we have 4052 // a fast fma device and require denormals. 4053 // 4054 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4055 EVT VT) const { 4056 VT = VT.getScalarType(); 4057 4058 switch (VT.getSimpleVT().SimpleTy) { 4059 case MVT::f32: { 4060 // This is as fast on some subtargets. However, we always have full rate f32 4061 // mad available which returns the same result as the separate operations 4062 // which we should prefer over fma. We can't use this if we want to support 4063 // denormals, so only report this in these cases. 4064 if (hasFP32Denormals(MF)) 4065 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4066 4067 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4068 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4069 } 4070 case MVT::f64: 4071 return true; 4072 case MVT::f16: 4073 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4074 default: 4075 break; 4076 } 4077 4078 return false; 4079 } 4080 4081 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4082 const SDNode *N) const { 4083 // TODO: Check future ftz flag 4084 // v_mad_f32/v_mac_f32 do not support denormals. 4085 EVT VT = N->getValueType(0); 4086 if (VT == MVT::f32) 4087 return !hasFP32Denormals(DAG.getMachineFunction()); 4088 if (VT == MVT::f16) { 4089 return Subtarget->hasMadF16() && 4090 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4091 } 4092 4093 return false; 4094 } 4095 4096 //===----------------------------------------------------------------------===// 4097 // Custom DAG Lowering Operations 4098 //===----------------------------------------------------------------------===// 4099 4100 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4101 // wider vector type is legal. 4102 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4103 SelectionDAG &DAG) const { 4104 unsigned Opc = Op.getOpcode(); 4105 EVT VT = Op.getValueType(); 4106 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4107 4108 SDValue Lo, Hi; 4109 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4110 4111 SDLoc SL(Op); 4112 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4113 Op->getFlags()); 4114 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4115 Op->getFlags()); 4116 4117 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4118 } 4119 4120 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4121 // wider vector type is legal. 4122 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4123 SelectionDAG &DAG) const { 4124 unsigned Opc = Op.getOpcode(); 4125 EVT VT = Op.getValueType(); 4126 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4127 4128 SDValue Lo0, Hi0; 4129 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4130 SDValue Lo1, Hi1; 4131 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4132 4133 SDLoc SL(Op); 4134 4135 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4136 Op->getFlags()); 4137 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4138 Op->getFlags()); 4139 4140 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4141 } 4142 4143 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4144 SelectionDAG &DAG) const { 4145 unsigned Opc = Op.getOpcode(); 4146 EVT VT = Op.getValueType(); 4147 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4148 4149 SDValue Lo0, Hi0; 4150 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4151 SDValue Lo1, Hi1; 4152 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4153 SDValue Lo2, Hi2; 4154 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4155 4156 SDLoc SL(Op); 4157 4158 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4159 Op->getFlags()); 4160 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4161 Op->getFlags()); 4162 4163 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4164 } 4165 4166 4167 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4168 switch (Op.getOpcode()) { 4169 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4170 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4171 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4172 case ISD::LOAD: { 4173 SDValue Result = LowerLOAD(Op, DAG); 4174 assert((!Result.getNode() || 4175 Result.getNode()->getNumValues() == 2) && 4176 "Load should return a value and a chain"); 4177 return Result; 4178 } 4179 4180 case ISD::FSIN: 4181 case ISD::FCOS: 4182 return LowerTrig(Op, DAG); 4183 case ISD::SELECT: return LowerSELECT(Op, DAG); 4184 case ISD::FDIV: return LowerFDIV(Op, DAG); 4185 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4186 case ISD::STORE: return LowerSTORE(Op, DAG); 4187 case ISD::GlobalAddress: { 4188 MachineFunction &MF = DAG.getMachineFunction(); 4189 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4190 return LowerGlobalAddress(MFI, Op, DAG); 4191 } 4192 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4193 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4194 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4195 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4196 case ISD::INSERT_SUBVECTOR: 4197 return lowerINSERT_SUBVECTOR(Op, DAG); 4198 case ISD::INSERT_VECTOR_ELT: 4199 return lowerINSERT_VECTOR_ELT(Op, DAG); 4200 case ISD::EXTRACT_VECTOR_ELT: 4201 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4202 case ISD::VECTOR_SHUFFLE: 4203 return lowerVECTOR_SHUFFLE(Op, DAG); 4204 case ISD::BUILD_VECTOR: 4205 return lowerBUILD_VECTOR(Op, DAG); 4206 case ISD::FP_ROUND: 4207 return lowerFP_ROUND(Op, DAG); 4208 case ISD::TRAP: 4209 return lowerTRAP(Op, DAG); 4210 case ISD::DEBUGTRAP: 4211 return lowerDEBUGTRAP(Op, DAG); 4212 case ISD::FABS: 4213 case ISD::FNEG: 4214 case ISD::FCANONICALIZE: 4215 case ISD::BSWAP: 4216 return splitUnaryVectorOp(Op, DAG); 4217 case ISD::FMINNUM: 4218 case ISD::FMAXNUM: 4219 return lowerFMINNUM_FMAXNUM(Op, DAG); 4220 case ISD::FMA: 4221 return splitTernaryVectorOp(Op, DAG); 4222 case ISD::SHL: 4223 case ISD::SRA: 4224 case ISD::SRL: 4225 case ISD::ADD: 4226 case ISD::SUB: 4227 case ISD::MUL: 4228 case ISD::SMIN: 4229 case ISD::SMAX: 4230 case ISD::UMIN: 4231 case ISD::UMAX: 4232 case ISD::FADD: 4233 case ISD::FMUL: 4234 case ISD::FMINNUM_IEEE: 4235 case ISD::FMAXNUM_IEEE: 4236 return splitBinaryVectorOp(Op, DAG); 4237 } 4238 return SDValue(); 4239 } 4240 4241 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4242 const SDLoc &DL, 4243 SelectionDAG &DAG, bool Unpacked) { 4244 if (!LoadVT.isVector()) 4245 return Result; 4246 4247 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4248 // Truncate to v2i16/v4i16. 4249 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4250 4251 // Workaround legalizer not scalarizing truncate after vector op 4252 // legalization byt not creating intermediate vector trunc. 4253 SmallVector<SDValue, 4> Elts; 4254 DAG.ExtractVectorElements(Result, Elts); 4255 for (SDValue &Elt : Elts) 4256 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4257 4258 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4259 4260 // Bitcast to original type (v2f16/v4f16). 4261 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4262 } 4263 4264 // Cast back to the original packed type. 4265 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4266 } 4267 4268 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4269 MemSDNode *M, 4270 SelectionDAG &DAG, 4271 ArrayRef<SDValue> Ops, 4272 bool IsIntrinsic) const { 4273 SDLoc DL(M); 4274 4275 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4276 EVT LoadVT = M->getValueType(0); 4277 4278 EVT EquivLoadVT = LoadVT; 4279 if (Unpacked && LoadVT.isVector()) { 4280 EquivLoadVT = LoadVT.isVector() ? 4281 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4282 LoadVT.getVectorNumElements()) : LoadVT; 4283 } 4284 4285 // Change from v4f16/v2f16 to EquivLoadVT. 4286 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4287 4288 SDValue Load 4289 = DAG.getMemIntrinsicNode( 4290 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4291 VTList, Ops, M->getMemoryVT(), 4292 M->getMemOperand()); 4293 if (!Unpacked) // Just adjusted the opcode. 4294 return Load; 4295 4296 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4297 4298 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4299 } 4300 4301 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4302 SelectionDAG &DAG, 4303 ArrayRef<SDValue> Ops) const { 4304 SDLoc DL(M); 4305 EVT LoadVT = M->getValueType(0); 4306 EVT EltType = LoadVT.getScalarType(); 4307 EVT IntVT = LoadVT.changeTypeToInteger(); 4308 4309 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4310 4311 unsigned Opc = 4312 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4313 4314 if (IsD16) { 4315 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4316 } 4317 4318 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4319 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4320 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4321 4322 if (isTypeLegal(LoadVT)) { 4323 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4324 M->getMemOperand(), DAG); 4325 } 4326 4327 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4328 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4329 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4330 M->getMemOperand(), DAG); 4331 return DAG.getMergeValues( 4332 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4333 DL); 4334 } 4335 4336 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4337 SDNode *N, SelectionDAG &DAG) { 4338 EVT VT = N->getValueType(0); 4339 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4340 int CondCode = CD->getSExtValue(); 4341 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4342 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4343 return DAG.getUNDEF(VT); 4344 4345 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4346 4347 SDValue LHS = N->getOperand(1); 4348 SDValue RHS = N->getOperand(2); 4349 4350 SDLoc DL(N); 4351 4352 EVT CmpVT = LHS.getValueType(); 4353 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4354 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4355 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4356 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4357 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4358 } 4359 4360 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4361 4362 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4363 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4364 4365 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4366 DAG.getCondCode(CCOpcode)); 4367 if (VT.bitsEq(CCVT)) 4368 return SetCC; 4369 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4370 } 4371 4372 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4373 SDNode *N, SelectionDAG &DAG) { 4374 EVT VT = N->getValueType(0); 4375 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4376 4377 int CondCode = CD->getSExtValue(); 4378 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4379 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4380 return DAG.getUNDEF(VT); 4381 } 4382 4383 SDValue Src0 = N->getOperand(1); 4384 SDValue Src1 = N->getOperand(2); 4385 EVT CmpVT = Src0.getValueType(); 4386 SDLoc SL(N); 4387 4388 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4389 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4390 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4391 } 4392 4393 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4394 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4395 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4396 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4397 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4398 Src1, DAG.getCondCode(CCOpcode)); 4399 if (VT.bitsEq(CCVT)) 4400 return SetCC; 4401 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4402 } 4403 4404 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4405 SelectionDAG &DAG) { 4406 EVT VT = N->getValueType(0); 4407 SDValue Src = N->getOperand(1); 4408 SDLoc SL(N); 4409 4410 if (Src.getOpcode() == ISD::SETCC) { 4411 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4412 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4413 Src.getOperand(1), Src.getOperand(2)); 4414 } 4415 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4416 // (ballot 0) -> 0 4417 if (Arg->isNullValue()) 4418 return DAG.getConstant(0, SL, VT); 4419 4420 // (ballot 1) -> EXEC/EXEC_LO 4421 if (Arg->isOne()) { 4422 Register Exec; 4423 if (VT.getScalarSizeInBits() == 32) 4424 Exec = AMDGPU::EXEC_LO; 4425 else if (VT.getScalarSizeInBits() == 64) 4426 Exec = AMDGPU::EXEC; 4427 else 4428 return SDValue(); 4429 4430 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4431 } 4432 } 4433 4434 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4435 // ISD::SETNE) 4436 return DAG.getNode( 4437 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4438 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4439 } 4440 4441 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4442 SmallVectorImpl<SDValue> &Results, 4443 SelectionDAG &DAG) const { 4444 switch (N->getOpcode()) { 4445 case ISD::INSERT_VECTOR_ELT: { 4446 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4447 Results.push_back(Res); 4448 return; 4449 } 4450 case ISD::EXTRACT_VECTOR_ELT: { 4451 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4452 Results.push_back(Res); 4453 return; 4454 } 4455 case ISD::INTRINSIC_WO_CHAIN: { 4456 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4457 switch (IID) { 4458 case Intrinsic::amdgcn_cvt_pkrtz: { 4459 SDValue Src0 = N->getOperand(1); 4460 SDValue Src1 = N->getOperand(2); 4461 SDLoc SL(N); 4462 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4463 Src0, Src1); 4464 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4465 return; 4466 } 4467 case Intrinsic::amdgcn_cvt_pknorm_i16: 4468 case Intrinsic::amdgcn_cvt_pknorm_u16: 4469 case Intrinsic::amdgcn_cvt_pk_i16: 4470 case Intrinsic::amdgcn_cvt_pk_u16: { 4471 SDValue Src0 = N->getOperand(1); 4472 SDValue Src1 = N->getOperand(2); 4473 SDLoc SL(N); 4474 unsigned Opcode; 4475 4476 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4477 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4478 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4479 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4480 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4481 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4482 else 4483 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4484 4485 EVT VT = N->getValueType(0); 4486 if (isTypeLegal(VT)) 4487 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4488 else { 4489 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4490 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4491 } 4492 return; 4493 } 4494 } 4495 break; 4496 } 4497 case ISD::INTRINSIC_W_CHAIN: { 4498 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4499 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4500 // FIXME: Hacky 4501 Results.push_back(Res.getOperand(0)); 4502 Results.push_back(Res.getOperand(1)); 4503 } else { 4504 Results.push_back(Res); 4505 Results.push_back(Res.getValue(1)); 4506 } 4507 return; 4508 } 4509 4510 break; 4511 } 4512 case ISD::SELECT: { 4513 SDLoc SL(N); 4514 EVT VT = N->getValueType(0); 4515 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4516 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4517 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4518 4519 EVT SelectVT = NewVT; 4520 if (NewVT.bitsLT(MVT::i32)) { 4521 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4522 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4523 SelectVT = MVT::i32; 4524 } 4525 4526 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4527 N->getOperand(0), LHS, RHS); 4528 4529 if (NewVT != SelectVT) 4530 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4531 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4532 return; 4533 } 4534 case ISD::FNEG: { 4535 if (N->getValueType(0) != MVT::v2f16) 4536 break; 4537 4538 SDLoc SL(N); 4539 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4540 4541 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4542 BC, 4543 DAG.getConstant(0x80008000, SL, MVT::i32)); 4544 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4545 return; 4546 } 4547 case ISD::FABS: { 4548 if (N->getValueType(0) != MVT::v2f16) 4549 break; 4550 4551 SDLoc SL(N); 4552 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4553 4554 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4555 BC, 4556 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4557 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4558 return; 4559 } 4560 default: 4561 break; 4562 } 4563 } 4564 4565 /// Helper function for LowerBRCOND 4566 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4567 4568 SDNode *Parent = Value.getNode(); 4569 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4570 I != E; ++I) { 4571 4572 if (I.getUse().get() != Value) 4573 continue; 4574 4575 if (I->getOpcode() == Opcode) 4576 return *I; 4577 } 4578 return nullptr; 4579 } 4580 4581 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4582 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4583 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4584 case Intrinsic::amdgcn_if: 4585 return AMDGPUISD::IF; 4586 case Intrinsic::amdgcn_else: 4587 return AMDGPUISD::ELSE; 4588 case Intrinsic::amdgcn_loop: 4589 return AMDGPUISD::LOOP; 4590 case Intrinsic::amdgcn_end_cf: 4591 llvm_unreachable("should not occur"); 4592 default: 4593 return 0; 4594 } 4595 } 4596 4597 // break, if_break, else_break are all only used as inputs to loop, not 4598 // directly as branch conditions. 4599 return 0; 4600 } 4601 4602 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4603 const Triple &TT = getTargetMachine().getTargetTriple(); 4604 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4605 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4606 AMDGPU::shouldEmitConstantsToTextSection(TT); 4607 } 4608 4609 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4610 // FIXME: Either avoid relying on address space here or change the default 4611 // address space for functions to avoid the explicit check. 4612 return (GV->getValueType()->isFunctionTy() || 4613 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4614 !shouldEmitFixup(GV) && 4615 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4616 } 4617 4618 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4619 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4620 } 4621 4622 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4623 if (!GV->hasExternalLinkage()) 4624 return true; 4625 4626 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4627 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4628 } 4629 4630 /// This transforms the control flow intrinsics to get the branch destination as 4631 /// last parameter, also switches branch target with BR if the need arise 4632 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4633 SelectionDAG &DAG) const { 4634 SDLoc DL(BRCOND); 4635 4636 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4637 SDValue Target = BRCOND.getOperand(2); 4638 SDNode *BR = nullptr; 4639 SDNode *SetCC = nullptr; 4640 4641 if (Intr->getOpcode() == ISD::SETCC) { 4642 // As long as we negate the condition everything is fine 4643 SetCC = Intr; 4644 Intr = SetCC->getOperand(0).getNode(); 4645 4646 } else { 4647 // Get the target from BR if we don't negate the condition 4648 BR = findUser(BRCOND, ISD::BR); 4649 Target = BR->getOperand(1); 4650 } 4651 4652 // FIXME: This changes the types of the intrinsics instead of introducing new 4653 // nodes with the correct types. 4654 // e.g. llvm.amdgcn.loop 4655 4656 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 4657 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 4658 4659 unsigned CFNode = isCFIntrinsic(Intr); 4660 if (CFNode == 0) { 4661 // This is a uniform branch so we don't need to legalize. 4662 return BRCOND; 4663 } 4664 4665 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4666 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4667 4668 assert(!SetCC || 4669 (SetCC->getConstantOperandVal(1) == 1 && 4670 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4671 ISD::SETNE)); 4672 4673 // operands of the new intrinsic call 4674 SmallVector<SDValue, 4> Ops; 4675 if (HaveChain) 4676 Ops.push_back(BRCOND.getOperand(0)); 4677 4678 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4679 Ops.push_back(Target); 4680 4681 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4682 4683 // build the new intrinsic call 4684 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4685 4686 if (!HaveChain) { 4687 SDValue Ops[] = { 4688 SDValue(Result, 0), 4689 BRCOND.getOperand(0) 4690 }; 4691 4692 Result = DAG.getMergeValues(Ops, DL).getNode(); 4693 } 4694 4695 if (BR) { 4696 // Give the branch instruction our target 4697 SDValue Ops[] = { 4698 BR->getOperand(0), 4699 BRCOND.getOperand(2) 4700 }; 4701 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4702 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4703 } 4704 4705 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4706 4707 // Copy the intrinsic results to registers 4708 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4709 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4710 if (!CopyToReg) 4711 continue; 4712 4713 Chain = DAG.getCopyToReg( 4714 Chain, DL, 4715 CopyToReg->getOperand(1), 4716 SDValue(Result, i - 1), 4717 SDValue()); 4718 4719 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4720 } 4721 4722 // Remove the old intrinsic from the chain 4723 DAG.ReplaceAllUsesOfValueWith( 4724 SDValue(Intr, Intr->getNumValues() - 1), 4725 Intr->getOperand(0)); 4726 4727 return Chain; 4728 } 4729 4730 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4731 SelectionDAG &DAG) const { 4732 MVT VT = Op.getSimpleValueType(); 4733 SDLoc DL(Op); 4734 // Checking the depth 4735 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4736 return DAG.getConstant(0, DL, VT); 4737 4738 MachineFunction &MF = DAG.getMachineFunction(); 4739 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4740 // Check for kernel and shader functions 4741 if (Info->isEntryFunction()) 4742 return DAG.getConstant(0, DL, VT); 4743 4744 MachineFrameInfo &MFI = MF.getFrameInfo(); 4745 // There is a call to @llvm.returnaddress in this function 4746 MFI.setReturnAddressIsTaken(true); 4747 4748 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4749 // Get the return address reg and mark it as an implicit live-in 4750 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4751 4752 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4753 } 4754 4755 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 4756 SDValue Op, 4757 const SDLoc &DL, 4758 EVT VT) const { 4759 return Op.getValueType().bitsLE(VT) ? 4760 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4761 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 4762 DAG.getTargetConstant(0, DL, MVT::i32)); 4763 } 4764 4765 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4766 assert(Op.getValueType() == MVT::f16 && 4767 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4768 4769 SDValue Src = Op.getOperand(0); 4770 EVT SrcVT = Src.getValueType(); 4771 if (SrcVT != MVT::f64) 4772 return Op; 4773 4774 SDLoc DL(Op); 4775 4776 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4777 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4778 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4779 } 4780 4781 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4782 SelectionDAG &DAG) const { 4783 EVT VT = Op.getValueType(); 4784 const MachineFunction &MF = DAG.getMachineFunction(); 4785 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4786 bool IsIEEEMode = Info->getMode().IEEE; 4787 4788 // FIXME: Assert during selection that this is only selected for 4789 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4790 // mode functions, but this happens to be OK since it's only done in cases 4791 // where there is known no sNaN. 4792 if (IsIEEEMode) 4793 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 4794 4795 if (VT == MVT::v4f16) 4796 return splitBinaryVectorOp(Op, DAG); 4797 return Op; 4798 } 4799 4800 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4801 SDLoc SL(Op); 4802 SDValue Chain = Op.getOperand(0); 4803 4804 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4805 !Subtarget->isTrapHandlerEnabled()) 4806 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4807 4808 MachineFunction &MF = DAG.getMachineFunction(); 4809 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4810 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4811 assert(UserSGPR != AMDGPU::NoRegister); 4812 SDValue QueuePtr = CreateLiveInRegister( 4813 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4814 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4815 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4816 QueuePtr, SDValue()); 4817 SDValue Ops[] = { 4818 ToReg, 4819 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 4820 SGPR01, 4821 ToReg.getValue(1) 4822 }; 4823 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4824 } 4825 4826 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 4827 SDLoc SL(Op); 4828 SDValue Chain = Op.getOperand(0); 4829 MachineFunction &MF = DAG.getMachineFunction(); 4830 4831 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4832 !Subtarget->isTrapHandlerEnabled()) { 4833 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4834 "debugtrap handler not supported", 4835 Op.getDebugLoc(), 4836 DS_Warning); 4837 LLVMContext &Ctx = MF.getFunction().getContext(); 4838 Ctx.diagnose(NoTrap); 4839 return Chain; 4840 } 4841 4842 SDValue Ops[] = { 4843 Chain, 4844 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 4845 }; 4846 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4847 } 4848 4849 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4850 SelectionDAG &DAG) const { 4851 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4852 if (Subtarget->hasApertureRegs()) { 4853 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 4854 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4855 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4856 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 4857 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4858 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4859 unsigned Encoding = 4860 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4861 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4862 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4863 4864 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4865 SDValue ApertureReg = SDValue( 4866 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4867 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4868 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4869 } 4870 4871 MachineFunction &MF = DAG.getMachineFunction(); 4872 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4873 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4874 assert(UserSGPR != AMDGPU::NoRegister); 4875 4876 SDValue QueuePtr = CreateLiveInRegister( 4877 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4878 4879 // Offset into amd_queue_t for group_segment_aperture_base_hi / 4880 // private_segment_aperture_base_hi. 4881 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 4882 4883 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 4884 4885 // TODO: Use custom target PseudoSourceValue. 4886 // TODO: We should use the value from the IR intrinsic call, but it might not 4887 // be available and how do we get it? 4888 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 4889 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4890 MinAlign(64, StructOffset), 4891 MachineMemOperand::MODereferenceable | 4892 MachineMemOperand::MOInvariant); 4893 } 4894 4895 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4896 SelectionDAG &DAG) const { 4897 SDLoc SL(Op); 4898 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4899 4900 SDValue Src = ASC->getOperand(0); 4901 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4902 4903 const AMDGPUTargetMachine &TM = 4904 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4905 4906 // flat -> local/private 4907 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4908 unsigned DestAS = ASC->getDestAddressSpace(); 4909 4910 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 4911 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 4912 unsigned NullVal = TM.getNullPointerValue(DestAS); 4913 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4914 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4915 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4916 4917 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4918 NonNull, Ptr, SegmentNullPtr); 4919 } 4920 } 4921 4922 // local/private -> flat 4923 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4924 unsigned SrcAS = ASC->getSrcAddressSpace(); 4925 4926 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 4927 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 4928 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4929 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4930 4931 SDValue NonNull 4932 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4933 4934 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4935 SDValue CvtPtr 4936 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4937 4938 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4939 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4940 FlatNullPtr); 4941 } 4942 } 4943 4944 // global <-> flat are no-ops and never emitted. 4945 4946 const MachineFunction &MF = DAG.getMachineFunction(); 4947 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 4948 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 4949 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 4950 4951 return DAG.getUNDEF(ASC->getValueType(0)); 4952 } 4953 4954 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 4955 // the small vector and inserting them into the big vector. That is better than 4956 // the default expansion of doing it via a stack slot. Even though the use of 4957 // the stack slot would be optimized away afterwards, the stack slot itself 4958 // remains. 4959 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4960 SelectionDAG &DAG) const { 4961 SDValue Vec = Op.getOperand(0); 4962 SDValue Ins = Op.getOperand(1); 4963 SDValue Idx = Op.getOperand(2); 4964 EVT VecVT = Vec.getValueType(); 4965 EVT InsVT = Ins.getValueType(); 4966 EVT EltVT = VecVT.getVectorElementType(); 4967 unsigned InsNumElts = InsVT.getVectorNumElements(); 4968 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 4969 SDLoc SL(Op); 4970 4971 for (unsigned I = 0; I != InsNumElts; ++I) { 4972 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 4973 DAG.getConstant(I, SL, MVT::i32)); 4974 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 4975 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 4976 } 4977 return Vec; 4978 } 4979 4980 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4981 SelectionDAG &DAG) const { 4982 SDValue Vec = Op.getOperand(0); 4983 SDValue InsVal = Op.getOperand(1); 4984 SDValue Idx = Op.getOperand(2); 4985 EVT VecVT = Vec.getValueType(); 4986 EVT EltVT = VecVT.getVectorElementType(); 4987 unsigned VecSize = VecVT.getSizeInBits(); 4988 unsigned EltSize = EltVT.getSizeInBits(); 4989 4990 4991 assert(VecSize <= 64); 4992 4993 unsigned NumElts = VecVT.getVectorNumElements(); 4994 SDLoc SL(Op); 4995 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 4996 4997 if (NumElts == 4 && EltSize == 16 && KIdx) { 4998 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 4999 5000 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5001 DAG.getConstant(0, SL, MVT::i32)); 5002 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5003 DAG.getConstant(1, SL, MVT::i32)); 5004 5005 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5006 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5007 5008 unsigned Idx = KIdx->getZExtValue(); 5009 bool InsertLo = Idx < 2; 5010 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5011 InsertLo ? LoVec : HiVec, 5012 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5013 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5014 5015 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5016 5017 SDValue Concat = InsertLo ? 5018 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5019 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5020 5021 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5022 } 5023 5024 if (isa<ConstantSDNode>(Idx)) 5025 return SDValue(); 5026 5027 MVT IntVT = MVT::getIntegerVT(VecSize); 5028 5029 // Avoid stack access for dynamic indexing. 5030 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5031 5032 // Create a congruent vector with the target value in each element so that 5033 // the required element can be masked and ORed into the target vector. 5034 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5035 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5036 5037 assert(isPowerOf2_32(EltSize)); 5038 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5039 5040 // Convert vector index to bit-index. 5041 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5042 5043 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5044 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5045 DAG.getConstant(0xffff, SL, IntVT), 5046 ScaledIdx); 5047 5048 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5049 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5050 DAG.getNOT(SL, BFM, IntVT), BCVec); 5051 5052 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5053 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5054 } 5055 5056 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5057 SelectionDAG &DAG) const { 5058 SDLoc SL(Op); 5059 5060 EVT ResultVT = Op.getValueType(); 5061 SDValue Vec = Op.getOperand(0); 5062 SDValue Idx = Op.getOperand(1); 5063 EVT VecVT = Vec.getValueType(); 5064 unsigned VecSize = VecVT.getSizeInBits(); 5065 EVT EltVT = VecVT.getVectorElementType(); 5066 assert(VecSize <= 64); 5067 5068 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5069 5070 // Make sure we do any optimizations that will make it easier to fold 5071 // source modifiers before obscuring it with bit operations. 5072 5073 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5074 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5075 return Combined; 5076 5077 unsigned EltSize = EltVT.getSizeInBits(); 5078 assert(isPowerOf2_32(EltSize)); 5079 5080 MVT IntVT = MVT::getIntegerVT(VecSize); 5081 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5082 5083 // Convert vector index to bit-index (* EltSize) 5084 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5085 5086 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5087 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5088 5089 if (ResultVT == MVT::f16) { 5090 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5091 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5092 } 5093 5094 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5095 } 5096 5097 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5098 assert(Elt % 2 == 0); 5099 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5100 } 5101 5102 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5103 SelectionDAG &DAG) const { 5104 SDLoc SL(Op); 5105 EVT ResultVT = Op.getValueType(); 5106 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5107 5108 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5109 EVT EltVT = PackVT.getVectorElementType(); 5110 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5111 5112 // vector_shuffle <0,1,6,7> lhs, rhs 5113 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5114 // 5115 // vector_shuffle <6,7,2,3> lhs, rhs 5116 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5117 // 5118 // vector_shuffle <6,7,0,1> lhs, rhs 5119 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5120 5121 // Avoid scalarizing when both halves are reading from consecutive elements. 5122 SmallVector<SDValue, 4> Pieces; 5123 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5124 if (elementPairIsContiguous(SVN->getMask(), I)) { 5125 const int Idx = SVN->getMaskElt(I); 5126 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5127 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5128 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5129 PackVT, SVN->getOperand(VecIdx), 5130 DAG.getConstant(EltIdx, SL, MVT::i32)); 5131 Pieces.push_back(SubVec); 5132 } else { 5133 const int Idx0 = SVN->getMaskElt(I); 5134 const int Idx1 = SVN->getMaskElt(I + 1); 5135 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5136 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5137 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5138 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5139 5140 SDValue Vec0 = SVN->getOperand(VecIdx0); 5141 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5142 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5143 5144 SDValue Vec1 = SVN->getOperand(VecIdx1); 5145 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5146 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5147 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5148 } 5149 } 5150 5151 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5152 } 5153 5154 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5155 SelectionDAG &DAG) const { 5156 SDLoc SL(Op); 5157 EVT VT = Op.getValueType(); 5158 5159 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5160 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5161 5162 // Turn into pair of packed build_vectors. 5163 // TODO: Special case for constants that can be materialized with s_mov_b64. 5164 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5165 { Op.getOperand(0), Op.getOperand(1) }); 5166 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5167 { Op.getOperand(2), Op.getOperand(3) }); 5168 5169 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5170 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5171 5172 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5173 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5174 } 5175 5176 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5177 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5178 5179 SDValue Lo = Op.getOperand(0); 5180 SDValue Hi = Op.getOperand(1); 5181 5182 // Avoid adding defined bits with the zero_extend. 5183 if (Hi.isUndef()) { 5184 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5185 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5186 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5187 } 5188 5189 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5190 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5191 5192 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5193 DAG.getConstant(16, SL, MVT::i32)); 5194 if (Lo.isUndef()) 5195 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5196 5197 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5198 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5199 5200 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5201 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5202 } 5203 5204 bool 5205 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5206 // We can fold offsets for anything that doesn't require a GOT relocation. 5207 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5208 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5209 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5210 !shouldEmitGOTReloc(GA->getGlobal()); 5211 } 5212 5213 static SDValue 5214 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5215 const SDLoc &DL, unsigned Offset, EVT PtrVT, 5216 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5217 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5218 // lowered to the following code sequence: 5219 // 5220 // For constant address space: 5221 // s_getpc_b64 s[0:1] 5222 // s_add_u32 s0, s0, $symbol 5223 // s_addc_u32 s1, s1, 0 5224 // 5225 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5226 // a fixup or relocation is emitted to replace $symbol with a literal 5227 // constant, which is a pc-relative offset from the encoding of the $symbol 5228 // operand to the global variable. 5229 // 5230 // For global address space: 5231 // s_getpc_b64 s[0:1] 5232 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5233 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5234 // 5235 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5236 // fixups or relocations are emitted to replace $symbol@*@lo and 5237 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5238 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5239 // operand to the global variable. 5240 // 5241 // What we want here is an offset from the value returned by s_getpc 5242 // (which is the address of the s_add_u32 instruction) to the global 5243 // variable, but since the encoding of $symbol starts 4 bytes after the start 5244 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5245 // small. This requires us to add 4 to the global variable offset in order to 5246 // compute the correct address. 5247 SDValue PtrLo = 5248 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5249 SDValue PtrHi; 5250 if (GAFlags == SIInstrInfo::MO_NONE) { 5251 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5252 } else { 5253 PtrHi = 5254 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5255 } 5256 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5257 } 5258 5259 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5260 SDValue Op, 5261 SelectionDAG &DAG) const { 5262 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5263 const GlobalValue *GV = GSD->getGlobal(); 5264 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5265 shouldUseLDSConstAddress(GV)) || 5266 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5267 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5268 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5269 5270 SDLoc DL(GSD); 5271 EVT PtrVT = Op.getValueType(); 5272 5273 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5274 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5275 SIInstrInfo::MO_ABS32_LO); 5276 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5277 } 5278 5279 if (shouldEmitFixup(GV)) 5280 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5281 else if (shouldEmitPCReloc(GV)) 5282 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5283 SIInstrInfo::MO_REL32); 5284 5285 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5286 SIInstrInfo::MO_GOTPCREL32); 5287 5288 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5289 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5290 const DataLayout &DataLayout = DAG.getDataLayout(); 5291 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 5292 MachinePointerInfo PtrInfo 5293 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5294 5295 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 5296 MachineMemOperand::MODereferenceable | 5297 MachineMemOperand::MOInvariant); 5298 } 5299 5300 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5301 const SDLoc &DL, SDValue V) const { 5302 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5303 // the destination register. 5304 // 5305 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5306 // so we will end up with redundant moves to m0. 5307 // 5308 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5309 5310 // A Null SDValue creates a glue result. 5311 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5312 V, Chain); 5313 return SDValue(M0, 0); 5314 } 5315 5316 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5317 SDValue Op, 5318 MVT VT, 5319 unsigned Offset) const { 5320 SDLoc SL(Op); 5321 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 5322 DAG.getEntryNode(), Offset, 4, false); 5323 // The local size values will have the hi 16-bits as zero. 5324 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5325 DAG.getValueType(VT)); 5326 } 5327 5328 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5329 EVT VT) { 5330 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5331 "non-hsa intrinsic with hsa target", 5332 DL.getDebugLoc()); 5333 DAG.getContext()->diagnose(BadIntrin); 5334 return DAG.getUNDEF(VT); 5335 } 5336 5337 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5338 EVT VT) { 5339 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5340 "intrinsic not supported on subtarget", 5341 DL.getDebugLoc()); 5342 DAG.getContext()->diagnose(BadIntrin); 5343 return DAG.getUNDEF(VT); 5344 } 5345 5346 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5347 ArrayRef<SDValue> Elts) { 5348 assert(!Elts.empty()); 5349 MVT Type; 5350 unsigned NumElts; 5351 5352 if (Elts.size() == 1) { 5353 Type = MVT::f32; 5354 NumElts = 1; 5355 } else if (Elts.size() == 2) { 5356 Type = MVT::v2f32; 5357 NumElts = 2; 5358 } else if (Elts.size() == 3) { 5359 Type = MVT::v3f32; 5360 NumElts = 3; 5361 } else if (Elts.size() <= 4) { 5362 Type = MVT::v4f32; 5363 NumElts = 4; 5364 } else if (Elts.size() <= 8) { 5365 Type = MVT::v8f32; 5366 NumElts = 8; 5367 } else { 5368 assert(Elts.size() <= 16); 5369 Type = MVT::v16f32; 5370 NumElts = 16; 5371 } 5372 5373 SmallVector<SDValue, 16> VecElts(NumElts); 5374 for (unsigned i = 0; i < Elts.size(); ++i) { 5375 SDValue Elt = Elts[i]; 5376 if (Elt.getValueType() != MVT::f32) 5377 Elt = DAG.getBitcast(MVT::f32, Elt); 5378 VecElts[i] = Elt; 5379 } 5380 for (unsigned i = Elts.size(); i < NumElts; ++i) 5381 VecElts[i] = DAG.getUNDEF(MVT::f32); 5382 5383 if (NumElts == 1) 5384 return VecElts[0]; 5385 return DAG.getBuildVector(Type, DL, VecElts); 5386 } 5387 5388 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5389 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5390 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5391 5392 uint64_t Value = CachePolicyConst->getZExtValue(); 5393 SDLoc DL(CachePolicy); 5394 if (GLC) { 5395 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5396 Value &= ~(uint64_t)0x1; 5397 } 5398 if (SLC) { 5399 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5400 Value &= ~(uint64_t)0x2; 5401 } 5402 if (DLC) { 5403 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5404 Value &= ~(uint64_t)0x4; 5405 } 5406 5407 return Value == 0; 5408 } 5409 5410 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5411 SDValue Src, int ExtraElts) { 5412 EVT SrcVT = Src.getValueType(); 5413 5414 SmallVector<SDValue, 8> Elts; 5415 5416 if (SrcVT.isVector()) 5417 DAG.ExtractVectorElements(Src, Elts); 5418 else 5419 Elts.push_back(Src); 5420 5421 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5422 while (ExtraElts--) 5423 Elts.push_back(Undef); 5424 5425 return DAG.getBuildVector(CastVT, DL, Elts); 5426 } 5427 5428 // Re-construct the required return value for a image load intrinsic. 5429 // This is more complicated due to the optional use TexFailCtrl which means the required 5430 // return type is an aggregate 5431 static SDValue constructRetValue(SelectionDAG &DAG, 5432 MachineSDNode *Result, 5433 ArrayRef<EVT> ResultTypes, 5434 bool IsTexFail, bool Unpacked, bool IsD16, 5435 int DMaskPop, int NumVDataDwords, 5436 const SDLoc &DL, LLVMContext &Context) { 5437 // Determine the required return type. This is the same regardless of IsTexFail flag 5438 EVT ReqRetVT = ResultTypes[0]; 5439 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5440 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5441 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5442 5443 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5444 DMaskPop : (DMaskPop + 1) / 2; 5445 5446 MVT DataDwordVT = NumDataDwords == 1 ? 5447 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5448 5449 MVT MaskPopVT = MaskPopDwords == 1 ? 5450 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5451 5452 SDValue Data(Result, 0); 5453 SDValue TexFail; 5454 5455 if (IsTexFail) { 5456 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5457 if (MaskPopVT.isVector()) { 5458 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5459 SDValue(Result, 0), ZeroIdx); 5460 } else { 5461 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5462 SDValue(Result, 0), ZeroIdx); 5463 } 5464 5465 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5466 SDValue(Result, 0), 5467 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5468 } 5469 5470 if (DataDwordVT.isVector()) 5471 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5472 NumDataDwords - MaskPopDwords); 5473 5474 if (IsD16) 5475 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5476 5477 if (!ReqRetVT.isVector()) 5478 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5479 5480 Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data); 5481 5482 if (TexFail) 5483 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5484 5485 if (Result->getNumValues() == 1) 5486 return Data; 5487 5488 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5489 } 5490 5491 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5492 SDValue *LWE, bool &IsTexFail) { 5493 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5494 5495 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5496 if (Value) { 5497 IsTexFail = true; 5498 } 5499 5500 SDLoc DL(TexFailCtrlConst); 5501 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5502 Value &= ~(uint64_t)0x1; 5503 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5504 Value &= ~(uint64_t)0x2; 5505 5506 return Value == 0; 5507 } 5508 5509 SDValue SITargetLowering::lowerImage(SDValue Op, 5510 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5511 SelectionDAG &DAG) const { 5512 SDLoc DL(Op); 5513 MachineFunction &MF = DAG.getMachineFunction(); 5514 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5515 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5516 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5517 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5518 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5519 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5520 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5521 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5522 unsigned IntrOpcode = Intr->BaseOpcode; 5523 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5524 5525 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5526 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5527 bool IsD16 = false; 5528 bool IsA16 = false; 5529 SDValue VData; 5530 int NumVDataDwords; 5531 bool AdjustRetType = false; 5532 5533 unsigned AddrIdx; // Index of first address argument 5534 unsigned DMask; 5535 unsigned DMaskLanes = 0; 5536 5537 if (BaseOpcode->Atomic) { 5538 VData = Op.getOperand(2); 5539 5540 bool Is64Bit = VData.getValueType() == MVT::i64; 5541 if (BaseOpcode->AtomicX2) { 5542 SDValue VData2 = Op.getOperand(3); 5543 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5544 {VData, VData2}); 5545 if (Is64Bit) 5546 VData = DAG.getBitcast(MVT::v4i32, VData); 5547 5548 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5549 DMask = Is64Bit ? 0xf : 0x3; 5550 NumVDataDwords = Is64Bit ? 4 : 2; 5551 AddrIdx = 4; 5552 } else { 5553 DMask = Is64Bit ? 0x3 : 0x1; 5554 NumVDataDwords = Is64Bit ? 2 : 1; 5555 AddrIdx = 3; 5556 } 5557 } else { 5558 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5559 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5560 DMask = DMaskConst->getZExtValue(); 5561 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5562 5563 if (BaseOpcode->Store) { 5564 VData = Op.getOperand(2); 5565 5566 MVT StoreVT = VData.getSimpleValueType(); 5567 if (StoreVT.getScalarType() == MVT::f16) { 5568 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5569 return Op; // D16 is unsupported for this instruction 5570 5571 IsD16 = true; 5572 VData = handleD16VData(VData, DAG); 5573 } 5574 5575 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5576 } else { 5577 // Work out the num dwords based on the dmask popcount and underlying type 5578 // and whether packing is supported. 5579 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5580 if (LoadVT.getScalarType() == MVT::f16) { 5581 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5582 return Op; // D16 is unsupported for this instruction 5583 5584 IsD16 = true; 5585 } 5586 5587 // Confirm that the return type is large enough for the dmask specified 5588 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5589 (!LoadVT.isVector() && DMaskLanes > 1)) 5590 return Op; 5591 5592 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5593 NumVDataDwords = (DMaskLanes + 1) / 2; 5594 else 5595 NumVDataDwords = DMaskLanes; 5596 5597 AdjustRetType = true; 5598 } 5599 5600 AddrIdx = DMaskIdx + 1; 5601 } 5602 5603 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5604 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5605 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5606 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5607 NumCoords + NumLCM; 5608 unsigned NumMIVAddrs = NumVAddrs; 5609 5610 SmallVector<SDValue, 4> VAddrs; 5611 5612 // Optimize _L to _LZ when _L is zero 5613 if (LZMappingInfo) { 5614 if (auto ConstantLod = 5615 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5616 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5617 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5618 NumMIVAddrs--; // remove 'lod' 5619 } 5620 } 5621 } 5622 5623 // Optimize _mip away, when 'lod' is zero 5624 if (MIPMappingInfo) { 5625 if (auto ConstantLod = 5626 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5627 if (ConstantLod->isNullValue()) { 5628 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5629 NumMIVAddrs--; // remove 'lod' 5630 } 5631 } 5632 } 5633 5634 // Check for 16 bit addresses and pack if true. 5635 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5636 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5637 const MVT VAddrScalarVT = VAddrVT.getScalarType(); 5638 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) { 5639 // Illegal to use a16 images 5640 if (!ST->hasFeature(AMDGPU::FeatureR128A16) && !ST->hasFeature(AMDGPU::FeatureGFX10A16)) 5641 return Op; 5642 5643 IsA16 = true; 5644 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5645 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) { 5646 SDValue AddrLo; 5647 // Push back extra arguments. 5648 if (i < DimIdx) { 5649 AddrLo = Op.getOperand(i); 5650 } else { 5651 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, 5652 // in 1D, derivatives dx/dh and dx/dv are packed with undef. 5653 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) || 5654 ((NumGradients / 2) % 2 == 1 && 5655 (i == DimIdx + (NumGradients / 2) - 1 || 5656 i == DimIdx + NumGradients - 1))) { 5657 AddrLo = Op.getOperand(i); 5658 if (AddrLo.getValueType() != MVT::i16) 5659 AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i)); 5660 AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo); 5661 } else { 5662 AddrLo = DAG.getBuildVector(VectorVT, DL, 5663 {Op.getOperand(i), Op.getOperand(i + 1)}); 5664 i++; 5665 } 5666 AddrLo = DAG.getBitcast(MVT::f32, AddrLo); 5667 } 5668 VAddrs.push_back(AddrLo); 5669 } 5670 } else { 5671 for (unsigned i = 0; i < NumMIVAddrs; ++i) 5672 VAddrs.push_back(Op.getOperand(AddrIdx + i)); 5673 } 5674 5675 // If the register allocator cannot place the address registers contiguously 5676 // without introducing moves, then using the non-sequential address encoding 5677 // is always preferable, since it saves VALU instructions and is usually a 5678 // wash in terms of code size or even better. 5679 // 5680 // However, we currently have no way of hinting to the register allocator that 5681 // MIMG addresses should be placed contiguously when it is possible to do so, 5682 // so force non-NSA for the common 2-address case as a heuristic. 5683 // 5684 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5685 // allocation when possible. 5686 bool UseNSA = 5687 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5688 SDValue VAddr; 5689 if (!UseNSA) 5690 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5691 5692 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5693 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5694 unsigned CtrlIdx; // Index of texfailctrl argument 5695 SDValue Unorm; 5696 if (!BaseOpcode->Sampler) { 5697 Unorm = True; 5698 CtrlIdx = AddrIdx + NumVAddrs + 1; 5699 } else { 5700 auto UnormConst = 5701 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 5702 5703 Unorm = UnormConst->getZExtValue() ? True : False; 5704 CtrlIdx = AddrIdx + NumVAddrs + 3; 5705 } 5706 5707 SDValue TFE; 5708 SDValue LWE; 5709 SDValue TexFail = Op.getOperand(CtrlIdx); 5710 bool IsTexFail = false; 5711 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 5712 return Op; 5713 5714 if (IsTexFail) { 5715 if (!DMaskLanes) { 5716 // Expecting to get an error flag since TFC is on - and dmask is 0 5717 // Force dmask to be at least 1 otherwise the instruction will fail 5718 DMask = 0x1; 5719 DMaskLanes = 1; 5720 NumVDataDwords = 1; 5721 } 5722 NumVDataDwords += 1; 5723 AdjustRetType = true; 5724 } 5725 5726 // Has something earlier tagged that the return type needs adjusting 5727 // This happens if the instruction is a load or has set TexFailCtrl flags 5728 if (AdjustRetType) { 5729 // NumVDataDwords reflects the true number of dwords required in the return type 5730 if (DMaskLanes == 0 && !BaseOpcode->Store) { 5731 // This is a no-op load. This can be eliminated 5732 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 5733 if (isa<MemSDNode>(Op)) 5734 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 5735 return Undef; 5736 } 5737 5738 EVT NewVT = NumVDataDwords > 1 ? 5739 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 5740 : MVT::i32; 5741 5742 ResultTypes[0] = NewVT; 5743 if (ResultTypes.size() == 3) { 5744 // Original result was aggregate type used for TexFailCtrl results 5745 // The actual instruction returns as a vector type which has now been 5746 // created. Remove the aggregate result. 5747 ResultTypes.erase(&ResultTypes[1]); 5748 } 5749 } 5750 5751 SDValue GLC; 5752 SDValue SLC; 5753 SDValue DLC; 5754 if (BaseOpcode->Atomic) { 5755 GLC = True; // TODO no-return optimization 5756 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 5757 IsGFX10 ? &DLC : nullptr)) 5758 return Op; 5759 } else { 5760 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 5761 IsGFX10 ? &DLC : nullptr)) 5762 return Op; 5763 } 5764 5765 SmallVector<SDValue, 26> Ops; 5766 if (BaseOpcode->Store || BaseOpcode->Atomic) 5767 Ops.push_back(VData); // vdata 5768 if (UseNSA) { 5769 for (const SDValue &Addr : VAddrs) 5770 Ops.push_back(Addr); 5771 } else { 5772 Ops.push_back(VAddr); 5773 } 5774 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 5775 if (BaseOpcode->Sampler) 5776 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 5777 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 5778 if (IsGFX10) 5779 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 5780 Ops.push_back(Unorm); 5781 if (IsGFX10) 5782 Ops.push_back(DLC); 5783 Ops.push_back(GLC); 5784 Ops.push_back(SLC); 5785 Ops.push_back(IsA16 && // r128, a16 for gfx9 5786 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 5787 if (IsGFX10) 5788 Ops.push_back(IsA16 ? True : False); 5789 Ops.push_back(TFE); 5790 Ops.push_back(LWE); 5791 if (!IsGFX10) 5792 Ops.push_back(DimInfo->DA ? True : False); 5793 if (BaseOpcode->HasD16) 5794 Ops.push_back(IsD16 ? True : False); 5795 if (isa<MemSDNode>(Op)) 5796 Ops.push_back(Op.getOperand(0)); // chain 5797 5798 int NumVAddrDwords = 5799 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 5800 int Opcode = -1; 5801 5802 if (IsGFX10) { 5803 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 5804 UseNSA ? AMDGPU::MIMGEncGfx10NSA 5805 : AMDGPU::MIMGEncGfx10Default, 5806 NumVDataDwords, NumVAddrDwords); 5807 } else { 5808 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5809 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 5810 NumVDataDwords, NumVAddrDwords); 5811 if (Opcode == -1) 5812 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 5813 NumVDataDwords, NumVAddrDwords); 5814 } 5815 assert(Opcode != -1); 5816 5817 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 5818 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 5819 MachineMemOperand *MemRef = MemOp->getMemOperand(); 5820 DAG.setNodeMemRefs(NewNode, {MemRef}); 5821 } 5822 5823 if (BaseOpcode->AtomicX2) { 5824 SmallVector<SDValue, 1> Elt; 5825 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 5826 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 5827 } else if (!BaseOpcode->Store) { 5828 return constructRetValue(DAG, NewNode, 5829 OrigResultTypes, IsTexFail, 5830 Subtarget->hasUnpackedD16VMem(), IsD16, 5831 DMaskLanes, NumVDataDwords, DL, 5832 *DAG.getContext()); 5833 } 5834 5835 return SDValue(NewNode, 0); 5836 } 5837 5838 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 5839 SDValue Offset, SDValue CachePolicy, 5840 SelectionDAG &DAG) const { 5841 MachineFunction &MF = DAG.getMachineFunction(); 5842 5843 const DataLayout &DataLayout = DAG.getDataLayout(); 5844 Align Alignment = 5845 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 5846 5847 MachineMemOperand *MMO = MF.getMachineMemOperand( 5848 MachinePointerInfo(), 5849 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 5850 MachineMemOperand::MOInvariant, 5851 VT.getStoreSize(), Alignment); 5852 5853 if (!Offset->isDivergent()) { 5854 SDValue Ops[] = { 5855 Rsrc, 5856 Offset, // Offset 5857 CachePolicy 5858 }; 5859 5860 // Widen vec3 load to vec4. 5861 if (VT.isVector() && VT.getVectorNumElements() == 3) { 5862 EVT WidenedVT = 5863 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 5864 auto WidenedOp = DAG.getMemIntrinsicNode( 5865 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 5866 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 5867 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 5868 DAG.getVectorIdxConstant(0, DL)); 5869 return Subvector; 5870 } 5871 5872 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 5873 DAG.getVTList(VT), Ops, VT, MMO); 5874 } 5875 5876 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 5877 // assume that the buffer is unswizzled. 5878 SmallVector<SDValue, 4> Loads; 5879 unsigned NumLoads = 1; 5880 MVT LoadVT = VT.getSimpleVT(); 5881 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 5882 assert((LoadVT.getScalarType() == MVT::i32 || 5883 LoadVT.getScalarType() == MVT::f32)); 5884 5885 if (NumElts == 8 || NumElts == 16) { 5886 NumLoads = NumElts / 4; 5887 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 5888 } 5889 5890 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 5891 SDValue Ops[] = { 5892 DAG.getEntryNode(), // Chain 5893 Rsrc, // rsrc 5894 DAG.getConstant(0, DL, MVT::i32), // vindex 5895 {}, // voffset 5896 {}, // soffset 5897 {}, // offset 5898 CachePolicy, // cachepolicy 5899 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 5900 }; 5901 5902 // Use the alignment to ensure that the required offsets will fit into the 5903 // immediate offsets. 5904 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 5905 5906 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 5907 for (unsigned i = 0; i < NumLoads; ++i) { 5908 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 5909 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 5910 LoadVT, MMO, DAG)); 5911 } 5912 5913 if (NumElts == 8 || NumElts == 16) 5914 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 5915 5916 return Loads[0]; 5917 } 5918 5919 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 5920 SelectionDAG &DAG) const { 5921 MachineFunction &MF = DAG.getMachineFunction(); 5922 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 5923 5924 EVT VT = Op.getValueType(); 5925 SDLoc DL(Op); 5926 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5927 5928 // TODO: Should this propagate fast-math-flags? 5929 5930 switch (IntrinsicID) { 5931 case Intrinsic::amdgcn_implicit_buffer_ptr: { 5932 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 5933 return emitNonHSAIntrinsicError(DAG, DL, VT); 5934 return getPreloadedValue(DAG, *MFI, VT, 5935 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 5936 } 5937 case Intrinsic::amdgcn_dispatch_ptr: 5938 case Intrinsic::amdgcn_queue_ptr: { 5939 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 5940 DiagnosticInfoUnsupported BadIntrin( 5941 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 5942 DL.getDebugLoc()); 5943 DAG.getContext()->diagnose(BadIntrin); 5944 return DAG.getUNDEF(VT); 5945 } 5946 5947 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 5948 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 5949 return getPreloadedValue(DAG, *MFI, VT, RegID); 5950 } 5951 case Intrinsic::amdgcn_implicitarg_ptr: { 5952 if (MFI->isEntryFunction()) 5953 return getImplicitArgPtr(DAG, DL); 5954 return getPreloadedValue(DAG, *MFI, VT, 5955 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 5956 } 5957 case Intrinsic::amdgcn_kernarg_segment_ptr: { 5958 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 5959 // This only makes sense to call in a kernel, so just lower to null. 5960 return DAG.getConstant(0, DL, VT); 5961 } 5962 5963 return getPreloadedValue(DAG, *MFI, VT, 5964 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 5965 } 5966 case Intrinsic::amdgcn_dispatch_id: { 5967 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 5968 } 5969 case Intrinsic::amdgcn_rcp: 5970 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 5971 case Intrinsic::amdgcn_rsq: 5972 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5973 case Intrinsic::amdgcn_rsq_legacy: 5974 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5975 return emitRemovedIntrinsicError(DAG, DL, VT); 5976 return SDValue(); 5977 case Intrinsic::amdgcn_rcp_legacy: 5978 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5979 return emitRemovedIntrinsicError(DAG, DL, VT); 5980 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 5981 case Intrinsic::amdgcn_rsq_clamp: { 5982 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5983 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 5984 5985 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 5986 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 5987 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 5988 5989 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5990 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 5991 DAG.getConstantFP(Max, DL, VT)); 5992 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 5993 DAG.getConstantFP(Min, DL, VT)); 5994 } 5995 case Intrinsic::r600_read_ngroups_x: 5996 if (Subtarget->isAmdHsaOS()) 5997 return emitNonHSAIntrinsicError(DAG, DL, VT); 5998 5999 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6000 SI::KernelInputOffsets::NGROUPS_X, 4, false); 6001 case Intrinsic::r600_read_ngroups_y: 6002 if (Subtarget->isAmdHsaOS()) 6003 return emitNonHSAIntrinsicError(DAG, DL, VT); 6004 6005 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6006 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 6007 case Intrinsic::r600_read_ngroups_z: 6008 if (Subtarget->isAmdHsaOS()) 6009 return emitNonHSAIntrinsicError(DAG, DL, VT); 6010 6011 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6012 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 6013 case Intrinsic::r600_read_global_size_x: 6014 if (Subtarget->isAmdHsaOS()) 6015 return emitNonHSAIntrinsicError(DAG, DL, VT); 6016 6017 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6018 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 6019 case Intrinsic::r600_read_global_size_y: 6020 if (Subtarget->isAmdHsaOS()) 6021 return emitNonHSAIntrinsicError(DAG, DL, VT); 6022 6023 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6024 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 6025 case Intrinsic::r600_read_global_size_z: 6026 if (Subtarget->isAmdHsaOS()) 6027 return emitNonHSAIntrinsicError(DAG, DL, VT); 6028 6029 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6030 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 6031 case Intrinsic::r600_read_local_size_x: 6032 if (Subtarget->isAmdHsaOS()) 6033 return emitNonHSAIntrinsicError(DAG, DL, VT); 6034 6035 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6036 SI::KernelInputOffsets::LOCAL_SIZE_X); 6037 case Intrinsic::r600_read_local_size_y: 6038 if (Subtarget->isAmdHsaOS()) 6039 return emitNonHSAIntrinsicError(DAG, DL, VT); 6040 6041 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6042 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6043 case Intrinsic::r600_read_local_size_z: 6044 if (Subtarget->isAmdHsaOS()) 6045 return emitNonHSAIntrinsicError(DAG, DL, VT); 6046 6047 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6048 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6049 case Intrinsic::amdgcn_workgroup_id_x: 6050 return getPreloadedValue(DAG, *MFI, VT, 6051 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6052 case Intrinsic::amdgcn_workgroup_id_y: 6053 return getPreloadedValue(DAG, *MFI, VT, 6054 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6055 case Intrinsic::amdgcn_workgroup_id_z: 6056 return getPreloadedValue(DAG, *MFI, VT, 6057 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6058 case Intrinsic::amdgcn_workitem_id_x: 6059 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6060 SDLoc(DAG.getEntryNode()), 6061 MFI->getArgInfo().WorkItemIDX); 6062 case Intrinsic::amdgcn_workitem_id_y: 6063 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6064 SDLoc(DAG.getEntryNode()), 6065 MFI->getArgInfo().WorkItemIDY); 6066 case Intrinsic::amdgcn_workitem_id_z: 6067 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6068 SDLoc(DAG.getEntryNode()), 6069 MFI->getArgInfo().WorkItemIDZ); 6070 case Intrinsic::amdgcn_wavefrontsize: 6071 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6072 SDLoc(Op), MVT::i32); 6073 case Intrinsic::amdgcn_s_buffer_load: { 6074 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 6075 SDValue GLC; 6076 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6077 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6078 IsGFX10 ? &DLC : nullptr)) 6079 return Op; 6080 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6081 DAG); 6082 } 6083 case Intrinsic::amdgcn_fdiv_fast: 6084 return lowerFDIV_FAST(Op, DAG); 6085 case Intrinsic::amdgcn_sin: 6086 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6087 6088 case Intrinsic::amdgcn_cos: 6089 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6090 6091 case Intrinsic::amdgcn_mul_u24: 6092 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6093 case Intrinsic::amdgcn_mul_i24: 6094 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6095 6096 case Intrinsic::amdgcn_log_clamp: { 6097 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6098 return SDValue(); 6099 6100 DiagnosticInfoUnsupported BadIntrin( 6101 MF.getFunction(), "intrinsic not supported on subtarget", 6102 DL.getDebugLoc()); 6103 DAG.getContext()->diagnose(BadIntrin); 6104 return DAG.getUNDEF(VT); 6105 } 6106 case Intrinsic::amdgcn_ldexp: 6107 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6108 Op.getOperand(1), Op.getOperand(2)); 6109 6110 case Intrinsic::amdgcn_fract: 6111 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6112 6113 case Intrinsic::amdgcn_class: 6114 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6115 Op.getOperand(1), Op.getOperand(2)); 6116 case Intrinsic::amdgcn_div_fmas: 6117 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6118 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6119 Op.getOperand(4)); 6120 6121 case Intrinsic::amdgcn_div_fixup: 6122 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6123 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6124 6125 case Intrinsic::amdgcn_trig_preop: 6126 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 6127 Op.getOperand(1), Op.getOperand(2)); 6128 case Intrinsic::amdgcn_div_scale: { 6129 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6130 6131 // Translate to the operands expected by the machine instruction. The 6132 // first parameter must be the same as the first instruction. 6133 SDValue Numerator = Op.getOperand(1); 6134 SDValue Denominator = Op.getOperand(2); 6135 6136 // Note this order is opposite of the machine instruction's operations, 6137 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6138 // intrinsic has the numerator as the first operand to match a normal 6139 // division operation. 6140 6141 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6142 6143 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6144 Denominator, Numerator); 6145 } 6146 case Intrinsic::amdgcn_icmp: { 6147 // There is a Pat that handles this variant, so return it as-is. 6148 if (Op.getOperand(1).getValueType() == MVT::i1 && 6149 Op.getConstantOperandVal(2) == 0 && 6150 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6151 return Op; 6152 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6153 } 6154 case Intrinsic::amdgcn_fcmp: { 6155 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6156 } 6157 case Intrinsic::amdgcn_ballot: 6158 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6159 case Intrinsic::amdgcn_fmed3: 6160 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6161 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6162 case Intrinsic::amdgcn_fdot2: 6163 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6164 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6165 Op.getOperand(4)); 6166 case Intrinsic::amdgcn_fmul_legacy: 6167 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6168 Op.getOperand(1), Op.getOperand(2)); 6169 case Intrinsic::amdgcn_sffbh: 6170 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6171 case Intrinsic::amdgcn_sbfe: 6172 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6173 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6174 case Intrinsic::amdgcn_ubfe: 6175 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6176 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6177 case Intrinsic::amdgcn_cvt_pkrtz: 6178 case Intrinsic::amdgcn_cvt_pknorm_i16: 6179 case Intrinsic::amdgcn_cvt_pknorm_u16: 6180 case Intrinsic::amdgcn_cvt_pk_i16: 6181 case Intrinsic::amdgcn_cvt_pk_u16: { 6182 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6183 EVT VT = Op.getValueType(); 6184 unsigned Opcode; 6185 6186 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6187 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6188 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6189 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6190 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6191 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6192 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6193 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6194 else 6195 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6196 6197 if (isTypeLegal(VT)) 6198 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6199 6200 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6201 Op.getOperand(1), Op.getOperand(2)); 6202 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6203 } 6204 case Intrinsic::amdgcn_fmad_ftz: 6205 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6206 Op.getOperand(2), Op.getOperand(3)); 6207 6208 case Intrinsic::amdgcn_if_break: 6209 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6210 Op->getOperand(1), Op->getOperand(2)), 0); 6211 6212 case Intrinsic::amdgcn_groupstaticsize: { 6213 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6214 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6215 return Op; 6216 6217 const Module *M = MF.getFunction().getParent(); 6218 const GlobalValue *GV = 6219 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6220 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6221 SIInstrInfo::MO_ABS32_LO); 6222 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6223 } 6224 case Intrinsic::amdgcn_is_shared: 6225 case Intrinsic::amdgcn_is_private: { 6226 SDLoc SL(Op); 6227 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6228 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6229 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6230 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6231 Op.getOperand(1)); 6232 6233 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6234 DAG.getConstant(1, SL, MVT::i32)); 6235 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6236 } 6237 case Intrinsic::amdgcn_alignbit: 6238 return DAG.getNode(ISD::FSHR, DL, VT, 6239 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6240 case Intrinsic::amdgcn_reloc_constant: { 6241 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6242 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6243 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6244 auto RelocSymbol = cast<GlobalVariable>( 6245 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6246 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6247 SIInstrInfo::MO_ABS32_LO); 6248 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6249 } 6250 default: 6251 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6252 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6253 return lowerImage(Op, ImageDimIntr, DAG); 6254 6255 return Op; 6256 } 6257 } 6258 6259 // This function computes an appropriate offset to pass to 6260 // MachineMemOperand::setOffset() based on the offset inputs to 6261 // an intrinsic. If any of the offsets are non-contstant or 6262 // if VIndex is non-zero then this function returns 0. Otherwise, 6263 // it returns the sum of VOffset, SOffset, and Offset. 6264 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6265 SDValue SOffset, 6266 SDValue Offset, 6267 SDValue VIndex = SDValue()) { 6268 6269 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6270 !isa<ConstantSDNode>(Offset)) 6271 return 0; 6272 6273 if (VIndex) { 6274 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6275 return 0; 6276 } 6277 6278 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6279 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6280 cast<ConstantSDNode>(Offset)->getSExtValue(); 6281 } 6282 6283 static unsigned getDSShaderTypeValue(const MachineFunction &MF) { 6284 switch (MF.getFunction().getCallingConv()) { 6285 case CallingConv::AMDGPU_PS: 6286 return 1; 6287 case CallingConv::AMDGPU_VS: 6288 return 2; 6289 case CallingConv::AMDGPU_GS: 6290 return 3; 6291 case CallingConv::AMDGPU_HS: 6292 case CallingConv::AMDGPU_LS: 6293 case CallingConv::AMDGPU_ES: 6294 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6295 case CallingConv::AMDGPU_CS: 6296 case CallingConv::AMDGPU_KERNEL: 6297 case CallingConv::C: 6298 case CallingConv::Fast: 6299 default: 6300 // Assume other calling conventions are various compute callable functions 6301 return 0; 6302 } 6303 } 6304 6305 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6306 SelectionDAG &DAG) const { 6307 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6308 SDLoc DL(Op); 6309 6310 switch (IntrID) { 6311 case Intrinsic::amdgcn_ds_ordered_add: 6312 case Intrinsic::amdgcn_ds_ordered_swap: { 6313 MemSDNode *M = cast<MemSDNode>(Op); 6314 SDValue Chain = M->getOperand(0); 6315 SDValue M0 = M->getOperand(2); 6316 SDValue Value = M->getOperand(3); 6317 unsigned IndexOperand = M->getConstantOperandVal(7); 6318 unsigned WaveRelease = M->getConstantOperandVal(8); 6319 unsigned WaveDone = M->getConstantOperandVal(9); 6320 6321 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6322 IndexOperand &= ~0x3f; 6323 unsigned CountDw = 0; 6324 6325 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6326 CountDw = (IndexOperand >> 24) & 0xf; 6327 IndexOperand &= ~(0xf << 24); 6328 6329 if (CountDw < 1 || CountDw > 4) { 6330 report_fatal_error( 6331 "ds_ordered_count: dword count must be between 1 and 4"); 6332 } 6333 } 6334 6335 if (IndexOperand) 6336 report_fatal_error("ds_ordered_count: bad index operand"); 6337 6338 if (WaveDone && !WaveRelease) 6339 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6340 6341 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6342 unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction()); 6343 unsigned Offset0 = OrderedCountIndex << 2; 6344 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6345 (Instruction << 4); 6346 6347 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6348 Offset1 |= (CountDw - 1) << 6; 6349 6350 unsigned Offset = Offset0 | (Offset1 << 8); 6351 6352 SDValue Ops[] = { 6353 Chain, 6354 Value, 6355 DAG.getTargetConstant(Offset, DL, MVT::i16), 6356 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6357 }; 6358 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6359 M->getVTList(), Ops, M->getMemoryVT(), 6360 M->getMemOperand()); 6361 } 6362 case Intrinsic::amdgcn_ds_fadd: { 6363 MemSDNode *M = cast<MemSDNode>(Op); 6364 unsigned Opc; 6365 switch (IntrID) { 6366 case Intrinsic::amdgcn_ds_fadd: 6367 Opc = ISD::ATOMIC_LOAD_FADD; 6368 break; 6369 } 6370 6371 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6372 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6373 M->getMemOperand()); 6374 } 6375 case Intrinsic::amdgcn_atomic_inc: 6376 case Intrinsic::amdgcn_atomic_dec: 6377 case Intrinsic::amdgcn_ds_fmin: 6378 case Intrinsic::amdgcn_ds_fmax: { 6379 MemSDNode *M = cast<MemSDNode>(Op); 6380 unsigned Opc; 6381 switch (IntrID) { 6382 case Intrinsic::amdgcn_atomic_inc: 6383 Opc = AMDGPUISD::ATOMIC_INC; 6384 break; 6385 case Intrinsic::amdgcn_atomic_dec: 6386 Opc = AMDGPUISD::ATOMIC_DEC; 6387 break; 6388 case Intrinsic::amdgcn_ds_fmin: 6389 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6390 break; 6391 case Intrinsic::amdgcn_ds_fmax: 6392 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6393 break; 6394 default: 6395 llvm_unreachable("Unknown intrinsic!"); 6396 } 6397 SDValue Ops[] = { 6398 M->getOperand(0), // Chain 6399 M->getOperand(2), // Ptr 6400 M->getOperand(3) // Value 6401 }; 6402 6403 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6404 M->getMemoryVT(), M->getMemOperand()); 6405 } 6406 case Intrinsic::amdgcn_buffer_load: 6407 case Intrinsic::amdgcn_buffer_load_format: { 6408 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6409 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6410 unsigned IdxEn = 1; 6411 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6412 IdxEn = Idx->getZExtValue() != 0; 6413 SDValue Ops[] = { 6414 Op.getOperand(0), // Chain 6415 Op.getOperand(2), // rsrc 6416 Op.getOperand(3), // vindex 6417 SDValue(), // voffset -- will be set by setBufferOffsets 6418 SDValue(), // soffset -- will be set by setBufferOffsets 6419 SDValue(), // offset -- will be set by setBufferOffsets 6420 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6421 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6422 }; 6423 6424 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6425 // We don't know the offset if vindex is non-zero, so clear it. 6426 if (IdxEn) 6427 Offset = 0; 6428 6429 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6430 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6431 6432 EVT VT = Op.getValueType(); 6433 EVT IntVT = VT.changeTypeToInteger(); 6434 auto *M = cast<MemSDNode>(Op); 6435 M->getMemOperand()->setOffset(Offset); 6436 EVT LoadVT = Op.getValueType(); 6437 6438 if (LoadVT.getScalarType() == MVT::f16) 6439 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6440 M, DAG, Ops); 6441 6442 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6443 if (LoadVT.getScalarType() == MVT::i8 || 6444 LoadVT.getScalarType() == MVT::i16) 6445 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6446 6447 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6448 M->getMemOperand(), DAG); 6449 } 6450 case Intrinsic::amdgcn_raw_buffer_load: 6451 case Intrinsic::amdgcn_raw_buffer_load_format: { 6452 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6453 6454 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6455 SDValue Ops[] = { 6456 Op.getOperand(0), // Chain 6457 Op.getOperand(2), // rsrc 6458 DAG.getConstant(0, DL, MVT::i32), // vindex 6459 Offsets.first, // voffset 6460 Op.getOperand(4), // soffset 6461 Offsets.second, // offset 6462 Op.getOperand(5), // cachepolicy, swizzled buffer 6463 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6464 }; 6465 6466 auto *M = cast<MemSDNode>(Op); 6467 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6468 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6469 } 6470 case Intrinsic::amdgcn_struct_buffer_load: 6471 case Intrinsic::amdgcn_struct_buffer_load_format: { 6472 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6473 6474 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6475 SDValue Ops[] = { 6476 Op.getOperand(0), // Chain 6477 Op.getOperand(2), // rsrc 6478 Op.getOperand(3), // vindex 6479 Offsets.first, // voffset 6480 Op.getOperand(5), // soffset 6481 Offsets.second, // offset 6482 Op.getOperand(6), // cachepolicy, swizzled buffer 6483 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6484 }; 6485 6486 auto *M = cast<MemSDNode>(Op); 6487 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6488 Ops[2])); 6489 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6490 } 6491 case Intrinsic::amdgcn_tbuffer_load: { 6492 MemSDNode *M = cast<MemSDNode>(Op); 6493 EVT LoadVT = Op.getValueType(); 6494 6495 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6496 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6497 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6498 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6499 unsigned IdxEn = 1; 6500 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6501 IdxEn = Idx->getZExtValue() != 0; 6502 SDValue Ops[] = { 6503 Op.getOperand(0), // Chain 6504 Op.getOperand(2), // rsrc 6505 Op.getOperand(3), // vindex 6506 Op.getOperand(4), // voffset 6507 Op.getOperand(5), // soffset 6508 Op.getOperand(6), // offset 6509 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6510 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6511 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6512 }; 6513 6514 if (LoadVT.getScalarType() == MVT::f16) 6515 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6516 M, DAG, Ops); 6517 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6518 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6519 DAG); 6520 } 6521 case Intrinsic::amdgcn_raw_tbuffer_load: { 6522 MemSDNode *M = cast<MemSDNode>(Op); 6523 EVT LoadVT = Op.getValueType(); 6524 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6525 6526 SDValue Ops[] = { 6527 Op.getOperand(0), // Chain 6528 Op.getOperand(2), // rsrc 6529 DAG.getConstant(0, DL, MVT::i32), // vindex 6530 Offsets.first, // voffset 6531 Op.getOperand(4), // soffset 6532 Offsets.second, // offset 6533 Op.getOperand(5), // format 6534 Op.getOperand(6), // cachepolicy, swizzled buffer 6535 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6536 }; 6537 6538 if (LoadVT.getScalarType() == MVT::f16) 6539 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6540 M, DAG, Ops); 6541 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6542 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6543 DAG); 6544 } 6545 case Intrinsic::amdgcn_struct_tbuffer_load: { 6546 MemSDNode *M = cast<MemSDNode>(Op); 6547 EVT LoadVT = Op.getValueType(); 6548 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6549 6550 SDValue Ops[] = { 6551 Op.getOperand(0), // Chain 6552 Op.getOperand(2), // rsrc 6553 Op.getOperand(3), // vindex 6554 Offsets.first, // voffset 6555 Op.getOperand(5), // soffset 6556 Offsets.second, // offset 6557 Op.getOperand(6), // format 6558 Op.getOperand(7), // cachepolicy, swizzled buffer 6559 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6560 }; 6561 6562 if (LoadVT.getScalarType() == MVT::f16) 6563 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6564 M, DAG, Ops); 6565 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6566 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6567 DAG); 6568 } 6569 case Intrinsic::amdgcn_buffer_atomic_swap: 6570 case Intrinsic::amdgcn_buffer_atomic_add: 6571 case Intrinsic::amdgcn_buffer_atomic_sub: 6572 case Intrinsic::amdgcn_buffer_atomic_smin: 6573 case Intrinsic::amdgcn_buffer_atomic_umin: 6574 case Intrinsic::amdgcn_buffer_atomic_smax: 6575 case Intrinsic::amdgcn_buffer_atomic_umax: 6576 case Intrinsic::amdgcn_buffer_atomic_and: 6577 case Intrinsic::amdgcn_buffer_atomic_or: 6578 case Intrinsic::amdgcn_buffer_atomic_xor: { 6579 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6580 unsigned IdxEn = 1; 6581 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6582 IdxEn = Idx->getZExtValue() != 0; 6583 SDValue Ops[] = { 6584 Op.getOperand(0), // Chain 6585 Op.getOperand(2), // vdata 6586 Op.getOperand(3), // rsrc 6587 Op.getOperand(4), // vindex 6588 SDValue(), // voffset -- will be set by setBufferOffsets 6589 SDValue(), // soffset -- will be set by setBufferOffsets 6590 SDValue(), // offset -- will be set by setBufferOffsets 6591 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6592 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6593 }; 6594 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6595 // We don't know the offset if vindex is non-zero, so clear it. 6596 if (IdxEn) 6597 Offset = 0; 6598 EVT VT = Op.getValueType(); 6599 6600 auto *M = cast<MemSDNode>(Op); 6601 M->getMemOperand()->setOffset(Offset); 6602 unsigned Opcode = 0; 6603 6604 switch (IntrID) { 6605 case Intrinsic::amdgcn_buffer_atomic_swap: 6606 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6607 break; 6608 case Intrinsic::amdgcn_buffer_atomic_add: 6609 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6610 break; 6611 case Intrinsic::amdgcn_buffer_atomic_sub: 6612 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6613 break; 6614 case Intrinsic::amdgcn_buffer_atomic_smin: 6615 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6616 break; 6617 case Intrinsic::amdgcn_buffer_atomic_umin: 6618 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6619 break; 6620 case Intrinsic::amdgcn_buffer_atomic_smax: 6621 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6622 break; 6623 case Intrinsic::amdgcn_buffer_atomic_umax: 6624 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6625 break; 6626 case Intrinsic::amdgcn_buffer_atomic_and: 6627 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6628 break; 6629 case Intrinsic::amdgcn_buffer_atomic_or: 6630 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6631 break; 6632 case Intrinsic::amdgcn_buffer_atomic_xor: 6633 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6634 break; 6635 default: 6636 llvm_unreachable("unhandled atomic opcode"); 6637 } 6638 6639 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6640 M->getMemOperand()); 6641 } 6642 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6643 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6644 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6645 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6646 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6647 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6648 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6649 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6650 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6651 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6652 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6653 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 6654 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6655 SDValue Ops[] = { 6656 Op.getOperand(0), // Chain 6657 Op.getOperand(2), // vdata 6658 Op.getOperand(3), // rsrc 6659 DAG.getConstant(0, DL, MVT::i32), // vindex 6660 Offsets.first, // voffset 6661 Op.getOperand(5), // soffset 6662 Offsets.second, // offset 6663 Op.getOperand(6), // cachepolicy 6664 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6665 }; 6666 EVT VT = Op.getValueType(); 6667 6668 auto *M = cast<MemSDNode>(Op); 6669 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6670 unsigned Opcode = 0; 6671 6672 switch (IntrID) { 6673 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6674 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6675 break; 6676 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6677 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6678 break; 6679 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6680 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6681 break; 6682 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6683 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6684 break; 6685 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6686 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6687 break; 6688 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6689 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6690 break; 6691 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6692 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6693 break; 6694 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6695 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6696 break; 6697 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6698 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6699 break; 6700 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6701 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6702 break; 6703 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6704 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6705 break; 6706 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 6707 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6708 break; 6709 default: 6710 llvm_unreachable("unhandled atomic opcode"); 6711 } 6712 6713 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6714 M->getMemOperand()); 6715 } 6716 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6717 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6718 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6719 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6720 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6721 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6722 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6723 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6724 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6725 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6726 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6727 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 6728 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6729 SDValue Ops[] = { 6730 Op.getOperand(0), // Chain 6731 Op.getOperand(2), // vdata 6732 Op.getOperand(3), // rsrc 6733 Op.getOperand(4), // vindex 6734 Offsets.first, // voffset 6735 Op.getOperand(6), // soffset 6736 Offsets.second, // offset 6737 Op.getOperand(7), // cachepolicy 6738 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6739 }; 6740 EVT VT = Op.getValueType(); 6741 6742 auto *M = cast<MemSDNode>(Op); 6743 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6744 Ops[3])); 6745 unsigned Opcode = 0; 6746 6747 switch (IntrID) { 6748 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6749 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6750 break; 6751 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6752 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6753 break; 6754 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6755 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6756 break; 6757 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6758 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6759 break; 6760 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6761 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6762 break; 6763 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6764 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6765 break; 6766 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6767 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6768 break; 6769 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6770 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6771 break; 6772 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6773 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6774 break; 6775 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6776 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6777 break; 6778 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6779 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6780 break; 6781 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 6782 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6783 break; 6784 default: 6785 llvm_unreachable("unhandled atomic opcode"); 6786 } 6787 6788 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6789 M->getMemOperand()); 6790 } 6791 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 6792 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6793 unsigned IdxEn = 1; 6794 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 6795 IdxEn = Idx->getZExtValue() != 0; 6796 SDValue Ops[] = { 6797 Op.getOperand(0), // Chain 6798 Op.getOperand(2), // src 6799 Op.getOperand(3), // cmp 6800 Op.getOperand(4), // rsrc 6801 Op.getOperand(5), // vindex 6802 SDValue(), // voffset -- will be set by setBufferOffsets 6803 SDValue(), // soffset -- will be set by setBufferOffsets 6804 SDValue(), // offset -- will be set by setBufferOffsets 6805 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6806 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6807 }; 6808 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 6809 // We don't know the offset if vindex is non-zero, so clear it. 6810 if (IdxEn) 6811 Offset = 0; 6812 EVT VT = Op.getValueType(); 6813 auto *M = cast<MemSDNode>(Op); 6814 M->getMemOperand()->setOffset(Offset); 6815 6816 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6817 Op->getVTList(), Ops, VT, M->getMemOperand()); 6818 } 6819 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 6820 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6821 SDValue Ops[] = { 6822 Op.getOperand(0), // Chain 6823 Op.getOperand(2), // src 6824 Op.getOperand(3), // cmp 6825 Op.getOperand(4), // rsrc 6826 DAG.getConstant(0, DL, MVT::i32), // vindex 6827 Offsets.first, // voffset 6828 Op.getOperand(6), // soffset 6829 Offsets.second, // offset 6830 Op.getOperand(7), // cachepolicy 6831 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6832 }; 6833 EVT VT = Op.getValueType(); 6834 auto *M = cast<MemSDNode>(Op); 6835 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 6836 6837 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6838 Op->getVTList(), Ops, VT, M->getMemOperand()); 6839 } 6840 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 6841 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 6842 SDValue Ops[] = { 6843 Op.getOperand(0), // Chain 6844 Op.getOperand(2), // src 6845 Op.getOperand(3), // cmp 6846 Op.getOperand(4), // rsrc 6847 Op.getOperand(5), // vindex 6848 Offsets.first, // voffset 6849 Op.getOperand(7), // soffset 6850 Offsets.second, // offset 6851 Op.getOperand(8), // cachepolicy 6852 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6853 }; 6854 EVT VT = Op.getValueType(); 6855 auto *M = cast<MemSDNode>(Op); 6856 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 6857 Ops[4])); 6858 6859 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6860 Op->getVTList(), Ops, VT, M->getMemOperand()); 6861 } 6862 6863 default: 6864 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6865 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 6866 return lowerImage(Op, ImageDimIntr, DAG); 6867 6868 return SDValue(); 6869 } 6870 } 6871 6872 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 6873 // dwordx4 if on SI. 6874 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 6875 SDVTList VTList, 6876 ArrayRef<SDValue> Ops, EVT MemVT, 6877 MachineMemOperand *MMO, 6878 SelectionDAG &DAG) const { 6879 EVT VT = VTList.VTs[0]; 6880 EVT WidenedVT = VT; 6881 EVT WidenedMemVT = MemVT; 6882 if (!Subtarget->hasDwordx3LoadStores() && 6883 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 6884 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 6885 WidenedVT.getVectorElementType(), 4); 6886 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 6887 WidenedMemVT.getVectorElementType(), 4); 6888 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 6889 } 6890 6891 assert(VTList.NumVTs == 2); 6892 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 6893 6894 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 6895 WidenedMemVT, MMO); 6896 if (WidenedVT != VT) { 6897 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 6898 DAG.getVectorIdxConstant(0, DL)); 6899 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 6900 } 6901 return NewOp; 6902 } 6903 6904 SDValue SITargetLowering::handleD16VData(SDValue VData, 6905 SelectionDAG &DAG) const { 6906 EVT StoreVT = VData.getValueType(); 6907 6908 // No change for f16 and legal vector D16 types. 6909 if (!StoreVT.isVector()) 6910 return VData; 6911 6912 SDLoc DL(VData); 6913 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 6914 6915 if (Subtarget->hasUnpackedD16VMem()) { 6916 // We need to unpack the packed data to store. 6917 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 6918 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 6919 6920 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 6921 StoreVT.getVectorNumElements()); 6922 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 6923 return DAG.UnrollVectorOp(ZExt.getNode()); 6924 } 6925 6926 assert(isTypeLegal(StoreVT)); 6927 return VData; 6928 } 6929 6930 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 6931 SelectionDAG &DAG) const { 6932 SDLoc DL(Op); 6933 SDValue Chain = Op.getOperand(0); 6934 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6935 MachineFunction &MF = DAG.getMachineFunction(); 6936 6937 switch (IntrinsicID) { 6938 case Intrinsic::amdgcn_exp_compr: { 6939 SDValue Src0 = Op.getOperand(4); 6940 SDValue Src1 = Op.getOperand(5); 6941 // Hack around illegal type on SI by directly selecting it. 6942 if (isTypeLegal(Src0.getValueType())) 6943 return SDValue(); 6944 6945 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 6946 SDValue Undef = DAG.getUNDEF(MVT::f32); 6947 const SDValue Ops[] = { 6948 Op.getOperand(2), // tgt 6949 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 6950 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 6951 Undef, // src2 6952 Undef, // src3 6953 Op.getOperand(7), // vm 6954 DAG.getTargetConstant(1, DL, MVT::i1), // compr 6955 Op.getOperand(3), // en 6956 Op.getOperand(0) // Chain 6957 }; 6958 6959 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 6960 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 6961 } 6962 case Intrinsic::amdgcn_s_barrier: { 6963 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 6964 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 6965 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 6966 if (WGSize <= ST.getWavefrontSize()) 6967 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 6968 Op.getOperand(0)), 0); 6969 } 6970 return SDValue(); 6971 }; 6972 case Intrinsic::amdgcn_tbuffer_store: { 6973 SDValue VData = Op.getOperand(2); 6974 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6975 if (IsD16) 6976 VData = handleD16VData(VData, DAG); 6977 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6978 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6979 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6980 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 6981 unsigned IdxEn = 1; 6982 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6983 IdxEn = Idx->getZExtValue() != 0; 6984 SDValue Ops[] = { 6985 Chain, 6986 VData, // vdata 6987 Op.getOperand(3), // rsrc 6988 Op.getOperand(4), // vindex 6989 Op.getOperand(5), // voffset 6990 Op.getOperand(6), // soffset 6991 Op.getOperand(7), // offset 6992 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6993 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6994 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 6995 }; 6996 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6997 AMDGPUISD::TBUFFER_STORE_FORMAT; 6998 MemSDNode *M = cast<MemSDNode>(Op); 6999 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7000 M->getMemoryVT(), M->getMemOperand()); 7001 } 7002 7003 case Intrinsic::amdgcn_struct_tbuffer_store: { 7004 SDValue VData = Op.getOperand(2); 7005 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7006 if (IsD16) 7007 VData = handleD16VData(VData, DAG); 7008 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7009 SDValue Ops[] = { 7010 Chain, 7011 VData, // vdata 7012 Op.getOperand(3), // rsrc 7013 Op.getOperand(4), // vindex 7014 Offsets.first, // voffset 7015 Op.getOperand(6), // soffset 7016 Offsets.second, // offset 7017 Op.getOperand(7), // format 7018 Op.getOperand(8), // cachepolicy, swizzled buffer 7019 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7020 }; 7021 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7022 AMDGPUISD::TBUFFER_STORE_FORMAT; 7023 MemSDNode *M = cast<MemSDNode>(Op); 7024 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7025 M->getMemoryVT(), M->getMemOperand()); 7026 } 7027 7028 case Intrinsic::amdgcn_raw_tbuffer_store: { 7029 SDValue VData = Op.getOperand(2); 7030 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7031 if (IsD16) 7032 VData = handleD16VData(VData, DAG); 7033 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7034 SDValue Ops[] = { 7035 Chain, 7036 VData, // vdata 7037 Op.getOperand(3), // rsrc 7038 DAG.getConstant(0, DL, MVT::i32), // vindex 7039 Offsets.first, // voffset 7040 Op.getOperand(5), // soffset 7041 Offsets.second, // offset 7042 Op.getOperand(6), // format 7043 Op.getOperand(7), // cachepolicy, swizzled buffer 7044 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7045 }; 7046 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7047 AMDGPUISD::TBUFFER_STORE_FORMAT; 7048 MemSDNode *M = cast<MemSDNode>(Op); 7049 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7050 M->getMemoryVT(), M->getMemOperand()); 7051 } 7052 7053 case Intrinsic::amdgcn_buffer_store: 7054 case Intrinsic::amdgcn_buffer_store_format: { 7055 SDValue VData = Op.getOperand(2); 7056 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7057 if (IsD16) 7058 VData = handleD16VData(VData, DAG); 7059 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7060 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7061 unsigned IdxEn = 1; 7062 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7063 IdxEn = Idx->getZExtValue() != 0; 7064 SDValue Ops[] = { 7065 Chain, 7066 VData, 7067 Op.getOperand(3), // rsrc 7068 Op.getOperand(4), // vindex 7069 SDValue(), // voffset -- will be set by setBufferOffsets 7070 SDValue(), // soffset -- will be set by setBufferOffsets 7071 SDValue(), // offset -- will be set by setBufferOffsets 7072 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7073 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7074 }; 7075 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7076 // We don't know the offset if vindex is non-zero, so clear it. 7077 if (IdxEn) 7078 Offset = 0; 7079 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7080 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7081 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7082 MemSDNode *M = cast<MemSDNode>(Op); 7083 M->getMemOperand()->setOffset(Offset); 7084 7085 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7086 EVT VDataType = VData.getValueType().getScalarType(); 7087 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7088 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7089 7090 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7091 M->getMemoryVT(), M->getMemOperand()); 7092 } 7093 7094 case Intrinsic::amdgcn_raw_buffer_store: 7095 case Intrinsic::amdgcn_raw_buffer_store_format: { 7096 const bool IsFormat = 7097 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7098 7099 SDValue VData = Op.getOperand(2); 7100 EVT VDataVT = VData.getValueType(); 7101 EVT EltType = VDataVT.getScalarType(); 7102 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7103 if (IsD16) 7104 VData = handleD16VData(VData, DAG); 7105 7106 if (!isTypeLegal(VDataVT)) { 7107 VData = 7108 DAG.getNode(ISD::BITCAST, DL, 7109 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7110 } 7111 7112 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7113 SDValue Ops[] = { 7114 Chain, 7115 VData, 7116 Op.getOperand(3), // rsrc 7117 DAG.getConstant(0, DL, MVT::i32), // vindex 7118 Offsets.first, // voffset 7119 Op.getOperand(5), // soffset 7120 Offsets.second, // offset 7121 Op.getOperand(6), // cachepolicy, swizzled buffer 7122 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7123 }; 7124 unsigned Opc = 7125 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7126 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7127 MemSDNode *M = cast<MemSDNode>(Op); 7128 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7129 7130 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7131 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7132 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7133 7134 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7135 M->getMemoryVT(), M->getMemOperand()); 7136 } 7137 7138 case Intrinsic::amdgcn_struct_buffer_store: 7139 case Intrinsic::amdgcn_struct_buffer_store_format: { 7140 const bool IsFormat = 7141 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7142 7143 SDValue VData = Op.getOperand(2); 7144 EVT VDataVT = VData.getValueType(); 7145 EVT EltType = VDataVT.getScalarType(); 7146 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7147 7148 if (IsD16) 7149 VData = handleD16VData(VData, DAG); 7150 7151 if (!isTypeLegal(VDataVT)) { 7152 VData = 7153 DAG.getNode(ISD::BITCAST, DL, 7154 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7155 } 7156 7157 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7158 SDValue Ops[] = { 7159 Chain, 7160 VData, 7161 Op.getOperand(3), // rsrc 7162 Op.getOperand(4), // vindex 7163 Offsets.first, // voffset 7164 Op.getOperand(6), // soffset 7165 Offsets.second, // offset 7166 Op.getOperand(7), // cachepolicy, swizzled buffer 7167 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7168 }; 7169 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7170 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7171 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7172 MemSDNode *M = cast<MemSDNode>(Op); 7173 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7174 Ops[3])); 7175 7176 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7177 EVT VDataType = VData.getValueType().getScalarType(); 7178 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7179 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7180 7181 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7182 M->getMemoryVT(), M->getMemOperand()); 7183 } 7184 7185 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7186 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7187 unsigned IdxEn = 1; 7188 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7189 IdxEn = Idx->getZExtValue() != 0; 7190 SDValue Ops[] = { 7191 Chain, 7192 Op.getOperand(2), // vdata 7193 Op.getOperand(3), // rsrc 7194 Op.getOperand(4), // vindex 7195 SDValue(), // voffset -- will be set by setBufferOffsets 7196 SDValue(), // soffset -- will be set by setBufferOffsets 7197 SDValue(), // offset -- will be set by setBufferOffsets 7198 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7199 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7200 }; 7201 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7202 // We don't know the offset if vindex is non-zero, so clear it. 7203 if (IdxEn) 7204 Offset = 0; 7205 EVT VT = Op.getOperand(2).getValueType(); 7206 7207 auto *M = cast<MemSDNode>(Op); 7208 M->getMemOperand()->setOffset(Offset); 7209 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 7210 : AMDGPUISD::BUFFER_ATOMIC_FADD; 7211 7212 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7213 M->getMemOperand()); 7214 } 7215 7216 case Intrinsic::amdgcn_global_atomic_fadd: { 7217 SDValue Ops[] = { 7218 Chain, 7219 Op.getOperand(2), // ptr 7220 Op.getOperand(3) // vdata 7221 }; 7222 EVT VT = Op.getOperand(3).getValueType(); 7223 7224 auto *M = cast<MemSDNode>(Op); 7225 if (VT.isVector()) { 7226 return DAG.getMemIntrinsicNode( 7227 AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT, 7228 M->getMemOperand()); 7229 } 7230 7231 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7232 DAG.getVTList(VT, MVT::Other), Ops, 7233 M->getMemOperand()).getValue(1); 7234 } 7235 case Intrinsic::amdgcn_end_cf: 7236 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7237 Op->getOperand(2), Chain), 0); 7238 7239 default: { 7240 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7241 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7242 return lowerImage(Op, ImageDimIntr, DAG); 7243 7244 return Op; 7245 } 7246 } 7247 } 7248 7249 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7250 // offset (the offset that is included in bounds checking and swizzling, to be 7251 // split between the instruction's voffset and immoffset fields) and soffset 7252 // (the offset that is excluded from bounds checking and swizzling, to go in 7253 // the instruction's soffset field). This function takes the first kind of 7254 // offset and figures out how to split it between voffset and immoffset. 7255 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7256 SDValue Offset, SelectionDAG &DAG) const { 7257 SDLoc DL(Offset); 7258 const unsigned MaxImm = 4095; 7259 SDValue N0 = Offset; 7260 ConstantSDNode *C1 = nullptr; 7261 7262 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7263 N0 = SDValue(); 7264 else if (DAG.isBaseWithConstantOffset(N0)) { 7265 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7266 N0 = N0.getOperand(0); 7267 } 7268 7269 if (C1) { 7270 unsigned ImmOffset = C1->getZExtValue(); 7271 // If the immediate value is too big for the immoffset field, put the value 7272 // and -4096 into the immoffset field so that the value that is copied/added 7273 // for the voffset field is a multiple of 4096, and it stands more chance 7274 // of being CSEd with the copy/add for another similar load/store. 7275 // However, do not do that rounding down to a multiple of 4096 if that is a 7276 // negative number, as it appears to be illegal to have a negative offset 7277 // in the vgpr, even if adding the immediate offset makes it positive. 7278 unsigned Overflow = ImmOffset & ~MaxImm; 7279 ImmOffset -= Overflow; 7280 if ((int32_t)Overflow < 0) { 7281 Overflow += ImmOffset; 7282 ImmOffset = 0; 7283 } 7284 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7285 if (Overflow) { 7286 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7287 if (!N0) 7288 N0 = OverflowVal; 7289 else { 7290 SDValue Ops[] = { N0, OverflowVal }; 7291 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7292 } 7293 } 7294 } 7295 if (!N0) 7296 N0 = DAG.getConstant(0, DL, MVT::i32); 7297 if (!C1) 7298 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7299 return {N0, SDValue(C1, 0)}; 7300 } 7301 7302 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7303 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7304 // pointed to by Offsets. 7305 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7306 SelectionDAG &DAG, SDValue *Offsets, 7307 unsigned Align) const { 7308 SDLoc DL(CombinedOffset); 7309 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7310 uint32_t Imm = C->getZExtValue(); 7311 uint32_t SOffset, ImmOffset; 7312 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 7313 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7314 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7315 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7316 return SOffset + ImmOffset; 7317 } 7318 } 7319 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7320 SDValue N0 = CombinedOffset.getOperand(0); 7321 SDValue N1 = CombinedOffset.getOperand(1); 7322 uint32_t SOffset, ImmOffset; 7323 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7324 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7325 Subtarget, Align)) { 7326 Offsets[0] = N0; 7327 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7328 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7329 return 0; 7330 } 7331 } 7332 Offsets[0] = CombinedOffset; 7333 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7334 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7335 return 0; 7336 } 7337 7338 // Handle 8 bit and 16 bit buffer loads 7339 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7340 EVT LoadVT, SDLoc DL, 7341 ArrayRef<SDValue> Ops, 7342 MemSDNode *M) const { 7343 EVT IntVT = LoadVT.changeTypeToInteger(); 7344 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7345 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7346 7347 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7348 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7349 Ops, IntVT, 7350 M->getMemOperand()); 7351 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7352 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7353 7354 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7355 } 7356 7357 // Handle 8 bit and 16 bit buffer stores 7358 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7359 EVT VDataType, SDLoc DL, 7360 SDValue Ops[], 7361 MemSDNode *M) const { 7362 if (VDataType == MVT::f16) 7363 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7364 7365 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7366 Ops[1] = BufferStoreExt; 7367 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7368 AMDGPUISD::BUFFER_STORE_SHORT; 7369 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7370 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7371 M->getMemOperand()); 7372 } 7373 7374 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7375 ISD::LoadExtType ExtType, SDValue Op, 7376 const SDLoc &SL, EVT VT) { 7377 if (VT.bitsLT(Op.getValueType())) 7378 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7379 7380 switch (ExtType) { 7381 case ISD::SEXTLOAD: 7382 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7383 case ISD::ZEXTLOAD: 7384 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7385 case ISD::EXTLOAD: 7386 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7387 case ISD::NON_EXTLOAD: 7388 return Op; 7389 } 7390 7391 llvm_unreachable("invalid ext type"); 7392 } 7393 7394 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7395 SelectionDAG &DAG = DCI.DAG; 7396 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7397 return SDValue(); 7398 7399 // FIXME: Constant loads should all be marked invariant. 7400 unsigned AS = Ld->getAddressSpace(); 7401 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7402 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7403 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7404 return SDValue(); 7405 7406 // Don't do this early, since it may interfere with adjacent load merging for 7407 // illegal types. We can avoid losing alignment information for exotic types 7408 // pre-legalize. 7409 EVT MemVT = Ld->getMemoryVT(); 7410 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7411 MemVT.getSizeInBits() >= 32) 7412 return SDValue(); 7413 7414 SDLoc SL(Ld); 7415 7416 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7417 "unexpected vector extload"); 7418 7419 // TODO: Drop only high part of range. 7420 SDValue Ptr = Ld->getBasePtr(); 7421 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7422 MVT::i32, SL, Ld->getChain(), Ptr, 7423 Ld->getOffset(), 7424 Ld->getPointerInfo(), MVT::i32, 7425 Ld->getAlignment(), 7426 Ld->getMemOperand()->getFlags(), 7427 Ld->getAAInfo(), 7428 nullptr); // Drop ranges 7429 7430 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7431 if (MemVT.isFloatingPoint()) { 7432 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7433 "unexpected fp extload"); 7434 TruncVT = MemVT.changeTypeToInteger(); 7435 } 7436 7437 SDValue Cvt = NewLoad; 7438 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7439 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7440 DAG.getValueType(TruncVT)); 7441 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7442 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7443 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7444 } else { 7445 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7446 } 7447 7448 EVT VT = Ld->getValueType(0); 7449 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7450 7451 DCI.AddToWorklist(Cvt.getNode()); 7452 7453 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7454 // the appropriate extension from the 32-bit load. 7455 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7456 DCI.AddToWorklist(Cvt.getNode()); 7457 7458 // Handle conversion back to floating point if necessary. 7459 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7460 7461 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7462 } 7463 7464 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7465 SDLoc DL(Op); 7466 LoadSDNode *Load = cast<LoadSDNode>(Op); 7467 ISD::LoadExtType ExtType = Load->getExtensionType(); 7468 EVT MemVT = Load->getMemoryVT(); 7469 7470 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7471 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7472 return SDValue(); 7473 7474 // FIXME: Copied from PPC 7475 // First, load into 32 bits, then truncate to 1 bit. 7476 7477 SDValue Chain = Load->getChain(); 7478 SDValue BasePtr = Load->getBasePtr(); 7479 MachineMemOperand *MMO = Load->getMemOperand(); 7480 7481 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7482 7483 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7484 BasePtr, RealMemVT, MMO); 7485 7486 if (!MemVT.isVector()) { 7487 SDValue Ops[] = { 7488 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7489 NewLD.getValue(1) 7490 }; 7491 7492 return DAG.getMergeValues(Ops, DL); 7493 } 7494 7495 SmallVector<SDValue, 3> Elts; 7496 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7497 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7498 DAG.getConstant(I, DL, MVT::i32)); 7499 7500 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7501 } 7502 7503 SDValue Ops[] = { 7504 DAG.getBuildVector(MemVT, DL, Elts), 7505 NewLD.getValue(1) 7506 }; 7507 7508 return DAG.getMergeValues(Ops, DL); 7509 } 7510 7511 if (!MemVT.isVector()) 7512 return SDValue(); 7513 7514 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7515 "Custom lowering for non-i32 vectors hasn't been implemented."); 7516 7517 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7518 MemVT, *Load->getMemOperand())) { 7519 SDValue Ops[2]; 7520 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7521 return DAG.getMergeValues(Ops, DL); 7522 } 7523 7524 unsigned Alignment = Load->getAlignment(); 7525 unsigned AS = Load->getAddressSpace(); 7526 if (Subtarget->hasLDSMisalignedBug() && 7527 AS == AMDGPUAS::FLAT_ADDRESS && 7528 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7529 return SplitVectorLoad(Op, DAG); 7530 } 7531 7532 MachineFunction &MF = DAG.getMachineFunction(); 7533 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7534 // If there is a possibilty that flat instruction access scratch memory 7535 // then we need to use the same legalization rules we use for private. 7536 if (AS == AMDGPUAS::FLAT_ADDRESS && 7537 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7538 AS = MFI->hasFlatScratchInit() ? 7539 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7540 7541 unsigned NumElements = MemVT.getVectorNumElements(); 7542 7543 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7544 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7545 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7546 if (MemVT.isPow2VectorType()) 7547 return SDValue(); 7548 if (NumElements == 3) 7549 return WidenVectorLoad(Op, DAG); 7550 return SplitVectorLoad(Op, DAG); 7551 } 7552 // Non-uniform loads will be selected to MUBUF instructions, so they 7553 // have the same legalization requirements as global and private 7554 // loads. 7555 // 7556 } 7557 7558 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7559 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7560 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7561 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7562 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 7563 Alignment >= 4 && NumElements < 32) { 7564 if (MemVT.isPow2VectorType()) 7565 return SDValue(); 7566 if (NumElements == 3) 7567 return WidenVectorLoad(Op, DAG); 7568 return SplitVectorLoad(Op, DAG); 7569 } 7570 // Non-uniform loads will be selected to MUBUF instructions, so they 7571 // have the same legalization requirements as global and private 7572 // loads. 7573 // 7574 } 7575 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7576 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7577 AS == AMDGPUAS::GLOBAL_ADDRESS || 7578 AS == AMDGPUAS::FLAT_ADDRESS) { 7579 if (NumElements > 4) 7580 return SplitVectorLoad(Op, DAG); 7581 // v3 loads not supported on SI. 7582 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7583 return WidenVectorLoad(Op, DAG); 7584 // v3 and v4 loads are supported for private and global memory. 7585 return SDValue(); 7586 } 7587 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7588 // Depending on the setting of the private_element_size field in the 7589 // resource descriptor, we can only make private accesses up to a certain 7590 // size. 7591 switch (Subtarget->getMaxPrivateElementSize()) { 7592 case 4: { 7593 SDValue Ops[2]; 7594 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7595 return DAG.getMergeValues(Ops, DL); 7596 } 7597 case 8: 7598 if (NumElements > 2) 7599 return SplitVectorLoad(Op, DAG); 7600 return SDValue(); 7601 case 16: 7602 // Same as global/flat 7603 if (NumElements > 4) 7604 return SplitVectorLoad(Op, DAG); 7605 // v3 loads not supported on SI. 7606 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7607 return WidenVectorLoad(Op, DAG); 7608 return SDValue(); 7609 default: 7610 llvm_unreachable("unsupported private_element_size"); 7611 } 7612 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7613 // Use ds_read_b128 if possible. 7614 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7615 MemVT.getStoreSize() == 16) 7616 return SDValue(); 7617 7618 if (NumElements > 2) 7619 return SplitVectorLoad(Op, DAG); 7620 7621 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7622 // address is negative, then the instruction is incorrectly treated as 7623 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7624 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7625 // load later in the SILoadStoreOptimizer. 7626 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7627 NumElements == 2 && MemVT.getStoreSize() == 8 && 7628 Load->getAlignment() < 8) { 7629 return SplitVectorLoad(Op, DAG); 7630 } 7631 } 7632 return SDValue(); 7633 } 7634 7635 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7636 EVT VT = Op.getValueType(); 7637 assert(VT.getSizeInBits() == 64); 7638 7639 SDLoc DL(Op); 7640 SDValue Cond = Op.getOperand(0); 7641 7642 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7643 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7644 7645 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7646 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7647 7648 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7649 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7650 7651 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7652 7653 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7654 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7655 7656 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7657 7658 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7659 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7660 } 7661 7662 // Catch division cases where we can use shortcuts with rcp and rsq 7663 // instructions. 7664 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7665 SelectionDAG &DAG) const { 7666 SDLoc SL(Op); 7667 SDValue LHS = Op.getOperand(0); 7668 SDValue RHS = Op.getOperand(1); 7669 EVT VT = Op.getValueType(); 7670 const SDNodeFlags Flags = Op->getFlags(); 7671 7672 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 7673 Flags.hasApproximateFuncs(); 7674 7675 // Without !fpmath accuracy information, we can't do more because we don't 7676 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 7677 if (!AllowInaccurateRcp) 7678 return SDValue(); 7679 7680 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7681 if (CLHS->isExactlyValue(1.0)) { 7682 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7683 // the CI documentation has a worst case error of 1 ulp. 7684 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7685 // use it as long as we aren't trying to use denormals. 7686 // 7687 // v_rcp_f16 and v_rsq_f16 DO support denormals. 7688 7689 // 1.0 / sqrt(x) -> rsq(x) 7690 7691 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 7692 // error seems really high at 2^29 ULP. 7693 if (RHS.getOpcode() == ISD::FSQRT) 7694 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 7695 7696 // 1.0 / x -> rcp(x) 7697 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7698 } 7699 7700 // Same as for 1.0, but expand the sign out of the constant. 7701 if (CLHS->isExactlyValue(-1.0)) { 7702 // -1.0 / x -> rcp (fneg x) 7703 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7704 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 7705 } 7706 } 7707 7708 // Turn into multiply by the reciprocal. 7709 // x / y -> x * (1.0 / y) 7710 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7711 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 7712 } 7713 7714 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7715 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 7716 if (GlueChain->getNumValues() <= 1) { 7717 return DAG.getNode(Opcode, SL, VT, A, B); 7718 } 7719 7720 assert(GlueChain->getNumValues() == 3); 7721 7722 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7723 switch (Opcode) { 7724 default: llvm_unreachable("no chain equivalent for opcode"); 7725 case ISD::FMUL: 7726 Opcode = AMDGPUISD::FMUL_W_CHAIN; 7727 break; 7728 } 7729 7730 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 7731 GlueChain.getValue(2)); 7732 } 7733 7734 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7735 EVT VT, SDValue A, SDValue B, SDValue C, 7736 SDValue GlueChain) { 7737 if (GlueChain->getNumValues() <= 1) { 7738 return DAG.getNode(Opcode, SL, VT, A, B, C); 7739 } 7740 7741 assert(GlueChain->getNumValues() == 3); 7742 7743 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7744 switch (Opcode) { 7745 default: llvm_unreachable("no chain equivalent for opcode"); 7746 case ISD::FMA: 7747 Opcode = AMDGPUISD::FMA_W_CHAIN; 7748 break; 7749 } 7750 7751 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 7752 GlueChain.getValue(2)); 7753 } 7754 7755 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 7756 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7757 return FastLowered; 7758 7759 SDLoc SL(Op); 7760 SDValue Src0 = Op.getOperand(0); 7761 SDValue Src1 = Op.getOperand(1); 7762 7763 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 7764 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 7765 7766 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 7767 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 7768 7769 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 7770 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 7771 7772 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 7773 } 7774 7775 // Faster 2.5 ULP division that does not support denormals. 7776 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 7777 SDLoc SL(Op); 7778 SDValue LHS = Op.getOperand(1); 7779 SDValue RHS = Op.getOperand(2); 7780 7781 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 7782 7783 const APFloat K0Val(BitsToFloat(0x6f800000)); 7784 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 7785 7786 const APFloat K1Val(BitsToFloat(0x2f800000)); 7787 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 7788 7789 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7790 7791 EVT SetCCVT = 7792 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 7793 7794 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 7795 7796 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 7797 7798 // TODO: Should this propagate fast-math-flags? 7799 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 7800 7801 // rcp does not support denormals. 7802 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 7803 7804 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 7805 7806 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 7807 } 7808 7809 // Returns immediate value for setting the F32 denorm mode when using the 7810 // S_DENORM_MODE instruction. 7811 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 7812 const SDLoc &SL, const GCNSubtarget *ST) { 7813 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 7814 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 7815 ? FP_DENORM_FLUSH_NONE 7816 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 7817 7818 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 7819 return DAG.getTargetConstant(Mode, SL, MVT::i32); 7820 } 7821 7822 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 7823 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7824 return FastLowered; 7825 7826 SDLoc SL(Op); 7827 SDValue LHS = Op.getOperand(0); 7828 SDValue RHS = Op.getOperand(1); 7829 7830 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7831 7832 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 7833 7834 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7835 RHS, RHS, LHS); 7836 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7837 LHS, RHS, LHS); 7838 7839 // Denominator is scaled to not be denormal, so using rcp is ok. 7840 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 7841 DenominatorScaled); 7842 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 7843 DenominatorScaled); 7844 7845 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 7846 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 7847 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 7848 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 7849 7850 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 7851 7852 if (!HasFP32Denormals) { 7853 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 7854 7855 SDValue EnableDenorm; 7856 if (Subtarget->hasDenormModeInst()) { 7857 const SDValue EnableDenormValue = 7858 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 7859 7860 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 7861 DAG.getEntryNode(), EnableDenormValue); 7862 } else { 7863 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 7864 SL, MVT::i32); 7865 EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 7866 DAG.getEntryNode(), EnableDenormValue, 7867 BitField); 7868 } 7869 7870 SDValue Ops[3] = { 7871 NegDivScale0, 7872 EnableDenorm.getValue(0), 7873 EnableDenorm.getValue(1) 7874 }; 7875 7876 NegDivScale0 = DAG.getMergeValues(Ops, SL); 7877 } 7878 7879 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 7880 ApproxRcp, One, NegDivScale0); 7881 7882 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 7883 ApproxRcp, Fma0); 7884 7885 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 7886 Fma1, Fma1); 7887 7888 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 7889 NumeratorScaled, Mul); 7890 7891 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 7892 7893 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 7894 NumeratorScaled, Fma3); 7895 7896 if (!HasFP32Denormals) { 7897 SDValue DisableDenorm; 7898 if (Subtarget->hasDenormModeInst()) { 7899 const SDValue DisableDenormValue = 7900 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 7901 7902 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 7903 Fma4.getValue(1), DisableDenormValue, 7904 Fma4.getValue(2)); 7905 } else { 7906 const SDValue DisableDenormValue = 7907 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 7908 7909 DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 7910 Fma4.getValue(1), DisableDenormValue, 7911 BitField, Fma4.getValue(2)); 7912 } 7913 7914 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 7915 DisableDenorm, DAG.getRoot()); 7916 DAG.setRoot(OutputChain); 7917 } 7918 7919 SDValue Scale = NumeratorScaled.getValue(1); 7920 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 7921 Fma4, Fma1, Fma3, Scale); 7922 7923 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 7924 } 7925 7926 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 7927 if (DAG.getTarget().Options.UnsafeFPMath) 7928 return lowerFastUnsafeFDIV(Op, DAG); 7929 7930 SDLoc SL(Op); 7931 SDValue X = Op.getOperand(0); 7932 SDValue Y = Op.getOperand(1); 7933 7934 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 7935 7936 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 7937 7938 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 7939 7940 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 7941 7942 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 7943 7944 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 7945 7946 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 7947 7948 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 7949 7950 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 7951 7952 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 7953 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 7954 7955 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 7956 NegDivScale0, Mul, DivScale1); 7957 7958 SDValue Scale; 7959 7960 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 7961 // Workaround a hardware bug on SI where the condition output from div_scale 7962 // is not usable. 7963 7964 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 7965 7966 // Figure out if the scale to use for div_fmas. 7967 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 7968 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 7969 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 7970 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 7971 7972 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 7973 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 7974 7975 SDValue Scale0Hi 7976 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 7977 SDValue Scale1Hi 7978 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 7979 7980 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 7981 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 7982 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 7983 } else { 7984 Scale = DivScale1.getValue(1); 7985 } 7986 7987 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 7988 Fma4, Fma3, Mul, Scale); 7989 7990 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 7991 } 7992 7993 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 7994 EVT VT = Op.getValueType(); 7995 7996 if (VT == MVT::f32) 7997 return LowerFDIV32(Op, DAG); 7998 7999 if (VT == MVT::f64) 8000 return LowerFDIV64(Op, DAG); 8001 8002 if (VT == MVT::f16) 8003 return LowerFDIV16(Op, DAG); 8004 8005 llvm_unreachable("Unexpected type for fdiv"); 8006 } 8007 8008 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8009 SDLoc DL(Op); 8010 StoreSDNode *Store = cast<StoreSDNode>(Op); 8011 EVT VT = Store->getMemoryVT(); 8012 8013 if (VT == MVT::i1) { 8014 return DAG.getTruncStore(Store->getChain(), DL, 8015 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8016 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8017 } 8018 8019 assert(VT.isVector() && 8020 Store->getValue().getValueType().getScalarType() == MVT::i32); 8021 8022 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8023 VT, *Store->getMemOperand())) { 8024 return expandUnalignedStore(Store, DAG); 8025 } 8026 8027 unsigned AS = Store->getAddressSpace(); 8028 if (Subtarget->hasLDSMisalignedBug() && 8029 AS == AMDGPUAS::FLAT_ADDRESS && 8030 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8031 return SplitVectorStore(Op, DAG); 8032 } 8033 8034 MachineFunction &MF = DAG.getMachineFunction(); 8035 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8036 // If there is a possibilty that flat instruction access scratch memory 8037 // then we need to use the same legalization rules we use for private. 8038 if (AS == AMDGPUAS::FLAT_ADDRESS && 8039 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8040 AS = MFI->hasFlatScratchInit() ? 8041 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8042 8043 unsigned NumElements = VT.getVectorNumElements(); 8044 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8045 AS == AMDGPUAS::FLAT_ADDRESS) { 8046 if (NumElements > 4) 8047 return SplitVectorStore(Op, DAG); 8048 // v3 stores not supported on SI. 8049 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8050 return SplitVectorStore(Op, DAG); 8051 return SDValue(); 8052 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8053 switch (Subtarget->getMaxPrivateElementSize()) { 8054 case 4: 8055 return scalarizeVectorStore(Store, DAG); 8056 case 8: 8057 if (NumElements > 2) 8058 return SplitVectorStore(Op, DAG); 8059 return SDValue(); 8060 case 16: 8061 if (NumElements > 4 || NumElements == 3) 8062 return SplitVectorStore(Op, DAG); 8063 return SDValue(); 8064 default: 8065 llvm_unreachable("unsupported private_element_size"); 8066 } 8067 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8068 // Use ds_write_b128 if possible. 8069 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 8070 VT.getStoreSize() == 16 && NumElements != 3) 8071 return SDValue(); 8072 8073 if (NumElements > 2) 8074 return SplitVectorStore(Op, DAG); 8075 8076 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8077 // address is negative, then the instruction is incorrectly treated as 8078 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8079 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8080 // store later in the SILoadStoreOptimizer. 8081 if (!Subtarget->hasUsableDSOffset() && 8082 NumElements == 2 && VT.getStoreSize() == 8 && 8083 Store->getAlignment() < 8) { 8084 return SplitVectorStore(Op, DAG); 8085 } 8086 8087 return SDValue(); 8088 } else { 8089 llvm_unreachable("unhandled address space"); 8090 } 8091 } 8092 8093 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8094 SDLoc DL(Op); 8095 EVT VT = Op.getValueType(); 8096 SDValue Arg = Op.getOperand(0); 8097 SDValue TrigVal; 8098 8099 // TODO: Should this propagate fast-math-flags? 8100 8101 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT); 8102 8103 if (Subtarget->hasTrigReducedRange()) { 8104 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 8105 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal); 8106 } else { 8107 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 8108 } 8109 8110 switch (Op.getOpcode()) { 8111 case ISD::FCOS: 8112 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal); 8113 case ISD::FSIN: 8114 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal); 8115 default: 8116 llvm_unreachable("Wrong trig opcode"); 8117 } 8118 } 8119 8120 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8121 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8122 assert(AtomicNode->isCompareAndSwap()); 8123 unsigned AS = AtomicNode->getAddressSpace(); 8124 8125 // No custom lowering required for local address space 8126 if (!isFlatGlobalAddrSpace(AS)) 8127 return Op; 8128 8129 // Non-local address space requires custom lowering for atomic compare 8130 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8131 SDLoc DL(Op); 8132 SDValue ChainIn = Op.getOperand(0); 8133 SDValue Addr = Op.getOperand(1); 8134 SDValue Old = Op.getOperand(2); 8135 SDValue New = Op.getOperand(3); 8136 EVT VT = Op.getValueType(); 8137 MVT SimpleVT = VT.getSimpleVT(); 8138 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8139 8140 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8141 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8142 8143 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8144 Ops, VT, AtomicNode->getMemOperand()); 8145 } 8146 8147 //===----------------------------------------------------------------------===// 8148 // Custom DAG optimizations 8149 //===----------------------------------------------------------------------===// 8150 8151 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8152 DAGCombinerInfo &DCI) const { 8153 EVT VT = N->getValueType(0); 8154 EVT ScalarVT = VT.getScalarType(); 8155 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8156 return SDValue(); 8157 8158 SelectionDAG &DAG = DCI.DAG; 8159 SDLoc DL(N); 8160 8161 SDValue Src = N->getOperand(0); 8162 EVT SrcVT = Src.getValueType(); 8163 8164 // TODO: We could try to match extracting the higher bytes, which would be 8165 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8166 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8167 // about in practice. 8168 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8169 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8170 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8171 DCI.AddToWorklist(Cvt.getNode()); 8172 8173 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8174 if (ScalarVT != MVT::f32) { 8175 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8176 DAG.getTargetConstant(0, DL, MVT::i32)); 8177 } 8178 return Cvt; 8179 } 8180 } 8181 8182 return SDValue(); 8183 } 8184 8185 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8186 8187 // This is a variant of 8188 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8189 // 8190 // The normal DAG combiner will do this, but only if the add has one use since 8191 // that would increase the number of instructions. 8192 // 8193 // This prevents us from seeing a constant offset that can be folded into a 8194 // memory instruction's addressing mode. If we know the resulting add offset of 8195 // a pointer can be folded into an addressing offset, we can replace the pointer 8196 // operand with the add of new constant offset. This eliminates one of the uses, 8197 // and may allow the remaining use to also be simplified. 8198 // 8199 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8200 unsigned AddrSpace, 8201 EVT MemVT, 8202 DAGCombinerInfo &DCI) const { 8203 SDValue N0 = N->getOperand(0); 8204 SDValue N1 = N->getOperand(1); 8205 8206 // We only do this to handle cases where it's profitable when there are 8207 // multiple uses of the add, so defer to the standard combine. 8208 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8209 N0->hasOneUse()) 8210 return SDValue(); 8211 8212 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8213 if (!CN1) 8214 return SDValue(); 8215 8216 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8217 if (!CAdd) 8218 return SDValue(); 8219 8220 // If the resulting offset is too large, we can't fold it into the addressing 8221 // mode offset. 8222 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8223 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8224 8225 AddrMode AM; 8226 AM.HasBaseReg = true; 8227 AM.BaseOffs = Offset.getSExtValue(); 8228 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8229 return SDValue(); 8230 8231 SelectionDAG &DAG = DCI.DAG; 8232 SDLoc SL(N); 8233 EVT VT = N->getValueType(0); 8234 8235 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8236 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 8237 8238 SDNodeFlags Flags; 8239 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8240 (N0.getOpcode() == ISD::OR || 8241 N0->getFlags().hasNoUnsignedWrap())); 8242 8243 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8244 } 8245 8246 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8247 DAGCombinerInfo &DCI) const { 8248 SDValue Ptr = N->getBasePtr(); 8249 SelectionDAG &DAG = DCI.DAG; 8250 SDLoc SL(N); 8251 8252 // TODO: We could also do this for multiplies. 8253 if (Ptr.getOpcode() == ISD::SHL) { 8254 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8255 N->getMemoryVT(), DCI); 8256 if (NewPtr) { 8257 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8258 8259 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8260 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8261 } 8262 } 8263 8264 return SDValue(); 8265 } 8266 8267 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8268 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8269 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8270 (Opc == ISD::XOR && Val == 0); 8271 } 8272 8273 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8274 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8275 // integer combine opportunities since most 64-bit operations are decomposed 8276 // this way. TODO: We won't want this for SALU especially if it is an inline 8277 // immediate. 8278 SDValue SITargetLowering::splitBinaryBitConstantOp( 8279 DAGCombinerInfo &DCI, 8280 const SDLoc &SL, 8281 unsigned Opc, SDValue LHS, 8282 const ConstantSDNode *CRHS) const { 8283 uint64_t Val = CRHS->getZExtValue(); 8284 uint32_t ValLo = Lo_32(Val); 8285 uint32_t ValHi = Hi_32(Val); 8286 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8287 8288 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8289 bitOpWithConstantIsReducible(Opc, ValHi)) || 8290 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8291 // If we need to materialize a 64-bit immediate, it will be split up later 8292 // anyway. Avoid creating the harder to understand 64-bit immediate 8293 // materialization. 8294 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8295 } 8296 8297 return SDValue(); 8298 } 8299 8300 // Returns true if argument is a boolean value which is not serialized into 8301 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8302 static bool isBoolSGPR(SDValue V) { 8303 if (V.getValueType() != MVT::i1) 8304 return false; 8305 switch (V.getOpcode()) { 8306 default: break; 8307 case ISD::SETCC: 8308 case ISD::AND: 8309 case ISD::OR: 8310 case ISD::XOR: 8311 case AMDGPUISD::FP_CLASS: 8312 return true; 8313 } 8314 return false; 8315 } 8316 8317 // If a constant has all zeroes or all ones within each byte return it. 8318 // Otherwise return 0. 8319 static uint32_t getConstantPermuteMask(uint32_t C) { 8320 // 0xff for any zero byte in the mask 8321 uint32_t ZeroByteMask = 0; 8322 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8323 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8324 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8325 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8326 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8327 if ((NonZeroByteMask & C) != NonZeroByteMask) 8328 return 0; // Partial bytes selected. 8329 return C; 8330 } 8331 8332 // Check if a node selects whole bytes from its operand 0 starting at a byte 8333 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8334 // or -1 if not succeeded. 8335 // Note byte select encoding: 8336 // value 0-3 selects corresponding source byte; 8337 // value 0xc selects zero; 8338 // value 0xff selects 0xff. 8339 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8340 assert(V.getValueSizeInBits() == 32); 8341 8342 if (V.getNumOperands() != 2) 8343 return ~0; 8344 8345 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8346 if (!N1) 8347 return ~0; 8348 8349 uint32_t C = N1->getZExtValue(); 8350 8351 switch (V.getOpcode()) { 8352 default: 8353 break; 8354 case ISD::AND: 8355 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8356 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8357 } 8358 break; 8359 8360 case ISD::OR: 8361 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8362 return (0x03020100 & ~ConstMask) | ConstMask; 8363 } 8364 break; 8365 8366 case ISD::SHL: 8367 if (C % 8) 8368 return ~0; 8369 8370 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8371 8372 case ISD::SRL: 8373 if (C % 8) 8374 return ~0; 8375 8376 return uint32_t(0x0c0c0c0c03020100ull >> C); 8377 } 8378 8379 return ~0; 8380 } 8381 8382 SDValue SITargetLowering::performAndCombine(SDNode *N, 8383 DAGCombinerInfo &DCI) const { 8384 if (DCI.isBeforeLegalize()) 8385 return SDValue(); 8386 8387 SelectionDAG &DAG = DCI.DAG; 8388 EVT VT = N->getValueType(0); 8389 SDValue LHS = N->getOperand(0); 8390 SDValue RHS = N->getOperand(1); 8391 8392 8393 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8394 if (VT == MVT::i64 && CRHS) { 8395 if (SDValue Split 8396 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8397 return Split; 8398 } 8399 8400 if (CRHS && VT == MVT::i32) { 8401 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8402 // nb = number of trailing zeroes in mask 8403 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8404 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8405 uint64_t Mask = CRHS->getZExtValue(); 8406 unsigned Bits = countPopulation(Mask); 8407 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8408 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8409 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8410 unsigned Shift = CShift->getZExtValue(); 8411 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8412 unsigned Offset = NB + Shift; 8413 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8414 SDLoc SL(N); 8415 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8416 LHS->getOperand(0), 8417 DAG.getConstant(Offset, SL, MVT::i32), 8418 DAG.getConstant(Bits, SL, MVT::i32)); 8419 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8420 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8421 DAG.getValueType(NarrowVT)); 8422 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8423 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8424 return Shl; 8425 } 8426 } 8427 } 8428 8429 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8430 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8431 isa<ConstantSDNode>(LHS.getOperand(2))) { 8432 uint32_t Sel = getConstantPermuteMask(Mask); 8433 if (!Sel) 8434 return SDValue(); 8435 8436 // Select 0xc for all zero bytes 8437 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8438 SDLoc DL(N); 8439 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8440 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8441 } 8442 } 8443 8444 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8445 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8446 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8447 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8448 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8449 8450 SDValue X = LHS.getOperand(0); 8451 SDValue Y = RHS.getOperand(0); 8452 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8453 return SDValue(); 8454 8455 if (LCC == ISD::SETO) { 8456 if (X != LHS.getOperand(1)) 8457 return SDValue(); 8458 8459 if (RCC == ISD::SETUNE) { 8460 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8461 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8462 return SDValue(); 8463 8464 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8465 SIInstrFlags::N_SUBNORMAL | 8466 SIInstrFlags::N_ZERO | 8467 SIInstrFlags::P_ZERO | 8468 SIInstrFlags::P_SUBNORMAL | 8469 SIInstrFlags::P_NORMAL; 8470 8471 static_assert(((~(SIInstrFlags::S_NAN | 8472 SIInstrFlags::Q_NAN | 8473 SIInstrFlags::N_INFINITY | 8474 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8475 "mask not equal"); 8476 8477 SDLoc DL(N); 8478 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8479 X, DAG.getConstant(Mask, DL, MVT::i32)); 8480 } 8481 } 8482 } 8483 8484 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8485 std::swap(LHS, RHS); 8486 8487 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8488 RHS.hasOneUse()) { 8489 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8490 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8491 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8492 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8493 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8494 (RHS.getOperand(0) == LHS.getOperand(0) && 8495 LHS.getOperand(0) == LHS.getOperand(1))) { 8496 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8497 unsigned NewMask = LCC == ISD::SETO ? 8498 Mask->getZExtValue() & ~OrdMask : 8499 Mask->getZExtValue() & OrdMask; 8500 8501 SDLoc DL(N); 8502 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8503 DAG.getConstant(NewMask, DL, MVT::i32)); 8504 } 8505 } 8506 8507 if (VT == MVT::i32 && 8508 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8509 // and x, (sext cc from i1) => select cc, x, 0 8510 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8511 std::swap(LHS, RHS); 8512 if (isBoolSGPR(RHS.getOperand(0))) 8513 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8514 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8515 } 8516 8517 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8518 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8519 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8520 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8521 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8522 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8523 if (LHSMask != ~0u && RHSMask != ~0u) { 8524 // Canonicalize the expression in an attempt to have fewer unique masks 8525 // and therefore fewer registers used to hold the masks. 8526 if (LHSMask > RHSMask) { 8527 std::swap(LHSMask, RHSMask); 8528 std::swap(LHS, RHS); 8529 } 8530 8531 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8532 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8533 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8534 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8535 8536 // Check of we need to combine values from two sources within a byte. 8537 if (!(LHSUsedLanes & RHSUsedLanes) && 8538 // If we select high and lower word keep it for SDWA. 8539 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8540 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8541 // Each byte in each mask is either selector mask 0-3, or has higher 8542 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8543 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8544 // mask which is not 0xff wins. By anding both masks we have a correct 8545 // result except that 0x0c shall be corrected to give 0x0c only. 8546 uint32_t Mask = LHSMask & RHSMask; 8547 for (unsigned I = 0; I < 32; I += 8) { 8548 uint32_t ByteSel = 0xff << I; 8549 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8550 Mask &= (0x0c << I) & 0xffffffff; 8551 } 8552 8553 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8554 // or 0x0c. 8555 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8556 SDLoc DL(N); 8557 8558 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8559 LHS.getOperand(0), RHS.getOperand(0), 8560 DAG.getConstant(Sel, DL, MVT::i32)); 8561 } 8562 } 8563 } 8564 8565 return SDValue(); 8566 } 8567 8568 SDValue SITargetLowering::performOrCombine(SDNode *N, 8569 DAGCombinerInfo &DCI) const { 8570 SelectionDAG &DAG = DCI.DAG; 8571 SDValue LHS = N->getOperand(0); 8572 SDValue RHS = N->getOperand(1); 8573 8574 EVT VT = N->getValueType(0); 8575 if (VT == MVT::i1) { 8576 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8577 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8578 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8579 SDValue Src = LHS.getOperand(0); 8580 if (Src != RHS.getOperand(0)) 8581 return SDValue(); 8582 8583 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8584 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8585 if (!CLHS || !CRHS) 8586 return SDValue(); 8587 8588 // Only 10 bits are used. 8589 static const uint32_t MaxMask = 0x3ff; 8590 8591 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8592 SDLoc DL(N); 8593 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8594 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8595 } 8596 8597 return SDValue(); 8598 } 8599 8600 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8601 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8602 LHS.getOpcode() == AMDGPUISD::PERM && 8603 isa<ConstantSDNode>(LHS.getOperand(2))) { 8604 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8605 if (!Sel) 8606 return SDValue(); 8607 8608 Sel |= LHS.getConstantOperandVal(2); 8609 SDLoc DL(N); 8610 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8611 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8612 } 8613 8614 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8615 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8616 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8617 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8618 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8619 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8620 if (LHSMask != ~0u && RHSMask != ~0u) { 8621 // Canonicalize the expression in an attempt to have fewer unique masks 8622 // and therefore fewer registers used to hold the masks. 8623 if (LHSMask > RHSMask) { 8624 std::swap(LHSMask, RHSMask); 8625 std::swap(LHS, RHS); 8626 } 8627 8628 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8629 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8630 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8631 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8632 8633 // Check of we need to combine values from two sources within a byte. 8634 if (!(LHSUsedLanes & RHSUsedLanes) && 8635 // If we select high and lower word keep it for SDWA. 8636 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8637 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8638 // Kill zero bytes selected by other mask. Zero value is 0xc. 8639 LHSMask &= ~RHSUsedLanes; 8640 RHSMask &= ~LHSUsedLanes; 8641 // Add 4 to each active LHS lane 8642 LHSMask |= LHSUsedLanes & 0x04040404; 8643 // Combine masks 8644 uint32_t Sel = LHSMask | RHSMask; 8645 SDLoc DL(N); 8646 8647 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8648 LHS.getOperand(0), RHS.getOperand(0), 8649 DAG.getConstant(Sel, DL, MVT::i32)); 8650 } 8651 } 8652 } 8653 8654 if (VT != MVT::i64) 8655 return SDValue(); 8656 8657 // TODO: This could be a generic combine with a predicate for extracting the 8658 // high half of an integer being free. 8659 8660 // (or i64:x, (zero_extend i32:y)) -> 8661 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8662 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8663 RHS.getOpcode() != ISD::ZERO_EXTEND) 8664 std::swap(LHS, RHS); 8665 8666 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8667 SDValue ExtSrc = RHS.getOperand(0); 8668 EVT SrcVT = ExtSrc.getValueType(); 8669 if (SrcVT == MVT::i32) { 8670 SDLoc SL(N); 8671 SDValue LowLHS, HiBits; 8672 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 8673 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 8674 8675 DCI.AddToWorklist(LowOr.getNode()); 8676 DCI.AddToWorklist(HiBits.getNode()); 8677 8678 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 8679 LowOr, HiBits); 8680 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 8681 } 8682 } 8683 8684 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8685 if (CRHS) { 8686 if (SDValue Split 8687 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 8688 return Split; 8689 } 8690 8691 return SDValue(); 8692 } 8693 8694 SDValue SITargetLowering::performXorCombine(SDNode *N, 8695 DAGCombinerInfo &DCI) const { 8696 EVT VT = N->getValueType(0); 8697 if (VT != MVT::i64) 8698 return SDValue(); 8699 8700 SDValue LHS = N->getOperand(0); 8701 SDValue RHS = N->getOperand(1); 8702 8703 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8704 if (CRHS) { 8705 if (SDValue Split 8706 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 8707 return Split; 8708 } 8709 8710 return SDValue(); 8711 } 8712 8713 // Instructions that will be lowered with a final instruction that zeros the 8714 // high result bits. 8715 // XXX - probably only need to list legal operations. 8716 static bool fp16SrcZerosHighBits(unsigned Opc) { 8717 switch (Opc) { 8718 case ISD::FADD: 8719 case ISD::FSUB: 8720 case ISD::FMUL: 8721 case ISD::FDIV: 8722 case ISD::FREM: 8723 case ISD::FMA: 8724 case ISD::FMAD: 8725 case ISD::FCANONICALIZE: 8726 case ISD::FP_ROUND: 8727 case ISD::UINT_TO_FP: 8728 case ISD::SINT_TO_FP: 8729 case ISD::FABS: 8730 // Fabs is lowered to a bit operation, but it's an and which will clear the 8731 // high bits anyway. 8732 case ISD::FSQRT: 8733 case ISD::FSIN: 8734 case ISD::FCOS: 8735 case ISD::FPOWI: 8736 case ISD::FPOW: 8737 case ISD::FLOG: 8738 case ISD::FLOG2: 8739 case ISD::FLOG10: 8740 case ISD::FEXP: 8741 case ISD::FEXP2: 8742 case ISD::FCEIL: 8743 case ISD::FTRUNC: 8744 case ISD::FRINT: 8745 case ISD::FNEARBYINT: 8746 case ISD::FROUND: 8747 case ISD::FFLOOR: 8748 case ISD::FMINNUM: 8749 case ISD::FMAXNUM: 8750 case AMDGPUISD::FRACT: 8751 case AMDGPUISD::CLAMP: 8752 case AMDGPUISD::COS_HW: 8753 case AMDGPUISD::SIN_HW: 8754 case AMDGPUISD::FMIN3: 8755 case AMDGPUISD::FMAX3: 8756 case AMDGPUISD::FMED3: 8757 case AMDGPUISD::FMAD_FTZ: 8758 case AMDGPUISD::RCP: 8759 case AMDGPUISD::RSQ: 8760 case AMDGPUISD::RCP_IFLAG: 8761 case AMDGPUISD::LDEXP: 8762 return true; 8763 default: 8764 // fcopysign, select and others may be lowered to 32-bit bit operations 8765 // which don't zero the high bits. 8766 return false; 8767 } 8768 } 8769 8770 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 8771 DAGCombinerInfo &DCI) const { 8772 if (!Subtarget->has16BitInsts() || 8773 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8774 return SDValue(); 8775 8776 EVT VT = N->getValueType(0); 8777 if (VT != MVT::i32) 8778 return SDValue(); 8779 8780 SDValue Src = N->getOperand(0); 8781 if (Src.getValueType() != MVT::i16) 8782 return SDValue(); 8783 8784 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 8785 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 8786 if (Src.getOpcode() == ISD::BITCAST) { 8787 SDValue BCSrc = Src.getOperand(0); 8788 if (BCSrc.getValueType() == MVT::f16 && 8789 fp16SrcZerosHighBits(BCSrc.getOpcode())) 8790 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 8791 } 8792 8793 return SDValue(); 8794 } 8795 8796 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 8797 DAGCombinerInfo &DCI) 8798 const { 8799 SDValue Src = N->getOperand(0); 8800 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 8801 8802 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 8803 VTSign->getVT() == MVT::i8) || 8804 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 8805 VTSign->getVT() == MVT::i16)) && 8806 Src.hasOneUse()) { 8807 auto *M = cast<MemSDNode>(Src); 8808 SDValue Ops[] = { 8809 Src.getOperand(0), // Chain 8810 Src.getOperand(1), // rsrc 8811 Src.getOperand(2), // vindex 8812 Src.getOperand(3), // voffset 8813 Src.getOperand(4), // soffset 8814 Src.getOperand(5), // offset 8815 Src.getOperand(6), 8816 Src.getOperand(7) 8817 }; 8818 // replace with BUFFER_LOAD_BYTE/SHORT 8819 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 8820 Src.getOperand(0).getValueType()); 8821 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 8822 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 8823 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 8824 ResList, 8825 Ops, M->getMemoryVT(), 8826 M->getMemOperand()); 8827 return DCI.DAG.getMergeValues({BufferLoadSignExt, 8828 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 8829 } 8830 return SDValue(); 8831 } 8832 8833 SDValue SITargetLowering::performClassCombine(SDNode *N, 8834 DAGCombinerInfo &DCI) const { 8835 SelectionDAG &DAG = DCI.DAG; 8836 SDValue Mask = N->getOperand(1); 8837 8838 // fp_class x, 0 -> false 8839 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 8840 if (CMask->isNullValue()) 8841 return DAG.getConstant(0, SDLoc(N), MVT::i1); 8842 } 8843 8844 if (N->getOperand(0).isUndef()) 8845 return DAG.getUNDEF(MVT::i1); 8846 8847 return SDValue(); 8848 } 8849 8850 SDValue SITargetLowering::performRcpCombine(SDNode *N, 8851 DAGCombinerInfo &DCI) const { 8852 EVT VT = N->getValueType(0); 8853 SDValue N0 = N->getOperand(0); 8854 8855 if (N0.isUndef()) 8856 return N0; 8857 8858 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 8859 N0.getOpcode() == ISD::SINT_TO_FP)) { 8860 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 8861 N->getFlags()); 8862 } 8863 8864 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 8865 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 8866 N0.getOperand(0), N->getFlags()); 8867 } 8868 8869 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 8870 } 8871 8872 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 8873 unsigned MaxDepth) const { 8874 unsigned Opcode = Op.getOpcode(); 8875 if (Opcode == ISD::FCANONICALIZE) 8876 return true; 8877 8878 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8879 auto F = CFP->getValueAPF(); 8880 if (F.isNaN() && F.isSignaling()) 8881 return false; 8882 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 8883 } 8884 8885 // If source is a result of another standard FP operation it is already in 8886 // canonical form. 8887 if (MaxDepth == 0) 8888 return false; 8889 8890 switch (Opcode) { 8891 // These will flush denorms if required. 8892 case ISD::FADD: 8893 case ISD::FSUB: 8894 case ISD::FMUL: 8895 case ISD::FCEIL: 8896 case ISD::FFLOOR: 8897 case ISD::FMA: 8898 case ISD::FMAD: 8899 case ISD::FSQRT: 8900 case ISD::FDIV: 8901 case ISD::FREM: 8902 case ISD::FP_ROUND: 8903 case ISD::FP_EXTEND: 8904 case AMDGPUISD::FMUL_LEGACY: 8905 case AMDGPUISD::FMAD_FTZ: 8906 case AMDGPUISD::RCP: 8907 case AMDGPUISD::RSQ: 8908 case AMDGPUISD::RSQ_CLAMP: 8909 case AMDGPUISD::RCP_LEGACY: 8910 case AMDGPUISD::RCP_IFLAG: 8911 case AMDGPUISD::TRIG_PREOP: 8912 case AMDGPUISD::DIV_SCALE: 8913 case AMDGPUISD::DIV_FMAS: 8914 case AMDGPUISD::DIV_FIXUP: 8915 case AMDGPUISD::FRACT: 8916 case AMDGPUISD::LDEXP: 8917 case AMDGPUISD::CVT_PKRTZ_F16_F32: 8918 case AMDGPUISD::CVT_F32_UBYTE0: 8919 case AMDGPUISD::CVT_F32_UBYTE1: 8920 case AMDGPUISD::CVT_F32_UBYTE2: 8921 case AMDGPUISD::CVT_F32_UBYTE3: 8922 return true; 8923 8924 // It can/will be lowered or combined as a bit operation. 8925 // Need to check their input recursively to handle. 8926 case ISD::FNEG: 8927 case ISD::FABS: 8928 case ISD::FCOPYSIGN: 8929 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8930 8931 case ISD::FSIN: 8932 case ISD::FCOS: 8933 case ISD::FSINCOS: 8934 return Op.getValueType().getScalarType() != MVT::f16; 8935 8936 case ISD::FMINNUM: 8937 case ISD::FMAXNUM: 8938 case ISD::FMINNUM_IEEE: 8939 case ISD::FMAXNUM_IEEE: 8940 case AMDGPUISD::CLAMP: 8941 case AMDGPUISD::FMED3: 8942 case AMDGPUISD::FMAX3: 8943 case AMDGPUISD::FMIN3: { 8944 // FIXME: Shouldn't treat the generic operations different based these. 8945 // However, we aren't really required to flush the result from 8946 // minnum/maxnum.. 8947 8948 // snans will be quieted, so we only need to worry about denormals. 8949 if (Subtarget->supportsMinMaxDenormModes() || 8950 denormalsEnabledForType(DAG, Op.getValueType())) 8951 return true; 8952 8953 // Flushing may be required. 8954 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 8955 // targets need to check their input recursively. 8956 8957 // FIXME: Does this apply with clamp? It's implemented with max. 8958 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 8959 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 8960 return false; 8961 } 8962 8963 return true; 8964 } 8965 case ISD::SELECT: { 8966 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 8967 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 8968 } 8969 case ISD::BUILD_VECTOR: { 8970 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 8971 SDValue SrcOp = Op.getOperand(i); 8972 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 8973 return false; 8974 } 8975 8976 return true; 8977 } 8978 case ISD::EXTRACT_VECTOR_ELT: 8979 case ISD::EXTRACT_SUBVECTOR: { 8980 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8981 } 8982 case ISD::INSERT_VECTOR_ELT: { 8983 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 8984 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 8985 } 8986 case ISD::UNDEF: 8987 // Could be anything. 8988 return false; 8989 8990 case ISD::BITCAST: { 8991 // Hack round the mess we make when legalizing extract_vector_elt 8992 SDValue Src = Op.getOperand(0); 8993 if (Src.getValueType() == MVT::i16 && 8994 Src.getOpcode() == ISD::TRUNCATE) { 8995 SDValue TruncSrc = Src.getOperand(0); 8996 if (TruncSrc.getValueType() == MVT::i32 && 8997 TruncSrc.getOpcode() == ISD::BITCAST && 8998 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 8999 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9000 } 9001 } 9002 9003 return false; 9004 } 9005 case ISD::INTRINSIC_WO_CHAIN: { 9006 unsigned IntrinsicID 9007 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9008 // TODO: Handle more intrinsics 9009 switch (IntrinsicID) { 9010 case Intrinsic::amdgcn_cvt_pkrtz: 9011 case Intrinsic::amdgcn_cubeid: 9012 case Intrinsic::amdgcn_frexp_mant: 9013 case Intrinsic::amdgcn_fdot2: 9014 case Intrinsic::amdgcn_rcp: 9015 case Intrinsic::amdgcn_rsq: 9016 case Intrinsic::amdgcn_rsq_clamp: 9017 case Intrinsic::amdgcn_rcp_legacy: 9018 case Intrinsic::amdgcn_rsq_legacy: 9019 return true; 9020 default: 9021 break; 9022 } 9023 9024 LLVM_FALLTHROUGH; 9025 } 9026 default: 9027 return denormalsEnabledForType(DAG, Op.getValueType()) && 9028 DAG.isKnownNeverSNaN(Op); 9029 } 9030 9031 llvm_unreachable("invalid operation"); 9032 } 9033 9034 // Constant fold canonicalize. 9035 SDValue SITargetLowering::getCanonicalConstantFP( 9036 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9037 // Flush denormals to 0 if not enabled. 9038 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9039 return DAG.getConstantFP(0.0, SL, VT); 9040 9041 if (C.isNaN()) { 9042 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9043 if (C.isSignaling()) { 9044 // Quiet a signaling NaN. 9045 // FIXME: Is this supposed to preserve payload bits? 9046 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9047 } 9048 9049 // Make sure it is the canonical NaN bitpattern. 9050 // 9051 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9052 // immediate? 9053 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9054 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9055 } 9056 9057 // Already canonical. 9058 return DAG.getConstantFP(C, SL, VT); 9059 } 9060 9061 static bool vectorEltWillFoldAway(SDValue Op) { 9062 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9063 } 9064 9065 SDValue SITargetLowering::performFCanonicalizeCombine( 9066 SDNode *N, 9067 DAGCombinerInfo &DCI) const { 9068 SelectionDAG &DAG = DCI.DAG; 9069 SDValue N0 = N->getOperand(0); 9070 EVT VT = N->getValueType(0); 9071 9072 // fcanonicalize undef -> qnan 9073 if (N0.isUndef()) { 9074 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9075 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9076 } 9077 9078 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9079 EVT VT = N->getValueType(0); 9080 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9081 } 9082 9083 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9084 // (fcanonicalize k) 9085 // 9086 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9087 9088 // TODO: This could be better with wider vectors that will be split to v2f16, 9089 // and to consider uses since there aren't that many packed operations. 9090 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9091 isTypeLegal(MVT::v2f16)) { 9092 SDLoc SL(N); 9093 SDValue NewElts[2]; 9094 SDValue Lo = N0.getOperand(0); 9095 SDValue Hi = N0.getOperand(1); 9096 EVT EltVT = Lo.getValueType(); 9097 9098 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9099 for (unsigned I = 0; I != 2; ++I) { 9100 SDValue Op = N0.getOperand(I); 9101 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9102 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9103 CFP->getValueAPF()); 9104 } else if (Op.isUndef()) { 9105 // Handled below based on what the other operand is. 9106 NewElts[I] = Op; 9107 } else { 9108 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9109 } 9110 } 9111 9112 // If one half is undef, and one is constant, perfer a splat vector rather 9113 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9114 // cheaper to use and may be free with a packed operation. 9115 if (NewElts[0].isUndef()) { 9116 if (isa<ConstantFPSDNode>(NewElts[1])) 9117 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9118 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9119 } 9120 9121 if (NewElts[1].isUndef()) { 9122 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9123 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9124 } 9125 9126 return DAG.getBuildVector(VT, SL, NewElts); 9127 } 9128 } 9129 9130 unsigned SrcOpc = N0.getOpcode(); 9131 9132 // If it's free to do so, push canonicalizes further up the source, which may 9133 // find a canonical source. 9134 // 9135 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9136 // sNaNs. 9137 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9138 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9139 if (CRHS && N0.hasOneUse()) { 9140 SDLoc SL(N); 9141 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9142 N0.getOperand(0)); 9143 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9144 DCI.AddToWorklist(Canon0.getNode()); 9145 9146 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9147 } 9148 } 9149 9150 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9151 } 9152 9153 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9154 switch (Opc) { 9155 case ISD::FMAXNUM: 9156 case ISD::FMAXNUM_IEEE: 9157 return AMDGPUISD::FMAX3; 9158 case ISD::SMAX: 9159 return AMDGPUISD::SMAX3; 9160 case ISD::UMAX: 9161 return AMDGPUISD::UMAX3; 9162 case ISD::FMINNUM: 9163 case ISD::FMINNUM_IEEE: 9164 return AMDGPUISD::FMIN3; 9165 case ISD::SMIN: 9166 return AMDGPUISD::SMIN3; 9167 case ISD::UMIN: 9168 return AMDGPUISD::UMIN3; 9169 default: 9170 llvm_unreachable("Not a min/max opcode"); 9171 } 9172 } 9173 9174 SDValue SITargetLowering::performIntMed3ImmCombine( 9175 SelectionDAG &DAG, const SDLoc &SL, 9176 SDValue Op0, SDValue Op1, bool Signed) const { 9177 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9178 if (!K1) 9179 return SDValue(); 9180 9181 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9182 if (!K0) 9183 return SDValue(); 9184 9185 if (Signed) { 9186 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9187 return SDValue(); 9188 } else { 9189 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9190 return SDValue(); 9191 } 9192 9193 EVT VT = K0->getValueType(0); 9194 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9195 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9196 return DAG.getNode(Med3Opc, SL, VT, 9197 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9198 } 9199 9200 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9201 MVT NVT = MVT::i32; 9202 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9203 9204 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9205 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9206 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9207 9208 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9209 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9210 } 9211 9212 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9213 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9214 return C; 9215 9216 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9217 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9218 return C; 9219 } 9220 9221 return nullptr; 9222 } 9223 9224 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9225 const SDLoc &SL, 9226 SDValue Op0, 9227 SDValue Op1) const { 9228 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9229 if (!K1) 9230 return SDValue(); 9231 9232 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9233 if (!K0) 9234 return SDValue(); 9235 9236 // Ordered >= (although NaN inputs should have folded away by now). 9237 if (K0->getValueAPF() > K1->getValueAPF()) 9238 return SDValue(); 9239 9240 const MachineFunction &MF = DAG.getMachineFunction(); 9241 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9242 9243 // TODO: Check IEEE bit enabled? 9244 EVT VT = Op0.getValueType(); 9245 if (Info->getMode().DX10Clamp) { 9246 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9247 // hardware fmed3 behavior converting to a min. 9248 // FIXME: Should this be allowing -0.0? 9249 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9250 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9251 } 9252 9253 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9254 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9255 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9256 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9257 // then give the other result, which is different from med3 with a NaN 9258 // input. 9259 SDValue Var = Op0.getOperand(0); 9260 if (!DAG.isKnownNeverSNaN(Var)) 9261 return SDValue(); 9262 9263 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9264 9265 if ((!K0->hasOneUse() || 9266 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9267 (!K1->hasOneUse() || 9268 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9269 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9270 Var, SDValue(K0, 0), SDValue(K1, 0)); 9271 } 9272 } 9273 9274 return SDValue(); 9275 } 9276 9277 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9278 DAGCombinerInfo &DCI) const { 9279 SelectionDAG &DAG = DCI.DAG; 9280 9281 EVT VT = N->getValueType(0); 9282 unsigned Opc = N->getOpcode(); 9283 SDValue Op0 = N->getOperand(0); 9284 SDValue Op1 = N->getOperand(1); 9285 9286 // Only do this if the inner op has one use since this will just increases 9287 // register pressure for no benefit. 9288 9289 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9290 !VT.isVector() && 9291 (VT == MVT::i32 || VT == MVT::f32 || 9292 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9293 // max(max(a, b), c) -> max3(a, b, c) 9294 // min(min(a, b), c) -> min3(a, b, c) 9295 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9296 SDLoc DL(N); 9297 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9298 DL, 9299 N->getValueType(0), 9300 Op0.getOperand(0), 9301 Op0.getOperand(1), 9302 Op1); 9303 } 9304 9305 // Try commuted. 9306 // max(a, max(b, c)) -> max3(a, b, c) 9307 // min(a, min(b, c)) -> min3(a, b, c) 9308 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9309 SDLoc DL(N); 9310 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9311 DL, 9312 N->getValueType(0), 9313 Op0, 9314 Op1.getOperand(0), 9315 Op1.getOperand(1)); 9316 } 9317 } 9318 9319 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9320 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9321 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9322 return Med3; 9323 } 9324 9325 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9326 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9327 return Med3; 9328 } 9329 9330 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9331 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9332 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9333 (Opc == AMDGPUISD::FMIN_LEGACY && 9334 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9335 (VT == MVT::f32 || VT == MVT::f64 || 9336 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9337 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9338 Op0.hasOneUse()) { 9339 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9340 return Res; 9341 } 9342 9343 return SDValue(); 9344 } 9345 9346 static bool isClampZeroToOne(SDValue A, SDValue B) { 9347 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9348 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9349 // FIXME: Should this be allowing -0.0? 9350 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9351 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9352 } 9353 } 9354 9355 return false; 9356 } 9357 9358 // FIXME: Should only worry about snans for version with chain. 9359 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9360 DAGCombinerInfo &DCI) const { 9361 EVT VT = N->getValueType(0); 9362 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9363 // NaNs. With a NaN input, the order of the operands may change the result. 9364 9365 SelectionDAG &DAG = DCI.DAG; 9366 SDLoc SL(N); 9367 9368 SDValue Src0 = N->getOperand(0); 9369 SDValue Src1 = N->getOperand(1); 9370 SDValue Src2 = N->getOperand(2); 9371 9372 if (isClampZeroToOne(Src0, Src1)) { 9373 // const_a, const_b, x -> clamp is safe in all cases including signaling 9374 // nans. 9375 // FIXME: Should this be allowing -0.0? 9376 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9377 } 9378 9379 const MachineFunction &MF = DAG.getMachineFunction(); 9380 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9381 9382 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9383 // handling no dx10-clamp? 9384 if (Info->getMode().DX10Clamp) { 9385 // If NaNs is clamped to 0, we are free to reorder the inputs. 9386 9387 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9388 std::swap(Src0, Src1); 9389 9390 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9391 std::swap(Src1, Src2); 9392 9393 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9394 std::swap(Src0, Src1); 9395 9396 if (isClampZeroToOne(Src1, Src2)) 9397 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9398 } 9399 9400 return SDValue(); 9401 } 9402 9403 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9404 DAGCombinerInfo &DCI) const { 9405 SDValue Src0 = N->getOperand(0); 9406 SDValue Src1 = N->getOperand(1); 9407 if (Src0.isUndef() && Src1.isUndef()) 9408 return DCI.DAG.getUNDEF(N->getValueType(0)); 9409 return SDValue(); 9410 } 9411 9412 SDValue SITargetLowering::performExtractVectorEltCombine( 9413 SDNode *N, DAGCombinerInfo &DCI) const { 9414 SDValue Vec = N->getOperand(0); 9415 SelectionDAG &DAG = DCI.DAG; 9416 9417 EVT VecVT = Vec.getValueType(); 9418 EVT EltVT = VecVT.getVectorElementType(); 9419 9420 if ((Vec.getOpcode() == ISD::FNEG || 9421 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9422 SDLoc SL(N); 9423 EVT EltVT = N->getValueType(0); 9424 SDValue Idx = N->getOperand(1); 9425 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9426 Vec.getOperand(0), Idx); 9427 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9428 } 9429 9430 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9431 // => 9432 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9433 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9434 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9435 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9436 SDLoc SL(N); 9437 EVT EltVT = N->getValueType(0); 9438 SDValue Idx = N->getOperand(1); 9439 unsigned Opc = Vec.getOpcode(); 9440 9441 switch(Opc) { 9442 default: 9443 break; 9444 // TODO: Support other binary operations. 9445 case ISD::FADD: 9446 case ISD::FSUB: 9447 case ISD::FMUL: 9448 case ISD::ADD: 9449 case ISD::UMIN: 9450 case ISD::UMAX: 9451 case ISD::SMIN: 9452 case ISD::SMAX: 9453 case ISD::FMAXNUM: 9454 case ISD::FMINNUM: 9455 case ISD::FMAXNUM_IEEE: 9456 case ISD::FMINNUM_IEEE: { 9457 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9458 Vec.getOperand(0), Idx); 9459 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9460 Vec.getOperand(1), Idx); 9461 9462 DCI.AddToWorklist(Elt0.getNode()); 9463 DCI.AddToWorklist(Elt1.getNode()); 9464 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9465 } 9466 } 9467 } 9468 9469 unsigned VecSize = VecVT.getSizeInBits(); 9470 unsigned EltSize = EltVT.getSizeInBits(); 9471 9472 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9473 // This elminates non-constant index and subsequent movrel or scratch access. 9474 // Sub-dword vectors of size 2 dword or less have better implementation. 9475 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9476 // instructions. 9477 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) && 9478 !isa<ConstantSDNode>(N->getOperand(1))) { 9479 SDLoc SL(N); 9480 SDValue Idx = N->getOperand(1); 9481 SDValue V; 9482 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9483 SDValue IC = DAG.getVectorIdxConstant(I, SL); 9484 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9485 if (I == 0) 9486 V = Elt; 9487 else 9488 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9489 } 9490 return V; 9491 } 9492 9493 if (!DCI.isBeforeLegalize()) 9494 return SDValue(); 9495 9496 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9497 // elements. This exposes more load reduction opportunities by replacing 9498 // multiple small extract_vector_elements with a single 32-bit extract. 9499 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9500 if (isa<MemSDNode>(Vec) && 9501 EltSize <= 16 && 9502 EltVT.isByteSized() && 9503 VecSize > 32 && 9504 VecSize % 32 == 0 && 9505 Idx) { 9506 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9507 9508 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9509 unsigned EltIdx = BitIndex / 32; 9510 unsigned LeftoverBitIdx = BitIndex % 32; 9511 SDLoc SL(N); 9512 9513 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9514 DCI.AddToWorklist(Cast.getNode()); 9515 9516 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9517 DAG.getConstant(EltIdx, SL, MVT::i32)); 9518 DCI.AddToWorklist(Elt.getNode()); 9519 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9520 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9521 DCI.AddToWorklist(Srl.getNode()); 9522 9523 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9524 DCI.AddToWorklist(Trunc.getNode()); 9525 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9526 } 9527 9528 return SDValue(); 9529 } 9530 9531 SDValue 9532 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9533 DAGCombinerInfo &DCI) const { 9534 SDValue Vec = N->getOperand(0); 9535 SDValue Idx = N->getOperand(2); 9536 EVT VecVT = Vec.getValueType(); 9537 EVT EltVT = VecVT.getVectorElementType(); 9538 unsigned VecSize = VecVT.getSizeInBits(); 9539 unsigned EltSize = EltVT.getSizeInBits(); 9540 9541 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9542 // => BUILD_VECTOR n x select (e, const-idx) 9543 // This elminates non-constant index and subsequent movrel or scratch access. 9544 // Sub-dword vectors of size 2 dword or less have better implementation. 9545 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9546 // instructions. 9547 if (isa<ConstantSDNode>(Idx) || 9548 VecSize > 256 || (VecSize <= 64 && EltSize < 32)) 9549 return SDValue(); 9550 9551 SelectionDAG &DAG = DCI.DAG; 9552 SDLoc SL(N); 9553 SDValue Ins = N->getOperand(1); 9554 EVT IdxVT = Idx.getValueType(); 9555 9556 SmallVector<SDValue, 16> Ops; 9557 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9558 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9559 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9560 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9561 Ops.push_back(V); 9562 } 9563 9564 return DAG.getBuildVector(VecVT, SL, Ops); 9565 } 9566 9567 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9568 const SDNode *N0, 9569 const SDNode *N1) const { 9570 EVT VT = N0->getValueType(0); 9571 9572 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9573 // support denormals ever. 9574 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9575 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9576 getSubtarget()->hasMadF16())) && 9577 isOperationLegal(ISD::FMAD, VT)) 9578 return ISD::FMAD; 9579 9580 const TargetOptions &Options = DAG.getTarget().Options; 9581 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9582 (N0->getFlags().hasAllowContract() && 9583 N1->getFlags().hasAllowContract())) && 9584 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 9585 return ISD::FMA; 9586 } 9587 9588 return 0; 9589 } 9590 9591 // For a reassociatable opcode perform: 9592 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9593 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9594 SelectionDAG &DAG) const { 9595 EVT VT = N->getValueType(0); 9596 if (VT != MVT::i32 && VT != MVT::i64) 9597 return SDValue(); 9598 9599 unsigned Opc = N->getOpcode(); 9600 SDValue Op0 = N->getOperand(0); 9601 SDValue Op1 = N->getOperand(1); 9602 9603 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9604 return SDValue(); 9605 9606 if (Op0->isDivergent()) 9607 std::swap(Op0, Op1); 9608 9609 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9610 return SDValue(); 9611 9612 SDValue Op2 = Op1.getOperand(1); 9613 Op1 = Op1.getOperand(0); 9614 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9615 return SDValue(); 9616 9617 if (Op1->isDivergent()) 9618 std::swap(Op1, Op2); 9619 9620 // If either operand is constant this will conflict with 9621 // DAGCombiner::ReassociateOps(). 9622 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9623 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9624 return SDValue(); 9625 9626 SDLoc SL(N); 9627 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9628 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9629 } 9630 9631 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9632 EVT VT, 9633 SDValue N0, SDValue N1, SDValue N2, 9634 bool Signed) { 9635 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9636 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9637 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 9638 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 9639 } 9640 9641 SDValue SITargetLowering::performAddCombine(SDNode *N, 9642 DAGCombinerInfo &DCI) const { 9643 SelectionDAG &DAG = DCI.DAG; 9644 EVT VT = N->getValueType(0); 9645 SDLoc SL(N); 9646 SDValue LHS = N->getOperand(0); 9647 SDValue RHS = N->getOperand(1); 9648 9649 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 9650 && Subtarget->hasMad64_32() && 9651 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 9652 VT.getScalarSizeInBits() <= 64) { 9653 if (LHS.getOpcode() != ISD::MUL) 9654 std::swap(LHS, RHS); 9655 9656 SDValue MulLHS = LHS.getOperand(0); 9657 SDValue MulRHS = LHS.getOperand(1); 9658 SDValue AddRHS = RHS; 9659 9660 // TODO: Maybe restrict if SGPR inputs. 9661 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 9662 numBitsUnsigned(MulRHS, DAG) <= 32) { 9663 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 9664 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 9665 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 9666 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 9667 } 9668 9669 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 9670 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 9671 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 9672 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 9673 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 9674 } 9675 9676 return SDValue(); 9677 } 9678 9679 if (SDValue V = reassociateScalarOps(N, DAG)) { 9680 return V; 9681 } 9682 9683 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 9684 return SDValue(); 9685 9686 // add x, zext (setcc) => addcarry x, 0, setcc 9687 // add x, sext (setcc) => subcarry x, 0, setcc 9688 unsigned Opc = LHS.getOpcode(); 9689 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9690 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 9691 std::swap(RHS, LHS); 9692 9693 Opc = RHS.getOpcode(); 9694 switch (Opc) { 9695 default: break; 9696 case ISD::ZERO_EXTEND: 9697 case ISD::SIGN_EXTEND: 9698 case ISD::ANY_EXTEND: { 9699 auto Cond = RHS.getOperand(0); 9700 // If this won't be a real VOPC output, we would still need to insert an 9701 // extra instruction anyway. 9702 if (!isBoolSGPR(Cond)) 9703 break; 9704 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9705 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9706 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9707 return DAG.getNode(Opc, SL, VTList, Args); 9708 } 9709 case ISD::ADDCARRY: { 9710 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 9711 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9712 if (!C || C->getZExtValue() != 0) break; 9713 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 9714 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 9715 } 9716 } 9717 return SDValue(); 9718 } 9719 9720 SDValue SITargetLowering::performSubCombine(SDNode *N, 9721 DAGCombinerInfo &DCI) const { 9722 SelectionDAG &DAG = DCI.DAG; 9723 EVT VT = N->getValueType(0); 9724 9725 if (VT != MVT::i32) 9726 return SDValue(); 9727 9728 SDLoc SL(N); 9729 SDValue LHS = N->getOperand(0); 9730 SDValue RHS = N->getOperand(1); 9731 9732 // sub x, zext (setcc) => subcarry x, 0, setcc 9733 // sub x, sext (setcc) => addcarry x, 0, setcc 9734 unsigned Opc = RHS.getOpcode(); 9735 switch (Opc) { 9736 default: break; 9737 case ISD::ZERO_EXTEND: 9738 case ISD::SIGN_EXTEND: 9739 case ISD::ANY_EXTEND: { 9740 auto Cond = RHS.getOperand(0); 9741 // If this won't be a real VOPC output, we would still need to insert an 9742 // extra instruction anyway. 9743 if (!isBoolSGPR(Cond)) 9744 break; 9745 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9746 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9747 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 9748 return DAG.getNode(Opc, SL, VTList, Args); 9749 } 9750 } 9751 9752 if (LHS.getOpcode() == ISD::SUBCARRY) { 9753 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 9754 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9755 if (!C || !C->isNullValue()) 9756 return SDValue(); 9757 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 9758 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 9759 } 9760 return SDValue(); 9761 } 9762 9763 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 9764 DAGCombinerInfo &DCI) const { 9765 9766 if (N->getValueType(0) != MVT::i32) 9767 return SDValue(); 9768 9769 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9770 if (!C || C->getZExtValue() != 0) 9771 return SDValue(); 9772 9773 SelectionDAG &DAG = DCI.DAG; 9774 SDValue LHS = N->getOperand(0); 9775 9776 // addcarry (add x, y), 0, cc => addcarry x, y, cc 9777 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 9778 unsigned LHSOpc = LHS.getOpcode(); 9779 unsigned Opc = N->getOpcode(); 9780 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 9781 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 9782 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 9783 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 9784 } 9785 return SDValue(); 9786 } 9787 9788 SDValue SITargetLowering::performFAddCombine(SDNode *N, 9789 DAGCombinerInfo &DCI) const { 9790 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9791 return SDValue(); 9792 9793 SelectionDAG &DAG = DCI.DAG; 9794 EVT VT = N->getValueType(0); 9795 9796 SDLoc SL(N); 9797 SDValue LHS = N->getOperand(0); 9798 SDValue RHS = N->getOperand(1); 9799 9800 // These should really be instruction patterns, but writing patterns with 9801 // source modiifiers is a pain. 9802 9803 // fadd (fadd (a, a), b) -> mad 2.0, a, b 9804 if (LHS.getOpcode() == ISD::FADD) { 9805 SDValue A = LHS.getOperand(0); 9806 if (A == LHS.getOperand(1)) { 9807 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9808 if (FusedOp != 0) { 9809 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9810 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 9811 } 9812 } 9813 } 9814 9815 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 9816 if (RHS.getOpcode() == ISD::FADD) { 9817 SDValue A = RHS.getOperand(0); 9818 if (A == RHS.getOperand(1)) { 9819 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9820 if (FusedOp != 0) { 9821 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9822 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 9823 } 9824 } 9825 } 9826 9827 return SDValue(); 9828 } 9829 9830 SDValue SITargetLowering::performFSubCombine(SDNode *N, 9831 DAGCombinerInfo &DCI) const { 9832 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9833 return SDValue(); 9834 9835 SelectionDAG &DAG = DCI.DAG; 9836 SDLoc SL(N); 9837 EVT VT = N->getValueType(0); 9838 assert(!VT.isVector()); 9839 9840 // Try to get the fneg to fold into the source modifier. This undoes generic 9841 // DAG combines and folds them into the mad. 9842 // 9843 // Only do this if we are not trying to support denormals. v_mad_f32 does 9844 // not support denormals ever. 9845 SDValue LHS = N->getOperand(0); 9846 SDValue RHS = N->getOperand(1); 9847 if (LHS.getOpcode() == ISD::FADD) { 9848 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 9849 SDValue A = LHS.getOperand(0); 9850 if (A == LHS.getOperand(1)) { 9851 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9852 if (FusedOp != 0){ 9853 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9854 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 9855 9856 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 9857 } 9858 } 9859 } 9860 9861 if (RHS.getOpcode() == ISD::FADD) { 9862 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 9863 9864 SDValue A = RHS.getOperand(0); 9865 if (A == RHS.getOperand(1)) { 9866 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9867 if (FusedOp != 0){ 9868 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 9869 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 9870 } 9871 } 9872 } 9873 9874 return SDValue(); 9875 } 9876 9877 SDValue SITargetLowering::performFMACombine(SDNode *N, 9878 DAGCombinerInfo &DCI) const { 9879 SelectionDAG &DAG = DCI.DAG; 9880 EVT VT = N->getValueType(0); 9881 SDLoc SL(N); 9882 9883 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 9884 return SDValue(); 9885 9886 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 9887 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 9888 SDValue Op1 = N->getOperand(0); 9889 SDValue Op2 = N->getOperand(1); 9890 SDValue FMA = N->getOperand(2); 9891 9892 if (FMA.getOpcode() != ISD::FMA || 9893 Op1.getOpcode() != ISD::FP_EXTEND || 9894 Op2.getOpcode() != ISD::FP_EXTEND) 9895 return SDValue(); 9896 9897 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 9898 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 9899 // is sufficient to allow generaing fdot2. 9900 const TargetOptions &Options = DAG.getTarget().Options; 9901 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9902 (N->getFlags().hasAllowContract() && 9903 FMA->getFlags().hasAllowContract())) { 9904 Op1 = Op1.getOperand(0); 9905 Op2 = Op2.getOperand(0); 9906 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9907 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9908 return SDValue(); 9909 9910 SDValue Vec1 = Op1.getOperand(0); 9911 SDValue Idx1 = Op1.getOperand(1); 9912 SDValue Vec2 = Op2.getOperand(0); 9913 9914 SDValue FMAOp1 = FMA.getOperand(0); 9915 SDValue FMAOp2 = FMA.getOperand(1); 9916 SDValue FMAAcc = FMA.getOperand(2); 9917 9918 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 9919 FMAOp2.getOpcode() != ISD::FP_EXTEND) 9920 return SDValue(); 9921 9922 FMAOp1 = FMAOp1.getOperand(0); 9923 FMAOp2 = FMAOp2.getOperand(0); 9924 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9925 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9926 return SDValue(); 9927 9928 SDValue Vec3 = FMAOp1.getOperand(0); 9929 SDValue Vec4 = FMAOp2.getOperand(0); 9930 SDValue Idx2 = FMAOp1.getOperand(1); 9931 9932 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 9933 // Idx1 and Idx2 cannot be the same. 9934 Idx1 == Idx2) 9935 return SDValue(); 9936 9937 if (Vec1 == Vec2 || Vec3 == Vec4) 9938 return SDValue(); 9939 9940 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 9941 return SDValue(); 9942 9943 if ((Vec1 == Vec3 && Vec2 == Vec4) || 9944 (Vec1 == Vec4 && Vec2 == Vec3)) { 9945 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 9946 DAG.getTargetConstant(0, SL, MVT::i1)); 9947 } 9948 } 9949 return SDValue(); 9950 } 9951 9952 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 9953 DAGCombinerInfo &DCI) const { 9954 SelectionDAG &DAG = DCI.DAG; 9955 SDLoc SL(N); 9956 9957 SDValue LHS = N->getOperand(0); 9958 SDValue RHS = N->getOperand(1); 9959 EVT VT = LHS.getValueType(); 9960 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 9961 9962 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 9963 if (!CRHS) { 9964 CRHS = dyn_cast<ConstantSDNode>(LHS); 9965 if (CRHS) { 9966 std::swap(LHS, RHS); 9967 CC = getSetCCSwappedOperands(CC); 9968 } 9969 } 9970 9971 if (CRHS) { 9972 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 9973 isBoolSGPR(LHS.getOperand(0))) { 9974 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 9975 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 9976 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 9977 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 9978 if ((CRHS->isAllOnesValue() && 9979 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 9980 (CRHS->isNullValue() && 9981 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 9982 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9983 DAG.getConstant(-1, SL, MVT::i1)); 9984 if ((CRHS->isAllOnesValue() && 9985 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 9986 (CRHS->isNullValue() && 9987 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 9988 return LHS.getOperand(0); 9989 } 9990 9991 uint64_t CRHSVal = CRHS->getZExtValue(); 9992 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 9993 LHS.getOpcode() == ISD::SELECT && 9994 isa<ConstantSDNode>(LHS.getOperand(1)) && 9995 isa<ConstantSDNode>(LHS.getOperand(2)) && 9996 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 9997 isBoolSGPR(LHS.getOperand(0))) { 9998 // Given CT != FT: 9999 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10000 // setcc (select cc, CT, CF), CF, ne => cc 10001 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10002 // setcc (select cc, CT, CF), CT, eq => cc 10003 uint64_t CT = LHS.getConstantOperandVal(1); 10004 uint64_t CF = LHS.getConstantOperandVal(2); 10005 10006 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10007 (CT == CRHSVal && CC == ISD::SETNE)) 10008 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10009 DAG.getConstant(-1, SL, MVT::i1)); 10010 if ((CF == CRHSVal && CC == ISD::SETNE) || 10011 (CT == CRHSVal && CC == ISD::SETEQ)) 10012 return LHS.getOperand(0); 10013 } 10014 } 10015 10016 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10017 VT != MVT::f16)) 10018 return SDValue(); 10019 10020 // Match isinf/isfinite pattern 10021 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10022 // (fcmp one (fabs x), inf) -> (fp_class x, 10023 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10024 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10025 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10026 if (!CRHS) 10027 return SDValue(); 10028 10029 const APFloat &APF = CRHS->getValueAPF(); 10030 if (APF.isInfinity() && !APF.isNegative()) { 10031 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10032 SIInstrFlags::N_INFINITY; 10033 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10034 SIInstrFlags::P_ZERO | 10035 SIInstrFlags::N_NORMAL | 10036 SIInstrFlags::P_NORMAL | 10037 SIInstrFlags::N_SUBNORMAL | 10038 SIInstrFlags::P_SUBNORMAL; 10039 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10040 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10041 DAG.getConstant(Mask, SL, MVT::i32)); 10042 } 10043 } 10044 10045 return SDValue(); 10046 } 10047 10048 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10049 DAGCombinerInfo &DCI) const { 10050 SelectionDAG &DAG = DCI.DAG; 10051 SDLoc SL(N); 10052 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10053 10054 SDValue Src = N->getOperand(0); 10055 SDValue Shift = N->getOperand(0); 10056 10057 // TODO: Extend type shouldn't matter (assuming legal types). 10058 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10059 Shift = Shift.getOperand(0); 10060 10061 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10062 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10063 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10064 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10065 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10066 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10067 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10068 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10069 SDLoc(Shift.getOperand(0)), MVT::i32); 10070 10071 unsigned ShiftOffset = 8 * Offset; 10072 if (Shift.getOpcode() == ISD::SHL) 10073 ShiftOffset -= C->getZExtValue(); 10074 else 10075 ShiftOffset += C->getZExtValue(); 10076 10077 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10078 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10079 MVT::f32, Shift); 10080 } 10081 } 10082 } 10083 10084 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10085 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10086 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10087 // We simplified Src. If this node is not dead, visit it again so it is 10088 // folded properly. 10089 if (N->getOpcode() != ISD::DELETED_NODE) 10090 DCI.AddToWorklist(N); 10091 return SDValue(N, 0); 10092 } 10093 10094 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10095 if (SDValue DemandedSrc = 10096 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10097 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10098 10099 return SDValue(); 10100 } 10101 10102 SDValue SITargetLowering::performClampCombine(SDNode *N, 10103 DAGCombinerInfo &DCI) const { 10104 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10105 if (!CSrc) 10106 return SDValue(); 10107 10108 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10109 const APFloat &F = CSrc->getValueAPF(); 10110 APFloat Zero = APFloat::getZero(F.getSemantics()); 10111 if (F < Zero || 10112 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10113 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10114 } 10115 10116 APFloat One(F.getSemantics(), "1.0"); 10117 if (F > One) 10118 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10119 10120 return SDValue(CSrc, 0); 10121 } 10122 10123 10124 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10125 DAGCombinerInfo &DCI) const { 10126 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10127 return SDValue(); 10128 switch (N->getOpcode()) { 10129 default: 10130 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10131 case ISD::ADD: 10132 return performAddCombine(N, DCI); 10133 case ISD::SUB: 10134 return performSubCombine(N, DCI); 10135 case ISD::ADDCARRY: 10136 case ISD::SUBCARRY: 10137 return performAddCarrySubCarryCombine(N, DCI); 10138 case ISD::FADD: 10139 return performFAddCombine(N, DCI); 10140 case ISD::FSUB: 10141 return performFSubCombine(N, DCI); 10142 case ISD::SETCC: 10143 return performSetCCCombine(N, DCI); 10144 case ISD::FMAXNUM: 10145 case ISD::FMINNUM: 10146 case ISD::FMAXNUM_IEEE: 10147 case ISD::FMINNUM_IEEE: 10148 case ISD::SMAX: 10149 case ISD::SMIN: 10150 case ISD::UMAX: 10151 case ISD::UMIN: 10152 case AMDGPUISD::FMIN_LEGACY: 10153 case AMDGPUISD::FMAX_LEGACY: 10154 return performMinMaxCombine(N, DCI); 10155 case ISD::FMA: 10156 return performFMACombine(N, DCI); 10157 case ISD::LOAD: { 10158 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10159 return Widended; 10160 LLVM_FALLTHROUGH; 10161 } 10162 case ISD::STORE: 10163 case ISD::ATOMIC_LOAD: 10164 case ISD::ATOMIC_STORE: 10165 case ISD::ATOMIC_CMP_SWAP: 10166 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 10167 case ISD::ATOMIC_SWAP: 10168 case ISD::ATOMIC_LOAD_ADD: 10169 case ISD::ATOMIC_LOAD_SUB: 10170 case ISD::ATOMIC_LOAD_AND: 10171 case ISD::ATOMIC_LOAD_OR: 10172 case ISD::ATOMIC_LOAD_XOR: 10173 case ISD::ATOMIC_LOAD_NAND: 10174 case ISD::ATOMIC_LOAD_MIN: 10175 case ISD::ATOMIC_LOAD_MAX: 10176 case ISD::ATOMIC_LOAD_UMIN: 10177 case ISD::ATOMIC_LOAD_UMAX: 10178 case ISD::ATOMIC_LOAD_FADD: 10179 case AMDGPUISD::ATOMIC_INC: 10180 case AMDGPUISD::ATOMIC_DEC: 10181 case AMDGPUISD::ATOMIC_LOAD_FMIN: 10182 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 10183 if (DCI.isBeforeLegalize()) 10184 break; 10185 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 10186 case ISD::AND: 10187 return performAndCombine(N, DCI); 10188 case ISD::OR: 10189 return performOrCombine(N, DCI); 10190 case ISD::XOR: 10191 return performXorCombine(N, DCI); 10192 case ISD::ZERO_EXTEND: 10193 return performZeroExtendCombine(N, DCI); 10194 case ISD::SIGN_EXTEND_INREG: 10195 return performSignExtendInRegCombine(N , DCI); 10196 case AMDGPUISD::FP_CLASS: 10197 return performClassCombine(N, DCI); 10198 case ISD::FCANONICALIZE: 10199 return performFCanonicalizeCombine(N, DCI); 10200 case AMDGPUISD::RCP: 10201 return performRcpCombine(N, DCI); 10202 case AMDGPUISD::FRACT: 10203 case AMDGPUISD::RSQ: 10204 case AMDGPUISD::RCP_LEGACY: 10205 case AMDGPUISD::RCP_IFLAG: 10206 case AMDGPUISD::RSQ_CLAMP: 10207 case AMDGPUISD::LDEXP: { 10208 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10209 SDValue Src = N->getOperand(0); 10210 if (Src.isUndef()) 10211 return Src; 10212 break; 10213 } 10214 case ISD::SINT_TO_FP: 10215 case ISD::UINT_TO_FP: 10216 return performUCharToFloatCombine(N, DCI); 10217 case AMDGPUISD::CVT_F32_UBYTE0: 10218 case AMDGPUISD::CVT_F32_UBYTE1: 10219 case AMDGPUISD::CVT_F32_UBYTE2: 10220 case AMDGPUISD::CVT_F32_UBYTE3: 10221 return performCvtF32UByteNCombine(N, DCI); 10222 case AMDGPUISD::FMED3: 10223 return performFMed3Combine(N, DCI); 10224 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10225 return performCvtPkRTZCombine(N, DCI); 10226 case AMDGPUISD::CLAMP: 10227 return performClampCombine(N, DCI); 10228 case ISD::SCALAR_TO_VECTOR: { 10229 SelectionDAG &DAG = DCI.DAG; 10230 EVT VT = N->getValueType(0); 10231 10232 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10233 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10234 SDLoc SL(N); 10235 SDValue Src = N->getOperand(0); 10236 EVT EltVT = Src.getValueType(); 10237 if (EltVT == MVT::f16) 10238 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10239 10240 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10241 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10242 } 10243 10244 break; 10245 } 10246 case ISD::EXTRACT_VECTOR_ELT: 10247 return performExtractVectorEltCombine(N, DCI); 10248 case ISD::INSERT_VECTOR_ELT: 10249 return performInsertVectorEltCombine(N, DCI); 10250 } 10251 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10252 } 10253 10254 /// Helper function for adjustWritemask 10255 static unsigned SubIdx2Lane(unsigned Idx) { 10256 switch (Idx) { 10257 default: return 0; 10258 case AMDGPU::sub0: return 0; 10259 case AMDGPU::sub1: return 1; 10260 case AMDGPU::sub2: return 2; 10261 case AMDGPU::sub3: return 3; 10262 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10263 } 10264 } 10265 10266 /// Adjust the writemask of MIMG instructions 10267 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10268 SelectionDAG &DAG) const { 10269 unsigned Opcode = Node->getMachineOpcode(); 10270 10271 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10272 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10273 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10274 return Node; // not implemented for D16 10275 10276 SDNode *Users[5] = { nullptr }; 10277 unsigned Lane = 0; 10278 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10279 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10280 unsigned NewDmask = 0; 10281 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10282 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10283 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10284 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10285 unsigned TFCLane = 0; 10286 bool HasChain = Node->getNumValues() > 1; 10287 10288 if (OldDmask == 0) { 10289 // These are folded out, but on the chance it happens don't assert. 10290 return Node; 10291 } 10292 10293 unsigned OldBitsSet = countPopulation(OldDmask); 10294 // Work out which is the TFE/LWE lane if that is enabled. 10295 if (UsesTFC) { 10296 TFCLane = OldBitsSet; 10297 } 10298 10299 // Try to figure out the used register components 10300 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10301 I != E; ++I) { 10302 10303 // Don't look at users of the chain. 10304 if (I.getUse().getResNo() != 0) 10305 continue; 10306 10307 // Abort if we can't understand the usage 10308 if (!I->isMachineOpcode() || 10309 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10310 return Node; 10311 10312 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10313 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10314 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10315 // set, etc. 10316 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10317 10318 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10319 if (UsesTFC && Lane == TFCLane) { 10320 Users[Lane] = *I; 10321 } else { 10322 // Set which texture component corresponds to the lane. 10323 unsigned Comp; 10324 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10325 Comp = countTrailingZeros(Dmask); 10326 Dmask &= ~(1 << Comp); 10327 } 10328 10329 // Abort if we have more than one user per component. 10330 if (Users[Lane]) 10331 return Node; 10332 10333 Users[Lane] = *I; 10334 NewDmask |= 1 << Comp; 10335 } 10336 } 10337 10338 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10339 bool NoChannels = !NewDmask; 10340 if (NoChannels) { 10341 if (!UsesTFC) { 10342 // No uses of the result and not using TFC. Then do nothing. 10343 return Node; 10344 } 10345 // If the original dmask has one channel - then nothing to do 10346 if (OldBitsSet == 1) 10347 return Node; 10348 // Use an arbitrary dmask - required for the instruction to work 10349 NewDmask = 1; 10350 } 10351 // Abort if there's no change 10352 if (NewDmask == OldDmask) 10353 return Node; 10354 10355 unsigned BitsSet = countPopulation(NewDmask); 10356 10357 // Check for TFE or LWE - increase the number of channels by one to account 10358 // for the extra return value 10359 // This will need adjustment for D16 if this is also included in 10360 // adjustWriteMask (this function) but at present D16 are excluded. 10361 unsigned NewChannels = BitsSet + UsesTFC; 10362 10363 int NewOpcode = 10364 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10365 assert(NewOpcode != -1 && 10366 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10367 "failed to find equivalent MIMG op"); 10368 10369 // Adjust the writemask in the node 10370 SmallVector<SDValue, 12> Ops; 10371 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10372 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10373 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10374 10375 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10376 10377 MVT ResultVT = NewChannels == 1 ? 10378 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10379 NewChannels == 5 ? 8 : NewChannels); 10380 SDVTList NewVTList = HasChain ? 10381 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10382 10383 10384 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10385 NewVTList, Ops); 10386 10387 if (HasChain) { 10388 // Update chain. 10389 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10390 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10391 } 10392 10393 if (NewChannels == 1) { 10394 assert(Node->hasNUsesOfValue(1, 0)); 10395 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10396 SDLoc(Node), Users[Lane]->getValueType(0), 10397 SDValue(NewNode, 0)); 10398 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10399 return nullptr; 10400 } 10401 10402 // Update the users of the node with the new indices 10403 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10404 SDNode *User = Users[i]; 10405 if (!User) { 10406 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10407 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10408 if (i || !NoChannels) 10409 continue; 10410 } else { 10411 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10412 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10413 } 10414 10415 switch (Idx) { 10416 default: break; 10417 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10418 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10419 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10420 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10421 } 10422 } 10423 10424 DAG.RemoveDeadNode(Node); 10425 return nullptr; 10426 } 10427 10428 static bool isFrameIndexOp(SDValue Op) { 10429 if (Op.getOpcode() == ISD::AssertZext) 10430 Op = Op.getOperand(0); 10431 10432 return isa<FrameIndexSDNode>(Op); 10433 } 10434 10435 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10436 /// with frame index operands. 10437 /// LLVM assumes that inputs are to these instructions are registers. 10438 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10439 SelectionDAG &DAG) const { 10440 if (Node->getOpcode() == ISD::CopyToReg) { 10441 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10442 SDValue SrcVal = Node->getOperand(2); 10443 10444 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10445 // to try understanding copies to physical registers. 10446 if (SrcVal.getValueType() == MVT::i1 && 10447 Register::isPhysicalRegister(DestReg->getReg())) { 10448 SDLoc SL(Node); 10449 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10450 SDValue VReg = DAG.getRegister( 10451 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10452 10453 SDNode *Glued = Node->getGluedNode(); 10454 SDValue ToVReg 10455 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10456 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10457 SDValue ToResultReg 10458 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10459 VReg, ToVReg.getValue(1)); 10460 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10461 DAG.RemoveDeadNode(Node); 10462 return ToResultReg.getNode(); 10463 } 10464 } 10465 10466 SmallVector<SDValue, 8> Ops; 10467 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10468 if (!isFrameIndexOp(Node->getOperand(i))) { 10469 Ops.push_back(Node->getOperand(i)); 10470 continue; 10471 } 10472 10473 SDLoc DL(Node); 10474 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10475 Node->getOperand(i).getValueType(), 10476 Node->getOperand(i)), 0)); 10477 } 10478 10479 return DAG.UpdateNodeOperands(Node, Ops); 10480 } 10481 10482 /// Fold the instructions after selecting them. 10483 /// Returns null if users were already updated. 10484 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10485 SelectionDAG &DAG) const { 10486 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10487 unsigned Opcode = Node->getMachineOpcode(); 10488 10489 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10490 !TII->isGather4(Opcode)) { 10491 return adjustWritemask(Node, DAG); 10492 } 10493 10494 if (Opcode == AMDGPU::INSERT_SUBREG || 10495 Opcode == AMDGPU::REG_SEQUENCE) { 10496 legalizeTargetIndependentNode(Node, DAG); 10497 return Node; 10498 } 10499 10500 switch (Opcode) { 10501 case AMDGPU::V_DIV_SCALE_F32: 10502 case AMDGPU::V_DIV_SCALE_F64: { 10503 // Satisfy the operand register constraint when one of the inputs is 10504 // undefined. Ordinarily each undef value will have its own implicit_def of 10505 // a vreg, so force these to use a single register. 10506 SDValue Src0 = Node->getOperand(0); 10507 SDValue Src1 = Node->getOperand(1); 10508 SDValue Src2 = Node->getOperand(2); 10509 10510 if ((Src0.isMachineOpcode() && 10511 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10512 (Src0 == Src1 || Src0 == Src2)) 10513 break; 10514 10515 MVT VT = Src0.getValueType().getSimpleVT(); 10516 const TargetRegisterClass *RC = 10517 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10518 10519 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10520 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10521 10522 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10523 UndefReg, Src0, SDValue()); 10524 10525 // src0 must be the same register as src1 or src2, even if the value is 10526 // undefined, so make sure we don't violate this constraint. 10527 if (Src0.isMachineOpcode() && 10528 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10529 if (Src1.isMachineOpcode() && 10530 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10531 Src0 = Src1; 10532 else if (Src2.isMachineOpcode() && 10533 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10534 Src0 = Src2; 10535 else { 10536 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10537 Src0 = UndefReg; 10538 Src1 = UndefReg; 10539 } 10540 } else 10541 break; 10542 10543 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10544 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10545 Ops.push_back(Node->getOperand(I)); 10546 10547 Ops.push_back(ImpDef.getValue(1)); 10548 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10549 } 10550 default: 10551 break; 10552 } 10553 10554 return Node; 10555 } 10556 10557 /// Assign the register class depending on the number of 10558 /// bits set in the writemask 10559 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10560 SDNode *Node) const { 10561 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10562 10563 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10564 10565 if (TII->isVOP3(MI.getOpcode())) { 10566 // Make sure constant bus requirements are respected. 10567 TII->legalizeOperandsVOP3(MRI, MI); 10568 10569 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10570 // This saves a chain-copy of registers and better ballance register 10571 // use between vgpr and agpr as agpr tuples tend to be big. 10572 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10573 unsigned Opc = MI.getOpcode(); 10574 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10575 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10576 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10577 if (I == -1) 10578 break; 10579 MachineOperand &Op = MI.getOperand(I); 10580 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10581 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10582 !Register::isVirtualRegister(Op.getReg()) || 10583 !TRI->isAGPR(MRI, Op.getReg())) 10584 continue; 10585 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10586 if (!Src || !Src->isCopy() || 10587 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10588 continue; 10589 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10590 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10591 // All uses of agpr64 and agpr32 can also accept vgpr except for 10592 // v_accvgpr_read, but we do not produce agpr reads during selection, 10593 // so no use checks are needed. 10594 MRI.setRegClass(Op.getReg(), NewRC); 10595 } 10596 } 10597 10598 return; 10599 } 10600 10601 // Replace unused atomics with the no return version. 10602 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10603 if (NoRetAtomicOp != -1) { 10604 if (!Node->hasAnyUseOfValue(0)) { 10605 MI.setDesc(TII->get(NoRetAtomicOp)); 10606 MI.RemoveOperand(0); 10607 return; 10608 } 10609 10610 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10611 // instruction, because the return type of these instructions is a vec2 of 10612 // the memory type, so it can be tied to the input operand. 10613 // This means these instructions always have a use, so we need to add a 10614 // special case to check if the atomic has only one extract_subreg use, 10615 // which itself has no uses. 10616 if ((Node->hasNUsesOfValue(1, 0) && 10617 Node->use_begin()->isMachineOpcode() && 10618 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10619 !Node->use_begin()->hasAnyUseOfValue(0))) { 10620 Register Def = MI.getOperand(0).getReg(); 10621 10622 // Change this into a noret atomic. 10623 MI.setDesc(TII->get(NoRetAtomicOp)); 10624 MI.RemoveOperand(0); 10625 10626 // If we only remove the def operand from the atomic instruction, the 10627 // extract_subreg will be left with a use of a vreg without a def. 10628 // So we need to insert an implicit_def to avoid machine verifier 10629 // errors. 10630 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10631 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10632 } 10633 return; 10634 } 10635 } 10636 10637 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 10638 uint64_t Val) { 10639 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 10640 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 10641 } 10642 10643 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 10644 const SDLoc &DL, 10645 SDValue Ptr) const { 10646 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10647 10648 // Build the half of the subregister with the constants before building the 10649 // full 128-bit register. If we are building multiple resource descriptors, 10650 // this will allow CSEing of the 2-component register. 10651 const SDValue Ops0[] = { 10652 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 10653 buildSMovImm32(DAG, DL, 0), 10654 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10655 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 10656 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 10657 }; 10658 10659 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 10660 MVT::v2i32, Ops0), 0); 10661 10662 // Combine the constants and the pointer. 10663 const SDValue Ops1[] = { 10664 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10665 Ptr, 10666 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 10667 SubRegHi, 10668 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 10669 }; 10670 10671 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 10672 } 10673 10674 /// Return a resource descriptor with the 'Add TID' bit enabled 10675 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 10676 /// of the resource descriptor) to create an offset, which is added to 10677 /// the resource pointer. 10678 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 10679 SDValue Ptr, uint32_t RsrcDword1, 10680 uint64_t RsrcDword2And3) const { 10681 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 10682 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 10683 if (RsrcDword1) { 10684 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 10685 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 10686 0); 10687 } 10688 10689 SDValue DataLo = buildSMovImm32(DAG, DL, 10690 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 10691 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 10692 10693 const SDValue Ops[] = { 10694 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10695 PtrLo, 10696 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10697 PtrHi, 10698 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 10699 DataLo, 10700 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 10701 DataHi, 10702 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 10703 }; 10704 10705 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 10706 } 10707 10708 //===----------------------------------------------------------------------===// 10709 // SI Inline Assembly Support 10710 //===----------------------------------------------------------------------===// 10711 10712 std::pair<unsigned, const TargetRegisterClass *> 10713 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10714 StringRef Constraint, 10715 MVT VT) const { 10716 const TargetRegisterClass *RC = nullptr; 10717 if (Constraint.size() == 1) { 10718 const unsigned BitWidth = VT.getSizeInBits(); 10719 switch (Constraint[0]) { 10720 default: 10721 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10722 case 's': 10723 case 'r': 10724 switch (BitWidth) { 10725 case 16: 10726 RC = &AMDGPU::SReg_32RegClass; 10727 break; 10728 case 64: 10729 RC = &AMDGPU::SGPR_64RegClass; 10730 break; 10731 default: 10732 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 10733 if (!RC) 10734 return std::make_pair(0U, nullptr); 10735 break; 10736 } 10737 break; 10738 case 'v': 10739 switch (BitWidth) { 10740 case 16: 10741 RC = &AMDGPU::VGPR_32RegClass; 10742 break; 10743 default: 10744 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 10745 if (!RC) 10746 return std::make_pair(0U, nullptr); 10747 break; 10748 } 10749 break; 10750 case 'a': 10751 if (!Subtarget->hasMAIInsts()) 10752 break; 10753 switch (BitWidth) { 10754 case 16: 10755 RC = &AMDGPU::AGPR_32RegClass; 10756 break; 10757 default: 10758 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 10759 if (!RC) 10760 return std::make_pair(0U, nullptr); 10761 break; 10762 } 10763 break; 10764 } 10765 // We actually support i128, i16 and f16 as inline parameters 10766 // even if they are not reported as legal 10767 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 10768 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 10769 return std::make_pair(0U, RC); 10770 } 10771 10772 if (Constraint.size() > 1) { 10773 if (Constraint[1] == 'v') { 10774 RC = &AMDGPU::VGPR_32RegClass; 10775 } else if (Constraint[1] == 's') { 10776 RC = &AMDGPU::SGPR_32RegClass; 10777 } else if (Constraint[1] == 'a') { 10778 RC = &AMDGPU::AGPR_32RegClass; 10779 } 10780 10781 if (RC) { 10782 uint32_t Idx; 10783 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 10784 if (!Failed && Idx < RC->getNumRegs()) 10785 return std::make_pair(RC->getRegister(Idx), RC); 10786 } 10787 } 10788 10789 // FIXME: Returns VS_32 for physical SGPR constraints 10790 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10791 } 10792 10793 SITargetLowering::ConstraintType 10794 SITargetLowering::getConstraintType(StringRef Constraint) const { 10795 if (Constraint.size() == 1) { 10796 switch (Constraint[0]) { 10797 default: break; 10798 case 's': 10799 case 'v': 10800 case 'a': 10801 return C_RegisterClass; 10802 } 10803 } 10804 return TargetLowering::getConstraintType(Constraint); 10805 } 10806 10807 // Figure out which registers should be reserved for stack access. Only after 10808 // the function is legalized do we know all of the non-spill stack objects or if 10809 // calls are present. 10810 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 10811 MachineRegisterInfo &MRI = MF.getRegInfo(); 10812 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10813 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 10814 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10815 10816 if (Info->isEntryFunction()) { 10817 // Callable functions have fixed registers used for stack access. 10818 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 10819 } 10820 10821 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 10822 Info->getStackPtrOffsetReg())); 10823 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 10824 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 10825 10826 // We need to worry about replacing the default register with itself in case 10827 // of MIR testcases missing the MFI. 10828 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 10829 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 10830 10831 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 10832 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 10833 10834 Info->limitOccupancy(MF); 10835 10836 if (ST.isWave32() && !MF.empty()) { 10837 // Add VCC_HI def because many instructions marked as imp-use VCC where 10838 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 10839 // having a use of undef. 10840 10841 const SIInstrInfo *TII = ST.getInstrInfo(); 10842 DebugLoc DL; 10843 10844 MachineBasicBlock &MBB = MF.front(); 10845 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 10846 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 10847 10848 for (auto &MBB : MF) { 10849 for (auto &MI : MBB) { 10850 TII->fixImplicitOperands(MI); 10851 } 10852 } 10853 } 10854 10855 TargetLoweringBase::finalizeLowering(MF); 10856 } 10857 10858 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 10859 KnownBits &Known, 10860 const APInt &DemandedElts, 10861 const SelectionDAG &DAG, 10862 unsigned Depth) const { 10863 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 10864 DAG, Depth); 10865 10866 // Set the high bits to zero based on the maximum allowed scratch size per 10867 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 10868 // calculation won't overflow, so assume the sign bit is never set. 10869 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 10870 } 10871 10872 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 10873 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 10874 const Align CacheLineAlign = Align(64); 10875 10876 // Pre-GFX10 target did not benefit from loop alignment 10877 if (!ML || DisableLoopAlignment || 10878 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 10879 getSubtarget()->hasInstFwdPrefetchBug()) 10880 return PrefAlign; 10881 10882 // On GFX10 I$ is 4 x 64 bytes cache lines. 10883 // By default prefetcher keeps one cache line behind and reads two ahead. 10884 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 10885 // behind and one ahead. 10886 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 10887 // If loop fits 64 bytes it always spans no more than two cache lines and 10888 // does not need an alignment. 10889 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 10890 // Else if loop is less or equal 192 bytes we need two lines behind. 10891 10892 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10893 const MachineBasicBlock *Header = ML->getHeader(); 10894 if (Header->getAlignment() != PrefAlign) 10895 return Header->getAlignment(); // Already processed. 10896 10897 unsigned LoopSize = 0; 10898 for (const MachineBasicBlock *MBB : ML->blocks()) { 10899 // If inner loop block is aligned assume in average half of the alignment 10900 // size to be added as nops. 10901 if (MBB != Header) 10902 LoopSize += MBB->getAlignment().value() / 2; 10903 10904 for (const MachineInstr &MI : *MBB) { 10905 LoopSize += TII->getInstSizeInBytes(MI); 10906 if (LoopSize > 192) 10907 return PrefAlign; 10908 } 10909 } 10910 10911 if (LoopSize <= 64) 10912 return PrefAlign; 10913 10914 if (LoopSize <= 128) 10915 return CacheLineAlign; 10916 10917 // If any of parent loops is surrounded by prefetch instructions do not 10918 // insert new for inner loop, which would reset parent's settings. 10919 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 10920 if (MachineBasicBlock *Exit = P->getExitBlock()) { 10921 auto I = Exit->getFirstNonDebugInstr(); 10922 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 10923 return CacheLineAlign; 10924 } 10925 } 10926 10927 MachineBasicBlock *Pre = ML->getLoopPreheader(); 10928 MachineBasicBlock *Exit = ML->getExitBlock(); 10929 10930 if (Pre && Exit) { 10931 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 10932 TII->get(AMDGPU::S_INST_PREFETCH)) 10933 .addImm(1); // prefetch 2 lines behind PC 10934 10935 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 10936 TII->get(AMDGPU::S_INST_PREFETCH)) 10937 .addImm(2); // prefetch 1 line behind PC 10938 } 10939 10940 return CacheLineAlign; 10941 } 10942 10943 LLVM_ATTRIBUTE_UNUSED 10944 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 10945 assert(N->getOpcode() == ISD::CopyFromReg); 10946 do { 10947 // Follow the chain until we find an INLINEASM node. 10948 N = N->getOperand(0).getNode(); 10949 if (N->getOpcode() == ISD::INLINEASM || 10950 N->getOpcode() == ISD::INLINEASM_BR) 10951 return true; 10952 } while (N->getOpcode() == ISD::CopyFromReg); 10953 return false; 10954 } 10955 10956 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 10957 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 10958 { 10959 switch (N->getOpcode()) { 10960 case ISD::CopyFromReg: 10961 { 10962 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 10963 const MachineFunction * MF = FLI->MF; 10964 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 10965 const MachineRegisterInfo &MRI = MF->getRegInfo(); 10966 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo(); 10967 Register Reg = R->getReg(); 10968 if (Reg.isPhysical()) 10969 return !TRI.isSGPRReg(MRI, Reg); 10970 10971 if (MRI.isLiveIn(Reg)) { 10972 // workitem.id.x workitem.id.y workitem.id.z 10973 // Any VGPR formal argument is also considered divergent 10974 if (!TRI.isSGPRReg(MRI, Reg)) 10975 return true; 10976 // Formal arguments of non-entry functions 10977 // are conservatively considered divergent 10978 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv())) 10979 return true; 10980 return false; 10981 } 10982 const Value *V = FLI->getValueFromVirtualReg(Reg); 10983 if (V) 10984 return KDA->isDivergent(V); 10985 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 10986 return !TRI.isSGPRReg(MRI, Reg); 10987 } 10988 break; 10989 case ISD::LOAD: { 10990 const LoadSDNode *L = cast<LoadSDNode>(N); 10991 unsigned AS = L->getAddressSpace(); 10992 // A flat load may access private memory. 10993 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 10994 } break; 10995 case ISD::CALLSEQ_END: 10996 return true; 10997 break; 10998 case ISD::INTRINSIC_WO_CHAIN: 10999 { 11000 11001 } 11002 return AMDGPU::isIntrinsicSourceOfDivergence( 11003 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11004 case ISD::INTRINSIC_W_CHAIN: 11005 return AMDGPU::isIntrinsicSourceOfDivergence( 11006 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11007 } 11008 return false; 11009 } 11010 11011 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11012 EVT VT) const { 11013 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11014 case MVT::f32: 11015 return hasFP32Denormals(DAG.getMachineFunction()); 11016 case MVT::f64: 11017 case MVT::f16: 11018 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11019 default: 11020 return false; 11021 } 11022 } 11023 11024 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11025 const SelectionDAG &DAG, 11026 bool SNaN, 11027 unsigned Depth) const { 11028 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11029 const MachineFunction &MF = DAG.getMachineFunction(); 11030 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11031 11032 if (Info->getMode().DX10Clamp) 11033 return true; // Clamped to 0. 11034 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11035 } 11036 11037 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11038 SNaN, Depth); 11039 } 11040 11041 TargetLowering::AtomicExpansionKind 11042 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11043 switch (RMW->getOperation()) { 11044 case AtomicRMWInst::FAdd: { 11045 Type *Ty = RMW->getType(); 11046 11047 // We don't have a way to support 16-bit atomics now, so just leave them 11048 // as-is. 11049 if (Ty->isHalfTy()) 11050 return AtomicExpansionKind::None; 11051 11052 if (!Ty->isFloatTy()) 11053 return AtomicExpansionKind::CmpXChg; 11054 11055 // TODO: Do have these for flat. Older targets also had them for buffers. 11056 unsigned AS = RMW->getPointerAddressSpace(); 11057 11058 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11059 return RMW->use_empty() ? AtomicExpansionKind::None : 11060 AtomicExpansionKind::CmpXChg; 11061 } 11062 11063 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11064 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11065 } 11066 default: 11067 break; 11068 } 11069 11070 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11071 } 11072 11073 const TargetRegisterClass * 11074 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11075 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11076 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11077 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11078 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11079 : &AMDGPU::SReg_32RegClass; 11080 if (!TRI->isSGPRClass(RC) && !isDivergent) 11081 return TRI->getEquivalentSGPRClass(RC); 11082 else if (TRI->isSGPRClass(RC) && isDivergent) 11083 return TRI->getEquivalentVGPRClass(RC); 11084 11085 return RC; 11086 } 11087 11088 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11089 // uniform values (as produced by the mask results of control flow intrinsics) 11090 // used outside of divergent blocks. The phi users need to also be treated as 11091 // always uniform. 11092 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11093 unsigned WaveSize) { 11094 // FIXME: We asssume we never cast the mask results of a control flow 11095 // intrinsic. 11096 // Early exit if the type won't be consistent as a compile time hack. 11097 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11098 if (!IT || IT->getBitWidth() != WaveSize) 11099 return false; 11100 11101 if (!isa<Instruction>(V)) 11102 return false; 11103 if (!Visited.insert(V).second) 11104 return false; 11105 bool Result = false; 11106 for (auto U : V->users()) { 11107 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11108 if (V == U->getOperand(1)) { 11109 switch (Intrinsic->getIntrinsicID()) { 11110 default: 11111 Result = false; 11112 break; 11113 case Intrinsic::amdgcn_if_break: 11114 case Intrinsic::amdgcn_if: 11115 case Intrinsic::amdgcn_else: 11116 Result = true; 11117 break; 11118 } 11119 } 11120 if (V == U->getOperand(0)) { 11121 switch (Intrinsic->getIntrinsicID()) { 11122 default: 11123 Result = false; 11124 break; 11125 case Intrinsic::amdgcn_end_cf: 11126 case Intrinsic::amdgcn_loop: 11127 Result = true; 11128 break; 11129 } 11130 } 11131 } else { 11132 Result = hasCFUser(U, Visited, WaveSize); 11133 } 11134 if (Result) 11135 break; 11136 } 11137 return Result; 11138 } 11139 11140 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11141 const Value *V) const { 11142 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11143 if (CI->isInlineAsm()) { 11144 // FIXME: This cannot give a correct answer. This should only trigger in 11145 // the case where inline asm returns mixed SGPR and VGPR results, used 11146 // outside the defining block. We don't have a specific result to 11147 // consider, so this assumes if any value is SGPR, the overall register 11148 // also needs to be SGPR. 11149 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11150 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11151 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11152 for (auto &TC : TargetConstraints) { 11153 if (TC.Type == InlineAsm::isOutput) { 11154 ComputeConstraintToUse(TC, SDValue()); 11155 unsigned AssignedReg; 11156 const TargetRegisterClass *RC; 11157 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11158 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11159 if (RC) { 11160 MachineRegisterInfo &MRI = MF.getRegInfo(); 11161 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11162 return true; 11163 else if (SIRI->isSGPRClass(RC)) 11164 return true; 11165 } 11166 } 11167 } 11168 } 11169 } 11170 SmallPtrSet<const Value *, 16> Visited; 11171 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11172 } 11173