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 #include "SIISelLowering.h" 15 #include "AMDGPU.h" 16 #include "AMDGPUInstrInfo.h" 17 #include "AMDGPUTargetMachine.h" 18 #include "SIMachineFunctionInfo.h" 19 #include "SIRegisterInfo.h" 20 #include "llvm/ADT/FloatingPointMode.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 23 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 24 #include "llvm/BinaryFormat/ELF.h" 25 #include "llvm/CodeGen/Analysis.h" 26 #include "llvm/CodeGen/FunctionLoweringInfo.h" 27 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 28 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h" 29 #include "llvm/CodeGen/MachineFrameInfo.h" 30 #include "llvm/CodeGen/MachineFunction.h" 31 #include "llvm/CodeGen/MachineLoopInfo.h" 32 #include "llvm/IR/DiagnosticInfo.h" 33 #include "llvm/IR/IntrinsicInst.h" 34 #include "llvm/IR/IntrinsicsAMDGPU.h" 35 #include "llvm/IR/IntrinsicsR600.h" 36 #include "llvm/Support/CommandLine.h" 37 #include "llvm/Support/KnownBits.h" 38 39 using namespace llvm; 40 41 #define DEBUG_TYPE "si-lower" 42 43 STATISTIC(NumTailCalls, "Number of tail calls"); 44 45 static cl::opt<bool> DisableLoopAlignment( 46 "amdgpu-disable-loop-alignment", 47 cl::desc("Do not align and prefetch loops"), 48 cl::init(false)); 49 50 static cl::opt<bool> UseDivergentRegisterIndexing( 51 "amdgpu-use-divergent-register-indexing", 52 cl::Hidden, 53 cl::desc("Use indirect register addressing for divergent indexes"), 54 cl::init(false)); 55 56 static bool hasFP32Denormals(const MachineFunction &MF) { 57 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 58 return Info->getMode().allFP32Denormals(); 59 } 60 61 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 62 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 63 return Info->getMode().allFP64FP16Denormals(); 64 } 65 66 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 67 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 68 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 69 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 70 return AMDGPU::SGPR0 + Reg; 71 } 72 } 73 llvm_unreachable("Cannot allocate sgpr"); 74 } 75 76 SITargetLowering::SITargetLowering(const TargetMachine &TM, 77 const GCNSubtarget &STI) 78 : AMDGPUTargetLowering(TM, STI), 79 Subtarget(&STI) { 80 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 81 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 82 83 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 84 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 85 86 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 87 88 const SIRegisterInfo *TRI = STI.getRegisterInfo(); 89 const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class(); 90 91 addRegisterClass(MVT::f64, V64RegClass); 92 addRegisterClass(MVT::v2f32, V64RegClass); 93 94 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 95 addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96)); 96 97 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 98 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 99 100 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 101 addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128)); 102 103 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 104 addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160)); 105 106 addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass); 107 addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192)); 108 109 addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass); 110 addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192)); 111 112 addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass); 113 addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224)); 114 115 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 116 addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256)); 117 118 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 119 addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256)); 120 121 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 122 addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512)); 123 124 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 125 addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512)); 126 127 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 128 addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024)); 129 130 if (Subtarget->has16BitInsts()) { 131 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 132 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 133 134 // Unless there are also VOP3P operations, not operations are really legal. 135 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 136 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 137 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 138 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 139 addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass); 140 addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass); 141 } 142 143 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 144 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024)); 145 146 computeRegisterProperties(Subtarget->getRegisterInfo()); 147 148 // The boolean content concept here is too inflexible. Compares only ever 149 // really produce a 1-bit result. Any copy/extend from these will turn into a 150 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 151 // it's what most targets use. 152 setBooleanContents(ZeroOrOneBooleanContent); 153 setBooleanVectorContents(ZeroOrOneBooleanContent); 154 155 // We need to custom lower vector stores from local memory 156 setOperationAction(ISD::LOAD, 157 {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32, 158 MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v16i32, MVT::i1, 159 MVT::v32i32}, 160 Custom); 161 162 setOperationAction(ISD::STORE, 163 {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32, 164 MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v16i32, MVT::i1, 165 MVT::v32i32}, 166 Custom); 167 168 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 169 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 170 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 171 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 172 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 173 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 174 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 175 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 176 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 177 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 178 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 179 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 180 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 181 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 182 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 183 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 184 185 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand); 186 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand); 187 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 188 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 189 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 190 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 191 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 192 193 setOperationAction(ISD::GlobalAddress, {MVT::i32, MVT::i64}, Custom); 194 195 setOperationAction(ISD::SELECT, MVT::i1, Promote); 196 setOperationAction(ISD::SELECT, MVT::i64, Custom); 197 setOperationAction(ISD::SELECT, MVT::f64, Promote); 198 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 199 200 setOperationAction(ISD::SELECT_CC, 201 {MVT::f32, MVT::i32, MVT::i64, MVT::f64, MVT::i1}, Expand); 202 203 setOperationAction(ISD::SETCC, MVT::i1, Promote); 204 setOperationAction(ISD::SETCC, {MVT::v2i1, MVT::v4i1}, Expand); 205 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 206 207 setOperationAction(ISD::TRUNCATE, 208 {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32, 209 MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v16i32}, 210 Expand); 211 setOperationAction(ISD::FP_ROUND, 212 {MVT::v2f32, MVT::v3f32, MVT::v4f32, MVT::v5f32, 213 MVT::v6f32, MVT::v7f32, MVT::v8f32, MVT::v16f32}, 214 Expand); 215 216 setOperationAction(ISD::SIGN_EXTEND_INREG, 217 {MVT::v2i1, MVT::v4i1, MVT::v2i8, MVT::v4i8, MVT::v2i16, 218 MVT::v3i16, MVT::v4i16, MVT::Other}, 219 Custom); 220 221 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 222 setOperationAction(ISD::BR_CC, 223 {MVT::i1, MVT::i32, MVT::i64, MVT::f32, MVT::f64}, Expand); 224 225 setOperationAction({ISD::UADDO, ISD::USUBO}, MVT::i32, Legal); 226 227 setOperationAction({ISD::ADDCARRY, ISD::SUBCARRY}, MVT::i32, Legal); 228 229 setOperationAction({ISD::SHL_PARTS, ISD::SRA_PARTS, ISD::SRL_PARTS}, MVT::i64, 230 Expand); 231 232 #if 0 233 setOperationAction({ISD::ADDCARRY, ISD::SUBCARRY}, MVT::i64, Legal); 234 #endif 235 236 // We only support LOAD/STORE and vector manipulation ops for vectors 237 // with > 4 elements. 238 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 239 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 240 MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32, 241 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 242 MVT::v8i16, MVT::v8f16, MVT::v16i64, MVT::v16f64, 243 MVT::v32i32, MVT::v32f32 }) { 244 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 245 switch (Op) { 246 case ISD::LOAD: 247 case ISD::STORE: 248 case ISD::BUILD_VECTOR: 249 case ISD::BITCAST: 250 case ISD::EXTRACT_VECTOR_ELT: 251 case ISD::INSERT_VECTOR_ELT: 252 case ISD::EXTRACT_SUBVECTOR: 253 case ISD::SCALAR_TO_VECTOR: 254 break; 255 case ISD::INSERT_SUBVECTOR: 256 case ISD::CONCAT_VECTORS: 257 setOperationAction(Op, VT, Custom); 258 break; 259 default: 260 setOperationAction(Op, VT, Expand); 261 break; 262 } 263 } 264 } 265 266 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 267 268 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 269 // is expanded to avoid having two separate loops in case the index is a VGPR. 270 271 // Most operations are naturally 32-bit vector operations. We only support 272 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 273 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 274 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 275 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 276 277 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 278 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 279 280 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 281 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 282 283 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 284 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 285 } 286 287 for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) { 288 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 289 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32); 290 291 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 292 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32); 293 294 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 295 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32); 296 297 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 298 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32); 299 } 300 301 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 302 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 303 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 304 305 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 306 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 307 308 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 309 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 310 311 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 312 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 313 } 314 315 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 316 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 317 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 318 319 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 320 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 321 322 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 323 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 324 325 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 326 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 327 } 328 329 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 330 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 331 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 332 333 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 334 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 335 336 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 337 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 338 339 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 340 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 341 } 342 343 setOperationAction(ISD::VECTOR_SHUFFLE, 344 {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32}, 345 Expand); 346 347 setOperationAction(ISD::BUILD_VECTOR, {MVT::v4f16, MVT::v4i16}, Custom); 348 349 // Avoid stack access for these. 350 // TODO: Generalize to more vector types. 351 setOperationAction({ISD::EXTRACT_VECTOR_ELT, ISD::INSERT_VECTOR_ELT}, 352 {MVT::v2i16, MVT::v2f16, MVT::v2i8, MVT::v4i8, MVT::v8i8, 353 MVT::v4i16, MVT::v4f16}, 354 Custom); 355 356 // Deal with vec3 vector operations when widened to vec4. 357 setOperationAction(ISD::INSERT_SUBVECTOR, 358 {MVT::v3i32, MVT::v3f32, MVT::v4i32, MVT::v4f32}, Custom); 359 360 // Deal with vec5/6/7 vector operations when widened to vec8. 361 setOperationAction(ISD::INSERT_SUBVECTOR, 362 {MVT::v5i32, MVT::v5f32, MVT::v6i32, MVT::v6f32, 363 MVT::v7i32, MVT::v7f32, MVT::v8i32, MVT::v8f32}, 364 Custom); 365 366 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 367 // and output demarshalling 368 setOperationAction(ISD::ATOMIC_CMP_SWAP, {MVT::i32, MVT::i64}, Custom); 369 370 // We can't return success/failure, only the old value, 371 // let LLVM add the comparison 372 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, {MVT::i32, MVT::i64}, 373 Expand); 374 375 if (Subtarget->hasFlatAddressSpace()) 376 setOperationAction(ISD::ADDRSPACECAST, {MVT::i32, MVT::i64}, Custom); 377 378 setOperationAction(ISD::BITREVERSE, {MVT::i32, MVT::i64}, Legal); 379 380 // FIXME: This should be narrowed to i32, but that only happens if i64 is 381 // illegal. 382 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 383 setOperationAction(ISD::BSWAP, {MVT::i64, MVT::i32}, Legal); 384 385 // On SI this is s_memtime and s_memrealtime on VI. 386 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 387 setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Custom); 388 389 if (Subtarget->has16BitInsts()) { 390 setOperationAction({ISD::FPOW, ISD::FPOWI}, MVT::f16, Promote); 391 setOperationAction({ISD::FLOG, ISD::FEXP, ISD::FLOG10}, MVT::f16, Custom); 392 } 393 394 if (Subtarget->hasMadMacF32Insts()) 395 setOperationAction(ISD::FMAD, MVT::f32, Legal); 396 397 if (!Subtarget->hasBFI()) 398 // fcopysign can be done in a single instruction with BFI. 399 setOperationAction(ISD::FCOPYSIGN, {MVT::f32, MVT::f64}, Expand); 400 401 if (!Subtarget->hasBCNT(32)) 402 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 403 404 if (!Subtarget->hasBCNT(64)) 405 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 406 407 if (Subtarget->hasFFBH()) 408 setOperationAction({ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF}, MVT::i32, Custom); 409 410 if (Subtarget->hasFFBL()) 411 setOperationAction({ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF}, MVT::i32, Custom); 412 413 // We only really have 32-bit BFE instructions (and 16-bit on VI). 414 // 415 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 416 // effort to match them now. We want this to be false for i64 cases when the 417 // extraction isn't restricted to the upper or lower half. Ideally we would 418 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 419 // span the midpoint are probably relatively rare, so don't worry about them 420 // for now. 421 if (Subtarget->hasBFE()) 422 setHasExtractBitsInsn(true); 423 424 // Clamp modifier on add/sub 425 if (Subtarget->hasIntClamp()) 426 setOperationAction({ISD::UADDSAT, ISD::USUBSAT}, MVT::i32, Legal); 427 428 if (Subtarget->hasAddNoCarry()) 429 setOperationAction({ISD::SADDSAT, ISD::SSUBSAT}, {MVT::i16, MVT::i32}, 430 Legal); 431 432 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, {MVT::f32, MVT::f64}, 433 Custom); 434 435 // These are really only legal for ieee_mode functions. We should be avoiding 436 // them for functions that don't have ieee_mode enabled, so just say they are 437 // legal. 438 setOperationAction({ISD::FMINNUM_IEEE, ISD::FMAXNUM_IEEE}, 439 {MVT::f32, MVT::f64}, Legal); 440 441 if (Subtarget->haveRoundOpsF64()) 442 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FRINT}, MVT::f64, Legal); 443 else 444 setOperationAction({ISD::FCEIL, ISD::FTRUNC, ISD::FRINT, ISD::FFLOOR}, 445 MVT::f64, Custom); 446 447 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 448 449 setOperationAction({ISD::FSIN, ISD::FCOS, ISD::FDIV}, MVT::f32, Custom); 450 setOperationAction(ISD::FDIV, MVT::f64, Custom); 451 452 if (Subtarget->has16BitInsts()) { 453 setOperationAction({ISD::Constant, ISD::SMIN, ISD::SMAX, ISD::UMIN, 454 ISD::UMAX, ISD::UADDSAT, ISD::USUBSAT}, 455 MVT::i16, Legal); 456 457 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 458 459 setOperationAction({ISD::ROTR, ISD::ROTL, ISD::SELECT_CC, ISD::BR_CC}, 460 MVT::i16, Expand); 461 462 setOperationAction({ISD::SIGN_EXTEND, ISD::SDIV, ISD::UDIV, ISD::SREM, 463 ISD::UREM, ISD::BITREVERSE, ISD::CTTZ, 464 ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF, 465 ISD::CTPOP}, 466 MVT::i16, Promote); 467 468 setOperationAction(ISD::LOAD, MVT::i16, Custom); 469 470 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 471 472 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 473 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 474 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 475 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 476 477 setOperationAction({ISD::FP_TO_SINT, ISD::FP_TO_UINT}, MVT::i16, Custom); 478 479 // F16 - Constant Actions. 480 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 481 482 // F16 - Load/Store Actions. 483 setOperationAction(ISD::LOAD, MVT::f16, Promote); 484 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 485 setOperationAction(ISD::STORE, MVT::f16, Promote); 486 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 487 488 // F16 - VOP1 Actions. 489 setOperationAction( 490 {ISD::FP_ROUND, ISD::FCOS, ISD::FSIN, ISD::FROUND, ISD::FPTRUNC_ROUND}, 491 MVT::f16, Custom); 492 493 setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP}, MVT::i16, Custom); 494 495 setOperationAction( 496 {ISD::FP_TO_SINT, ISD::FP_TO_UINT, ISD::SINT_TO_FP, ISD::UINT_TO_FP}, 497 MVT::f16, Promote); 498 499 // F16 - VOP2 Actions. 500 setOperationAction({ISD::BR_CC, ISD::SELECT_CC}, MVT::f16, Expand); 501 502 setOperationAction(ISD::FDIV, MVT::f16, Custom); 503 504 // F16 - VOP3 Actions. 505 setOperationAction(ISD::FMA, MVT::f16, Legal); 506 if (STI.hasMadF16()) 507 setOperationAction(ISD::FMAD, MVT::f16, Legal); 508 509 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16, MVT::v8i16, 510 MVT::v8f16}) { 511 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 512 switch (Op) { 513 case ISD::LOAD: 514 case ISD::STORE: 515 case ISD::BUILD_VECTOR: 516 case ISD::BITCAST: 517 case ISD::EXTRACT_VECTOR_ELT: 518 case ISD::INSERT_VECTOR_ELT: 519 case ISD::INSERT_SUBVECTOR: 520 case ISD::EXTRACT_SUBVECTOR: 521 case ISD::SCALAR_TO_VECTOR: 522 break; 523 case ISD::CONCAT_VECTORS: 524 setOperationAction(Op, VT, Custom); 525 break; 526 default: 527 setOperationAction(Op, VT, Expand); 528 break; 529 } 530 } 531 } 532 533 // v_perm_b32 can handle either of these. 534 setOperationAction(ISD::BSWAP, {MVT::i16, MVT::v2i16}, Legal); 535 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 536 537 // XXX - Do these do anything? Vector constants turn into build_vector. 538 setOperationAction(ISD::Constant, {MVT::v2i16, MVT::v2f16}, Legal); 539 540 setOperationAction(ISD::UNDEF, {MVT::v2i16, MVT::v2f16}, Legal); 541 542 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 543 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 544 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 545 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 546 547 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 548 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 549 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 550 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 551 552 setOperationAction(ISD::AND, MVT::v2i16, Promote); 553 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 554 setOperationAction(ISD::OR, MVT::v2i16, Promote); 555 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 556 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 557 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 558 559 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 560 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 561 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 562 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 563 564 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 565 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 566 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 567 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 568 569 setOperationAction(ISD::LOAD, MVT::v8i16, Promote); 570 AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32); 571 setOperationAction(ISD::LOAD, MVT::v8f16, Promote); 572 AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32); 573 574 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 575 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 576 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 577 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 578 579 setOperationAction(ISD::STORE, MVT::v8i16, Promote); 580 AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32); 581 setOperationAction(ISD::STORE, MVT::v8f16, Promote); 582 AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32); 583 584 setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND}, 585 MVT::v2i32, Expand); 586 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 587 588 setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND}, 589 MVT::v4i32, Expand); 590 591 setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND}, 592 MVT::v8i32, Expand); 593 594 if (!Subtarget->hasVOP3PInsts()) 595 setOperationAction(ISD::BUILD_VECTOR, {MVT::v2i16, MVT::v2f16}, Custom); 596 597 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 598 // This isn't really legal, but this avoids the legalizer unrolling it (and 599 // allows matching fneg (fabs x) patterns) 600 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 601 602 setOperationAction({ISD::FMAXNUM, ISD::FMINNUM}, MVT::f16, Custom); 603 setOperationAction({ISD::FMAXNUM_IEEE, ISD::FMINNUM_IEEE}, MVT::f16, Legal); 604 605 setOperationAction({ISD::FMINNUM_IEEE, ISD::FMAXNUM_IEEE}, 606 {MVT::v4f16, MVT::v8f16}, Custom); 607 608 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, {MVT::v4f16, MVT::v8f16}, 609 Expand); 610 611 for (MVT Vec16 : { MVT::v8i16, MVT::v8f16 }) { 612 setOperationAction( 613 {ISD::BUILD_VECTOR, ISD::EXTRACT_VECTOR_ELT, ISD::SCALAR_TO_VECTOR}, 614 Vec16, Custom); 615 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec16, Expand); 616 } 617 } 618 619 if (Subtarget->hasVOP3PInsts()) { 620 setOperationAction({ISD::ADD, ISD::SUB, ISD::MUL, ISD::SHL, ISD::SRL, 621 ISD::SRA, ISD::SMIN, ISD::UMIN, ISD::SMAX, ISD::UMAX, 622 ISD::UADDSAT, ISD::USUBSAT, ISD::SADDSAT, ISD::SSUBSAT}, 623 MVT::v2i16, Legal); 624 625 setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FMINNUM_IEEE, 626 ISD::FMAXNUM_IEEE, ISD::FCANONICALIZE}, 627 MVT::v2f16, Legal); 628 629 setOperationAction(ISD::EXTRACT_VECTOR_ELT, {MVT::v2i16, MVT::v2f16}, 630 Custom); 631 632 setOperationAction(ISD::VECTOR_SHUFFLE, 633 {MVT::v4f16, MVT::v4i16, MVT::v8f16, MVT::v8i16}, 634 Custom); 635 636 for (MVT VT : {MVT::v4i16, MVT::v8i16}) 637 // Split vector operations. 638 setOperationAction({ISD::SHL, ISD::SRA, ISD::SRL, ISD::ADD, ISD::SUB, 639 ISD::MUL, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, 640 ISD::UADDSAT, ISD::SADDSAT, ISD::USUBSAT, 641 ISD::SSUBSAT}, 642 VT, Custom); 643 644 for (MVT VT : {MVT::v4f16, MVT::v8f16}) 645 // Split vector operations. 646 setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FCANONICALIZE}, 647 VT, Custom); 648 649 setOperationAction({ISD::FMAXNUM, ISD::FMINNUM}, {MVT::v2f16, MVT::v4f16}, 650 Custom); 651 652 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 653 setOperationAction(ISD::SELECT, {MVT::v4i16, MVT::v4f16}, Custom); 654 655 if (Subtarget->hasPackedFP32Ops()) { 656 setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FNEG}, 657 MVT::v2f32, Legal); 658 setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA}, 659 {MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32}, 660 Custom); 661 } 662 } 663 664 setOperationAction({ISD::FNEG, ISD::FABS}, MVT::v4f16, Custom); 665 666 if (Subtarget->has16BitInsts()) { 667 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 668 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 669 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 670 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 671 } else { 672 // Legalization hack. 673 setOperationAction(ISD::SELECT, {MVT::v2i16, MVT::v2f16}, Custom); 674 675 setOperationAction({ISD::FNEG, ISD::FABS}, MVT::v2f16, Custom); 676 } 677 678 setOperationAction(ISD::SELECT, 679 {MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8, 680 MVT::v8i16, MVT::v8f16}, 681 Custom); 682 683 setOperationAction({ISD::SMULO, ISD::UMULO}, MVT::i64, Custom); 684 685 if (Subtarget->hasMad64_32()) 686 setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, MVT::i32, Custom); 687 688 setOperationAction(ISD::INTRINSIC_WO_CHAIN, 689 {MVT::Other, MVT::f32, MVT::v4f32, MVT::i16, MVT::f16, 690 MVT::v2i16, MVT::v2f16}, 691 Custom); 692 693 setOperationAction(ISD::INTRINSIC_W_CHAIN, 694 {MVT::v2f16, MVT::v2i16, MVT::v3f16, MVT::v3i16, 695 MVT::v4f16, MVT::v4i16, MVT::v8f16, MVT::Other, MVT::f16, 696 MVT::i16, MVT::i8}, 697 Custom); 698 699 setOperationAction(ISD::INTRINSIC_VOID, 700 {MVT::Other, MVT::v2i16, MVT::v2f16, MVT::v3i16, 701 MVT::v3f16, MVT::v4f16, MVT::v4i16, MVT::f16, MVT::i16, 702 MVT::i8}, 703 Custom); 704 705 setTargetDAGCombine({ISD::ADD, 706 ISD::ADDCARRY, 707 ISD::SUB, 708 ISD::SUBCARRY, 709 ISD::FADD, 710 ISD::FSUB, 711 ISD::FMINNUM, 712 ISD::FMAXNUM, 713 ISD::FMINNUM_IEEE, 714 ISD::FMAXNUM_IEEE, 715 ISD::FMA, 716 ISD::SMIN, 717 ISD::SMAX, 718 ISD::UMIN, 719 ISD::UMAX, 720 ISD::SETCC, 721 ISD::AND, 722 ISD::OR, 723 ISD::XOR, 724 ISD::SINT_TO_FP, 725 ISD::UINT_TO_FP, 726 ISD::FCANONICALIZE, 727 ISD::SCALAR_TO_VECTOR, 728 ISD::ZERO_EXTEND, 729 ISD::SIGN_EXTEND_INREG, 730 ISD::EXTRACT_VECTOR_ELT, 731 ISD::INSERT_VECTOR_ELT}); 732 733 // All memory operations. Some folding on the pointer operand is done to help 734 // matching the constant offsets in the addressing modes. 735 setTargetDAGCombine({ISD::LOAD, 736 ISD::STORE, 737 ISD::ATOMIC_LOAD, 738 ISD::ATOMIC_STORE, 739 ISD::ATOMIC_CMP_SWAP, 740 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 741 ISD::ATOMIC_SWAP, 742 ISD::ATOMIC_LOAD_ADD, 743 ISD::ATOMIC_LOAD_SUB, 744 ISD::ATOMIC_LOAD_AND, 745 ISD::ATOMIC_LOAD_OR, 746 ISD::ATOMIC_LOAD_XOR, 747 ISD::ATOMIC_LOAD_NAND, 748 ISD::ATOMIC_LOAD_MIN, 749 ISD::ATOMIC_LOAD_MAX, 750 ISD::ATOMIC_LOAD_UMIN, 751 ISD::ATOMIC_LOAD_UMAX, 752 ISD::ATOMIC_LOAD_FADD, 753 ISD::INTRINSIC_VOID, 754 ISD::INTRINSIC_W_CHAIN}); 755 756 // FIXME: In other contexts we pretend this is a per-function property. 757 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 758 759 setSchedulingPreference(Sched::RegPressure); 760 } 761 762 const GCNSubtarget *SITargetLowering::getSubtarget() const { 763 return Subtarget; 764 } 765 766 //===----------------------------------------------------------------------===// 767 // TargetLowering queries 768 //===----------------------------------------------------------------------===// 769 770 // v_mad_mix* support a conversion from f16 to f32. 771 // 772 // There is only one special case when denormals are enabled we don't currently, 773 // where this is OK to use. 774 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 775 EVT DestVT, EVT SrcVT) const { 776 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 777 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 778 DestVT.getScalarType() == MVT::f32 && 779 SrcVT.getScalarType() == MVT::f16 && 780 // TODO: This probably only requires no input flushing? 781 !hasFP32Denormals(DAG.getMachineFunction()); 782 } 783 784 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode, 785 LLT DestTy, LLT SrcTy) const { 786 return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) || 787 (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) && 788 DestTy.getScalarSizeInBits() == 32 && 789 SrcTy.getScalarSizeInBits() == 16 && 790 // TODO: This probably only requires no input flushing? 791 !hasFP32Denormals(*MI.getMF()); 792 } 793 794 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 795 // SI has some legal vector types, but no legal vector operations. Say no 796 // shuffles are legal in order to prefer scalarizing some vector operations. 797 return false; 798 } 799 800 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 801 CallingConv::ID CC, 802 EVT VT) const { 803 if (CC == CallingConv::AMDGPU_KERNEL) 804 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 805 806 if (VT.isVector()) { 807 EVT ScalarVT = VT.getScalarType(); 808 unsigned Size = ScalarVT.getSizeInBits(); 809 if (Size == 16) { 810 if (Subtarget->has16BitInsts()) 811 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 812 return VT.isInteger() ? MVT::i32 : MVT::f32; 813 } 814 815 if (Size < 16) 816 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 817 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 818 } 819 820 if (VT.getSizeInBits() > 32) 821 return MVT::i32; 822 823 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 824 } 825 826 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 827 CallingConv::ID CC, 828 EVT VT) const { 829 if (CC == CallingConv::AMDGPU_KERNEL) 830 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 831 832 if (VT.isVector()) { 833 unsigned NumElts = VT.getVectorNumElements(); 834 EVT ScalarVT = VT.getScalarType(); 835 unsigned Size = ScalarVT.getSizeInBits(); 836 837 // FIXME: Should probably promote 8-bit vectors to i16. 838 if (Size == 16 && Subtarget->has16BitInsts()) 839 return (NumElts + 1) / 2; 840 841 if (Size <= 32) 842 return NumElts; 843 844 if (Size > 32) 845 return NumElts * ((Size + 31) / 32); 846 } else if (VT.getSizeInBits() > 32) 847 return (VT.getSizeInBits() + 31) / 32; 848 849 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 850 } 851 852 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 853 LLVMContext &Context, CallingConv::ID CC, 854 EVT VT, EVT &IntermediateVT, 855 unsigned &NumIntermediates, MVT &RegisterVT) const { 856 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 857 unsigned NumElts = VT.getVectorNumElements(); 858 EVT ScalarVT = VT.getScalarType(); 859 unsigned Size = ScalarVT.getSizeInBits(); 860 // FIXME: We should fix the ABI to be the same on targets without 16-bit 861 // support, but unless we can properly handle 3-vectors, it will be still be 862 // inconsistent. 863 if (Size == 16 && Subtarget->has16BitInsts()) { 864 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 865 IntermediateVT = RegisterVT; 866 NumIntermediates = (NumElts + 1) / 2; 867 return NumIntermediates; 868 } 869 870 if (Size == 32) { 871 RegisterVT = ScalarVT.getSimpleVT(); 872 IntermediateVT = RegisterVT; 873 NumIntermediates = NumElts; 874 return NumIntermediates; 875 } 876 877 if (Size < 16 && Subtarget->has16BitInsts()) { 878 // FIXME: Should probably form v2i16 pieces 879 RegisterVT = MVT::i16; 880 IntermediateVT = ScalarVT; 881 NumIntermediates = NumElts; 882 return NumIntermediates; 883 } 884 885 886 if (Size != 16 && Size <= 32) { 887 RegisterVT = MVT::i32; 888 IntermediateVT = ScalarVT; 889 NumIntermediates = NumElts; 890 return NumIntermediates; 891 } 892 893 if (Size > 32) { 894 RegisterVT = MVT::i32; 895 IntermediateVT = RegisterVT; 896 NumIntermediates = NumElts * ((Size + 31) / 32); 897 return NumIntermediates; 898 } 899 } 900 901 return TargetLowering::getVectorTypeBreakdownForCallingConv( 902 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 903 } 904 905 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 906 assert(DMaskLanes != 0); 907 908 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 909 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 910 return EVT::getVectorVT(Ty->getContext(), 911 EVT::getEVT(VT->getElementType()), 912 NumElts); 913 } 914 915 return EVT::getEVT(Ty); 916 } 917 918 // Peek through TFE struct returns to only use the data size. 919 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 920 auto *ST = dyn_cast<StructType>(Ty); 921 if (!ST) 922 return memVTFromImageData(Ty, DMaskLanes); 923 924 // Some intrinsics return an aggregate type - special case to work out the 925 // correct memVT. 926 // 927 // Only limited forms of aggregate type currently expected. 928 if (ST->getNumContainedTypes() != 2 || 929 !ST->getContainedType(1)->isIntegerTy(32)) 930 return EVT(); 931 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 932 } 933 934 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 935 const CallInst &CI, 936 MachineFunction &MF, 937 unsigned IntrID) const { 938 Info.flags = MachineMemOperand::MONone; 939 if (CI.hasMetadata(LLVMContext::MD_invariant_load)) 940 Info.flags |= MachineMemOperand::MOInvariant; 941 942 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 943 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 944 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 945 (Intrinsic::ID)IntrID); 946 if (Attr.hasFnAttr(Attribute::ReadNone)) 947 return false; 948 949 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 950 951 const GCNTargetMachine &TM = 952 static_cast<const GCNTargetMachine &>(getTargetMachine()); 953 954 if (RsrcIntr->IsImage) { 955 Info.ptrVal = MFI->getImagePSV(TM); 956 Info.align.reset(); 957 } else { 958 Info.ptrVal = MFI->getBufferPSV(TM); 959 } 960 961 Info.flags |= MachineMemOperand::MODereferenceable; 962 if (Attr.hasFnAttr(Attribute::ReadOnly)) { 963 unsigned DMaskLanes = 4; 964 965 if (RsrcIntr->IsImage) { 966 const AMDGPU::ImageDimIntrinsicInfo *Intr 967 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 968 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 969 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 970 971 if (!BaseOpcode->Gather4) { 972 // If this isn't a gather, we may have excess loaded elements in the 973 // IR type. Check the dmask for the real number of elements loaded. 974 unsigned DMask 975 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 976 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 977 } 978 979 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 980 } else 981 Info.memVT = EVT::getEVT(CI.getType()); 982 983 // FIXME: What does alignment mean for an image? 984 Info.opc = ISD::INTRINSIC_W_CHAIN; 985 Info.flags |= MachineMemOperand::MOLoad; 986 } else if (Attr.hasFnAttr(Attribute::WriteOnly)) { 987 Info.opc = ISD::INTRINSIC_VOID; 988 989 Type *DataTy = CI.getArgOperand(0)->getType(); 990 if (RsrcIntr->IsImage) { 991 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 992 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 993 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 994 } else 995 Info.memVT = EVT::getEVT(DataTy); 996 997 Info.flags |= MachineMemOperand::MOStore; 998 } else { 999 // Atomic 1000 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1001 ISD::INTRINSIC_W_CHAIN; 1002 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1003 Info.flags |= MachineMemOperand::MOLoad | 1004 MachineMemOperand::MOStore | 1005 MachineMemOperand::MODereferenceable; 1006 1007 // XXX - Should this be volatile without known ordering? 1008 Info.flags |= MachineMemOperand::MOVolatile; 1009 1010 switch (IntrID) { 1011 default: 1012 break; 1013 case Intrinsic::amdgcn_raw_buffer_load_lds: 1014 case Intrinsic::amdgcn_struct_buffer_load_lds: { 1015 unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue(); 1016 Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8); 1017 return true; 1018 } 1019 } 1020 } 1021 return true; 1022 } 1023 1024 switch (IntrID) { 1025 case Intrinsic::amdgcn_atomic_inc: 1026 case Intrinsic::amdgcn_atomic_dec: 1027 case Intrinsic::amdgcn_ds_ordered_add: 1028 case Intrinsic::amdgcn_ds_ordered_swap: 1029 case Intrinsic::amdgcn_ds_fadd: 1030 case Intrinsic::amdgcn_ds_fmin: 1031 case Intrinsic::amdgcn_ds_fmax: { 1032 Info.opc = ISD::INTRINSIC_W_CHAIN; 1033 Info.memVT = MVT::getVT(CI.getType()); 1034 Info.ptrVal = CI.getOperand(0); 1035 Info.align.reset(); 1036 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1037 1038 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1039 if (!Vol->isZero()) 1040 Info.flags |= MachineMemOperand::MOVolatile; 1041 1042 return true; 1043 } 1044 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1045 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1046 1047 const GCNTargetMachine &TM = 1048 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1049 1050 Info.opc = ISD::INTRINSIC_W_CHAIN; 1051 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1052 Info.ptrVal = MFI->getBufferPSV(TM); 1053 Info.align.reset(); 1054 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1055 1056 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1057 if (!Vol || !Vol->isZero()) 1058 Info.flags |= MachineMemOperand::MOVolatile; 1059 1060 return true; 1061 } 1062 case Intrinsic::amdgcn_ds_append: 1063 case Intrinsic::amdgcn_ds_consume: { 1064 Info.opc = ISD::INTRINSIC_W_CHAIN; 1065 Info.memVT = MVT::getVT(CI.getType()); 1066 Info.ptrVal = CI.getOperand(0); 1067 Info.align.reset(); 1068 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1069 1070 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1071 if (!Vol->isZero()) 1072 Info.flags |= MachineMemOperand::MOVolatile; 1073 1074 return true; 1075 } 1076 case Intrinsic::amdgcn_global_atomic_csub: { 1077 Info.opc = ISD::INTRINSIC_W_CHAIN; 1078 Info.memVT = MVT::getVT(CI.getType()); 1079 Info.ptrVal = CI.getOperand(0); 1080 Info.align.reset(); 1081 Info.flags |= MachineMemOperand::MOLoad | 1082 MachineMemOperand::MOStore | 1083 MachineMemOperand::MOVolatile; 1084 return true; 1085 } 1086 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1087 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1088 Info.opc = ISD::INTRINSIC_W_CHAIN; 1089 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1090 1091 const GCNTargetMachine &TM = 1092 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1093 1094 Info.ptrVal = MFI->getImagePSV(TM); 1095 Info.align.reset(); 1096 Info.flags |= MachineMemOperand::MOLoad | 1097 MachineMemOperand::MODereferenceable; 1098 return true; 1099 } 1100 case Intrinsic::amdgcn_global_atomic_fadd: 1101 case Intrinsic::amdgcn_global_atomic_fmin: 1102 case Intrinsic::amdgcn_global_atomic_fmax: 1103 case Intrinsic::amdgcn_flat_atomic_fadd: 1104 case Intrinsic::amdgcn_flat_atomic_fmin: 1105 case Intrinsic::amdgcn_flat_atomic_fmax: 1106 case Intrinsic::amdgcn_global_atomic_fadd_v2bf16: 1107 case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: { 1108 Info.opc = ISD::INTRINSIC_W_CHAIN; 1109 Info.memVT = MVT::getVT(CI.getType()); 1110 Info.ptrVal = CI.getOperand(0); 1111 Info.align.reset(); 1112 Info.flags |= MachineMemOperand::MOLoad | 1113 MachineMemOperand::MOStore | 1114 MachineMemOperand::MODereferenceable | 1115 MachineMemOperand::MOVolatile; 1116 return true; 1117 } 1118 case Intrinsic::amdgcn_ds_gws_init: 1119 case Intrinsic::amdgcn_ds_gws_barrier: 1120 case Intrinsic::amdgcn_ds_gws_sema_v: 1121 case Intrinsic::amdgcn_ds_gws_sema_br: 1122 case Intrinsic::amdgcn_ds_gws_sema_p: 1123 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1124 Info.opc = ISD::INTRINSIC_VOID; 1125 1126 const GCNTargetMachine &TM = 1127 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1128 1129 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1130 Info.ptrVal = MFI->getGWSPSV(TM); 1131 1132 // This is an abstract access, but we need to specify a type and size. 1133 Info.memVT = MVT::i32; 1134 Info.size = 4; 1135 Info.align = Align(4); 1136 1137 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1138 Info.flags |= MachineMemOperand::MOLoad; 1139 else 1140 Info.flags |= MachineMemOperand::MOStore; 1141 return true; 1142 } 1143 case Intrinsic::amdgcn_global_load_lds: { 1144 Info.opc = ISD::INTRINSIC_VOID; 1145 unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue(); 1146 Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8); 1147 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1148 MachineMemOperand::MOVolatile; 1149 return true; 1150 } 1151 default: 1152 return false; 1153 } 1154 } 1155 1156 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1157 SmallVectorImpl<Value*> &Ops, 1158 Type *&AccessTy) const { 1159 switch (II->getIntrinsicID()) { 1160 case Intrinsic::amdgcn_atomic_inc: 1161 case Intrinsic::amdgcn_atomic_dec: 1162 case Intrinsic::amdgcn_ds_ordered_add: 1163 case Intrinsic::amdgcn_ds_ordered_swap: 1164 case Intrinsic::amdgcn_ds_append: 1165 case Intrinsic::amdgcn_ds_consume: 1166 case Intrinsic::amdgcn_ds_fadd: 1167 case Intrinsic::amdgcn_ds_fmin: 1168 case Intrinsic::amdgcn_ds_fmax: 1169 case Intrinsic::amdgcn_global_atomic_fadd: 1170 case Intrinsic::amdgcn_flat_atomic_fadd: 1171 case Intrinsic::amdgcn_flat_atomic_fmin: 1172 case Intrinsic::amdgcn_flat_atomic_fmax: 1173 case Intrinsic::amdgcn_global_atomic_fadd_v2bf16: 1174 case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: 1175 case Intrinsic::amdgcn_global_atomic_csub: { 1176 Value *Ptr = II->getArgOperand(0); 1177 AccessTy = II->getType(); 1178 Ops.push_back(Ptr); 1179 return true; 1180 } 1181 default: 1182 return false; 1183 } 1184 } 1185 1186 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1187 if (!Subtarget->hasFlatInstOffsets()) { 1188 // Flat instructions do not have offsets, and only have the register 1189 // address. 1190 return AM.BaseOffs == 0 && AM.Scale == 0; 1191 } 1192 1193 return AM.Scale == 0 && 1194 (AM.BaseOffs == 0 || 1195 Subtarget->getInstrInfo()->isLegalFLATOffset( 1196 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT)); 1197 } 1198 1199 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1200 if (Subtarget->hasFlatGlobalInsts()) 1201 return AM.Scale == 0 && 1202 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1203 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1204 SIInstrFlags::FlatGlobal)); 1205 1206 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1207 // Assume the we will use FLAT for all global memory accesses 1208 // on VI. 1209 // FIXME: This assumption is currently wrong. On VI we still use 1210 // MUBUF instructions for the r + i addressing mode. As currently 1211 // implemented, the MUBUF instructions only work on buffer < 4GB. 1212 // It may be possible to support > 4GB buffers with MUBUF instructions, 1213 // by setting the stride value in the resource descriptor which would 1214 // increase the size limit to (stride * 4GB). However, this is risky, 1215 // because it has never been validated. 1216 return isLegalFlatAddressingMode(AM); 1217 } 1218 1219 return isLegalMUBUFAddressingMode(AM); 1220 } 1221 1222 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1223 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1224 // additionally can do r + r + i with addr64. 32-bit has more addressing 1225 // mode options. Depending on the resource constant, it can also do 1226 // (i64 r0) + (i32 r1) * (i14 i). 1227 // 1228 // Private arrays end up using a scratch buffer most of the time, so also 1229 // assume those use MUBUF instructions. Scratch loads / stores are currently 1230 // implemented as mubuf instructions with offen bit set, so slightly 1231 // different than the normal addr64. 1232 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1233 return false; 1234 1235 // FIXME: Since we can split immediate into soffset and immediate offset, 1236 // would it make sense to allow any immediate? 1237 1238 switch (AM.Scale) { 1239 case 0: // r + i or just i, depending on HasBaseReg. 1240 return true; 1241 case 1: 1242 return true; // We have r + r or r + i. 1243 case 2: 1244 if (AM.HasBaseReg) { 1245 // Reject 2 * r + r. 1246 return false; 1247 } 1248 1249 // Allow 2 * r as r + r 1250 // Or 2 * r + i is allowed as r + r + i. 1251 return true; 1252 default: // Don't allow n * r 1253 return false; 1254 } 1255 } 1256 1257 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1258 const AddrMode &AM, Type *Ty, 1259 unsigned AS, Instruction *I) const { 1260 // No global is ever allowed as a base. 1261 if (AM.BaseGV) 1262 return false; 1263 1264 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1265 return isLegalGlobalAddressingMode(AM); 1266 1267 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1268 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1269 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1270 // If the offset isn't a multiple of 4, it probably isn't going to be 1271 // correctly aligned. 1272 // FIXME: Can we get the real alignment here? 1273 if (AM.BaseOffs % 4 != 0) 1274 return isLegalMUBUFAddressingMode(AM); 1275 1276 // There are no SMRD extloads, so if we have to do a small type access we 1277 // will use a MUBUF load. 1278 // FIXME?: We also need to do this if unaligned, but we don't know the 1279 // alignment here. 1280 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1281 return isLegalGlobalAddressingMode(AM); 1282 1283 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1284 // SMRD instructions have an 8-bit, dword offset on SI. 1285 if (!isUInt<8>(AM.BaseOffs / 4)) 1286 return false; 1287 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1288 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1289 // in 8-bits, it can use a smaller encoding. 1290 if (!isUInt<32>(AM.BaseOffs / 4)) 1291 return false; 1292 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1293 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1294 if (!isUInt<20>(AM.BaseOffs)) 1295 return false; 1296 } else 1297 llvm_unreachable("unhandled generation"); 1298 1299 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1300 return true; 1301 1302 if (AM.Scale == 1 && AM.HasBaseReg) 1303 return true; 1304 1305 return false; 1306 1307 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1308 return isLegalMUBUFAddressingMode(AM); 1309 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1310 AS == AMDGPUAS::REGION_ADDRESS) { 1311 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1312 // field. 1313 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1314 // an 8-bit dword offset but we don't know the alignment here. 1315 if (!isUInt<16>(AM.BaseOffs)) 1316 return false; 1317 1318 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1319 return true; 1320 1321 if (AM.Scale == 1 && AM.HasBaseReg) 1322 return true; 1323 1324 return false; 1325 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1326 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1327 // For an unknown address space, this usually means that this is for some 1328 // reason being used for pure arithmetic, and not based on some addressing 1329 // computation. We don't have instructions that compute pointers with any 1330 // addressing modes, so treat them as having no offset like flat 1331 // instructions. 1332 return isLegalFlatAddressingMode(AM); 1333 } 1334 1335 // Assume a user alias of global for unknown address spaces. 1336 return isLegalGlobalAddressingMode(AM); 1337 } 1338 1339 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1340 const MachineFunction &MF) const { 1341 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1342 return (MemVT.getSizeInBits() <= 4 * 32); 1343 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1344 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1345 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1346 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1347 return (MemVT.getSizeInBits() <= 2 * 32); 1348 } 1349 return true; 1350 } 1351 1352 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1353 unsigned Size, unsigned AddrSpace, Align Alignment, 1354 MachineMemOperand::Flags Flags, bool *IsFast) const { 1355 if (IsFast) 1356 *IsFast = false; 1357 1358 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1359 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1360 // Check if alignment requirements for ds_read/write instructions are 1361 // disabled. 1362 if (!Subtarget->hasUnalignedDSAccessEnabled() && Alignment < Align(4)) 1363 return false; 1364 1365 Align RequiredAlignment(PowerOf2Ceil(Size/8)); // Natural alignment. 1366 if (Subtarget->hasLDSMisalignedBug() && Size > 32 && 1367 Alignment < RequiredAlignment) 1368 return false; 1369 1370 // Either, the alignment requirements are "enabled", or there is an 1371 // unaligned LDS access related hardware bug though alignment requirements 1372 // are "disabled". In either case, we need to check for proper alignment 1373 // requirements. 1374 // 1375 switch (Size) { 1376 case 64: 1377 // SI has a hardware bug in the LDS / GDS bounds checking: if the base 1378 // address is negative, then the instruction is incorrectly treated as 1379 // out-of-bounds even if base + offsets is in bounds. Split vectorized 1380 // loads here to avoid emitting ds_read2_b32. We may re-combine the 1381 // load later in the SILoadStoreOptimizer. 1382 if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8)) 1383 return false; 1384 1385 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we 1386 // can do a 4 byte aligned, 8 byte access in a single operation using 1387 // ds_read2/write2_b32 with adjacent offsets. 1388 RequiredAlignment = Align(4); 1389 1390 if (Subtarget->hasUnalignedDSAccessEnabled()) { 1391 // We will either select ds_read_b64/ds_write_b64 or ds_read2_b32/ 1392 // ds_write2_b32 depending on the alignment. In either case with either 1393 // alignment there is no faster way of doing this. 1394 if (IsFast) 1395 *IsFast = true; 1396 return true; 1397 } 1398 1399 break; 1400 case 96: 1401 if (!Subtarget->hasDS96AndDS128()) 1402 return false; 1403 1404 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on 1405 // gfx8 and older. 1406 1407 if (Subtarget->hasUnalignedDSAccessEnabled()) { 1408 // Naturally aligned access is fastest. However, also report it is Fast 1409 // if memory is aligned less than DWORD. A narrow load or store will be 1410 // be equally slow as a single ds_read_b96/ds_write_b96, but there will 1411 // be more of them, so overall we will pay less penalty issuing a single 1412 // instruction. 1413 if (IsFast) 1414 *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4); 1415 return true; 1416 } 1417 1418 break; 1419 case 128: 1420 if (!Subtarget->hasDS96AndDS128() || !Subtarget->useDS128()) 1421 return false; 1422 1423 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on 1424 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a 1425 // single operation using ds_read2/write2_b64. 1426 RequiredAlignment = Align(8); 1427 1428 if (Subtarget->hasUnalignedDSAccessEnabled()) { 1429 // Naturally aligned access is fastest. However, also report it is Fast 1430 // if memory is aligned less than DWORD. A narrow load or store will be 1431 // be equally slow as a single ds_read_b128/ds_write_b128, but there 1432 // will be more of them, so overall we will pay less penalty issuing a 1433 // single instruction. 1434 if (IsFast) 1435 *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4); 1436 return true; 1437 } 1438 1439 break; 1440 default: 1441 if (Size > 32) 1442 return false; 1443 1444 break; 1445 } 1446 1447 if (IsFast) 1448 *IsFast = Alignment >= RequiredAlignment; 1449 1450 return Alignment >= RequiredAlignment || 1451 Subtarget->hasUnalignedDSAccessEnabled(); 1452 } 1453 1454 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1455 bool AlignedBy4 = Alignment >= Align(4); 1456 if (IsFast) 1457 *IsFast = AlignedBy4; 1458 1459 return AlignedBy4 || 1460 Subtarget->enableFlatScratch() || 1461 Subtarget->hasUnalignedScratchAccess(); 1462 } 1463 1464 // FIXME: We have to be conservative here and assume that flat operations 1465 // will access scratch. If we had access to the IR function, then we 1466 // could determine if any private memory was used in the function. 1467 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1468 !Subtarget->hasUnalignedScratchAccess()) { 1469 bool AlignedBy4 = Alignment >= Align(4); 1470 if (IsFast) 1471 *IsFast = AlignedBy4; 1472 1473 return AlignedBy4; 1474 } 1475 1476 if (Subtarget->hasUnalignedBufferAccessEnabled()) { 1477 // If we have a uniform constant load, it still requires using a slow 1478 // buffer instruction if unaligned. 1479 if (IsFast) { 1480 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1481 // 2-byte alignment is worse than 1 unless doing a 2-byte access. 1482 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1483 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1484 Alignment >= Align(4) : Alignment != Align(2); 1485 } 1486 1487 return true; 1488 } 1489 1490 // Smaller than dword value must be aligned. 1491 if (Size < 32) 1492 return false; 1493 1494 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1495 // byte-address are ignored, thus forcing Dword alignment. 1496 // This applies to private, global, and constant memory. 1497 if (IsFast) 1498 *IsFast = true; 1499 1500 return Size >= 32 && Alignment >= Align(4); 1501 } 1502 1503 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1504 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1505 bool *IsFast) const { 1506 bool Allow = allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1507 Alignment, Flags, IsFast); 1508 1509 if (Allow && IsFast && Subtarget->hasUnalignedDSAccessEnabled() && 1510 (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1511 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1512 // Lie it is fast if +unaligned-access-mode is passed so that DS accesses 1513 // get vectorized. We could use ds_read2_b*/ds_write2_b* instructions on a 1514 // misaligned data which is faster than a pair of ds_read_b*/ds_write_b* 1515 // which would be equally misaligned. 1516 // This is only used by the common passes, selection always calls the 1517 // allowsMisalignedMemoryAccessesImpl version. 1518 *IsFast = true; 1519 } 1520 1521 return Allow; 1522 } 1523 1524 EVT SITargetLowering::getOptimalMemOpType( 1525 const MemOp &Op, const AttributeList &FuncAttributes) const { 1526 // FIXME: Should account for address space here. 1527 1528 // The default fallback uses the private pointer size as a guess for a type to 1529 // use. Make sure we switch these to 64-bit accesses. 1530 1531 if (Op.size() >= 16 && 1532 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1533 return MVT::v4i32; 1534 1535 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1536 return MVT::v2i32; 1537 1538 // Use the default. 1539 return MVT::Other; 1540 } 1541 1542 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1543 const MemSDNode *MemNode = cast<MemSDNode>(N); 1544 return MemNode->getMemOperand()->getFlags() & MONoClobber; 1545 } 1546 1547 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1548 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1549 AS == AMDGPUAS::PRIVATE_ADDRESS; 1550 } 1551 1552 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1553 unsigned DestAS) const { 1554 // Flat -> private/local is a simple truncate. 1555 // Flat -> global is no-op 1556 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1557 return true; 1558 1559 const GCNTargetMachine &TM = 1560 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1561 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1562 } 1563 1564 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1565 const MemSDNode *MemNode = cast<MemSDNode>(N); 1566 1567 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1568 } 1569 1570 TargetLoweringBase::LegalizeTypeAction 1571 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1572 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 && 1573 VT.getScalarType().bitsLE(MVT::i16)) 1574 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1575 return TargetLoweringBase::getPreferredVectorAction(VT); 1576 } 1577 1578 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1579 Type *Ty) const { 1580 // FIXME: Could be smarter if called for vector constants. 1581 return true; 1582 } 1583 1584 bool SITargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 1585 unsigned Index) const { 1586 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 1587 return false; 1588 1589 // TODO: Add more cases that are cheap. 1590 return Index == 0; 1591 } 1592 1593 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1594 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1595 switch (Op) { 1596 case ISD::LOAD: 1597 case ISD::STORE: 1598 1599 // These operations are done with 32-bit instructions anyway. 1600 case ISD::AND: 1601 case ISD::OR: 1602 case ISD::XOR: 1603 case ISD::SELECT: 1604 // TODO: Extensions? 1605 return true; 1606 default: 1607 return false; 1608 } 1609 } 1610 1611 // SimplifySetCC uses this function to determine whether or not it should 1612 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1613 if (VT == MVT::i1 && Op == ISD::SETCC) 1614 return false; 1615 1616 return TargetLowering::isTypeDesirableForOp(Op, VT); 1617 } 1618 1619 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1620 const SDLoc &SL, 1621 SDValue Chain, 1622 uint64_t Offset) const { 1623 const DataLayout &DL = DAG.getDataLayout(); 1624 MachineFunction &MF = DAG.getMachineFunction(); 1625 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1626 1627 const ArgDescriptor *InputPtrReg; 1628 const TargetRegisterClass *RC; 1629 LLT ArgTy; 1630 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1631 1632 std::tie(InputPtrReg, RC, ArgTy) = 1633 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1634 1635 // We may not have the kernarg segment argument if we have no kernel 1636 // arguments. 1637 if (!InputPtrReg) 1638 return DAG.getConstant(0, SL, PtrVT); 1639 1640 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1641 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1642 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1643 1644 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1645 } 1646 1647 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1648 const SDLoc &SL) const { 1649 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1650 FIRST_IMPLICIT); 1651 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1652 } 1653 1654 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1655 const SDLoc &SL, SDValue Val, 1656 bool Signed, 1657 const ISD::InputArg *Arg) const { 1658 // First, if it is a widened vector, narrow it. 1659 if (VT.isVector() && 1660 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1661 EVT NarrowedVT = 1662 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1663 VT.getVectorNumElements()); 1664 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1665 DAG.getConstant(0, SL, MVT::i32)); 1666 } 1667 1668 // Then convert the vector elements or scalar value. 1669 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1670 VT.bitsLT(MemVT)) { 1671 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1672 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1673 } 1674 1675 if (MemVT.isFloatingPoint()) 1676 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1677 else if (Signed) 1678 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1679 else 1680 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1681 1682 return Val; 1683 } 1684 1685 SDValue SITargetLowering::lowerKernargMemParameter( 1686 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1687 uint64_t Offset, Align Alignment, bool Signed, 1688 const ISD::InputArg *Arg) const { 1689 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1690 1691 // Try to avoid using an extload by loading earlier than the argument address, 1692 // and extracting the relevant bits. The load should hopefully be merged with 1693 // the previous argument. 1694 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1695 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1696 int64_t AlignDownOffset = alignDown(Offset, 4); 1697 int64_t OffsetDiff = Offset - AlignDownOffset; 1698 1699 EVT IntVT = MemVT.changeTypeToInteger(); 1700 1701 // TODO: If we passed in the base kernel offset we could have a better 1702 // alignment than 4, but we don't really need it. 1703 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1704 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1705 MachineMemOperand::MODereferenceable | 1706 MachineMemOperand::MOInvariant); 1707 1708 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1709 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1710 1711 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1712 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1713 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1714 1715 1716 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1717 } 1718 1719 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1720 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1721 MachineMemOperand::MODereferenceable | 1722 MachineMemOperand::MOInvariant); 1723 1724 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1725 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1726 } 1727 1728 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1729 const SDLoc &SL, SDValue Chain, 1730 const ISD::InputArg &Arg) const { 1731 MachineFunction &MF = DAG.getMachineFunction(); 1732 MachineFrameInfo &MFI = MF.getFrameInfo(); 1733 1734 if (Arg.Flags.isByVal()) { 1735 unsigned Size = Arg.Flags.getByValSize(); 1736 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1737 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1738 } 1739 1740 unsigned ArgOffset = VA.getLocMemOffset(); 1741 unsigned ArgSize = VA.getValVT().getStoreSize(); 1742 1743 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1744 1745 // Create load nodes to retrieve arguments from the stack. 1746 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1747 SDValue ArgValue; 1748 1749 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1750 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1751 MVT MemVT = VA.getValVT(); 1752 1753 switch (VA.getLocInfo()) { 1754 default: 1755 break; 1756 case CCValAssign::BCvt: 1757 MemVT = VA.getLocVT(); 1758 break; 1759 case CCValAssign::SExt: 1760 ExtType = ISD::SEXTLOAD; 1761 break; 1762 case CCValAssign::ZExt: 1763 ExtType = ISD::ZEXTLOAD; 1764 break; 1765 case CCValAssign::AExt: 1766 ExtType = ISD::EXTLOAD; 1767 break; 1768 } 1769 1770 ArgValue = DAG.getExtLoad( 1771 ExtType, SL, VA.getLocVT(), Chain, FIN, 1772 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1773 MemVT); 1774 return ArgValue; 1775 } 1776 1777 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1778 const SIMachineFunctionInfo &MFI, 1779 EVT VT, 1780 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1781 const ArgDescriptor *Reg; 1782 const TargetRegisterClass *RC; 1783 LLT Ty; 1784 1785 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1786 if (!Reg) { 1787 if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) { 1788 // It's possible for a kernarg intrinsic call to appear in a kernel with 1789 // no allocated segment, in which case we do not add the user sgpr 1790 // argument, so just return null. 1791 return DAG.getConstant(0, SDLoc(), VT); 1792 } 1793 1794 // It's undefined behavior if a function marked with the amdgpu-no-* 1795 // attributes uses the corresponding intrinsic. 1796 return DAG.getUNDEF(VT); 1797 } 1798 1799 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1800 } 1801 1802 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1803 CallingConv::ID CallConv, 1804 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1805 FunctionType *FType, 1806 SIMachineFunctionInfo *Info) { 1807 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1808 const ISD::InputArg *Arg = &Ins[I]; 1809 1810 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1811 "vector type argument should have been split"); 1812 1813 // First check if it's a PS input addr. 1814 if (CallConv == CallingConv::AMDGPU_PS && 1815 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1816 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1817 1818 // Inconveniently only the first part of the split is marked as isSplit, 1819 // so skip to the end. We only want to increment PSInputNum once for the 1820 // entire split argument. 1821 if (Arg->Flags.isSplit()) { 1822 while (!Arg->Flags.isSplitEnd()) { 1823 assert((!Arg->VT.isVector() || 1824 Arg->VT.getScalarSizeInBits() == 16) && 1825 "unexpected vector split in ps argument type"); 1826 if (!SkipArg) 1827 Splits.push_back(*Arg); 1828 Arg = &Ins[++I]; 1829 } 1830 } 1831 1832 if (SkipArg) { 1833 // We can safely skip PS inputs. 1834 Skipped.set(Arg->getOrigArgIndex()); 1835 ++PSInputNum; 1836 continue; 1837 } 1838 1839 Info->markPSInputAllocated(PSInputNum); 1840 if (Arg->Used) 1841 Info->markPSInputEnabled(PSInputNum); 1842 1843 ++PSInputNum; 1844 } 1845 1846 Splits.push_back(*Arg); 1847 } 1848 } 1849 1850 // Allocate special inputs passed in VGPRs. 1851 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1852 MachineFunction &MF, 1853 const SIRegisterInfo &TRI, 1854 SIMachineFunctionInfo &Info) const { 1855 const LLT S32 = LLT::scalar(32); 1856 MachineRegisterInfo &MRI = MF.getRegInfo(); 1857 1858 if (Info.hasWorkItemIDX()) { 1859 Register Reg = AMDGPU::VGPR0; 1860 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1861 1862 CCInfo.AllocateReg(Reg); 1863 unsigned Mask = (Subtarget->hasPackedTID() && 1864 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 1865 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1866 } 1867 1868 if (Info.hasWorkItemIDY()) { 1869 assert(Info.hasWorkItemIDX()); 1870 if (Subtarget->hasPackedTID()) { 1871 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1872 0x3ff << 10)); 1873 } else { 1874 unsigned Reg = AMDGPU::VGPR1; 1875 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1876 1877 CCInfo.AllocateReg(Reg); 1878 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1879 } 1880 } 1881 1882 if (Info.hasWorkItemIDZ()) { 1883 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 1884 if (Subtarget->hasPackedTID()) { 1885 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1886 0x3ff << 20)); 1887 } else { 1888 unsigned Reg = AMDGPU::VGPR2; 1889 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1890 1891 CCInfo.AllocateReg(Reg); 1892 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1893 } 1894 } 1895 } 1896 1897 // Try to allocate a VGPR at the end of the argument list, or if no argument 1898 // VGPRs are left allocating a stack slot. 1899 // If \p Mask is is given it indicates bitfield position in the register. 1900 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1901 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1902 ArgDescriptor Arg = ArgDescriptor()) { 1903 if (Arg.isSet()) 1904 return ArgDescriptor::createArg(Arg, Mask); 1905 1906 ArrayRef<MCPhysReg> ArgVGPRs 1907 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1908 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1909 if (RegIdx == ArgVGPRs.size()) { 1910 // Spill to stack required. 1911 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1912 1913 return ArgDescriptor::createStack(Offset, Mask); 1914 } 1915 1916 unsigned Reg = ArgVGPRs[RegIdx]; 1917 Reg = CCInfo.AllocateReg(Reg); 1918 assert(Reg != AMDGPU::NoRegister); 1919 1920 MachineFunction &MF = CCInfo.getMachineFunction(); 1921 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1922 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1923 return ArgDescriptor::createRegister(Reg, Mask); 1924 } 1925 1926 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1927 const TargetRegisterClass *RC, 1928 unsigned NumArgRegs) { 1929 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1930 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1931 if (RegIdx == ArgSGPRs.size()) 1932 report_fatal_error("ran out of SGPRs for arguments"); 1933 1934 unsigned Reg = ArgSGPRs[RegIdx]; 1935 Reg = CCInfo.AllocateReg(Reg); 1936 assert(Reg != AMDGPU::NoRegister); 1937 1938 MachineFunction &MF = CCInfo.getMachineFunction(); 1939 MF.addLiveIn(Reg, RC); 1940 return ArgDescriptor::createRegister(Reg); 1941 } 1942 1943 // If this has a fixed position, we still should allocate the register in the 1944 // CCInfo state. Technically we could get away with this for values passed 1945 // outside of the normal argument range. 1946 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 1947 const TargetRegisterClass *RC, 1948 MCRegister Reg) { 1949 Reg = CCInfo.AllocateReg(Reg); 1950 assert(Reg != AMDGPU::NoRegister); 1951 MachineFunction &MF = CCInfo.getMachineFunction(); 1952 MF.addLiveIn(Reg, RC); 1953 } 1954 1955 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 1956 if (Arg) { 1957 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 1958 Arg.getRegister()); 1959 } else 1960 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1961 } 1962 1963 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 1964 if (Arg) { 1965 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 1966 Arg.getRegister()); 1967 } else 1968 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1969 } 1970 1971 /// Allocate implicit function VGPR arguments at the end of allocated user 1972 /// arguments. 1973 void SITargetLowering::allocateSpecialInputVGPRs( 1974 CCState &CCInfo, MachineFunction &MF, 1975 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1976 const unsigned Mask = 0x3ff; 1977 ArgDescriptor Arg; 1978 1979 if (Info.hasWorkItemIDX()) { 1980 Arg = allocateVGPR32Input(CCInfo, Mask); 1981 Info.setWorkItemIDX(Arg); 1982 } 1983 1984 if (Info.hasWorkItemIDY()) { 1985 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1986 Info.setWorkItemIDY(Arg); 1987 } 1988 1989 if (Info.hasWorkItemIDZ()) 1990 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1991 } 1992 1993 /// Allocate implicit function VGPR arguments in fixed registers. 1994 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1995 CCState &CCInfo, MachineFunction &MF, 1996 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1997 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1998 if (!Reg) 1999 report_fatal_error("failed to allocated VGPR for implicit arguments"); 2000 2001 const unsigned Mask = 0x3ff; 2002 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 2003 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 2004 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 2005 } 2006 2007 void SITargetLowering::allocateSpecialInputSGPRs( 2008 CCState &CCInfo, 2009 MachineFunction &MF, 2010 const SIRegisterInfo &TRI, 2011 SIMachineFunctionInfo &Info) const { 2012 auto &ArgInfo = Info.getArgInfo(); 2013 2014 // TODO: Unify handling with private memory pointers. 2015 if (Info.hasDispatchPtr()) 2016 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 2017 2018 if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) 2019 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 2020 2021 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 2022 // constant offset from the kernarg segment. 2023 if (Info.hasImplicitArgPtr()) 2024 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 2025 2026 if (Info.hasDispatchID()) 2027 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 2028 2029 // flat_scratch_init is not applicable for non-kernel functions. 2030 2031 if (Info.hasWorkGroupIDX()) 2032 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2033 2034 if (Info.hasWorkGroupIDY()) 2035 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2036 2037 if (Info.hasWorkGroupIDZ()) 2038 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2039 } 2040 2041 // Allocate special inputs passed in user SGPRs. 2042 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2043 MachineFunction &MF, 2044 const SIRegisterInfo &TRI, 2045 SIMachineFunctionInfo &Info) const { 2046 if (Info.hasImplicitBufferPtr()) { 2047 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2048 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2049 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2050 } 2051 2052 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2053 if (Info.hasPrivateSegmentBuffer()) { 2054 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2055 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2056 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2057 } 2058 2059 if (Info.hasDispatchPtr()) { 2060 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2061 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2062 CCInfo.AllocateReg(DispatchPtrReg); 2063 } 2064 2065 if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) { 2066 Register QueuePtrReg = Info.addQueuePtr(TRI); 2067 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2068 CCInfo.AllocateReg(QueuePtrReg); 2069 } 2070 2071 if (Info.hasKernargSegmentPtr()) { 2072 MachineRegisterInfo &MRI = MF.getRegInfo(); 2073 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2074 CCInfo.AllocateReg(InputPtrReg); 2075 2076 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2077 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2078 } 2079 2080 if (Info.hasDispatchID()) { 2081 Register DispatchIDReg = Info.addDispatchID(TRI); 2082 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2083 CCInfo.AllocateReg(DispatchIDReg); 2084 } 2085 2086 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2087 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2088 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2089 CCInfo.AllocateReg(FlatScratchInitReg); 2090 } 2091 2092 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2093 // these from the dispatch pointer. 2094 } 2095 2096 // Allocate special input registers that are initialized per-wave. 2097 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2098 MachineFunction &MF, 2099 SIMachineFunctionInfo &Info, 2100 CallingConv::ID CallConv, 2101 bool IsShader) const { 2102 if (Info.hasWorkGroupIDX()) { 2103 Register Reg = Info.addWorkGroupIDX(); 2104 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2105 CCInfo.AllocateReg(Reg); 2106 } 2107 2108 if (Info.hasWorkGroupIDY()) { 2109 Register Reg = Info.addWorkGroupIDY(); 2110 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2111 CCInfo.AllocateReg(Reg); 2112 } 2113 2114 if (Info.hasWorkGroupIDZ()) { 2115 Register Reg = Info.addWorkGroupIDZ(); 2116 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2117 CCInfo.AllocateReg(Reg); 2118 } 2119 2120 if (Info.hasWorkGroupInfo()) { 2121 Register Reg = Info.addWorkGroupInfo(); 2122 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2123 CCInfo.AllocateReg(Reg); 2124 } 2125 2126 if (Info.hasPrivateSegmentWaveByteOffset()) { 2127 // Scratch wave offset passed in system SGPR. 2128 unsigned PrivateSegmentWaveByteOffsetReg; 2129 2130 if (IsShader) { 2131 PrivateSegmentWaveByteOffsetReg = 2132 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2133 2134 // This is true if the scratch wave byte offset doesn't have a fixed 2135 // location. 2136 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2137 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2138 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2139 } 2140 } else 2141 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2142 2143 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2144 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2145 } 2146 } 2147 2148 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2149 MachineFunction &MF, 2150 const SIRegisterInfo &TRI, 2151 SIMachineFunctionInfo &Info) { 2152 // Now that we've figured out where the scratch register inputs are, see if 2153 // should reserve the arguments and use them directly. 2154 MachineFrameInfo &MFI = MF.getFrameInfo(); 2155 bool HasStackObjects = MFI.hasStackObjects(); 2156 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2157 2158 // Record that we know we have non-spill stack objects so we don't need to 2159 // check all stack objects later. 2160 if (HasStackObjects) 2161 Info.setHasNonSpillStackObjects(true); 2162 2163 // Everything live out of a block is spilled with fast regalloc, so it's 2164 // almost certain that spilling will be required. 2165 if (TM.getOptLevel() == CodeGenOpt::None) 2166 HasStackObjects = true; 2167 2168 // For now assume stack access is needed in any callee functions, so we need 2169 // the scratch registers to pass in. 2170 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2171 2172 if (!ST.enableFlatScratch()) { 2173 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2174 // If we have stack objects, we unquestionably need the private buffer 2175 // resource. For the Code Object V2 ABI, this will be the first 4 user 2176 // SGPR inputs. We can reserve those and use them directly. 2177 2178 Register PrivateSegmentBufferReg = 2179 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2180 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2181 } else { 2182 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2183 // We tentatively reserve the last registers (skipping the last registers 2184 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2185 // we'll replace these with the ones immediately after those which were 2186 // really allocated. In the prologue copies will be inserted from the 2187 // argument to these reserved registers. 2188 2189 // Without HSA, relocations are used for the scratch pointer and the 2190 // buffer resource setup is always inserted in the prologue. Scratch wave 2191 // offset is still in an input SGPR. 2192 Info.setScratchRSrcReg(ReservedBufferReg); 2193 } 2194 } 2195 2196 MachineRegisterInfo &MRI = MF.getRegInfo(); 2197 2198 // For entry functions we have to set up the stack pointer if we use it, 2199 // whereas non-entry functions get this "for free". This means there is no 2200 // intrinsic advantage to using S32 over S34 in cases where we do not have 2201 // calls but do need a frame pointer (i.e. if we are requested to have one 2202 // because frame pointer elimination is disabled). To keep things simple we 2203 // only ever use S32 as the call ABI stack pointer, and so using it does not 2204 // imply we need a separate frame pointer. 2205 // 2206 // Try to use s32 as the SP, but move it if it would interfere with input 2207 // arguments. This won't work with calls though. 2208 // 2209 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2210 // registers. 2211 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2212 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2213 } else { 2214 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2215 2216 if (MFI.hasCalls()) 2217 report_fatal_error("call in graphics shader with too many input SGPRs"); 2218 2219 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2220 if (!MRI.isLiveIn(Reg)) { 2221 Info.setStackPtrOffsetReg(Reg); 2222 break; 2223 } 2224 } 2225 2226 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2227 report_fatal_error("failed to find register for SP"); 2228 } 2229 2230 // hasFP should be accurate for entry functions even before the frame is 2231 // finalized, because it does not rely on the known stack size, only 2232 // properties like whether variable sized objects are present. 2233 if (ST.getFrameLowering()->hasFP(MF)) { 2234 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2235 } 2236 } 2237 2238 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2239 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2240 return !Info->isEntryFunction(); 2241 } 2242 2243 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2244 2245 } 2246 2247 void SITargetLowering::insertCopiesSplitCSR( 2248 MachineBasicBlock *Entry, 2249 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2250 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2251 2252 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2253 if (!IStart) 2254 return; 2255 2256 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2257 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2258 MachineBasicBlock::iterator MBBI = Entry->begin(); 2259 for (const MCPhysReg *I = IStart; *I; ++I) { 2260 const TargetRegisterClass *RC = nullptr; 2261 if (AMDGPU::SReg_64RegClass.contains(*I)) 2262 RC = &AMDGPU::SGPR_64RegClass; 2263 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2264 RC = &AMDGPU::SGPR_32RegClass; 2265 else 2266 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2267 2268 Register NewVR = MRI->createVirtualRegister(RC); 2269 // Create copy from CSR to a virtual register. 2270 Entry->addLiveIn(*I); 2271 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2272 .addReg(*I); 2273 2274 // Insert the copy-back instructions right before the terminator. 2275 for (auto *Exit : Exits) 2276 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2277 TII->get(TargetOpcode::COPY), *I) 2278 .addReg(NewVR); 2279 } 2280 } 2281 2282 SDValue SITargetLowering::LowerFormalArguments( 2283 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2284 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2285 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2286 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2287 2288 MachineFunction &MF = DAG.getMachineFunction(); 2289 const Function &Fn = MF.getFunction(); 2290 FunctionType *FType = MF.getFunction().getFunctionType(); 2291 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2292 2293 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2294 DiagnosticInfoUnsupported NoGraphicsHSA( 2295 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2296 DAG.getContext()->diagnose(NoGraphicsHSA); 2297 return DAG.getEntryNode(); 2298 } 2299 2300 Info->allocateModuleLDSGlobal(Fn); 2301 2302 SmallVector<ISD::InputArg, 16> Splits; 2303 SmallVector<CCValAssign, 16> ArgLocs; 2304 BitVector Skipped(Ins.size()); 2305 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2306 *DAG.getContext()); 2307 2308 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2309 bool IsKernel = AMDGPU::isKernel(CallConv); 2310 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2311 2312 if (IsGraphics) { 2313 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2314 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2315 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2316 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2317 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2318 !Info->hasWorkItemIDZ()); 2319 } 2320 2321 if (CallConv == CallingConv::AMDGPU_PS) { 2322 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2323 2324 // At least one interpolation mode must be enabled or else the GPU will 2325 // hang. 2326 // 2327 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2328 // set PSInputAddr, the user wants to enable some bits after the compilation 2329 // based on run-time states. Since we can't know what the final PSInputEna 2330 // will look like, so we shouldn't do anything here and the user should take 2331 // responsibility for the correct programming. 2332 // 2333 // Otherwise, the following restrictions apply: 2334 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2335 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2336 // enabled too. 2337 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2338 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2339 CCInfo.AllocateReg(AMDGPU::VGPR0); 2340 CCInfo.AllocateReg(AMDGPU::VGPR1); 2341 Info->markPSInputAllocated(0); 2342 Info->markPSInputEnabled(0); 2343 } 2344 if (Subtarget->isAmdPalOS()) { 2345 // For isAmdPalOS, the user does not enable some bits after compilation 2346 // based on run-time states; the register values being generated here are 2347 // the final ones set in hardware. Therefore we need to apply the 2348 // workaround to PSInputAddr and PSInputEnable together. (The case where 2349 // a bit is set in PSInputAddr but not PSInputEnable is where the 2350 // frontend set up an input arg for a particular interpolation mode, but 2351 // nothing uses that input arg. Really we should have an earlier pass 2352 // that removes such an arg.) 2353 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2354 if ((PsInputBits & 0x7F) == 0 || 2355 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2356 Info->markPSInputEnabled( 2357 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2358 } 2359 } else if (IsKernel) { 2360 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2361 } else { 2362 Splits.append(Ins.begin(), Ins.end()); 2363 } 2364 2365 if (IsEntryFunc) { 2366 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2367 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2368 } else if (!IsGraphics) { 2369 // For the fixed ABI, pass workitem IDs in the last argument register. 2370 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2371 } 2372 2373 if (IsKernel) { 2374 analyzeFormalArgumentsCompute(CCInfo, Ins); 2375 } else { 2376 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2377 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2378 } 2379 2380 SmallVector<SDValue, 16> Chains; 2381 2382 // FIXME: This is the minimum kernel argument alignment. We should improve 2383 // this to the maximum alignment of the arguments. 2384 // 2385 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2386 // kern arg offset. 2387 const Align KernelArgBaseAlign = Align(16); 2388 2389 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2390 const ISD::InputArg &Arg = Ins[i]; 2391 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2392 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2393 continue; 2394 } 2395 2396 CCValAssign &VA = ArgLocs[ArgIdx++]; 2397 MVT VT = VA.getLocVT(); 2398 2399 if (IsEntryFunc && VA.isMemLoc()) { 2400 VT = Ins[i].VT; 2401 EVT MemVT = VA.getLocVT(); 2402 2403 const uint64_t Offset = VA.getLocMemOffset(); 2404 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2405 2406 if (Arg.Flags.isByRef()) { 2407 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2408 2409 const GCNTargetMachine &TM = 2410 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2411 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2412 Arg.Flags.getPointerAddrSpace())) { 2413 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2414 Arg.Flags.getPointerAddrSpace()); 2415 } 2416 2417 InVals.push_back(Ptr); 2418 continue; 2419 } 2420 2421 SDValue Arg = lowerKernargMemParameter( 2422 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2423 Chains.push_back(Arg.getValue(1)); 2424 2425 auto *ParamTy = 2426 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2427 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2428 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2429 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2430 // On SI local pointers are just offsets into LDS, so they are always 2431 // less than 16-bits. On CI and newer they could potentially be 2432 // real pointers, so we can't guarantee their size. 2433 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2434 DAG.getValueType(MVT::i16)); 2435 } 2436 2437 InVals.push_back(Arg); 2438 continue; 2439 } else if (!IsEntryFunc && VA.isMemLoc()) { 2440 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2441 InVals.push_back(Val); 2442 if (!Arg.Flags.isByVal()) 2443 Chains.push_back(Val.getValue(1)); 2444 continue; 2445 } 2446 2447 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2448 2449 Register Reg = VA.getLocReg(); 2450 const TargetRegisterClass *RC = nullptr; 2451 if (AMDGPU::VGPR_32RegClass.contains(Reg)) 2452 RC = &AMDGPU::VGPR_32RegClass; 2453 else if (AMDGPU::SGPR_32RegClass.contains(Reg)) 2454 RC = &AMDGPU::SGPR_32RegClass; 2455 else 2456 llvm_unreachable("Unexpected register class in LowerFormalArguments!"); 2457 EVT ValVT = VA.getValVT(); 2458 2459 Reg = MF.addLiveIn(Reg, RC); 2460 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2461 2462 if (Arg.Flags.isSRet()) { 2463 // The return object should be reasonably addressable. 2464 2465 // FIXME: This helps when the return is a real sret. If it is a 2466 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2467 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2468 unsigned NumBits 2469 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2470 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2471 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2472 } 2473 2474 // If this is an 8 or 16-bit value, it is really passed promoted 2475 // to 32 bits. Insert an assert[sz]ext to capture this, then 2476 // truncate to the right size. 2477 switch (VA.getLocInfo()) { 2478 case CCValAssign::Full: 2479 break; 2480 case CCValAssign::BCvt: 2481 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2482 break; 2483 case CCValAssign::SExt: 2484 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2485 DAG.getValueType(ValVT)); 2486 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2487 break; 2488 case CCValAssign::ZExt: 2489 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2490 DAG.getValueType(ValVT)); 2491 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2492 break; 2493 case CCValAssign::AExt: 2494 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2495 break; 2496 default: 2497 llvm_unreachable("Unknown loc info!"); 2498 } 2499 2500 InVals.push_back(Val); 2501 } 2502 2503 // Start adding system SGPRs. 2504 if (IsEntryFunc) { 2505 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2506 } else { 2507 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2508 if (!IsGraphics) 2509 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2510 } 2511 2512 auto &ArgUsageInfo = 2513 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2514 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2515 2516 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2517 Info->setBytesInStackArgArea(StackArgSize); 2518 2519 return Chains.empty() ? Chain : 2520 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2521 } 2522 2523 // TODO: If return values can't fit in registers, we should return as many as 2524 // possible in registers before passing on stack. 2525 bool SITargetLowering::CanLowerReturn( 2526 CallingConv::ID CallConv, 2527 MachineFunction &MF, bool IsVarArg, 2528 const SmallVectorImpl<ISD::OutputArg> &Outs, 2529 LLVMContext &Context) const { 2530 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2531 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2532 // for shaders. Vector types should be explicitly handled by CC. 2533 if (AMDGPU::isEntryFunctionCC(CallConv)) 2534 return true; 2535 2536 SmallVector<CCValAssign, 16> RVLocs; 2537 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2538 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2539 } 2540 2541 SDValue 2542 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2543 bool isVarArg, 2544 const SmallVectorImpl<ISD::OutputArg> &Outs, 2545 const SmallVectorImpl<SDValue> &OutVals, 2546 const SDLoc &DL, SelectionDAG &DAG) const { 2547 MachineFunction &MF = DAG.getMachineFunction(); 2548 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2549 2550 if (AMDGPU::isKernel(CallConv)) { 2551 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2552 OutVals, DL, DAG); 2553 } 2554 2555 bool IsShader = AMDGPU::isShader(CallConv); 2556 2557 Info->setIfReturnsVoid(Outs.empty()); 2558 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2559 2560 // CCValAssign - represent the assignment of the return value to a location. 2561 SmallVector<CCValAssign, 48> RVLocs; 2562 SmallVector<ISD::OutputArg, 48> Splits; 2563 2564 // CCState - Info about the registers and stack slots. 2565 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2566 *DAG.getContext()); 2567 2568 // Analyze outgoing return values. 2569 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2570 2571 SDValue Flag; 2572 SmallVector<SDValue, 48> RetOps; 2573 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2574 2575 // Copy the result values into the output registers. 2576 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2577 ++I, ++RealRVLocIdx) { 2578 CCValAssign &VA = RVLocs[I]; 2579 assert(VA.isRegLoc() && "Can only return in registers!"); 2580 // TODO: Partially return in registers if return values don't fit. 2581 SDValue Arg = OutVals[RealRVLocIdx]; 2582 2583 // Copied from other backends. 2584 switch (VA.getLocInfo()) { 2585 case CCValAssign::Full: 2586 break; 2587 case CCValAssign::BCvt: 2588 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2589 break; 2590 case CCValAssign::SExt: 2591 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2592 break; 2593 case CCValAssign::ZExt: 2594 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2595 break; 2596 case CCValAssign::AExt: 2597 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2598 break; 2599 default: 2600 llvm_unreachable("Unknown loc info!"); 2601 } 2602 2603 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2604 Flag = Chain.getValue(1); 2605 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2606 } 2607 2608 // FIXME: Does sret work properly? 2609 if (!Info->isEntryFunction()) { 2610 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2611 const MCPhysReg *I = 2612 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2613 if (I) { 2614 for (; *I; ++I) { 2615 if (AMDGPU::SReg_64RegClass.contains(*I)) 2616 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2617 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2618 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2619 else 2620 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2621 } 2622 } 2623 } 2624 2625 // Update chain and glue. 2626 RetOps[0] = Chain; 2627 if (Flag.getNode()) 2628 RetOps.push_back(Flag); 2629 2630 unsigned Opc = AMDGPUISD::ENDPGM; 2631 if (!IsWaveEnd) 2632 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2633 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2634 } 2635 2636 SDValue SITargetLowering::LowerCallResult( 2637 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2638 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2639 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2640 SDValue ThisVal) const { 2641 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2642 2643 // Assign locations to each value returned by this call. 2644 SmallVector<CCValAssign, 16> RVLocs; 2645 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2646 *DAG.getContext()); 2647 CCInfo.AnalyzeCallResult(Ins, RetCC); 2648 2649 // Copy all of the result registers out of their specified physreg. 2650 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2651 CCValAssign VA = RVLocs[i]; 2652 SDValue Val; 2653 2654 if (VA.isRegLoc()) { 2655 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2656 Chain = Val.getValue(1); 2657 InFlag = Val.getValue(2); 2658 } else if (VA.isMemLoc()) { 2659 report_fatal_error("TODO: return values in memory"); 2660 } else 2661 llvm_unreachable("unknown argument location type"); 2662 2663 switch (VA.getLocInfo()) { 2664 case CCValAssign::Full: 2665 break; 2666 case CCValAssign::BCvt: 2667 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2668 break; 2669 case CCValAssign::ZExt: 2670 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2671 DAG.getValueType(VA.getValVT())); 2672 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2673 break; 2674 case CCValAssign::SExt: 2675 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2676 DAG.getValueType(VA.getValVT())); 2677 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2678 break; 2679 case CCValAssign::AExt: 2680 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2681 break; 2682 default: 2683 llvm_unreachable("Unknown loc info!"); 2684 } 2685 2686 InVals.push_back(Val); 2687 } 2688 2689 return Chain; 2690 } 2691 2692 // Add code to pass special inputs required depending on used features separate 2693 // from the explicit user arguments present in the IR. 2694 void SITargetLowering::passSpecialInputs( 2695 CallLoweringInfo &CLI, 2696 CCState &CCInfo, 2697 const SIMachineFunctionInfo &Info, 2698 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2699 SmallVectorImpl<SDValue> &MemOpChains, 2700 SDValue Chain) const { 2701 // If we don't have a call site, this was a call inserted by 2702 // legalization. These can never use special inputs. 2703 if (!CLI.CB) 2704 return; 2705 2706 SelectionDAG &DAG = CLI.DAG; 2707 const SDLoc &DL = CLI.DL; 2708 const Function &F = DAG.getMachineFunction().getFunction(); 2709 2710 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2711 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2712 2713 const AMDGPUFunctionArgInfo *CalleeArgInfo 2714 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2715 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2716 auto &ArgUsageInfo = 2717 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2718 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2719 } 2720 2721 // TODO: Unify with private memory register handling. This is complicated by 2722 // the fact that at least in kernels, the input argument is not necessarily 2723 // in the same location as the input. 2724 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue, 2725 StringLiteral> ImplicitAttrs[] = { 2726 {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"}, 2727 {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" }, 2728 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"}, 2729 {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"}, 2730 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"}, 2731 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"}, 2732 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"} 2733 }; 2734 2735 for (auto Attr : ImplicitAttrs) { 2736 const ArgDescriptor *OutgoingArg; 2737 const TargetRegisterClass *ArgRC; 2738 LLT ArgTy; 2739 2740 AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first; 2741 2742 // If the callee does not use the attribute value, skip copying the value. 2743 if (CLI.CB->hasFnAttr(Attr.second)) 2744 continue; 2745 2746 std::tie(OutgoingArg, ArgRC, ArgTy) = 2747 CalleeArgInfo->getPreloadedValue(InputID); 2748 if (!OutgoingArg) 2749 continue; 2750 2751 const ArgDescriptor *IncomingArg; 2752 const TargetRegisterClass *IncomingArgRC; 2753 LLT Ty; 2754 std::tie(IncomingArg, IncomingArgRC, Ty) = 2755 CallerArgInfo.getPreloadedValue(InputID); 2756 assert(IncomingArgRC == ArgRC); 2757 2758 // All special arguments are ints for now. 2759 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2760 SDValue InputReg; 2761 2762 if (IncomingArg) { 2763 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2764 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) { 2765 // The implicit arg ptr is special because it doesn't have a corresponding 2766 // input for kernels, and is computed from the kernarg segment pointer. 2767 InputReg = getImplicitArgPtr(DAG, DL); 2768 } else { 2769 // We may have proven the input wasn't needed, although the ABI is 2770 // requiring it. We just need to allocate the register appropriately. 2771 InputReg = DAG.getUNDEF(ArgVT); 2772 } 2773 2774 if (OutgoingArg->isRegister()) { 2775 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2776 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2777 report_fatal_error("failed to allocate implicit input argument"); 2778 } else { 2779 unsigned SpecialArgOffset = 2780 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2781 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2782 SpecialArgOffset); 2783 MemOpChains.push_back(ArgStore); 2784 } 2785 } 2786 2787 // Pack workitem IDs into a single register or pass it as is if already 2788 // packed. 2789 const ArgDescriptor *OutgoingArg; 2790 const TargetRegisterClass *ArgRC; 2791 LLT Ty; 2792 2793 std::tie(OutgoingArg, ArgRC, Ty) = 2794 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2795 if (!OutgoingArg) 2796 std::tie(OutgoingArg, ArgRC, Ty) = 2797 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2798 if (!OutgoingArg) 2799 std::tie(OutgoingArg, ArgRC, Ty) = 2800 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2801 if (!OutgoingArg) 2802 return; 2803 2804 const ArgDescriptor *IncomingArgX = std::get<0>( 2805 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2806 const ArgDescriptor *IncomingArgY = std::get<0>( 2807 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2808 const ArgDescriptor *IncomingArgZ = std::get<0>( 2809 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2810 2811 SDValue InputReg; 2812 SDLoc SL; 2813 2814 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x"); 2815 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y"); 2816 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z"); 2817 2818 // If incoming ids are not packed we need to pack them. 2819 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX && 2820 NeedWorkItemIDX) { 2821 if (Subtarget->getMaxWorkitemID(F, 0) != 0) { 2822 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2823 } else { 2824 InputReg = DAG.getConstant(0, DL, MVT::i32); 2825 } 2826 } 2827 2828 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY && 2829 NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) { 2830 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2831 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2832 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2833 InputReg = InputReg.getNode() ? 2834 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2835 } 2836 2837 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ && 2838 NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) { 2839 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2840 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2841 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2842 InputReg = InputReg.getNode() ? 2843 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2844 } 2845 2846 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) { 2847 if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) { 2848 // We're in a situation where the outgoing function requires the workitem 2849 // ID, but the calling function does not have it (e.g a graphics function 2850 // calling a C calling convention function). This is illegal, but we need 2851 // to produce something. 2852 InputReg = DAG.getUNDEF(MVT::i32); 2853 } else { 2854 // Workitem ids are already packed, any of present incoming arguments 2855 // will carry all required fields. 2856 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2857 IncomingArgX ? *IncomingArgX : 2858 IncomingArgY ? *IncomingArgY : 2859 *IncomingArgZ, ~0u); 2860 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2861 } 2862 } 2863 2864 if (OutgoingArg->isRegister()) { 2865 if (InputReg) 2866 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2867 2868 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2869 } else { 2870 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2871 if (InputReg) { 2872 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2873 SpecialArgOffset); 2874 MemOpChains.push_back(ArgStore); 2875 } 2876 } 2877 } 2878 2879 static bool canGuaranteeTCO(CallingConv::ID CC) { 2880 return CC == CallingConv::Fast; 2881 } 2882 2883 /// Return true if we might ever do TCO for calls with this calling convention. 2884 static bool mayTailCallThisCC(CallingConv::ID CC) { 2885 switch (CC) { 2886 case CallingConv::C: 2887 case CallingConv::AMDGPU_Gfx: 2888 return true; 2889 default: 2890 return canGuaranteeTCO(CC); 2891 } 2892 } 2893 2894 bool SITargetLowering::isEligibleForTailCallOptimization( 2895 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2896 const SmallVectorImpl<ISD::OutputArg> &Outs, 2897 const SmallVectorImpl<SDValue> &OutVals, 2898 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2899 if (!mayTailCallThisCC(CalleeCC)) 2900 return false; 2901 2902 // For a divergent call target, we need to do a waterfall loop over the 2903 // possible callees which precludes us from using a simple jump. 2904 if (Callee->isDivergent()) 2905 return false; 2906 2907 MachineFunction &MF = DAG.getMachineFunction(); 2908 const Function &CallerF = MF.getFunction(); 2909 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2910 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2911 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2912 2913 // Kernels aren't callable, and don't have a live in return address so it 2914 // doesn't make sense to do a tail call with entry functions. 2915 if (!CallerPreserved) 2916 return false; 2917 2918 bool CCMatch = CallerCC == CalleeCC; 2919 2920 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2921 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2922 return true; 2923 return false; 2924 } 2925 2926 // TODO: Can we handle var args? 2927 if (IsVarArg) 2928 return false; 2929 2930 for (const Argument &Arg : CallerF.args()) { 2931 if (Arg.hasByValAttr()) 2932 return false; 2933 } 2934 2935 LLVMContext &Ctx = *DAG.getContext(); 2936 2937 // Check that the call results are passed in the same way. 2938 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2939 CCAssignFnForCall(CalleeCC, IsVarArg), 2940 CCAssignFnForCall(CallerCC, IsVarArg))) 2941 return false; 2942 2943 // The callee has to preserve all registers the caller needs to preserve. 2944 if (!CCMatch) { 2945 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2946 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2947 return false; 2948 } 2949 2950 // Nothing more to check if the callee is taking no arguments. 2951 if (Outs.empty()) 2952 return true; 2953 2954 SmallVector<CCValAssign, 16> ArgLocs; 2955 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2956 2957 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2958 2959 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2960 // If the stack arguments for this call do not fit into our own save area then 2961 // the call cannot be made tail. 2962 // TODO: Is this really necessary? 2963 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2964 return false; 2965 2966 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2967 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2968 } 2969 2970 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2971 if (!CI->isTailCall()) 2972 return false; 2973 2974 const Function *ParentFn = CI->getParent()->getParent(); 2975 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2976 return false; 2977 return true; 2978 } 2979 2980 // The wave scratch offset register is used as the global base pointer. 2981 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2982 SmallVectorImpl<SDValue> &InVals) const { 2983 SelectionDAG &DAG = CLI.DAG; 2984 const SDLoc &DL = CLI.DL; 2985 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2986 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2987 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2988 SDValue Chain = CLI.Chain; 2989 SDValue Callee = CLI.Callee; 2990 bool &IsTailCall = CLI.IsTailCall; 2991 CallingConv::ID CallConv = CLI.CallConv; 2992 bool IsVarArg = CLI.IsVarArg; 2993 bool IsSibCall = false; 2994 bool IsThisReturn = false; 2995 MachineFunction &MF = DAG.getMachineFunction(); 2996 2997 if (Callee.isUndef() || isNullConstant(Callee)) { 2998 if (!CLI.IsTailCall) { 2999 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 3000 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 3001 } 3002 3003 return Chain; 3004 } 3005 3006 if (IsVarArg) { 3007 return lowerUnhandledCall(CLI, InVals, 3008 "unsupported call to variadic function "); 3009 } 3010 3011 if (!CLI.CB) 3012 report_fatal_error("unsupported libcall legalization"); 3013 3014 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 3015 return lowerUnhandledCall(CLI, InVals, 3016 "unsupported required tail call to function "); 3017 } 3018 3019 if (AMDGPU::isShader(CallConv)) { 3020 // Note the issue is with the CC of the called function, not of the call 3021 // itself. 3022 return lowerUnhandledCall(CLI, InVals, 3023 "unsupported call to a shader function "); 3024 } 3025 3026 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 3027 CallConv != CallingConv::AMDGPU_Gfx) { 3028 // Only allow calls with specific calling conventions. 3029 return lowerUnhandledCall(CLI, InVals, 3030 "unsupported calling convention for call from " 3031 "graphics shader of function "); 3032 } 3033 3034 if (IsTailCall) { 3035 IsTailCall = isEligibleForTailCallOptimization( 3036 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3037 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 3038 report_fatal_error("failed to perform tail call elimination on a call " 3039 "site marked musttail"); 3040 } 3041 3042 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3043 3044 // A sibling call is one where we're under the usual C ABI and not planning 3045 // to change that but can still do a tail call: 3046 if (!TailCallOpt && IsTailCall) 3047 IsSibCall = true; 3048 3049 if (IsTailCall) 3050 ++NumTailCalls; 3051 } 3052 3053 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3054 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3055 SmallVector<SDValue, 8> MemOpChains; 3056 3057 // Analyze operands of the call, assigning locations to each operand. 3058 SmallVector<CCValAssign, 16> ArgLocs; 3059 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3060 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3061 3062 if (CallConv != CallingConv::AMDGPU_Gfx) { 3063 // With a fixed ABI, allocate fixed registers before user arguments. 3064 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3065 } 3066 3067 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3068 3069 // Get a count of how many bytes are to be pushed on the stack. 3070 unsigned NumBytes = CCInfo.getNextStackOffset(); 3071 3072 if (IsSibCall) { 3073 // Since we're not changing the ABI to make this a tail call, the memory 3074 // operands are already available in the caller's incoming argument space. 3075 NumBytes = 0; 3076 } 3077 3078 // FPDiff is the byte offset of the call's argument area from the callee's. 3079 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3080 // by this amount for a tail call. In a sibling call it must be 0 because the 3081 // caller will deallocate the entire stack and the callee still expects its 3082 // arguments to begin at SP+0. Completely unused for non-tail calls. 3083 int32_t FPDiff = 0; 3084 MachineFrameInfo &MFI = MF.getFrameInfo(); 3085 3086 // Adjust the stack pointer for the new arguments... 3087 // These operations are automatically eliminated by the prolog/epilog pass 3088 if (!IsSibCall) { 3089 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3090 3091 if (!Subtarget->enableFlatScratch()) { 3092 SmallVector<SDValue, 4> CopyFromChains; 3093 3094 // In the HSA case, this should be an identity copy. 3095 SDValue ScratchRSrcReg 3096 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3097 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3098 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3099 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3100 } 3101 } 3102 3103 MVT PtrVT = MVT::i32; 3104 3105 // Walk the register/memloc assignments, inserting copies/loads. 3106 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3107 CCValAssign &VA = ArgLocs[i]; 3108 SDValue Arg = OutVals[i]; 3109 3110 // Promote the value if needed. 3111 switch (VA.getLocInfo()) { 3112 case CCValAssign::Full: 3113 break; 3114 case CCValAssign::BCvt: 3115 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3116 break; 3117 case CCValAssign::ZExt: 3118 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3119 break; 3120 case CCValAssign::SExt: 3121 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3122 break; 3123 case CCValAssign::AExt: 3124 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3125 break; 3126 case CCValAssign::FPExt: 3127 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3128 break; 3129 default: 3130 llvm_unreachable("Unknown loc info!"); 3131 } 3132 3133 if (VA.isRegLoc()) { 3134 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3135 } else { 3136 assert(VA.isMemLoc()); 3137 3138 SDValue DstAddr; 3139 MachinePointerInfo DstInfo; 3140 3141 unsigned LocMemOffset = VA.getLocMemOffset(); 3142 int32_t Offset = LocMemOffset; 3143 3144 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3145 MaybeAlign Alignment; 3146 3147 if (IsTailCall) { 3148 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3149 unsigned OpSize = Flags.isByVal() ? 3150 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3151 3152 // FIXME: We can have better than the minimum byval required alignment. 3153 Alignment = 3154 Flags.isByVal() 3155 ? Flags.getNonZeroByValAlign() 3156 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3157 3158 Offset = Offset + FPDiff; 3159 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3160 3161 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3162 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3163 3164 // Make sure any stack arguments overlapping with where we're storing 3165 // are loaded before this eventual operation. Otherwise they'll be 3166 // clobbered. 3167 3168 // FIXME: Why is this really necessary? This seems to just result in a 3169 // lot of code to copy the stack and write them back to the same 3170 // locations, which are supposed to be immutable? 3171 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3172 } else { 3173 // Stores to the argument stack area are relative to the stack pointer. 3174 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(), 3175 MVT::i32); 3176 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff); 3177 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3178 Alignment = 3179 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3180 } 3181 3182 if (Outs[i].Flags.isByVal()) { 3183 SDValue SizeNode = 3184 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3185 SDValue Cpy = 3186 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3187 Outs[i].Flags.getNonZeroByValAlign(), 3188 /*isVol = */ false, /*AlwaysInline = */ true, 3189 /*isTailCall = */ false, DstInfo, 3190 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3191 3192 MemOpChains.push_back(Cpy); 3193 } else { 3194 SDValue Store = 3195 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3196 MemOpChains.push_back(Store); 3197 } 3198 } 3199 } 3200 3201 if (!MemOpChains.empty()) 3202 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3203 3204 // Build a sequence of copy-to-reg nodes chained together with token chain 3205 // and flag operands which copy the outgoing args into the appropriate regs. 3206 SDValue InFlag; 3207 for (auto &RegToPass : RegsToPass) { 3208 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3209 RegToPass.second, InFlag); 3210 InFlag = Chain.getValue(1); 3211 } 3212 3213 3214 // We don't usually want to end the call-sequence here because we would tidy 3215 // the frame up *after* the call, however in the ABI-changing tail-call case 3216 // we've carefully laid out the parameters so that when sp is reset they'll be 3217 // in the correct location. 3218 if (IsTailCall && !IsSibCall) { 3219 Chain = DAG.getCALLSEQ_END(Chain, 3220 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3221 DAG.getTargetConstant(0, DL, MVT::i32), 3222 InFlag, DL); 3223 InFlag = Chain.getValue(1); 3224 } 3225 3226 std::vector<SDValue> Ops; 3227 Ops.push_back(Chain); 3228 Ops.push_back(Callee); 3229 // Add a redundant copy of the callee global which will not be legalized, as 3230 // we need direct access to the callee later. 3231 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3232 const GlobalValue *GV = GSD->getGlobal(); 3233 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3234 } else { 3235 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3236 } 3237 3238 if (IsTailCall) { 3239 // Each tail call may have to adjust the stack by a different amount, so 3240 // this information must travel along with the operation for eventual 3241 // consumption by emitEpilogue. 3242 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3243 } 3244 3245 // Add argument registers to the end of the list so that they are known live 3246 // into the call. 3247 for (auto &RegToPass : RegsToPass) { 3248 Ops.push_back(DAG.getRegister(RegToPass.first, 3249 RegToPass.second.getValueType())); 3250 } 3251 3252 // Add a register mask operand representing the call-preserved registers. 3253 3254 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3255 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3256 assert(Mask && "Missing call preserved mask for calling convention"); 3257 Ops.push_back(DAG.getRegisterMask(Mask)); 3258 3259 if (InFlag.getNode()) 3260 Ops.push_back(InFlag); 3261 3262 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3263 3264 // If we're doing a tall call, use a TC_RETURN here rather than an 3265 // actual call instruction. 3266 if (IsTailCall) { 3267 MFI.setHasTailCall(); 3268 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3269 } 3270 3271 // Returns a chain and a flag for retval copy to use. 3272 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3273 Chain = Call.getValue(0); 3274 InFlag = Call.getValue(1); 3275 3276 uint64_t CalleePopBytes = NumBytes; 3277 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3278 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3279 InFlag, DL); 3280 if (!Ins.empty()) 3281 InFlag = Chain.getValue(1); 3282 3283 // Handle result values, copying them out of physregs into vregs that we 3284 // return. 3285 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3286 InVals, IsThisReturn, 3287 IsThisReturn ? OutVals[0] : SDValue()); 3288 } 3289 3290 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3291 // except for applying the wave size scale to the increment amount. 3292 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3293 SDValue Op, SelectionDAG &DAG) const { 3294 const MachineFunction &MF = DAG.getMachineFunction(); 3295 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3296 3297 SDLoc dl(Op); 3298 EVT VT = Op.getValueType(); 3299 SDValue Tmp1 = Op; 3300 SDValue Tmp2 = Op.getValue(1); 3301 SDValue Tmp3 = Op.getOperand(2); 3302 SDValue Chain = Tmp1.getOperand(0); 3303 3304 Register SPReg = Info->getStackPtrOffsetReg(); 3305 3306 // Chain the dynamic stack allocation so that it doesn't modify the stack 3307 // pointer when other instructions are using the stack. 3308 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3309 3310 SDValue Size = Tmp2.getOperand(1); 3311 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3312 Chain = SP.getValue(1); 3313 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3314 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3315 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3316 unsigned Opc = 3317 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3318 ISD::ADD : ISD::SUB; 3319 3320 SDValue ScaledSize = DAG.getNode( 3321 ISD::SHL, dl, VT, Size, 3322 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3323 3324 Align StackAlign = TFL->getStackAlign(); 3325 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3326 if (Alignment && *Alignment > StackAlign) { 3327 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3328 DAG.getConstant(-(uint64_t)Alignment->value() 3329 << ST.getWavefrontSizeLog2(), 3330 dl, VT)); 3331 } 3332 3333 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3334 Tmp2 = DAG.getCALLSEQ_END( 3335 Chain, DAG.getIntPtrConstant(0, dl, true), 3336 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3337 3338 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3339 } 3340 3341 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3342 SelectionDAG &DAG) const { 3343 // We only handle constant sizes here to allow non-entry block, static sized 3344 // allocas. A truly dynamic value is more difficult to support because we 3345 // don't know if the size value is uniform or not. If the size isn't uniform, 3346 // we would need to do a wave reduction to get the maximum size to know how 3347 // much to increment the uniform stack pointer. 3348 SDValue Size = Op.getOperand(1); 3349 if (isa<ConstantSDNode>(Size)) 3350 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3351 3352 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3353 } 3354 3355 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3356 const MachineFunction &MF) const { 3357 Register Reg = StringSwitch<Register>(RegName) 3358 .Case("m0", AMDGPU::M0) 3359 .Case("exec", AMDGPU::EXEC) 3360 .Case("exec_lo", AMDGPU::EXEC_LO) 3361 .Case("exec_hi", AMDGPU::EXEC_HI) 3362 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3363 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3364 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3365 .Default(Register()); 3366 3367 if (Reg == AMDGPU::NoRegister) { 3368 report_fatal_error(Twine("invalid register name \"" 3369 + StringRef(RegName) + "\".")); 3370 3371 } 3372 3373 if (!Subtarget->hasFlatScrRegister() && 3374 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3375 report_fatal_error(Twine("invalid register \"" 3376 + StringRef(RegName) + "\" for subtarget.")); 3377 } 3378 3379 switch (Reg) { 3380 case AMDGPU::M0: 3381 case AMDGPU::EXEC_LO: 3382 case AMDGPU::EXEC_HI: 3383 case AMDGPU::FLAT_SCR_LO: 3384 case AMDGPU::FLAT_SCR_HI: 3385 if (VT.getSizeInBits() == 32) 3386 return Reg; 3387 break; 3388 case AMDGPU::EXEC: 3389 case AMDGPU::FLAT_SCR: 3390 if (VT.getSizeInBits() == 64) 3391 return Reg; 3392 break; 3393 default: 3394 llvm_unreachable("missing register type checking"); 3395 } 3396 3397 report_fatal_error(Twine("invalid type for register \"" 3398 + StringRef(RegName) + "\".")); 3399 } 3400 3401 // If kill is not the last instruction, split the block so kill is always a 3402 // proper terminator. 3403 MachineBasicBlock * 3404 SITargetLowering::splitKillBlock(MachineInstr &MI, 3405 MachineBasicBlock *BB) const { 3406 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3407 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3408 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3409 return SplitBB; 3410 } 3411 3412 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3413 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3414 // be the first instruction in the remainder block. 3415 // 3416 /// \returns { LoopBody, Remainder } 3417 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3418 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3419 MachineFunction *MF = MBB.getParent(); 3420 MachineBasicBlock::iterator I(&MI); 3421 3422 // To insert the loop we need to split the block. Move everything after this 3423 // point to a new block, and insert a new empty block between the two. 3424 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3425 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3426 MachineFunction::iterator MBBI(MBB); 3427 ++MBBI; 3428 3429 MF->insert(MBBI, LoopBB); 3430 MF->insert(MBBI, RemainderBB); 3431 3432 LoopBB->addSuccessor(LoopBB); 3433 LoopBB->addSuccessor(RemainderBB); 3434 3435 // Move the rest of the block into a new block. 3436 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3437 3438 if (InstInLoop) { 3439 auto Next = std::next(I); 3440 3441 // Move instruction to loop body. 3442 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3443 3444 // Move the rest of the block. 3445 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3446 } else { 3447 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3448 } 3449 3450 MBB.addSuccessor(LoopBB); 3451 3452 return std::make_pair(LoopBB, RemainderBB); 3453 } 3454 3455 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3456 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3457 MachineBasicBlock *MBB = MI.getParent(); 3458 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3459 auto I = MI.getIterator(); 3460 auto E = std::next(I); 3461 3462 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3463 .addImm(0); 3464 3465 MIBundleBuilder Bundler(*MBB, I, E); 3466 finalizeBundle(*MBB, Bundler.begin()); 3467 } 3468 3469 MachineBasicBlock * 3470 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3471 MachineBasicBlock *BB) const { 3472 const DebugLoc &DL = MI.getDebugLoc(); 3473 3474 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3475 3476 MachineBasicBlock *LoopBB; 3477 MachineBasicBlock *RemainderBB; 3478 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3479 3480 // Apparently kill flags are only valid if the def is in the same block? 3481 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3482 Src->setIsKill(false); 3483 3484 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3485 3486 MachineBasicBlock::iterator I = LoopBB->end(); 3487 3488 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3489 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3490 3491 // Clear TRAP_STS.MEM_VIOL 3492 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3493 .addImm(0) 3494 .addImm(EncodedReg); 3495 3496 bundleInstWithWaitcnt(MI); 3497 3498 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3499 3500 // Load and check TRAP_STS.MEM_VIOL 3501 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3502 .addImm(EncodedReg); 3503 3504 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3505 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3506 .addReg(Reg, RegState::Kill) 3507 .addImm(0); 3508 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3509 .addMBB(LoopBB); 3510 3511 return RemainderBB; 3512 } 3513 3514 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3515 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3516 // will only do one iteration. In the worst case, this will loop 64 times. 3517 // 3518 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3519 static MachineBasicBlock::iterator 3520 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3521 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3522 const DebugLoc &DL, const MachineOperand &Idx, 3523 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3524 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3525 Register &SGPRIdxReg) { 3526 3527 MachineFunction *MF = OrigBB.getParent(); 3528 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3529 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3530 MachineBasicBlock::iterator I = LoopBB.begin(); 3531 3532 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3533 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3534 Register NewExec = MRI.createVirtualRegister(BoolRC); 3535 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3536 Register CondReg = MRI.createVirtualRegister(BoolRC); 3537 3538 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3539 .addReg(InitReg) 3540 .addMBB(&OrigBB) 3541 .addReg(ResultReg) 3542 .addMBB(&LoopBB); 3543 3544 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3545 .addReg(InitSaveExecReg) 3546 .addMBB(&OrigBB) 3547 .addReg(NewExec) 3548 .addMBB(&LoopBB); 3549 3550 // Read the next variant <- also loop target. 3551 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3552 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3553 3554 // Compare the just read M0 value to all possible Idx values. 3555 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3556 .addReg(CurrentIdxReg) 3557 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3558 3559 // Update EXEC, save the original EXEC value to VCC. 3560 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3561 : AMDGPU::S_AND_SAVEEXEC_B64), 3562 NewExec) 3563 .addReg(CondReg, RegState::Kill); 3564 3565 MRI.setSimpleHint(NewExec, CondReg); 3566 3567 if (UseGPRIdxMode) { 3568 if (Offset == 0) { 3569 SGPRIdxReg = CurrentIdxReg; 3570 } else { 3571 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3572 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3573 .addReg(CurrentIdxReg, RegState::Kill) 3574 .addImm(Offset); 3575 } 3576 } else { 3577 // Move index from VCC into M0 3578 if (Offset == 0) { 3579 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3580 .addReg(CurrentIdxReg, RegState::Kill); 3581 } else { 3582 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3583 .addReg(CurrentIdxReg, RegState::Kill) 3584 .addImm(Offset); 3585 } 3586 } 3587 3588 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3589 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3590 MachineInstr *InsertPt = 3591 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3592 : AMDGPU::S_XOR_B64_term), Exec) 3593 .addReg(Exec) 3594 .addReg(NewExec); 3595 3596 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3597 // s_cbranch_scc0? 3598 3599 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3600 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3601 .addMBB(&LoopBB); 3602 3603 return InsertPt->getIterator(); 3604 } 3605 3606 // This has slightly sub-optimal regalloc when the source vector is killed by 3607 // the read. The register allocator does not understand that the kill is 3608 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3609 // subregister from it, using 1 more VGPR than necessary. This was saved when 3610 // this was expanded after register allocation. 3611 static MachineBasicBlock::iterator 3612 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3613 unsigned InitResultReg, unsigned PhiReg, int Offset, 3614 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3615 MachineFunction *MF = MBB.getParent(); 3616 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3617 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3618 MachineRegisterInfo &MRI = MF->getRegInfo(); 3619 const DebugLoc &DL = MI.getDebugLoc(); 3620 MachineBasicBlock::iterator I(&MI); 3621 3622 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3623 Register DstReg = MI.getOperand(0).getReg(); 3624 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3625 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3626 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3627 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3628 3629 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3630 3631 // Save the EXEC mask 3632 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3633 .addReg(Exec); 3634 3635 MachineBasicBlock *LoopBB; 3636 MachineBasicBlock *RemainderBB; 3637 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3638 3639 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3640 3641 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3642 InitResultReg, DstReg, PhiReg, TmpExec, 3643 Offset, UseGPRIdxMode, SGPRIdxReg); 3644 3645 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3646 MachineFunction::iterator MBBI(LoopBB); 3647 ++MBBI; 3648 MF->insert(MBBI, LandingPad); 3649 LoopBB->removeSuccessor(RemainderBB); 3650 LandingPad->addSuccessor(RemainderBB); 3651 LoopBB->addSuccessor(LandingPad); 3652 MachineBasicBlock::iterator First = LandingPad->begin(); 3653 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3654 .addReg(SaveExec); 3655 3656 return InsPt; 3657 } 3658 3659 // Returns subreg index, offset 3660 static std::pair<unsigned, int> 3661 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3662 const TargetRegisterClass *SuperRC, 3663 unsigned VecReg, 3664 int Offset) { 3665 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3666 3667 // Skip out of bounds offsets, or else we would end up using an undefined 3668 // register. 3669 if (Offset >= NumElts || Offset < 0) 3670 return std::make_pair(AMDGPU::sub0, Offset); 3671 3672 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3673 } 3674 3675 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3676 MachineRegisterInfo &MRI, MachineInstr &MI, 3677 int Offset) { 3678 MachineBasicBlock *MBB = MI.getParent(); 3679 const DebugLoc &DL = MI.getDebugLoc(); 3680 MachineBasicBlock::iterator I(&MI); 3681 3682 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3683 3684 assert(Idx->getReg() != AMDGPU::NoRegister); 3685 3686 if (Offset == 0) { 3687 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3688 } else { 3689 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3690 .add(*Idx) 3691 .addImm(Offset); 3692 } 3693 } 3694 3695 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3696 MachineRegisterInfo &MRI, MachineInstr &MI, 3697 int Offset) { 3698 MachineBasicBlock *MBB = MI.getParent(); 3699 const DebugLoc &DL = MI.getDebugLoc(); 3700 MachineBasicBlock::iterator I(&MI); 3701 3702 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3703 3704 if (Offset == 0) 3705 return Idx->getReg(); 3706 3707 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3708 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3709 .add(*Idx) 3710 .addImm(Offset); 3711 return Tmp; 3712 } 3713 3714 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3715 MachineBasicBlock &MBB, 3716 const GCNSubtarget &ST) { 3717 const SIInstrInfo *TII = ST.getInstrInfo(); 3718 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3719 MachineFunction *MF = MBB.getParent(); 3720 MachineRegisterInfo &MRI = MF->getRegInfo(); 3721 3722 Register Dst = MI.getOperand(0).getReg(); 3723 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3724 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3725 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3726 3727 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3728 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3729 3730 unsigned SubReg; 3731 std::tie(SubReg, Offset) 3732 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3733 3734 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3735 3736 // Check for a SGPR index. 3737 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3738 MachineBasicBlock::iterator I(&MI); 3739 const DebugLoc &DL = MI.getDebugLoc(); 3740 3741 if (UseGPRIdxMode) { 3742 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3743 // to avoid interfering with other uses, so probably requires a new 3744 // optimization pass. 3745 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3746 3747 const MCInstrDesc &GPRIDXDesc = 3748 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3749 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3750 .addReg(SrcReg) 3751 .addReg(Idx) 3752 .addImm(SubReg); 3753 } else { 3754 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3755 3756 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3757 .addReg(SrcReg, 0, SubReg) 3758 .addReg(SrcReg, RegState::Implicit); 3759 } 3760 3761 MI.eraseFromParent(); 3762 3763 return &MBB; 3764 } 3765 3766 // Control flow needs to be inserted if indexing with a VGPR. 3767 const DebugLoc &DL = MI.getDebugLoc(); 3768 MachineBasicBlock::iterator I(&MI); 3769 3770 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3771 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3772 3773 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3774 3775 Register SGPRIdxReg; 3776 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3777 UseGPRIdxMode, SGPRIdxReg); 3778 3779 MachineBasicBlock *LoopBB = InsPt->getParent(); 3780 3781 if (UseGPRIdxMode) { 3782 const MCInstrDesc &GPRIDXDesc = 3783 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3784 3785 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3786 .addReg(SrcReg) 3787 .addReg(SGPRIdxReg) 3788 .addImm(SubReg); 3789 } else { 3790 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3791 .addReg(SrcReg, 0, SubReg) 3792 .addReg(SrcReg, RegState::Implicit); 3793 } 3794 3795 MI.eraseFromParent(); 3796 3797 return LoopBB; 3798 } 3799 3800 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3801 MachineBasicBlock &MBB, 3802 const GCNSubtarget &ST) { 3803 const SIInstrInfo *TII = ST.getInstrInfo(); 3804 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3805 MachineFunction *MF = MBB.getParent(); 3806 MachineRegisterInfo &MRI = MF->getRegInfo(); 3807 3808 Register Dst = MI.getOperand(0).getReg(); 3809 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3810 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3811 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3812 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3813 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3814 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3815 3816 // This can be an immediate, but will be folded later. 3817 assert(Val->getReg()); 3818 3819 unsigned SubReg; 3820 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3821 SrcVec->getReg(), 3822 Offset); 3823 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3824 3825 if (Idx->getReg() == AMDGPU::NoRegister) { 3826 MachineBasicBlock::iterator I(&MI); 3827 const DebugLoc &DL = MI.getDebugLoc(); 3828 3829 assert(Offset == 0); 3830 3831 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3832 .add(*SrcVec) 3833 .add(*Val) 3834 .addImm(SubReg); 3835 3836 MI.eraseFromParent(); 3837 return &MBB; 3838 } 3839 3840 // Check for a SGPR index. 3841 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3842 MachineBasicBlock::iterator I(&MI); 3843 const DebugLoc &DL = MI.getDebugLoc(); 3844 3845 if (UseGPRIdxMode) { 3846 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3847 3848 const MCInstrDesc &GPRIDXDesc = 3849 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3850 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3851 .addReg(SrcVec->getReg()) 3852 .add(*Val) 3853 .addReg(Idx) 3854 .addImm(SubReg); 3855 } else { 3856 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3857 3858 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3859 TRI.getRegSizeInBits(*VecRC), 32, false); 3860 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3861 .addReg(SrcVec->getReg()) 3862 .add(*Val) 3863 .addImm(SubReg); 3864 } 3865 MI.eraseFromParent(); 3866 return &MBB; 3867 } 3868 3869 // Control flow needs to be inserted if indexing with a VGPR. 3870 if (Val->isReg()) 3871 MRI.clearKillFlags(Val->getReg()); 3872 3873 const DebugLoc &DL = MI.getDebugLoc(); 3874 3875 Register PhiReg = MRI.createVirtualRegister(VecRC); 3876 3877 Register SGPRIdxReg; 3878 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3879 UseGPRIdxMode, SGPRIdxReg); 3880 MachineBasicBlock *LoopBB = InsPt->getParent(); 3881 3882 if (UseGPRIdxMode) { 3883 const MCInstrDesc &GPRIDXDesc = 3884 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3885 3886 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3887 .addReg(PhiReg) 3888 .add(*Val) 3889 .addReg(SGPRIdxReg) 3890 .addImm(AMDGPU::sub0); 3891 } else { 3892 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3893 TRI.getRegSizeInBits(*VecRC), 32, false); 3894 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3895 .addReg(PhiReg) 3896 .add(*Val) 3897 .addImm(AMDGPU::sub0); 3898 } 3899 3900 MI.eraseFromParent(); 3901 return LoopBB; 3902 } 3903 3904 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3905 MachineInstr &MI, MachineBasicBlock *BB) const { 3906 3907 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3908 MachineFunction *MF = BB->getParent(); 3909 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3910 3911 switch (MI.getOpcode()) { 3912 case AMDGPU::S_UADDO_PSEUDO: 3913 case AMDGPU::S_USUBO_PSEUDO: { 3914 const DebugLoc &DL = MI.getDebugLoc(); 3915 MachineOperand &Dest0 = MI.getOperand(0); 3916 MachineOperand &Dest1 = MI.getOperand(1); 3917 MachineOperand &Src0 = MI.getOperand(2); 3918 MachineOperand &Src1 = MI.getOperand(3); 3919 3920 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3921 ? AMDGPU::S_ADD_I32 3922 : AMDGPU::S_SUB_I32; 3923 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3924 3925 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3926 .addImm(1) 3927 .addImm(0); 3928 3929 MI.eraseFromParent(); 3930 return BB; 3931 } 3932 case AMDGPU::S_ADD_U64_PSEUDO: 3933 case AMDGPU::S_SUB_U64_PSEUDO: { 3934 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3935 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3936 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3937 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3938 const DebugLoc &DL = MI.getDebugLoc(); 3939 3940 MachineOperand &Dest = MI.getOperand(0); 3941 MachineOperand &Src0 = MI.getOperand(1); 3942 MachineOperand &Src1 = MI.getOperand(2); 3943 3944 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3945 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3946 3947 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3948 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3949 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3950 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3951 3952 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3953 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3954 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3955 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3956 3957 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3958 3959 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3960 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3961 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3962 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3963 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3964 .addReg(DestSub0) 3965 .addImm(AMDGPU::sub0) 3966 .addReg(DestSub1) 3967 .addImm(AMDGPU::sub1); 3968 MI.eraseFromParent(); 3969 return BB; 3970 } 3971 case AMDGPU::V_ADD_U64_PSEUDO: 3972 case AMDGPU::V_SUB_U64_PSEUDO: { 3973 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3974 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3975 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3976 const DebugLoc &DL = MI.getDebugLoc(); 3977 3978 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3979 3980 MachineOperand &Dest = MI.getOperand(0); 3981 MachineOperand &Src0 = MI.getOperand(1); 3982 MachineOperand &Src1 = MI.getOperand(2); 3983 3984 if (IsAdd && ST.hasLshlAddB64()) { 3985 auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64), 3986 Dest.getReg()) 3987 .add(Src0) 3988 .addImm(0) 3989 .add(Src1); 3990 TII->legalizeOperands(*Add); 3991 MI.eraseFromParent(); 3992 return BB; 3993 } 3994 3995 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3996 3997 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3998 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3999 4000 Register CarryReg = MRI.createVirtualRegister(CarryRC); 4001 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 4002 4003 const TargetRegisterClass *Src0RC = Src0.isReg() 4004 ? MRI.getRegClass(Src0.getReg()) 4005 : &AMDGPU::VReg_64RegClass; 4006 const TargetRegisterClass *Src1RC = Src1.isReg() 4007 ? MRI.getRegClass(Src1.getReg()) 4008 : &AMDGPU::VReg_64RegClass; 4009 4010 const TargetRegisterClass *Src0SubRC = 4011 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 4012 const TargetRegisterClass *Src1SubRC = 4013 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 4014 4015 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 4016 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 4017 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 4018 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 4019 4020 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 4021 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 4022 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 4023 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 4024 4025 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 4026 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 4027 .addReg(CarryReg, RegState::Define) 4028 .add(SrcReg0Sub0) 4029 .add(SrcReg1Sub0) 4030 .addImm(0); // clamp bit 4031 4032 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 4033 MachineInstr *HiHalf = 4034 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 4035 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 4036 .add(SrcReg0Sub1) 4037 .add(SrcReg1Sub1) 4038 .addReg(CarryReg, RegState::Kill) 4039 .addImm(0); // clamp bit 4040 4041 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4042 .addReg(DestSub0) 4043 .addImm(AMDGPU::sub0) 4044 .addReg(DestSub1) 4045 .addImm(AMDGPU::sub1); 4046 TII->legalizeOperands(*LoHalf); 4047 TII->legalizeOperands(*HiHalf); 4048 MI.eraseFromParent(); 4049 return BB; 4050 } 4051 case AMDGPU::S_ADD_CO_PSEUDO: 4052 case AMDGPU::S_SUB_CO_PSEUDO: { 4053 // This pseudo has a chance to be selected 4054 // only from uniform add/subcarry node. All the VGPR operands 4055 // therefore assumed to be splat vectors. 4056 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4057 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4058 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4059 MachineBasicBlock::iterator MII = MI; 4060 const DebugLoc &DL = MI.getDebugLoc(); 4061 MachineOperand &Dest = MI.getOperand(0); 4062 MachineOperand &CarryDest = MI.getOperand(1); 4063 MachineOperand &Src0 = MI.getOperand(2); 4064 MachineOperand &Src1 = MI.getOperand(3); 4065 MachineOperand &Src2 = MI.getOperand(4); 4066 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4067 ? AMDGPU::S_ADDC_U32 4068 : AMDGPU::S_SUBB_U32; 4069 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4070 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4071 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4072 .addReg(Src0.getReg()); 4073 Src0.setReg(RegOp0); 4074 } 4075 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4076 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4077 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4078 .addReg(Src1.getReg()); 4079 Src1.setReg(RegOp1); 4080 } 4081 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4082 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4083 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4084 .addReg(Src2.getReg()); 4085 Src2.setReg(RegOp2); 4086 } 4087 4088 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4089 unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC); 4090 assert(WaveSize == 64 || WaveSize == 32); 4091 4092 if (WaveSize == 64) { 4093 if (ST.hasScalarCompareEq64()) { 4094 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4095 .addReg(Src2.getReg()) 4096 .addImm(0); 4097 } else { 4098 const TargetRegisterClass *SubRC = 4099 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4100 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4101 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4102 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4103 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4104 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4105 4106 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4107 .add(Src2Sub0) 4108 .add(Src2Sub1); 4109 4110 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4111 .addReg(Src2_32, RegState::Kill) 4112 .addImm(0); 4113 } 4114 } else { 4115 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4116 .addReg(Src2.getReg()) 4117 .addImm(0); 4118 } 4119 4120 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4121 4122 unsigned SelOpc = 4123 (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32; 4124 4125 BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg()) 4126 .addImm(-1) 4127 .addImm(0); 4128 4129 MI.eraseFromParent(); 4130 return BB; 4131 } 4132 case AMDGPU::SI_INIT_M0: { 4133 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4134 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4135 .add(MI.getOperand(0)); 4136 MI.eraseFromParent(); 4137 return BB; 4138 } 4139 case AMDGPU::GET_GROUPSTATICSIZE: { 4140 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4141 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4142 DebugLoc DL = MI.getDebugLoc(); 4143 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4144 .add(MI.getOperand(0)) 4145 .addImm(MFI->getLDSSize()); 4146 MI.eraseFromParent(); 4147 return BB; 4148 } 4149 case AMDGPU::SI_INDIRECT_SRC_V1: 4150 case AMDGPU::SI_INDIRECT_SRC_V2: 4151 case AMDGPU::SI_INDIRECT_SRC_V4: 4152 case AMDGPU::SI_INDIRECT_SRC_V8: 4153 case AMDGPU::SI_INDIRECT_SRC_V16: 4154 case AMDGPU::SI_INDIRECT_SRC_V32: 4155 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4156 case AMDGPU::SI_INDIRECT_DST_V1: 4157 case AMDGPU::SI_INDIRECT_DST_V2: 4158 case AMDGPU::SI_INDIRECT_DST_V4: 4159 case AMDGPU::SI_INDIRECT_DST_V8: 4160 case AMDGPU::SI_INDIRECT_DST_V16: 4161 case AMDGPU::SI_INDIRECT_DST_V32: 4162 return emitIndirectDst(MI, *BB, *getSubtarget()); 4163 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4164 case AMDGPU::SI_KILL_I1_PSEUDO: 4165 return splitKillBlock(MI, BB); 4166 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4167 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4168 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4169 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4170 4171 Register Dst = MI.getOperand(0).getReg(); 4172 Register Src0 = MI.getOperand(1).getReg(); 4173 Register Src1 = MI.getOperand(2).getReg(); 4174 const DebugLoc &DL = MI.getDebugLoc(); 4175 Register SrcCond = MI.getOperand(3).getReg(); 4176 4177 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4178 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4179 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4180 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4181 4182 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4183 .addReg(SrcCond); 4184 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4185 .addImm(0) 4186 .addReg(Src0, 0, AMDGPU::sub0) 4187 .addImm(0) 4188 .addReg(Src1, 0, AMDGPU::sub0) 4189 .addReg(SrcCondCopy); 4190 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4191 .addImm(0) 4192 .addReg(Src0, 0, AMDGPU::sub1) 4193 .addImm(0) 4194 .addReg(Src1, 0, AMDGPU::sub1) 4195 .addReg(SrcCondCopy); 4196 4197 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4198 .addReg(DstLo) 4199 .addImm(AMDGPU::sub0) 4200 .addReg(DstHi) 4201 .addImm(AMDGPU::sub1); 4202 MI.eraseFromParent(); 4203 return BB; 4204 } 4205 case AMDGPU::SI_BR_UNDEF: { 4206 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4207 const DebugLoc &DL = MI.getDebugLoc(); 4208 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4209 .add(MI.getOperand(0)); 4210 Br->getOperand(1).setIsUndef(true); // read undef SCC 4211 MI.eraseFromParent(); 4212 return BB; 4213 } 4214 case AMDGPU::ADJCALLSTACKUP: 4215 case AMDGPU::ADJCALLSTACKDOWN: { 4216 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4217 MachineInstrBuilder MIB(*MF, &MI); 4218 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4219 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4220 return BB; 4221 } 4222 case AMDGPU::SI_CALL_ISEL: { 4223 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4224 const DebugLoc &DL = MI.getDebugLoc(); 4225 4226 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4227 4228 MachineInstrBuilder MIB; 4229 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4230 4231 for (const MachineOperand &MO : MI.operands()) 4232 MIB.add(MO); 4233 4234 MIB.cloneMemRefs(MI); 4235 MI.eraseFromParent(); 4236 return BB; 4237 } 4238 case AMDGPU::V_ADD_CO_U32_e32: 4239 case AMDGPU::V_SUB_CO_U32_e32: 4240 case AMDGPU::V_SUBREV_CO_U32_e32: { 4241 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4242 const DebugLoc &DL = MI.getDebugLoc(); 4243 unsigned Opc = MI.getOpcode(); 4244 4245 bool NeedClampOperand = false; 4246 if (TII->pseudoToMCOpcode(Opc) == -1) { 4247 Opc = AMDGPU::getVOPe64(Opc); 4248 NeedClampOperand = true; 4249 } 4250 4251 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4252 if (TII->isVOP3(*I)) { 4253 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4254 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4255 I.addReg(TRI->getVCC(), RegState::Define); 4256 } 4257 I.add(MI.getOperand(1)) 4258 .add(MI.getOperand(2)); 4259 if (NeedClampOperand) 4260 I.addImm(0); // clamp bit for e64 encoding 4261 4262 TII->legalizeOperands(*I); 4263 4264 MI.eraseFromParent(); 4265 return BB; 4266 } 4267 case AMDGPU::V_ADDC_U32_e32: 4268 case AMDGPU::V_SUBB_U32_e32: 4269 case AMDGPU::V_SUBBREV_U32_e32: 4270 // These instructions have an implicit use of vcc which counts towards the 4271 // constant bus limit. 4272 TII->legalizeOperands(MI); 4273 return BB; 4274 case AMDGPU::DS_GWS_INIT: 4275 case AMDGPU::DS_GWS_SEMA_BR: 4276 case AMDGPU::DS_GWS_BARRIER: 4277 TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::data0); 4278 LLVM_FALLTHROUGH; 4279 case AMDGPU::DS_GWS_SEMA_V: 4280 case AMDGPU::DS_GWS_SEMA_P: 4281 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4282 // A s_waitcnt 0 is required to be the instruction immediately following. 4283 if (getSubtarget()->hasGWSAutoReplay()) { 4284 bundleInstWithWaitcnt(MI); 4285 return BB; 4286 } 4287 4288 return emitGWSMemViolTestLoop(MI, BB); 4289 case AMDGPU::S_SETREG_B32: { 4290 // Try to optimize cases that only set the denormal mode or rounding mode. 4291 // 4292 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4293 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4294 // instead. 4295 // 4296 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4297 // allow you to have a no side effect instruction in the output of a 4298 // sideeffecting pattern. 4299 unsigned ID, Offset, Width; 4300 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4301 if (ID != AMDGPU::Hwreg::ID_MODE) 4302 return BB; 4303 4304 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4305 const unsigned SetMask = WidthMask << Offset; 4306 4307 if (getSubtarget()->hasDenormModeInst()) { 4308 unsigned SetDenormOp = 0; 4309 unsigned SetRoundOp = 0; 4310 4311 // The dedicated instructions can only set the whole denorm or round mode 4312 // at once, not a subset of bits in either. 4313 if (SetMask == 4314 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4315 // If this fully sets both the round and denorm mode, emit the two 4316 // dedicated instructions for these. 4317 SetRoundOp = AMDGPU::S_ROUND_MODE; 4318 SetDenormOp = AMDGPU::S_DENORM_MODE; 4319 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4320 SetRoundOp = AMDGPU::S_ROUND_MODE; 4321 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4322 SetDenormOp = AMDGPU::S_DENORM_MODE; 4323 } 4324 4325 if (SetRoundOp || SetDenormOp) { 4326 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4327 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4328 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4329 unsigned ImmVal = Def->getOperand(1).getImm(); 4330 if (SetRoundOp) { 4331 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4332 .addImm(ImmVal & 0xf); 4333 4334 // If we also have the denorm mode, get just the denorm mode bits. 4335 ImmVal >>= 4; 4336 } 4337 4338 if (SetDenormOp) { 4339 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4340 .addImm(ImmVal & 0xf); 4341 } 4342 4343 MI.eraseFromParent(); 4344 return BB; 4345 } 4346 } 4347 } 4348 4349 // If only FP bits are touched, used the no side effects pseudo. 4350 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4351 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4352 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4353 4354 return BB; 4355 } 4356 default: 4357 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4358 } 4359 } 4360 4361 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4362 return isTypeLegal(VT.getScalarType()); 4363 } 4364 4365 bool SITargetLowering::hasAtomicFaddRtnForTy(SDValue &Op) const { 4366 switch (Op.getValue(0).getSimpleValueType().SimpleTy) { 4367 case MVT::f32: 4368 return Subtarget->hasAtomicFaddRtnInsts(); 4369 case MVT::v2f16: 4370 case MVT::f64: 4371 return Subtarget->hasGFX90AInsts(); 4372 default: 4373 return false; 4374 } 4375 } 4376 4377 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4378 // This currently forces unfolding various combinations of fsub into fma with 4379 // free fneg'd operands. As long as we have fast FMA (controlled by 4380 // isFMAFasterThanFMulAndFAdd), we should perform these. 4381 4382 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4383 // most of these combines appear to be cycle neutral but save on instruction 4384 // count / code size. 4385 return true; 4386 } 4387 4388 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; } 4389 4390 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4391 EVT VT) const { 4392 if (!VT.isVector()) { 4393 return MVT::i1; 4394 } 4395 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4396 } 4397 4398 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4399 // TODO: Should i16 be used always if legal? For now it would force VALU 4400 // shifts. 4401 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4402 } 4403 4404 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4405 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4406 ? Ty.changeElementSize(16) 4407 : Ty.changeElementSize(32); 4408 } 4409 4410 // Answering this is somewhat tricky and depends on the specific device which 4411 // have different rates for fma or all f64 operations. 4412 // 4413 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4414 // regardless of which device (although the number of cycles differs between 4415 // devices), so it is always profitable for f64. 4416 // 4417 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4418 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4419 // which we can always do even without fused FP ops since it returns the same 4420 // result as the separate operations and since it is always full 4421 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4422 // however does not support denormals, so we do report fma as faster if we have 4423 // a fast fma device and require denormals. 4424 // 4425 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4426 EVT VT) const { 4427 VT = VT.getScalarType(); 4428 4429 switch (VT.getSimpleVT().SimpleTy) { 4430 case MVT::f32: { 4431 // If mad is not available this depends only on if f32 fma is full rate. 4432 if (!Subtarget->hasMadMacF32Insts()) 4433 return Subtarget->hasFastFMAF32(); 4434 4435 // Otherwise f32 mad is always full rate and returns the same result as 4436 // the separate operations so should be preferred over fma. 4437 // However does not support denormals. 4438 if (hasFP32Denormals(MF)) 4439 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4440 4441 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4442 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4443 } 4444 case MVT::f64: 4445 return true; 4446 case MVT::f16: 4447 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4448 default: 4449 break; 4450 } 4451 4452 return false; 4453 } 4454 4455 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4456 LLT Ty) const { 4457 switch (Ty.getScalarSizeInBits()) { 4458 case 16: 4459 return isFMAFasterThanFMulAndFAdd(MF, MVT::f16); 4460 case 32: 4461 return isFMAFasterThanFMulAndFAdd(MF, MVT::f32); 4462 case 64: 4463 return isFMAFasterThanFMulAndFAdd(MF, MVT::f64); 4464 default: 4465 break; 4466 } 4467 4468 return false; 4469 } 4470 4471 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const { 4472 if (!Ty.isScalar()) 4473 return false; 4474 4475 if (Ty.getScalarSizeInBits() == 16) 4476 return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF()); 4477 if (Ty.getScalarSizeInBits() == 32) 4478 return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF()); 4479 4480 return false; 4481 } 4482 4483 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4484 const SDNode *N) const { 4485 // TODO: Check future ftz flag 4486 // v_mad_f32/v_mac_f32 do not support denormals. 4487 EVT VT = N->getValueType(0); 4488 if (VT == MVT::f32) 4489 return Subtarget->hasMadMacF32Insts() && 4490 !hasFP32Denormals(DAG.getMachineFunction()); 4491 if (VT == MVT::f16) { 4492 return Subtarget->hasMadF16() && 4493 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4494 } 4495 4496 return false; 4497 } 4498 4499 //===----------------------------------------------------------------------===// 4500 // Custom DAG Lowering Operations 4501 //===----------------------------------------------------------------------===// 4502 4503 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4504 // wider vector type is legal. 4505 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4506 SelectionDAG &DAG) const { 4507 unsigned Opc = Op.getOpcode(); 4508 EVT VT = Op.getValueType(); 4509 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4510 4511 SDValue Lo, Hi; 4512 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4513 4514 SDLoc SL(Op); 4515 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4516 Op->getFlags()); 4517 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4518 Op->getFlags()); 4519 4520 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4521 } 4522 4523 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4524 // wider vector type is legal. 4525 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4526 SelectionDAG &DAG) const { 4527 unsigned Opc = Op.getOpcode(); 4528 EVT VT = Op.getValueType(); 4529 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4530 VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 || 4531 VT == MVT::v16f32 || VT == MVT::v32f32); 4532 4533 SDValue Lo0, Hi0; 4534 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4535 SDValue Lo1, Hi1; 4536 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4537 4538 SDLoc SL(Op); 4539 4540 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4541 Op->getFlags()); 4542 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4543 Op->getFlags()); 4544 4545 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4546 } 4547 4548 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4549 SelectionDAG &DAG) const { 4550 unsigned Opc = Op.getOpcode(); 4551 EVT VT = Op.getValueType(); 4552 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 || 4553 VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 || 4554 VT == MVT::v16f32 || VT == MVT::v32f32); 4555 4556 SDValue Lo0, Hi0; 4557 SDValue Op0 = Op.getOperand(0); 4558 std::tie(Lo0, Hi0) = Op0.getValueType().isVector() 4559 ? DAG.SplitVectorOperand(Op.getNode(), 0) 4560 : std::make_pair(Op0, Op0); 4561 SDValue Lo1, Hi1; 4562 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4563 SDValue Lo2, Hi2; 4564 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4565 4566 SDLoc SL(Op); 4567 auto ResVT = DAG.GetSplitDestVTs(VT); 4568 4569 SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2, 4570 Op->getFlags()); 4571 SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2, 4572 Op->getFlags()); 4573 4574 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4575 } 4576 4577 4578 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4579 switch (Op.getOpcode()) { 4580 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4581 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4582 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4583 case ISD::LOAD: { 4584 SDValue Result = LowerLOAD(Op, DAG); 4585 assert((!Result.getNode() || 4586 Result.getNode()->getNumValues() == 2) && 4587 "Load should return a value and a chain"); 4588 return Result; 4589 } 4590 4591 case ISD::FSIN: 4592 case ISD::FCOS: 4593 return LowerTrig(Op, DAG); 4594 case ISD::SELECT: return LowerSELECT(Op, DAG); 4595 case ISD::FDIV: return LowerFDIV(Op, DAG); 4596 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4597 case ISD::STORE: return LowerSTORE(Op, DAG); 4598 case ISD::GlobalAddress: { 4599 MachineFunction &MF = DAG.getMachineFunction(); 4600 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4601 return LowerGlobalAddress(MFI, Op, DAG); 4602 } 4603 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4604 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4605 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4606 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4607 case ISD::INSERT_SUBVECTOR: 4608 return lowerINSERT_SUBVECTOR(Op, DAG); 4609 case ISD::INSERT_VECTOR_ELT: 4610 return lowerINSERT_VECTOR_ELT(Op, DAG); 4611 case ISD::EXTRACT_VECTOR_ELT: 4612 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4613 case ISD::VECTOR_SHUFFLE: 4614 return lowerVECTOR_SHUFFLE(Op, DAG); 4615 case ISD::SCALAR_TO_VECTOR: 4616 return lowerSCALAR_TO_VECTOR(Op, DAG); 4617 case ISD::BUILD_VECTOR: 4618 return lowerBUILD_VECTOR(Op, DAG); 4619 case ISD::FP_ROUND: 4620 return lowerFP_ROUND(Op, DAG); 4621 case ISD::FPTRUNC_ROUND: { 4622 unsigned Opc; 4623 SDLoc DL(Op); 4624 4625 if (Op.getOperand(0)->getValueType(0) != MVT::f32) 4626 return SDValue(); 4627 4628 // Get the rounding mode from the last operand 4629 int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4630 if (RoundMode == (int)RoundingMode::TowardPositive) 4631 Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD; 4632 else if (RoundMode == (int)RoundingMode::TowardNegative) 4633 Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD; 4634 else 4635 return SDValue(); 4636 4637 return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0)); 4638 } 4639 case ISD::TRAP: 4640 return lowerTRAP(Op, DAG); 4641 case ISD::DEBUGTRAP: 4642 return lowerDEBUGTRAP(Op, DAG); 4643 case ISD::FABS: 4644 case ISD::FNEG: 4645 case ISD::FCANONICALIZE: 4646 case ISD::BSWAP: 4647 return splitUnaryVectorOp(Op, DAG); 4648 case ISD::FMINNUM: 4649 case ISD::FMAXNUM: 4650 return lowerFMINNUM_FMAXNUM(Op, DAG); 4651 case ISD::FMA: 4652 return splitTernaryVectorOp(Op, DAG); 4653 case ISD::FP_TO_SINT: 4654 case ISD::FP_TO_UINT: 4655 return LowerFP_TO_INT(Op, DAG); 4656 case ISD::SHL: 4657 case ISD::SRA: 4658 case ISD::SRL: 4659 case ISD::ADD: 4660 case ISD::SUB: 4661 case ISD::MUL: 4662 case ISD::SMIN: 4663 case ISD::SMAX: 4664 case ISD::UMIN: 4665 case ISD::UMAX: 4666 case ISD::FADD: 4667 case ISD::FMUL: 4668 case ISD::FMINNUM_IEEE: 4669 case ISD::FMAXNUM_IEEE: 4670 case ISD::UADDSAT: 4671 case ISD::USUBSAT: 4672 case ISD::SADDSAT: 4673 case ISD::SSUBSAT: 4674 return splitBinaryVectorOp(Op, DAG); 4675 case ISD::SMULO: 4676 case ISD::UMULO: 4677 return lowerXMULO(Op, DAG); 4678 case ISD::SMUL_LOHI: 4679 case ISD::UMUL_LOHI: 4680 return lowerXMUL_LOHI(Op, DAG); 4681 case ISD::DYNAMIC_STACKALLOC: 4682 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4683 } 4684 return SDValue(); 4685 } 4686 4687 // Used for D16: Casts the result of an instruction into the right vector, 4688 // packs values if loads return unpacked values. 4689 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4690 const SDLoc &DL, 4691 SelectionDAG &DAG, bool Unpacked) { 4692 if (!LoadVT.isVector()) 4693 return Result; 4694 4695 // Cast back to the original packed type or to a larger type that is a 4696 // multiple of 32 bit for D16. Widening the return type is a required for 4697 // legalization. 4698 EVT FittingLoadVT = LoadVT; 4699 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4700 FittingLoadVT = 4701 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4702 LoadVT.getVectorNumElements() + 1); 4703 } 4704 4705 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4706 // Truncate to v2i16/v4i16. 4707 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4708 4709 // Workaround legalizer not scalarizing truncate after vector op 4710 // legalization but not creating intermediate vector trunc. 4711 SmallVector<SDValue, 4> Elts; 4712 DAG.ExtractVectorElements(Result, Elts); 4713 for (SDValue &Elt : Elts) 4714 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4715 4716 // Pad illegal v1i16/v3fi6 to v4i16 4717 if ((LoadVT.getVectorNumElements() % 2) == 1) 4718 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4719 4720 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4721 4722 // Bitcast to original type (v2f16/v4f16). 4723 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4724 } 4725 4726 // Cast back to the original packed type. 4727 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4728 } 4729 4730 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4731 MemSDNode *M, 4732 SelectionDAG &DAG, 4733 ArrayRef<SDValue> Ops, 4734 bool IsIntrinsic) const { 4735 SDLoc DL(M); 4736 4737 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4738 EVT LoadVT = M->getValueType(0); 4739 4740 EVT EquivLoadVT = LoadVT; 4741 if (LoadVT.isVector()) { 4742 if (Unpacked) { 4743 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4744 LoadVT.getVectorNumElements()); 4745 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4746 // Widen v3f16 to legal type 4747 EquivLoadVT = 4748 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4749 LoadVT.getVectorNumElements() + 1); 4750 } 4751 } 4752 4753 // Change from v4f16/v2f16 to EquivLoadVT. 4754 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4755 4756 SDValue Load 4757 = DAG.getMemIntrinsicNode( 4758 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4759 VTList, Ops, M->getMemoryVT(), 4760 M->getMemOperand()); 4761 4762 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4763 4764 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4765 } 4766 4767 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4768 SelectionDAG &DAG, 4769 ArrayRef<SDValue> Ops) const { 4770 SDLoc DL(M); 4771 EVT LoadVT = M->getValueType(0); 4772 EVT EltType = LoadVT.getScalarType(); 4773 EVT IntVT = LoadVT.changeTypeToInteger(); 4774 4775 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4776 4777 unsigned Opc = 4778 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4779 4780 if (IsD16) { 4781 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4782 } 4783 4784 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4785 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4786 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4787 4788 if (isTypeLegal(LoadVT)) { 4789 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4790 M->getMemOperand(), DAG); 4791 } 4792 4793 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4794 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4795 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4796 M->getMemOperand(), DAG); 4797 return DAG.getMergeValues( 4798 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4799 DL); 4800 } 4801 4802 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4803 SDNode *N, SelectionDAG &DAG) { 4804 EVT VT = N->getValueType(0); 4805 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4806 unsigned CondCode = CD->getZExtValue(); 4807 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4808 return DAG.getUNDEF(VT); 4809 4810 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4811 4812 SDValue LHS = N->getOperand(1); 4813 SDValue RHS = N->getOperand(2); 4814 4815 SDLoc DL(N); 4816 4817 EVT CmpVT = LHS.getValueType(); 4818 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4819 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4820 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4821 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4822 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4823 } 4824 4825 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4826 4827 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4828 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4829 4830 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4831 DAG.getCondCode(CCOpcode)); 4832 if (VT.bitsEq(CCVT)) 4833 return SetCC; 4834 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4835 } 4836 4837 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4838 SDNode *N, SelectionDAG &DAG) { 4839 EVT VT = N->getValueType(0); 4840 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4841 4842 unsigned CondCode = CD->getZExtValue(); 4843 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4844 return DAG.getUNDEF(VT); 4845 4846 SDValue Src0 = N->getOperand(1); 4847 SDValue Src1 = N->getOperand(2); 4848 EVT CmpVT = Src0.getValueType(); 4849 SDLoc SL(N); 4850 4851 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4852 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4853 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4854 } 4855 4856 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4857 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4858 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4859 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4860 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4861 Src1, DAG.getCondCode(CCOpcode)); 4862 if (VT.bitsEq(CCVT)) 4863 return SetCC; 4864 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4865 } 4866 4867 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4868 SelectionDAG &DAG) { 4869 EVT VT = N->getValueType(0); 4870 SDValue Src = N->getOperand(1); 4871 SDLoc SL(N); 4872 4873 if (Src.getOpcode() == ISD::SETCC) { 4874 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4875 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4876 Src.getOperand(1), Src.getOperand(2)); 4877 } 4878 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4879 // (ballot 0) -> 0 4880 if (Arg->isZero()) 4881 return DAG.getConstant(0, SL, VT); 4882 4883 // (ballot 1) -> EXEC/EXEC_LO 4884 if (Arg->isOne()) { 4885 Register Exec; 4886 if (VT.getScalarSizeInBits() == 32) 4887 Exec = AMDGPU::EXEC_LO; 4888 else if (VT.getScalarSizeInBits() == 64) 4889 Exec = AMDGPU::EXEC; 4890 else 4891 return SDValue(); 4892 4893 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4894 } 4895 } 4896 4897 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4898 // ISD::SETNE) 4899 return DAG.getNode( 4900 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4901 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4902 } 4903 4904 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4905 SmallVectorImpl<SDValue> &Results, 4906 SelectionDAG &DAG) const { 4907 switch (N->getOpcode()) { 4908 case ISD::INSERT_VECTOR_ELT: { 4909 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4910 Results.push_back(Res); 4911 return; 4912 } 4913 case ISD::EXTRACT_VECTOR_ELT: { 4914 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4915 Results.push_back(Res); 4916 return; 4917 } 4918 case ISD::INTRINSIC_WO_CHAIN: { 4919 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4920 switch (IID) { 4921 case Intrinsic::amdgcn_cvt_pkrtz: { 4922 SDValue Src0 = N->getOperand(1); 4923 SDValue Src1 = N->getOperand(2); 4924 SDLoc SL(N); 4925 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4926 Src0, Src1); 4927 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4928 return; 4929 } 4930 case Intrinsic::amdgcn_cvt_pknorm_i16: 4931 case Intrinsic::amdgcn_cvt_pknorm_u16: 4932 case Intrinsic::amdgcn_cvt_pk_i16: 4933 case Intrinsic::amdgcn_cvt_pk_u16: { 4934 SDValue Src0 = N->getOperand(1); 4935 SDValue Src1 = N->getOperand(2); 4936 SDLoc SL(N); 4937 unsigned Opcode; 4938 4939 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4940 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4941 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4942 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4943 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4944 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4945 else 4946 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4947 4948 EVT VT = N->getValueType(0); 4949 if (isTypeLegal(VT)) 4950 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4951 else { 4952 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4953 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4954 } 4955 return; 4956 } 4957 } 4958 break; 4959 } 4960 case ISD::INTRINSIC_W_CHAIN: { 4961 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4962 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4963 // FIXME: Hacky 4964 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4965 Results.push_back(Res.getOperand(I)); 4966 } 4967 } else { 4968 Results.push_back(Res); 4969 Results.push_back(Res.getValue(1)); 4970 } 4971 return; 4972 } 4973 4974 break; 4975 } 4976 case ISD::SELECT: { 4977 SDLoc SL(N); 4978 EVT VT = N->getValueType(0); 4979 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4980 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4981 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4982 4983 EVT SelectVT = NewVT; 4984 if (NewVT.bitsLT(MVT::i32)) { 4985 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4986 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4987 SelectVT = MVT::i32; 4988 } 4989 4990 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4991 N->getOperand(0), LHS, RHS); 4992 4993 if (NewVT != SelectVT) 4994 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4995 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4996 return; 4997 } 4998 case ISD::FNEG: { 4999 if (N->getValueType(0) != MVT::v2f16) 5000 break; 5001 5002 SDLoc SL(N); 5003 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5004 5005 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 5006 BC, 5007 DAG.getConstant(0x80008000, SL, MVT::i32)); 5008 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5009 return; 5010 } 5011 case ISD::FABS: { 5012 if (N->getValueType(0) != MVT::v2f16) 5013 break; 5014 5015 SDLoc SL(N); 5016 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5017 5018 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 5019 BC, 5020 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 5021 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5022 return; 5023 } 5024 default: 5025 break; 5026 } 5027 } 5028 5029 /// Helper function for LowerBRCOND 5030 static SDNode *findUser(SDValue Value, unsigned Opcode) { 5031 5032 SDNode *Parent = Value.getNode(); 5033 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 5034 I != E; ++I) { 5035 5036 if (I.getUse().get() != Value) 5037 continue; 5038 5039 if (I->getOpcode() == Opcode) 5040 return *I; 5041 } 5042 return nullptr; 5043 } 5044 5045 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 5046 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 5047 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 5048 case Intrinsic::amdgcn_if: 5049 return AMDGPUISD::IF; 5050 case Intrinsic::amdgcn_else: 5051 return AMDGPUISD::ELSE; 5052 case Intrinsic::amdgcn_loop: 5053 return AMDGPUISD::LOOP; 5054 case Intrinsic::amdgcn_end_cf: 5055 llvm_unreachable("should not occur"); 5056 default: 5057 return 0; 5058 } 5059 } 5060 5061 // break, if_break, else_break are all only used as inputs to loop, not 5062 // directly as branch conditions. 5063 return 0; 5064 } 5065 5066 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 5067 const Triple &TT = getTargetMachine().getTargetTriple(); 5068 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5069 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5070 AMDGPU::shouldEmitConstantsToTextSection(TT); 5071 } 5072 5073 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 5074 // FIXME: Either avoid relying on address space here or change the default 5075 // address space for functions to avoid the explicit check. 5076 return (GV->getValueType()->isFunctionTy() || 5077 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 5078 !shouldEmitFixup(GV) && 5079 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 5080 } 5081 5082 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 5083 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 5084 } 5085 5086 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 5087 if (!GV->hasExternalLinkage()) 5088 return true; 5089 5090 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5091 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5092 } 5093 5094 /// This transforms the control flow intrinsics to get the branch destination as 5095 /// last parameter, also switches branch target with BR if the need arise 5096 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5097 SelectionDAG &DAG) const { 5098 SDLoc DL(BRCOND); 5099 5100 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5101 SDValue Target = BRCOND.getOperand(2); 5102 SDNode *BR = nullptr; 5103 SDNode *SetCC = nullptr; 5104 5105 if (Intr->getOpcode() == ISD::SETCC) { 5106 // As long as we negate the condition everything is fine 5107 SetCC = Intr; 5108 Intr = SetCC->getOperand(0).getNode(); 5109 5110 } else { 5111 // Get the target from BR if we don't negate the condition 5112 BR = findUser(BRCOND, ISD::BR); 5113 assert(BR && "brcond missing unconditional branch user"); 5114 Target = BR->getOperand(1); 5115 } 5116 5117 unsigned CFNode = isCFIntrinsic(Intr); 5118 if (CFNode == 0) { 5119 // This is a uniform branch so we don't need to legalize. 5120 return BRCOND; 5121 } 5122 5123 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5124 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5125 5126 assert(!SetCC || 5127 (SetCC->getConstantOperandVal(1) == 1 && 5128 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5129 ISD::SETNE)); 5130 5131 // operands of the new intrinsic call 5132 SmallVector<SDValue, 4> Ops; 5133 if (HaveChain) 5134 Ops.push_back(BRCOND.getOperand(0)); 5135 5136 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5137 Ops.push_back(Target); 5138 5139 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5140 5141 // build the new intrinsic call 5142 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5143 5144 if (!HaveChain) { 5145 SDValue Ops[] = { 5146 SDValue(Result, 0), 5147 BRCOND.getOperand(0) 5148 }; 5149 5150 Result = DAG.getMergeValues(Ops, DL).getNode(); 5151 } 5152 5153 if (BR) { 5154 // Give the branch instruction our target 5155 SDValue Ops[] = { 5156 BR->getOperand(0), 5157 BRCOND.getOperand(2) 5158 }; 5159 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5160 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5161 } 5162 5163 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5164 5165 // Copy the intrinsic results to registers 5166 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5167 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5168 if (!CopyToReg) 5169 continue; 5170 5171 Chain = DAG.getCopyToReg( 5172 Chain, DL, 5173 CopyToReg->getOperand(1), 5174 SDValue(Result, i - 1), 5175 SDValue()); 5176 5177 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5178 } 5179 5180 // Remove the old intrinsic from the chain 5181 DAG.ReplaceAllUsesOfValueWith( 5182 SDValue(Intr, Intr->getNumValues() - 1), 5183 Intr->getOperand(0)); 5184 5185 return Chain; 5186 } 5187 5188 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5189 SelectionDAG &DAG) const { 5190 MVT VT = Op.getSimpleValueType(); 5191 SDLoc DL(Op); 5192 // Checking the depth 5193 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5194 return DAG.getConstant(0, DL, VT); 5195 5196 MachineFunction &MF = DAG.getMachineFunction(); 5197 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5198 // Check for kernel and shader functions 5199 if (Info->isEntryFunction()) 5200 return DAG.getConstant(0, DL, VT); 5201 5202 MachineFrameInfo &MFI = MF.getFrameInfo(); 5203 // There is a call to @llvm.returnaddress in this function 5204 MFI.setReturnAddressIsTaken(true); 5205 5206 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5207 // Get the return address reg and mark it as an implicit live-in 5208 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5209 5210 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5211 } 5212 5213 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5214 SDValue Op, 5215 const SDLoc &DL, 5216 EVT VT) const { 5217 return Op.getValueType().bitsLE(VT) ? 5218 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5219 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5220 DAG.getTargetConstant(0, DL, MVT::i32)); 5221 } 5222 5223 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5224 assert(Op.getValueType() == MVT::f16 && 5225 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5226 5227 SDValue Src = Op.getOperand(0); 5228 EVT SrcVT = Src.getValueType(); 5229 if (SrcVT != MVT::f64) 5230 return Op; 5231 5232 SDLoc DL(Op); 5233 5234 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5235 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5236 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5237 } 5238 5239 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5240 SelectionDAG &DAG) const { 5241 EVT VT = Op.getValueType(); 5242 const MachineFunction &MF = DAG.getMachineFunction(); 5243 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5244 bool IsIEEEMode = Info->getMode().IEEE; 5245 5246 // FIXME: Assert during selection that this is only selected for 5247 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5248 // mode functions, but this happens to be OK since it's only done in cases 5249 // where there is known no sNaN. 5250 if (IsIEEEMode) 5251 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5252 5253 if (VT == MVT::v4f16 || VT == MVT::v8f16) 5254 return splitBinaryVectorOp(Op, DAG); 5255 return Op; 5256 } 5257 5258 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5259 EVT VT = Op.getValueType(); 5260 SDLoc SL(Op); 5261 SDValue LHS = Op.getOperand(0); 5262 SDValue RHS = Op.getOperand(1); 5263 bool isSigned = Op.getOpcode() == ISD::SMULO; 5264 5265 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5266 const APInt &C = RHSC->getAPIntValue(); 5267 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5268 if (C.isPowerOf2()) { 5269 // smulo(x, signed_min) is same as umulo(x, signed_min). 5270 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5271 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5272 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5273 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5274 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5275 SL, VT, Result, ShiftAmt), 5276 LHS, ISD::SETNE); 5277 return DAG.getMergeValues({ Result, Overflow }, SL); 5278 } 5279 } 5280 5281 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5282 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5283 SL, VT, LHS, RHS); 5284 5285 SDValue Sign = isSigned 5286 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5287 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5288 : DAG.getConstant(0, SL, VT); 5289 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5290 5291 return DAG.getMergeValues({ Result, Overflow }, SL); 5292 } 5293 5294 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const { 5295 if (Op->isDivergent()) { 5296 // Select to V_MAD_[IU]64_[IU]32. 5297 return Op; 5298 } 5299 if (Subtarget->hasSMulHi()) { 5300 // Expand to S_MUL_I32 + S_MUL_HI_[IU]32. 5301 return SDValue(); 5302 } 5303 // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to 5304 // calculate the high part, so we might as well do the whole thing with 5305 // V_MAD_[IU]64_[IU]32. 5306 return Op; 5307 } 5308 5309 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5310 if (!Subtarget->isTrapHandlerEnabled() || 5311 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5312 return lowerTrapEndpgm(Op, DAG); 5313 5314 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5315 switch (*HsaAbiVer) { 5316 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5317 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5318 return lowerTrapHsaQueuePtr(Op, DAG); 5319 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5320 case ELF::ELFABIVERSION_AMDGPU_HSA_V5: 5321 return Subtarget->supportsGetDoorbellID() ? 5322 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5323 } 5324 } 5325 5326 llvm_unreachable("Unknown trap handler"); 5327 } 5328 5329 SDValue SITargetLowering::lowerTrapEndpgm( 5330 SDValue Op, SelectionDAG &DAG) const { 5331 SDLoc SL(Op); 5332 SDValue Chain = Op.getOperand(0); 5333 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5334 } 5335 5336 SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT, 5337 const SDLoc &DL, Align Alignment, ImplicitParameter Param) const { 5338 MachineFunction &MF = DAG.getMachineFunction(); 5339 uint64_t Offset = getImplicitParameterOffset(MF, Param); 5340 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset); 5341 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5342 return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment, 5343 MachineMemOperand::MODereferenceable | 5344 MachineMemOperand::MOInvariant); 5345 } 5346 5347 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5348 SDValue Op, SelectionDAG &DAG) const { 5349 SDLoc SL(Op); 5350 SDValue Chain = Op.getOperand(0); 5351 5352 SDValue QueuePtr; 5353 // For code object version 5, QueuePtr is passed through implicit kernarg. 5354 if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) { 5355 QueuePtr = 5356 loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR); 5357 } else { 5358 MachineFunction &MF = DAG.getMachineFunction(); 5359 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5360 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5361 5362 if (UserSGPR == AMDGPU::NoRegister) { 5363 // We probably are in a function incorrectly marked with 5364 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the 5365 // trap, so just use a null pointer. 5366 QueuePtr = DAG.getConstant(0, SL, MVT::i64); 5367 } else { 5368 QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR, 5369 MVT::i64); 5370 } 5371 } 5372 5373 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5374 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5375 QueuePtr, SDValue()); 5376 5377 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5378 SDValue Ops[] = { 5379 ToReg, 5380 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5381 SGPR01, 5382 ToReg.getValue(1) 5383 }; 5384 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5385 } 5386 5387 SDValue SITargetLowering::lowerTrapHsa( 5388 SDValue Op, SelectionDAG &DAG) const { 5389 SDLoc SL(Op); 5390 SDValue Chain = Op.getOperand(0); 5391 5392 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5393 SDValue Ops[] = { 5394 Chain, 5395 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5396 }; 5397 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5398 } 5399 5400 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5401 SDLoc SL(Op); 5402 SDValue Chain = Op.getOperand(0); 5403 MachineFunction &MF = DAG.getMachineFunction(); 5404 5405 if (!Subtarget->isTrapHandlerEnabled() || 5406 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5407 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5408 "debugtrap handler not supported", 5409 Op.getDebugLoc(), 5410 DS_Warning); 5411 LLVMContext &Ctx = MF.getFunction().getContext(); 5412 Ctx.diagnose(NoTrap); 5413 return Chain; 5414 } 5415 5416 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5417 SDValue Ops[] = { 5418 Chain, 5419 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5420 }; 5421 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5422 } 5423 5424 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5425 SelectionDAG &DAG) const { 5426 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5427 if (Subtarget->hasApertureRegs()) { 5428 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5429 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5430 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5431 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5432 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5433 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5434 unsigned Encoding = 5435 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5436 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5437 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5438 5439 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5440 SDValue ApertureReg = SDValue( 5441 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5442 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5443 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5444 } 5445 5446 // For code object version 5, private_base and shared_base are passed through 5447 // implicit kernargs. 5448 if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) { 5449 ImplicitParameter Param = 5450 (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE; 5451 return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param); 5452 } 5453 5454 MachineFunction &MF = DAG.getMachineFunction(); 5455 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5456 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5457 if (UserSGPR == AMDGPU::NoRegister) { 5458 // We probably are in a function incorrectly marked with 5459 // amdgpu-no-queue-ptr. This is undefined. 5460 return DAG.getUNDEF(MVT::i32); 5461 } 5462 5463 SDValue QueuePtr = CreateLiveInRegister( 5464 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5465 5466 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5467 // private_segment_aperture_base_hi. 5468 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5469 5470 SDValue Ptr = 5471 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5472 5473 // TODO: Use custom target PseudoSourceValue. 5474 // TODO: We should use the value from the IR intrinsic call, but it might not 5475 // be available and how do we get it? 5476 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5477 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5478 commonAlignment(Align(64), StructOffset), 5479 MachineMemOperand::MODereferenceable | 5480 MachineMemOperand::MOInvariant); 5481 } 5482 5483 /// Return true if the value is a known valid address, such that a null check is 5484 /// not necessary. 5485 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG, 5486 const AMDGPUTargetMachine &TM, unsigned AddrSpace) { 5487 if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) || 5488 isa<BasicBlockSDNode>(Val)) 5489 return true; 5490 5491 if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val)) 5492 return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace); 5493 5494 // TODO: Search through arithmetic, handle arguments and loads 5495 // marked nonnull. 5496 return false; 5497 } 5498 5499 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5500 SelectionDAG &DAG) const { 5501 SDLoc SL(Op); 5502 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5503 5504 SDValue Src = ASC->getOperand(0); 5505 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5506 unsigned SrcAS = ASC->getSrcAddressSpace(); 5507 5508 const AMDGPUTargetMachine &TM = 5509 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5510 5511 // flat -> local/private 5512 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) { 5513 unsigned DestAS = ASC->getDestAddressSpace(); 5514 5515 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5516 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5517 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5518 5519 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5520 return Ptr; 5521 5522 unsigned NullVal = TM.getNullPointerValue(DestAS); 5523 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5524 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5525 5526 return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr, 5527 SegmentNullPtr); 5528 } 5529 } 5530 5531 // local/private -> flat 5532 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5533 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5534 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5535 5536 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5537 SDValue CvtPtr = 5538 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5539 CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr); 5540 5541 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5542 return CvtPtr; 5543 5544 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5545 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5546 5547 SDValue NonNull 5548 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5549 5550 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr, 5551 FlatNullPtr); 5552 } 5553 } 5554 5555 if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5556 Op.getValueType() == MVT::i64) { 5557 const SIMachineFunctionInfo *Info = 5558 DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>(); 5559 SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32); 5560 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi); 5561 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 5562 } 5563 5564 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5565 Src.getValueType() == MVT::i64) 5566 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5567 5568 // global <-> flat are no-ops and never emitted. 5569 5570 const MachineFunction &MF = DAG.getMachineFunction(); 5571 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5572 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5573 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5574 5575 return DAG.getUNDEF(ASC->getValueType(0)); 5576 } 5577 5578 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5579 // the small vector and inserting them into the big vector. That is better than 5580 // the default expansion of doing it via a stack slot. Even though the use of 5581 // the stack slot would be optimized away afterwards, the stack slot itself 5582 // remains. 5583 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5584 SelectionDAG &DAG) const { 5585 SDValue Vec = Op.getOperand(0); 5586 SDValue Ins = Op.getOperand(1); 5587 SDValue Idx = Op.getOperand(2); 5588 EVT VecVT = Vec.getValueType(); 5589 EVT InsVT = Ins.getValueType(); 5590 EVT EltVT = VecVT.getVectorElementType(); 5591 unsigned InsNumElts = InsVT.getVectorNumElements(); 5592 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5593 SDLoc SL(Op); 5594 5595 for (unsigned I = 0; I != InsNumElts; ++I) { 5596 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5597 DAG.getConstant(I, SL, MVT::i32)); 5598 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5599 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5600 } 5601 return Vec; 5602 } 5603 5604 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5605 SelectionDAG &DAG) const { 5606 SDValue Vec = Op.getOperand(0); 5607 SDValue InsVal = Op.getOperand(1); 5608 SDValue Idx = Op.getOperand(2); 5609 EVT VecVT = Vec.getValueType(); 5610 EVT EltVT = VecVT.getVectorElementType(); 5611 unsigned VecSize = VecVT.getSizeInBits(); 5612 unsigned EltSize = EltVT.getSizeInBits(); 5613 SDLoc SL(Op); 5614 5615 // Specially handle the case of v4i16 with static indexing. 5616 unsigned NumElts = VecVT.getVectorNumElements(); 5617 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5618 if (NumElts == 4 && EltSize == 16 && KIdx) { 5619 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5620 5621 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5622 DAG.getConstant(0, SL, MVT::i32)); 5623 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5624 DAG.getConstant(1, SL, MVT::i32)); 5625 5626 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5627 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5628 5629 unsigned Idx = KIdx->getZExtValue(); 5630 bool InsertLo = Idx < 2; 5631 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5632 InsertLo ? LoVec : HiVec, 5633 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5634 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5635 5636 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5637 5638 SDValue Concat = InsertLo ? 5639 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5640 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5641 5642 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5643 } 5644 5645 // Static indexing does not lower to stack access, and hence there is no need 5646 // for special custom lowering to avoid stack access. 5647 if (isa<ConstantSDNode>(Idx)) 5648 return SDValue(); 5649 5650 // Avoid stack access for dynamic indexing by custom lowering to 5651 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5652 5653 assert(VecSize <= 64 && "Expected target vector size to be <= 64 bits"); 5654 5655 MVT IntVT = MVT::getIntegerVT(VecSize); 5656 5657 // Convert vector index to bit-index and get the required bit mask. 5658 assert(isPowerOf2_32(EltSize)); 5659 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5660 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5661 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5662 DAG.getConstant(0xffff, SL, IntVT), 5663 ScaledIdx); 5664 5665 // 1. Create a congruent vector with the target value in each element. 5666 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5667 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5668 5669 // 2. Mask off all other indicies except the required index within (1). 5670 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5671 5672 // 3. Mask off the required index within the target vector. 5673 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5674 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5675 DAG.getNOT(SL, BFM, IntVT), BCVec); 5676 5677 // 4. Get (2) and (3) ORed into the target vector. 5678 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5679 5680 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5681 } 5682 5683 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5684 SelectionDAG &DAG) const { 5685 SDLoc SL(Op); 5686 5687 EVT ResultVT = Op.getValueType(); 5688 SDValue Vec = Op.getOperand(0); 5689 SDValue Idx = Op.getOperand(1); 5690 EVT VecVT = Vec.getValueType(); 5691 unsigned VecSize = VecVT.getSizeInBits(); 5692 EVT EltVT = VecVT.getVectorElementType(); 5693 5694 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5695 5696 // Make sure we do any optimizations that will make it easier to fold 5697 // source modifiers before obscuring it with bit operations. 5698 5699 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5700 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5701 return Combined; 5702 5703 if (VecSize == 128) { 5704 SDValue Lo, Hi; 5705 EVT LoVT, HiVT; 5706 SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec); 5707 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5708 Lo = 5709 DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5710 V2, DAG.getConstant(0, SL, MVT::i32))); 5711 Hi = 5712 DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5713 V2, DAG.getConstant(1, SL, MVT::i32))); 5714 EVT IdxVT = Idx.getValueType(); 5715 unsigned NElem = VecVT.getVectorNumElements(); 5716 assert(isPowerOf2_32(NElem)); 5717 SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT); 5718 SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask); 5719 SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT); 5720 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx); 5721 } 5722 5723 assert(VecSize <= 64); 5724 5725 MVT IntVT = MVT::getIntegerVT(VecSize); 5726 5727 // If Vec is just a SCALAR_TO_VECTOR, then use the scalar integer directly. 5728 SDValue VecBC = peekThroughBitcasts(Vec); 5729 if (VecBC.getOpcode() == ISD::SCALAR_TO_VECTOR) { 5730 SDValue Src = VecBC.getOperand(0); 5731 Src = DAG.getBitcast(Src.getValueType().changeTypeToInteger(), Src); 5732 Vec = DAG.getAnyExtOrTrunc(Src, SL, IntVT); 5733 } 5734 5735 unsigned EltSize = EltVT.getSizeInBits(); 5736 assert(isPowerOf2_32(EltSize)); 5737 5738 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5739 5740 // Convert vector index to bit-index (* EltSize) 5741 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5742 5743 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5744 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5745 5746 if (ResultVT == MVT::f16) { 5747 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5748 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5749 } 5750 5751 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5752 } 5753 5754 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5755 assert(Elt % 2 == 0); 5756 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5757 } 5758 5759 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5760 SelectionDAG &DAG) const { 5761 SDLoc SL(Op); 5762 EVT ResultVT = Op.getValueType(); 5763 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5764 5765 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5766 EVT EltVT = PackVT.getVectorElementType(); 5767 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5768 5769 // vector_shuffle <0,1,6,7> lhs, rhs 5770 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5771 // 5772 // vector_shuffle <6,7,2,3> lhs, rhs 5773 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5774 // 5775 // vector_shuffle <6,7,0,1> lhs, rhs 5776 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5777 5778 // Avoid scalarizing when both halves are reading from consecutive elements. 5779 SmallVector<SDValue, 4> Pieces; 5780 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5781 if (elementPairIsContiguous(SVN->getMask(), I)) { 5782 const int Idx = SVN->getMaskElt(I); 5783 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5784 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5785 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5786 PackVT, SVN->getOperand(VecIdx), 5787 DAG.getConstant(EltIdx, SL, MVT::i32)); 5788 Pieces.push_back(SubVec); 5789 } else { 5790 const int Idx0 = SVN->getMaskElt(I); 5791 const int Idx1 = SVN->getMaskElt(I + 1); 5792 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5793 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5794 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5795 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5796 5797 SDValue Vec0 = SVN->getOperand(VecIdx0); 5798 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5799 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5800 5801 SDValue Vec1 = SVN->getOperand(VecIdx1); 5802 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5803 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5804 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5805 } 5806 } 5807 5808 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5809 } 5810 5811 SDValue SITargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op, 5812 SelectionDAG &DAG) const { 5813 SDValue SVal = Op.getOperand(0); 5814 EVT ResultVT = Op.getValueType(); 5815 EVT SValVT = SVal.getValueType(); 5816 SDValue UndefVal = DAG.getUNDEF(SValVT); 5817 SDLoc SL(Op); 5818 5819 SmallVector<SDValue, 8> VElts; 5820 VElts.push_back(SVal); 5821 for (int I = 1, E = ResultVT.getVectorNumElements(); I < E; ++I) 5822 VElts.push_back(UndefVal); 5823 5824 return DAG.getBuildVector(ResultVT, SL, VElts); 5825 } 5826 5827 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5828 SelectionDAG &DAG) const { 5829 SDLoc SL(Op); 5830 EVT VT = Op.getValueType(); 5831 5832 if (VT == MVT::v4i16 || VT == MVT::v4f16 || 5833 VT == MVT::v8i16 || VT == MVT::v8f16) { 5834 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 5835 VT.getVectorNumElements() / 2); 5836 MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits()); 5837 5838 // Turn into pair of packed build_vectors. 5839 // TODO: Special case for constants that can be materialized with s_mov_b64. 5840 SmallVector<SDValue, 4> LoOps, HiOps; 5841 for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) { 5842 LoOps.push_back(Op.getOperand(I)); 5843 HiOps.push_back(Op.getOperand(I + E)); 5844 } 5845 SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps); 5846 SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps); 5847 5848 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo); 5849 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi); 5850 5851 SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL, 5852 { CastLo, CastHi }); 5853 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5854 } 5855 5856 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5857 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5858 5859 SDValue Lo = Op.getOperand(0); 5860 SDValue Hi = Op.getOperand(1); 5861 5862 // Avoid adding defined bits with the zero_extend. 5863 if (Hi.isUndef()) { 5864 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5865 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5866 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5867 } 5868 5869 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5870 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5871 5872 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5873 DAG.getConstant(16, SL, MVT::i32)); 5874 if (Lo.isUndef()) 5875 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5876 5877 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5878 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5879 5880 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5881 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5882 } 5883 5884 bool 5885 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5886 // We can fold offsets for anything that doesn't require a GOT relocation. 5887 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5888 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5889 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5890 !shouldEmitGOTReloc(GA->getGlobal()); 5891 } 5892 5893 static SDValue 5894 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5895 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5896 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5897 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5898 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5899 // lowered to the following code sequence: 5900 // 5901 // For constant address space: 5902 // s_getpc_b64 s[0:1] 5903 // s_add_u32 s0, s0, $symbol 5904 // s_addc_u32 s1, s1, 0 5905 // 5906 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5907 // a fixup or relocation is emitted to replace $symbol with a literal 5908 // constant, which is a pc-relative offset from the encoding of the $symbol 5909 // operand to the global variable. 5910 // 5911 // For global address space: 5912 // s_getpc_b64 s[0:1] 5913 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5914 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5915 // 5916 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5917 // fixups or relocations are emitted to replace $symbol@*@lo and 5918 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5919 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5920 // operand to the global variable. 5921 // 5922 // What we want here is an offset from the value returned by s_getpc 5923 // (which is the address of the s_add_u32 instruction) to the global 5924 // variable, but since the encoding of $symbol starts 4 bytes after the start 5925 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5926 // small. This requires us to add 4 to the global variable offset in order to 5927 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5928 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5929 // instruction. 5930 SDValue PtrLo = 5931 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5932 SDValue PtrHi; 5933 if (GAFlags == SIInstrInfo::MO_NONE) { 5934 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5935 } else { 5936 PtrHi = 5937 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5938 } 5939 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5940 } 5941 5942 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5943 SDValue Op, 5944 SelectionDAG &DAG) const { 5945 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5946 SDLoc DL(GSD); 5947 EVT PtrVT = Op.getValueType(); 5948 5949 const GlobalValue *GV = GSD->getGlobal(); 5950 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5951 shouldUseLDSConstAddress(GV)) || 5952 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5953 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5954 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5955 GV->hasExternalLinkage()) { 5956 Type *Ty = GV->getValueType(); 5957 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5958 // zero-sized type in other languages to declare the dynamic shared 5959 // memory which size is not known at the compile time. They will be 5960 // allocated by the runtime and placed directly after the static 5961 // allocated ones. They all share the same offset. 5962 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5963 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5964 // Adjust alignment for that dynamic shared memory array. 5965 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5966 return SDValue( 5967 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5968 } 5969 } 5970 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5971 } 5972 5973 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5974 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5975 SIInstrInfo::MO_ABS32_LO); 5976 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5977 } 5978 5979 if (shouldEmitFixup(GV)) 5980 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5981 else if (shouldEmitPCReloc(GV)) 5982 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5983 SIInstrInfo::MO_REL32); 5984 5985 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5986 SIInstrInfo::MO_GOTPCREL32); 5987 5988 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5989 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5990 const DataLayout &DataLayout = DAG.getDataLayout(); 5991 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5992 MachinePointerInfo PtrInfo 5993 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5994 5995 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5996 MachineMemOperand::MODereferenceable | 5997 MachineMemOperand::MOInvariant); 5998 } 5999 6000 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 6001 const SDLoc &DL, SDValue V) const { 6002 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 6003 // the destination register. 6004 // 6005 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 6006 // so we will end up with redundant moves to m0. 6007 // 6008 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 6009 6010 // A Null SDValue creates a glue result. 6011 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 6012 V, Chain); 6013 return SDValue(M0, 0); 6014 } 6015 6016 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 6017 SDValue Op, 6018 MVT VT, 6019 unsigned Offset) const { 6020 SDLoc SL(Op); 6021 SDValue Param = lowerKernargMemParameter( 6022 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 6023 // The local size values will have the hi 16-bits as zero. 6024 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 6025 DAG.getValueType(VT)); 6026 } 6027 6028 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6029 EVT VT) { 6030 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6031 "non-hsa intrinsic with hsa target", 6032 DL.getDebugLoc()); 6033 DAG.getContext()->diagnose(BadIntrin); 6034 return DAG.getUNDEF(VT); 6035 } 6036 6037 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6038 EVT VT) { 6039 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6040 "intrinsic not supported on subtarget", 6041 DL.getDebugLoc()); 6042 DAG.getContext()->diagnose(BadIntrin); 6043 return DAG.getUNDEF(VT); 6044 } 6045 6046 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 6047 ArrayRef<SDValue> Elts) { 6048 assert(!Elts.empty()); 6049 MVT Type; 6050 unsigned NumElts = Elts.size(); 6051 6052 if (NumElts <= 8) { 6053 Type = MVT::getVectorVT(MVT::f32, NumElts); 6054 } else { 6055 assert(Elts.size() <= 16); 6056 Type = MVT::v16f32; 6057 NumElts = 16; 6058 } 6059 6060 SmallVector<SDValue, 16> VecElts(NumElts); 6061 for (unsigned i = 0; i < Elts.size(); ++i) { 6062 SDValue Elt = Elts[i]; 6063 if (Elt.getValueType() != MVT::f32) 6064 Elt = DAG.getBitcast(MVT::f32, Elt); 6065 VecElts[i] = Elt; 6066 } 6067 for (unsigned i = Elts.size(); i < NumElts; ++i) 6068 VecElts[i] = DAG.getUNDEF(MVT::f32); 6069 6070 if (NumElts == 1) 6071 return VecElts[0]; 6072 return DAG.getBuildVector(Type, DL, VecElts); 6073 } 6074 6075 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 6076 SDValue Src, int ExtraElts) { 6077 EVT SrcVT = Src.getValueType(); 6078 6079 SmallVector<SDValue, 8> Elts; 6080 6081 if (SrcVT.isVector()) 6082 DAG.ExtractVectorElements(Src, Elts); 6083 else 6084 Elts.push_back(Src); 6085 6086 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 6087 while (ExtraElts--) 6088 Elts.push_back(Undef); 6089 6090 return DAG.getBuildVector(CastVT, DL, Elts); 6091 } 6092 6093 // Re-construct the required return value for a image load intrinsic. 6094 // This is more complicated due to the optional use TexFailCtrl which means the required 6095 // return type is an aggregate 6096 static SDValue constructRetValue(SelectionDAG &DAG, 6097 MachineSDNode *Result, 6098 ArrayRef<EVT> ResultTypes, 6099 bool IsTexFail, bool Unpacked, bool IsD16, 6100 int DMaskPop, int NumVDataDwords, 6101 const SDLoc &DL) { 6102 // Determine the required return type. This is the same regardless of IsTexFail flag 6103 EVT ReqRetVT = ResultTypes[0]; 6104 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 6105 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6106 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 6107 6108 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6109 DMaskPop : (DMaskPop + 1) / 2; 6110 6111 MVT DataDwordVT = NumDataDwords == 1 ? 6112 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 6113 6114 MVT MaskPopVT = MaskPopDwords == 1 ? 6115 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 6116 6117 SDValue Data(Result, 0); 6118 SDValue TexFail; 6119 6120 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 6121 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 6122 if (MaskPopVT.isVector()) { 6123 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 6124 SDValue(Result, 0), ZeroIdx); 6125 } else { 6126 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 6127 SDValue(Result, 0), ZeroIdx); 6128 } 6129 } 6130 6131 if (DataDwordVT.isVector()) 6132 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 6133 NumDataDwords - MaskPopDwords); 6134 6135 if (IsD16) 6136 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 6137 6138 EVT LegalReqRetVT = ReqRetVT; 6139 if (!ReqRetVT.isVector()) { 6140 if (!Data.getValueType().isInteger()) 6141 Data = DAG.getNode(ISD::BITCAST, DL, 6142 Data.getValueType().changeTypeToInteger(), Data); 6143 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 6144 } else { 6145 // We need to widen the return vector to a legal type 6146 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 6147 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 6148 LegalReqRetVT = 6149 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 6150 ReqRetVT.getVectorNumElements() + 1); 6151 } 6152 } 6153 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 6154 6155 if (IsTexFail) { 6156 TexFail = 6157 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 6158 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 6159 6160 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 6161 } 6162 6163 if (Result->getNumValues() == 1) 6164 return Data; 6165 6166 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 6167 } 6168 6169 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 6170 SDValue *LWE, bool &IsTexFail) { 6171 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 6172 6173 uint64_t Value = TexFailCtrlConst->getZExtValue(); 6174 if (Value) { 6175 IsTexFail = true; 6176 } 6177 6178 SDLoc DL(TexFailCtrlConst); 6179 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 6180 Value &= ~(uint64_t)0x1; 6181 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 6182 Value &= ~(uint64_t)0x2; 6183 6184 return Value == 0; 6185 } 6186 6187 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op, 6188 MVT PackVectorVT, 6189 SmallVectorImpl<SDValue> &PackedAddrs, 6190 unsigned DimIdx, unsigned EndIdx, 6191 unsigned NumGradients) { 6192 SDLoc DL(Op); 6193 for (unsigned I = DimIdx; I < EndIdx; I++) { 6194 SDValue Addr = Op.getOperand(I); 6195 6196 // Gradients are packed with undef for each coordinate. 6197 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 6198 // 1D: undef,dx/dh; undef,dx/dv 6199 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 6200 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 6201 if (((I + 1) >= EndIdx) || 6202 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 6203 I == DimIdx + NumGradients - 1))) { 6204 if (Addr.getValueType() != MVT::i16) 6205 Addr = DAG.getBitcast(MVT::i16, Addr); 6206 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 6207 } else { 6208 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 6209 I++; 6210 } 6211 Addr = DAG.getBitcast(MVT::f32, Addr); 6212 PackedAddrs.push_back(Addr); 6213 } 6214 } 6215 6216 SDValue SITargetLowering::lowerImage(SDValue Op, 6217 const AMDGPU::ImageDimIntrinsicInfo *Intr, 6218 SelectionDAG &DAG, bool WithChain) const { 6219 SDLoc DL(Op); 6220 MachineFunction &MF = DAG.getMachineFunction(); 6221 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 6222 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 6223 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 6224 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 6225 unsigned IntrOpcode = Intr->BaseOpcode; 6226 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6227 bool IsGFX11Plus = AMDGPU::isGFX11Plus(*Subtarget); 6228 6229 SmallVector<EVT, 3> ResultTypes(Op->values()); 6230 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 6231 bool IsD16 = false; 6232 bool IsG16 = false; 6233 bool IsA16 = false; 6234 SDValue VData; 6235 int NumVDataDwords; 6236 bool AdjustRetType = false; 6237 6238 // Offset of intrinsic arguments 6239 const unsigned ArgOffset = WithChain ? 2 : 1; 6240 6241 unsigned DMask; 6242 unsigned DMaskLanes = 0; 6243 6244 if (BaseOpcode->Atomic) { 6245 VData = Op.getOperand(2); 6246 6247 bool Is64Bit = VData.getValueType() == MVT::i64; 6248 if (BaseOpcode->AtomicX2) { 6249 SDValue VData2 = Op.getOperand(3); 6250 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6251 {VData, VData2}); 6252 if (Is64Bit) 6253 VData = DAG.getBitcast(MVT::v4i32, VData); 6254 6255 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6256 DMask = Is64Bit ? 0xf : 0x3; 6257 NumVDataDwords = Is64Bit ? 4 : 2; 6258 } else { 6259 DMask = Is64Bit ? 0x3 : 0x1; 6260 NumVDataDwords = Is64Bit ? 2 : 1; 6261 } 6262 } else { 6263 auto *DMaskConst = 6264 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6265 DMask = DMaskConst->getZExtValue(); 6266 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6267 6268 if (BaseOpcode->Store) { 6269 VData = Op.getOperand(2); 6270 6271 MVT StoreVT = VData.getSimpleValueType(); 6272 if (StoreVT.getScalarType() == MVT::f16) { 6273 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6274 return Op; // D16 is unsupported for this instruction 6275 6276 IsD16 = true; 6277 VData = handleD16VData(VData, DAG, true); 6278 } 6279 6280 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6281 } else { 6282 // Work out the num dwords based on the dmask popcount and underlying type 6283 // and whether packing is supported. 6284 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6285 if (LoadVT.getScalarType() == MVT::f16) { 6286 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6287 return Op; // D16 is unsupported for this instruction 6288 6289 IsD16 = true; 6290 } 6291 6292 // Confirm that the return type is large enough for the dmask specified 6293 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6294 (!LoadVT.isVector() && DMaskLanes > 1)) 6295 return Op; 6296 6297 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6298 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6299 // instructions. 6300 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6301 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6302 NumVDataDwords = (DMaskLanes + 1) / 2; 6303 else 6304 NumVDataDwords = DMaskLanes; 6305 6306 AdjustRetType = true; 6307 } 6308 } 6309 6310 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6311 SmallVector<SDValue, 4> VAddrs; 6312 6313 // Check for 16 bit addresses or derivatives and pack if true. 6314 MVT VAddrVT = 6315 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6316 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6317 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6318 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6319 6320 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6321 VAddrScalarVT = VAddrVT.getScalarType(); 6322 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6323 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6324 6325 // Push back extra arguments. 6326 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) { 6327 if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) { 6328 assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument"); 6329 // Special handling of bias when A16 is on. Bias is of type half but 6330 // occupies full 32-bit. 6331 SDValue Bias = DAG.getBuildVector( 6332 MVT::v2f16, DL, 6333 {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)}); 6334 VAddrs.push_back(Bias); 6335 } else { 6336 assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) && 6337 "Bias needs to be converted to 16 bit in A16 mode"); 6338 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6339 } 6340 } 6341 6342 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) { 6343 // 16 bit gradients are supported, but are tied to the A16 control 6344 // so both gradients and addresses must be 16 bit 6345 LLVM_DEBUG( 6346 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6347 "require 16 bit args for both gradients and addresses"); 6348 return Op; 6349 } 6350 6351 if (IsA16) { 6352 if (!ST->hasA16()) { 6353 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6354 "support 16 bit addresses\n"); 6355 return Op; 6356 } 6357 } 6358 6359 // We've dealt with incorrect input so we know that if IsA16, IsG16 6360 // are set then we have to compress/pack operands (either address, 6361 // gradient or both) 6362 // In the case where a16 and gradients are tied (no G16 support) then we 6363 // have already verified that both IsA16 and IsG16 are true 6364 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) { 6365 // Activate g16 6366 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6367 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6368 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6369 } 6370 6371 // Add gradients (packed or unpacked) 6372 if (IsG16) { 6373 // Pack the gradients 6374 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6375 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs, 6376 ArgOffset + Intr->GradientStart, 6377 ArgOffset + Intr->CoordStart, Intr->NumGradients); 6378 } else { 6379 for (unsigned I = ArgOffset + Intr->GradientStart; 6380 I < ArgOffset + Intr->CoordStart; I++) 6381 VAddrs.push_back(Op.getOperand(I)); 6382 } 6383 6384 // Add addresses (packed or unpacked) 6385 if (IsA16) { 6386 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs, 6387 ArgOffset + Intr->CoordStart, VAddrEnd, 6388 0 /* No gradients */); 6389 } else { 6390 // Add uncompressed address 6391 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6392 VAddrs.push_back(Op.getOperand(I)); 6393 } 6394 6395 // If the register allocator cannot place the address registers contiguously 6396 // without introducing moves, then using the non-sequential address encoding 6397 // is always preferable, since it saves VALU instructions and is usually a 6398 // wash in terms of code size or even better. 6399 // 6400 // However, we currently have no way of hinting to the register allocator that 6401 // MIMG addresses should be placed contiguously when it is possible to do so, 6402 // so force non-NSA for the common 2-address case as a heuristic. 6403 // 6404 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6405 // allocation when possible. 6406 // 6407 // TODO: we can actually allow partial NSA where the final register is a 6408 // contiguous set of the remaining addresses. 6409 // This could help where there are more addresses than supported. 6410 bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) && 6411 VAddrs.size() >= 3 && 6412 VAddrs.size() <= (unsigned)ST->getNSAMaxSize(); 6413 SDValue VAddr; 6414 if (!UseNSA) 6415 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6416 6417 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6418 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6419 SDValue Unorm; 6420 if (!BaseOpcode->Sampler) { 6421 Unorm = True; 6422 } else { 6423 auto UnormConst = 6424 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6425 6426 Unorm = UnormConst->getZExtValue() ? True : False; 6427 } 6428 6429 SDValue TFE; 6430 SDValue LWE; 6431 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6432 bool IsTexFail = false; 6433 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6434 return Op; 6435 6436 if (IsTexFail) { 6437 if (!DMaskLanes) { 6438 // Expecting to get an error flag since TFC is on - and dmask is 0 6439 // Force dmask to be at least 1 otherwise the instruction will fail 6440 DMask = 0x1; 6441 DMaskLanes = 1; 6442 NumVDataDwords = 1; 6443 } 6444 NumVDataDwords += 1; 6445 AdjustRetType = true; 6446 } 6447 6448 // Has something earlier tagged that the return type needs adjusting 6449 // This happens if the instruction is a load or has set TexFailCtrl flags 6450 if (AdjustRetType) { 6451 // NumVDataDwords reflects the true number of dwords required in the return type 6452 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6453 // This is a no-op load. This can be eliminated 6454 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6455 if (isa<MemSDNode>(Op)) 6456 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6457 return Undef; 6458 } 6459 6460 EVT NewVT = NumVDataDwords > 1 ? 6461 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6462 : MVT::i32; 6463 6464 ResultTypes[0] = NewVT; 6465 if (ResultTypes.size() == 3) { 6466 // Original result was aggregate type used for TexFailCtrl results 6467 // The actual instruction returns as a vector type which has now been 6468 // created. Remove the aggregate result. 6469 ResultTypes.erase(&ResultTypes[1]); 6470 } 6471 } 6472 6473 unsigned CPol = cast<ConstantSDNode>( 6474 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6475 if (BaseOpcode->Atomic) 6476 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6477 if (CPol & ~AMDGPU::CPol::ALL) 6478 return Op; 6479 6480 SmallVector<SDValue, 26> Ops; 6481 if (BaseOpcode->Store || BaseOpcode->Atomic) 6482 Ops.push_back(VData); // vdata 6483 if (UseNSA) 6484 append_range(Ops, VAddrs); 6485 else 6486 Ops.push_back(VAddr); 6487 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6488 if (BaseOpcode->Sampler) 6489 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6490 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6491 if (IsGFX10Plus) 6492 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6493 Ops.push_back(Unorm); 6494 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6495 Ops.push_back(IsA16 && // r128, a16 for gfx9 6496 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6497 if (IsGFX10Plus) 6498 Ops.push_back(IsA16 ? True : False); 6499 if (!Subtarget->hasGFX90AInsts()) { 6500 Ops.push_back(TFE); //tfe 6501 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6502 report_fatal_error("TFE is not supported on this GPU"); 6503 } 6504 Ops.push_back(LWE); // lwe 6505 if (!IsGFX10Plus) 6506 Ops.push_back(DimInfo->DA ? True : False); 6507 if (BaseOpcode->HasD16) 6508 Ops.push_back(IsD16 ? True : False); 6509 if (isa<MemSDNode>(Op)) 6510 Ops.push_back(Op.getOperand(0)); // chain 6511 6512 int NumVAddrDwords = 6513 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6514 int Opcode = -1; 6515 6516 if (IsGFX11Plus) { 6517 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6518 UseNSA ? AMDGPU::MIMGEncGfx11NSA 6519 : AMDGPU::MIMGEncGfx11Default, 6520 NumVDataDwords, NumVAddrDwords); 6521 } else if (IsGFX10Plus) { 6522 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6523 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6524 : AMDGPU::MIMGEncGfx10Default, 6525 NumVDataDwords, NumVAddrDwords); 6526 } else { 6527 if (Subtarget->hasGFX90AInsts()) { 6528 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6529 NumVDataDwords, NumVAddrDwords); 6530 if (Opcode == -1) 6531 report_fatal_error( 6532 "requested image instruction is not supported on this GPU"); 6533 } 6534 if (Opcode == -1 && 6535 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6536 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6537 NumVDataDwords, NumVAddrDwords); 6538 if (Opcode == -1) 6539 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6540 NumVDataDwords, NumVAddrDwords); 6541 } 6542 assert(Opcode != -1); 6543 6544 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6545 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6546 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6547 DAG.setNodeMemRefs(NewNode, {MemRef}); 6548 } 6549 6550 if (BaseOpcode->AtomicX2) { 6551 SmallVector<SDValue, 1> Elt; 6552 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6553 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6554 } 6555 if (BaseOpcode->Store) 6556 return SDValue(NewNode, 0); 6557 return constructRetValue(DAG, NewNode, 6558 OrigResultTypes, IsTexFail, 6559 Subtarget->hasUnpackedD16VMem(), IsD16, 6560 DMaskLanes, NumVDataDwords, DL); 6561 } 6562 6563 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6564 SDValue Offset, SDValue CachePolicy, 6565 SelectionDAG &DAG) const { 6566 MachineFunction &MF = DAG.getMachineFunction(); 6567 6568 const DataLayout &DataLayout = DAG.getDataLayout(); 6569 Align Alignment = 6570 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6571 6572 MachineMemOperand *MMO = MF.getMachineMemOperand( 6573 MachinePointerInfo(), 6574 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6575 MachineMemOperand::MOInvariant, 6576 VT.getStoreSize(), Alignment); 6577 6578 if (!Offset->isDivergent()) { 6579 SDValue Ops[] = { 6580 Rsrc, 6581 Offset, // Offset 6582 CachePolicy 6583 }; 6584 6585 // Widen vec3 load to vec4. 6586 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6587 EVT WidenedVT = 6588 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6589 auto WidenedOp = DAG.getMemIntrinsicNode( 6590 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6591 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6592 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6593 DAG.getVectorIdxConstant(0, DL)); 6594 return Subvector; 6595 } 6596 6597 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6598 DAG.getVTList(VT), Ops, VT, MMO); 6599 } 6600 6601 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6602 // assume that the buffer is unswizzled. 6603 SmallVector<SDValue, 4> Loads; 6604 unsigned NumLoads = 1; 6605 MVT LoadVT = VT.getSimpleVT(); 6606 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6607 assert((LoadVT.getScalarType() == MVT::i32 || 6608 LoadVT.getScalarType() == MVT::f32)); 6609 6610 if (NumElts == 8 || NumElts == 16) { 6611 NumLoads = NumElts / 4; 6612 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6613 } 6614 6615 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6616 SDValue Ops[] = { 6617 DAG.getEntryNode(), // Chain 6618 Rsrc, // rsrc 6619 DAG.getConstant(0, DL, MVT::i32), // vindex 6620 {}, // voffset 6621 {}, // soffset 6622 {}, // offset 6623 CachePolicy, // cachepolicy 6624 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6625 }; 6626 6627 // Use the alignment to ensure that the required offsets will fit into the 6628 // immediate offsets. 6629 setBufferOffsets(Offset, DAG, &Ops[3], 6630 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6631 6632 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6633 for (unsigned i = 0; i < NumLoads; ++i) { 6634 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6635 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6636 LoadVT, MMO, DAG)); 6637 } 6638 6639 if (NumElts == 8 || NumElts == 16) 6640 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6641 6642 return Loads[0]; 6643 } 6644 6645 SDValue SITargetLowering::lowerWorkitemID(SelectionDAG &DAG, SDValue Op, 6646 unsigned Dim, 6647 const ArgDescriptor &Arg) const { 6648 SDLoc SL(Op); 6649 MachineFunction &MF = DAG.getMachineFunction(); 6650 unsigned MaxID = Subtarget->getMaxWorkitemID(MF.getFunction(), Dim); 6651 if (MaxID == 0) 6652 return DAG.getConstant(0, SL, MVT::i32); 6653 6654 SDValue Val = loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6655 SDLoc(DAG.getEntryNode()), Arg); 6656 6657 // Don't bother inserting AssertZext for packed IDs since we're emitting the 6658 // masking operations anyway. 6659 // 6660 // TODO: We could assert the top bit is 0 for the source copy. 6661 if (Arg.isMasked()) 6662 return Val; 6663 6664 // Preserve the known bits after expansion to a copy. 6665 EVT SmallVT = 6666 EVT::getIntegerVT(*DAG.getContext(), 32 - countLeadingZeros(MaxID)); 6667 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Val, 6668 DAG.getValueType(SmallVT)); 6669 } 6670 6671 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6672 SelectionDAG &DAG) const { 6673 MachineFunction &MF = DAG.getMachineFunction(); 6674 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6675 6676 EVT VT = Op.getValueType(); 6677 SDLoc DL(Op); 6678 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6679 6680 // TODO: Should this propagate fast-math-flags? 6681 6682 switch (IntrinsicID) { 6683 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6684 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6685 return emitNonHSAIntrinsicError(DAG, DL, VT); 6686 return getPreloadedValue(DAG, *MFI, VT, 6687 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6688 } 6689 case Intrinsic::amdgcn_dispatch_ptr: 6690 case Intrinsic::amdgcn_queue_ptr: { 6691 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6692 DiagnosticInfoUnsupported BadIntrin( 6693 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6694 DL.getDebugLoc()); 6695 DAG.getContext()->diagnose(BadIntrin); 6696 return DAG.getUNDEF(VT); 6697 } 6698 6699 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6700 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6701 return getPreloadedValue(DAG, *MFI, VT, RegID); 6702 } 6703 case Intrinsic::amdgcn_implicitarg_ptr: { 6704 if (MFI->isEntryFunction()) 6705 return getImplicitArgPtr(DAG, DL); 6706 return getPreloadedValue(DAG, *MFI, VT, 6707 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6708 } 6709 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6710 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6711 // This only makes sense to call in a kernel, so just lower to null. 6712 return DAG.getConstant(0, DL, VT); 6713 } 6714 6715 return getPreloadedValue(DAG, *MFI, VT, 6716 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6717 } 6718 case Intrinsic::amdgcn_dispatch_id: { 6719 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6720 } 6721 case Intrinsic::amdgcn_rcp: 6722 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6723 case Intrinsic::amdgcn_rsq: 6724 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6725 case Intrinsic::amdgcn_rsq_legacy: 6726 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6727 return emitRemovedIntrinsicError(DAG, DL, VT); 6728 return SDValue(); 6729 case Intrinsic::amdgcn_rcp_legacy: 6730 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6731 return emitRemovedIntrinsicError(DAG, DL, VT); 6732 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6733 case Intrinsic::amdgcn_rsq_clamp: { 6734 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6735 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6736 6737 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6738 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6739 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6740 6741 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6742 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6743 DAG.getConstantFP(Max, DL, VT)); 6744 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6745 DAG.getConstantFP(Min, DL, VT)); 6746 } 6747 case Intrinsic::r600_read_ngroups_x: 6748 if (Subtarget->isAmdHsaOS()) 6749 return emitNonHSAIntrinsicError(DAG, DL, VT); 6750 6751 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6752 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6753 false); 6754 case Intrinsic::r600_read_ngroups_y: 6755 if (Subtarget->isAmdHsaOS()) 6756 return emitNonHSAIntrinsicError(DAG, DL, VT); 6757 6758 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6759 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6760 false); 6761 case Intrinsic::r600_read_ngroups_z: 6762 if (Subtarget->isAmdHsaOS()) 6763 return emitNonHSAIntrinsicError(DAG, DL, VT); 6764 6765 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6766 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6767 false); 6768 case Intrinsic::r600_read_global_size_x: 6769 if (Subtarget->isAmdHsaOS()) 6770 return emitNonHSAIntrinsicError(DAG, DL, VT); 6771 6772 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6773 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6774 Align(4), false); 6775 case Intrinsic::r600_read_global_size_y: 6776 if (Subtarget->isAmdHsaOS()) 6777 return emitNonHSAIntrinsicError(DAG, DL, VT); 6778 6779 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6780 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6781 Align(4), false); 6782 case Intrinsic::r600_read_global_size_z: 6783 if (Subtarget->isAmdHsaOS()) 6784 return emitNonHSAIntrinsicError(DAG, DL, VT); 6785 6786 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6787 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6788 Align(4), false); 6789 case Intrinsic::r600_read_local_size_x: 6790 if (Subtarget->isAmdHsaOS()) 6791 return emitNonHSAIntrinsicError(DAG, DL, VT); 6792 6793 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6794 SI::KernelInputOffsets::LOCAL_SIZE_X); 6795 case Intrinsic::r600_read_local_size_y: 6796 if (Subtarget->isAmdHsaOS()) 6797 return emitNonHSAIntrinsicError(DAG, DL, VT); 6798 6799 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6800 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6801 case Intrinsic::r600_read_local_size_z: 6802 if (Subtarget->isAmdHsaOS()) 6803 return emitNonHSAIntrinsicError(DAG, DL, VT); 6804 6805 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6806 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6807 case Intrinsic::amdgcn_workgroup_id_x: 6808 return getPreloadedValue(DAG, *MFI, VT, 6809 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6810 case Intrinsic::amdgcn_workgroup_id_y: 6811 return getPreloadedValue(DAG, *MFI, VT, 6812 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6813 case Intrinsic::amdgcn_workgroup_id_z: 6814 return getPreloadedValue(DAG, *MFI, VT, 6815 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6816 case Intrinsic::amdgcn_workitem_id_x: 6817 return lowerWorkitemID(DAG, Op, 0, MFI->getArgInfo().WorkItemIDX); 6818 case Intrinsic::amdgcn_workitem_id_y: 6819 return lowerWorkitemID(DAG, Op, 1, MFI->getArgInfo().WorkItemIDY); 6820 case Intrinsic::amdgcn_workitem_id_z: 6821 return lowerWorkitemID(DAG, Op, 2, MFI->getArgInfo().WorkItemIDZ); 6822 case Intrinsic::amdgcn_wavefrontsize: 6823 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6824 SDLoc(Op), MVT::i32); 6825 case Intrinsic::amdgcn_s_buffer_load: { 6826 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6827 if (CPol & ~AMDGPU::CPol::ALL) 6828 return Op; 6829 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6830 DAG); 6831 } 6832 case Intrinsic::amdgcn_fdiv_fast: 6833 return lowerFDIV_FAST(Op, DAG); 6834 case Intrinsic::amdgcn_sin: 6835 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6836 6837 case Intrinsic::amdgcn_cos: 6838 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6839 6840 case Intrinsic::amdgcn_mul_u24: 6841 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6842 case Intrinsic::amdgcn_mul_i24: 6843 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6844 6845 case Intrinsic::amdgcn_log_clamp: { 6846 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6847 return SDValue(); 6848 6849 return emitRemovedIntrinsicError(DAG, DL, VT); 6850 } 6851 case Intrinsic::amdgcn_ldexp: 6852 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6853 Op.getOperand(1), Op.getOperand(2)); 6854 6855 case Intrinsic::amdgcn_fract: 6856 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6857 6858 case Intrinsic::amdgcn_class: 6859 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6860 Op.getOperand(1), Op.getOperand(2)); 6861 case Intrinsic::amdgcn_div_fmas: 6862 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6863 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6864 Op.getOperand(4)); 6865 6866 case Intrinsic::amdgcn_div_fixup: 6867 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6868 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6869 6870 case Intrinsic::amdgcn_div_scale: { 6871 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6872 6873 // Translate to the operands expected by the machine instruction. The 6874 // first parameter must be the same as the first instruction. 6875 SDValue Numerator = Op.getOperand(1); 6876 SDValue Denominator = Op.getOperand(2); 6877 6878 // Note this order is opposite of the machine instruction's operations, 6879 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6880 // intrinsic has the numerator as the first operand to match a normal 6881 // division operation. 6882 6883 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator; 6884 6885 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6886 Denominator, Numerator); 6887 } 6888 case Intrinsic::amdgcn_icmp: { 6889 // There is a Pat that handles this variant, so return it as-is. 6890 if (Op.getOperand(1).getValueType() == MVT::i1 && 6891 Op.getConstantOperandVal(2) == 0 && 6892 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6893 return Op; 6894 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6895 } 6896 case Intrinsic::amdgcn_fcmp: { 6897 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6898 } 6899 case Intrinsic::amdgcn_ballot: 6900 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6901 case Intrinsic::amdgcn_fmed3: 6902 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6903 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6904 case Intrinsic::amdgcn_fdot2: 6905 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6906 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6907 Op.getOperand(4)); 6908 case Intrinsic::amdgcn_fmul_legacy: 6909 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6910 Op.getOperand(1), Op.getOperand(2)); 6911 case Intrinsic::amdgcn_sffbh: 6912 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6913 case Intrinsic::amdgcn_sbfe: 6914 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6915 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6916 case Intrinsic::amdgcn_ubfe: 6917 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6918 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6919 case Intrinsic::amdgcn_cvt_pkrtz: 6920 case Intrinsic::amdgcn_cvt_pknorm_i16: 6921 case Intrinsic::amdgcn_cvt_pknorm_u16: 6922 case Intrinsic::amdgcn_cvt_pk_i16: 6923 case Intrinsic::amdgcn_cvt_pk_u16: { 6924 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6925 EVT VT = Op.getValueType(); 6926 unsigned Opcode; 6927 6928 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6929 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6930 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6931 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6932 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6933 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6934 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6935 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6936 else 6937 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6938 6939 if (isTypeLegal(VT)) 6940 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6941 6942 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6943 Op.getOperand(1), Op.getOperand(2)); 6944 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6945 } 6946 case Intrinsic::amdgcn_fmad_ftz: 6947 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6948 Op.getOperand(2), Op.getOperand(3)); 6949 6950 case Intrinsic::amdgcn_if_break: 6951 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6952 Op->getOperand(1), Op->getOperand(2)), 0); 6953 6954 case Intrinsic::amdgcn_groupstaticsize: { 6955 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6956 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6957 return Op; 6958 6959 const Module *M = MF.getFunction().getParent(); 6960 const GlobalValue *GV = 6961 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6962 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6963 SIInstrInfo::MO_ABS32_LO); 6964 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6965 } 6966 case Intrinsic::amdgcn_is_shared: 6967 case Intrinsic::amdgcn_is_private: { 6968 SDLoc SL(Op); 6969 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6970 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6971 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6972 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6973 Op.getOperand(1)); 6974 6975 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6976 DAG.getConstant(1, SL, MVT::i32)); 6977 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6978 } 6979 case Intrinsic::amdgcn_perm: 6980 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1), 6981 Op.getOperand(2), Op.getOperand(3)); 6982 case Intrinsic::amdgcn_reloc_constant: { 6983 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6984 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6985 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6986 auto RelocSymbol = cast<GlobalVariable>( 6987 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6988 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6989 SIInstrInfo::MO_ABS32_LO); 6990 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6991 } 6992 default: 6993 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6994 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6995 return lowerImage(Op, ImageDimIntr, DAG, false); 6996 6997 return Op; 6998 } 6999 } 7000 7001 /// Update \p MMO based on the offset inputs to an intrinsic. 7002 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset, 7003 SDValue SOffset, SDValue Offset, 7004 SDValue VIndex = SDValue()) { 7005 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 7006 !isa<ConstantSDNode>(Offset)) { 7007 // The combined offset is not known to be constant, so we cannot represent 7008 // it in the MMO. Give up. 7009 MMO->setValue((Value *)nullptr); 7010 return; 7011 } 7012 7013 if (VIndex && (!isa<ConstantSDNode>(VIndex) || 7014 !cast<ConstantSDNode>(VIndex)->isZero())) { 7015 // The strided index component of the address is not known to be zero, so we 7016 // cannot represent it in the MMO. Give up. 7017 MMO->setValue((Value *)nullptr); 7018 return; 7019 } 7020 7021 MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() + 7022 cast<ConstantSDNode>(SOffset)->getSExtValue() + 7023 cast<ConstantSDNode>(Offset)->getSExtValue()); 7024 } 7025 7026 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 7027 SelectionDAG &DAG, 7028 unsigned NewOpcode) const { 7029 SDLoc DL(Op); 7030 7031 SDValue VData = Op.getOperand(2); 7032 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7033 SDValue Ops[] = { 7034 Op.getOperand(0), // Chain 7035 VData, // vdata 7036 Op.getOperand(3), // rsrc 7037 DAG.getConstant(0, DL, MVT::i32), // vindex 7038 Offsets.first, // voffset 7039 Op.getOperand(5), // soffset 7040 Offsets.second, // offset 7041 Op.getOperand(6), // cachepolicy 7042 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7043 }; 7044 7045 auto *M = cast<MemSDNode>(Op); 7046 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 7047 7048 EVT MemVT = VData.getValueType(); 7049 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7050 M->getMemOperand()); 7051 } 7052 7053 // Return a value to use for the idxen operand by examining the vindex operand. 7054 static unsigned getIdxEn(SDValue VIndex) { 7055 if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex)) 7056 // No need to set idxen if vindex is known to be zero. 7057 return VIndexC->getZExtValue() != 0; 7058 return 1; 7059 } 7060 7061 SDValue 7062 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 7063 unsigned NewOpcode) const { 7064 SDLoc DL(Op); 7065 7066 SDValue VData = Op.getOperand(2); 7067 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7068 SDValue Ops[] = { 7069 Op.getOperand(0), // Chain 7070 VData, // vdata 7071 Op.getOperand(3), // rsrc 7072 Op.getOperand(4), // vindex 7073 Offsets.first, // voffset 7074 Op.getOperand(6), // soffset 7075 Offsets.second, // offset 7076 Op.getOperand(7), // cachepolicy 7077 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7078 }; 7079 7080 auto *M = cast<MemSDNode>(Op); 7081 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7082 7083 EVT MemVT = VData.getValueType(); 7084 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7085 M->getMemOperand()); 7086 } 7087 7088 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 7089 SelectionDAG &DAG) const { 7090 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7091 SDLoc DL(Op); 7092 7093 switch (IntrID) { 7094 case Intrinsic::amdgcn_ds_ordered_add: 7095 case Intrinsic::amdgcn_ds_ordered_swap: { 7096 MemSDNode *M = cast<MemSDNode>(Op); 7097 SDValue Chain = M->getOperand(0); 7098 SDValue M0 = M->getOperand(2); 7099 SDValue Value = M->getOperand(3); 7100 unsigned IndexOperand = M->getConstantOperandVal(7); 7101 unsigned WaveRelease = M->getConstantOperandVal(8); 7102 unsigned WaveDone = M->getConstantOperandVal(9); 7103 7104 unsigned OrderedCountIndex = IndexOperand & 0x3f; 7105 IndexOperand &= ~0x3f; 7106 unsigned CountDw = 0; 7107 7108 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 7109 CountDw = (IndexOperand >> 24) & 0xf; 7110 IndexOperand &= ~(0xf << 24); 7111 7112 if (CountDw < 1 || CountDw > 4) { 7113 report_fatal_error( 7114 "ds_ordered_count: dword count must be between 1 and 4"); 7115 } 7116 } 7117 7118 if (IndexOperand) 7119 report_fatal_error("ds_ordered_count: bad index operand"); 7120 7121 if (WaveDone && !WaveRelease) 7122 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 7123 7124 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 7125 unsigned ShaderType = 7126 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 7127 unsigned Offset0 = OrderedCountIndex << 2; 7128 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (Instruction << 4); 7129 7130 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 7131 Offset1 |= (CountDw - 1) << 6; 7132 7133 if (Subtarget->getGeneration() < AMDGPUSubtarget::GFX11) 7134 Offset1 |= ShaderType << 2; 7135 7136 unsigned Offset = Offset0 | (Offset1 << 8); 7137 7138 SDValue Ops[] = { 7139 Chain, 7140 Value, 7141 DAG.getTargetConstant(Offset, DL, MVT::i16), 7142 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 7143 }; 7144 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 7145 M->getVTList(), Ops, M->getMemoryVT(), 7146 M->getMemOperand()); 7147 } 7148 case Intrinsic::amdgcn_ds_fadd: { 7149 MemSDNode *M = cast<MemSDNode>(Op); 7150 unsigned Opc; 7151 switch (IntrID) { 7152 case Intrinsic::amdgcn_ds_fadd: 7153 Opc = ISD::ATOMIC_LOAD_FADD; 7154 break; 7155 } 7156 7157 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 7158 M->getOperand(0), M->getOperand(2), M->getOperand(3), 7159 M->getMemOperand()); 7160 } 7161 case Intrinsic::amdgcn_atomic_inc: 7162 case Intrinsic::amdgcn_atomic_dec: 7163 case Intrinsic::amdgcn_ds_fmin: 7164 case Intrinsic::amdgcn_ds_fmax: { 7165 MemSDNode *M = cast<MemSDNode>(Op); 7166 unsigned Opc; 7167 switch (IntrID) { 7168 case Intrinsic::amdgcn_atomic_inc: 7169 Opc = AMDGPUISD::ATOMIC_INC; 7170 break; 7171 case Intrinsic::amdgcn_atomic_dec: 7172 Opc = AMDGPUISD::ATOMIC_DEC; 7173 break; 7174 case Intrinsic::amdgcn_ds_fmin: 7175 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 7176 break; 7177 case Intrinsic::amdgcn_ds_fmax: 7178 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 7179 break; 7180 default: 7181 llvm_unreachable("Unknown intrinsic!"); 7182 } 7183 SDValue Ops[] = { 7184 M->getOperand(0), // Chain 7185 M->getOperand(2), // Ptr 7186 M->getOperand(3) // Value 7187 }; 7188 7189 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 7190 M->getMemoryVT(), M->getMemOperand()); 7191 } 7192 case Intrinsic::amdgcn_buffer_load: 7193 case Intrinsic::amdgcn_buffer_load_format: { 7194 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 7195 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7196 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7197 SDValue Ops[] = { 7198 Op.getOperand(0), // Chain 7199 Op.getOperand(2), // rsrc 7200 Op.getOperand(3), // vindex 7201 SDValue(), // voffset -- will be set by setBufferOffsets 7202 SDValue(), // soffset -- will be set by setBufferOffsets 7203 SDValue(), // offset -- will be set by setBufferOffsets 7204 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7205 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7206 }; 7207 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 7208 7209 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 7210 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 7211 7212 EVT VT = Op.getValueType(); 7213 EVT IntVT = VT.changeTypeToInteger(); 7214 auto *M = cast<MemSDNode>(Op); 7215 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7216 EVT LoadVT = Op.getValueType(); 7217 7218 if (LoadVT.getScalarType() == MVT::f16) 7219 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 7220 M, DAG, Ops); 7221 7222 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 7223 if (LoadVT.getScalarType() == MVT::i8 || 7224 LoadVT.getScalarType() == MVT::i16) 7225 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 7226 7227 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 7228 M->getMemOperand(), DAG); 7229 } 7230 case Intrinsic::amdgcn_raw_buffer_load: 7231 case Intrinsic::amdgcn_raw_buffer_load_format: { 7232 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 7233 7234 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7235 SDValue Ops[] = { 7236 Op.getOperand(0), // Chain 7237 Op.getOperand(2), // rsrc 7238 DAG.getConstant(0, DL, MVT::i32), // vindex 7239 Offsets.first, // voffset 7240 Op.getOperand(4), // soffset 7241 Offsets.second, // offset 7242 Op.getOperand(5), // cachepolicy, swizzled buffer 7243 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7244 }; 7245 7246 auto *M = cast<MemSDNode>(Op); 7247 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]); 7248 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 7249 } 7250 case Intrinsic::amdgcn_struct_buffer_load: 7251 case Intrinsic::amdgcn_struct_buffer_load_format: { 7252 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7253 7254 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7255 SDValue Ops[] = { 7256 Op.getOperand(0), // Chain 7257 Op.getOperand(2), // rsrc 7258 Op.getOperand(3), // vindex 7259 Offsets.first, // voffset 7260 Op.getOperand(5), // soffset 7261 Offsets.second, // offset 7262 Op.getOperand(6), // cachepolicy, swizzled buffer 7263 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7264 }; 7265 7266 auto *M = cast<MemSDNode>(Op); 7267 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7268 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7269 } 7270 case Intrinsic::amdgcn_tbuffer_load: { 7271 MemSDNode *M = cast<MemSDNode>(Op); 7272 EVT LoadVT = Op.getValueType(); 7273 7274 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7275 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7276 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7277 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7278 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7279 SDValue Ops[] = { 7280 Op.getOperand(0), // Chain 7281 Op.getOperand(2), // rsrc 7282 Op.getOperand(3), // vindex 7283 Op.getOperand(4), // voffset 7284 Op.getOperand(5), // soffset 7285 Op.getOperand(6), // offset 7286 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7287 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7288 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7289 }; 7290 7291 if (LoadVT.getScalarType() == MVT::f16) 7292 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7293 M, DAG, Ops); 7294 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7295 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7296 DAG); 7297 } 7298 case Intrinsic::amdgcn_raw_tbuffer_load: { 7299 MemSDNode *M = cast<MemSDNode>(Op); 7300 EVT LoadVT = Op.getValueType(); 7301 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7302 7303 SDValue Ops[] = { 7304 Op.getOperand(0), // Chain 7305 Op.getOperand(2), // rsrc 7306 DAG.getConstant(0, DL, MVT::i32), // vindex 7307 Offsets.first, // voffset 7308 Op.getOperand(4), // soffset 7309 Offsets.second, // offset 7310 Op.getOperand(5), // format 7311 Op.getOperand(6), // cachepolicy, swizzled buffer 7312 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7313 }; 7314 7315 if (LoadVT.getScalarType() == MVT::f16) 7316 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7317 M, DAG, Ops); 7318 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7319 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7320 DAG); 7321 } 7322 case Intrinsic::amdgcn_struct_tbuffer_load: { 7323 MemSDNode *M = cast<MemSDNode>(Op); 7324 EVT LoadVT = Op.getValueType(); 7325 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7326 7327 SDValue Ops[] = { 7328 Op.getOperand(0), // Chain 7329 Op.getOperand(2), // rsrc 7330 Op.getOperand(3), // vindex 7331 Offsets.first, // voffset 7332 Op.getOperand(5), // soffset 7333 Offsets.second, // offset 7334 Op.getOperand(6), // format 7335 Op.getOperand(7), // cachepolicy, swizzled buffer 7336 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7337 }; 7338 7339 if (LoadVT.getScalarType() == MVT::f16) 7340 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7341 M, DAG, Ops); 7342 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7343 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7344 DAG); 7345 } 7346 case Intrinsic::amdgcn_buffer_atomic_swap: 7347 case Intrinsic::amdgcn_buffer_atomic_add: 7348 case Intrinsic::amdgcn_buffer_atomic_sub: 7349 case Intrinsic::amdgcn_buffer_atomic_csub: 7350 case Intrinsic::amdgcn_buffer_atomic_smin: 7351 case Intrinsic::amdgcn_buffer_atomic_umin: 7352 case Intrinsic::amdgcn_buffer_atomic_smax: 7353 case Intrinsic::amdgcn_buffer_atomic_umax: 7354 case Intrinsic::amdgcn_buffer_atomic_and: 7355 case Intrinsic::amdgcn_buffer_atomic_or: 7356 case Intrinsic::amdgcn_buffer_atomic_xor: 7357 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7358 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7359 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7360 SDValue Ops[] = { 7361 Op.getOperand(0), // Chain 7362 Op.getOperand(2), // vdata 7363 Op.getOperand(3), // rsrc 7364 Op.getOperand(4), // vindex 7365 SDValue(), // voffset -- will be set by setBufferOffsets 7366 SDValue(), // soffset -- will be set by setBufferOffsets 7367 SDValue(), // offset -- will be set by setBufferOffsets 7368 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7369 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7370 }; 7371 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7372 7373 EVT VT = Op.getValueType(); 7374 7375 auto *M = cast<MemSDNode>(Op); 7376 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7377 unsigned Opcode = 0; 7378 7379 switch (IntrID) { 7380 case Intrinsic::amdgcn_buffer_atomic_swap: 7381 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7382 break; 7383 case Intrinsic::amdgcn_buffer_atomic_add: 7384 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7385 break; 7386 case Intrinsic::amdgcn_buffer_atomic_sub: 7387 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7388 break; 7389 case Intrinsic::amdgcn_buffer_atomic_csub: 7390 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7391 break; 7392 case Intrinsic::amdgcn_buffer_atomic_smin: 7393 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7394 break; 7395 case Intrinsic::amdgcn_buffer_atomic_umin: 7396 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7397 break; 7398 case Intrinsic::amdgcn_buffer_atomic_smax: 7399 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7400 break; 7401 case Intrinsic::amdgcn_buffer_atomic_umax: 7402 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7403 break; 7404 case Intrinsic::amdgcn_buffer_atomic_and: 7405 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7406 break; 7407 case Intrinsic::amdgcn_buffer_atomic_or: 7408 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7409 break; 7410 case Intrinsic::amdgcn_buffer_atomic_xor: 7411 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7412 break; 7413 case Intrinsic::amdgcn_buffer_atomic_fadd: 7414 if (!Op.getValue(0).use_empty() && !hasAtomicFaddRtnForTy(Op)) { 7415 DiagnosticInfoUnsupported 7416 NoFpRet(DAG.getMachineFunction().getFunction(), 7417 "return versions of fp atomics not supported", 7418 DL.getDebugLoc(), DS_Error); 7419 DAG.getContext()->diagnose(NoFpRet); 7420 return SDValue(); 7421 } 7422 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7423 break; 7424 default: 7425 llvm_unreachable("unhandled atomic opcode"); 7426 } 7427 7428 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7429 M->getMemOperand()); 7430 } 7431 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7432 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7433 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7434 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7435 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7436 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7437 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7438 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7439 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7440 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7441 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7442 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7443 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7444 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7445 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7446 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7447 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7448 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7449 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7450 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7451 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7452 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7453 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7454 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7455 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7456 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7457 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7458 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7459 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7460 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7461 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7462 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7463 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7464 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7465 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7466 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7467 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7468 return lowerStructBufferAtomicIntrin(Op, DAG, 7469 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7470 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7471 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7472 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7473 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7474 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7475 return lowerStructBufferAtomicIntrin(Op, DAG, 7476 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7477 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7478 return lowerStructBufferAtomicIntrin(Op, DAG, 7479 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7480 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7481 return lowerStructBufferAtomicIntrin(Op, DAG, 7482 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7483 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7484 return lowerStructBufferAtomicIntrin(Op, DAG, 7485 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7486 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7487 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7488 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7489 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7490 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7491 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7492 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7493 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7494 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7495 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7496 7497 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7498 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7499 unsigned IdxEn = getIdxEn(Op.getOperand(5)); 7500 SDValue Ops[] = { 7501 Op.getOperand(0), // Chain 7502 Op.getOperand(2), // src 7503 Op.getOperand(3), // cmp 7504 Op.getOperand(4), // rsrc 7505 Op.getOperand(5), // vindex 7506 SDValue(), // voffset -- will be set by setBufferOffsets 7507 SDValue(), // soffset -- will be set by setBufferOffsets 7508 SDValue(), // offset -- will be set by setBufferOffsets 7509 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7510 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7511 }; 7512 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7513 7514 EVT VT = Op.getValueType(); 7515 auto *M = cast<MemSDNode>(Op); 7516 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7517 7518 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7519 Op->getVTList(), Ops, VT, M->getMemOperand()); 7520 } 7521 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7522 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7523 SDValue Ops[] = { 7524 Op.getOperand(0), // Chain 7525 Op.getOperand(2), // src 7526 Op.getOperand(3), // cmp 7527 Op.getOperand(4), // rsrc 7528 DAG.getConstant(0, DL, MVT::i32), // vindex 7529 Offsets.first, // voffset 7530 Op.getOperand(6), // soffset 7531 Offsets.second, // offset 7532 Op.getOperand(7), // cachepolicy 7533 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7534 }; 7535 EVT VT = Op.getValueType(); 7536 auto *M = cast<MemSDNode>(Op); 7537 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]); 7538 7539 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7540 Op->getVTList(), Ops, VT, M->getMemOperand()); 7541 } 7542 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7543 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7544 SDValue Ops[] = { 7545 Op.getOperand(0), // Chain 7546 Op.getOperand(2), // src 7547 Op.getOperand(3), // cmp 7548 Op.getOperand(4), // rsrc 7549 Op.getOperand(5), // vindex 7550 Offsets.first, // voffset 7551 Op.getOperand(7), // soffset 7552 Offsets.second, // offset 7553 Op.getOperand(8), // cachepolicy 7554 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7555 }; 7556 EVT VT = Op.getValueType(); 7557 auto *M = cast<MemSDNode>(Op); 7558 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7559 7560 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7561 Op->getVTList(), Ops, VT, M->getMemOperand()); 7562 } 7563 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7564 MemSDNode *M = cast<MemSDNode>(Op); 7565 SDValue NodePtr = M->getOperand(2); 7566 SDValue RayExtent = M->getOperand(3); 7567 SDValue RayOrigin = M->getOperand(4); 7568 SDValue RayDir = M->getOperand(5); 7569 SDValue RayInvDir = M->getOperand(6); 7570 SDValue TDescr = M->getOperand(7); 7571 7572 assert(NodePtr.getValueType() == MVT::i32 || 7573 NodePtr.getValueType() == MVT::i64); 7574 assert(RayDir.getValueType() == MVT::v3f16 || 7575 RayDir.getValueType() == MVT::v3f32); 7576 7577 if (!Subtarget->hasGFX10_AEncoding()) { 7578 emitRemovedIntrinsicError(DAG, DL, Op.getValueType()); 7579 return SDValue(); 7580 } 7581 7582 const bool IsGFX11Plus = AMDGPU::isGFX11Plus(*Subtarget); 7583 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7584 const bool Is64 = NodePtr.getValueType() == MVT::i64; 7585 const unsigned NumVDataDwords = 4; 7586 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11); 7587 const unsigned NumVAddrs = IsGFX11Plus ? (IsA16 ? 4 : 5) : NumVAddrDwords; 7588 const bool UseNSA = 7589 Subtarget->hasNSAEncoding() && NumVAddrs <= Subtarget->getNSAMaxSize(); 7590 const unsigned BaseOpcodes[2][2] = { 7591 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16}, 7592 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY, 7593 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}}; 7594 int Opcode; 7595 if (UseNSA) { 7596 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16], 7597 IsGFX11Plus ? AMDGPU::MIMGEncGfx11NSA 7598 : AMDGPU::MIMGEncGfx10NSA, 7599 NumVDataDwords, NumVAddrDwords); 7600 } else { 7601 Opcode = 7602 AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16], 7603 IsGFX11Plus ? AMDGPU::MIMGEncGfx11Default 7604 : AMDGPU::MIMGEncGfx10Default, 7605 NumVDataDwords, PowerOf2Ceil(NumVAddrDwords)); 7606 } 7607 assert(Opcode != -1); 7608 7609 SmallVector<SDValue, 16> Ops; 7610 7611 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7612 SmallVector<SDValue, 3> Lanes; 7613 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7614 if (Lanes[0].getValueSizeInBits() == 32) { 7615 for (unsigned I = 0; I < 3; ++I) 7616 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7617 } else { 7618 if (IsAligned) { 7619 Ops.push_back( 7620 DAG.getBitcast(MVT::i32, 7621 DAG.getBuildVector(MVT::v2f16, DL, 7622 { Lanes[0], Lanes[1] }))); 7623 Ops.push_back(Lanes[2]); 7624 } else { 7625 SDValue Elt0 = Ops.pop_back_val(); 7626 Ops.push_back( 7627 DAG.getBitcast(MVT::i32, 7628 DAG.getBuildVector(MVT::v2f16, DL, 7629 { Elt0, Lanes[0] }))); 7630 Ops.push_back( 7631 DAG.getBitcast(MVT::i32, 7632 DAG.getBuildVector(MVT::v2f16, DL, 7633 { Lanes[1], Lanes[2] }))); 7634 } 7635 } 7636 }; 7637 7638 if (UseNSA && IsGFX11Plus) { 7639 Ops.push_back(NodePtr); 7640 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7641 Ops.push_back(RayOrigin); 7642 if (IsA16) { 7643 SmallVector<SDValue, 3> DirLanes, InvDirLanes, MergedLanes; 7644 DAG.ExtractVectorElements(RayDir, DirLanes, 0, 3); 7645 DAG.ExtractVectorElements(RayInvDir, InvDirLanes, 0, 3); 7646 for (unsigned I = 0; I < 3; ++I) { 7647 MergedLanes.push_back(DAG.getBitcast( 7648 MVT::i32, DAG.getBuildVector(MVT::v2f16, DL, 7649 {DirLanes[I], InvDirLanes[I]}))); 7650 } 7651 Ops.push_back(DAG.getBuildVector(MVT::v3i32, DL, MergedLanes)); 7652 } else { 7653 Ops.push_back(RayDir); 7654 Ops.push_back(RayInvDir); 7655 } 7656 } else { 7657 if (Is64) 7658 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 7659 2); 7660 else 7661 Ops.push_back(NodePtr); 7662 7663 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7664 packLanes(RayOrigin, true); 7665 packLanes(RayDir, true); 7666 packLanes(RayInvDir, false); 7667 } 7668 7669 if (!UseNSA) { 7670 // Build a single vector containing all the operands so far prepared. 7671 if (NumVAddrDwords > 8) { 7672 SDValue Undef = DAG.getUNDEF(MVT::i32); 7673 Ops.append(16 - Ops.size(), Undef); 7674 } 7675 assert(Ops.size() == 8 || Ops.size() == 16); 7676 SDValue MergedOps = DAG.getBuildVector( 7677 Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops); 7678 Ops.clear(); 7679 Ops.push_back(MergedOps); 7680 } 7681 7682 Ops.push_back(TDescr); 7683 if (IsA16) 7684 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7685 Ops.push_back(M->getChain()); 7686 7687 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7688 MachineMemOperand *MemRef = M->getMemOperand(); 7689 DAG.setNodeMemRefs(NewNode, {MemRef}); 7690 return SDValue(NewNode, 0); 7691 } 7692 case Intrinsic::amdgcn_global_atomic_fadd: 7693 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7694 DiagnosticInfoUnsupported 7695 NoFpRet(DAG.getMachineFunction().getFunction(), 7696 "return versions of fp atomics not supported", 7697 DL.getDebugLoc(), DS_Error); 7698 DAG.getContext()->diagnose(NoFpRet); 7699 return SDValue(); 7700 } 7701 LLVM_FALLTHROUGH; 7702 case Intrinsic::amdgcn_global_atomic_fmin: 7703 case Intrinsic::amdgcn_global_atomic_fmax: 7704 case Intrinsic::amdgcn_flat_atomic_fadd: 7705 case Intrinsic::amdgcn_flat_atomic_fmin: 7706 case Intrinsic::amdgcn_flat_atomic_fmax: { 7707 MemSDNode *M = cast<MemSDNode>(Op); 7708 SDValue Ops[] = { 7709 M->getOperand(0), // Chain 7710 M->getOperand(2), // Ptr 7711 M->getOperand(3) // Value 7712 }; 7713 unsigned Opcode = 0; 7714 switch (IntrID) { 7715 case Intrinsic::amdgcn_global_atomic_fadd: 7716 case Intrinsic::amdgcn_flat_atomic_fadd: { 7717 EVT VT = Op.getOperand(3).getValueType(); 7718 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7719 DAG.getVTList(VT, MVT::Other), Ops, 7720 M->getMemOperand()); 7721 } 7722 case Intrinsic::amdgcn_global_atomic_fmin: 7723 case Intrinsic::amdgcn_flat_atomic_fmin: { 7724 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7725 break; 7726 } 7727 case Intrinsic::amdgcn_global_atomic_fmax: 7728 case Intrinsic::amdgcn_flat_atomic_fmax: { 7729 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7730 break; 7731 } 7732 default: 7733 llvm_unreachable("unhandled atomic opcode"); 7734 } 7735 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7736 M->getVTList(), Ops, M->getMemoryVT(), 7737 M->getMemOperand()); 7738 } 7739 default: 7740 7741 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7742 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7743 return lowerImage(Op, ImageDimIntr, DAG, true); 7744 7745 return SDValue(); 7746 } 7747 } 7748 7749 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7750 // dwordx4 if on SI. 7751 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7752 SDVTList VTList, 7753 ArrayRef<SDValue> Ops, EVT MemVT, 7754 MachineMemOperand *MMO, 7755 SelectionDAG &DAG) const { 7756 EVT VT = VTList.VTs[0]; 7757 EVT WidenedVT = VT; 7758 EVT WidenedMemVT = MemVT; 7759 if (!Subtarget->hasDwordx3LoadStores() && 7760 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7761 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7762 WidenedVT.getVectorElementType(), 4); 7763 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7764 WidenedMemVT.getVectorElementType(), 4); 7765 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7766 } 7767 7768 assert(VTList.NumVTs == 2); 7769 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7770 7771 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7772 WidenedMemVT, MMO); 7773 if (WidenedVT != VT) { 7774 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7775 DAG.getVectorIdxConstant(0, DL)); 7776 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7777 } 7778 return NewOp; 7779 } 7780 7781 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7782 bool ImageStore) const { 7783 EVT StoreVT = VData.getValueType(); 7784 7785 // No change for f16 and legal vector D16 types. 7786 if (!StoreVT.isVector()) 7787 return VData; 7788 7789 SDLoc DL(VData); 7790 unsigned NumElements = StoreVT.getVectorNumElements(); 7791 7792 if (Subtarget->hasUnpackedD16VMem()) { 7793 // We need to unpack the packed data to store. 7794 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7795 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7796 7797 EVT EquivStoreVT = 7798 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7799 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7800 return DAG.UnrollVectorOp(ZExt.getNode()); 7801 } 7802 7803 // The sq block of gfx8.1 does not estimate register use correctly for d16 7804 // image store instructions. The data operand is computed as if it were not a 7805 // d16 image instruction. 7806 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7807 // Bitcast to i16 7808 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7809 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7810 7811 // Decompose into scalars 7812 SmallVector<SDValue, 4> Elts; 7813 DAG.ExtractVectorElements(IntVData, Elts); 7814 7815 // Group pairs of i16 into v2i16 and bitcast to i32 7816 SmallVector<SDValue, 4> PackedElts; 7817 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7818 SDValue Pair = 7819 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7820 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7821 PackedElts.push_back(IntPair); 7822 } 7823 if ((NumElements % 2) == 1) { 7824 // Handle v3i16 7825 unsigned I = Elts.size() / 2; 7826 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7827 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7828 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7829 PackedElts.push_back(IntPair); 7830 } 7831 7832 // Pad using UNDEF 7833 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7834 7835 // Build final vector 7836 EVT VecVT = 7837 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7838 return DAG.getBuildVector(VecVT, DL, PackedElts); 7839 } 7840 7841 if (NumElements == 3) { 7842 EVT IntStoreVT = 7843 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7844 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7845 7846 EVT WidenedStoreVT = EVT::getVectorVT( 7847 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7848 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7849 WidenedStoreVT.getStoreSizeInBits()); 7850 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7851 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7852 } 7853 7854 assert(isTypeLegal(StoreVT)); 7855 return VData; 7856 } 7857 7858 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7859 SelectionDAG &DAG) const { 7860 SDLoc DL(Op); 7861 SDValue Chain = Op.getOperand(0); 7862 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7863 MachineFunction &MF = DAG.getMachineFunction(); 7864 7865 switch (IntrinsicID) { 7866 case Intrinsic::amdgcn_exp_compr: { 7867 SDValue Src0 = Op.getOperand(4); 7868 SDValue Src1 = Op.getOperand(5); 7869 // Hack around illegal type on SI by directly selecting it. 7870 if (isTypeLegal(Src0.getValueType())) 7871 return SDValue(); 7872 7873 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7874 SDValue Undef = DAG.getUNDEF(MVT::f32); 7875 const SDValue Ops[] = { 7876 Op.getOperand(2), // tgt 7877 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7878 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7879 Undef, // src2 7880 Undef, // src3 7881 Op.getOperand(7), // vm 7882 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7883 Op.getOperand(3), // en 7884 Op.getOperand(0) // Chain 7885 }; 7886 7887 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7888 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7889 } 7890 case Intrinsic::amdgcn_s_barrier: { 7891 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7892 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7893 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7894 if (WGSize <= ST.getWavefrontSize()) 7895 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7896 Op.getOperand(0)), 0); 7897 } 7898 return SDValue(); 7899 }; 7900 case Intrinsic::amdgcn_tbuffer_store: { 7901 SDValue VData = Op.getOperand(2); 7902 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7903 if (IsD16) 7904 VData = handleD16VData(VData, DAG); 7905 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7906 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7907 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7908 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7909 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7910 SDValue Ops[] = { 7911 Chain, 7912 VData, // vdata 7913 Op.getOperand(3), // rsrc 7914 Op.getOperand(4), // vindex 7915 Op.getOperand(5), // voffset 7916 Op.getOperand(6), // soffset 7917 Op.getOperand(7), // offset 7918 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7919 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7920 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7921 }; 7922 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7923 AMDGPUISD::TBUFFER_STORE_FORMAT; 7924 MemSDNode *M = cast<MemSDNode>(Op); 7925 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7926 M->getMemoryVT(), M->getMemOperand()); 7927 } 7928 7929 case Intrinsic::amdgcn_struct_tbuffer_store: { 7930 SDValue VData = Op.getOperand(2); 7931 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7932 if (IsD16) 7933 VData = handleD16VData(VData, DAG); 7934 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7935 SDValue Ops[] = { 7936 Chain, 7937 VData, // vdata 7938 Op.getOperand(3), // rsrc 7939 Op.getOperand(4), // vindex 7940 Offsets.first, // voffset 7941 Op.getOperand(6), // soffset 7942 Offsets.second, // offset 7943 Op.getOperand(7), // format 7944 Op.getOperand(8), // cachepolicy, swizzled buffer 7945 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7946 }; 7947 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7948 AMDGPUISD::TBUFFER_STORE_FORMAT; 7949 MemSDNode *M = cast<MemSDNode>(Op); 7950 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7951 M->getMemoryVT(), M->getMemOperand()); 7952 } 7953 7954 case Intrinsic::amdgcn_raw_tbuffer_store: { 7955 SDValue VData = Op.getOperand(2); 7956 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7957 if (IsD16) 7958 VData = handleD16VData(VData, DAG); 7959 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7960 SDValue Ops[] = { 7961 Chain, 7962 VData, // vdata 7963 Op.getOperand(3), // rsrc 7964 DAG.getConstant(0, DL, MVT::i32), // vindex 7965 Offsets.first, // voffset 7966 Op.getOperand(5), // soffset 7967 Offsets.second, // offset 7968 Op.getOperand(6), // format 7969 Op.getOperand(7), // cachepolicy, swizzled buffer 7970 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7971 }; 7972 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7973 AMDGPUISD::TBUFFER_STORE_FORMAT; 7974 MemSDNode *M = cast<MemSDNode>(Op); 7975 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7976 M->getMemoryVT(), M->getMemOperand()); 7977 } 7978 7979 case Intrinsic::amdgcn_buffer_store: 7980 case Intrinsic::amdgcn_buffer_store_format: { 7981 SDValue VData = Op.getOperand(2); 7982 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7983 if (IsD16) 7984 VData = handleD16VData(VData, DAG); 7985 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7986 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7987 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7988 SDValue Ops[] = { 7989 Chain, 7990 VData, 7991 Op.getOperand(3), // rsrc 7992 Op.getOperand(4), // vindex 7993 SDValue(), // voffset -- will be set by setBufferOffsets 7994 SDValue(), // soffset -- will be set by setBufferOffsets 7995 SDValue(), // offset -- will be set by setBufferOffsets 7996 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7997 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7998 }; 7999 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 8000 8001 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 8002 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8003 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8004 MemSDNode *M = cast<MemSDNode>(Op); 8005 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8006 8007 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8008 EVT VDataType = VData.getValueType().getScalarType(); 8009 if (VDataType == MVT::i8 || VDataType == MVT::i16) 8010 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8011 8012 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8013 M->getMemoryVT(), M->getMemOperand()); 8014 } 8015 8016 case Intrinsic::amdgcn_raw_buffer_store: 8017 case Intrinsic::amdgcn_raw_buffer_store_format: { 8018 const bool IsFormat = 8019 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 8020 8021 SDValue VData = Op.getOperand(2); 8022 EVT VDataVT = VData.getValueType(); 8023 EVT EltType = VDataVT.getScalarType(); 8024 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 8025 if (IsD16) { 8026 VData = handleD16VData(VData, DAG); 8027 VDataVT = VData.getValueType(); 8028 } 8029 8030 if (!isTypeLegal(VDataVT)) { 8031 VData = 8032 DAG.getNode(ISD::BITCAST, DL, 8033 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 8034 } 8035 8036 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 8037 SDValue Ops[] = { 8038 Chain, 8039 VData, 8040 Op.getOperand(3), // rsrc 8041 DAG.getConstant(0, DL, MVT::i32), // vindex 8042 Offsets.first, // voffset 8043 Op.getOperand(5), // soffset 8044 Offsets.second, // offset 8045 Op.getOperand(6), // cachepolicy, swizzled buffer 8046 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 8047 }; 8048 unsigned Opc = 8049 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 8050 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8051 MemSDNode *M = cast<MemSDNode>(Op); 8052 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 8053 8054 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8055 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8056 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 8057 8058 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8059 M->getMemoryVT(), M->getMemOperand()); 8060 } 8061 8062 case Intrinsic::amdgcn_struct_buffer_store: 8063 case Intrinsic::amdgcn_struct_buffer_store_format: { 8064 const bool IsFormat = 8065 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 8066 8067 SDValue VData = Op.getOperand(2); 8068 EVT VDataVT = VData.getValueType(); 8069 EVT EltType = VDataVT.getScalarType(); 8070 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 8071 8072 if (IsD16) { 8073 VData = handleD16VData(VData, DAG); 8074 VDataVT = VData.getValueType(); 8075 } 8076 8077 if (!isTypeLegal(VDataVT)) { 8078 VData = 8079 DAG.getNode(ISD::BITCAST, DL, 8080 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 8081 } 8082 8083 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 8084 SDValue Ops[] = { 8085 Chain, 8086 VData, 8087 Op.getOperand(3), // rsrc 8088 Op.getOperand(4), // vindex 8089 Offsets.first, // voffset 8090 Op.getOperand(6), // soffset 8091 Offsets.second, // offset 8092 Op.getOperand(7), // cachepolicy, swizzled buffer 8093 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 8094 }; 8095 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 8096 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8097 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8098 MemSDNode *M = cast<MemSDNode>(Op); 8099 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8100 8101 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8102 EVT VDataType = VData.getValueType().getScalarType(); 8103 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8104 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8105 8106 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8107 M->getMemoryVT(), M->getMemOperand()); 8108 } 8109 case Intrinsic::amdgcn_raw_buffer_load_lds: 8110 case Intrinsic::amdgcn_struct_buffer_load_lds: { 8111 unsigned Opc; 8112 bool HasVIndex = IntrinsicID == Intrinsic::amdgcn_struct_buffer_load_lds; 8113 unsigned OpOffset = HasVIndex ? 1 : 0; 8114 SDValue VOffset = Op.getOperand(5 + OpOffset); 8115 auto CVOffset = dyn_cast<ConstantSDNode>(VOffset); 8116 bool HasVOffset = !CVOffset || !CVOffset->isZero(); 8117 unsigned Size = Op->getConstantOperandVal(4); 8118 8119 switch (Size) { 8120 default: 8121 return SDValue(); 8122 case 1: 8123 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_BOTHEN 8124 : AMDGPU::BUFFER_LOAD_UBYTE_LDS_IDXEN 8125 : HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFEN 8126 : AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFSET; 8127 break; 8128 case 2: 8129 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_BOTHEN 8130 : AMDGPU::BUFFER_LOAD_USHORT_LDS_IDXEN 8131 : HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFEN 8132 : AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFSET; 8133 break; 8134 case 4: 8135 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_BOTHEN 8136 : AMDGPU::BUFFER_LOAD_DWORD_LDS_IDXEN 8137 : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFEN 8138 : AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFSET; 8139 break; 8140 } 8141 8142 SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 8143 8144 SmallVector<SDValue, 8> Ops; 8145 8146 if (HasVIndex && HasVOffset) 8147 Ops.push_back(DAG.getBuildVector(MVT::v2i32, DL, 8148 { Op.getOperand(5), // VIndex 8149 VOffset })); 8150 else if (HasVIndex) 8151 Ops.push_back(Op.getOperand(5)); 8152 else if (HasVOffset) 8153 Ops.push_back(VOffset); 8154 8155 Ops.push_back(Op.getOperand(2)); // rsrc 8156 Ops.push_back(Op.getOperand(6 + OpOffset)); // soffset 8157 Ops.push_back(Op.getOperand(7 + OpOffset)); // imm offset 8158 unsigned Aux = Op.getConstantOperandVal(8 + OpOffset); 8159 Ops.push_back( 8160 DAG.getTargetConstant(Aux & AMDGPU::CPol::ALL, DL, MVT::i8)); // cpol 8161 Ops.push_back( 8162 DAG.getTargetConstant((Aux >> 3) & 1, DL, MVT::i8)); // swz 8163 Ops.push_back(M0Val.getValue(0)); // Chain 8164 Ops.push_back(M0Val.getValue(1)); // Glue 8165 8166 auto *M = cast<MemSDNode>(Op); 8167 MachineMemOperand *LoadMMO = M->getMemOperand(); 8168 MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo(); 8169 LoadPtrI.Offset = Op->getConstantOperandVal(7 + OpOffset); 8170 MachinePointerInfo StorePtrI = LoadPtrI; 8171 StorePtrI.V = nullptr; 8172 StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS; 8173 8174 auto F = LoadMMO->getFlags() & 8175 ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad); 8176 LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad, 8177 Size, LoadMMO->getBaseAlign()); 8178 8179 MachineMemOperand *StoreMMO = 8180 MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore, 8181 sizeof(int32_t), LoadMMO->getBaseAlign()); 8182 8183 auto Load = DAG.getMachineNode(Opc, DL, M->getVTList(), Ops); 8184 DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO}); 8185 8186 return SDValue(Load, 0); 8187 } 8188 case Intrinsic::amdgcn_global_load_lds: { 8189 unsigned Opc; 8190 unsigned Size = Op->getConstantOperandVal(4); 8191 switch (Size) { 8192 default: 8193 return SDValue(); 8194 case 1: 8195 Opc = AMDGPU::GLOBAL_LOAD_LDS_UBYTE; 8196 break; 8197 case 2: 8198 Opc = AMDGPU::GLOBAL_LOAD_LDS_USHORT; 8199 break; 8200 case 4: 8201 Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORD; 8202 break; 8203 } 8204 8205 auto *M = cast<MemSDNode>(Op); 8206 SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 8207 8208 SmallVector<SDValue, 6> Ops; 8209 8210 SDValue Addr = Op.getOperand(2); // Global ptr 8211 SDValue VOffset; 8212 // Try to split SAddr and VOffset. Global and LDS pointers share the same 8213 // immediate offset, so we cannot use a regular SelectGlobalSAddr(). 8214 if (Addr->isDivergent() && Addr.getOpcode() == ISD::ADD) { 8215 SDValue LHS = Addr.getOperand(0); 8216 SDValue RHS = Addr.getOperand(1); 8217 8218 if (LHS->isDivergent()) 8219 std::swap(LHS, RHS); 8220 8221 if (!LHS->isDivergent() && RHS.getOpcode() == ISD::ZERO_EXTEND && 8222 RHS.getOperand(0).getValueType() == MVT::i32) { 8223 // add (i64 sgpr), (zero_extend (i32 vgpr)) 8224 Addr = LHS; 8225 VOffset = RHS.getOperand(0); 8226 } 8227 } 8228 8229 Ops.push_back(Addr); 8230 if (!Addr->isDivergent()) { 8231 Opc = AMDGPU::getGlobalSaddrOp(Opc); 8232 if (!VOffset) 8233 VOffset = SDValue( 8234 DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, DL, MVT::i32, 8235 DAG.getTargetConstant(0, DL, MVT::i32)), 0); 8236 Ops.push_back(VOffset); 8237 } 8238 8239 Ops.push_back(Op.getOperand(5)); // Offset 8240 Ops.push_back(Op.getOperand(6)); // CPol 8241 Ops.push_back(M0Val.getValue(0)); // Chain 8242 Ops.push_back(M0Val.getValue(1)); // Glue 8243 8244 MachineMemOperand *LoadMMO = M->getMemOperand(); 8245 MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo(); 8246 LoadPtrI.Offset = Op->getConstantOperandVal(5); 8247 MachinePointerInfo StorePtrI = LoadPtrI; 8248 LoadPtrI.AddrSpace = AMDGPUAS::GLOBAL_ADDRESS; 8249 StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS; 8250 auto F = LoadMMO->getFlags() & 8251 ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad); 8252 LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad, 8253 Size, LoadMMO->getBaseAlign()); 8254 MachineMemOperand *StoreMMO = 8255 MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore, 8256 sizeof(int32_t), Align(4)); 8257 8258 auto Load = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops); 8259 DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO}); 8260 8261 return SDValue(Load, 0); 8262 } 8263 case Intrinsic::amdgcn_end_cf: 8264 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 8265 Op->getOperand(2), Chain), 0); 8266 8267 default: { 8268 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 8269 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 8270 return lowerImage(Op, ImageDimIntr, DAG, true); 8271 8272 return Op; 8273 } 8274 } 8275 } 8276 8277 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 8278 // offset (the offset that is included in bounds checking and swizzling, to be 8279 // split between the instruction's voffset and immoffset fields) and soffset 8280 // (the offset that is excluded from bounds checking and swizzling, to go in 8281 // the instruction's soffset field). This function takes the first kind of 8282 // offset and figures out how to split it between voffset and immoffset. 8283 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 8284 SDValue Offset, SelectionDAG &DAG) const { 8285 SDLoc DL(Offset); 8286 const unsigned MaxImm = 4095; 8287 SDValue N0 = Offset; 8288 ConstantSDNode *C1 = nullptr; 8289 8290 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 8291 N0 = SDValue(); 8292 else if (DAG.isBaseWithConstantOffset(N0)) { 8293 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 8294 N0 = N0.getOperand(0); 8295 } 8296 8297 if (C1) { 8298 unsigned ImmOffset = C1->getZExtValue(); 8299 // If the immediate value is too big for the immoffset field, put the value 8300 // and -4096 into the immoffset field so that the value that is copied/added 8301 // for the voffset field is a multiple of 4096, and it stands more chance 8302 // of being CSEd with the copy/add for another similar load/store. 8303 // However, do not do that rounding down to a multiple of 4096 if that is a 8304 // negative number, as it appears to be illegal to have a negative offset 8305 // in the vgpr, even if adding the immediate offset makes it positive. 8306 unsigned Overflow = ImmOffset & ~MaxImm; 8307 ImmOffset -= Overflow; 8308 if ((int32_t)Overflow < 0) { 8309 Overflow += ImmOffset; 8310 ImmOffset = 0; 8311 } 8312 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 8313 if (Overflow) { 8314 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 8315 if (!N0) 8316 N0 = OverflowVal; 8317 else { 8318 SDValue Ops[] = { N0, OverflowVal }; 8319 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 8320 } 8321 } 8322 } 8323 if (!N0) 8324 N0 = DAG.getConstant(0, DL, MVT::i32); 8325 if (!C1) 8326 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 8327 return {N0, SDValue(C1, 0)}; 8328 } 8329 8330 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 8331 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 8332 // pointed to by Offsets. 8333 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 8334 SelectionDAG &DAG, SDValue *Offsets, 8335 Align Alignment) const { 8336 SDLoc DL(CombinedOffset); 8337 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 8338 uint32_t Imm = C->getZExtValue(); 8339 uint32_t SOffset, ImmOffset; 8340 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 8341 Alignment)) { 8342 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 8343 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8344 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8345 return; 8346 } 8347 } 8348 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 8349 SDValue N0 = CombinedOffset.getOperand(0); 8350 SDValue N1 = CombinedOffset.getOperand(1); 8351 uint32_t SOffset, ImmOffset; 8352 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 8353 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 8354 Subtarget, Alignment)) { 8355 Offsets[0] = N0; 8356 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8357 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8358 return; 8359 } 8360 } 8361 Offsets[0] = CombinedOffset; 8362 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 8363 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 8364 } 8365 8366 // Handle 8 bit and 16 bit buffer loads 8367 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 8368 EVT LoadVT, SDLoc DL, 8369 ArrayRef<SDValue> Ops, 8370 MemSDNode *M) const { 8371 EVT IntVT = LoadVT.changeTypeToInteger(); 8372 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 8373 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 8374 8375 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 8376 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 8377 Ops, IntVT, 8378 M->getMemOperand()); 8379 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 8380 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 8381 8382 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 8383 } 8384 8385 // Handle 8 bit and 16 bit buffer stores 8386 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 8387 EVT VDataType, SDLoc DL, 8388 SDValue Ops[], 8389 MemSDNode *M) const { 8390 if (VDataType == MVT::f16) 8391 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 8392 8393 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 8394 Ops[1] = BufferStoreExt; 8395 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 8396 AMDGPUISD::BUFFER_STORE_SHORT; 8397 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 8398 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 8399 M->getMemOperand()); 8400 } 8401 8402 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 8403 ISD::LoadExtType ExtType, SDValue Op, 8404 const SDLoc &SL, EVT VT) { 8405 if (VT.bitsLT(Op.getValueType())) 8406 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 8407 8408 switch (ExtType) { 8409 case ISD::SEXTLOAD: 8410 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 8411 case ISD::ZEXTLOAD: 8412 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 8413 case ISD::EXTLOAD: 8414 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 8415 case ISD::NON_EXTLOAD: 8416 return Op; 8417 } 8418 8419 llvm_unreachable("invalid ext type"); 8420 } 8421 8422 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 8423 SelectionDAG &DAG = DCI.DAG; 8424 if (Ld->getAlign() < Align(4) || Ld->isDivergent()) 8425 return SDValue(); 8426 8427 // FIXME: Constant loads should all be marked invariant. 8428 unsigned AS = Ld->getAddressSpace(); 8429 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 8430 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 8431 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 8432 return SDValue(); 8433 8434 // Don't do this early, since it may interfere with adjacent load merging for 8435 // illegal types. We can avoid losing alignment information for exotic types 8436 // pre-legalize. 8437 EVT MemVT = Ld->getMemoryVT(); 8438 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 8439 MemVT.getSizeInBits() >= 32) 8440 return SDValue(); 8441 8442 SDLoc SL(Ld); 8443 8444 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 8445 "unexpected vector extload"); 8446 8447 // TODO: Drop only high part of range. 8448 SDValue Ptr = Ld->getBasePtr(); 8449 SDValue NewLoad = DAG.getLoad( 8450 ISD::UNINDEXED, ISD::NON_EXTLOAD, MVT::i32, SL, Ld->getChain(), Ptr, 8451 Ld->getOffset(), Ld->getPointerInfo(), MVT::i32, Ld->getAlign(), 8452 Ld->getMemOperand()->getFlags(), Ld->getAAInfo(), 8453 nullptr); // Drop ranges 8454 8455 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 8456 if (MemVT.isFloatingPoint()) { 8457 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 8458 "unexpected fp extload"); 8459 TruncVT = MemVT.changeTypeToInteger(); 8460 } 8461 8462 SDValue Cvt = NewLoad; 8463 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 8464 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 8465 DAG.getValueType(TruncVT)); 8466 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 8467 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 8468 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 8469 } else { 8470 assert(Ld->getExtensionType() == ISD::EXTLOAD); 8471 } 8472 8473 EVT VT = Ld->getValueType(0); 8474 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8475 8476 DCI.AddToWorklist(Cvt.getNode()); 8477 8478 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8479 // the appropriate extension from the 32-bit load. 8480 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8481 DCI.AddToWorklist(Cvt.getNode()); 8482 8483 // Handle conversion back to floating point if necessary. 8484 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8485 8486 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8487 } 8488 8489 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8490 SDLoc DL(Op); 8491 LoadSDNode *Load = cast<LoadSDNode>(Op); 8492 ISD::LoadExtType ExtType = Load->getExtensionType(); 8493 EVT MemVT = Load->getMemoryVT(); 8494 8495 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8496 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8497 return SDValue(); 8498 8499 // FIXME: Copied from PPC 8500 // First, load into 32 bits, then truncate to 1 bit. 8501 8502 SDValue Chain = Load->getChain(); 8503 SDValue BasePtr = Load->getBasePtr(); 8504 MachineMemOperand *MMO = Load->getMemOperand(); 8505 8506 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8507 8508 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8509 BasePtr, RealMemVT, MMO); 8510 8511 if (!MemVT.isVector()) { 8512 SDValue Ops[] = { 8513 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8514 NewLD.getValue(1) 8515 }; 8516 8517 return DAG.getMergeValues(Ops, DL); 8518 } 8519 8520 SmallVector<SDValue, 3> Elts; 8521 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8522 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8523 DAG.getConstant(I, DL, MVT::i32)); 8524 8525 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8526 } 8527 8528 SDValue Ops[] = { 8529 DAG.getBuildVector(MemVT, DL, Elts), 8530 NewLD.getValue(1) 8531 }; 8532 8533 return DAG.getMergeValues(Ops, DL); 8534 } 8535 8536 if (!MemVT.isVector()) 8537 return SDValue(); 8538 8539 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8540 "Custom lowering for non-i32 vectors hasn't been implemented."); 8541 8542 Align Alignment = Load->getAlign(); 8543 unsigned AS = Load->getAddressSpace(); 8544 if (Subtarget->hasLDSMisalignedBug() && AS == AMDGPUAS::FLAT_ADDRESS && 8545 Alignment.value() < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8546 return SplitVectorLoad(Op, DAG); 8547 } 8548 8549 MachineFunction &MF = DAG.getMachineFunction(); 8550 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8551 // If there is a possibility that flat instruction access scratch memory 8552 // then we need to use the same legalization rules we use for private. 8553 if (AS == AMDGPUAS::FLAT_ADDRESS && 8554 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8555 AS = MFI->hasFlatScratchInit() ? 8556 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8557 8558 unsigned NumElements = MemVT.getVectorNumElements(); 8559 8560 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8561 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8562 if (!Op->isDivergent() && Alignment >= Align(4) && NumElements < 32) { 8563 if (MemVT.isPow2VectorType()) 8564 return SDValue(); 8565 return WidenOrSplitVectorLoad(Op, DAG); 8566 } 8567 // Non-uniform loads will be selected to MUBUF instructions, so they 8568 // have the same legalization requirements as global and private 8569 // loads. 8570 // 8571 } 8572 8573 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8574 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8575 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8576 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8577 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8578 Alignment >= Align(4) && NumElements < 32) { 8579 if (MemVT.isPow2VectorType()) 8580 return SDValue(); 8581 return WidenOrSplitVectorLoad(Op, DAG); 8582 } 8583 // Non-uniform loads will be selected to MUBUF instructions, so they 8584 // have the same legalization requirements as global and private 8585 // loads. 8586 // 8587 } 8588 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8589 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8590 AS == AMDGPUAS::GLOBAL_ADDRESS || 8591 AS == AMDGPUAS::FLAT_ADDRESS) { 8592 if (NumElements > 4) 8593 return SplitVectorLoad(Op, DAG); 8594 // v3 loads not supported on SI. 8595 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8596 return WidenOrSplitVectorLoad(Op, DAG); 8597 8598 // v3 and v4 loads are supported for private and global memory. 8599 return SDValue(); 8600 } 8601 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8602 // Depending on the setting of the private_element_size field in the 8603 // resource descriptor, we can only make private accesses up to a certain 8604 // size. 8605 switch (Subtarget->getMaxPrivateElementSize()) { 8606 case 4: { 8607 SDValue Ops[2]; 8608 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8609 return DAG.getMergeValues(Ops, DL); 8610 } 8611 case 8: 8612 if (NumElements > 2) 8613 return SplitVectorLoad(Op, DAG); 8614 return SDValue(); 8615 case 16: 8616 // Same as global/flat 8617 if (NumElements > 4) 8618 return SplitVectorLoad(Op, DAG); 8619 // v3 loads not supported on SI. 8620 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8621 return WidenOrSplitVectorLoad(Op, DAG); 8622 8623 return SDValue(); 8624 default: 8625 llvm_unreachable("unsupported private_element_size"); 8626 } 8627 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8628 bool Fast = false; 8629 auto Flags = Load->getMemOperand()->getFlags(); 8630 if (allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8631 Load->getAlign(), Flags, &Fast) && 8632 Fast) 8633 return SDValue(); 8634 8635 if (MemVT.isVector()) 8636 return SplitVectorLoad(Op, DAG); 8637 } 8638 8639 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8640 MemVT, *Load->getMemOperand())) { 8641 SDValue Ops[2]; 8642 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8643 return DAG.getMergeValues(Ops, DL); 8644 } 8645 8646 return SDValue(); 8647 } 8648 8649 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8650 EVT VT = Op.getValueType(); 8651 if (VT.getSizeInBits() == 128) 8652 return splitTernaryVectorOp(Op, DAG); 8653 8654 assert(VT.getSizeInBits() == 64); 8655 8656 SDLoc DL(Op); 8657 SDValue Cond = Op.getOperand(0); 8658 8659 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8660 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8661 8662 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8663 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8664 8665 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8666 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8667 8668 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8669 8670 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8671 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8672 8673 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8674 8675 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8676 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8677 } 8678 8679 // Catch division cases where we can use shortcuts with rcp and rsq 8680 // instructions. 8681 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8682 SelectionDAG &DAG) const { 8683 SDLoc SL(Op); 8684 SDValue LHS = Op.getOperand(0); 8685 SDValue RHS = Op.getOperand(1); 8686 EVT VT = Op.getValueType(); 8687 const SDNodeFlags Flags = Op->getFlags(); 8688 8689 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8690 8691 // Without !fpmath accuracy information, we can't do more because we don't 8692 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8693 if (!AllowInaccurateRcp) 8694 return SDValue(); 8695 8696 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8697 if (CLHS->isExactlyValue(1.0)) { 8698 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8699 // the CI documentation has a worst case error of 1 ulp. 8700 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8701 // use it as long as we aren't trying to use denormals. 8702 // 8703 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8704 8705 // 1.0 / sqrt(x) -> rsq(x) 8706 8707 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8708 // error seems really high at 2^29 ULP. 8709 if (RHS.getOpcode() == ISD::FSQRT) 8710 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8711 8712 // 1.0 / x -> rcp(x) 8713 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8714 } 8715 8716 // Same as for 1.0, but expand the sign out of the constant. 8717 if (CLHS->isExactlyValue(-1.0)) { 8718 // -1.0 / x -> rcp (fneg x) 8719 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8720 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8721 } 8722 } 8723 8724 // Turn into multiply by the reciprocal. 8725 // x / y -> x * (1.0 / y) 8726 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8727 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8728 } 8729 8730 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8731 SelectionDAG &DAG) const { 8732 SDLoc SL(Op); 8733 SDValue X = Op.getOperand(0); 8734 SDValue Y = Op.getOperand(1); 8735 EVT VT = Op.getValueType(); 8736 const SDNodeFlags Flags = Op->getFlags(); 8737 8738 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8739 DAG.getTarget().Options.UnsafeFPMath; 8740 if (!AllowInaccurateDiv) 8741 return SDValue(); 8742 8743 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8744 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8745 8746 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8747 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8748 8749 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8750 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8751 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8752 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8753 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8754 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8755 } 8756 8757 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8758 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8759 SDNodeFlags Flags) { 8760 if (GlueChain->getNumValues() <= 1) { 8761 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8762 } 8763 8764 assert(GlueChain->getNumValues() == 3); 8765 8766 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8767 switch (Opcode) { 8768 default: llvm_unreachable("no chain equivalent for opcode"); 8769 case ISD::FMUL: 8770 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8771 break; 8772 } 8773 8774 return DAG.getNode(Opcode, SL, VTList, 8775 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8776 Flags); 8777 } 8778 8779 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8780 EVT VT, SDValue A, SDValue B, SDValue C, 8781 SDValue GlueChain, SDNodeFlags Flags) { 8782 if (GlueChain->getNumValues() <= 1) { 8783 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8784 } 8785 8786 assert(GlueChain->getNumValues() == 3); 8787 8788 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8789 switch (Opcode) { 8790 default: llvm_unreachable("no chain equivalent for opcode"); 8791 case ISD::FMA: 8792 Opcode = AMDGPUISD::FMA_W_CHAIN; 8793 break; 8794 } 8795 8796 return DAG.getNode(Opcode, SL, VTList, 8797 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8798 Flags); 8799 } 8800 8801 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8802 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8803 return FastLowered; 8804 8805 SDLoc SL(Op); 8806 SDValue Src0 = Op.getOperand(0); 8807 SDValue Src1 = Op.getOperand(1); 8808 8809 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8810 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8811 8812 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8813 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8814 8815 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8816 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8817 8818 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8819 } 8820 8821 // Faster 2.5 ULP division that does not support denormals. 8822 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8823 SDLoc SL(Op); 8824 SDValue LHS = Op.getOperand(1); 8825 SDValue RHS = Op.getOperand(2); 8826 8827 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8828 8829 const APFloat K0Val(BitsToFloat(0x6f800000)); 8830 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8831 8832 const APFloat K1Val(BitsToFloat(0x2f800000)); 8833 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8834 8835 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8836 8837 EVT SetCCVT = 8838 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8839 8840 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8841 8842 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8843 8844 // TODO: Should this propagate fast-math-flags? 8845 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8846 8847 // rcp does not support denormals. 8848 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8849 8850 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8851 8852 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8853 } 8854 8855 // Returns immediate value for setting the F32 denorm mode when using the 8856 // S_DENORM_MODE instruction. 8857 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8858 const SDLoc &SL, const GCNSubtarget *ST) { 8859 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8860 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8861 ? FP_DENORM_FLUSH_NONE 8862 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8863 8864 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8865 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8866 } 8867 8868 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8869 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8870 return FastLowered; 8871 8872 // The selection matcher assumes anything with a chain selecting to a 8873 // mayRaiseFPException machine instruction. Since we're introducing a chain 8874 // here, we need to explicitly report nofpexcept for the regular fdiv 8875 // lowering. 8876 SDNodeFlags Flags = Op->getFlags(); 8877 Flags.setNoFPExcept(true); 8878 8879 SDLoc SL(Op); 8880 SDValue LHS = Op.getOperand(0); 8881 SDValue RHS = Op.getOperand(1); 8882 8883 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8884 8885 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8886 8887 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8888 {RHS, RHS, LHS}, Flags); 8889 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8890 {LHS, RHS, LHS}, Flags); 8891 8892 // Denominator is scaled to not be denormal, so using rcp is ok. 8893 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8894 DenominatorScaled, Flags); 8895 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8896 DenominatorScaled, Flags); 8897 8898 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8899 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8900 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8901 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8902 8903 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8904 8905 if (!HasFP32Denormals) { 8906 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8907 // lowering. The chain dependence is insufficient, and we need glue. We do 8908 // not need the glue variants in a strictfp function. 8909 8910 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8911 8912 SDNode *EnableDenorm; 8913 if (Subtarget->hasDenormModeInst()) { 8914 const SDValue EnableDenormValue = 8915 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8916 8917 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8918 DAG.getEntryNode(), EnableDenormValue).getNode(); 8919 } else { 8920 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8921 SL, MVT::i32); 8922 EnableDenorm = 8923 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8924 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8925 } 8926 8927 SDValue Ops[3] = { 8928 NegDivScale0, 8929 SDValue(EnableDenorm, 0), 8930 SDValue(EnableDenorm, 1) 8931 }; 8932 8933 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8934 } 8935 8936 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8937 ApproxRcp, One, NegDivScale0, Flags); 8938 8939 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8940 ApproxRcp, Fma0, Flags); 8941 8942 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8943 Fma1, Fma1, Flags); 8944 8945 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8946 NumeratorScaled, Mul, Flags); 8947 8948 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8949 Fma2, Fma1, Mul, Fma2, Flags); 8950 8951 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8952 NumeratorScaled, Fma3, Flags); 8953 8954 if (!HasFP32Denormals) { 8955 SDNode *DisableDenorm; 8956 if (Subtarget->hasDenormModeInst()) { 8957 const SDValue DisableDenormValue = 8958 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8959 8960 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8961 Fma4.getValue(1), DisableDenormValue, 8962 Fma4.getValue(2)).getNode(); 8963 } else { 8964 const SDValue DisableDenormValue = 8965 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8966 8967 DisableDenorm = DAG.getMachineNode( 8968 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8969 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8970 } 8971 8972 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8973 SDValue(DisableDenorm, 0), DAG.getRoot()); 8974 DAG.setRoot(OutputChain); 8975 } 8976 8977 SDValue Scale = NumeratorScaled.getValue(1); 8978 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8979 {Fma4, Fma1, Fma3, Scale}, Flags); 8980 8981 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8982 } 8983 8984 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8985 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8986 return FastLowered; 8987 8988 SDLoc SL(Op); 8989 SDValue X = Op.getOperand(0); 8990 SDValue Y = Op.getOperand(1); 8991 8992 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8993 8994 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8995 8996 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8997 8998 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8999 9000 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 9001 9002 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 9003 9004 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 9005 9006 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 9007 9008 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 9009 9010 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 9011 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 9012 9013 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 9014 NegDivScale0, Mul, DivScale1); 9015 9016 SDValue Scale; 9017 9018 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 9019 // Workaround a hardware bug on SI where the condition output from div_scale 9020 // is not usable. 9021 9022 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 9023 9024 // Figure out if the scale to use for div_fmas. 9025 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 9026 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 9027 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 9028 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 9029 9030 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 9031 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 9032 9033 SDValue Scale0Hi 9034 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 9035 SDValue Scale1Hi 9036 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 9037 9038 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 9039 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 9040 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 9041 } else { 9042 Scale = DivScale1.getValue(1); 9043 } 9044 9045 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 9046 Fma4, Fma3, Mul, Scale); 9047 9048 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 9049 } 9050 9051 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 9052 EVT VT = Op.getValueType(); 9053 9054 if (VT == MVT::f32) 9055 return LowerFDIV32(Op, DAG); 9056 9057 if (VT == MVT::f64) 9058 return LowerFDIV64(Op, DAG); 9059 9060 if (VT == MVT::f16) 9061 return LowerFDIV16(Op, DAG); 9062 9063 llvm_unreachable("Unexpected type for fdiv"); 9064 } 9065 9066 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 9067 SDLoc DL(Op); 9068 StoreSDNode *Store = cast<StoreSDNode>(Op); 9069 EVT VT = Store->getMemoryVT(); 9070 9071 if (VT == MVT::i1) { 9072 return DAG.getTruncStore(Store->getChain(), DL, 9073 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 9074 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 9075 } 9076 9077 assert(VT.isVector() && 9078 Store->getValue().getValueType().getScalarType() == MVT::i32); 9079 9080 unsigned AS = Store->getAddressSpace(); 9081 if (Subtarget->hasLDSMisalignedBug() && 9082 AS == AMDGPUAS::FLAT_ADDRESS && 9083 Store->getAlign().value() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 9084 return SplitVectorStore(Op, DAG); 9085 } 9086 9087 MachineFunction &MF = DAG.getMachineFunction(); 9088 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 9089 // If there is a possibility that flat instruction access scratch memory 9090 // then we need to use the same legalization rules we use for private. 9091 if (AS == AMDGPUAS::FLAT_ADDRESS && 9092 !Subtarget->hasMultiDwordFlatScratchAddressing()) 9093 AS = MFI->hasFlatScratchInit() ? 9094 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 9095 9096 unsigned NumElements = VT.getVectorNumElements(); 9097 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 9098 AS == AMDGPUAS::FLAT_ADDRESS) { 9099 if (NumElements > 4) 9100 return SplitVectorStore(Op, DAG); 9101 // v3 stores not supported on SI. 9102 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 9103 return SplitVectorStore(Op, DAG); 9104 9105 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 9106 VT, *Store->getMemOperand())) 9107 return expandUnalignedStore(Store, DAG); 9108 9109 return SDValue(); 9110 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 9111 switch (Subtarget->getMaxPrivateElementSize()) { 9112 case 4: 9113 return scalarizeVectorStore(Store, DAG); 9114 case 8: 9115 if (NumElements > 2) 9116 return SplitVectorStore(Op, DAG); 9117 return SDValue(); 9118 case 16: 9119 if (NumElements > 4 || 9120 (NumElements == 3 && !Subtarget->enableFlatScratch())) 9121 return SplitVectorStore(Op, DAG); 9122 return SDValue(); 9123 default: 9124 llvm_unreachable("unsupported private_element_size"); 9125 } 9126 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 9127 bool Fast = false; 9128 auto Flags = Store->getMemOperand()->getFlags(); 9129 if (allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 9130 Store->getAlign(), Flags, &Fast) && 9131 Fast) 9132 return SDValue(); 9133 9134 if (VT.isVector()) 9135 return SplitVectorStore(Op, DAG); 9136 9137 return expandUnalignedStore(Store, DAG); 9138 } 9139 9140 // Probably an invalid store. If so we'll end up emitting a selection error. 9141 return SDValue(); 9142 } 9143 9144 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 9145 SDLoc DL(Op); 9146 EVT VT = Op.getValueType(); 9147 SDValue Arg = Op.getOperand(0); 9148 SDValue TrigVal; 9149 9150 // Propagate fast-math flags so that the multiply we introduce can be folded 9151 // if Arg is already the result of a multiply by constant. 9152 auto Flags = Op->getFlags(); 9153 9154 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 9155 9156 if (Subtarget->hasTrigReducedRange()) { 9157 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9158 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 9159 } else { 9160 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9161 } 9162 9163 switch (Op.getOpcode()) { 9164 case ISD::FCOS: 9165 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 9166 case ISD::FSIN: 9167 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 9168 default: 9169 llvm_unreachable("Wrong trig opcode"); 9170 } 9171 } 9172 9173 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 9174 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 9175 assert(AtomicNode->isCompareAndSwap()); 9176 unsigned AS = AtomicNode->getAddressSpace(); 9177 9178 // No custom lowering required for local address space 9179 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 9180 return Op; 9181 9182 // Non-local address space requires custom lowering for atomic compare 9183 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 9184 SDLoc DL(Op); 9185 SDValue ChainIn = Op.getOperand(0); 9186 SDValue Addr = Op.getOperand(1); 9187 SDValue Old = Op.getOperand(2); 9188 SDValue New = Op.getOperand(3); 9189 EVT VT = Op.getValueType(); 9190 MVT SimpleVT = VT.getSimpleVT(); 9191 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 9192 9193 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 9194 SDValue Ops[] = { ChainIn, Addr, NewOld }; 9195 9196 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 9197 Ops, VT, AtomicNode->getMemOperand()); 9198 } 9199 9200 //===----------------------------------------------------------------------===// 9201 // Custom DAG optimizations 9202 //===----------------------------------------------------------------------===// 9203 9204 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 9205 DAGCombinerInfo &DCI) const { 9206 EVT VT = N->getValueType(0); 9207 EVT ScalarVT = VT.getScalarType(); 9208 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 9209 return SDValue(); 9210 9211 SelectionDAG &DAG = DCI.DAG; 9212 SDLoc DL(N); 9213 9214 SDValue Src = N->getOperand(0); 9215 EVT SrcVT = Src.getValueType(); 9216 9217 // TODO: We could try to match extracting the higher bytes, which would be 9218 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 9219 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 9220 // about in practice. 9221 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 9222 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 9223 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 9224 DCI.AddToWorklist(Cvt.getNode()); 9225 9226 // For the f16 case, fold to a cast to f32 and then cast back to f16. 9227 if (ScalarVT != MVT::f32) { 9228 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 9229 DAG.getTargetConstant(0, DL, MVT::i32)); 9230 } 9231 return Cvt; 9232 } 9233 } 9234 9235 return SDValue(); 9236 } 9237 9238 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 9239 9240 // This is a variant of 9241 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 9242 // 9243 // The normal DAG combiner will do this, but only if the add has one use since 9244 // that would increase the number of instructions. 9245 // 9246 // This prevents us from seeing a constant offset that can be folded into a 9247 // memory instruction's addressing mode. If we know the resulting add offset of 9248 // a pointer can be folded into an addressing offset, we can replace the pointer 9249 // operand with the add of new constant offset. This eliminates one of the uses, 9250 // and may allow the remaining use to also be simplified. 9251 // 9252 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 9253 unsigned AddrSpace, 9254 EVT MemVT, 9255 DAGCombinerInfo &DCI) const { 9256 SDValue N0 = N->getOperand(0); 9257 SDValue N1 = N->getOperand(1); 9258 9259 // We only do this to handle cases where it's profitable when there are 9260 // multiple uses of the add, so defer to the standard combine. 9261 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 9262 N0->hasOneUse()) 9263 return SDValue(); 9264 9265 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 9266 if (!CN1) 9267 return SDValue(); 9268 9269 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 9270 if (!CAdd) 9271 return SDValue(); 9272 9273 // If the resulting offset is too large, we can't fold it into the addressing 9274 // mode offset. 9275 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 9276 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 9277 9278 AddrMode AM; 9279 AM.HasBaseReg = true; 9280 AM.BaseOffs = Offset.getSExtValue(); 9281 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 9282 return SDValue(); 9283 9284 SelectionDAG &DAG = DCI.DAG; 9285 SDLoc SL(N); 9286 EVT VT = N->getValueType(0); 9287 9288 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 9289 SDValue COffset = DAG.getConstant(Offset, SL, VT); 9290 9291 SDNodeFlags Flags; 9292 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 9293 (N0.getOpcode() == ISD::OR || 9294 N0->getFlags().hasNoUnsignedWrap())); 9295 9296 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 9297 } 9298 9299 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 9300 /// by the chain and intrinsic ID. Theoretically we would also need to check the 9301 /// specific intrinsic, but they all place the pointer operand first. 9302 static unsigned getBasePtrIndex(const MemSDNode *N) { 9303 switch (N->getOpcode()) { 9304 case ISD::STORE: 9305 case ISD::INTRINSIC_W_CHAIN: 9306 case ISD::INTRINSIC_VOID: 9307 return 2; 9308 default: 9309 return 1; 9310 } 9311 } 9312 9313 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 9314 DAGCombinerInfo &DCI) const { 9315 SelectionDAG &DAG = DCI.DAG; 9316 SDLoc SL(N); 9317 9318 unsigned PtrIdx = getBasePtrIndex(N); 9319 SDValue Ptr = N->getOperand(PtrIdx); 9320 9321 // TODO: We could also do this for multiplies. 9322 if (Ptr.getOpcode() == ISD::SHL) { 9323 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 9324 N->getMemoryVT(), DCI); 9325 if (NewPtr) { 9326 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 9327 9328 NewOps[PtrIdx] = NewPtr; 9329 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 9330 } 9331 } 9332 9333 return SDValue(); 9334 } 9335 9336 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 9337 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 9338 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 9339 (Opc == ISD::XOR && Val == 0); 9340 } 9341 9342 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 9343 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 9344 // integer combine opportunities since most 64-bit operations are decomposed 9345 // this way. TODO: We won't want this for SALU especially if it is an inline 9346 // immediate. 9347 SDValue SITargetLowering::splitBinaryBitConstantOp( 9348 DAGCombinerInfo &DCI, 9349 const SDLoc &SL, 9350 unsigned Opc, SDValue LHS, 9351 const ConstantSDNode *CRHS) const { 9352 uint64_t Val = CRHS->getZExtValue(); 9353 uint32_t ValLo = Lo_32(Val); 9354 uint32_t ValHi = Hi_32(Val); 9355 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9356 9357 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 9358 bitOpWithConstantIsReducible(Opc, ValHi)) || 9359 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 9360 // If we need to materialize a 64-bit immediate, it will be split up later 9361 // anyway. Avoid creating the harder to understand 64-bit immediate 9362 // materialization. 9363 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 9364 } 9365 9366 return SDValue(); 9367 } 9368 9369 // Returns true if argument is a boolean value which is not serialized into 9370 // memory or argument and does not require v_cndmask_b32 to be deserialized. 9371 static bool isBoolSGPR(SDValue V) { 9372 if (V.getValueType() != MVT::i1) 9373 return false; 9374 switch (V.getOpcode()) { 9375 default: 9376 break; 9377 case ISD::SETCC: 9378 case AMDGPUISD::FP_CLASS: 9379 return true; 9380 case ISD::AND: 9381 case ISD::OR: 9382 case ISD::XOR: 9383 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 9384 } 9385 return false; 9386 } 9387 9388 // If a constant has all zeroes or all ones within each byte return it. 9389 // Otherwise return 0. 9390 static uint32_t getConstantPermuteMask(uint32_t C) { 9391 // 0xff for any zero byte in the mask 9392 uint32_t ZeroByteMask = 0; 9393 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 9394 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 9395 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 9396 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 9397 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 9398 if ((NonZeroByteMask & C) != NonZeroByteMask) 9399 return 0; // Partial bytes selected. 9400 return C; 9401 } 9402 9403 // Check if a node selects whole bytes from its operand 0 starting at a byte 9404 // boundary while masking the rest. Returns select mask as in the v_perm_b32 9405 // or -1 if not succeeded. 9406 // Note byte select encoding: 9407 // value 0-3 selects corresponding source byte; 9408 // value 0xc selects zero; 9409 // value 0xff selects 0xff. 9410 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 9411 assert(V.getValueSizeInBits() == 32); 9412 9413 if (V.getNumOperands() != 2) 9414 return ~0; 9415 9416 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 9417 if (!N1) 9418 return ~0; 9419 9420 uint32_t C = N1->getZExtValue(); 9421 9422 switch (V.getOpcode()) { 9423 default: 9424 break; 9425 case ISD::AND: 9426 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9427 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 9428 } 9429 break; 9430 9431 case ISD::OR: 9432 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9433 return (0x03020100 & ~ConstMask) | ConstMask; 9434 } 9435 break; 9436 9437 case ISD::SHL: 9438 if (C % 8) 9439 return ~0; 9440 9441 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 9442 9443 case ISD::SRL: 9444 if (C % 8) 9445 return ~0; 9446 9447 return uint32_t(0x0c0c0c0c03020100ull >> C); 9448 } 9449 9450 return ~0; 9451 } 9452 9453 SDValue SITargetLowering::performAndCombine(SDNode *N, 9454 DAGCombinerInfo &DCI) const { 9455 if (DCI.isBeforeLegalize()) 9456 return SDValue(); 9457 9458 SelectionDAG &DAG = DCI.DAG; 9459 EVT VT = N->getValueType(0); 9460 SDValue LHS = N->getOperand(0); 9461 SDValue RHS = N->getOperand(1); 9462 9463 9464 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9465 if (VT == MVT::i64 && CRHS) { 9466 if (SDValue Split 9467 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9468 return Split; 9469 } 9470 9471 if (CRHS && VT == MVT::i32) { 9472 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9473 // nb = number of trailing zeroes in mask 9474 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9475 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9476 uint64_t Mask = CRHS->getZExtValue(); 9477 unsigned Bits = countPopulation(Mask); 9478 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9479 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9480 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9481 unsigned Shift = CShift->getZExtValue(); 9482 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9483 unsigned Offset = NB + Shift; 9484 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9485 SDLoc SL(N); 9486 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9487 LHS->getOperand(0), 9488 DAG.getConstant(Offset, SL, MVT::i32), 9489 DAG.getConstant(Bits, SL, MVT::i32)); 9490 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9491 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9492 DAG.getValueType(NarrowVT)); 9493 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9494 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9495 return Shl; 9496 } 9497 } 9498 } 9499 9500 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9501 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9502 isa<ConstantSDNode>(LHS.getOperand(2))) { 9503 uint32_t Sel = getConstantPermuteMask(Mask); 9504 if (!Sel) 9505 return SDValue(); 9506 9507 // Select 0xc for all zero bytes 9508 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9509 SDLoc DL(N); 9510 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9511 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9512 } 9513 } 9514 9515 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9516 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9517 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9518 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9519 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9520 9521 SDValue X = LHS.getOperand(0); 9522 SDValue Y = RHS.getOperand(0); 9523 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9524 return SDValue(); 9525 9526 if (LCC == ISD::SETO) { 9527 if (X != LHS.getOperand(1)) 9528 return SDValue(); 9529 9530 if (RCC == ISD::SETUNE) { 9531 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9532 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9533 return SDValue(); 9534 9535 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9536 SIInstrFlags::N_SUBNORMAL | 9537 SIInstrFlags::N_ZERO | 9538 SIInstrFlags::P_ZERO | 9539 SIInstrFlags::P_SUBNORMAL | 9540 SIInstrFlags::P_NORMAL; 9541 9542 static_assert(((~(SIInstrFlags::S_NAN | 9543 SIInstrFlags::Q_NAN | 9544 SIInstrFlags::N_INFINITY | 9545 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9546 "mask not equal"); 9547 9548 SDLoc DL(N); 9549 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9550 X, DAG.getConstant(Mask, DL, MVT::i32)); 9551 } 9552 } 9553 } 9554 9555 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9556 std::swap(LHS, RHS); 9557 9558 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9559 RHS.hasOneUse()) { 9560 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9561 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9562 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9563 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9564 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9565 (RHS.getOperand(0) == LHS.getOperand(0) && 9566 LHS.getOperand(0) == LHS.getOperand(1))) { 9567 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9568 unsigned NewMask = LCC == ISD::SETO ? 9569 Mask->getZExtValue() & ~OrdMask : 9570 Mask->getZExtValue() & OrdMask; 9571 9572 SDLoc DL(N); 9573 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9574 DAG.getConstant(NewMask, DL, MVT::i32)); 9575 } 9576 } 9577 9578 if (VT == MVT::i32 && 9579 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9580 // and x, (sext cc from i1) => select cc, x, 0 9581 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9582 std::swap(LHS, RHS); 9583 if (isBoolSGPR(RHS.getOperand(0))) 9584 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9585 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9586 } 9587 9588 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9589 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9590 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9591 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9592 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9593 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9594 if (LHSMask != ~0u && RHSMask != ~0u) { 9595 // Canonicalize the expression in an attempt to have fewer unique masks 9596 // and therefore fewer registers used to hold the masks. 9597 if (LHSMask > RHSMask) { 9598 std::swap(LHSMask, RHSMask); 9599 std::swap(LHS, RHS); 9600 } 9601 9602 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9603 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9604 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9605 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9606 9607 // Check of we need to combine values from two sources within a byte. 9608 if (!(LHSUsedLanes & RHSUsedLanes) && 9609 // If we select high and lower word keep it for SDWA. 9610 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9611 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9612 // Each byte in each mask is either selector mask 0-3, or has higher 9613 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9614 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9615 // mask which is not 0xff wins. By anding both masks we have a correct 9616 // result except that 0x0c shall be corrected to give 0x0c only. 9617 uint32_t Mask = LHSMask & RHSMask; 9618 for (unsigned I = 0; I < 32; I += 8) { 9619 uint32_t ByteSel = 0xff << I; 9620 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9621 Mask &= (0x0c << I) & 0xffffffff; 9622 } 9623 9624 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9625 // or 0x0c. 9626 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9627 SDLoc DL(N); 9628 9629 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9630 LHS.getOperand(0), RHS.getOperand(0), 9631 DAG.getConstant(Sel, DL, MVT::i32)); 9632 } 9633 } 9634 } 9635 9636 return SDValue(); 9637 } 9638 9639 SDValue SITargetLowering::performOrCombine(SDNode *N, 9640 DAGCombinerInfo &DCI) const { 9641 SelectionDAG &DAG = DCI.DAG; 9642 SDValue LHS = N->getOperand(0); 9643 SDValue RHS = N->getOperand(1); 9644 9645 EVT VT = N->getValueType(0); 9646 if (VT == MVT::i1) { 9647 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9648 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9649 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9650 SDValue Src = LHS.getOperand(0); 9651 if (Src != RHS.getOperand(0)) 9652 return SDValue(); 9653 9654 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9655 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9656 if (!CLHS || !CRHS) 9657 return SDValue(); 9658 9659 // Only 10 bits are used. 9660 static const uint32_t MaxMask = 0x3ff; 9661 9662 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9663 SDLoc DL(N); 9664 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9665 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9666 } 9667 9668 return SDValue(); 9669 } 9670 9671 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9672 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9673 LHS.getOpcode() == AMDGPUISD::PERM && 9674 isa<ConstantSDNode>(LHS.getOperand(2))) { 9675 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9676 if (!Sel) 9677 return SDValue(); 9678 9679 Sel |= LHS.getConstantOperandVal(2); 9680 SDLoc DL(N); 9681 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9682 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9683 } 9684 9685 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9686 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9687 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9688 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9689 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9690 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9691 if (LHSMask != ~0u && RHSMask != ~0u) { 9692 // Canonicalize the expression in an attempt to have fewer unique masks 9693 // and therefore fewer registers used to hold the masks. 9694 if (LHSMask > RHSMask) { 9695 std::swap(LHSMask, RHSMask); 9696 std::swap(LHS, RHS); 9697 } 9698 9699 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9700 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9701 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9702 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9703 9704 // Check of we need to combine values from two sources within a byte. 9705 if (!(LHSUsedLanes & RHSUsedLanes) && 9706 // If we select high and lower word keep it for SDWA. 9707 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9708 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9709 // Kill zero bytes selected by other mask. Zero value is 0xc. 9710 LHSMask &= ~RHSUsedLanes; 9711 RHSMask &= ~LHSUsedLanes; 9712 // Add 4 to each active LHS lane 9713 LHSMask |= LHSUsedLanes & 0x04040404; 9714 // Combine masks 9715 uint32_t Sel = LHSMask | RHSMask; 9716 SDLoc DL(N); 9717 9718 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9719 LHS.getOperand(0), RHS.getOperand(0), 9720 DAG.getConstant(Sel, DL, MVT::i32)); 9721 } 9722 } 9723 } 9724 9725 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9726 return SDValue(); 9727 9728 // TODO: This could be a generic combine with a predicate for extracting the 9729 // high half of an integer being free. 9730 9731 // (or i64:x, (zero_extend i32:y)) -> 9732 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9733 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9734 RHS.getOpcode() != ISD::ZERO_EXTEND) 9735 std::swap(LHS, RHS); 9736 9737 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9738 SDValue ExtSrc = RHS.getOperand(0); 9739 EVT SrcVT = ExtSrc.getValueType(); 9740 if (SrcVT == MVT::i32) { 9741 SDLoc SL(N); 9742 SDValue LowLHS, HiBits; 9743 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9744 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9745 9746 DCI.AddToWorklist(LowOr.getNode()); 9747 DCI.AddToWorklist(HiBits.getNode()); 9748 9749 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9750 LowOr, HiBits); 9751 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9752 } 9753 } 9754 9755 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9756 if (CRHS) { 9757 if (SDValue Split 9758 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, 9759 N->getOperand(0), CRHS)) 9760 return Split; 9761 } 9762 9763 return SDValue(); 9764 } 9765 9766 SDValue SITargetLowering::performXorCombine(SDNode *N, 9767 DAGCombinerInfo &DCI) const { 9768 if (SDValue RV = reassociateScalarOps(N, DCI.DAG)) 9769 return RV; 9770 9771 EVT VT = N->getValueType(0); 9772 if (VT != MVT::i64) 9773 return SDValue(); 9774 9775 SDValue LHS = N->getOperand(0); 9776 SDValue RHS = N->getOperand(1); 9777 9778 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9779 if (CRHS) { 9780 if (SDValue Split 9781 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9782 return Split; 9783 } 9784 9785 return SDValue(); 9786 } 9787 9788 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9789 DAGCombinerInfo &DCI) const { 9790 if (!Subtarget->has16BitInsts() || 9791 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9792 return SDValue(); 9793 9794 EVT VT = N->getValueType(0); 9795 if (VT != MVT::i32) 9796 return SDValue(); 9797 9798 SDValue Src = N->getOperand(0); 9799 if (Src.getValueType() != MVT::i16) 9800 return SDValue(); 9801 9802 return SDValue(); 9803 } 9804 9805 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9806 DAGCombinerInfo &DCI) 9807 const { 9808 SDValue Src = N->getOperand(0); 9809 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9810 9811 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9812 VTSign->getVT() == MVT::i8) || 9813 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9814 VTSign->getVT() == MVT::i16)) && 9815 Src.hasOneUse()) { 9816 auto *M = cast<MemSDNode>(Src); 9817 SDValue Ops[] = { 9818 Src.getOperand(0), // Chain 9819 Src.getOperand(1), // rsrc 9820 Src.getOperand(2), // vindex 9821 Src.getOperand(3), // voffset 9822 Src.getOperand(4), // soffset 9823 Src.getOperand(5), // offset 9824 Src.getOperand(6), 9825 Src.getOperand(7) 9826 }; 9827 // replace with BUFFER_LOAD_BYTE/SHORT 9828 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9829 Src.getOperand(0).getValueType()); 9830 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9831 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9832 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9833 ResList, 9834 Ops, M->getMemoryVT(), 9835 M->getMemOperand()); 9836 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9837 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9838 } 9839 return SDValue(); 9840 } 9841 9842 SDValue SITargetLowering::performClassCombine(SDNode *N, 9843 DAGCombinerInfo &DCI) const { 9844 SelectionDAG &DAG = DCI.DAG; 9845 SDValue Mask = N->getOperand(1); 9846 9847 // fp_class x, 0 -> false 9848 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9849 if (CMask->isZero()) 9850 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9851 } 9852 9853 if (N->getOperand(0).isUndef()) 9854 return DAG.getUNDEF(MVT::i1); 9855 9856 return SDValue(); 9857 } 9858 9859 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9860 DAGCombinerInfo &DCI) const { 9861 EVT VT = N->getValueType(0); 9862 SDValue N0 = N->getOperand(0); 9863 9864 if (N0.isUndef()) 9865 return N0; 9866 9867 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9868 N0.getOpcode() == ISD::SINT_TO_FP)) { 9869 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9870 N->getFlags()); 9871 } 9872 9873 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9874 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9875 N0.getOperand(0), N->getFlags()); 9876 } 9877 9878 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9879 } 9880 9881 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9882 unsigned MaxDepth) const { 9883 unsigned Opcode = Op.getOpcode(); 9884 if (Opcode == ISD::FCANONICALIZE) 9885 return true; 9886 9887 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9888 auto F = CFP->getValueAPF(); 9889 if (F.isNaN() && F.isSignaling()) 9890 return false; 9891 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9892 } 9893 9894 // If source is a result of another standard FP operation it is already in 9895 // canonical form. 9896 if (MaxDepth == 0) 9897 return false; 9898 9899 switch (Opcode) { 9900 // These will flush denorms if required. 9901 case ISD::FADD: 9902 case ISD::FSUB: 9903 case ISD::FMUL: 9904 case ISD::FCEIL: 9905 case ISD::FFLOOR: 9906 case ISD::FMA: 9907 case ISD::FMAD: 9908 case ISD::FSQRT: 9909 case ISD::FDIV: 9910 case ISD::FREM: 9911 case ISD::FP_ROUND: 9912 case ISD::FP_EXTEND: 9913 case AMDGPUISD::FMUL_LEGACY: 9914 case AMDGPUISD::FMAD_FTZ: 9915 case AMDGPUISD::RCP: 9916 case AMDGPUISD::RSQ: 9917 case AMDGPUISD::RSQ_CLAMP: 9918 case AMDGPUISD::RCP_LEGACY: 9919 case AMDGPUISD::RCP_IFLAG: 9920 case AMDGPUISD::DIV_SCALE: 9921 case AMDGPUISD::DIV_FMAS: 9922 case AMDGPUISD::DIV_FIXUP: 9923 case AMDGPUISD::FRACT: 9924 case AMDGPUISD::LDEXP: 9925 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9926 case AMDGPUISD::CVT_F32_UBYTE0: 9927 case AMDGPUISD::CVT_F32_UBYTE1: 9928 case AMDGPUISD::CVT_F32_UBYTE2: 9929 case AMDGPUISD::CVT_F32_UBYTE3: 9930 return true; 9931 9932 // It can/will be lowered or combined as a bit operation. 9933 // Need to check their input recursively to handle. 9934 case ISD::FNEG: 9935 case ISD::FABS: 9936 case ISD::FCOPYSIGN: 9937 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9938 9939 case ISD::FSIN: 9940 case ISD::FCOS: 9941 case ISD::FSINCOS: 9942 return Op.getValueType().getScalarType() != MVT::f16; 9943 9944 case ISD::FMINNUM: 9945 case ISD::FMAXNUM: 9946 case ISD::FMINNUM_IEEE: 9947 case ISD::FMAXNUM_IEEE: 9948 case AMDGPUISD::CLAMP: 9949 case AMDGPUISD::FMED3: 9950 case AMDGPUISD::FMAX3: 9951 case AMDGPUISD::FMIN3: { 9952 // FIXME: Shouldn't treat the generic operations different based these. 9953 // However, we aren't really required to flush the result from 9954 // minnum/maxnum.. 9955 9956 // snans will be quieted, so we only need to worry about denormals. 9957 if (Subtarget->supportsMinMaxDenormModes() || 9958 denormalsEnabledForType(DAG, Op.getValueType())) 9959 return true; 9960 9961 // Flushing may be required. 9962 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9963 // targets need to check their input recursively. 9964 9965 // FIXME: Does this apply with clamp? It's implemented with max. 9966 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9967 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9968 return false; 9969 } 9970 9971 return true; 9972 } 9973 case ISD::SELECT: { 9974 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9975 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9976 } 9977 case ISD::BUILD_VECTOR: { 9978 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9979 SDValue SrcOp = Op.getOperand(i); 9980 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9981 return false; 9982 } 9983 9984 return true; 9985 } 9986 case ISD::EXTRACT_VECTOR_ELT: 9987 case ISD::EXTRACT_SUBVECTOR: { 9988 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9989 } 9990 case ISD::INSERT_VECTOR_ELT: { 9991 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9992 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9993 } 9994 case ISD::UNDEF: 9995 // Could be anything. 9996 return false; 9997 9998 case ISD::BITCAST: 9999 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 10000 case ISD::TRUNCATE: { 10001 // Hack round the mess we make when legalizing extract_vector_elt 10002 if (Op.getValueType() == MVT::i16) { 10003 SDValue TruncSrc = Op.getOperand(0); 10004 if (TruncSrc.getValueType() == MVT::i32 && 10005 TruncSrc.getOpcode() == ISD::BITCAST && 10006 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 10007 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 10008 } 10009 } 10010 return false; 10011 } 10012 case ISD::INTRINSIC_WO_CHAIN: { 10013 unsigned IntrinsicID 10014 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10015 // TODO: Handle more intrinsics 10016 switch (IntrinsicID) { 10017 case Intrinsic::amdgcn_cvt_pkrtz: 10018 case Intrinsic::amdgcn_cubeid: 10019 case Intrinsic::amdgcn_frexp_mant: 10020 case Intrinsic::amdgcn_fdot2: 10021 case Intrinsic::amdgcn_rcp: 10022 case Intrinsic::amdgcn_rsq: 10023 case Intrinsic::amdgcn_rsq_clamp: 10024 case Intrinsic::amdgcn_rcp_legacy: 10025 case Intrinsic::amdgcn_rsq_legacy: 10026 case Intrinsic::amdgcn_trig_preop: 10027 return true; 10028 default: 10029 break; 10030 } 10031 10032 LLVM_FALLTHROUGH; 10033 } 10034 default: 10035 return denormalsEnabledForType(DAG, Op.getValueType()) && 10036 DAG.isKnownNeverSNaN(Op); 10037 } 10038 10039 llvm_unreachable("invalid operation"); 10040 } 10041 10042 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 10043 unsigned MaxDepth) const { 10044 MachineRegisterInfo &MRI = MF.getRegInfo(); 10045 MachineInstr *MI = MRI.getVRegDef(Reg); 10046 unsigned Opcode = MI->getOpcode(); 10047 10048 if (Opcode == AMDGPU::G_FCANONICALIZE) 10049 return true; 10050 10051 Optional<FPValueAndVReg> FCR; 10052 // Constant splat (can be padded with undef) or scalar constant. 10053 if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) { 10054 if (FCR->Value.isSignaling()) 10055 return false; 10056 return !FCR->Value.isDenormal() || 10057 denormalsEnabledForType(MRI.getType(FCR->VReg), MF); 10058 } 10059 10060 if (MaxDepth == 0) 10061 return false; 10062 10063 switch (Opcode) { 10064 case AMDGPU::G_FMINNUM_IEEE: 10065 case AMDGPU::G_FMAXNUM_IEEE: { 10066 if (Subtarget->supportsMinMaxDenormModes() || 10067 denormalsEnabledForType(MRI.getType(Reg), MF)) 10068 return true; 10069 for (const MachineOperand &MO : llvm::drop_begin(MI->operands())) 10070 if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1)) 10071 return false; 10072 return true; 10073 } 10074 default: 10075 return denormalsEnabledForType(MRI.getType(Reg), MF) && 10076 isKnownNeverSNaN(Reg, MRI); 10077 } 10078 10079 llvm_unreachable("invalid operation"); 10080 } 10081 10082 // Constant fold canonicalize. 10083 SDValue SITargetLowering::getCanonicalConstantFP( 10084 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 10085 // Flush denormals to 0 if not enabled. 10086 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 10087 return DAG.getConstantFP(0.0, SL, VT); 10088 10089 if (C.isNaN()) { 10090 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 10091 if (C.isSignaling()) { 10092 // Quiet a signaling NaN. 10093 // FIXME: Is this supposed to preserve payload bits? 10094 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 10095 } 10096 10097 // Make sure it is the canonical NaN bitpattern. 10098 // 10099 // TODO: Can we use -1 as the canonical NaN value since it's an inline 10100 // immediate? 10101 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 10102 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 10103 } 10104 10105 // Already canonical. 10106 return DAG.getConstantFP(C, SL, VT); 10107 } 10108 10109 static bool vectorEltWillFoldAway(SDValue Op) { 10110 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 10111 } 10112 10113 SDValue SITargetLowering::performFCanonicalizeCombine( 10114 SDNode *N, 10115 DAGCombinerInfo &DCI) const { 10116 SelectionDAG &DAG = DCI.DAG; 10117 SDValue N0 = N->getOperand(0); 10118 EVT VT = N->getValueType(0); 10119 10120 // fcanonicalize undef -> qnan 10121 if (N0.isUndef()) { 10122 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 10123 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 10124 } 10125 10126 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 10127 EVT VT = N->getValueType(0); 10128 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 10129 } 10130 10131 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 10132 // (fcanonicalize k) 10133 // 10134 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 10135 10136 // TODO: This could be better with wider vectors that will be split to v2f16, 10137 // and to consider uses since there aren't that many packed operations. 10138 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 10139 isTypeLegal(MVT::v2f16)) { 10140 SDLoc SL(N); 10141 SDValue NewElts[2]; 10142 SDValue Lo = N0.getOperand(0); 10143 SDValue Hi = N0.getOperand(1); 10144 EVT EltVT = Lo.getValueType(); 10145 10146 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 10147 for (unsigned I = 0; I != 2; ++I) { 10148 SDValue Op = N0.getOperand(I); 10149 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 10150 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 10151 CFP->getValueAPF()); 10152 } else if (Op.isUndef()) { 10153 // Handled below based on what the other operand is. 10154 NewElts[I] = Op; 10155 } else { 10156 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 10157 } 10158 } 10159 10160 // If one half is undef, and one is constant, prefer a splat vector rather 10161 // than the normal qNaN. If it's a register, prefer 0.0 since that's 10162 // cheaper to use and may be free with a packed operation. 10163 if (NewElts[0].isUndef()) { 10164 if (isa<ConstantFPSDNode>(NewElts[1])) 10165 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 10166 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 10167 } 10168 10169 if (NewElts[1].isUndef()) { 10170 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 10171 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 10172 } 10173 10174 return DAG.getBuildVector(VT, SL, NewElts); 10175 } 10176 } 10177 10178 unsigned SrcOpc = N0.getOpcode(); 10179 10180 // If it's free to do so, push canonicalizes further up the source, which may 10181 // find a canonical source. 10182 // 10183 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 10184 // sNaNs. 10185 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 10186 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 10187 if (CRHS && N0.hasOneUse()) { 10188 SDLoc SL(N); 10189 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 10190 N0.getOperand(0)); 10191 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 10192 DCI.AddToWorklist(Canon0.getNode()); 10193 10194 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 10195 } 10196 } 10197 10198 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 10199 } 10200 10201 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 10202 switch (Opc) { 10203 case ISD::FMAXNUM: 10204 case ISD::FMAXNUM_IEEE: 10205 return AMDGPUISD::FMAX3; 10206 case ISD::SMAX: 10207 return AMDGPUISD::SMAX3; 10208 case ISD::UMAX: 10209 return AMDGPUISD::UMAX3; 10210 case ISD::FMINNUM: 10211 case ISD::FMINNUM_IEEE: 10212 return AMDGPUISD::FMIN3; 10213 case ISD::SMIN: 10214 return AMDGPUISD::SMIN3; 10215 case ISD::UMIN: 10216 return AMDGPUISD::UMIN3; 10217 default: 10218 llvm_unreachable("Not a min/max opcode"); 10219 } 10220 } 10221 10222 SDValue SITargetLowering::performIntMed3ImmCombine( 10223 SelectionDAG &DAG, const SDLoc &SL, 10224 SDValue Op0, SDValue Op1, bool Signed) const { 10225 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 10226 if (!K1) 10227 return SDValue(); 10228 10229 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 10230 if (!K0) 10231 return SDValue(); 10232 10233 if (Signed) { 10234 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 10235 return SDValue(); 10236 } else { 10237 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 10238 return SDValue(); 10239 } 10240 10241 EVT VT = K0->getValueType(0); 10242 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 10243 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 10244 return DAG.getNode(Med3Opc, SL, VT, 10245 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 10246 } 10247 10248 // If there isn't a 16-bit med3 operation, convert to 32-bit. 10249 if (VT == MVT::i16) { 10250 MVT NVT = MVT::i32; 10251 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 10252 10253 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 10254 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 10255 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 10256 10257 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 10258 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 10259 } 10260 10261 return SDValue(); 10262 } 10263 10264 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 10265 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 10266 return C; 10267 10268 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 10269 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 10270 return C; 10271 } 10272 10273 return nullptr; 10274 } 10275 10276 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 10277 const SDLoc &SL, 10278 SDValue Op0, 10279 SDValue Op1) const { 10280 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 10281 if (!K1) 10282 return SDValue(); 10283 10284 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 10285 if (!K0) 10286 return SDValue(); 10287 10288 // Ordered >= (although NaN inputs should have folded away by now). 10289 if (K0->getValueAPF() > K1->getValueAPF()) 10290 return SDValue(); 10291 10292 const MachineFunction &MF = DAG.getMachineFunction(); 10293 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10294 10295 // TODO: Check IEEE bit enabled? 10296 EVT VT = Op0.getValueType(); 10297 if (Info->getMode().DX10Clamp) { 10298 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 10299 // hardware fmed3 behavior converting to a min. 10300 // FIXME: Should this be allowing -0.0? 10301 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 10302 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 10303 } 10304 10305 // med3 for f16 is only available on gfx9+, and not available for v2f16. 10306 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 10307 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 10308 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 10309 // then give the other result, which is different from med3 with a NaN 10310 // input. 10311 SDValue Var = Op0.getOperand(0); 10312 if (!DAG.isKnownNeverSNaN(Var)) 10313 return SDValue(); 10314 10315 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10316 10317 if ((!K0->hasOneUse() || 10318 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 10319 (!K1->hasOneUse() || 10320 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 10321 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 10322 Var, SDValue(K0, 0), SDValue(K1, 0)); 10323 } 10324 } 10325 10326 return SDValue(); 10327 } 10328 10329 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 10330 DAGCombinerInfo &DCI) const { 10331 SelectionDAG &DAG = DCI.DAG; 10332 10333 EVT VT = N->getValueType(0); 10334 unsigned Opc = N->getOpcode(); 10335 SDValue Op0 = N->getOperand(0); 10336 SDValue Op1 = N->getOperand(1); 10337 10338 // Only do this if the inner op has one use since this will just increases 10339 // register pressure for no benefit. 10340 10341 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 10342 !VT.isVector() && 10343 (VT == MVT::i32 || VT == MVT::f32 || 10344 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 10345 // max(max(a, b), c) -> max3(a, b, c) 10346 // min(min(a, b), c) -> min3(a, b, c) 10347 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 10348 SDLoc DL(N); 10349 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10350 DL, 10351 N->getValueType(0), 10352 Op0.getOperand(0), 10353 Op0.getOperand(1), 10354 Op1); 10355 } 10356 10357 // Try commuted. 10358 // max(a, max(b, c)) -> max3(a, b, c) 10359 // min(a, min(b, c)) -> min3(a, b, c) 10360 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 10361 SDLoc DL(N); 10362 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10363 DL, 10364 N->getValueType(0), 10365 Op0, 10366 Op1.getOperand(0), 10367 Op1.getOperand(1)); 10368 } 10369 } 10370 10371 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 10372 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 10373 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 10374 return Med3; 10375 } 10376 10377 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 10378 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 10379 return Med3; 10380 } 10381 10382 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 10383 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 10384 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 10385 (Opc == AMDGPUISD::FMIN_LEGACY && 10386 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 10387 (VT == MVT::f32 || VT == MVT::f64 || 10388 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 10389 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 10390 Op0.hasOneUse()) { 10391 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 10392 return Res; 10393 } 10394 10395 return SDValue(); 10396 } 10397 10398 static bool isClampZeroToOne(SDValue A, SDValue B) { 10399 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 10400 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 10401 // FIXME: Should this be allowing -0.0? 10402 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 10403 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 10404 } 10405 } 10406 10407 return false; 10408 } 10409 10410 // FIXME: Should only worry about snans for version with chain. 10411 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10412 DAGCombinerInfo &DCI) const { 10413 EVT VT = N->getValueType(0); 10414 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10415 // NaNs. With a NaN input, the order of the operands may change the result. 10416 10417 SelectionDAG &DAG = DCI.DAG; 10418 SDLoc SL(N); 10419 10420 SDValue Src0 = N->getOperand(0); 10421 SDValue Src1 = N->getOperand(1); 10422 SDValue Src2 = N->getOperand(2); 10423 10424 if (isClampZeroToOne(Src0, Src1)) { 10425 // const_a, const_b, x -> clamp is safe in all cases including signaling 10426 // nans. 10427 // FIXME: Should this be allowing -0.0? 10428 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10429 } 10430 10431 const MachineFunction &MF = DAG.getMachineFunction(); 10432 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10433 10434 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10435 // handling no dx10-clamp? 10436 if (Info->getMode().DX10Clamp) { 10437 // If NaNs is clamped to 0, we are free to reorder the inputs. 10438 10439 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10440 std::swap(Src0, Src1); 10441 10442 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10443 std::swap(Src1, Src2); 10444 10445 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10446 std::swap(Src0, Src1); 10447 10448 if (isClampZeroToOne(Src1, Src2)) 10449 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10450 } 10451 10452 return SDValue(); 10453 } 10454 10455 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10456 DAGCombinerInfo &DCI) const { 10457 SDValue Src0 = N->getOperand(0); 10458 SDValue Src1 = N->getOperand(1); 10459 if (Src0.isUndef() && Src1.isUndef()) 10460 return DCI.DAG.getUNDEF(N->getValueType(0)); 10461 return SDValue(); 10462 } 10463 10464 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10465 // expanded into a set of cmp/select instructions. 10466 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10467 unsigned NumElem, 10468 bool IsDivergentIdx, 10469 const GCNSubtarget *Subtarget) { 10470 if (UseDivergentRegisterIndexing) 10471 return false; 10472 10473 unsigned VecSize = EltSize * NumElem; 10474 10475 // Sub-dword vectors of size 2 dword or less have better implementation. 10476 if (VecSize <= 64 && EltSize < 32) 10477 return false; 10478 10479 // Always expand the rest of sub-dword instructions, otherwise it will be 10480 // lowered via memory. 10481 if (EltSize < 32) 10482 return true; 10483 10484 // Always do this if var-idx is divergent, otherwise it will become a loop. 10485 if (IsDivergentIdx) 10486 return true; 10487 10488 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10489 unsigned NumInsts = NumElem /* Number of compares */ + 10490 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10491 10492 // On some architectures (GFX9) movrel is not available and it's better 10493 // to expand. 10494 if (!Subtarget->hasMovrel()) 10495 return NumInsts <= 16; 10496 10497 // If movrel is available, use it instead of expanding for vector of 8 10498 // elements. 10499 return NumInsts <= 15; 10500 } 10501 10502 bool SITargetLowering::shouldExpandVectorDynExt(SDNode *N) const { 10503 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10504 if (isa<ConstantSDNode>(Idx)) 10505 return false; 10506 10507 SDValue Vec = N->getOperand(0); 10508 EVT VecVT = Vec.getValueType(); 10509 EVT EltVT = VecVT.getVectorElementType(); 10510 unsigned EltSize = EltVT.getSizeInBits(); 10511 unsigned NumElem = VecVT.getVectorNumElements(); 10512 10513 return SITargetLowering::shouldExpandVectorDynExt( 10514 EltSize, NumElem, Idx->isDivergent(), getSubtarget()); 10515 } 10516 10517 SDValue SITargetLowering::performExtractVectorEltCombine( 10518 SDNode *N, DAGCombinerInfo &DCI) const { 10519 SDValue Vec = N->getOperand(0); 10520 SelectionDAG &DAG = DCI.DAG; 10521 10522 EVT VecVT = Vec.getValueType(); 10523 EVT EltVT = VecVT.getVectorElementType(); 10524 10525 if ((Vec.getOpcode() == ISD::FNEG || 10526 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10527 SDLoc SL(N); 10528 EVT EltVT = N->getValueType(0); 10529 SDValue Idx = N->getOperand(1); 10530 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10531 Vec.getOperand(0), Idx); 10532 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10533 } 10534 10535 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10536 // => 10537 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10538 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10539 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10540 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10541 SDLoc SL(N); 10542 EVT EltVT = N->getValueType(0); 10543 SDValue Idx = N->getOperand(1); 10544 unsigned Opc = Vec.getOpcode(); 10545 10546 switch(Opc) { 10547 default: 10548 break; 10549 // TODO: Support other binary operations. 10550 case ISD::FADD: 10551 case ISD::FSUB: 10552 case ISD::FMUL: 10553 case ISD::ADD: 10554 case ISD::UMIN: 10555 case ISD::UMAX: 10556 case ISD::SMIN: 10557 case ISD::SMAX: 10558 case ISD::FMAXNUM: 10559 case ISD::FMINNUM: 10560 case ISD::FMAXNUM_IEEE: 10561 case ISD::FMINNUM_IEEE: { 10562 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10563 Vec.getOperand(0), Idx); 10564 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10565 Vec.getOperand(1), Idx); 10566 10567 DCI.AddToWorklist(Elt0.getNode()); 10568 DCI.AddToWorklist(Elt1.getNode()); 10569 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10570 } 10571 } 10572 } 10573 10574 unsigned VecSize = VecVT.getSizeInBits(); 10575 unsigned EltSize = EltVT.getSizeInBits(); 10576 10577 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10578 if (shouldExpandVectorDynExt(N)) { 10579 SDLoc SL(N); 10580 SDValue Idx = N->getOperand(1); 10581 SDValue V; 10582 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10583 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10584 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10585 if (I == 0) 10586 V = Elt; 10587 else 10588 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10589 } 10590 return V; 10591 } 10592 10593 if (!DCI.isBeforeLegalize()) 10594 return SDValue(); 10595 10596 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10597 // elements. This exposes more load reduction opportunities by replacing 10598 // multiple small extract_vector_elements with a single 32-bit extract. 10599 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10600 if (isa<MemSDNode>(Vec) && 10601 EltSize <= 16 && 10602 EltVT.isByteSized() && 10603 VecSize > 32 && 10604 VecSize % 32 == 0 && 10605 Idx) { 10606 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10607 10608 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10609 unsigned EltIdx = BitIndex / 32; 10610 unsigned LeftoverBitIdx = BitIndex % 32; 10611 SDLoc SL(N); 10612 10613 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10614 DCI.AddToWorklist(Cast.getNode()); 10615 10616 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10617 DAG.getConstant(EltIdx, SL, MVT::i32)); 10618 DCI.AddToWorklist(Elt.getNode()); 10619 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10620 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10621 DCI.AddToWorklist(Srl.getNode()); 10622 10623 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10624 DCI.AddToWorklist(Trunc.getNode()); 10625 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10626 } 10627 10628 return SDValue(); 10629 } 10630 10631 SDValue 10632 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10633 DAGCombinerInfo &DCI) const { 10634 SDValue Vec = N->getOperand(0); 10635 SDValue Idx = N->getOperand(2); 10636 EVT VecVT = Vec.getValueType(); 10637 EVT EltVT = VecVT.getVectorElementType(); 10638 10639 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10640 // => BUILD_VECTOR n x select (e, const-idx) 10641 if (!shouldExpandVectorDynExt(N)) 10642 return SDValue(); 10643 10644 SelectionDAG &DAG = DCI.DAG; 10645 SDLoc SL(N); 10646 SDValue Ins = N->getOperand(1); 10647 EVT IdxVT = Idx.getValueType(); 10648 10649 SmallVector<SDValue, 16> Ops; 10650 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10651 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10652 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10653 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10654 Ops.push_back(V); 10655 } 10656 10657 return DAG.getBuildVector(VecVT, SL, Ops); 10658 } 10659 10660 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10661 const SDNode *N0, 10662 const SDNode *N1) const { 10663 EVT VT = N0->getValueType(0); 10664 10665 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10666 // support denormals ever. 10667 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10668 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10669 getSubtarget()->hasMadF16())) && 10670 isOperationLegal(ISD::FMAD, VT)) 10671 return ISD::FMAD; 10672 10673 const TargetOptions &Options = DAG.getTarget().Options; 10674 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10675 (N0->getFlags().hasAllowContract() && 10676 N1->getFlags().hasAllowContract())) && 10677 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10678 return ISD::FMA; 10679 } 10680 10681 return 0; 10682 } 10683 10684 // For a reassociatable opcode perform: 10685 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10686 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10687 SelectionDAG &DAG) const { 10688 EVT VT = N->getValueType(0); 10689 if (VT != MVT::i32 && VT != MVT::i64) 10690 return SDValue(); 10691 10692 if (DAG.isBaseWithConstantOffset(SDValue(N, 0))) 10693 return SDValue(); 10694 10695 unsigned Opc = N->getOpcode(); 10696 SDValue Op0 = N->getOperand(0); 10697 SDValue Op1 = N->getOperand(1); 10698 10699 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10700 return SDValue(); 10701 10702 if (Op0->isDivergent()) 10703 std::swap(Op0, Op1); 10704 10705 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10706 return SDValue(); 10707 10708 SDValue Op2 = Op1.getOperand(1); 10709 Op1 = Op1.getOperand(0); 10710 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10711 return SDValue(); 10712 10713 if (Op1->isDivergent()) 10714 std::swap(Op1, Op2); 10715 10716 SDLoc SL(N); 10717 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10718 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10719 } 10720 10721 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10722 EVT VT, 10723 SDValue N0, SDValue N1, SDValue N2, 10724 bool Signed) { 10725 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10726 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10727 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10728 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10729 } 10730 10731 // Fold (add (mul x, y), z) --> (mad_[iu]64_[iu]32 x, y, z) plus high 10732 // multiplies, if any. 10733 // 10734 // Full 64-bit multiplies that feed into an addition are lowered here instead 10735 // of using the generic expansion. The generic expansion ends up with 10736 // a tree of ADD nodes that prevents us from using the "add" part of the 10737 // MAD instruction. The expansion produced here results in a chain of ADDs 10738 // instead of a tree. 10739 SDValue SITargetLowering::tryFoldToMad64_32(SDNode *N, 10740 DAGCombinerInfo &DCI) const { 10741 assert(N->getOpcode() == ISD::ADD); 10742 10743 SelectionDAG &DAG = DCI.DAG; 10744 EVT VT = N->getValueType(0); 10745 SDLoc SL(N); 10746 SDValue LHS = N->getOperand(0); 10747 SDValue RHS = N->getOperand(1); 10748 10749 if (VT.isVector()) 10750 return SDValue(); 10751 10752 // S_MUL_HI_[IU]32 was added in gfx9, which allows us to keep the overall 10753 // result in scalar registers for uniform values. 10754 if (!N->isDivergent() && Subtarget->hasSMulHi()) 10755 return SDValue(); 10756 10757 unsigned NumBits = VT.getScalarSizeInBits(); 10758 if (NumBits <= 32 || NumBits > 64) 10759 return SDValue(); 10760 10761 if (LHS.getOpcode() != ISD::MUL) { 10762 assert(RHS.getOpcode() == ISD::MUL); 10763 std::swap(LHS, RHS); 10764 } 10765 10766 // Avoid the fold if it would unduly increase the number of multiplies due to 10767 // multiple uses, except on hardware with full-rate multiply-add (which is 10768 // part of full-rate 64-bit ops). 10769 if (!Subtarget->hasFullRate64Ops()) { 10770 unsigned NumUsers = 0; 10771 for (SDNode *Use : LHS->uses()) { 10772 // There is a use that does not feed into addition, so the multiply can't 10773 // be removed. We prefer MUL + ADD + ADDC over MAD + MUL. 10774 if (Use->getOpcode() != ISD::ADD) 10775 return SDValue(); 10776 10777 // We prefer 2xMAD over MUL + 2xADD + 2xADDC (code density), and prefer 10778 // MUL + 3xADD + 3xADDC over 3xMAD. 10779 ++NumUsers; 10780 if (NumUsers >= 3) 10781 return SDValue(); 10782 } 10783 } 10784 10785 SDValue MulLHS = LHS.getOperand(0); 10786 SDValue MulRHS = LHS.getOperand(1); 10787 SDValue AddRHS = RHS; 10788 10789 // Always check whether operands are small unsigned values, since that 10790 // knowledge is useful in more cases. Check for small signed values only if 10791 // doing so can unlock a shorter code sequence. 10792 bool MulLHSUnsigned32 = numBitsUnsigned(MulLHS, DAG) <= 32; 10793 bool MulRHSUnsigned32 = numBitsUnsigned(MulRHS, DAG) <= 32; 10794 10795 bool MulSignedLo = false; 10796 if (!MulLHSUnsigned32 || !MulRHSUnsigned32) { 10797 MulSignedLo = numBitsSigned(MulLHS, DAG) <= 32 && 10798 numBitsSigned(MulRHS, DAG) <= 32; 10799 } 10800 10801 // The operands and final result all have the same number of bits. If 10802 // operands need to be extended, they can be extended with garbage. The 10803 // resulting garbage in the high bits of the mad_[iu]64_[iu]32 result is 10804 // truncated away in the end. 10805 if (VT != MVT::i64) { 10806 MulLHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulLHS); 10807 MulRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulRHS); 10808 AddRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, AddRHS); 10809 } 10810 10811 // The basic code generated is conceptually straightforward. Pseudo code: 10812 // 10813 // accum = mad_64_32 lhs.lo, rhs.lo, accum 10814 // accum.hi = add (mul lhs.hi, rhs.lo), accum.hi 10815 // accum.hi = add (mul lhs.lo, rhs.hi), accum.hi 10816 // 10817 // The second and third lines are optional, depending on whether the factors 10818 // are {sign,zero}-extended or not. 10819 // 10820 // The actual DAG is noisier than the pseudo code, but only due to 10821 // instructions that disassemble values into low and high parts, and 10822 // assemble the final result. 10823 SDValue Zero = DAG.getConstant(0, SL, MVT::i32); 10824 SDValue One = DAG.getConstant(1, SL, MVT::i32); 10825 10826 auto MulLHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulLHS); 10827 auto MulRHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulRHS); 10828 SDValue Accum = 10829 getMad64_32(DAG, SL, MVT::i64, MulLHSLo, MulRHSLo, AddRHS, MulSignedLo); 10830 10831 if (!MulSignedLo && (!MulLHSUnsigned32 || !MulRHSUnsigned32)) { 10832 auto AccumLo = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, Zero); 10833 auto AccumHi = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, One); 10834 10835 if (!MulLHSUnsigned32) { 10836 auto MulLHSHi = 10837 DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulLHS, One); 10838 SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSHi, MulRHSLo); 10839 AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi); 10840 } 10841 10842 if (!MulRHSUnsigned32) { 10843 auto MulRHSHi = 10844 DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulRHS, One); 10845 SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSLo, MulRHSHi); 10846 AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi); 10847 } 10848 10849 Accum = DAG.getBuildVector(MVT::v2i32, SL, {AccumLo, AccumHi}); 10850 Accum = DAG.getBitcast(MVT::i64, Accum); 10851 } 10852 10853 if (VT != MVT::i64) 10854 Accum = DAG.getNode(ISD::TRUNCATE, SL, VT, Accum); 10855 return Accum; 10856 } 10857 10858 SDValue SITargetLowering::performAddCombine(SDNode *N, 10859 DAGCombinerInfo &DCI) const { 10860 SelectionDAG &DAG = DCI.DAG; 10861 EVT VT = N->getValueType(0); 10862 SDLoc SL(N); 10863 SDValue LHS = N->getOperand(0); 10864 SDValue RHS = N->getOperand(1); 10865 10866 if (LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) { 10867 if (Subtarget->hasMad64_32()) { 10868 if (SDValue Folded = tryFoldToMad64_32(N, DCI)) 10869 return Folded; 10870 } 10871 10872 return SDValue(); 10873 } 10874 10875 if (SDValue V = reassociateScalarOps(N, DAG)) { 10876 return V; 10877 } 10878 10879 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10880 return SDValue(); 10881 10882 // add x, zext (setcc) => addcarry x, 0, setcc 10883 // add x, sext (setcc) => subcarry x, 0, setcc 10884 unsigned Opc = LHS.getOpcode(); 10885 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10886 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10887 std::swap(RHS, LHS); 10888 10889 Opc = RHS.getOpcode(); 10890 switch (Opc) { 10891 default: break; 10892 case ISD::ZERO_EXTEND: 10893 case ISD::SIGN_EXTEND: 10894 case ISD::ANY_EXTEND: { 10895 auto Cond = RHS.getOperand(0); 10896 // If this won't be a real VOPC output, we would still need to insert an 10897 // extra instruction anyway. 10898 if (!isBoolSGPR(Cond)) 10899 break; 10900 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10901 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10902 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10903 return DAG.getNode(Opc, SL, VTList, Args); 10904 } 10905 case ISD::ADDCARRY: { 10906 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10907 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10908 if (!C || C->getZExtValue() != 0) break; 10909 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10910 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10911 } 10912 } 10913 return SDValue(); 10914 } 10915 10916 SDValue SITargetLowering::performSubCombine(SDNode *N, 10917 DAGCombinerInfo &DCI) const { 10918 SelectionDAG &DAG = DCI.DAG; 10919 EVT VT = N->getValueType(0); 10920 10921 if (VT != MVT::i32) 10922 return SDValue(); 10923 10924 SDLoc SL(N); 10925 SDValue LHS = N->getOperand(0); 10926 SDValue RHS = N->getOperand(1); 10927 10928 // sub x, zext (setcc) => subcarry x, 0, setcc 10929 // sub x, sext (setcc) => addcarry x, 0, setcc 10930 unsigned Opc = RHS.getOpcode(); 10931 switch (Opc) { 10932 default: break; 10933 case ISD::ZERO_EXTEND: 10934 case ISD::SIGN_EXTEND: 10935 case ISD::ANY_EXTEND: { 10936 auto Cond = RHS.getOperand(0); 10937 // If this won't be a real VOPC output, we would still need to insert an 10938 // extra instruction anyway. 10939 if (!isBoolSGPR(Cond)) 10940 break; 10941 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10942 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10943 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10944 return DAG.getNode(Opc, SL, VTList, Args); 10945 } 10946 } 10947 10948 if (LHS.getOpcode() == ISD::SUBCARRY) { 10949 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10950 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10951 if (!C || !C->isZero()) 10952 return SDValue(); 10953 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10954 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10955 } 10956 return SDValue(); 10957 } 10958 10959 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10960 DAGCombinerInfo &DCI) const { 10961 10962 if (N->getValueType(0) != MVT::i32) 10963 return SDValue(); 10964 10965 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10966 if (!C || C->getZExtValue() != 0) 10967 return SDValue(); 10968 10969 SelectionDAG &DAG = DCI.DAG; 10970 SDValue LHS = N->getOperand(0); 10971 10972 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10973 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10974 unsigned LHSOpc = LHS.getOpcode(); 10975 unsigned Opc = N->getOpcode(); 10976 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10977 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10978 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10979 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10980 } 10981 return SDValue(); 10982 } 10983 10984 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10985 DAGCombinerInfo &DCI) const { 10986 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10987 return SDValue(); 10988 10989 SelectionDAG &DAG = DCI.DAG; 10990 EVT VT = N->getValueType(0); 10991 10992 SDLoc SL(N); 10993 SDValue LHS = N->getOperand(0); 10994 SDValue RHS = N->getOperand(1); 10995 10996 // These should really be instruction patterns, but writing patterns with 10997 // source modifiers is a pain. 10998 10999 // fadd (fadd (a, a), b) -> mad 2.0, a, b 11000 if (LHS.getOpcode() == ISD::FADD) { 11001 SDValue A = LHS.getOperand(0); 11002 if (A == LHS.getOperand(1)) { 11003 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 11004 if (FusedOp != 0) { 11005 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 11006 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 11007 } 11008 } 11009 } 11010 11011 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 11012 if (RHS.getOpcode() == ISD::FADD) { 11013 SDValue A = RHS.getOperand(0); 11014 if (A == RHS.getOperand(1)) { 11015 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 11016 if (FusedOp != 0) { 11017 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 11018 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 11019 } 11020 } 11021 } 11022 11023 return SDValue(); 11024 } 11025 11026 SDValue SITargetLowering::performFSubCombine(SDNode *N, 11027 DAGCombinerInfo &DCI) const { 11028 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 11029 return SDValue(); 11030 11031 SelectionDAG &DAG = DCI.DAG; 11032 SDLoc SL(N); 11033 EVT VT = N->getValueType(0); 11034 assert(!VT.isVector()); 11035 11036 // Try to get the fneg to fold into the source modifier. This undoes generic 11037 // DAG combines and folds them into the mad. 11038 // 11039 // Only do this if we are not trying to support denormals. v_mad_f32 does 11040 // not support denormals ever. 11041 SDValue LHS = N->getOperand(0); 11042 SDValue RHS = N->getOperand(1); 11043 if (LHS.getOpcode() == ISD::FADD) { 11044 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 11045 SDValue A = LHS.getOperand(0); 11046 if (A == LHS.getOperand(1)) { 11047 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 11048 if (FusedOp != 0){ 11049 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 11050 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 11051 11052 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 11053 } 11054 } 11055 } 11056 11057 if (RHS.getOpcode() == ISD::FADD) { 11058 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 11059 11060 SDValue A = RHS.getOperand(0); 11061 if (A == RHS.getOperand(1)) { 11062 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 11063 if (FusedOp != 0){ 11064 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 11065 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 11066 } 11067 } 11068 } 11069 11070 return SDValue(); 11071 } 11072 11073 SDValue SITargetLowering::performFMACombine(SDNode *N, 11074 DAGCombinerInfo &DCI) const { 11075 SelectionDAG &DAG = DCI.DAG; 11076 EVT VT = N->getValueType(0); 11077 SDLoc SL(N); 11078 11079 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 11080 return SDValue(); 11081 11082 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 11083 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 11084 SDValue Op1 = N->getOperand(0); 11085 SDValue Op2 = N->getOperand(1); 11086 SDValue FMA = N->getOperand(2); 11087 11088 if (FMA.getOpcode() != ISD::FMA || 11089 Op1.getOpcode() != ISD::FP_EXTEND || 11090 Op2.getOpcode() != ISD::FP_EXTEND) 11091 return SDValue(); 11092 11093 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 11094 // regardless of the denorm mode setting. Therefore, 11095 // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2. 11096 const TargetOptions &Options = DAG.getTarget().Options; 11097 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 11098 (N->getFlags().hasAllowContract() && 11099 FMA->getFlags().hasAllowContract())) { 11100 Op1 = Op1.getOperand(0); 11101 Op2 = Op2.getOperand(0); 11102 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11103 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11104 return SDValue(); 11105 11106 SDValue Vec1 = Op1.getOperand(0); 11107 SDValue Idx1 = Op1.getOperand(1); 11108 SDValue Vec2 = Op2.getOperand(0); 11109 11110 SDValue FMAOp1 = FMA.getOperand(0); 11111 SDValue FMAOp2 = FMA.getOperand(1); 11112 SDValue FMAAcc = FMA.getOperand(2); 11113 11114 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 11115 FMAOp2.getOpcode() != ISD::FP_EXTEND) 11116 return SDValue(); 11117 11118 FMAOp1 = FMAOp1.getOperand(0); 11119 FMAOp2 = FMAOp2.getOperand(0); 11120 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11121 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11122 return SDValue(); 11123 11124 SDValue Vec3 = FMAOp1.getOperand(0); 11125 SDValue Vec4 = FMAOp2.getOperand(0); 11126 SDValue Idx2 = FMAOp1.getOperand(1); 11127 11128 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 11129 // Idx1 and Idx2 cannot be the same. 11130 Idx1 == Idx2) 11131 return SDValue(); 11132 11133 if (Vec1 == Vec2 || Vec3 == Vec4) 11134 return SDValue(); 11135 11136 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 11137 return SDValue(); 11138 11139 if ((Vec1 == Vec3 && Vec2 == Vec4) || 11140 (Vec1 == Vec4 && Vec2 == Vec3)) { 11141 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 11142 DAG.getTargetConstant(0, SL, MVT::i1)); 11143 } 11144 } 11145 return SDValue(); 11146 } 11147 11148 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 11149 DAGCombinerInfo &DCI) const { 11150 SelectionDAG &DAG = DCI.DAG; 11151 SDLoc SL(N); 11152 11153 SDValue LHS = N->getOperand(0); 11154 SDValue RHS = N->getOperand(1); 11155 EVT VT = LHS.getValueType(); 11156 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11157 11158 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 11159 if (!CRHS) { 11160 CRHS = dyn_cast<ConstantSDNode>(LHS); 11161 if (CRHS) { 11162 std::swap(LHS, RHS); 11163 CC = getSetCCSwappedOperands(CC); 11164 } 11165 } 11166 11167 if (CRHS) { 11168 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 11169 isBoolSGPR(LHS.getOperand(0))) { 11170 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 11171 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 11172 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 11173 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 11174 if ((CRHS->isAllOnes() && 11175 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 11176 (CRHS->isZero() && 11177 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 11178 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 11179 DAG.getConstant(-1, SL, MVT::i1)); 11180 if ((CRHS->isAllOnes() && 11181 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 11182 (CRHS->isZero() && 11183 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 11184 return LHS.getOperand(0); 11185 } 11186 11187 const APInt &CRHSVal = CRHS->getAPIntValue(); 11188 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 11189 LHS.getOpcode() == ISD::SELECT && 11190 isa<ConstantSDNode>(LHS.getOperand(1)) && 11191 isa<ConstantSDNode>(LHS.getOperand(2)) && 11192 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 11193 isBoolSGPR(LHS.getOperand(0))) { 11194 // Given CT != FT: 11195 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 11196 // setcc (select cc, CT, CF), CF, ne => cc 11197 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 11198 // setcc (select cc, CT, CF), CT, eq => cc 11199 const APInt &CT = LHS.getConstantOperandAPInt(1); 11200 const APInt &CF = LHS.getConstantOperandAPInt(2); 11201 11202 if ((CF == CRHSVal && CC == ISD::SETEQ) || 11203 (CT == CRHSVal && CC == ISD::SETNE)) 11204 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 11205 DAG.getConstant(-1, SL, MVT::i1)); 11206 if ((CF == CRHSVal && CC == ISD::SETNE) || 11207 (CT == CRHSVal && CC == ISD::SETEQ)) 11208 return LHS.getOperand(0); 11209 } 11210 } 11211 11212 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 11213 VT != MVT::f16)) 11214 return SDValue(); 11215 11216 // Match isinf/isfinite pattern 11217 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 11218 // (fcmp one (fabs x), inf) -> (fp_class x, 11219 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 11220 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 11221 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 11222 if (!CRHS) 11223 return SDValue(); 11224 11225 const APFloat &APF = CRHS->getValueAPF(); 11226 if (APF.isInfinity() && !APF.isNegative()) { 11227 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 11228 SIInstrFlags::N_INFINITY; 11229 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 11230 SIInstrFlags::P_ZERO | 11231 SIInstrFlags::N_NORMAL | 11232 SIInstrFlags::P_NORMAL | 11233 SIInstrFlags::N_SUBNORMAL | 11234 SIInstrFlags::P_SUBNORMAL; 11235 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 11236 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 11237 DAG.getConstant(Mask, SL, MVT::i32)); 11238 } 11239 } 11240 11241 return SDValue(); 11242 } 11243 11244 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 11245 DAGCombinerInfo &DCI) const { 11246 SelectionDAG &DAG = DCI.DAG; 11247 SDLoc SL(N); 11248 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 11249 11250 SDValue Src = N->getOperand(0); 11251 SDValue Shift = N->getOperand(0); 11252 11253 // TODO: Extend type shouldn't matter (assuming legal types). 11254 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 11255 Shift = Shift.getOperand(0); 11256 11257 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 11258 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 11259 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 11260 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 11261 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 11262 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 11263 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 11264 SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0), 11265 SDLoc(Shift.getOperand(0)), MVT::i32); 11266 11267 unsigned ShiftOffset = 8 * Offset; 11268 if (Shift.getOpcode() == ISD::SHL) 11269 ShiftOffset -= C->getZExtValue(); 11270 else 11271 ShiftOffset += C->getZExtValue(); 11272 11273 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 11274 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 11275 MVT::f32, Shifted); 11276 } 11277 } 11278 } 11279 11280 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11281 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 11282 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 11283 // We simplified Src. If this node is not dead, visit it again so it is 11284 // folded properly. 11285 if (N->getOpcode() != ISD::DELETED_NODE) 11286 DCI.AddToWorklist(N); 11287 return SDValue(N, 0); 11288 } 11289 11290 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 11291 if (SDValue DemandedSrc = 11292 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 11293 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 11294 11295 return SDValue(); 11296 } 11297 11298 SDValue SITargetLowering::performClampCombine(SDNode *N, 11299 DAGCombinerInfo &DCI) const { 11300 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 11301 if (!CSrc) 11302 return SDValue(); 11303 11304 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 11305 const APFloat &F = CSrc->getValueAPF(); 11306 APFloat Zero = APFloat::getZero(F.getSemantics()); 11307 if (F < Zero || 11308 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 11309 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 11310 } 11311 11312 APFloat One(F.getSemantics(), "1.0"); 11313 if (F > One) 11314 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 11315 11316 return SDValue(CSrc, 0); 11317 } 11318 11319 11320 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 11321 DAGCombinerInfo &DCI) const { 11322 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 11323 return SDValue(); 11324 switch (N->getOpcode()) { 11325 case ISD::ADD: 11326 return performAddCombine(N, DCI); 11327 case ISD::SUB: 11328 return performSubCombine(N, DCI); 11329 case ISD::ADDCARRY: 11330 case ISD::SUBCARRY: 11331 return performAddCarrySubCarryCombine(N, DCI); 11332 case ISD::FADD: 11333 return performFAddCombine(N, DCI); 11334 case ISD::FSUB: 11335 return performFSubCombine(N, DCI); 11336 case ISD::SETCC: 11337 return performSetCCCombine(N, DCI); 11338 case ISD::FMAXNUM: 11339 case ISD::FMINNUM: 11340 case ISD::FMAXNUM_IEEE: 11341 case ISD::FMINNUM_IEEE: 11342 case ISD::SMAX: 11343 case ISD::SMIN: 11344 case ISD::UMAX: 11345 case ISD::UMIN: 11346 case AMDGPUISD::FMIN_LEGACY: 11347 case AMDGPUISD::FMAX_LEGACY: 11348 return performMinMaxCombine(N, DCI); 11349 case ISD::FMA: 11350 return performFMACombine(N, DCI); 11351 case ISD::AND: 11352 return performAndCombine(N, DCI); 11353 case ISD::OR: 11354 return performOrCombine(N, DCI); 11355 case ISD::XOR: 11356 return performXorCombine(N, DCI); 11357 case ISD::ZERO_EXTEND: 11358 return performZeroExtendCombine(N, DCI); 11359 case ISD::SIGN_EXTEND_INREG: 11360 return performSignExtendInRegCombine(N , DCI); 11361 case AMDGPUISD::FP_CLASS: 11362 return performClassCombine(N, DCI); 11363 case ISD::FCANONICALIZE: 11364 return performFCanonicalizeCombine(N, DCI); 11365 case AMDGPUISD::RCP: 11366 return performRcpCombine(N, DCI); 11367 case AMDGPUISD::FRACT: 11368 case AMDGPUISD::RSQ: 11369 case AMDGPUISD::RCP_LEGACY: 11370 case AMDGPUISD::RCP_IFLAG: 11371 case AMDGPUISD::RSQ_CLAMP: 11372 case AMDGPUISD::LDEXP: { 11373 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 11374 SDValue Src = N->getOperand(0); 11375 if (Src.isUndef()) 11376 return Src; 11377 break; 11378 } 11379 case ISD::SINT_TO_FP: 11380 case ISD::UINT_TO_FP: 11381 return performUCharToFloatCombine(N, DCI); 11382 case AMDGPUISD::CVT_F32_UBYTE0: 11383 case AMDGPUISD::CVT_F32_UBYTE1: 11384 case AMDGPUISD::CVT_F32_UBYTE2: 11385 case AMDGPUISD::CVT_F32_UBYTE3: 11386 return performCvtF32UByteNCombine(N, DCI); 11387 case AMDGPUISD::FMED3: 11388 return performFMed3Combine(N, DCI); 11389 case AMDGPUISD::CVT_PKRTZ_F16_F32: 11390 return performCvtPkRTZCombine(N, DCI); 11391 case AMDGPUISD::CLAMP: 11392 return performClampCombine(N, DCI); 11393 case ISD::SCALAR_TO_VECTOR: { 11394 SelectionDAG &DAG = DCI.DAG; 11395 EVT VT = N->getValueType(0); 11396 11397 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 11398 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 11399 SDLoc SL(N); 11400 SDValue Src = N->getOperand(0); 11401 EVT EltVT = Src.getValueType(); 11402 if (EltVT == MVT::f16) 11403 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 11404 11405 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 11406 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 11407 } 11408 11409 break; 11410 } 11411 case ISD::EXTRACT_VECTOR_ELT: 11412 return performExtractVectorEltCombine(N, DCI); 11413 case ISD::INSERT_VECTOR_ELT: 11414 return performInsertVectorEltCombine(N, DCI); 11415 case ISD::LOAD: { 11416 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 11417 return Widended; 11418 LLVM_FALLTHROUGH; 11419 } 11420 default: { 11421 if (!DCI.isBeforeLegalize()) { 11422 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 11423 return performMemSDNodeCombine(MemNode, DCI); 11424 } 11425 11426 break; 11427 } 11428 } 11429 11430 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 11431 } 11432 11433 /// Helper function for adjustWritemask 11434 static unsigned SubIdx2Lane(unsigned Idx) { 11435 switch (Idx) { 11436 default: return ~0u; 11437 case AMDGPU::sub0: return 0; 11438 case AMDGPU::sub1: return 1; 11439 case AMDGPU::sub2: return 2; 11440 case AMDGPU::sub3: return 3; 11441 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 11442 } 11443 } 11444 11445 /// Adjust the writemask of MIMG instructions 11446 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 11447 SelectionDAG &DAG) const { 11448 unsigned Opcode = Node->getMachineOpcode(); 11449 11450 // Subtract 1 because the vdata output is not a MachineSDNode operand. 11451 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 11452 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 11453 return Node; // not implemented for D16 11454 11455 SDNode *Users[5] = { nullptr }; 11456 unsigned Lane = 0; 11457 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 11458 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 11459 unsigned NewDmask = 0; 11460 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 11461 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 11462 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 11463 Node->getConstantOperandVal(LWEIdx)) 11464 ? true 11465 : false; 11466 unsigned TFCLane = 0; 11467 bool HasChain = Node->getNumValues() > 1; 11468 11469 if (OldDmask == 0) { 11470 // These are folded out, but on the chance it happens don't assert. 11471 return Node; 11472 } 11473 11474 unsigned OldBitsSet = countPopulation(OldDmask); 11475 // Work out which is the TFE/LWE lane if that is enabled. 11476 if (UsesTFC) { 11477 TFCLane = OldBitsSet; 11478 } 11479 11480 // Try to figure out the used register components 11481 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 11482 I != E; ++I) { 11483 11484 // Don't look at users of the chain. 11485 if (I.getUse().getResNo() != 0) 11486 continue; 11487 11488 // Abort if we can't understand the usage 11489 if (!I->isMachineOpcode() || 11490 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 11491 return Node; 11492 11493 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 11494 // Note that subregs are packed, i.e. Lane==0 is the first bit set 11495 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 11496 // set, etc. 11497 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 11498 if (Lane == ~0u) 11499 return Node; 11500 11501 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 11502 if (UsesTFC && Lane == TFCLane) { 11503 Users[Lane] = *I; 11504 } else { 11505 // Set which texture component corresponds to the lane. 11506 unsigned Comp; 11507 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 11508 Comp = countTrailingZeros(Dmask); 11509 Dmask &= ~(1 << Comp); 11510 } 11511 11512 // Abort if we have more than one user per component. 11513 if (Users[Lane]) 11514 return Node; 11515 11516 Users[Lane] = *I; 11517 NewDmask |= 1 << Comp; 11518 } 11519 } 11520 11521 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11522 bool NoChannels = !NewDmask; 11523 if (NoChannels) { 11524 if (!UsesTFC) { 11525 // No uses of the result and not using TFC. Then do nothing. 11526 return Node; 11527 } 11528 // If the original dmask has one channel - then nothing to do 11529 if (OldBitsSet == 1) 11530 return Node; 11531 // Use an arbitrary dmask - required for the instruction to work 11532 NewDmask = 1; 11533 } 11534 // Abort if there's no change 11535 if (NewDmask == OldDmask) 11536 return Node; 11537 11538 unsigned BitsSet = countPopulation(NewDmask); 11539 11540 // Check for TFE or LWE - increase the number of channels by one to account 11541 // for the extra return value 11542 // This will need adjustment for D16 if this is also included in 11543 // adjustWriteMask (this function) but at present D16 are excluded. 11544 unsigned NewChannels = BitsSet + UsesTFC; 11545 11546 int NewOpcode = 11547 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11548 assert(NewOpcode != -1 && 11549 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11550 "failed to find equivalent MIMG op"); 11551 11552 // Adjust the writemask in the node 11553 SmallVector<SDValue, 12> Ops; 11554 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11555 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11556 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11557 11558 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11559 11560 MVT ResultVT = NewChannels == 1 ? 11561 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11562 NewChannels == 5 ? 8 : NewChannels); 11563 SDVTList NewVTList = HasChain ? 11564 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11565 11566 11567 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11568 NewVTList, Ops); 11569 11570 if (HasChain) { 11571 // Update chain. 11572 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11573 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11574 } 11575 11576 if (NewChannels == 1) { 11577 assert(Node->hasNUsesOfValue(1, 0)); 11578 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11579 SDLoc(Node), Users[Lane]->getValueType(0), 11580 SDValue(NewNode, 0)); 11581 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11582 return nullptr; 11583 } 11584 11585 // Update the users of the node with the new indices 11586 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11587 SDNode *User = Users[i]; 11588 if (!User) { 11589 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11590 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11591 if (i || !NoChannels) 11592 continue; 11593 } else { 11594 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11595 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11596 } 11597 11598 switch (Idx) { 11599 default: break; 11600 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11601 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11602 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11603 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11604 } 11605 } 11606 11607 DAG.RemoveDeadNode(Node); 11608 return nullptr; 11609 } 11610 11611 static bool isFrameIndexOp(SDValue Op) { 11612 if (Op.getOpcode() == ISD::AssertZext) 11613 Op = Op.getOperand(0); 11614 11615 return isa<FrameIndexSDNode>(Op); 11616 } 11617 11618 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11619 /// with frame index operands. 11620 /// LLVM assumes that inputs are to these instructions are registers. 11621 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11622 SelectionDAG &DAG) const { 11623 if (Node->getOpcode() == ISD::CopyToReg) { 11624 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11625 SDValue SrcVal = Node->getOperand(2); 11626 11627 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11628 // to try understanding copies to physical registers. 11629 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11630 SDLoc SL(Node); 11631 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11632 SDValue VReg = DAG.getRegister( 11633 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11634 11635 SDNode *Glued = Node->getGluedNode(); 11636 SDValue ToVReg 11637 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11638 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11639 SDValue ToResultReg 11640 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11641 VReg, ToVReg.getValue(1)); 11642 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11643 DAG.RemoveDeadNode(Node); 11644 return ToResultReg.getNode(); 11645 } 11646 } 11647 11648 SmallVector<SDValue, 8> Ops; 11649 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11650 if (!isFrameIndexOp(Node->getOperand(i))) { 11651 Ops.push_back(Node->getOperand(i)); 11652 continue; 11653 } 11654 11655 SDLoc DL(Node); 11656 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11657 Node->getOperand(i).getValueType(), 11658 Node->getOperand(i)), 0)); 11659 } 11660 11661 return DAG.UpdateNodeOperands(Node, Ops); 11662 } 11663 11664 /// Fold the instructions after selecting them. 11665 /// Returns null if users were already updated. 11666 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11667 SelectionDAG &DAG) const { 11668 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11669 unsigned Opcode = Node->getMachineOpcode(); 11670 11671 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11672 !TII->isGather4(Opcode) && 11673 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11674 return adjustWritemask(Node, DAG); 11675 } 11676 11677 if (Opcode == AMDGPU::INSERT_SUBREG || 11678 Opcode == AMDGPU::REG_SEQUENCE) { 11679 legalizeTargetIndependentNode(Node, DAG); 11680 return Node; 11681 } 11682 11683 switch (Opcode) { 11684 case AMDGPU::V_DIV_SCALE_F32_e64: 11685 case AMDGPU::V_DIV_SCALE_F64_e64: { 11686 // Satisfy the operand register constraint when one of the inputs is 11687 // undefined. Ordinarily each undef value will have its own implicit_def of 11688 // a vreg, so force these to use a single register. 11689 SDValue Src0 = Node->getOperand(1); 11690 SDValue Src1 = Node->getOperand(3); 11691 SDValue Src2 = Node->getOperand(5); 11692 11693 if ((Src0.isMachineOpcode() && 11694 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11695 (Src0 == Src1 || Src0 == Src2)) 11696 break; 11697 11698 MVT VT = Src0.getValueType().getSimpleVT(); 11699 const TargetRegisterClass *RC = 11700 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11701 11702 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11703 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11704 11705 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11706 UndefReg, Src0, SDValue()); 11707 11708 // src0 must be the same register as src1 or src2, even if the value is 11709 // undefined, so make sure we don't violate this constraint. 11710 if (Src0.isMachineOpcode() && 11711 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11712 if (Src1.isMachineOpcode() && 11713 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11714 Src0 = Src1; 11715 else if (Src2.isMachineOpcode() && 11716 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11717 Src0 = Src2; 11718 else { 11719 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11720 Src0 = UndefReg; 11721 Src1 = UndefReg; 11722 } 11723 } else 11724 break; 11725 11726 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11727 Ops[1] = Src0; 11728 Ops[3] = Src1; 11729 Ops[5] = Src2; 11730 Ops.push_back(ImpDef.getValue(1)); 11731 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11732 } 11733 default: 11734 break; 11735 } 11736 11737 return Node; 11738 } 11739 11740 // Any MIMG instructions that use tfe or lwe require an initialization of the 11741 // result register that will be written in the case of a memory access failure. 11742 // The required code is also added to tie this init code to the result of the 11743 // img instruction. 11744 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11745 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11746 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11747 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11748 MachineBasicBlock &MBB = *MI.getParent(); 11749 11750 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11751 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11752 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11753 11754 if (!TFE && !LWE) // intersect_ray 11755 return; 11756 11757 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11758 unsigned LWEVal = LWE->getImm(); 11759 unsigned D16Val = D16 ? D16->getImm() : 0; 11760 11761 if (!TFEVal && !LWEVal) 11762 return; 11763 11764 // At least one of TFE or LWE are non-zero 11765 // We have to insert a suitable initialization of the result value and 11766 // tie this to the dest of the image instruction. 11767 11768 const DebugLoc &DL = MI.getDebugLoc(); 11769 11770 int DstIdx = 11771 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11772 11773 // Calculate which dword we have to initialize to 0. 11774 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11775 11776 // check that dmask operand is found. 11777 assert(MO_Dmask && "Expected dmask operand in instruction"); 11778 11779 unsigned dmask = MO_Dmask->getImm(); 11780 // Determine the number of active lanes taking into account the 11781 // Gather4 special case 11782 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11783 11784 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11785 11786 unsigned InitIdx = 11787 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11788 11789 // Abandon attempt if the dst size isn't large enough 11790 // - this is in fact an error but this is picked up elsewhere and 11791 // reported correctly. 11792 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11793 if (DstSize < InitIdx) 11794 return; 11795 11796 // Create a register for the initialization value. 11797 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11798 unsigned NewDst = 0; // Final initialized value will be in here 11799 11800 // If PRTStrictNull feature is enabled (the default) then initialize 11801 // all the result registers to 0, otherwise just the error indication 11802 // register (VGPRn+1) 11803 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11804 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11805 11806 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11807 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11808 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11809 // Initialize dword 11810 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11811 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11812 .addImm(0); 11813 // Insert into the super-reg 11814 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11815 .addReg(PrevDst) 11816 .addReg(SubReg) 11817 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11818 11819 PrevDst = NewDst; 11820 } 11821 11822 // Add as an implicit operand 11823 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11824 11825 // Tie the just added implicit operand to the dst 11826 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11827 } 11828 11829 /// Assign the register class depending on the number of 11830 /// bits set in the writemask 11831 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11832 SDNode *Node) const { 11833 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11834 11835 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11836 11837 if (TII->isVOP3(MI.getOpcode())) { 11838 // Make sure constant bus requirements are respected. 11839 TII->legalizeOperandsVOP3(MRI, MI); 11840 11841 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11842 // This saves a chain-copy of registers and better balance register 11843 // use between vgpr and agpr as agpr tuples tend to be big. 11844 if (MI.getDesc().OpInfo) { 11845 unsigned Opc = MI.getOpcode(); 11846 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11847 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11848 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11849 if (I == -1) 11850 break; 11851 MachineOperand &Op = MI.getOperand(I); 11852 if (!Op.isReg() || !Op.getReg().isVirtual()) 11853 continue; 11854 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11855 if (!TRI->hasAGPRs(RC)) 11856 continue; 11857 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11858 if (!Src || !Src->isCopy() || 11859 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11860 continue; 11861 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11862 // All uses of agpr64 and agpr32 can also accept vgpr except for 11863 // v_accvgpr_read, but we do not produce agpr reads during selection, 11864 // so no use checks are needed. 11865 MRI.setRegClass(Op.getReg(), NewRC); 11866 } 11867 11868 // Resolve the rest of AV operands to AGPRs. 11869 if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) { 11870 if (Src2->isReg() && Src2->getReg().isVirtual()) { 11871 auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg()); 11872 if (TRI->isVectorSuperClass(RC)) { 11873 auto *NewRC = TRI->getEquivalentAGPRClass(RC); 11874 MRI.setRegClass(Src2->getReg(), NewRC); 11875 if (Src2->isTied()) 11876 MRI.setRegClass(MI.getOperand(0).getReg(), NewRC); 11877 } 11878 } 11879 } 11880 } 11881 11882 return; 11883 } 11884 11885 if (TII->isMIMG(MI)) { 11886 if (!MI.mayStore()) 11887 AddIMGInit(MI); 11888 TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::vaddr); 11889 } 11890 } 11891 11892 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11893 uint64_t Val) { 11894 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11895 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11896 } 11897 11898 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11899 const SDLoc &DL, 11900 SDValue Ptr) const { 11901 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11902 11903 // Build the half of the subregister with the constants before building the 11904 // full 128-bit register. If we are building multiple resource descriptors, 11905 // this will allow CSEing of the 2-component register. 11906 const SDValue Ops0[] = { 11907 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11908 buildSMovImm32(DAG, DL, 0), 11909 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11910 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11911 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11912 }; 11913 11914 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11915 MVT::v2i32, Ops0), 0); 11916 11917 // Combine the constants and the pointer. 11918 const SDValue Ops1[] = { 11919 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11920 Ptr, 11921 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11922 SubRegHi, 11923 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11924 }; 11925 11926 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11927 } 11928 11929 /// Return a resource descriptor with the 'Add TID' bit enabled 11930 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11931 /// of the resource descriptor) to create an offset, which is added to 11932 /// the resource pointer. 11933 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11934 SDValue Ptr, uint32_t RsrcDword1, 11935 uint64_t RsrcDword2And3) const { 11936 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11937 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11938 if (RsrcDword1) { 11939 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11940 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11941 0); 11942 } 11943 11944 SDValue DataLo = buildSMovImm32(DAG, DL, 11945 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11946 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11947 11948 const SDValue Ops[] = { 11949 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11950 PtrLo, 11951 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11952 PtrHi, 11953 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11954 DataLo, 11955 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11956 DataHi, 11957 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11958 }; 11959 11960 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11961 } 11962 11963 //===----------------------------------------------------------------------===// 11964 // SI Inline Assembly Support 11965 //===----------------------------------------------------------------------===// 11966 11967 std::pair<unsigned, const TargetRegisterClass *> 11968 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11969 StringRef Constraint, 11970 MVT VT) const { 11971 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11972 11973 const TargetRegisterClass *RC = nullptr; 11974 if (Constraint.size() == 1) { 11975 const unsigned BitWidth = VT.getSizeInBits(); 11976 switch (Constraint[0]) { 11977 default: 11978 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11979 case 's': 11980 case 'r': 11981 switch (BitWidth) { 11982 case 16: 11983 RC = &AMDGPU::SReg_32RegClass; 11984 break; 11985 case 64: 11986 RC = &AMDGPU::SGPR_64RegClass; 11987 break; 11988 default: 11989 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11990 if (!RC) 11991 return std::make_pair(0U, nullptr); 11992 break; 11993 } 11994 break; 11995 case 'v': 11996 switch (BitWidth) { 11997 case 16: 11998 RC = &AMDGPU::VGPR_32RegClass; 11999 break; 12000 default: 12001 RC = TRI->getVGPRClassForBitWidth(BitWidth); 12002 if (!RC) 12003 return std::make_pair(0U, nullptr); 12004 break; 12005 } 12006 break; 12007 case 'a': 12008 if (!Subtarget->hasMAIInsts()) 12009 break; 12010 switch (BitWidth) { 12011 case 16: 12012 RC = &AMDGPU::AGPR_32RegClass; 12013 break; 12014 default: 12015 RC = TRI->getAGPRClassForBitWidth(BitWidth); 12016 if (!RC) 12017 return std::make_pair(0U, nullptr); 12018 break; 12019 } 12020 break; 12021 } 12022 // We actually support i128, i16 and f16 as inline parameters 12023 // even if they are not reported as legal 12024 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 12025 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 12026 return std::make_pair(0U, RC); 12027 } 12028 12029 if (Constraint.startswith("{") && Constraint.endswith("}")) { 12030 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 12031 if (RegName.consume_front("v")) { 12032 RC = &AMDGPU::VGPR_32RegClass; 12033 } else if (RegName.consume_front("s")) { 12034 RC = &AMDGPU::SGPR_32RegClass; 12035 } else if (RegName.consume_front("a")) { 12036 RC = &AMDGPU::AGPR_32RegClass; 12037 } 12038 12039 if (RC) { 12040 uint32_t Idx; 12041 if (RegName.consume_front("[")) { 12042 uint32_t End; 12043 bool Failed = RegName.consumeInteger(10, Idx); 12044 Failed |= !RegName.consume_front(":"); 12045 Failed |= RegName.consumeInteger(10, End); 12046 Failed |= !RegName.consume_back("]"); 12047 if (!Failed) { 12048 uint32_t Width = (End - Idx + 1) * 32; 12049 MCRegister Reg = RC->getRegister(Idx); 12050 if (SIRegisterInfo::isVGPRClass(RC)) 12051 RC = TRI->getVGPRClassForBitWidth(Width); 12052 else if (SIRegisterInfo::isSGPRClass(RC)) 12053 RC = TRI->getSGPRClassForBitWidth(Width); 12054 else if (SIRegisterInfo::isAGPRClass(RC)) 12055 RC = TRI->getAGPRClassForBitWidth(Width); 12056 if (RC) { 12057 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC); 12058 return std::make_pair(Reg, RC); 12059 } 12060 } 12061 } else { 12062 bool Failed = RegName.getAsInteger(10, Idx); 12063 if (!Failed && Idx < RC->getNumRegs()) 12064 return std::make_pair(RC->getRegister(Idx), RC); 12065 } 12066 } 12067 } 12068 12069 auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 12070 if (Ret.first) 12071 Ret.second = TRI->getPhysRegClass(Ret.first); 12072 12073 return Ret; 12074 } 12075 12076 static bool isImmConstraint(StringRef Constraint) { 12077 if (Constraint.size() == 1) { 12078 switch (Constraint[0]) { 12079 default: break; 12080 case 'I': 12081 case 'J': 12082 case 'A': 12083 case 'B': 12084 case 'C': 12085 return true; 12086 } 12087 } else if (Constraint == "DA" || 12088 Constraint == "DB") { 12089 return true; 12090 } 12091 return false; 12092 } 12093 12094 SITargetLowering::ConstraintType 12095 SITargetLowering::getConstraintType(StringRef Constraint) const { 12096 if (Constraint.size() == 1) { 12097 switch (Constraint[0]) { 12098 default: break; 12099 case 's': 12100 case 'v': 12101 case 'a': 12102 return C_RegisterClass; 12103 } 12104 } 12105 if (isImmConstraint(Constraint)) { 12106 return C_Other; 12107 } 12108 return TargetLowering::getConstraintType(Constraint); 12109 } 12110 12111 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 12112 if (!AMDGPU::isInlinableIntLiteral(Val)) { 12113 Val = Val & maskTrailingOnes<uint64_t>(Size); 12114 } 12115 return Val; 12116 } 12117 12118 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 12119 std::string &Constraint, 12120 std::vector<SDValue> &Ops, 12121 SelectionDAG &DAG) const { 12122 if (isImmConstraint(Constraint)) { 12123 uint64_t Val; 12124 if (getAsmOperandConstVal(Op, Val) && 12125 checkAsmConstraintVal(Op, Constraint, Val)) { 12126 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 12127 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 12128 } 12129 } else { 12130 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12131 } 12132 } 12133 12134 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 12135 unsigned Size = Op.getScalarValueSizeInBits(); 12136 if (Size > 64) 12137 return false; 12138 12139 if (Size == 16 && !Subtarget->has16BitInsts()) 12140 return false; 12141 12142 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12143 Val = C->getSExtValue(); 12144 return true; 12145 } 12146 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 12147 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 12148 return true; 12149 } 12150 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 12151 if (Size != 16 || Op.getNumOperands() != 2) 12152 return false; 12153 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 12154 return false; 12155 if (ConstantSDNode *C = V->getConstantSplatNode()) { 12156 Val = C->getSExtValue(); 12157 return true; 12158 } 12159 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 12160 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 12161 return true; 12162 } 12163 } 12164 12165 return false; 12166 } 12167 12168 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 12169 const std::string &Constraint, 12170 uint64_t Val) const { 12171 if (Constraint.size() == 1) { 12172 switch (Constraint[0]) { 12173 case 'I': 12174 return AMDGPU::isInlinableIntLiteral(Val); 12175 case 'J': 12176 return isInt<16>(Val); 12177 case 'A': 12178 return checkAsmConstraintValA(Op, Val); 12179 case 'B': 12180 return isInt<32>(Val); 12181 case 'C': 12182 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 12183 AMDGPU::isInlinableIntLiteral(Val); 12184 default: 12185 break; 12186 } 12187 } else if (Constraint.size() == 2) { 12188 if (Constraint == "DA") { 12189 int64_t HiBits = static_cast<int32_t>(Val >> 32); 12190 int64_t LoBits = static_cast<int32_t>(Val); 12191 return checkAsmConstraintValA(Op, HiBits, 32) && 12192 checkAsmConstraintValA(Op, LoBits, 32); 12193 } 12194 if (Constraint == "DB") { 12195 return true; 12196 } 12197 } 12198 llvm_unreachable("Invalid asm constraint"); 12199 } 12200 12201 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 12202 uint64_t Val, 12203 unsigned MaxSize) const { 12204 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 12205 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 12206 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 12207 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 12208 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 12209 return true; 12210 } 12211 return false; 12212 } 12213 12214 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 12215 switch (UnalignedClassID) { 12216 case AMDGPU::VReg_64RegClassID: 12217 return AMDGPU::VReg_64_Align2RegClassID; 12218 case AMDGPU::VReg_96RegClassID: 12219 return AMDGPU::VReg_96_Align2RegClassID; 12220 case AMDGPU::VReg_128RegClassID: 12221 return AMDGPU::VReg_128_Align2RegClassID; 12222 case AMDGPU::VReg_160RegClassID: 12223 return AMDGPU::VReg_160_Align2RegClassID; 12224 case AMDGPU::VReg_192RegClassID: 12225 return AMDGPU::VReg_192_Align2RegClassID; 12226 case AMDGPU::VReg_224RegClassID: 12227 return AMDGPU::VReg_224_Align2RegClassID; 12228 case AMDGPU::VReg_256RegClassID: 12229 return AMDGPU::VReg_256_Align2RegClassID; 12230 case AMDGPU::VReg_512RegClassID: 12231 return AMDGPU::VReg_512_Align2RegClassID; 12232 case AMDGPU::VReg_1024RegClassID: 12233 return AMDGPU::VReg_1024_Align2RegClassID; 12234 case AMDGPU::AReg_64RegClassID: 12235 return AMDGPU::AReg_64_Align2RegClassID; 12236 case AMDGPU::AReg_96RegClassID: 12237 return AMDGPU::AReg_96_Align2RegClassID; 12238 case AMDGPU::AReg_128RegClassID: 12239 return AMDGPU::AReg_128_Align2RegClassID; 12240 case AMDGPU::AReg_160RegClassID: 12241 return AMDGPU::AReg_160_Align2RegClassID; 12242 case AMDGPU::AReg_192RegClassID: 12243 return AMDGPU::AReg_192_Align2RegClassID; 12244 case AMDGPU::AReg_256RegClassID: 12245 return AMDGPU::AReg_256_Align2RegClassID; 12246 case AMDGPU::AReg_512RegClassID: 12247 return AMDGPU::AReg_512_Align2RegClassID; 12248 case AMDGPU::AReg_1024RegClassID: 12249 return AMDGPU::AReg_1024_Align2RegClassID; 12250 default: 12251 return -1; 12252 } 12253 } 12254 12255 // Figure out which registers should be reserved for stack access. Only after 12256 // the function is legalized do we know all of the non-spill stack objects or if 12257 // calls are present. 12258 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 12259 MachineRegisterInfo &MRI = MF.getRegInfo(); 12260 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12261 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 12262 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12263 const SIInstrInfo *TII = ST.getInstrInfo(); 12264 12265 if (Info->isEntryFunction()) { 12266 // Callable functions have fixed registers used for stack access. 12267 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 12268 } 12269 12270 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 12271 Info->getStackPtrOffsetReg())); 12272 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 12273 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 12274 12275 // We need to worry about replacing the default register with itself in case 12276 // of MIR testcases missing the MFI. 12277 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 12278 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 12279 12280 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 12281 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 12282 12283 Info->limitOccupancy(MF); 12284 12285 if (ST.isWave32() && !MF.empty()) { 12286 for (auto &MBB : MF) { 12287 for (auto &MI : MBB) { 12288 TII->fixImplicitOperands(MI); 12289 } 12290 } 12291 } 12292 12293 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 12294 // classes if required. Ideally the register class constraints would differ 12295 // per-subtarget, but there's no easy way to achieve that right now. This is 12296 // not a problem for VGPRs because the correctly aligned VGPR class is implied 12297 // from using them as the register class for legal types. 12298 if (ST.needsAlignedVGPRs()) { 12299 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 12300 const Register Reg = Register::index2VirtReg(I); 12301 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 12302 if (!RC) 12303 continue; 12304 int NewClassID = getAlignedAGPRClassID(RC->getID()); 12305 if (NewClassID != -1) 12306 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 12307 } 12308 } 12309 12310 TargetLoweringBase::finalizeLowering(MF); 12311 } 12312 12313 void SITargetLowering::computeKnownBitsForFrameIndex( 12314 const int FI, KnownBits &Known, const MachineFunction &MF) const { 12315 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 12316 12317 // Set the high bits to zero based on the maximum allowed scratch size per 12318 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 12319 // calculation won't overflow, so assume the sign bit is never set. 12320 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 12321 } 12322 12323 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 12324 KnownBits &Known, unsigned Dim) { 12325 unsigned MaxValue = 12326 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 12327 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 12328 } 12329 12330 void SITargetLowering::computeKnownBitsForTargetInstr( 12331 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 12332 const MachineRegisterInfo &MRI, unsigned Depth) const { 12333 const MachineInstr *MI = MRI.getVRegDef(R); 12334 switch (MI->getOpcode()) { 12335 case AMDGPU::G_INTRINSIC: { 12336 switch (MI->getIntrinsicID()) { 12337 case Intrinsic::amdgcn_workitem_id_x: 12338 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 12339 break; 12340 case Intrinsic::amdgcn_workitem_id_y: 12341 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 12342 break; 12343 case Intrinsic::amdgcn_workitem_id_z: 12344 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 12345 break; 12346 case Intrinsic::amdgcn_mbcnt_lo: 12347 case Intrinsic::amdgcn_mbcnt_hi: { 12348 // These return at most the wavefront size - 1. 12349 unsigned Size = MRI.getType(R).getSizeInBits(); 12350 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 12351 break; 12352 } 12353 case Intrinsic::amdgcn_groupstaticsize: { 12354 // We can report everything over the maximum size as 0. We can't report 12355 // based on the actual size because we don't know if it's accurate or not 12356 // at any given point. 12357 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 12358 break; 12359 } 12360 } 12361 break; 12362 } 12363 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 12364 Known.Zero.setHighBits(24); 12365 break; 12366 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 12367 Known.Zero.setHighBits(16); 12368 break; 12369 } 12370 } 12371 12372 Align SITargetLowering::computeKnownAlignForTargetInstr( 12373 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 12374 unsigned Depth) const { 12375 const MachineInstr *MI = MRI.getVRegDef(R); 12376 switch (MI->getOpcode()) { 12377 case AMDGPU::G_INTRINSIC: 12378 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 12379 // FIXME: Can this move to generic code? What about the case where the call 12380 // site specifies a lower alignment? 12381 Intrinsic::ID IID = MI->getIntrinsicID(); 12382 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 12383 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 12384 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 12385 return *RetAlign; 12386 return Align(1); 12387 } 12388 default: 12389 return Align(1); 12390 } 12391 } 12392 12393 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12394 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 12395 const Align CacheLineAlign = Align(64); 12396 12397 // Pre-GFX10 target did not benefit from loop alignment 12398 if (!ML || DisableLoopAlignment || 12399 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 12400 getSubtarget()->hasInstFwdPrefetchBug()) 12401 return PrefAlign; 12402 12403 // On GFX10 I$ is 4 x 64 bytes cache lines. 12404 // By default prefetcher keeps one cache line behind and reads two ahead. 12405 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 12406 // behind and one ahead. 12407 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 12408 // If loop fits 64 bytes it always spans no more than two cache lines and 12409 // does not need an alignment. 12410 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 12411 // Else if loop is less or equal 192 bytes we need two lines behind. 12412 12413 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 12414 const MachineBasicBlock *Header = ML->getHeader(); 12415 if (Header->getAlignment() != PrefAlign) 12416 return Header->getAlignment(); // Already processed. 12417 12418 unsigned LoopSize = 0; 12419 for (const MachineBasicBlock *MBB : ML->blocks()) { 12420 // If inner loop block is aligned assume in average half of the alignment 12421 // size to be added as nops. 12422 if (MBB != Header) 12423 LoopSize += MBB->getAlignment().value() / 2; 12424 12425 for (const MachineInstr &MI : *MBB) { 12426 LoopSize += TII->getInstSizeInBytes(MI); 12427 if (LoopSize > 192) 12428 return PrefAlign; 12429 } 12430 } 12431 12432 if (LoopSize <= 64) 12433 return PrefAlign; 12434 12435 if (LoopSize <= 128) 12436 return CacheLineAlign; 12437 12438 // If any of parent loops is surrounded by prefetch instructions do not 12439 // insert new for inner loop, which would reset parent's settings. 12440 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 12441 if (MachineBasicBlock *Exit = P->getExitBlock()) { 12442 auto I = Exit->getFirstNonDebugInstr(); 12443 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 12444 return CacheLineAlign; 12445 } 12446 } 12447 12448 MachineBasicBlock *Pre = ML->getLoopPreheader(); 12449 MachineBasicBlock *Exit = ML->getExitBlock(); 12450 12451 if (Pre && Exit) { 12452 auto PreTerm = Pre->getFirstTerminator(); 12453 if (PreTerm == Pre->begin() || 12454 std::prev(PreTerm)->getOpcode() != AMDGPU::S_INST_PREFETCH) 12455 BuildMI(*Pre, PreTerm, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH)) 12456 .addImm(1); // prefetch 2 lines behind PC 12457 12458 auto ExitHead = Exit->getFirstNonDebugInstr(); 12459 if (ExitHead == Exit->end() || 12460 ExitHead->getOpcode() != AMDGPU::S_INST_PREFETCH) 12461 BuildMI(*Exit, ExitHead, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH)) 12462 .addImm(2); // prefetch 1 line behind PC 12463 } 12464 12465 return CacheLineAlign; 12466 } 12467 12468 LLVM_ATTRIBUTE_UNUSED 12469 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 12470 assert(N->getOpcode() == ISD::CopyFromReg); 12471 do { 12472 // Follow the chain until we find an INLINEASM node. 12473 N = N->getOperand(0).getNode(); 12474 if (N->getOpcode() == ISD::INLINEASM || 12475 N->getOpcode() == ISD::INLINEASM_BR) 12476 return true; 12477 } while (N->getOpcode() == ISD::CopyFromReg); 12478 return false; 12479 } 12480 12481 bool SITargetLowering::isSDNodeSourceOfDivergence( 12482 const SDNode *N, FunctionLoweringInfo *FLI, 12483 LegacyDivergenceAnalysis *KDA) const { 12484 switch (N->getOpcode()) { 12485 case ISD::CopyFromReg: { 12486 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 12487 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 12488 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12489 Register Reg = R->getReg(); 12490 12491 // FIXME: Why does this need to consider isLiveIn? 12492 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 12493 return !TRI->isSGPRReg(MRI, Reg); 12494 12495 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 12496 return KDA->isDivergent(V); 12497 12498 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 12499 return !TRI->isSGPRReg(MRI, Reg); 12500 } 12501 case ISD::LOAD: { 12502 const LoadSDNode *L = cast<LoadSDNode>(N); 12503 unsigned AS = L->getAddressSpace(); 12504 // A flat load may access private memory. 12505 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 12506 } 12507 case ISD::CALLSEQ_END: 12508 return true; 12509 case ISD::INTRINSIC_WO_CHAIN: 12510 return AMDGPU::isIntrinsicSourceOfDivergence( 12511 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 12512 case ISD::INTRINSIC_W_CHAIN: 12513 return AMDGPU::isIntrinsicSourceOfDivergence( 12514 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 12515 case AMDGPUISD::ATOMIC_CMP_SWAP: 12516 case AMDGPUISD::ATOMIC_INC: 12517 case AMDGPUISD::ATOMIC_DEC: 12518 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12519 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12520 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12521 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12522 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12523 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12524 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12525 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12526 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12527 case AMDGPUISD::BUFFER_ATOMIC_AND: 12528 case AMDGPUISD::BUFFER_ATOMIC_OR: 12529 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12530 case AMDGPUISD::BUFFER_ATOMIC_INC: 12531 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12532 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12533 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12534 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12535 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12536 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12537 // Target-specific read-modify-write atomics are sources of divergence. 12538 return true; 12539 default: 12540 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12541 // Generic read-modify-write atomics are sources of divergence. 12542 return A->readMem() && A->writeMem(); 12543 } 12544 return false; 12545 } 12546 } 12547 12548 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12549 EVT VT) const { 12550 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12551 case MVT::f32: 12552 return hasFP32Denormals(DAG.getMachineFunction()); 12553 case MVT::f64: 12554 case MVT::f16: 12555 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12556 default: 12557 return false; 12558 } 12559 } 12560 12561 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12562 MachineFunction &MF) const { 12563 switch (Ty.getScalarSizeInBits()) { 12564 case 32: 12565 return hasFP32Denormals(MF); 12566 case 64: 12567 case 16: 12568 return hasFP64FP16Denormals(MF); 12569 default: 12570 return false; 12571 } 12572 } 12573 12574 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12575 const SelectionDAG &DAG, 12576 bool SNaN, 12577 unsigned Depth) const { 12578 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12579 const MachineFunction &MF = DAG.getMachineFunction(); 12580 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12581 12582 if (Info->getMode().DX10Clamp) 12583 return true; // Clamped to 0. 12584 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12585 } 12586 12587 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12588 SNaN, Depth); 12589 } 12590 12591 // Global FP atomic instructions have a hardcoded FP mode and do not support 12592 // FP32 denormals, and only support v2f16 denormals. 12593 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12594 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12595 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12596 if (&Flt == &APFloat::IEEEsingle()) 12597 return DenormMode == DenormalMode::getPreserveSign(); 12598 return DenormMode == DenormalMode::getIEEE(); 12599 } 12600 12601 TargetLowering::AtomicExpansionKind 12602 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12603 unsigned AS = RMW->getPointerAddressSpace(); 12604 if (AS == AMDGPUAS::PRIVATE_ADDRESS) 12605 return AtomicExpansionKind::NotAtomic; 12606 12607 auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) { 12608 OptimizationRemarkEmitter ORE(RMW->getFunction()); 12609 LLVMContext &Ctx = RMW->getFunction()->getContext(); 12610 SmallVector<StringRef> SSNs; 12611 Ctx.getSyncScopeNames(SSNs); 12612 auto MemScope = SSNs[RMW->getSyncScopeID()].empty() 12613 ? "system" 12614 : SSNs[RMW->getSyncScopeID()]; 12615 ORE.emit([&]() { 12616 return OptimizationRemark(DEBUG_TYPE, "Passed", RMW) 12617 << "Hardware instruction generated for atomic " 12618 << RMW->getOperationName(RMW->getOperation()) 12619 << " operation at memory scope " << MemScope 12620 << " due to an unsafe request."; 12621 }); 12622 return Kind; 12623 }; 12624 12625 switch (RMW->getOperation()) { 12626 case AtomicRMWInst::FAdd: { 12627 Type *Ty = RMW->getType(); 12628 12629 // We don't have a way to support 16-bit atomics now, so just leave them 12630 // as-is. 12631 if (Ty->isHalfTy()) 12632 return AtomicExpansionKind::None; 12633 12634 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12635 return AtomicExpansionKind::CmpXChg; 12636 12637 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12638 Subtarget->hasAtomicFaddNoRtnInsts()) { 12639 if (Subtarget->hasGFX940Insts()) 12640 return AtomicExpansionKind::None; 12641 12642 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12643 // floating point atomic instructions. May generate more efficient code, 12644 // but may not respect rounding and denormal modes, and may give incorrect 12645 // results for certain memory destinations. 12646 if (RMW->getFunction() 12647 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12648 .getValueAsString() != "true") 12649 return AtomicExpansionKind::CmpXChg; 12650 12651 if (Subtarget->hasGFX90AInsts()) { 12652 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) 12653 return AtomicExpansionKind::CmpXChg; 12654 12655 auto SSID = RMW->getSyncScopeID(); 12656 if (SSID == SyncScope::System || 12657 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12658 return AtomicExpansionKind::CmpXChg; 12659 12660 return ReportUnsafeHWInst(AtomicExpansionKind::None); 12661 } 12662 12663 if (AS == AMDGPUAS::FLAT_ADDRESS) 12664 return AtomicExpansionKind::CmpXChg; 12665 12666 return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12667 : AtomicExpansionKind::CmpXChg; 12668 } 12669 12670 // DS FP atomics do respect the denormal mode, but the rounding mode is 12671 // fixed to round-to-nearest-even. 12672 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12673 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) { 12674 if (!Ty->isDoubleTy()) 12675 return AtomicExpansionKind::None; 12676 12677 if (fpModeMatchesGlobalFPAtomicMode(RMW)) 12678 return AtomicExpansionKind::None; 12679 12680 return RMW->getFunction() 12681 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12682 .getValueAsString() == "true" 12683 ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12684 : AtomicExpansionKind::CmpXChg; 12685 } 12686 12687 return AtomicExpansionKind::CmpXChg; 12688 } 12689 default: 12690 break; 12691 } 12692 12693 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12694 } 12695 12696 TargetLowering::AtomicExpansionKind 12697 SITargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 12698 return LI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12699 ? AtomicExpansionKind::NotAtomic 12700 : AtomicExpansionKind::None; 12701 } 12702 12703 TargetLowering::AtomicExpansionKind 12704 SITargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 12705 return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12706 ? AtomicExpansionKind::NotAtomic 12707 : AtomicExpansionKind::None; 12708 } 12709 12710 TargetLowering::AtomicExpansionKind 12711 SITargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CmpX) const { 12712 return CmpX->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12713 ? AtomicExpansionKind::NotAtomic 12714 : AtomicExpansionKind::None; 12715 } 12716 12717 const TargetRegisterClass * 12718 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12719 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12720 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12721 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12722 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12723 : &AMDGPU::SReg_32RegClass; 12724 if (!TRI->isSGPRClass(RC) && !isDivergent) 12725 return TRI->getEquivalentSGPRClass(RC); 12726 else if (TRI->isSGPRClass(RC) && isDivergent) 12727 return TRI->getEquivalentVGPRClass(RC); 12728 12729 return RC; 12730 } 12731 12732 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12733 // uniform values (as produced by the mask results of control flow intrinsics) 12734 // used outside of divergent blocks. The phi users need to also be treated as 12735 // always uniform. 12736 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12737 unsigned WaveSize) { 12738 // FIXME: We assume we never cast the mask results of a control flow 12739 // intrinsic. 12740 // Early exit if the type won't be consistent as a compile time hack. 12741 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12742 if (!IT || IT->getBitWidth() != WaveSize) 12743 return false; 12744 12745 if (!isa<Instruction>(V)) 12746 return false; 12747 if (!Visited.insert(V).second) 12748 return false; 12749 bool Result = false; 12750 for (auto U : V->users()) { 12751 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12752 if (V == U->getOperand(1)) { 12753 switch (Intrinsic->getIntrinsicID()) { 12754 default: 12755 Result = false; 12756 break; 12757 case Intrinsic::amdgcn_if_break: 12758 case Intrinsic::amdgcn_if: 12759 case Intrinsic::amdgcn_else: 12760 Result = true; 12761 break; 12762 } 12763 } 12764 if (V == U->getOperand(0)) { 12765 switch (Intrinsic->getIntrinsicID()) { 12766 default: 12767 Result = false; 12768 break; 12769 case Intrinsic::amdgcn_end_cf: 12770 case Intrinsic::amdgcn_loop: 12771 Result = true; 12772 break; 12773 } 12774 } 12775 } else { 12776 Result = hasCFUser(U, Visited, WaveSize); 12777 } 12778 if (Result) 12779 break; 12780 } 12781 return Result; 12782 } 12783 12784 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12785 const Value *V) const { 12786 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12787 if (CI->isInlineAsm()) { 12788 // FIXME: This cannot give a correct answer. This should only trigger in 12789 // the case where inline asm returns mixed SGPR and VGPR results, used 12790 // outside the defining block. We don't have a specific result to 12791 // consider, so this assumes if any value is SGPR, the overall register 12792 // also needs to be SGPR. 12793 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12794 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12795 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12796 for (auto &TC : TargetConstraints) { 12797 if (TC.Type == InlineAsm::isOutput) { 12798 ComputeConstraintToUse(TC, SDValue()); 12799 const TargetRegisterClass *RC = getRegForInlineAsmConstraint( 12800 SIRI, TC.ConstraintCode, TC.ConstraintVT).second; 12801 if (RC && SIRI->isSGPRClass(RC)) 12802 return true; 12803 } 12804 } 12805 } 12806 } 12807 SmallPtrSet<const Value *, 16> Visited; 12808 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12809 } 12810 12811 std::pair<InstructionCost, MVT> 12812 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12813 Type *Ty) const { 12814 std::pair<InstructionCost, MVT> Cost = 12815 TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12816 auto Size = DL.getTypeSizeInBits(Ty); 12817 // Maximum load or store can handle 8 dwords for scalar and 4 for 12818 // vector ALU. Let's assume anything above 8 dwords is expensive 12819 // even if legal. 12820 if (Size <= 256) 12821 return Cost; 12822 12823 Cost.first += (Size + 255) / 256; 12824 return Cost; 12825 } 12826 12827 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const { 12828 SDNode::use_iterator I = N->use_begin(), E = N->use_end(); 12829 for (; I != E; ++I) { 12830 if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) { 12831 if (getBasePtrIndex(M) == I.getOperandNo()) 12832 return true; 12833 } 12834 } 12835 return false; 12836 } 12837 12838 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0, 12839 SDValue N1) const { 12840 if (!N0.hasOneUse()) 12841 return false; 12842 // Take care of the opportunity to keep N0 uniform 12843 if (N0->isDivergent() || !N1->isDivergent()) 12844 return true; 12845 // Check if we have a good chance to form the memory access pattern with the 12846 // base and offset 12847 return (DAG.isBaseWithConstantOffset(N0) && 12848 hasMemSDNodeUser(*N0->use_begin())); 12849 } 12850 12851 MachineMemOperand::Flags 12852 SITargetLowering::getTargetMMOFlags(const Instruction &I) const { 12853 // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load. 12854 if (I.getMetadata("amdgpu.noclobber")) 12855 return MONoClobber; 12856 return MachineMemOperand::MONone; 12857 } 12858