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::enableAggressiveFMAFusion(EVT VT) const { 4366 // This currently forces unfolding various combinations of fsub into fma with 4367 // free fneg'd operands. As long as we have fast FMA (controlled by 4368 // isFMAFasterThanFMulAndFAdd), we should perform these. 4369 4370 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4371 // most of these combines appear to be cycle neutral but save on instruction 4372 // count / code size. 4373 return true; 4374 } 4375 4376 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; } 4377 4378 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4379 EVT VT) const { 4380 if (!VT.isVector()) { 4381 return MVT::i1; 4382 } 4383 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4384 } 4385 4386 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4387 // TODO: Should i16 be used always if legal? For now it would force VALU 4388 // shifts. 4389 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4390 } 4391 4392 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4393 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4394 ? Ty.changeElementSize(16) 4395 : Ty.changeElementSize(32); 4396 } 4397 4398 // Answering this is somewhat tricky and depends on the specific device which 4399 // have different rates for fma or all f64 operations. 4400 // 4401 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4402 // regardless of which device (although the number of cycles differs between 4403 // devices), so it is always profitable for f64. 4404 // 4405 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4406 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4407 // which we can always do even without fused FP ops since it returns the same 4408 // result as the separate operations and since it is always full 4409 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4410 // however does not support denormals, so we do report fma as faster if we have 4411 // a fast fma device and require denormals. 4412 // 4413 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4414 EVT VT) const { 4415 VT = VT.getScalarType(); 4416 4417 switch (VT.getSimpleVT().SimpleTy) { 4418 case MVT::f32: { 4419 // If mad is not available this depends only on if f32 fma is full rate. 4420 if (!Subtarget->hasMadMacF32Insts()) 4421 return Subtarget->hasFastFMAF32(); 4422 4423 // Otherwise f32 mad is always full rate and returns the same result as 4424 // the separate operations so should be preferred over fma. 4425 // However does not support denormals. 4426 if (hasFP32Denormals(MF)) 4427 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4428 4429 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4430 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4431 } 4432 case MVT::f64: 4433 return true; 4434 case MVT::f16: 4435 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4436 default: 4437 break; 4438 } 4439 4440 return false; 4441 } 4442 4443 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4444 LLT Ty) const { 4445 switch (Ty.getScalarSizeInBits()) { 4446 case 16: 4447 return isFMAFasterThanFMulAndFAdd(MF, MVT::f16); 4448 case 32: 4449 return isFMAFasterThanFMulAndFAdd(MF, MVT::f32); 4450 case 64: 4451 return isFMAFasterThanFMulAndFAdd(MF, MVT::f64); 4452 default: 4453 break; 4454 } 4455 4456 return false; 4457 } 4458 4459 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const { 4460 if (!Ty.isScalar()) 4461 return false; 4462 4463 if (Ty.getScalarSizeInBits() == 16) 4464 return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF()); 4465 if (Ty.getScalarSizeInBits() == 32) 4466 return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF()); 4467 4468 return false; 4469 } 4470 4471 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4472 const SDNode *N) const { 4473 // TODO: Check future ftz flag 4474 // v_mad_f32/v_mac_f32 do not support denormals. 4475 EVT VT = N->getValueType(0); 4476 if (VT == MVT::f32) 4477 return Subtarget->hasMadMacF32Insts() && 4478 !hasFP32Denormals(DAG.getMachineFunction()); 4479 if (VT == MVT::f16) { 4480 return Subtarget->hasMadF16() && 4481 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4482 } 4483 4484 return false; 4485 } 4486 4487 //===----------------------------------------------------------------------===// 4488 // Custom DAG Lowering Operations 4489 //===----------------------------------------------------------------------===// 4490 4491 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4492 // wider vector type is legal. 4493 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4494 SelectionDAG &DAG) const { 4495 unsigned Opc = Op.getOpcode(); 4496 EVT VT = Op.getValueType(); 4497 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4498 4499 SDValue Lo, Hi; 4500 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4501 4502 SDLoc SL(Op); 4503 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4504 Op->getFlags()); 4505 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4506 Op->getFlags()); 4507 4508 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4509 } 4510 4511 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4512 // wider vector type is legal. 4513 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4514 SelectionDAG &DAG) const { 4515 unsigned Opc = Op.getOpcode(); 4516 EVT VT = Op.getValueType(); 4517 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4518 VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 || 4519 VT == MVT::v16f32 || VT == MVT::v32f32); 4520 4521 SDValue Lo0, Hi0; 4522 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4523 SDValue Lo1, Hi1; 4524 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4525 4526 SDLoc SL(Op); 4527 4528 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4529 Op->getFlags()); 4530 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4531 Op->getFlags()); 4532 4533 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4534 } 4535 4536 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4537 SelectionDAG &DAG) const { 4538 unsigned Opc = Op.getOpcode(); 4539 EVT VT = Op.getValueType(); 4540 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 || 4541 VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 || 4542 VT == MVT::v16f32 || VT == MVT::v32f32); 4543 4544 SDValue Lo0, Hi0; 4545 SDValue Op0 = Op.getOperand(0); 4546 std::tie(Lo0, Hi0) = Op0.getValueType().isVector() 4547 ? DAG.SplitVectorOperand(Op.getNode(), 0) 4548 : std::make_pair(Op0, Op0); 4549 SDValue Lo1, Hi1; 4550 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4551 SDValue Lo2, Hi2; 4552 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4553 4554 SDLoc SL(Op); 4555 auto ResVT = DAG.GetSplitDestVTs(VT); 4556 4557 SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2, 4558 Op->getFlags()); 4559 SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2, 4560 Op->getFlags()); 4561 4562 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4563 } 4564 4565 4566 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4567 switch (Op.getOpcode()) { 4568 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4569 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4570 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4571 case ISD::LOAD: { 4572 SDValue Result = LowerLOAD(Op, DAG); 4573 assert((!Result.getNode() || 4574 Result.getNode()->getNumValues() == 2) && 4575 "Load should return a value and a chain"); 4576 return Result; 4577 } 4578 4579 case ISD::FSIN: 4580 case ISD::FCOS: 4581 return LowerTrig(Op, DAG); 4582 case ISD::SELECT: return LowerSELECT(Op, DAG); 4583 case ISD::FDIV: return LowerFDIV(Op, DAG); 4584 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4585 case ISD::STORE: return LowerSTORE(Op, DAG); 4586 case ISD::GlobalAddress: { 4587 MachineFunction &MF = DAG.getMachineFunction(); 4588 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4589 return LowerGlobalAddress(MFI, Op, DAG); 4590 } 4591 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4592 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4593 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4594 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4595 case ISD::INSERT_SUBVECTOR: 4596 return lowerINSERT_SUBVECTOR(Op, DAG); 4597 case ISD::INSERT_VECTOR_ELT: 4598 return lowerINSERT_VECTOR_ELT(Op, DAG); 4599 case ISD::EXTRACT_VECTOR_ELT: 4600 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4601 case ISD::VECTOR_SHUFFLE: 4602 return lowerVECTOR_SHUFFLE(Op, DAG); 4603 case ISD::SCALAR_TO_VECTOR: 4604 return lowerSCALAR_TO_VECTOR(Op, DAG); 4605 case ISD::BUILD_VECTOR: 4606 return lowerBUILD_VECTOR(Op, DAG); 4607 case ISD::FP_ROUND: 4608 return lowerFP_ROUND(Op, DAG); 4609 case ISD::FPTRUNC_ROUND: { 4610 unsigned Opc; 4611 SDLoc DL(Op); 4612 4613 if (Op.getOperand(0)->getValueType(0) != MVT::f32) 4614 return SDValue(); 4615 4616 // Get the rounding mode from the last operand 4617 int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4618 if (RoundMode == (int)RoundingMode::TowardPositive) 4619 Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD; 4620 else if (RoundMode == (int)RoundingMode::TowardNegative) 4621 Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD; 4622 else 4623 return SDValue(); 4624 4625 return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0)); 4626 } 4627 case ISD::TRAP: 4628 return lowerTRAP(Op, DAG); 4629 case ISD::DEBUGTRAP: 4630 return lowerDEBUGTRAP(Op, DAG); 4631 case ISD::FABS: 4632 case ISD::FNEG: 4633 case ISD::FCANONICALIZE: 4634 case ISD::BSWAP: 4635 return splitUnaryVectorOp(Op, DAG); 4636 case ISD::FMINNUM: 4637 case ISD::FMAXNUM: 4638 return lowerFMINNUM_FMAXNUM(Op, DAG); 4639 case ISD::FMA: 4640 return splitTernaryVectorOp(Op, DAG); 4641 case ISD::FP_TO_SINT: 4642 case ISD::FP_TO_UINT: 4643 return LowerFP_TO_INT(Op, DAG); 4644 case ISD::SHL: 4645 case ISD::SRA: 4646 case ISD::SRL: 4647 case ISD::ADD: 4648 case ISD::SUB: 4649 case ISD::MUL: 4650 case ISD::SMIN: 4651 case ISD::SMAX: 4652 case ISD::UMIN: 4653 case ISD::UMAX: 4654 case ISD::FADD: 4655 case ISD::FMUL: 4656 case ISD::FMINNUM_IEEE: 4657 case ISD::FMAXNUM_IEEE: 4658 case ISD::UADDSAT: 4659 case ISD::USUBSAT: 4660 case ISD::SADDSAT: 4661 case ISD::SSUBSAT: 4662 return splitBinaryVectorOp(Op, DAG); 4663 case ISD::SMULO: 4664 case ISD::UMULO: 4665 return lowerXMULO(Op, DAG); 4666 case ISD::SMUL_LOHI: 4667 case ISD::UMUL_LOHI: 4668 return lowerXMUL_LOHI(Op, DAG); 4669 case ISD::DYNAMIC_STACKALLOC: 4670 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4671 } 4672 return SDValue(); 4673 } 4674 4675 // Used for D16: Casts the result of an instruction into the right vector, 4676 // packs values if loads return unpacked values. 4677 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4678 const SDLoc &DL, 4679 SelectionDAG &DAG, bool Unpacked) { 4680 if (!LoadVT.isVector()) 4681 return Result; 4682 4683 // Cast back to the original packed type or to a larger type that is a 4684 // multiple of 32 bit for D16. Widening the return type is a required for 4685 // legalization. 4686 EVT FittingLoadVT = LoadVT; 4687 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4688 FittingLoadVT = 4689 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4690 LoadVT.getVectorNumElements() + 1); 4691 } 4692 4693 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4694 // Truncate to v2i16/v4i16. 4695 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4696 4697 // Workaround legalizer not scalarizing truncate after vector op 4698 // legalization but not creating intermediate vector trunc. 4699 SmallVector<SDValue, 4> Elts; 4700 DAG.ExtractVectorElements(Result, Elts); 4701 for (SDValue &Elt : Elts) 4702 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4703 4704 // Pad illegal v1i16/v3fi6 to v4i16 4705 if ((LoadVT.getVectorNumElements() % 2) == 1) 4706 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4707 4708 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4709 4710 // Bitcast to original type (v2f16/v4f16). 4711 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4712 } 4713 4714 // Cast back to the original packed type. 4715 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4716 } 4717 4718 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4719 MemSDNode *M, 4720 SelectionDAG &DAG, 4721 ArrayRef<SDValue> Ops, 4722 bool IsIntrinsic) const { 4723 SDLoc DL(M); 4724 4725 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4726 EVT LoadVT = M->getValueType(0); 4727 4728 EVT EquivLoadVT = LoadVT; 4729 if (LoadVT.isVector()) { 4730 if (Unpacked) { 4731 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4732 LoadVT.getVectorNumElements()); 4733 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4734 // Widen v3f16 to legal type 4735 EquivLoadVT = 4736 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4737 LoadVT.getVectorNumElements() + 1); 4738 } 4739 } 4740 4741 // Change from v4f16/v2f16 to EquivLoadVT. 4742 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4743 4744 SDValue Load 4745 = DAG.getMemIntrinsicNode( 4746 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4747 VTList, Ops, M->getMemoryVT(), 4748 M->getMemOperand()); 4749 4750 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4751 4752 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4753 } 4754 4755 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4756 SelectionDAG &DAG, 4757 ArrayRef<SDValue> Ops) const { 4758 SDLoc DL(M); 4759 EVT LoadVT = M->getValueType(0); 4760 EVT EltType = LoadVT.getScalarType(); 4761 EVT IntVT = LoadVT.changeTypeToInteger(); 4762 4763 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4764 4765 unsigned Opc = 4766 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4767 4768 if (IsD16) { 4769 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4770 } 4771 4772 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4773 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4774 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4775 4776 if (isTypeLegal(LoadVT)) { 4777 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4778 M->getMemOperand(), DAG); 4779 } 4780 4781 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4782 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4783 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4784 M->getMemOperand(), DAG); 4785 return DAG.getMergeValues( 4786 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4787 DL); 4788 } 4789 4790 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4791 SDNode *N, SelectionDAG &DAG) { 4792 EVT VT = N->getValueType(0); 4793 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4794 unsigned CondCode = CD->getZExtValue(); 4795 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4796 return DAG.getUNDEF(VT); 4797 4798 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4799 4800 SDValue LHS = N->getOperand(1); 4801 SDValue RHS = N->getOperand(2); 4802 4803 SDLoc DL(N); 4804 4805 EVT CmpVT = LHS.getValueType(); 4806 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4807 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4808 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4809 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4810 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4811 } 4812 4813 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4814 4815 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4816 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4817 4818 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4819 DAG.getCondCode(CCOpcode)); 4820 if (VT.bitsEq(CCVT)) 4821 return SetCC; 4822 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4823 } 4824 4825 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4826 SDNode *N, SelectionDAG &DAG) { 4827 EVT VT = N->getValueType(0); 4828 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4829 4830 unsigned CondCode = CD->getZExtValue(); 4831 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4832 return DAG.getUNDEF(VT); 4833 4834 SDValue Src0 = N->getOperand(1); 4835 SDValue Src1 = N->getOperand(2); 4836 EVT CmpVT = Src0.getValueType(); 4837 SDLoc SL(N); 4838 4839 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4840 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4841 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4842 } 4843 4844 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4845 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4846 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4847 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4848 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4849 Src1, DAG.getCondCode(CCOpcode)); 4850 if (VT.bitsEq(CCVT)) 4851 return SetCC; 4852 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4853 } 4854 4855 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4856 SelectionDAG &DAG) { 4857 EVT VT = N->getValueType(0); 4858 SDValue Src = N->getOperand(1); 4859 SDLoc SL(N); 4860 4861 if (Src.getOpcode() == ISD::SETCC) { 4862 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4863 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4864 Src.getOperand(1), Src.getOperand(2)); 4865 } 4866 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4867 // (ballot 0) -> 0 4868 if (Arg->isZero()) 4869 return DAG.getConstant(0, SL, VT); 4870 4871 // (ballot 1) -> EXEC/EXEC_LO 4872 if (Arg->isOne()) { 4873 Register Exec; 4874 if (VT.getScalarSizeInBits() == 32) 4875 Exec = AMDGPU::EXEC_LO; 4876 else if (VT.getScalarSizeInBits() == 64) 4877 Exec = AMDGPU::EXEC; 4878 else 4879 return SDValue(); 4880 4881 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4882 } 4883 } 4884 4885 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4886 // ISD::SETNE) 4887 return DAG.getNode( 4888 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4889 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4890 } 4891 4892 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4893 SmallVectorImpl<SDValue> &Results, 4894 SelectionDAG &DAG) const { 4895 switch (N->getOpcode()) { 4896 case ISD::INSERT_VECTOR_ELT: { 4897 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4898 Results.push_back(Res); 4899 return; 4900 } 4901 case ISD::EXTRACT_VECTOR_ELT: { 4902 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4903 Results.push_back(Res); 4904 return; 4905 } 4906 case ISD::INTRINSIC_WO_CHAIN: { 4907 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4908 switch (IID) { 4909 case Intrinsic::amdgcn_cvt_pkrtz: { 4910 SDValue Src0 = N->getOperand(1); 4911 SDValue Src1 = N->getOperand(2); 4912 SDLoc SL(N); 4913 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4914 Src0, Src1); 4915 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4916 return; 4917 } 4918 case Intrinsic::amdgcn_cvt_pknorm_i16: 4919 case Intrinsic::amdgcn_cvt_pknorm_u16: 4920 case Intrinsic::amdgcn_cvt_pk_i16: 4921 case Intrinsic::amdgcn_cvt_pk_u16: { 4922 SDValue Src0 = N->getOperand(1); 4923 SDValue Src1 = N->getOperand(2); 4924 SDLoc SL(N); 4925 unsigned Opcode; 4926 4927 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4928 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4929 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4930 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4931 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4932 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4933 else 4934 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4935 4936 EVT VT = N->getValueType(0); 4937 if (isTypeLegal(VT)) 4938 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4939 else { 4940 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4941 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4942 } 4943 return; 4944 } 4945 } 4946 break; 4947 } 4948 case ISD::INTRINSIC_W_CHAIN: { 4949 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4950 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4951 // FIXME: Hacky 4952 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4953 Results.push_back(Res.getOperand(I)); 4954 } 4955 } else { 4956 Results.push_back(Res); 4957 Results.push_back(Res.getValue(1)); 4958 } 4959 return; 4960 } 4961 4962 break; 4963 } 4964 case ISD::SELECT: { 4965 SDLoc SL(N); 4966 EVT VT = N->getValueType(0); 4967 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4968 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4969 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4970 4971 EVT SelectVT = NewVT; 4972 if (NewVT.bitsLT(MVT::i32)) { 4973 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4974 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4975 SelectVT = MVT::i32; 4976 } 4977 4978 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4979 N->getOperand(0), LHS, RHS); 4980 4981 if (NewVT != SelectVT) 4982 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4983 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4984 return; 4985 } 4986 case ISD::FNEG: { 4987 if (N->getValueType(0) != MVT::v2f16) 4988 break; 4989 4990 SDLoc SL(N); 4991 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4992 4993 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4994 BC, 4995 DAG.getConstant(0x80008000, SL, MVT::i32)); 4996 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4997 return; 4998 } 4999 case ISD::FABS: { 5000 if (N->getValueType(0) != MVT::v2f16) 5001 break; 5002 5003 SDLoc SL(N); 5004 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5005 5006 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 5007 BC, 5008 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 5009 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5010 return; 5011 } 5012 default: 5013 break; 5014 } 5015 } 5016 5017 /// Helper function for LowerBRCOND 5018 static SDNode *findUser(SDValue Value, unsigned Opcode) { 5019 5020 SDNode *Parent = Value.getNode(); 5021 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 5022 I != E; ++I) { 5023 5024 if (I.getUse().get() != Value) 5025 continue; 5026 5027 if (I->getOpcode() == Opcode) 5028 return *I; 5029 } 5030 return nullptr; 5031 } 5032 5033 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 5034 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 5035 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 5036 case Intrinsic::amdgcn_if: 5037 return AMDGPUISD::IF; 5038 case Intrinsic::amdgcn_else: 5039 return AMDGPUISD::ELSE; 5040 case Intrinsic::amdgcn_loop: 5041 return AMDGPUISD::LOOP; 5042 case Intrinsic::amdgcn_end_cf: 5043 llvm_unreachable("should not occur"); 5044 default: 5045 return 0; 5046 } 5047 } 5048 5049 // break, if_break, else_break are all only used as inputs to loop, not 5050 // directly as branch conditions. 5051 return 0; 5052 } 5053 5054 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 5055 const Triple &TT = getTargetMachine().getTargetTriple(); 5056 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5057 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5058 AMDGPU::shouldEmitConstantsToTextSection(TT); 5059 } 5060 5061 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 5062 // FIXME: Either avoid relying on address space here or change the default 5063 // address space for functions to avoid the explicit check. 5064 return (GV->getValueType()->isFunctionTy() || 5065 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 5066 !shouldEmitFixup(GV) && 5067 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 5068 } 5069 5070 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 5071 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 5072 } 5073 5074 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 5075 if (!GV->hasExternalLinkage()) 5076 return true; 5077 5078 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5079 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5080 } 5081 5082 /// This transforms the control flow intrinsics to get the branch destination as 5083 /// last parameter, also switches branch target with BR if the need arise 5084 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5085 SelectionDAG &DAG) const { 5086 SDLoc DL(BRCOND); 5087 5088 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5089 SDValue Target = BRCOND.getOperand(2); 5090 SDNode *BR = nullptr; 5091 SDNode *SetCC = nullptr; 5092 5093 if (Intr->getOpcode() == ISD::SETCC) { 5094 // As long as we negate the condition everything is fine 5095 SetCC = Intr; 5096 Intr = SetCC->getOperand(0).getNode(); 5097 5098 } else { 5099 // Get the target from BR if we don't negate the condition 5100 BR = findUser(BRCOND, ISD::BR); 5101 assert(BR && "brcond missing unconditional branch user"); 5102 Target = BR->getOperand(1); 5103 } 5104 5105 unsigned CFNode = isCFIntrinsic(Intr); 5106 if (CFNode == 0) { 5107 // This is a uniform branch so we don't need to legalize. 5108 return BRCOND; 5109 } 5110 5111 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5112 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5113 5114 assert(!SetCC || 5115 (SetCC->getConstantOperandVal(1) == 1 && 5116 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5117 ISD::SETNE)); 5118 5119 // operands of the new intrinsic call 5120 SmallVector<SDValue, 4> Ops; 5121 if (HaveChain) 5122 Ops.push_back(BRCOND.getOperand(0)); 5123 5124 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5125 Ops.push_back(Target); 5126 5127 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5128 5129 // build the new intrinsic call 5130 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5131 5132 if (!HaveChain) { 5133 SDValue Ops[] = { 5134 SDValue(Result, 0), 5135 BRCOND.getOperand(0) 5136 }; 5137 5138 Result = DAG.getMergeValues(Ops, DL).getNode(); 5139 } 5140 5141 if (BR) { 5142 // Give the branch instruction our target 5143 SDValue Ops[] = { 5144 BR->getOperand(0), 5145 BRCOND.getOperand(2) 5146 }; 5147 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5148 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5149 } 5150 5151 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5152 5153 // Copy the intrinsic results to registers 5154 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5155 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5156 if (!CopyToReg) 5157 continue; 5158 5159 Chain = DAG.getCopyToReg( 5160 Chain, DL, 5161 CopyToReg->getOperand(1), 5162 SDValue(Result, i - 1), 5163 SDValue()); 5164 5165 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5166 } 5167 5168 // Remove the old intrinsic from the chain 5169 DAG.ReplaceAllUsesOfValueWith( 5170 SDValue(Intr, Intr->getNumValues() - 1), 5171 Intr->getOperand(0)); 5172 5173 return Chain; 5174 } 5175 5176 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5177 SelectionDAG &DAG) const { 5178 MVT VT = Op.getSimpleValueType(); 5179 SDLoc DL(Op); 5180 // Checking the depth 5181 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5182 return DAG.getConstant(0, DL, VT); 5183 5184 MachineFunction &MF = DAG.getMachineFunction(); 5185 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5186 // Check for kernel and shader functions 5187 if (Info->isEntryFunction()) 5188 return DAG.getConstant(0, DL, VT); 5189 5190 MachineFrameInfo &MFI = MF.getFrameInfo(); 5191 // There is a call to @llvm.returnaddress in this function 5192 MFI.setReturnAddressIsTaken(true); 5193 5194 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5195 // Get the return address reg and mark it as an implicit live-in 5196 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5197 5198 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5199 } 5200 5201 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5202 SDValue Op, 5203 const SDLoc &DL, 5204 EVT VT) const { 5205 return Op.getValueType().bitsLE(VT) ? 5206 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5207 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5208 DAG.getTargetConstant(0, DL, MVT::i32)); 5209 } 5210 5211 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5212 assert(Op.getValueType() == MVT::f16 && 5213 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5214 5215 SDValue Src = Op.getOperand(0); 5216 EVT SrcVT = Src.getValueType(); 5217 if (SrcVT != MVT::f64) 5218 return Op; 5219 5220 SDLoc DL(Op); 5221 5222 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5223 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5224 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5225 } 5226 5227 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5228 SelectionDAG &DAG) const { 5229 EVT VT = Op.getValueType(); 5230 const MachineFunction &MF = DAG.getMachineFunction(); 5231 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5232 bool IsIEEEMode = Info->getMode().IEEE; 5233 5234 // FIXME: Assert during selection that this is only selected for 5235 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5236 // mode functions, but this happens to be OK since it's only done in cases 5237 // where there is known no sNaN. 5238 if (IsIEEEMode) 5239 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5240 5241 if (VT == MVT::v4f16 || VT == MVT::v8f16) 5242 return splitBinaryVectorOp(Op, DAG); 5243 return Op; 5244 } 5245 5246 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5247 EVT VT = Op.getValueType(); 5248 SDLoc SL(Op); 5249 SDValue LHS = Op.getOperand(0); 5250 SDValue RHS = Op.getOperand(1); 5251 bool isSigned = Op.getOpcode() == ISD::SMULO; 5252 5253 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5254 const APInt &C = RHSC->getAPIntValue(); 5255 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5256 if (C.isPowerOf2()) { 5257 // smulo(x, signed_min) is same as umulo(x, signed_min). 5258 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5259 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5260 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5261 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5262 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5263 SL, VT, Result, ShiftAmt), 5264 LHS, ISD::SETNE); 5265 return DAG.getMergeValues({ Result, Overflow }, SL); 5266 } 5267 } 5268 5269 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5270 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5271 SL, VT, LHS, RHS); 5272 5273 SDValue Sign = isSigned 5274 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5275 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5276 : DAG.getConstant(0, SL, VT); 5277 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5278 5279 return DAG.getMergeValues({ Result, Overflow }, SL); 5280 } 5281 5282 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const { 5283 if (Op->isDivergent()) { 5284 // Select to V_MAD_[IU]64_[IU]32. 5285 return Op; 5286 } 5287 if (Subtarget->hasSMulHi()) { 5288 // Expand to S_MUL_I32 + S_MUL_HI_[IU]32. 5289 return SDValue(); 5290 } 5291 // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to 5292 // calculate the high part, so we might as well do the whole thing with 5293 // V_MAD_[IU]64_[IU]32. 5294 return Op; 5295 } 5296 5297 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5298 if (!Subtarget->isTrapHandlerEnabled() || 5299 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5300 return lowerTrapEndpgm(Op, DAG); 5301 5302 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5303 switch (*HsaAbiVer) { 5304 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5305 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5306 return lowerTrapHsaQueuePtr(Op, DAG); 5307 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5308 case ELF::ELFABIVERSION_AMDGPU_HSA_V5: 5309 return Subtarget->supportsGetDoorbellID() ? 5310 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5311 } 5312 } 5313 5314 llvm_unreachable("Unknown trap handler"); 5315 } 5316 5317 SDValue SITargetLowering::lowerTrapEndpgm( 5318 SDValue Op, SelectionDAG &DAG) const { 5319 SDLoc SL(Op); 5320 SDValue Chain = Op.getOperand(0); 5321 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5322 } 5323 5324 SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT, 5325 const SDLoc &DL, Align Alignment, ImplicitParameter Param) const { 5326 MachineFunction &MF = DAG.getMachineFunction(); 5327 uint64_t Offset = getImplicitParameterOffset(MF, Param); 5328 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset); 5329 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5330 return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment, 5331 MachineMemOperand::MODereferenceable | 5332 MachineMemOperand::MOInvariant); 5333 } 5334 5335 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5336 SDValue Op, SelectionDAG &DAG) const { 5337 SDLoc SL(Op); 5338 SDValue Chain = Op.getOperand(0); 5339 5340 SDValue QueuePtr; 5341 // For code object version 5, QueuePtr is passed through implicit kernarg. 5342 if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) { 5343 QueuePtr = 5344 loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR); 5345 } else { 5346 MachineFunction &MF = DAG.getMachineFunction(); 5347 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5348 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5349 5350 if (UserSGPR == AMDGPU::NoRegister) { 5351 // We probably are in a function incorrectly marked with 5352 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the 5353 // trap, so just use a null pointer. 5354 QueuePtr = DAG.getConstant(0, SL, MVT::i64); 5355 } else { 5356 QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR, 5357 MVT::i64); 5358 } 5359 } 5360 5361 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5362 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5363 QueuePtr, SDValue()); 5364 5365 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5366 SDValue Ops[] = { 5367 ToReg, 5368 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5369 SGPR01, 5370 ToReg.getValue(1) 5371 }; 5372 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5373 } 5374 5375 SDValue SITargetLowering::lowerTrapHsa( 5376 SDValue Op, SelectionDAG &DAG) const { 5377 SDLoc SL(Op); 5378 SDValue Chain = Op.getOperand(0); 5379 5380 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5381 SDValue Ops[] = { 5382 Chain, 5383 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5384 }; 5385 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5386 } 5387 5388 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5389 SDLoc SL(Op); 5390 SDValue Chain = Op.getOperand(0); 5391 MachineFunction &MF = DAG.getMachineFunction(); 5392 5393 if (!Subtarget->isTrapHandlerEnabled() || 5394 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5395 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5396 "debugtrap handler not supported", 5397 Op.getDebugLoc(), 5398 DS_Warning); 5399 LLVMContext &Ctx = MF.getFunction().getContext(); 5400 Ctx.diagnose(NoTrap); 5401 return Chain; 5402 } 5403 5404 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5405 SDValue Ops[] = { 5406 Chain, 5407 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5408 }; 5409 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5410 } 5411 5412 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5413 SelectionDAG &DAG) const { 5414 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5415 if (Subtarget->hasApertureRegs()) { 5416 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5417 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5418 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5419 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5420 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5421 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5422 unsigned Encoding = 5423 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5424 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5425 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5426 5427 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5428 SDValue ApertureReg = SDValue( 5429 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5430 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5431 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5432 } 5433 5434 // For code object version 5, private_base and shared_base are passed through 5435 // implicit kernargs. 5436 if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) { 5437 ImplicitParameter Param = 5438 (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE; 5439 return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param); 5440 } 5441 5442 MachineFunction &MF = DAG.getMachineFunction(); 5443 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5444 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5445 if (UserSGPR == AMDGPU::NoRegister) { 5446 // We probably are in a function incorrectly marked with 5447 // amdgpu-no-queue-ptr. This is undefined. 5448 return DAG.getUNDEF(MVT::i32); 5449 } 5450 5451 SDValue QueuePtr = CreateLiveInRegister( 5452 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5453 5454 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5455 // private_segment_aperture_base_hi. 5456 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5457 5458 SDValue Ptr = 5459 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5460 5461 // TODO: Use custom target PseudoSourceValue. 5462 // TODO: We should use the value from the IR intrinsic call, but it might not 5463 // be available and how do we get it? 5464 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5465 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5466 commonAlignment(Align(64), StructOffset), 5467 MachineMemOperand::MODereferenceable | 5468 MachineMemOperand::MOInvariant); 5469 } 5470 5471 /// Return true if the value is a known valid address, such that a null check is 5472 /// not necessary. 5473 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG, 5474 const AMDGPUTargetMachine &TM, unsigned AddrSpace) { 5475 if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) || 5476 isa<BasicBlockSDNode>(Val)) 5477 return true; 5478 5479 if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val)) 5480 return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace); 5481 5482 // TODO: Search through arithmetic, handle arguments and loads 5483 // marked nonnull. 5484 return false; 5485 } 5486 5487 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5488 SelectionDAG &DAG) const { 5489 SDLoc SL(Op); 5490 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5491 5492 SDValue Src = ASC->getOperand(0); 5493 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5494 unsigned SrcAS = ASC->getSrcAddressSpace(); 5495 5496 const AMDGPUTargetMachine &TM = 5497 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5498 5499 // flat -> local/private 5500 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) { 5501 unsigned DestAS = ASC->getDestAddressSpace(); 5502 5503 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5504 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5505 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5506 5507 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5508 return Ptr; 5509 5510 unsigned NullVal = TM.getNullPointerValue(DestAS); 5511 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5512 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5513 5514 return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr, 5515 SegmentNullPtr); 5516 } 5517 } 5518 5519 // local/private -> flat 5520 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5521 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5522 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5523 5524 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5525 SDValue CvtPtr = 5526 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5527 CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr); 5528 5529 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5530 return CvtPtr; 5531 5532 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5533 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5534 5535 SDValue NonNull 5536 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5537 5538 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr, 5539 FlatNullPtr); 5540 } 5541 } 5542 5543 if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5544 Op.getValueType() == MVT::i64) { 5545 const SIMachineFunctionInfo *Info = 5546 DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>(); 5547 SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32); 5548 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi); 5549 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 5550 } 5551 5552 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5553 Src.getValueType() == MVT::i64) 5554 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5555 5556 // global <-> flat are no-ops and never emitted. 5557 5558 const MachineFunction &MF = DAG.getMachineFunction(); 5559 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5560 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5561 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5562 5563 return DAG.getUNDEF(ASC->getValueType(0)); 5564 } 5565 5566 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5567 // the small vector and inserting them into the big vector. That is better than 5568 // the default expansion of doing it via a stack slot. Even though the use of 5569 // the stack slot would be optimized away afterwards, the stack slot itself 5570 // remains. 5571 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5572 SelectionDAG &DAG) const { 5573 SDValue Vec = Op.getOperand(0); 5574 SDValue Ins = Op.getOperand(1); 5575 SDValue Idx = Op.getOperand(2); 5576 EVT VecVT = Vec.getValueType(); 5577 EVT InsVT = Ins.getValueType(); 5578 EVT EltVT = VecVT.getVectorElementType(); 5579 unsigned InsNumElts = InsVT.getVectorNumElements(); 5580 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5581 SDLoc SL(Op); 5582 5583 for (unsigned I = 0; I != InsNumElts; ++I) { 5584 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5585 DAG.getConstant(I, SL, MVT::i32)); 5586 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5587 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5588 } 5589 return Vec; 5590 } 5591 5592 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5593 SelectionDAG &DAG) const { 5594 SDValue Vec = Op.getOperand(0); 5595 SDValue InsVal = Op.getOperand(1); 5596 SDValue Idx = Op.getOperand(2); 5597 EVT VecVT = Vec.getValueType(); 5598 EVT EltVT = VecVT.getVectorElementType(); 5599 unsigned VecSize = VecVT.getSizeInBits(); 5600 unsigned EltSize = EltVT.getSizeInBits(); 5601 SDLoc SL(Op); 5602 5603 // Specially handle the case of v4i16 with static indexing. 5604 unsigned NumElts = VecVT.getVectorNumElements(); 5605 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5606 if (NumElts == 4 && EltSize == 16 && KIdx) { 5607 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5608 5609 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5610 DAG.getConstant(0, SL, MVT::i32)); 5611 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5612 DAG.getConstant(1, SL, MVT::i32)); 5613 5614 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5615 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5616 5617 unsigned Idx = KIdx->getZExtValue(); 5618 bool InsertLo = Idx < 2; 5619 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5620 InsertLo ? LoVec : HiVec, 5621 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5622 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5623 5624 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5625 5626 SDValue Concat = InsertLo ? 5627 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5628 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5629 5630 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5631 } 5632 5633 // Static indexing does not lower to stack access, and hence there is no need 5634 // for special custom lowering to avoid stack access. 5635 if (isa<ConstantSDNode>(Idx)) 5636 return SDValue(); 5637 5638 // Avoid stack access for dynamic indexing by custom lowering to 5639 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5640 5641 assert(VecSize <= 64 && "Expected target vector size to be <= 64 bits"); 5642 5643 MVT IntVT = MVT::getIntegerVT(VecSize); 5644 5645 // Convert vector index to bit-index and get the required bit mask. 5646 assert(isPowerOf2_32(EltSize)); 5647 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5648 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5649 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5650 DAG.getConstant(0xffff, SL, IntVT), 5651 ScaledIdx); 5652 5653 // 1. Create a congruent vector with the target value in each element. 5654 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5655 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5656 5657 // 2. Mask off all other indicies except the required index within (1). 5658 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5659 5660 // 3. Mask off the required index within the target vector. 5661 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5662 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5663 DAG.getNOT(SL, BFM, IntVT), BCVec); 5664 5665 // 4. Get (2) and (3) ORed into the target vector. 5666 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5667 5668 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5669 } 5670 5671 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5672 SelectionDAG &DAG) const { 5673 SDLoc SL(Op); 5674 5675 EVT ResultVT = Op.getValueType(); 5676 SDValue Vec = Op.getOperand(0); 5677 SDValue Idx = Op.getOperand(1); 5678 EVT VecVT = Vec.getValueType(); 5679 unsigned VecSize = VecVT.getSizeInBits(); 5680 EVT EltVT = VecVT.getVectorElementType(); 5681 5682 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5683 5684 // Make sure we do any optimizations that will make it easier to fold 5685 // source modifiers before obscuring it with bit operations. 5686 5687 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5688 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5689 return Combined; 5690 5691 if (VecSize == 128) { 5692 SDValue Lo, Hi; 5693 EVT LoVT, HiVT; 5694 SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec); 5695 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5696 Lo = 5697 DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5698 V2, DAG.getConstant(0, SL, MVT::i32))); 5699 Hi = 5700 DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5701 V2, DAG.getConstant(1, SL, MVT::i32))); 5702 EVT IdxVT = Idx.getValueType(); 5703 unsigned NElem = VecVT.getVectorNumElements(); 5704 assert(isPowerOf2_32(NElem)); 5705 SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT); 5706 SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask); 5707 SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT); 5708 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx); 5709 } 5710 5711 assert(VecSize <= 64); 5712 5713 MVT IntVT = MVT::getIntegerVT(VecSize); 5714 5715 // If Vec is just a SCALAR_TO_VECTOR, then use the scalar integer directly. 5716 SDValue VecBC = peekThroughBitcasts(Vec); 5717 if (VecBC.getOpcode() == ISD::SCALAR_TO_VECTOR) { 5718 SDValue Src = VecBC.getOperand(0); 5719 Src = DAG.getBitcast(Src.getValueType().changeTypeToInteger(), Src); 5720 Vec = DAG.getAnyExtOrTrunc(Src, SL, IntVT); 5721 } 5722 5723 unsigned EltSize = EltVT.getSizeInBits(); 5724 assert(isPowerOf2_32(EltSize)); 5725 5726 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5727 5728 // Convert vector index to bit-index (* EltSize) 5729 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5730 5731 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5732 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5733 5734 if (ResultVT == MVT::f16) { 5735 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5736 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5737 } 5738 5739 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5740 } 5741 5742 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5743 assert(Elt % 2 == 0); 5744 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5745 } 5746 5747 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5748 SelectionDAG &DAG) const { 5749 SDLoc SL(Op); 5750 EVT ResultVT = Op.getValueType(); 5751 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5752 5753 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5754 EVT EltVT = PackVT.getVectorElementType(); 5755 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5756 5757 // vector_shuffle <0,1,6,7> lhs, rhs 5758 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5759 // 5760 // vector_shuffle <6,7,2,3> lhs, rhs 5761 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5762 // 5763 // vector_shuffle <6,7,0,1> lhs, rhs 5764 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5765 5766 // Avoid scalarizing when both halves are reading from consecutive elements. 5767 SmallVector<SDValue, 4> Pieces; 5768 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5769 if (elementPairIsContiguous(SVN->getMask(), I)) { 5770 const int Idx = SVN->getMaskElt(I); 5771 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5772 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5773 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5774 PackVT, SVN->getOperand(VecIdx), 5775 DAG.getConstant(EltIdx, SL, MVT::i32)); 5776 Pieces.push_back(SubVec); 5777 } else { 5778 const int Idx0 = SVN->getMaskElt(I); 5779 const int Idx1 = SVN->getMaskElt(I + 1); 5780 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5781 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5782 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5783 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5784 5785 SDValue Vec0 = SVN->getOperand(VecIdx0); 5786 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5787 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5788 5789 SDValue Vec1 = SVN->getOperand(VecIdx1); 5790 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5791 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5792 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5793 } 5794 } 5795 5796 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5797 } 5798 5799 SDValue SITargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op, 5800 SelectionDAG &DAG) const { 5801 SDValue SVal = Op.getOperand(0); 5802 EVT ResultVT = Op.getValueType(); 5803 EVT SValVT = SVal.getValueType(); 5804 SDValue UndefVal = DAG.getUNDEF(SValVT); 5805 SDLoc SL(Op); 5806 5807 SmallVector<SDValue, 8> VElts; 5808 VElts.push_back(SVal); 5809 for (int I = 1, E = ResultVT.getVectorNumElements(); I < E; ++I) 5810 VElts.push_back(UndefVal); 5811 5812 return DAG.getBuildVector(ResultVT, SL, VElts); 5813 } 5814 5815 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5816 SelectionDAG &DAG) const { 5817 SDLoc SL(Op); 5818 EVT VT = Op.getValueType(); 5819 5820 if (VT == MVT::v4i16 || VT == MVT::v4f16 || 5821 VT == MVT::v8i16 || VT == MVT::v8f16) { 5822 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 5823 VT.getVectorNumElements() / 2); 5824 MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits()); 5825 5826 // Turn into pair of packed build_vectors. 5827 // TODO: Special case for constants that can be materialized with s_mov_b64. 5828 SmallVector<SDValue, 4> LoOps, HiOps; 5829 for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) { 5830 LoOps.push_back(Op.getOperand(I)); 5831 HiOps.push_back(Op.getOperand(I + E)); 5832 } 5833 SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps); 5834 SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps); 5835 5836 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo); 5837 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi); 5838 5839 SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL, 5840 { CastLo, CastHi }); 5841 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5842 } 5843 5844 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5845 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5846 5847 SDValue Lo = Op.getOperand(0); 5848 SDValue Hi = Op.getOperand(1); 5849 5850 // Avoid adding defined bits with the zero_extend. 5851 if (Hi.isUndef()) { 5852 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5853 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5854 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5855 } 5856 5857 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5858 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5859 5860 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5861 DAG.getConstant(16, SL, MVT::i32)); 5862 if (Lo.isUndef()) 5863 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5864 5865 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5866 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5867 5868 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5869 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5870 } 5871 5872 bool 5873 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5874 // We can fold offsets for anything that doesn't require a GOT relocation. 5875 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5876 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5877 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5878 !shouldEmitGOTReloc(GA->getGlobal()); 5879 } 5880 5881 static SDValue 5882 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5883 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5884 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5885 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5886 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5887 // lowered to the following code sequence: 5888 // 5889 // For constant address space: 5890 // s_getpc_b64 s[0:1] 5891 // s_add_u32 s0, s0, $symbol 5892 // s_addc_u32 s1, s1, 0 5893 // 5894 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5895 // a fixup or relocation is emitted to replace $symbol with a literal 5896 // constant, which is a pc-relative offset from the encoding of the $symbol 5897 // operand to the global variable. 5898 // 5899 // For global address space: 5900 // s_getpc_b64 s[0:1] 5901 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5902 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5903 // 5904 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5905 // fixups or relocations are emitted to replace $symbol@*@lo and 5906 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5907 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5908 // operand to the global variable. 5909 // 5910 // What we want here is an offset from the value returned by s_getpc 5911 // (which is the address of the s_add_u32 instruction) to the global 5912 // variable, but since the encoding of $symbol starts 4 bytes after the start 5913 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5914 // small. This requires us to add 4 to the global variable offset in order to 5915 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5916 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5917 // instruction. 5918 SDValue PtrLo = 5919 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5920 SDValue PtrHi; 5921 if (GAFlags == SIInstrInfo::MO_NONE) { 5922 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5923 } else { 5924 PtrHi = 5925 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5926 } 5927 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5928 } 5929 5930 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5931 SDValue Op, 5932 SelectionDAG &DAG) const { 5933 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5934 SDLoc DL(GSD); 5935 EVT PtrVT = Op.getValueType(); 5936 5937 const GlobalValue *GV = GSD->getGlobal(); 5938 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5939 shouldUseLDSConstAddress(GV)) || 5940 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5941 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5942 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5943 GV->hasExternalLinkage()) { 5944 Type *Ty = GV->getValueType(); 5945 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5946 // zero-sized type in other languages to declare the dynamic shared 5947 // memory which size is not known at the compile time. They will be 5948 // allocated by the runtime and placed directly after the static 5949 // allocated ones. They all share the same offset. 5950 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5951 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5952 // Adjust alignment for that dynamic shared memory array. 5953 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5954 return SDValue( 5955 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5956 } 5957 } 5958 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5959 } 5960 5961 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5962 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5963 SIInstrInfo::MO_ABS32_LO); 5964 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5965 } 5966 5967 if (shouldEmitFixup(GV)) 5968 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5969 else if (shouldEmitPCReloc(GV)) 5970 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5971 SIInstrInfo::MO_REL32); 5972 5973 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5974 SIInstrInfo::MO_GOTPCREL32); 5975 5976 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5977 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5978 const DataLayout &DataLayout = DAG.getDataLayout(); 5979 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5980 MachinePointerInfo PtrInfo 5981 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5982 5983 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5984 MachineMemOperand::MODereferenceable | 5985 MachineMemOperand::MOInvariant); 5986 } 5987 5988 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5989 const SDLoc &DL, SDValue V) const { 5990 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5991 // the destination register. 5992 // 5993 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5994 // so we will end up with redundant moves to m0. 5995 // 5996 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5997 5998 // A Null SDValue creates a glue result. 5999 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 6000 V, Chain); 6001 return SDValue(M0, 0); 6002 } 6003 6004 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 6005 SDValue Op, 6006 MVT VT, 6007 unsigned Offset) const { 6008 SDLoc SL(Op); 6009 SDValue Param = lowerKernargMemParameter( 6010 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 6011 // The local size values will have the hi 16-bits as zero. 6012 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 6013 DAG.getValueType(VT)); 6014 } 6015 6016 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6017 EVT VT) { 6018 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6019 "non-hsa intrinsic with hsa target", 6020 DL.getDebugLoc()); 6021 DAG.getContext()->diagnose(BadIntrin); 6022 return DAG.getUNDEF(VT); 6023 } 6024 6025 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6026 EVT VT) { 6027 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6028 "intrinsic not supported on subtarget", 6029 DL.getDebugLoc()); 6030 DAG.getContext()->diagnose(BadIntrin); 6031 return DAG.getUNDEF(VT); 6032 } 6033 6034 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 6035 ArrayRef<SDValue> Elts) { 6036 assert(!Elts.empty()); 6037 MVT Type; 6038 unsigned NumElts = Elts.size(); 6039 6040 if (NumElts <= 8) { 6041 Type = MVT::getVectorVT(MVT::f32, NumElts); 6042 } else { 6043 assert(Elts.size() <= 16); 6044 Type = MVT::v16f32; 6045 NumElts = 16; 6046 } 6047 6048 SmallVector<SDValue, 16> VecElts(NumElts); 6049 for (unsigned i = 0; i < Elts.size(); ++i) { 6050 SDValue Elt = Elts[i]; 6051 if (Elt.getValueType() != MVT::f32) 6052 Elt = DAG.getBitcast(MVT::f32, Elt); 6053 VecElts[i] = Elt; 6054 } 6055 for (unsigned i = Elts.size(); i < NumElts; ++i) 6056 VecElts[i] = DAG.getUNDEF(MVT::f32); 6057 6058 if (NumElts == 1) 6059 return VecElts[0]; 6060 return DAG.getBuildVector(Type, DL, VecElts); 6061 } 6062 6063 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 6064 SDValue Src, int ExtraElts) { 6065 EVT SrcVT = Src.getValueType(); 6066 6067 SmallVector<SDValue, 8> Elts; 6068 6069 if (SrcVT.isVector()) 6070 DAG.ExtractVectorElements(Src, Elts); 6071 else 6072 Elts.push_back(Src); 6073 6074 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 6075 while (ExtraElts--) 6076 Elts.push_back(Undef); 6077 6078 return DAG.getBuildVector(CastVT, DL, Elts); 6079 } 6080 6081 // Re-construct the required return value for a image load intrinsic. 6082 // This is more complicated due to the optional use TexFailCtrl which means the required 6083 // return type is an aggregate 6084 static SDValue constructRetValue(SelectionDAG &DAG, 6085 MachineSDNode *Result, 6086 ArrayRef<EVT> ResultTypes, 6087 bool IsTexFail, bool Unpacked, bool IsD16, 6088 int DMaskPop, int NumVDataDwords, 6089 const SDLoc &DL) { 6090 // Determine the required return type. This is the same regardless of IsTexFail flag 6091 EVT ReqRetVT = ResultTypes[0]; 6092 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 6093 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6094 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 6095 6096 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6097 DMaskPop : (DMaskPop + 1) / 2; 6098 6099 MVT DataDwordVT = NumDataDwords == 1 ? 6100 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 6101 6102 MVT MaskPopVT = MaskPopDwords == 1 ? 6103 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 6104 6105 SDValue Data(Result, 0); 6106 SDValue TexFail; 6107 6108 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 6109 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 6110 if (MaskPopVT.isVector()) { 6111 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 6112 SDValue(Result, 0), ZeroIdx); 6113 } else { 6114 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 6115 SDValue(Result, 0), ZeroIdx); 6116 } 6117 } 6118 6119 if (DataDwordVT.isVector()) 6120 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 6121 NumDataDwords - MaskPopDwords); 6122 6123 if (IsD16) 6124 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 6125 6126 EVT LegalReqRetVT = ReqRetVT; 6127 if (!ReqRetVT.isVector()) { 6128 if (!Data.getValueType().isInteger()) 6129 Data = DAG.getNode(ISD::BITCAST, DL, 6130 Data.getValueType().changeTypeToInteger(), Data); 6131 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 6132 } else { 6133 // We need to widen the return vector to a legal type 6134 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 6135 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 6136 LegalReqRetVT = 6137 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 6138 ReqRetVT.getVectorNumElements() + 1); 6139 } 6140 } 6141 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 6142 6143 if (IsTexFail) { 6144 TexFail = 6145 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 6146 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 6147 6148 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 6149 } 6150 6151 if (Result->getNumValues() == 1) 6152 return Data; 6153 6154 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 6155 } 6156 6157 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 6158 SDValue *LWE, bool &IsTexFail) { 6159 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 6160 6161 uint64_t Value = TexFailCtrlConst->getZExtValue(); 6162 if (Value) { 6163 IsTexFail = true; 6164 } 6165 6166 SDLoc DL(TexFailCtrlConst); 6167 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 6168 Value &= ~(uint64_t)0x1; 6169 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 6170 Value &= ~(uint64_t)0x2; 6171 6172 return Value == 0; 6173 } 6174 6175 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op, 6176 MVT PackVectorVT, 6177 SmallVectorImpl<SDValue> &PackedAddrs, 6178 unsigned DimIdx, unsigned EndIdx, 6179 unsigned NumGradients) { 6180 SDLoc DL(Op); 6181 for (unsigned I = DimIdx; I < EndIdx; I++) { 6182 SDValue Addr = Op.getOperand(I); 6183 6184 // Gradients are packed with undef for each coordinate. 6185 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 6186 // 1D: undef,dx/dh; undef,dx/dv 6187 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 6188 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 6189 if (((I + 1) >= EndIdx) || 6190 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 6191 I == DimIdx + NumGradients - 1))) { 6192 if (Addr.getValueType() != MVT::i16) 6193 Addr = DAG.getBitcast(MVT::i16, Addr); 6194 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 6195 } else { 6196 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 6197 I++; 6198 } 6199 Addr = DAG.getBitcast(MVT::f32, Addr); 6200 PackedAddrs.push_back(Addr); 6201 } 6202 } 6203 6204 SDValue SITargetLowering::lowerImage(SDValue Op, 6205 const AMDGPU::ImageDimIntrinsicInfo *Intr, 6206 SelectionDAG &DAG, bool WithChain) const { 6207 SDLoc DL(Op); 6208 MachineFunction &MF = DAG.getMachineFunction(); 6209 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 6210 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 6211 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 6212 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 6213 unsigned IntrOpcode = Intr->BaseOpcode; 6214 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6215 6216 SmallVector<EVT, 3> ResultTypes(Op->values()); 6217 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 6218 bool IsD16 = false; 6219 bool IsG16 = false; 6220 bool IsA16 = false; 6221 SDValue VData; 6222 int NumVDataDwords; 6223 bool AdjustRetType = false; 6224 6225 // Offset of intrinsic arguments 6226 const unsigned ArgOffset = WithChain ? 2 : 1; 6227 6228 unsigned DMask; 6229 unsigned DMaskLanes = 0; 6230 6231 if (BaseOpcode->Atomic) { 6232 VData = Op.getOperand(2); 6233 6234 bool Is64Bit = VData.getValueType() == MVT::i64; 6235 if (BaseOpcode->AtomicX2) { 6236 SDValue VData2 = Op.getOperand(3); 6237 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6238 {VData, VData2}); 6239 if (Is64Bit) 6240 VData = DAG.getBitcast(MVT::v4i32, VData); 6241 6242 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6243 DMask = Is64Bit ? 0xf : 0x3; 6244 NumVDataDwords = Is64Bit ? 4 : 2; 6245 } else { 6246 DMask = Is64Bit ? 0x3 : 0x1; 6247 NumVDataDwords = Is64Bit ? 2 : 1; 6248 } 6249 } else { 6250 auto *DMaskConst = 6251 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6252 DMask = DMaskConst->getZExtValue(); 6253 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6254 6255 if (BaseOpcode->Store) { 6256 VData = Op.getOperand(2); 6257 6258 MVT StoreVT = VData.getSimpleValueType(); 6259 if (StoreVT.getScalarType() == MVT::f16) { 6260 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6261 return Op; // D16 is unsupported for this instruction 6262 6263 IsD16 = true; 6264 VData = handleD16VData(VData, DAG, true); 6265 } 6266 6267 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6268 } else { 6269 // Work out the num dwords based on the dmask popcount and underlying type 6270 // and whether packing is supported. 6271 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6272 if (LoadVT.getScalarType() == MVT::f16) { 6273 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6274 return Op; // D16 is unsupported for this instruction 6275 6276 IsD16 = true; 6277 } 6278 6279 // Confirm that the return type is large enough for the dmask specified 6280 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6281 (!LoadVT.isVector() && DMaskLanes > 1)) 6282 return Op; 6283 6284 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6285 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6286 // instructions. 6287 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6288 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6289 NumVDataDwords = (DMaskLanes + 1) / 2; 6290 else 6291 NumVDataDwords = DMaskLanes; 6292 6293 AdjustRetType = true; 6294 } 6295 } 6296 6297 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6298 SmallVector<SDValue, 4> VAddrs; 6299 6300 // Check for 16 bit addresses or derivatives and pack if true. 6301 MVT VAddrVT = 6302 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6303 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6304 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6305 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6306 6307 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6308 VAddrScalarVT = VAddrVT.getScalarType(); 6309 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6310 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6311 6312 // Push back extra arguments. 6313 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) { 6314 if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) { 6315 assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument"); 6316 // Special handling of bias when A16 is on. Bias is of type half but 6317 // occupies full 32-bit. 6318 SDValue Bias = DAG.getBuildVector( 6319 MVT::v2f16, DL, 6320 {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)}); 6321 VAddrs.push_back(Bias); 6322 } else { 6323 assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) && 6324 "Bias needs to be converted to 16 bit in A16 mode"); 6325 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6326 } 6327 } 6328 6329 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) { 6330 // 16 bit gradients are supported, but are tied to the A16 control 6331 // so both gradients and addresses must be 16 bit 6332 LLVM_DEBUG( 6333 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6334 "require 16 bit args for both gradients and addresses"); 6335 return Op; 6336 } 6337 6338 if (IsA16) { 6339 if (!ST->hasA16()) { 6340 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6341 "support 16 bit addresses\n"); 6342 return Op; 6343 } 6344 } 6345 6346 // We've dealt with incorrect input so we know that if IsA16, IsG16 6347 // are set then we have to compress/pack operands (either address, 6348 // gradient or both) 6349 // In the case where a16 and gradients are tied (no G16 support) then we 6350 // have already verified that both IsA16 and IsG16 are true 6351 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) { 6352 // Activate g16 6353 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6354 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6355 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6356 } 6357 6358 // Add gradients (packed or unpacked) 6359 if (IsG16) { 6360 // Pack the gradients 6361 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6362 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs, 6363 ArgOffset + Intr->GradientStart, 6364 ArgOffset + Intr->CoordStart, Intr->NumGradients); 6365 } else { 6366 for (unsigned I = ArgOffset + Intr->GradientStart; 6367 I < ArgOffset + Intr->CoordStart; I++) 6368 VAddrs.push_back(Op.getOperand(I)); 6369 } 6370 6371 // Add addresses (packed or unpacked) 6372 if (IsA16) { 6373 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs, 6374 ArgOffset + Intr->CoordStart, VAddrEnd, 6375 0 /* No gradients */); 6376 } else { 6377 // Add uncompressed address 6378 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6379 VAddrs.push_back(Op.getOperand(I)); 6380 } 6381 6382 // If the register allocator cannot place the address registers contiguously 6383 // without introducing moves, then using the non-sequential address encoding 6384 // is always preferable, since it saves VALU instructions and is usually a 6385 // wash in terms of code size or even better. 6386 // 6387 // However, we currently have no way of hinting to the register allocator that 6388 // MIMG addresses should be placed contiguously when it is possible to do so, 6389 // so force non-NSA for the common 2-address case as a heuristic. 6390 // 6391 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6392 // allocation when possible. 6393 bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) && 6394 VAddrs.size() >= 3 && 6395 VAddrs.size() <= (unsigned)ST->getNSAMaxSize(); 6396 SDValue VAddr; 6397 if (!UseNSA) 6398 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6399 6400 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6401 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6402 SDValue Unorm; 6403 if (!BaseOpcode->Sampler) { 6404 Unorm = True; 6405 } else { 6406 auto UnormConst = 6407 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6408 6409 Unorm = UnormConst->getZExtValue() ? True : False; 6410 } 6411 6412 SDValue TFE; 6413 SDValue LWE; 6414 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6415 bool IsTexFail = false; 6416 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6417 return Op; 6418 6419 if (IsTexFail) { 6420 if (!DMaskLanes) { 6421 // Expecting to get an error flag since TFC is on - and dmask is 0 6422 // Force dmask to be at least 1 otherwise the instruction will fail 6423 DMask = 0x1; 6424 DMaskLanes = 1; 6425 NumVDataDwords = 1; 6426 } 6427 NumVDataDwords += 1; 6428 AdjustRetType = true; 6429 } 6430 6431 // Has something earlier tagged that the return type needs adjusting 6432 // This happens if the instruction is a load or has set TexFailCtrl flags 6433 if (AdjustRetType) { 6434 // NumVDataDwords reflects the true number of dwords required in the return type 6435 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6436 // This is a no-op load. This can be eliminated 6437 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6438 if (isa<MemSDNode>(Op)) 6439 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6440 return Undef; 6441 } 6442 6443 EVT NewVT = NumVDataDwords > 1 ? 6444 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6445 : MVT::i32; 6446 6447 ResultTypes[0] = NewVT; 6448 if (ResultTypes.size() == 3) { 6449 // Original result was aggregate type used for TexFailCtrl results 6450 // The actual instruction returns as a vector type which has now been 6451 // created. Remove the aggregate result. 6452 ResultTypes.erase(&ResultTypes[1]); 6453 } 6454 } 6455 6456 unsigned CPol = cast<ConstantSDNode>( 6457 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6458 if (BaseOpcode->Atomic) 6459 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6460 if (CPol & ~AMDGPU::CPol::ALL) 6461 return Op; 6462 6463 SmallVector<SDValue, 26> Ops; 6464 if (BaseOpcode->Store || BaseOpcode->Atomic) 6465 Ops.push_back(VData); // vdata 6466 if (UseNSA) 6467 append_range(Ops, VAddrs); 6468 else 6469 Ops.push_back(VAddr); 6470 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6471 if (BaseOpcode->Sampler) 6472 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6473 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6474 if (IsGFX10Plus) 6475 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6476 Ops.push_back(Unorm); 6477 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6478 Ops.push_back(IsA16 && // r128, a16 for gfx9 6479 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6480 if (IsGFX10Plus) 6481 Ops.push_back(IsA16 ? True : False); 6482 if (!Subtarget->hasGFX90AInsts()) { 6483 Ops.push_back(TFE); //tfe 6484 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6485 report_fatal_error("TFE is not supported on this GPU"); 6486 } 6487 Ops.push_back(LWE); // lwe 6488 if (!IsGFX10Plus) 6489 Ops.push_back(DimInfo->DA ? True : False); 6490 if (BaseOpcode->HasD16) 6491 Ops.push_back(IsD16 ? True : False); 6492 if (isa<MemSDNode>(Op)) 6493 Ops.push_back(Op.getOperand(0)); // chain 6494 6495 int NumVAddrDwords = 6496 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6497 int Opcode = -1; 6498 6499 if (IsGFX10Plus) { 6500 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6501 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6502 : AMDGPU::MIMGEncGfx10Default, 6503 NumVDataDwords, NumVAddrDwords); 6504 } else { 6505 if (Subtarget->hasGFX90AInsts()) { 6506 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6507 NumVDataDwords, NumVAddrDwords); 6508 if (Opcode == -1) 6509 report_fatal_error( 6510 "requested image instruction is not supported on this GPU"); 6511 } 6512 if (Opcode == -1 && 6513 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6514 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6515 NumVDataDwords, NumVAddrDwords); 6516 if (Opcode == -1) 6517 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6518 NumVDataDwords, NumVAddrDwords); 6519 } 6520 assert(Opcode != -1); 6521 6522 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6523 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6524 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6525 DAG.setNodeMemRefs(NewNode, {MemRef}); 6526 } 6527 6528 if (BaseOpcode->AtomicX2) { 6529 SmallVector<SDValue, 1> Elt; 6530 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6531 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6532 } 6533 if (BaseOpcode->Store) 6534 return SDValue(NewNode, 0); 6535 return constructRetValue(DAG, NewNode, 6536 OrigResultTypes, IsTexFail, 6537 Subtarget->hasUnpackedD16VMem(), IsD16, 6538 DMaskLanes, NumVDataDwords, DL); 6539 } 6540 6541 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6542 SDValue Offset, SDValue CachePolicy, 6543 SelectionDAG &DAG) const { 6544 MachineFunction &MF = DAG.getMachineFunction(); 6545 6546 const DataLayout &DataLayout = DAG.getDataLayout(); 6547 Align Alignment = 6548 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6549 6550 MachineMemOperand *MMO = MF.getMachineMemOperand( 6551 MachinePointerInfo(), 6552 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6553 MachineMemOperand::MOInvariant, 6554 VT.getStoreSize(), Alignment); 6555 6556 if (!Offset->isDivergent()) { 6557 SDValue Ops[] = { 6558 Rsrc, 6559 Offset, // Offset 6560 CachePolicy 6561 }; 6562 6563 // Widen vec3 load to vec4. 6564 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6565 EVT WidenedVT = 6566 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6567 auto WidenedOp = DAG.getMemIntrinsicNode( 6568 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6569 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6570 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6571 DAG.getVectorIdxConstant(0, DL)); 6572 return Subvector; 6573 } 6574 6575 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6576 DAG.getVTList(VT), Ops, VT, MMO); 6577 } 6578 6579 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6580 // assume that the buffer is unswizzled. 6581 SmallVector<SDValue, 4> Loads; 6582 unsigned NumLoads = 1; 6583 MVT LoadVT = VT.getSimpleVT(); 6584 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6585 assert((LoadVT.getScalarType() == MVT::i32 || 6586 LoadVT.getScalarType() == MVT::f32)); 6587 6588 if (NumElts == 8 || NumElts == 16) { 6589 NumLoads = NumElts / 4; 6590 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6591 } 6592 6593 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6594 SDValue Ops[] = { 6595 DAG.getEntryNode(), // Chain 6596 Rsrc, // rsrc 6597 DAG.getConstant(0, DL, MVT::i32), // vindex 6598 {}, // voffset 6599 {}, // soffset 6600 {}, // offset 6601 CachePolicy, // cachepolicy 6602 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6603 }; 6604 6605 // Use the alignment to ensure that the required offsets will fit into the 6606 // immediate offsets. 6607 setBufferOffsets(Offset, DAG, &Ops[3], 6608 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6609 6610 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6611 for (unsigned i = 0; i < NumLoads; ++i) { 6612 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6613 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6614 LoadVT, MMO, DAG)); 6615 } 6616 6617 if (NumElts == 8 || NumElts == 16) 6618 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6619 6620 return Loads[0]; 6621 } 6622 6623 SDValue SITargetLowering::lowerWorkitemID(SelectionDAG &DAG, SDValue Op, 6624 unsigned Dim, 6625 const ArgDescriptor &Arg) const { 6626 SDLoc SL(Op); 6627 MachineFunction &MF = DAG.getMachineFunction(); 6628 unsigned MaxID = Subtarget->getMaxWorkitemID(MF.getFunction(), Dim); 6629 if (MaxID == 0) 6630 return DAG.getConstant(0, SL, MVT::i32); 6631 6632 SDValue Val = loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6633 SDLoc(DAG.getEntryNode()), Arg); 6634 6635 // Don't bother inserting AssertZext for packed IDs since we're emitting the 6636 // masking operations anyway. 6637 // 6638 // TODO: We could assert the top bit is 0 for the source copy. 6639 if (Arg.isMasked()) 6640 return Val; 6641 6642 // Preserve the known bits after expansion to a copy. 6643 EVT SmallVT = 6644 EVT::getIntegerVT(*DAG.getContext(), 32 - countLeadingZeros(MaxID)); 6645 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Val, 6646 DAG.getValueType(SmallVT)); 6647 } 6648 6649 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6650 SelectionDAG &DAG) const { 6651 MachineFunction &MF = DAG.getMachineFunction(); 6652 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6653 6654 EVT VT = Op.getValueType(); 6655 SDLoc DL(Op); 6656 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6657 6658 // TODO: Should this propagate fast-math-flags? 6659 6660 switch (IntrinsicID) { 6661 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6662 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6663 return emitNonHSAIntrinsicError(DAG, DL, VT); 6664 return getPreloadedValue(DAG, *MFI, VT, 6665 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6666 } 6667 case Intrinsic::amdgcn_dispatch_ptr: 6668 case Intrinsic::amdgcn_queue_ptr: { 6669 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6670 DiagnosticInfoUnsupported BadIntrin( 6671 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6672 DL.getDebugLoc()); 6673 DAG.getContext()->diagnose(BadIntrin); 6674 return DAG.getUNDEF(VT); 6675 } 6676 6677 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6678 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6679 return getPreloadedValue(DAG, *MFI, VT, RegID); 6680 } 6681 case Intrinsic::amdgcn_implicitarg_ptr: { 6682 if (MFI->isEntryFunction()) 6683 return getImplicitArgPtr(DAG, DL); 6684 return getPreloadedValue(DAG, *MFI, VT, 6685 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6686 } 6687 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6688 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6689 // This only makes sense to call in a kernel, so just lower to null. 6690 return DAG.getConstant(0, DL, VT); 6691 } 6692 6693 return getPreloadedValue(DAG, *MFI, VT, 6694 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6695 } 6696 case Intrinsic::amdgcn_dispatch_id: { 6697 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6698 } 6699 case Intrinsic::amdgcn_rcp: 6700 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6701 case Intrinsic::amdgcn_rsq: 6702 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6703 case Intrinsic::amdgcn_rsq_legacy: 6704 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6705 return emitRemovedIntrinsicError(DAG, DL, VT); 6706 return SDValue(); 6707 case Intrinsic::amdgcn_rcp_legacy: 6708 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6709 return emitRemovedIntrinsicError(DAG, DL, VT); 6710 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6711 case Intrinsic::amdgcn_rsq_clamp: { 6712 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6713 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6714 6715 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6716 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6717 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6718 6719 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6720 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6721 DAG.getConstantFP(Max, DL, VT)); 6722 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6723 DAG.getConstantFP(Min, DL, VT)); 6724 } 6725 case Intrinsic::r600_read_ngroups_x: 6726 if (Subtarget->isAmdHsaOS()) 6727 return emitNonHSAIntrinsicError(DAG, DL, VT); 6728 6729 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6730 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6731 false); 6732 case Intrinsic::r600_read_ngroups_y: 6733 if (Subtarget->isAmdHsaOS()) 6734 return emitNonHSAIntrinsicError(DAG, DL, VT); 6735 6736 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6737 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6738 false); 6739 case Intrinsic::r600_read_ngroups_z: 6740 if (Subtarget->isAmdHsaOS()) 6741 return emitNonHSAIntrinsicError(DAG, DL, VT); 6742 6743 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6744 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6745 false); 6746 case Intrinsic::r600_read_global_size_x: 6747 if (Subtarget->isAmdHsaOS()) 6748 return emitNonHSAIntrinsicError(DAG, DL, VT); 6749 6750 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6751 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6752 Align(4), false); 6753 case Intrinsic::r600_read_global_size_y: 6754 if (Subtarget->isAmdHsaOS()) 6755 return emitNonHSAIntrinsicError(DAG, DL, VT); 6756 6757 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6758 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6759 Align(4), false); 6760 case Intrinsic::r600_read_global_size_z: 6761 if (Subtarget->isAmdHsaOS()) 6762 return emitNonHSAIntrinsicError(DAG, DL, VT); 6763 6764 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6765 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6766 Align(4), false); 6767 case Intrinsic::r600_read_local_size_x: 6768 if (Subtarget->isAmdHsaOS()) 6769 return emitNonHSAIntrinsicError(DAG, DL, VT); 6770 6771 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6772 SI::KernelInputOffsets::LOCAL_SIZE_X); 6773 case Intrinsic::r600_read_local_size_y: 6774 if (Subtarget->isAmdHsaOS()) 6775 return emitNonHSAIntrinsicError(DAG, DL, VT); 6776 6777 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6778 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6779 case Intrinsic::r600_read_local_size_z: 6780 if (Subtarget->isAmdHsaOS()) 6781 return emitNonHSAIntrinsicError(DAG, DL, VT); 6782 6783 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6784 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6785 case Intrinsic::amdgcn_workgroup_id_x: 6786 return getPreloadedValue(DAG, *MFI, VT, 6787 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6788 case Intrinsic::amdgcn_workgroup_id_y: 6789 return getPreloadedValue(DAG, *MFI, VT, 6790 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6791 case Intrinsic::amdgcn_workgroup_id_z: 6792 return getPreloadedValue(DAG, *MFI, VT, 6793 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6794 case Intrinsic::amdgcn_workitem_id_x: 6795 return lowerWorkitemID(DAG, Op, 0, MFI->getArgInfo().WorkItemIDX); 6796 case Intrinsic::amdgcn_workitem_id_y: 6797 return lowerWorkitemID(DAG, Op, 1, MFI->getArgInfo().WorkItemIDY); 6798 case Intrinsic::amdgcn_workitem_id_z: 6799 return lowerWorkitemID(DAG, Op, 2, MFI->getArgInfo().WorkItemIDZ); 6800 case Intrinsic::amdgcn_wavefrontsize: 6801 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6802 SDLoc(Op), MVT::i32); 6803 case Intrinsic::amdgcn_s_buffer_load: { 6804 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6805 if (CPol & ~AMDGPU::CPol::ALL) 6806 return Op; 6807 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6808 DAG); 6809 } 6810 case Intrinsic::amdgcn_fdiv_fast: 6811 return lowerFDIV_FAST(Op, DAG); 6812 case Intrinsic::amdgcn_sin: 6813 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6814 6815 case Intrinsic::amdgcn_cos: 6816 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6817 6818 case Intrinsic::amdgcn_mul_u24: 6819 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6820 case Intrinsic::amdgcn_mul_i24: 6821 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6822 6823 case Intrinsic::amdgcn_log_clamp: { 6824 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6825 return SDValue(); 6826 6827 return emitRemovedIntrinsicError(DAG, DL, VT); 6828 } 6829 case Intrinsic::amdgcn_ldexp: 6830 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6831 Op.getOperand(1), Op.getOperand(2)); 6832 6833 case Intrinsic::amdgcn_fract: 6834 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6835 6836 case Intrinsic::amdgcn_class: 6837 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6838 Op.getOperand(1), Op.getOperand(2)); 6839 case Intrinsic::amdgcn_div_fmas: 6840 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6841 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6842 Op.getOperand(4)); 6843 6844 case Intrinsic::amdgcn_div_fixup: 6845 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6846 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6847 6848 case Intrinsic::amdgcn_div_scale: { 6849 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6850 6851 // Translate to the operands expected by the machine instruction. The 6852 // first parameter must be the same as the first instruction. 6853 SDValue Numerator = Op.getOperand(1); 6854 SDValue Denominator = Op.getOperand(2); 6855 6856 // Note this order is opposite of the machine instruction's operations, 6857 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6858 // intrinsic has the numerator as the first operand to match a normal 6859 // division operation. 6860 6861 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator; 6862 6863 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6864 Denominator, Numerator); 6865 } 6866 case Intrinsic::amdgcn_icmp: { 6867 // There is a Pat that handles this variant, so return it as-is. 6868 if (Op.getOperand(1).getValueType() == MVT::i1 && 6869 Op.getConstantOperandVal(2) == 0 && 6870 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6871 return Op; 6872 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6873 } 6874 case Intrinsic::amdgcn_fcmp: { 6875 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6876 } 6877 case Intrinsic::amdgcn_ballot: 6878 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6879 case Intrinsic::amdgcn_fmed3: 6880 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6881 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6882 case Intrinsic::amdgcn_fdot2: 6883 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6884 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6885 Op.getOperand(4)); 6886 case Intrinsic::amdgcn_fmul_legacy: 6887 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6888 Op.getOperand(1), Op.getOperand(2)); 6889 case Intrinsic::amdgcn_sffbh: 6890 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6891 case Intrinsic::amdgcn_sbfe: 6892 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6893 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6894 case Intrinsic::amdgcn_ubfe: 6895 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6896 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6897 case Intrinsic::amdgcn_cvt_pkrtz: 6898 case Intrinsic::amdgcn_cvt_pknorm_i16: 6899 case Intrinsic::amdgcn_cvt_pknorm_u16: 6900 case Intrinsic::amdgcn_cvt_pk_i16: 6901 case Intrinsic::amdgcn_cvt_pk_u16: { 6902 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6903 EVT VT = Op.getValueType(); 6904 unsigned Opcode; 6905 6906 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6907 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6908 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6909 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6910 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6911 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6912 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6913 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6914 else 6915 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6916 6917 if (isTypeLegal(VT)) 6918 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6919 6920 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6921 Op.getOperand(1), Op.getOperand(2)); 6922 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6923 } 6924 case Intrinsic::amdgcn_fmad_ftz: 6925 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6926 Op.getOperand(2), Op.getOperand(3)); 6927 6928 case Intrinsic::amdgcn_if_break: 6929 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6930 Op->getOperand(1), Op->getOperand(2)), 0); 6931 6932 case Intrinsic::amdgcn_groupstaticsize: { 6933 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6934 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6935 return Op; 6936 6937 const Module *M = MF.getFunction().getParent(); 6938 const GlobalValue *GV = 6939 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6940 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6941 SIInstrInfo::MO_ABS32_LO); 6942 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6943 } 6944 case Intrinsic::amdgcn_is_shared: 6945 case Intrinsic::amdgcn_is_private: { 6946 SDLoc SL(Op); 6947 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6948 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6949 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6950 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6951 Op.getOperand(1)); 6952 6953 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6954 DAG.getConstant(1, SL, MVT::i32)); 6955 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6956 } 6957 case Intrinsic::amdgcn_perm: 6958 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1), 6959 Op.getOperand(2), Op.getOperand(3)); 6960 case Intrinsic::amdgcn_reloc_constant: { 6961 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6962 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6963 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6964 auto RelocSymbol = cast<GlobalVariable>( 6965 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6966 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6967 SIInstrInfo::MO_ABS32_LO); 6968 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6969 } 6970 default: 6971 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6972 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6973 return lowerImage(Op, ImageDimIntr, DAG, false); 6974 6975 return Op; 6976 } 6977 } 6978 6979 /// Update \p MMO based on the offset inputs to an intrinsic. 6980 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset, 6981 SDValue SOffset, SDValue Offset, 6982 SDValue VIndex = SDValue()) { 6983 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6984 !isa<ConstantSDNode>(Offset)) { 6985 // The combined offset is not known to be constant, so we cannot represent 6986 // it in the MMO. Give up. 6987 MMO->setValue((Value *)nullptr); 6988 return; 6989 } 6990 6991 if (VIndex && (!isa<ConstantSDNode>(VIndex) || 6992 !cast<ConstantSDNode>(VIndex)->isZero())) { 6993 // The strided index component of the address is not known to be zero, so we 6994 // cannot represent it in the MMO. Give up. 6995 MMO->setValue((Value *)nullptr); 6996 return; 6997 } 6998 6999 MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() + 7000 cast<ConstantSDNode>(SOffset)->getSExtValue() + 7001 cast<ConstantSDNode>(Offset)->getSExtValue()); 7002 } 7003 7004 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 7005 SelectionDAG &DAG, 7006 unsigned NewOpcode) const { 7007 SDLoc DL(Op); 7008 7009 SDValue VData = Op.getOperand(2); 7010 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7011 SDValue Ops[] = { 7012 Op.getOperand(0), // Chain 7013 VData, // vdata 7014 Op.getOperand(3), // rsrc 7015 DAG.getConstant(0, DL, MVT::i32), // vindex 7016 Offsets.first, // voffset 7017 Op.getOperand(5), // soffset 7018 Offsets.second, // offset 7019 Op.getOperand(6), // cachepolicy 7020 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7021 }; 7022 7023 auto *M = cast<MemSDNode>(Op); 7024 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 7025 7026 EVT MemVT = VData.getValueType(); 7027 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7028 M->getMemOperand()); 7029 } 7030 7031 // Return a value to use for the idxen operand by examining the vindex operand. 7032 static unsigned getIdxEn(SDValue VIndex) { 7033 if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex)) 7034 // No need to set idxen if vindex is known to be zero. 7035 return VIndexC->getZExtValue() != 0; 7036 return 1; 7037 } 7038 7039 SDValue 7040 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 7041 unsigned NewOpcode) const { 7042 SDLoc DL(Op); 7043 7044 SDValue VData = Op.getOperand(2); 7045 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7046 SDValue Ops[] = { 7047 Op.getOperand(0), // Chain 7048 VData, // vdata 7049 Op.getOperand(3), // rsrc 7050 Op.getOperand(4), // vindex 7051 Offsets.first, // voffset 7052 Op.getOperand(6), // soffset 7053 Offsets.second, // offset 7054 Op.getOperand(7), // cachepolicy 7055 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7056 }; 7057 7058 auto *M = cast<MemSDNode>(Op); 7059 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7060 7061 EVT MemVT = VData.getValueType(); 7062 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7063 M->getMemOperand()); 7064 } 7065 7066 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 7067 SelectionDAG &DAG) const { 7068 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7069 SDLoc DL(Op); 7070 7071 switch (IntrID) { 7072 case Intrinsic::amdgcn_ds_ordered_add: 7073 case Intrinsic::amdgcn_ds_ordered_swap: { 7074 MemSDNode *M = cast<MemSDNode>(Op); 7075 SDValue Chain = M->getOperand(0); 7076 SDValue M0 = M->getOperand(2); 7077 SDValue Value = M->getOperand(3); 7078 unsigned IndexOperand = M->getConstantOperandVal(7); 7079 unsigned WaveRelease = M->getConstantOperandVal(8); 7080 unsigned WaveDone = M->getConstantOperandVal(9); 7081 7082 unsigned OrderedCountIndex = IndexOperand & 0x3f; 7083 IndexOperand &= ~0x3f; 7084 unsigned CountDw = 0; 7085 7086 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 7087 CountDw = (IndexOperand >> 24) & 0xf; 7088 IndexOperand &= ~(0xf << 24); 7089 7090 if (CountDw < 1 || CountDw > 4) { 7091 report_fatal_error( 7092 "ds_ordered_count: dword count must be between 1 and 4"); 7093 } 7094 } 7095 7096 if (IndexOperand) 7097 report_fatal_error("ds_ordered_count: bad index operand"); 7098 7099 if (WaveDone && !WaveRelease) 7100 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 7101 7102 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 7103 unsigned ShaderType = 7104 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 7105 unsigned Offset0 = OrderedCountIndex << 2; 7106 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 7107 (Instruction << 4); 7108 7109 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 7110 Offset1 |= (CountDw - 1) << 6; 7111 7112 unsigned Offset = Offset0 | (Offset1 << 8); 7113 7114 SDValue Ops[] = { 7115 Chain, 7116 Value, 7117 DAG.getTargetConstant(Offset, DL, MVT::i16), 7118 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 7119 }; 7120 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 7121 M->getVTList(), Ops, M->getMemoryVT(), 7122 M->getMemOperand()); 7123 } 7124 case Intrinsic::amdgcn_ds_fadd: { 7125 MemSDNode *M = cast<MemSDNode>(Op); 7126 unsigned Opc; 7127 switch (IntrID) { 7128 case Intrinsic::amdgcn_ds_fadd: 7129 Opc = ISD::ATOMIC_LOAD_FADD; 7130 break; 7131 } 7132 7133 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 7134 M->getOperand(0), M->getOperand(2), M->getOperand(3), 7135 M->getMemOperand()); 7136 } 7137 case Intrinsic::amdgcn_atomic_inc: 7138 case Intrinsic::amdgcn_atomic_dec: 7139 case Intrinsic::amdgcn_ds_fmin: 7140 case Intrinsic::amdgcn_ds_fmax: { 7141 MemSDNode *M = cast<MemSDNode>(Op); 7142 unsigned Opc; 7143 switch (IntrID) { 7144 case Intrinsic::amdgcn_atomic_inc: 7145 Opc = AMDGPUISD::ATOMIC_INC; 7146 break; 7147 case Intrinsic::amdgcn_atomic_dec: 7148 Opc = AMDGPUISD::ATOMIC_DEC; 7149 break; 7150 case Intrinsic::amdgcn_ds_fmin: 7151 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 7152 break; 7153 case Intrinsic::amdgcn_ds_fmax: 7154 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 7155 break; 7156 default: 7157 llvm_unreachable("Unknown intrinsic!"); 7158 } 7159 SDValue Ops[] = { 7160 M->getOperand(0), // Chain 7161 M->getOperand(2), // Ptr 7162 M->getOperand(3) // Value 7163 }; 7164 7165 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 7166 M->getMemoryVT(), M->getMemOperand()); 7167 } 7168 case Intrinsic::amdgcn_buffer_load: 7169 case Intrinsic::amdgcn_buffer_load_format: { 7170 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 7171 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7172 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7173 SDValue Ops[] = { 7174 Op.getOperand(0), // Chain 7175 Op.getOperand(2), // rsrc 7176 Op.getOperand(3), // vindex 7177 SDValue(), // voffset -- will be set by setBufferOffsets 7178 SDValue(), // soffset -- will be set by setBufferOffsets 7179 SDValue(), // offset -- will be set by setBufferOffsets 7180 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7181 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7182 }; 7183 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 7184 7185 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 7186 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 7187 7188 EVT VT = Op.getValueType(); 7189 EVT IntVT = VT.changeTypeToInteger(); 7190 auto *M = cast<MemSDNode>(Op); 7191 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7192 EVT LoadVT = Op.getValueType(); 7193 7194 if (LoadVT.getScalarType() == MVT::f16) 7195 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 7196 M, DAG, Ops); 7197 7198 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 7199 if (LoadVT.getScalarType() == MVT::i8 || 7200 LoadVT.getScalarType() == MVT::i16) 7201 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 7202 7203 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 7204 M->getMemOperand(), DAG); 7205 } 7206 case Intrinsic::amdgcn_raw_buffer_load: 7207 case Intrinsic::amdgcn_raw_buffer_load_format: { 7208 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 7209 7210 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7211 SDValue Ops[] = { 7212 Op.getOperand(0), // Chain 7213 Op.getOperand(2), // rsrc 7214 DAG.getConstant(0, DL, MVT::i32), // vindex 7215 Offsets.first, // voffset 7216 Op.getOperand(4), // soffset 7217 Offsets.second, // offset 7218 Op.getOperand(5), // cachepolicy, swizzled buffer 7219 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7220 }; 7221 7222 auto *M = cast<MemSDNode>(Op); 7223 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]); 7224 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 7225 } 7226 case Intrinsic::amdgcn_struct_buffer_load: 7227 case Intrinsic::amdgcn_struct_buffer_load_format: { 7228 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7229 7230 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7231 SDValue Ops[] = { 7232 Op.getOperand(0), // Chain 7233 Op.getOperand(2), // rsrc 7234 Op.getOperand(3), // vindex 7235 Offsets.first, // voffset 7236 Op.getOperand(5), // soffset 7237 Offsets.second, // offset 7238 Op.getOperand(6), // cachepolicy, swizzled buffer 7239 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7240 }; 7241 7242 auto *M = cast<MemSDNode>(Op); 7243 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7244 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7245 } 7246 case Intrinsic::amdgcn_tbuffer_load: { 7247 MemSDNode *M = cast<MemSDNode>(Op); 7248 EVT LoadVT = Op.getValueType(); 7249 7250 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7251 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7252 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7253 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7254 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7255 SDValue Ops[] = { 7256 Op.getOperand(0), // Chain 7257 Op.getOperand(2), // rsrc 7258 Op.getOperand(3), // vindex 7259 Op.getOperand(4), // voffset 7260 Op.getOperand(5), // soffset 7261 Op.getOperand(6), // offset 7262 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7263 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7264 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7265 }; 7266 7267 if (LoadVT.getScalarType() == MVT::f16) 7268 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7269 M, DAG, Ops); 7270 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7271 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7272 DAG); 7273 } 7274 case Intrinsic::amdgcn_raw_tbuffer_load: { 7275 MemSDNode *M = cast<MemSDNode>(Op); 7276 EVT LoadVT = Op.getValueType(); 7277 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7278 7279 SDValue Ops[] = { 7280 Op.getOperand(0), // Chain 7281 Op.getOperand(2), // rsrc 7282 DAG.getConstant(0, DL, MVT::i32), // vindex 7283 Offsets.first, // voffset 7284 Op.getOperand(4), // soffset 7285 Offsets.second, // offset 7286 Op.getOperand(5), // format 7287 Op.getOperand(6), // cachepolicy, swizzled buffer 7288 DAG.getTargetConstant(0, 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_struct_tbuffer_load: { 7299 MemSDNode *M = cast<MemSDNode>(Op); 7300 EVT LoadVT = Op.getValueType(); 7301 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7302 7303 SDValue Ops[] = { 7304 Op.getOperand(0), // Chain 7305 Op.getOperand(2), // rsrc 7306 Op.getOperand(3), // vindex 7307 Offsets.first, // voffset 7308 Op.getOperand(5), // soffset 7309 Offsets.second, // offset 7310 Op.getOperand(6), // format 7311 Op.getOperand(7), // cachepolicy, swizzled buffer 7312 DAG.getTargetConstant(1, 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_buffer_atomic_swap: 7323 case Intrinsic::amdgcn_buffer_atomic_add: 7324 case Intrinsic::amdgcn_buffer_atomic_sub: 7325 case Intrinsic::amdgcn_buffer_atomic_csub: 7326 case Intrinsic::amdgcn_buffer_atomic_smin: 7327 case Intrinsic::amdgcn_buffer_atomic_umin: 7328 case Intrinsic::amdgcn_buffer_atomic_smax: 7329 case Intrinsic::amdgcn_buffer_atomic_umax: 7330 case Intrinsic::amdgcn_buffer_atomic_and: 7331 case Intrinsic::amdgcn_buffer_atomic_or: 7332 case Intrinsic::amdgcn_buffer_atomic_xor: 7333 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7334 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7335 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7336 SDValue Ops[] = { 7337 Op.getOperand(0), // Chain 7338 Op.getOperand(2), // vdata 7339 Op.getOperand(3), // rsrc 7340 Op.getOperand(4), // vindex 7341 SDValue(), // voffset -- will be set by setBufferOffsets 7342 SDValue(), // soffset -- will be set by setBufferOffsets 7343 SDValue(), // offset -- will be set by setBufferOffsets 7344 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7345 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7346 }; 7347 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7348 7349 EVT VT = Op.getValueType(); 7350 7351 auto *M = cast<MemSDNode>(Op); 7352 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7353 unsigned Opcode = 0; 7354 7355 switch (IntrID) { 7356 case Intrinsic::amdgcn_buffer_atomic_swap: 7357 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7358 break; 7359 case Intrinsic::amdgcn_buffer_atomic_add: 7360 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7361 break; 7362 case Intrinsic::amdgcn_buffer_atomic_sub: 7363 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7364 break; 7365 case Intrinsic::amdgcn_buffer_atomic_csub: 7366 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7367 break; 7368 case Intrinsic::amdgcn_buffer_atomic_smin: 7369 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7370 break; 7371 case Intrinsic::amdgcn_buffer_atomic_umin: 7372 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7373 break; 7374 case Intrinsic::amdgcn_buffer_atomic_smax: 7375 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7376 break; 7377 case Intrinsic::amdgcn_buffer_atomic_umax: 7378 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7379 break; 7380 case Intrinsic::amdgcn_buffer_atomic_and: 7381 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7382 break; 7383 case Intrinsic::amdgcn_buffer_atomic_or: 7384 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7385 break; 7386 case Intrinsic::amdgcn_buffer_atomic_xor: 7387 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7388 break; 7389 case Intrinsic::amdgcn_buffer_atomic_fadd: 7390 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7391 DiagnosticInfoUnsupported 7392 NoFpRet(DAG.getMachineFunction().getFunction(), 7393 "return versions of fp atomics not supported", 7394 DL.getDebugLoc(), DS_Error); 7395 DAG.getContext()->diagnose(NoFpRet); 7396 return SDValue(); 7397 } 7398 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7399 break; 7400 default: 7401 llvm_unreachable("unhandled atomic opcode"); 7402 } 7403 7404 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7405 M->getMemOperand()); 7406 } 7407 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7408 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7409 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7410 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7411 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7412 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7413 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7414 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7415 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7416 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7417 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7418 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7419 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7420 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7421 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7422 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7423 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7424 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7425 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7426 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7427 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7428 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7429 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7430 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7431 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7432 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7433 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7434 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7435 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7436 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7437 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7438 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7439 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7440 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7441 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7442 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7443 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7444 return lowerStructBufferAtomicIntrin(Op, DAG, 7445 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7446 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7447 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7448 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7449 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7450 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7451 return lowerStructBufferAtomicIntrin(Op, DAG, 7452 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7453 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7454 return lowerStructBufferAtomicIntrin(Op, DAG, 7455 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7456 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7457 return lowerStructBufferAtomicIntrin(Op, DAG, 7458 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7459 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7460 return lowerStructBufferAtomicIntrin(Op, DAG, 7461 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7462 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7463 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7464 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7465 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7466 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7467 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7468 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7469 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7470 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7471 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7472 7473 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7474 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7475 unsigned IdxEn = getIdxEn(Op.getOperand(5)); 7476 SDValue Ops[] = { 7477 Op.getOperand(0), // Chain 7478 Op.getOperand(2), // src 7479 Op.getOperand(3), // cmp 7480 Op.getOperand(4), // rsrc 7481 Op.getOperand(5), // vindex 7482 SDValue(), // voffset -- will be set by setBufferOffsets 7483 SDValue(), // soffset -- will be set by setBufferOffsets 7484 SDValue(), // offset -- will be set by setBufferOffsets 7485 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7486 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7487 }; 7488 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7489 7490 EVT VT = Op.getValueType(); 7491 auto *M = cast<MemSDNode>(Op); 7492 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7493 7494 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7495 Op->getVTList(), Ops, VT, M->getMemOperand()); 7496 } 7497 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7498 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7499 SDValue Ops[] = { 7500 Op.getOperand(0), // Chain 7501 Op.getOperand(2), // src 7502 Op.getOperand(3), // cmp 7503 Op.getOperand(4), // rsrc 7504 DAG.getConstant(0, DL, MVT::i32), // vindex 7505 Offsets.first, // voffset 7506 Op.getOperand(6), // soffset 7507 Offsets.second, // offset 7508 Op.getOperand(7), // cachepolicy 7509 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7510 }; 7511 EVT VT = Op.getValueType(); 7512 auto *M = cast<MemSDNode>(Op); 7513 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]); 7514 7515 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7516 Op->getVTList(), Ops, VT, M->getMemOperand()); 7517 } 7518 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7519 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7520 SDValue Ops[] = { 7521 Op.getOperand(0), // Chain 7522 Op.getOperand(2), // src 7523 Op.getOperand(3), // cmp 7524 Op.getOperand(4), // rsrc 7525 Op.getOperand(5), // vindex 7526 Offsets.first, // voffset 7527 Op.getOperand(7), // soffset 7528 Offsets.second, // offset 7529 Op.getOperand(8), // cachepolicy 7530 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7531 }; 7532 EVT VT = Op.getValueType(); 7533 auto *M = cast<MemSDNode>(Op); 7534 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7535 7536 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7537 Op->getVTList(), Ops, VT, M->getMemOperand()); 7538 } 7539 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7540 MemSDNode *M = cast<MemSDNode>(Op); 7541 SDValue NodePtr = M->getOperand(2); 7542 SDValue RayExtent = M->getOperand(3); 7543 SDValue RayOrigin = M->getOperand(4); 7544 SDValue RayDir = M->getOperand(5); 7545 SDValue RayInvDir = M->getOperand(6); 7546 SDValue TDescr = M->getOperand(7); 7547 7548 assert(NodePtr.getValueType() == MVT::i32 || 7549 NodePtr.getValueType() == MVT::i64); 7550 assert(RayDir.getValueType() == MVT::v3f16 || 7551 RayDir.getValueType() == MVT::v3f32); 7552 7553 if (!Subtarget->hasGFX10_AEncoding()) { 7554 emitRemovedIntrinsicError(DAG, DL, Op.getValueType()); 7555 return SDValue(); 7556 } 7557 7558 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7559 const bool Is64 = NodePtr.getValueType() == MVT::i64; 7560 const unsigned NumVDataDwords = 4; 7561 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11); 7562 const bool UseNSA = Subtarget->hasNSAEncoding() && 7563 NumVAddrDwords <= Subtarget->getNSAMaxSize(); 7564 const unsigned BaseOpcodes[2][2] = { 7565 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16}, 7566 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY, 7567 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}}; 7568 int Opcode; 7569 if (UseNSA) { 7570 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16], 7571 AMDGPU::MIMGEncGfx10NSA, NumVDataDwords, 7572 NumVAddrDwords); 7573 } else { 7574 Opcode = AMDGPU::getMIMGOpcode( 7575 BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords, 7576 PowerOf2Ceil(NumVAddrDwords)); 7577 } 7578 assert(Opcode != -1); 7579 7580 SmallVector<SDValue, 16> Ops; 7581 7582 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7583 SmallVector<SDValue, 3> Lanes; 7584 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7585 if (Lanes[0].getValueSizeInBits() == 32) { 7586 for (unsigned I = 0; I < 3; ++I) 7587 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7588 } else { 7589 if (IsAligned) { 7590 Ops.push_back( 7591 DAG.getBitcast(MVT::i32, 7592 DAG.getBuildVector(MVT::v2f16, DL, 7593 { Lanes[0], Lanes[1] }))); 7594 Ops.push_back(Lanes[2]); 7595 } else { 7596 SDValue Elt0 = Ops.pop_back_val(); 7597 Ops.push_back( 7598 DAG.getBitcast(MVT::i32, 7599 DAG.getBuildVector(MVT::v2f16, DL, 7600 { Elt0, Lanes[0] }))); 7601 Ops.push_back( 7602 DAG.getBitcast(MVT::i32, 7603 DAG.getBuildVector(MVT::v2f16, DL, 7604 { Lanes[1], Lanes[2] }))); 7605 } 7606 } 7607 }; 7608 7609 if (Is64) 7610 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7611 else 7612 Ops.push_back(NodePtr); 7613 7614 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7615 packLanes(RayOrigin, true); 7616 packLanes(RayDir, true); 7617 packLanes(RayInvDir, false); 7618 7619 if (!UseNSA) { 7620 // Build a single vector containing all the operands so far prepared. 7621 if (NumVAddrDwords > 8) { 7622 SDValue Undef = DAG.getUNDEF(MVT::i32); 7623 Ops.append(16 - Ops.size(), Undef); 7624 } 7625 assert(Ops.size() == 8 || Ops.size() == 16); 7626 SDValue MergedOps = DAG.getBuildVector( 7627 Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops); 7628 Ops.clear(); 7629 Ops.push_back(MergedOps); 7630 } 7631 7632 Ops.push_back(TDescr); 7633 if (IsA16) 7634 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7635 Ops.push_back(M->getChain()); 7636 7637 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7638 MachineMemOperand *MemRef = M->getMemOperand(); 7639 DAG.setNodeMemRefs(NewNode, {MemRef}); 7640 return SDValue(NewNode, 0); 7641 } 7642 case Intrinsic::amdgcn_global_atomic_fadd: 7643 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7644 DiagnosticInfoUnsupported 7645 NoFpRet(DAG.getMachineFunction().getFunction(), 7646 "return versions of fp atomics not supported", 7647 DL.getDebugLoc(), DS_Error); 7648 DAG.getContext()->diagnose(NoFpRet); 7649 return SDValue(); 7650 } 7651 LLVM_FALLTHROUGH; 7652 case Intrinsic::amdgcn_global_atomic_fmin: 7653 case Intrinsic::amdgcn_global_atomic_fmax: 7654 case Intrinsic::amdgcn_flat_atomic_fadd: 7655 case Intrinsic::amdgcn_flat_atomic_fmin: 7656 case Intrinsic::amdgcn_flat_atomic_fmax: { 7657 MemSDNode *M = cast<MemSDNode>(Op); 7658 SDValue Ops[] = { 7659 M->getOperand(0), // Chain 7660 M->getOperand(2), // Ptr 7661 M->getOperand(3) // Value 7662 }; 7663 unsigned Opcode = 0; 7664 switch (IntrID) { 7665 case Intrinsic::amdgcn_global_atomic_fadd: 7666 case Intrinsic::amdgcn_flat_atomic_fadd: { 7667 EVT VT = Op.getOperand(3).getValueType(); 7668 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7669 DAG.getVTList(VT, MVT::Other), Ops, 7670 M->getMemOperand()); 7671 } 7672 case Intrinsic::amdgcn_global_atomic_fmin: 7673 case Intrinsic::amdgcn_flat_atomic_fmin: { 7674 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7675 break; 7676 } 7677 case Intrinsic::amdgcn_global_atomic_fmax: 7678 case Intrinsic::amdgcn_flat_atomic_fmax: { 7679 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7680 break; 7681 } 7682 default: 7683 llvm_unreachable("unhandled atomic opcode"); 7684 } 7685 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7686 M->getVTList(), Ops, M->getMemoryVT(), 7687 M->getMemOperand()); 7688 } 7689 default: 7690 7691 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7692 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7693 return lowerImage(Op, ImageDimIntr, DAG, true); 7694 7695 return SDValue(); 7696 } 7697 } 7698 7699 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7700 // dwordx4 if on SI. 7701 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7702 SDVTList VTList, 7703 ArrayRef<SDValue> Ops, EVT MemVT, 7704 MachineMemOperand *MMO, 7705 SelectionDAG &DAG) const { 7706 EVT VT = VTList.VTs[0]; 7707 EVT WidenedVT = VT; 7708 EVT WidenedMemVT = MemVT; 7709 if (!Subtarget->hasDwordx3LoadStores() && 7710 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7711 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7712 WidenedVT.getVectorElementType(), 4); 7713 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7714 WidenedMemVT.getVectorElementType(), 4); 7715 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7716 } 7717 7718 assert(VTList.NumVTs == 2); 7719 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7720 7721 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7722 WidenedMemVT, MMO); 7723 if (WidenedVT != VT) { 7724 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7725 DAG.getVectorIdxConstant(0, DL)); 7726 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7727 } 7728 return NewOp; 7729 } 7730 7731 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7732 bool ImageStore) const { 7733 EVT StoreVT = VData.getValueType(); 7734 7735 // No change for f16 and legal vector D16 types. 7736 if (!StoreVT.isVector()) 7737 return VData; 7738 7739 SDLoc DL(VData); 7740 unsigned NumElements = StoreVT.getVectorNumElements(); 7741 7742 if (Subtarget->hasUnpackedD16VMem()) { 7743 // We need to unpack the packed data to store. 7744 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7745 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7746 7747 EVT EquivStoreVT = 7748 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7749 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7750 return DAG.UnrollVectorOp(ZExt.getNode()); 7751 } 7752 7753 // The sq block of gfx8.1 does not estimate register use correctly for d16 7754 // image store instructions. The data operand is computed as if it were not a 7755 // d16 image instruction. 7756 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7757 // Bitcast to i16 7758 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7759 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7760 7761 // Decompose into scalars 7762 SmallVector<SDValue, 4> Elts; 7763 DAG.ExtractVectorElements(IntVData, Elts); 7764 7765 // Group pairs of i16 into v2i16 and bitcast to i32 7766 SmallVector<SDValue, 4> PackedElts; 7767 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7768 SDValue Pair = 7769 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7770 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7771 PackedElts.push_back(IntPair); 7772 } 7773 if ((NumElements % 2) == 1) { 7774 // Handle v3i16 7775 unsigned I = Elts.size() / 2; 7776 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7777 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7778 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7779 PackedElts.push_back(IntPair); 7780 } 7781 7782 // Pad using UNDEF 7783 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7784 7785 // Build final vector 7786 EVT VecVT = 7787 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7788 return DAG.getBuildVector(VecVT, DL, PackedElts); 7789 } 7790 7791 if (NumElements == 3) { 7792 EVT IntStoreVT = 7793 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7794 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7795 7796 EVT WidenedStoreVT = EVT::getVectorVT( 7797 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7798 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7799 WidenedStoreVT.getStoreSizeInBits()); 7800 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7801 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7802 } 7803 7804 assert(isTypeLegal(StoreVT)); 7805 return VData; 7806 } 7807 7808 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7809 SelectionDAG &DAG) const { 7810 SDLoc DL(Op); 7811 SDValue Chain = Op.getOperand(0); 7812 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7813 MachineFunction &MF = DAG.getMachineFunction(); 7814 7815 switch (IntrinsicID) { 7816 case Intrinsic::amdgcn_exp_compr: { 7817 SDValue Src0 = Op.getOperand(4); 7818 SDValue Src1 = Op.getOperand(5); 7819 // Hack around illegal type on SI by directly selecting it. 7820 if (isTypeLegal(Src0.getValueType())) 7821 return SDValue(); 7822 7823 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7824 SDValue Undef = DAG.getUNDEF(MVT::f32); 7825 const SDValue Ops[] = { 7826 Op.getOperand(2), // tgt 7827 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7828 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7829 Undef, // src2 7830 Undef, // src3 7831 Op.getOperand(7), // vm 7832 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7833 Op.getOperand(3), // en 7834 Op.getOperand(0) // Chain 7835 }; 7836 7837 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7838 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7839 } 7840 case Intrinsic::amdgcn_s_barrier: { 7841 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7842 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7843 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7844 if (WGSize <= ST.getWavefrontSize()) 7845 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7846 Op.getOperand(0)), 0); 7847 } 7848 return SDValue(); 7849 }; 7850 case Intrinsic::amdgcn_tbuffer_store: { 7851 SDValue VData = Op.getOperand(2); 7852 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7853 if (IsD16) 7854 VData = handleD16VData(VData, DAG); 7855 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7856 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7857 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7858 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7859 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7860 SDValue Ops[] = { 7861 Chain, 7862 VData, // vdata 7863 Op.getOperand(3), // rsrc 7864 Op.getOperand(4), // vindex 7865 Op.getOperand(5), // voffset 7866 Op.getOperand(6), // soffset 7867 Op.getOperand(7), // offset 7868 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7869 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7870 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7871 }; 7872 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7873 AMDGPUISD::TBUFFER_STORE_FORMAT; 7874 MemSDNode *M = cast<MemSDNode>(Op); 7875 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7876 M->getMemoryVT(), M->getMemOperand()); 7877 } 7878 7879 case Intrinsic::amdgcn_struct_tbuffer_store: { 7880 SDValue VData = Op.getOperand(2); 7881 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7882 if (IsD16) 7883 VData = handleD16VData(VData, DAG); 7884 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7885 SDValue Ops[] = { 7886 Chain, 7887 VData, // vdata 7888 Op.getOperand(3), // rsrc 7889 Op.getOperand(4), // vindex 7890 Offsets.first, // voffset 7891 Op.getOperand(6), // soffset 7892 Offsets.second, // offset 7893 Op.getOperand(7), // format 7894 Op.getOperand(8), // cachepolicy, swizzled buffer 7895 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7896 }; 7897 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7898 AMDGPUISD::TBUFFER_STORE_FORMAT; 7899 MemSDNode *M = cast<MemSDNode>(Op); 7900 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7901 M->getMemoryVT(), M->getMemOperand()); 7902 } 7903 7904 case Intrinsic::amdgcn_raw_tbuffer_store: { 7905 SDValue VData = Op.getOperand(2); 7906 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7907 if (IsD16) 7908 VData = handleD16VData(VData, DAG); 7909 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7910 SDValue Ops[] = { 7911 Chain, 7912 VData, // vdata 7913 Op.getOperand(3), // rsrc 7914 DAG.getConstant(0, DL, MVT::i32), // vindex 7915 Offsets.first, // voffset 7916 Op.getOperand(5), // soffset 7917 Offsets.second, // offset 7918 Op.getOperand(6), // format 7919 Op.getOperand(7), // cachepolicy, swizzled buffer 7920 DAG.getTargetConstant(0, 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_buffer_store: 7930 case Intrinsic::amdgcn_buffer_store_format: { 7931 SDValue VData = Op.getOperand(2); 7932 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7933 if (IsD16) 7934 VData = handleD16VData(VData, DAG); 7935 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7936 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7937 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7938 SDValue Ops[] = { 7939 Chain, 7940 VData, 7941 Op.getOperand(3), // rsrc 7942 Op.getOperand(4), // vindex 7943 SDValue(), // voffset -- will be set by setBufferOffsets 7944 SDValue(), // soffset -- will be set by setBufferOffsets 7945 SDValue(), // offset -- will be set by setBufferOffsets 7946 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7947 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7948 }; 7949 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7950 7951 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7952 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7953 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7954 MemSDNode *M = cast<MemSDNode>(Op); 7955 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7956 7957 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7958 EVT VDataType = VData.getValueType().getScalarType(); 7959 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7960 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7961 7962 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7963 M->getMemoryVT(), M->getMemOperand()); 7964 } 7965 7966 case Intrinsic::amdgcn_raw_buffer_store: 7967 case Intrinsic::amdgcn_raw_buffer_store_format: { 7968 const bool IsFormat = 7969 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7970 7971 SDValue VData = Op.getOperand(2); 7972 EVT VDataVT = VData.getValueType(); 7973 EVT EltType = VDataVT.getScalarType(); 7974 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7975 if (IsD16) { 7976 VData = handleD16VData(VData, DAG); 7977 VDataVT = VData.getValueType(); 7978 } 7979 7980 if (!isTypeLegal(VDataVT)) { 7981 VData = 7982 DAG.getNode(ISD::BITCAST, DL, 7983 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7984 } 7985 7986 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7987 SDValue Ops[] = { 7988 Chain, 7989 VData, 7990 Op.getOperand(3), // rsrc 7991 DAG.getConstant(0, DL, MVT::i32), // vindex 7992 Offsets.first, // voffset 7993 Op.getOperand(5), // soffset 7994 Offsets.second, // offset 7995 Op.getOperand(6), // cachepolicy, swizzled buffer 7996 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7997 }; 7998 unsigned Opc = 7999 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 8000 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8001 MemSDNode *M = cast<MemSDNode>(Op); 8002 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 8003 8004 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8005 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8006 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 8007 8008 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8009 M->getMemoryVT(), M->getMemOperand()); 8010 } 8011 8012 case Intrinsic::amdgcn_struct_buffer_store: 8013 case Intrinsic::amdgcn_struct_buffer_store_format: { 8014 const bool IsFormat = 8015 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 8016 8017 SDValue VData = Op.getOperand(2); 8018 EVT VDataVT = VData.getValueType(); 8019 EVT EltType = VDataVT.getScalarType(); 8020 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 8021 8022 if (IsD16) { 8023 VData = handleD16VData(VData, DAG); 8024 VDataVT = VData.getValueType(); 8025 } 8026 8027 if (!isTypeLegal(VDataVT)) { 8028 VData = 8029 DAG.getNode(ISD::BITCAST, DL, 8030 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 8031 } 8032 8033 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 8034 SDValue Ops[] = { 8035 Chain, 8036 VData, 8037 Op.getOperand(3), // rsrc 8038 Op.getOperand(4), // vindex 8039 Offsets.first, // voffset 8040 Op.getOperand(6), // soffset 8041 Offsets.second, // offset 8042 Op.getOperand(7), // cachepolicy, swizzled buffer 8043 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 8044 }; 8045 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 8046 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8047 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8048 MemSDNode *M = cast<MemSDNode>(Op); 8049 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8050 8051 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8052 EVT VDataType = VData.getValueType().getScalarType(); 8053 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8054 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8055 8056 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8057 M->getMemoryVT(), M->getMemOperand()); 8058 } 8059 case Intrinsic::amdgcn_raw_buffer_load_lds: 8060 case Intrinsic::amdgcn_struct_buffer_load_lds: { 8061 unsigned Opc; 8062 bool HasVIndex = IntrinsicID == Intrinsic::amdgcn_struct_buffer_load_lds; 8063 unsigned OpOffset = HasVIndex ? 1 : 0; 8064 SDValue VOffset = Op.getOperand(5 + OpOffset); 8065 auto CVOffset = dyn_cast<ConstantSDNode>(VOffset); 8066 bool HasVOffset = !CVOffset || !CVOffset->isZero(); 8067 unsigned Size = Op->getConstantOperandVal(4); 8068 8069 switch (Size) { 8070 default: 8071 return SDValue(); 8072 case 1: 8073 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_BOTHEN 8074 : AMDGPU::BUFFER_LOAD_UBYTE_LDS_IDXEN 8075 : HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFEN 8076 : AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFSET; 8077 break; 8078 case 2: 8079 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_BOTHEN 8080 : AMDGPU::BUFFER_LOAD_USHORT_LDS_IDXEN 8081 : HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFEN 8082 : AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFSET; 8083 break; 8084 case 4: 8085 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_BOTHEN 8086 : AMDGPU::BUFFER_LOAD_DWORD_LDS_IDXEN 8087 : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFEN 8088 : AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFSET; 8089 break; 8090 } 8091 8092 SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 8093 8094 SmallVector<SDValue, 8> Ops; 8095 8096 if (HasVIndex && HasVOffset) 8097 Ops.push_back(DAG.getBuildVector(MVT::v2i32, DL, 8098 { Op.getOperand(5), // VIndex 8099 VOffset })); 8100 else if (HasVIndex) 8101 Ops.push_back(Op.getOperand(5)); 8102 else if (HasVOffset) 8103 Ops.push_back(VOffset); 8104 8105 Ops.push_back(Op.getOperand(2)); // rsrc 8106 Ops.push_back(Op.getOperand(6 + OpOffset)); // soffset 8107 Ops.push_back(Op.getOperand(7 + OpOffset)); // imm offset 8108 unsigned Aux = Op.getConstantOperandVal(8 + OpOffset); 8109 Ops.push_back( 8110 DAG.getTargetConstant(Aux & AMDGPU::CPol::ALL, DL, MVT::i8)); // cpol 8111 Ops.push_back( 8112 DAG.getTargetConstant((Aux >> 3) & 1, DL, MVT::i8)); // swz 8113 Ops.push_back(M0Val.getValue(0)); // Chain 8114 Ops.push_back(M0Val.getValue(1)); // Glue 8115 8116 auto *M = cast<MemSDNode>(Op); 8117 MachineMemOperand *LoadMMO = M->getMemOperand(); 8118 MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo(); 8119 LoadPtrI.Offset = Op->getConstantOperandVal(7 + OpOffset); 8120 MachinePointerInfo StorePtrI = LoadPtrI; 8121 StorePtrI.V = nullptr; 8122 StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS; 8123 8124 auto F = LoadMMO->getFlags() & 8125 ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad); 8126 LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad, 8127 Size, LoadMMO->getBaseAlign()); 8128 8129 MachineMemOperand *StoreMMO = 8130 MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore, 8131 sizeof(int32_t), LoadMMO->getBaseAlign()); 8132 8133 auto Load = DAG.getMachineNode(Opc, DL, M->getVTList(), Ops); 8134 DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO}); 8135 8136 return SDValue(Load, 0); 8137 } 8138 case Intrinsic::amdgcn_global_load_lds: { 8139 unsigned Opc; 8140 unsigned Size = Op->getConstantOperandVal(4); 8141 switch (Size) { 8142 default: 8143 return SDValue(); 8144 case 1: 8145 Opc = AMDGPU::GLOBAL_LOAD_LDS_UBYTE; 8146 break; 8147 case 2: 8148 Opc = AMDGPU::GLOBAL_LOAD_LDS_USHORT; 8149 break; 8150 case 4: 8151 Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORD; 8152 break; 8153 } 8154 8155 auto *M = cast<MemSDNode>(Op); 8156 SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 8157 8158 SmallVector<SDValue, 6> Ops; 8159 8160 SDValue Addr = Op.getOperand(2); // Global ptr 8161 SDValue VOffset; 8162 // Try to split SAddr and VOffset. Global and LDS pointers share the same 8163 // immediate offset, so we cannot use a regular SelectGlobalSAddr(). 8164 if (Addr->isDivergent() && Addr.getOpcode() == ISD::ADD) { 8165 SDValue LHS = Addr.getOperand(0); 8166 SDValue RHS = Addr.getOperand(1); 8167 8168 if (LHS->isDivergent()) 8169 std::swap(LHS, RHS); 8170 8171 if (!LHS->isDivergent() && RHS.getOpcode() == ISD::ZERO_EXTEND && 8172 RHS.getOperand(0).getValueType() == MVT::i32) { 8173 // add (i64 sgpr), (zero_extend (i32 vgpr)) 8174 Addr = LHS; 8175 VOffset = RHS.getOperand(0); 8176 } 8177 } 8178 8179 Ops.push_back(Addr); 8180 if (!Addr->isDivergent()) { 8181 Opc = AMDGPU::getGlobalSaddrOp(Opc); 8182 if (!VOffset) 8183 VOffset = SDValue( 8184 DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, DL, MVT::i32, 8185 DAG.getTargetConstant(0, DL, MVT::i32)), 0); 8186 Ops.push_back(VOffset); 8187 } 8188 8189 Ops.push_back(Op.getOperand(5)); // Offset 8190 Ops.push_back(Op.getOperand(6)); // CPol 8191 Ops.push_back(M0Val.getValue(0)); // Chain 8192 Ops.push_back(M0Val.getValue(1)); // Glue 8193 8194 MachineMemOperand *LoadMMO = M->getMemOperand(); 8195 MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo(); 8196 LoadPtrI.Offset = Op->getConstantOperandVal(5); 8197 MachinePointerInfo StorePtrI = LoadPtrI; 8198 LoadPtrI.AddrSpace = AMDGPUAS::GLOBAL_ADDRESS; 8199 StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS; 8200 auto F = LoadMMO->getFlags() & 8201 ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad); 8202 LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad, 8203 Size, LoadMMO->getBaseAlign()); 8204 MachineMemOperand *StoreMMO = 8205 MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore, 8206 sizeof(int32_t), Align(4)); 8207 8208 auto Load = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops); 8209 DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO}); 8210 8211 return SDValue(Load, 0); 8212 } 8213 case Intrinsic::amdgcn_end_cf: 8214 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 8215 Op->getOperand(2), Chain), 0); 8216 8217 default: { 8218 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 8219 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 8220 return lowerImage(Op, ImageDimIntr, DAG, true); 8221 8222 return Op; 8223 } 8224 } 8225 } 8226 8227 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 8228 // offset (the offset that is included in bounds checking and swizzling, to be 8229 // split between the instruction's voffset and immoffset fields) and soffset 8230 // (the offset that is excluded from bounds checking and swizzling, to go in 8231 // the instruction's soffset field). This function takes the first kind of 8232 // offset and figures out how to split it between voffset and immoffset. 8233 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 8234 SDValue Offset, SelectionDAG &DAG) const { 8235 SDLoc DL(Offset); 8236 const unsigned MaxImm = 4095; 8237 SDValue N0 = Offset; 8238 ConstantSDNode *C1 = nullptr; 8239 8240 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 8241 N0 = SDValue(); 8242 else if (DAG.isBaseWithConstantOffset(N0)) { 8243 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 8244 N0 = N0.getOperand(0); 8245 } 8246 8247 if (C1) { 8248 unsigned ImmOffset = C1->getZExtValue(); 8249 // If the immediate value is too big for the immoffset field, put the value 8250 // and -4096 into the immoffset field so that the value that is copied/added 8251 // for the voffset field is a multiple of 4096, and it stands more chance 8252 // of being CSEd with the copy/add for another similar load/store. 8253 // However, do not do that rounding down to a multiple of 4096 if that is a 8254 // negative number, as it appears to be illegal to have a negative offset 8255 // in the vgpr, even if adding the immediate offset makes it positive. 8256 unsigned Overflow = ImmOffset & ~MaxImm; 8257 ImmOffset -= Overflow; 8258 if ((int32_t)Overflow < 0) { 8259 Overflow += ImmOffset; 8260 ImmOffset = 0; 8261 } 8262 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 8263 if (Overflow) { 8264 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 8265 if (!N0) 8266 N0 = OverflowVal; 8267 else { 8268 SDValue Ops[] = { N0, OverflowVal }; 8269 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 8270 } 8271 } 8272 } 8273 if (!N0) 8274 N0 = DAG.getConstant(0, DL, MVT::i32); 8275 if (!C1) 8276 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 8277 return {N0, SDValue(C1, 0)}; 8278 } 8279 8280 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 8281 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 8282 // pointed to by Offsets. 8283 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 8284 SelectionDAG &DAG, SDValue *Offsets, 8285 Align Alignment) const { 8286 SDLoc DL(CombinedOffset); 8287 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 8288 uint32_t Imm = C->getZExtValue(); 8289 uint32_t SOffset, ImmOffset; 8290 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 8291 Alignment)) { 8292 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 8293 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8294 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8295 return; 8296 } 8297 } 8298 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 8299 SDValue N0 = CombinedOffset.getOperand(0); 8300 SDValue N1 = CombinedOffset.getOperand(1); 8301 uint32_t SOffset, ImmOffset; 8302 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 8303 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 8304 Subtarget, Alignment)) { 8305 Offsets[0] = N0; 8306 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8307 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8308 return; 8309 } 8310 } 8311 Offsets[0] = CombinedOffset; 8312 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 8313 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 8314 } 8315 8316 // Handle 8 bit and 16 bit buffer loads 8317 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 8318 EVT LoadVT, SDLoc DL, 8319 ArrayRef<SDValue> Ops, 8320 MemSDNode *M) const { 8321 EVT IntVT = LoadVT.changeTypeToInteger(); 8322 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 8323 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 8324 8325 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 8326 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 8327 Ops, IntVT, 8328 M->getMemOperand()); 8329 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 8330 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 8331 8332 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 8333 } 8334 8335 // Handle 8 bit and 16 bit buffer stores 8336 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 8337 EVT VDataType, SDLoc DL, 8338 SDValue Ops[], 8339 MemSDNode *M) const { 8340 if (VDataType == MVT::f16) 8341 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 8342 8343 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 8344 Ops[1] = BufferStoreExt; 8345 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 8346 AMDGPUISD::BUFFER_STORE_SHORT; 8347 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 8348 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 8349 M->getMemOperand()); 8350 } 8351 8352 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 8353 ISD::LoadExtType ExtType, SDValue Op, 8354 const SDLoc &SL, EVT VT) { 8355 if (VT.bitsLT(Op.getValueType())) 8356 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 8357 8358 switch (ExtType) { 8359 case ISD::SEXTLOAD: 8360 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 8361 case ISD::ZEXTLOAD: 8362 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 8363 case ISD::EXTLOAD: 8364 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 8365 case ISD::NON_EXTLOAD: 8366 return Op; 8367 } 8368 8369 llvm_unreachable("invalid ext type"); 8370 } 8371 8372 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 8373 SelectionDAG &DAG = DCI.DAG; 8374 if (Ld->getAlign() < Align(4) || Ld->isDivergent()) 8375 return SDValue(); 8376 8377 // FIXME: Constant loads should all be marked invariant. 8378 unsigned AS = Ld->getAddressSpace(); 8379 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 8380 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 8381 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 8382 return SDValue(); 8383 8384 // Don't do this early, since it may interfere with adjacent load merging for 8385 // illegal types. We can avoid losing alignment information for exotic types 8386 // pre-legalize. 8387 EVT MemVT = Ld->getMemoryVT(); 8388 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 8389 MemVT.getSizeInBits() >= 32) 8390 return SDValue(); 8391 8392 SDLoc SL(Ld); 8393 8394 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 8395 "unexpected vector extload"); 8396 8397 // TODO: Drop only high part of range. 8398 SDValue Ptr = Ld->getBasePtr(); 8399 SDValue NewLoad = DAG.getLoad( 8400 ISD::UNINDEXED, ISD::NON_EXTLOAD, MVT::i32, SL, Ld->getChain(), Ptr, 8401 Ld->getOffset(), Ld->getPointerInfo(), MVT::i32, Ld->getAlign(), 8402 Ld->getMemOperand()->getFlags(), Ld->getAAInfo(), 8403 nullptr); // Drop ranges 8404 8405 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 8406 if (MemVT.isFloatingPoint()) { 8407 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 8408 "unexpected fp extload"); 8409 TruncVT = MemVT.changeTypeToInteger(); 8410 } 8411 8412 SDValue Cvt = NewLoad; 8413 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 8414 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 8415 DAG.getValueType(TruncVT)); 8416 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 8417 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 8418 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 8419 } else { 8420 assert(Ld->getExtensionType() == ISD::EXTLOAD); 8421 } 8422 8423 EVT VT = Ld->getValueType(0); 8424 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8425 8426 DCI.AddToWorklist(Cvt.getNode()); 8427 8428 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8429 // the appropriate extension from the 32-bit load. 8430 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8431 DCI.AddToWorklist(Cvt.getNode()); 8432 8433 // Handle conversion back to floating point if necessary. 8434 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8435 8436 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8437 } 8438 8439 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8440 SDLoc DL(Op); 8441 LoadSDNode *Load = cast<LoadSDNode>(Op); 8442 ISD::LoadExtType ExtType = Load->getExtensionType(); 8443 EVT MemVT = Load->getMemoryVT(); 8444 8445 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8446 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8447 return SDValue(); 8448 8449 // FIXME: Copied from PPC 8450 // First, load into 32 bits, then truncate to 1 bit. 8451 8452 SDValue Chain = Load->getChain(); 8453 SDValue BasePtr = Load->getBasePtr(); 8454 MachineMemOperand *MMO = Load->getMemOperand(); 8455 8456 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8457 8458 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8459 BasePtr, RealMemVT, MMO); 8460 8461 if (!MemVT.isVector()) { 8462 SDValue Ops[] = { 8463 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8464 NewLD.getValue(1) 8465 }; 8466 8467 return DAG.getMergeValues(Ops, DL); 8468 } 8469 8470 SmallVector<SDValue, 3> Elts; 8471 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8472 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8473 DAG.getConstant(I, DL, MVT::i32)); 8474 8475 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8476 } 8477 8478 SDValue Ops[] = { 8479 DAG.getBuildVector(MemVT, DL, Elts), 8480 NewLD.getValue(1) 8481 }; 8482 8483 return DAG.getMergeValues(Ops, DL); 8484 } 8485 8486 if (!MemVT.isVector()) 8487 return SDValue(); 8488 8489 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8490 "Custom lowering for non-i32 vectors hasn't been implemented."); 8491 8492 Align Alignment = Load->getAlign(); 8493 unsigned AS = Load->getAddressSpace(); 8494 if (Subtarget->hasLDSMisalignedBug() && AS == AMDGPUAS::FLAT_ADDRESS && 8495 Alignment.value() < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8496 return SplitVectorLoad(Op, DAG); 8497 } 8498 8499 MachineFunction &MF = DAG.getMachineFunction(); 8500 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8501 // If there is a possibility that flat instruction access scratch memory 8502 // then we need to use the same legalization rules we use for private. 8503 if (AS == AMDGPUAS::FLAT_ADDRESS && 8504 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8505 AS = MFI->hasFlatScratchInit() ? 8506 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8507 8508 unsigned NumElements = MemVT.getVectorNumElements(); 8509 8510 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8511 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8512 if (!Op->isDivergent() && Alignment >= Align(4) && NumElements < 32) { 8513 if (MemVT.isPow2VectorType()) 8514 return SDValue(); 8515 return WidenOrSplitVectorLoad(Op, DAG); 8516 } 8517 // Non-uniform loads will be selected to MUBUF instructions, so they 8518 // have the same legalization requirements as global and private 8519 // loads. 8520 // 8521 } 8522 8523 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8524 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8525 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8526 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8527 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8528 Alignment >= Align(4) && NumElements < 32) { 8529 if (MemVT.isPow2VectorType()) 8530 return SDValue(); 8531 return WidenOrSplitVectorLoad(Op, DAG); 8532 } 8533 // Non-uniform loads will be selected to MUBUF instructions, so they 8534 // have the same legalization requirements as global and private 8535 // loads. 8536 // 8537 } 8538 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8539 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8540 AS == AMDGPUAS::GLOBAL_ADDRESS || 8541 AS == AMDGPUAS::FLAT_ADDRESS) { 8542 if (NumElements > 4) 8543 return SplitVectorLoad(Op, DAG); 8544 // v3 loads not supported on SI. 8545 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8546 return WidenOrSplitVectorLoad(Op, DAG); 8547 8548 // v3 and v4 loads are supported for private and global memory. 8549 return SDValue(); 8550 } 8551 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8552 // Depending on the setting of the private_element_size field in the 8553 // resource descriptor, we can only make private accesses up to a certain 8554 // size. 8555 switch (Subtarget->getMaxPrivateElementSize()) { 8556 case 4: { 8557 SDValue Ops[2]; 8558 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8559 return DAG.getMergeValues(Ops, DL); 8560 } 8561 case 8: 8562 if (NumElements > 2) 8563 return SplitVectorLoad(Op, DAG); 8564 return SDValue(); 8565 case 16: 8566 // Same as global/flat 8567 if (NumElements > 4) 8568 return SplitVectorLoad(Op, DAG); 8569 // v3 loads not supported on SI. 8570 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8571 return WidenOrSplitVectorLoad(Op, DAG); 8572 8573 return SDValue(); 8574 default: 8575 llvm_unreachable("unsupported private_element_size"); 8576 } 8577 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8578 bool Fast = false; 8579 auto Flags = Load->getMemOperand()->getFlags(); 8580 if (allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8581 Load->getAlign(), Flags, &Fast) && 8582 Fast) 8583 return SDValue(); 8584 8585 if (MemVT.isVector()) 8586 return SplitVectorLoad(Op, DAG); 8587 } 8588 8589 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8590 MemVT, *Load->getMemOperand())) { 8591 SDValue Ops[2]; 8592 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8593 return DAG.getMergeValues(Ops, DL); 8594 } 8595 8596 return SDValue(); 8597 } 8598 8599 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8600 EVT VT = Op.getValueType(); 8601 if (VT.getSizeInBits() == 128) 8602 return splitTernaryVectorOp(Op, DAG); 8603 8604 assert(VT.getSizeInBits() == 64); 8605 8606 SDLoc DL(Op); 8607 SDValue Cond = Op.getOperand(0); 8608 8609 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8610 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8611 8612 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8613 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8614 8615 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8616 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8617 8618 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8619 8620 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8621 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8622 8623 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8624 8625 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8626 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8627 } 8628 8629 // Catch division cases where we can use shortcuts with rcp and rsq 8630 // instructions. 8631 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8632 SelectionDAG &DAG) const { 8633 SDLoc SL(Op); 8634 SDValue LHS = Op.getOperand(0); 8635 SDValue RHS = Op.getOperand(1); 8636 EVT VT = Op.getValueType(); 8637 const SDNodeFlags Flags = Op->getFlags(); 8638 8639 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8640 8641 // Without !fpmath accuracy information, we can't do more because we don't 8642 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8643 if (!AllowInaccurateRcp) 8644 return SDValue(); 8645 8646 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8647 if (CLHS->isExactlyValue(1.0)) { 8648 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8649 // the CI documentation has a worst case error of 1 ulp. 8650 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8651 // use it as long as we aren't trying to use denormals. 8652 // 8653 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8654 8655 // 1.0 / sqrt(x) -> rsq(x) 8656 8657 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8658 // error seems really high at 2^29 ULP. 8659 if (RHS.getOpcode() == ISD::FSQRT) 8660 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8661 8662 // 1.0 / x -> rcp(x) 8663 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8664 } 8665 8666 // Same as for 1.0, but expand the sign out of the constant. 8667 if (CLHS->isExactlyValue(-1.0)) { 8668 // -1.0 / x -> rcp (fneg x) 8669 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8670 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8671 } 8672 } 8673 8674 // Turn into multiply by the reciprocal. 8675 // x / y -> x * (1.0 / y) 8676 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8677 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8678 } 8679 8680 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8681 SelectionDAG &DAG) const { 8682 SDLoc SL(Op); 8683 SDValue X = Op.getOperand(0); 8684 SDValue Y = Op.getOperand(1); 8685 EVT VT = Op.getValueType(); 8686 const SDNodeFlags Flags = Op->getFlags(); 8687 8688 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8689 DAG.getTarget().Options.UnsafeFPMath; 8690 if (!AllowInaccurateDiv) 8691 return SDValue(); 8692 8693 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8694 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8695 8696 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8697 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8698 8699 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8700 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8701 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8702 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8703 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8704 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8705 } 8706 8707 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8708 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8709 SDNodeFlags Flags) { 8710 if (GlueChain->getNumValues() <= 1) { 8711 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8712 } 8713 8714 assert(GlueChain->getNumValues() == 3); 8715 8716 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8717 switch (Opcode) { 8718 default: llvm_unreachable("no chain equivalent for opcode"); 8719 case ISD::FMUL: 8720 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8721 break; 8722 } 8723 8724 return DAG.getNode(Opcode, SL, VTList, 8725 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8726 Flags); 8727 } 8728 8729 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8730 EVT VT, SDValue A, SDValue B, SDValue C, 8731 SDValue GlueChain, SDNodeFlags Flags) { 8732 if (GlueChain->getNumValues() <= 1) { 8733 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8734 } 8735 8736 assert(GlueChain->getNumValues() == 3); 8737 8738 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8739 switch (Opcode) { 8740 default: llvm_unreachable("no chain equivalent for opcode"); 8741 case ISD::FMA: 8742 Opcode = AMDGPUISD::FMA_W_CHAIN; 8743 break; 8744 } 8745 8746 return DAG.getNode(Opcode, SL, VTList, 8747 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8748 Flags); 8749 } 8750 8751 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8752 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8753 return FastLowered; 8754 8755 SDLoc SL(Op); 8756 SDValue Src0 = Op.getOperand(0); 8757 SDValue Src1 = Op.getOperand(1); 8758 8759 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8760 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8761 8762 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8763 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8764 8765 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8766 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8767 8768 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8769 } 8770 8771 // Faster 2.5 ULP division that does not support denormals. 8772 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8773 SDLoc SL(Op); 8774 SDValue LHS = Op.getOperand(1); 8775 SDValue RHS = Op.getOperand(2); 8776 8777 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8778 8779 const APFloat K0Val(BitsToFloat(0x6f800000)); 8780 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8781 8782 const APFloat K1Val(BitsToFloat(0x2f800000)); 8783 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8784 8785 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8786 8787 EVT SetCCVT = 8788 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8789 8790 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8791 8792 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8793 8794 // TODO: Should this propagate fast-math-flags? 8795 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8796 8797 // rcp does not support denormals. 8798 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8799 8800 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8801 8802 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8803 } 8804 8805 // Returns immediate value for setting the F32 denorm mode when using the 8806 // S_DENORM_MODE instruction. 8807 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8808 const SDLoc &SL, const GCNSubtarget *ST) { 8809 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8810 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8811 ? FP_DENORM_FLUSH_NONE 8812 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8813 8814 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8815 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8816 } 8817 8818 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8819 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8820 return FastLowered; 8821 8822 // The selection matcher assumes anything with a chain selecting to a 8823 // mayRaiseFPException machine instruction. Since we're introducing a chain 8824 // here, we need to explicitly report nofpexcept for the regular fdiv 8825 // lowering. 8826 SDNodeFlags Flags = Op->getFlags(); 8827 Flags.setNoFPExcept(true); 8828 8829 SDLoc SL(Op); 8830 SDValue LHS = Op.getOperand(0); 8831 SDValue RHS = Op.getOperand(1); 8832 8833 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8834 8835 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8836 8837 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8838 {RHS, RHS, LHS}, Flags); 8839 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8840 {LHS, RHS, LHS}, Flags); 8841 8842 // Denominator is scaled to not be denormal, so using rcp is ok. 8843 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8844 DenominatorScaled, Flags); 8845 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8846 DenominatorScaled, Flags); 8847 8848 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8849 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8850 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8851 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8852 8853 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8854 8855 if (!HasFP32Denormals) { 8856 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8857 // lowering. The chain dependence is insufficient, and we need glue. We do 8858 // not need the glue variants in a strictfp function. 8859 8860 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8861 8862 SDNode *EnableDenorm; 8863 if (Subtarget->hasDenormModeInst()) { 8864 const SDValue EnableDenormValue = 8865 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8866 8867 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8868 DAG.getEntryNode(), EnableDenormValue).getNode(); 8869 } else { 8870 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8871 SL, MVT::i32); 8872 EnableDenorm = 8873 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8874 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8875 } 8876 8877 SDValue Ops[3] = { 8878 NegDivScale0, 8879 SDValue(EnableDenorm, 0), 8880 SDValue(EnableDenorm, 1) 8881 }; 8882 8883 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8884 } 8885 8886 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8887 ApproxRcp, One, NegDivScale0, Flags); 8888 8889 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8890 ApproxRcp, Fma0, Flags); 8891 8892 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8893 Fma1, Fma1, Flags); 8894 8895 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8896 NumeratorScaled, Mul, Flags); 8897 8898 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8899 Fma2, Fma1, Mul, Fma2, Flags); 8900 8901 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8902 NumeratorScaled, Fma3, Flags); 8903 8904 if (!HasFP32Denormals) { 8905 SDNode *DisableDenorm; 8906 if (Subtarget->hasDenormModeInst()) { 8907 const SDValue DisableDenormValue = 8908 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8909 8910 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8911 Fma4.getValue(1), DisableDenormValue, 8912 Fma4.getValue(2)).getNode(); 8913 } else { 8914 const SDValue DisableDenormValue = 8915 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8916 8917 DisableDenorm = DAG.getMachineNode( 8918 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8919 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8920 } 8921 8922 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8923 SDValue(DisableDenorm, 0), DAG.getRoot()); 8924 DAG.setRoot(OutputChain); 8925 } 8926 8927 SDValue Scale = NumeratorScaled.getValue(1); 8928 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8929 {Fma4, Fma1, Fma3, Scale}, Flags); 8930 8931 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8932 } 8933 8934 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8935 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8936 return FastLowered; 8937 8938 SDLoc SL(Op); 8939 SDValue X = Op.getOperand(0); 8940 SDValue Y = Op.getOperand(1); 8941 8942 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8943 8944 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8945 8946 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8947 8948 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8949 8950 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8951 8952 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8953 8954 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8955 8956 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8957 8958 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8959 8960 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8961 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8962 8963 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8964 NegDivScale0, Mul, DivScale1); 8965 8966 SDValue Scale; 8967 8968 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8969 // Workaround a hardware bug on SI where the condition output from div_scale 8970 // is not usable. 8971 8972 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8973 8974 // Figure out if the scale to use for div_fmas. 8975 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8976 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8977 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8978 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8979 8980 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8981 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8982 8983 SDValue Scale0Hi 8984 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8985 SDValue Scale1Hi 8986 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8987 8988 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8989 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8990 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8991 } else { 8992 Scale = DivScale1.getValue(1); 8993 } 8994 8995 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8996 Fma4, Fma3, Mul, Scale); 8997 8998 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8999 } 9000 9001 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 9002 EVT VT = Op.getValueType(); 9003 9004 if (VT == MVT::f32) 9005 return LowerFDIV32(Op, DAG); 9006 9007 if (VT == MVT::f64) 9008 return LowerFDIV64(Op, DAG); 9009 9010 if (VT == MVT::f16) 9011 return LowerFDIV16(Op, DAG); 9012 9013 llvm_unreachable("Unexpected type for fdiv"); 9014 } 9015 9016 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 9017 SDLoc DL(Op); 9018 StoreSDNode *Store = cast<StoreSDNode>(Op); 9019 EVT VT = Store->getMemoryVT(); 9020 9021 if (VT == MVT::i1) { 9022 return DAG.getTruncStore(Store->getChain(), DL, 9023 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 9024 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 9025 } 9026 9027 assert(VT.isVector() && 9028 Store->getValue().getValueType().getScalarType() == MVT::i32); 9029 9030 unsigned AS = Store->getAddressSpace(); 9031 if (Subtarget->hasLDSMisalignedBug() && 9032 AS == AMDGPUAS::FLAT_ADDRESS && 9033 Store->getAlign().value() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 9034 return SplitVectorStore(Op, DAG); 9035 } 9036 9037 MachineFunction &MF = DAG.getMachineFunction(); 9038 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 9039 // If there is a possibility that flat instruction access scratch memory 9040 // then we need to use the same legalization rules we use for private. 9041 if (AS == AMDGPUAS::FLAT_ADDRESS && 9042 !Subtarget->hasMultiDwordFlatScratchAddressing()) 9043 AS = MFI->hasFlatScratchInit() ? 9044 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 9045 9046 unsigned NumElements = VT.getVectorNumElements(); 9047 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 9048 AS == AMDGPUAS::FLAT_ADDRESS) { 9049 if (NumElements > 4) 9050 return SplitVectorStore(Op, DAG); 9051 // v3 stores not supported on SI. 9052 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 9053 return SplitVectorStore(Op, DAG); 9054 9055 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 9056 VT, *Store->getMemOperand())) 9057 return expandUnalignedStore(Store, DAG); 9058 9059 return SDValue(); 9060 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 9061 switch (Subtarget->getMaxPrivateElementSize()) { 9062 case 4: 9063 return scalarizeVectorStore(Store, DAG); 9064 case 8: 9065 if (NumElements > 2) 9066 return SplitVectorStore(Op, DAG); 9067 return SDValue(); 9068 case 16: 9069 if (NumElements > 4 || 9070 (NumElements == 3 && !Subtarget->enableFlatScratch())) 9071 return SplitVectorStore(Op, DAG); 9072 return SDValue(); 9073 default: 9074 llvm_unreachable("unsupported private_element_size"); 9075 } 9076 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 9077 bool Fast = false; 9078 auto Flags = Store->getMemOperand()->getFlags(); 9079 if (allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 9080 Store->getAlign(), Flags, &Fast) && 9081 Fast) 9082 return SDValue(); 9083 9084 if (VT.isVector()) 9085 return SplitVectorStore(Op, DAG); 9086 9087 return expandUnalignedStore(Store, DAG); 9088 } 9089 9090 // Probably an invalid store. If so we'll end up emitting a selection error. 9091 return SDValue(); 9092 } 9093 9094 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 9095 SDLoc DL(Op); 9096 EVT VT = Op.getValueType(); 9097 SDValue Arg = Op.getOperand(0); 9098 SDValue TrigVal; 9099 9100 // Propagate fast-math flags so that the multiply we introduce can be folded 9101 // if Arg is already the result of a multiply by constant. 9102 auto Flags = Op->getFlags(); 9103 9104 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 9105 9106 if (Subtarget->hasTrigReducedRange()) { 9107 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9108 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 9109 } else { 9110 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9111 } 9112 9113 switch (Op.getOpcode()) { 9114 case ISD::FCOS: 9115 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 9116 case ISD::FSIN: 9117 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 9118 default: 9119 llvm_unreachable("Wrong trig opcode"); 9120 } 9121 } 9122 9123 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 9124 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 9125 assert(AtomicNode->isCompareAndSwap()); 9126 unsigned AS = AtomicNode->getAddressSpace(); 9127 9128 // No custom lowering required for local address space 9129 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 9130 return Op; 9131 9132 // Non-local address space requires custom lowering for atomic compare 9133 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 9134 SDLoc DL(Op); 9135 SDValue ChainIn = Op.getOperand(0); 9136 SDValue Addr = Op.getOperand(1); 9137 SDValue Old = Op.getOperand(2); 9138 SDValue New = Op.getOperand(3); 9139 EVT VT = Op.getValueType(); 9140 MVT SimpleVT = VT.getSimpleVT(); 9141 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 9142 9143 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 9144 SDValue Ops[] = { ChainIn, Addr, NewOld }; 9145 9146 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 9147 Ops, VT, AtomicNode->getMemOperand()); 9148 } 9149 9150 //===----------------------------------------------------------------------===// 9151 // Custom DAG optimizations 9152 //===----------------------------------------------------------------------===// 9153 9154 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 9155 DAGCombinerInfo &DCI) const { 9156 EVT VT = N->getValueType(0); 9157 EVT ScalarVT = VT.getScalarType(); 9158 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 9159 return SDValue(); 9160 9161 SelectionDAG &DAG = DCI.DAG; 9162 SDLoc DL(N); 9163 9164 SDValue Src = N->getOperand(0); 9165 EVT SrcVT = Src.getValueType(); 9166 9167 // TODO: We could try to match extracting the higher bytes, which would be 9168 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 9169 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 9170 // about in practice. 9171 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 9172 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 9173 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 9174 DCI.AddToWorklist(Cvt.getNode()); 9175 9176 // For the f16 case, fold to a cast to f32 and then cast back to f16. 9177 if (ScalarVT != MVT::f32) { 9178 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 9179 DAG.getTargetConstant(0, DL, MVT::i32)); 9180 } 9181 return Cvt; 9182 } 9183 } 9184 9185 return SDValue(); 9186 } 9187 9188 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 9189 9190 // This is a variant of 9191 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 9192 // 9193 // The normal DAG combiner will do this, but only if the add has one use since 9194 // that would increase the number of instructions. 9195 // 9196 // This prevents us from seeing a constant offset that can be folded into a 9197 // memory instruction's addressing mode. If we know the resulting add offset of 9198 // a pointer can be folded into an addressing offset, we can replace the pointer 9199 // operand with the add of new constant offset. This eliminates one of the uses, 9200 // and may allow the remaining use to also be simplified. 9201 // 9202 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 9203 unsigned AddrSpace, 9204 EVT MemVT, 9205 DAGCombinerInfo &DCI) const { 9206 SDValue N0 = N->getOperand(0); 9207 SDValue N1 = N->getOperand(1); 9208 9209 // We only do this to handle cases where it's profitable when there are 9210 // multiple uses of the add, so defer to the standard combine. 9211 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 9212 N0->hasOneUse()) 9213 return SDValue(); 9214 9215 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 9216 if (!CN1) 9217 return SDValue(); 9218 9219 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 9220 if (!CAdd) 9221 return SDValue(); 9222 9223 // If the resulting offset is too large, we can't fold it into the addressing 9224 // mode offset. 9225 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 9226 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 9227 9228 AddrMode AM; 9229 AM.HasBaseReg = true; 9230 AM.BaseOffs = Offset.getSExtValue(); 9231 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 9232 return SDValue(); 9233 9234 SelectionDAG &DAG = DCI.DAG; 9235 SDLoc SL(N); 9236 EVT VT = N->getValueType(0); 9237 9238 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 9239 SDValue COffset = DAG.getConstant(Offset, SL, VT); 9240 9241 SDNodeFlags Flags; 9242 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 9243 (N0.getOpcode() == ISD::OR || 9244 N0->getFlags().hasNoUnsignedWrap())); 9245 9246 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 9247 } 9248 9249 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 9250 /// by the chain and intrinsic ID. Theoretically we would also need to check the 9251 /// specific intrinsic, but they all place the pointer operand first. 9252 static unsigned getBasePtrIndex(const MemSDNode *N) { 9253 switch (N->getOpcode()) { 9254 case ISD::STORE: 9255 case ISD::INTRINSIC_W_CHAIN: 9256 case ISD::INTRINSIC_VOID: 9257 return 2; 9258 default: 9259 return 1; 9260 } 9261 } 9262 9263 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 9264 DAGCombinerInfo &DCI) const { 9265 SelectionDAG &DAG = DCI.DAG; 9266 SDLoc SL(N); 9267 9268 unsigned PtrIdx = getBasePtrIndex(N); 9269 SDValue Ptr = N->getOperand(PtrIdx); 9270 9271 // TODO: We could also do this for multiplies. 9272 if (Ptr.getOpcode() == ISD::SHL) { 9273 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 9274 N->getMemoryVT(), DCI); 9275 if (NewPtr) { 9276 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 9277 9278 NewOps[PtrIdx] = NewPtr; 9279 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 9280 } 9281 } 9282 9283 return SDValue(); 9284 } 9285 9286 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 9287 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 9288 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 9289 (Opc == ISD::XOR && Val == 0); 9290 } 9291 9292 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 9293 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 9294 // integer combine opportunities since most 64-bit operations are decomposed 9295 // this way. TODO: We won't want this for SALU especially if it is an inline 9296 // immediate. 9297 SDValue SITargetLowering::splitBinaryBitConstantOp( 9298 DAGCombinerInfo &DCI, 9299 const SDLoc &SL, 9300 unsigned Opc, SDValue LHS, 9301 const ConstantSDNode *CRHS) const { 9302 uint64_t Val = CRHS->getZExtValue(); 9303 uint32_t ValLo = Lo_32(Val); 9304 uint32_t ValHi = Hi_32(Val); 9305 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9306 9307 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 9308 bitOpWithConstantIsReducible(Opc, ValHi)) || 9309 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 9310 // If we need to materialize a 64-bit immediate, it will be split up later 9311 // anyway. Avoid creating the harder to understand 64-bit immediate 9312 // materialization. 9313 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 9314 } 9315 9316 return SDValue(); 9317 } 9318 9319 // Returns true if argument is a boolean value which is not serialized into 9320 // memory or argument and does not require v_cndmask_b32 to be deserialized. 9321 static bool isBoolSGPR(SDValue V) { 9322 if (V.getValueType() != MVT::i1) 9323 return false; 9324 switch (V.getOpcode()) { 9325 default: 9326 break; 9327 case ISD::SETCC: 9328 case AMDGPUISD::FP_CLASS: 9329 return true; 9330 case ISD::AND: 9331 case ISD::OR: 9332 case ISD::XOR: 9333 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 9334 } 9335 return false; 9336 } 9337 9338 // If a constant has all zeroes or all ones within each byte return it. 9339 // Otherwise return 0. 9340 static uint32_t getConstantPermuteMask(uint32_t C) { 9341 // 0xff for any zero byte in the mask 9342 uint32_t ZeroByteMask = 0; 9343 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 9344 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 9345 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 9346 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 9347 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 9348 if ((NonZeroByteMask & C) != NonZeroByteMask) 9349 return 0; // Partial bytes selected. 9350 return C; 9351 } 9352 9353 // Check if a node selects whole bytes from its operand 0 starting at a byte 9354 // boundary while masking the rest. Returns select mask as in the v_perm_b32 9355 // or -1 if not succeeded. 9356 // Note byte select encoding: 9357 // value 0-3 selects corresponding source byte; 9358 // value 0xc selects zero; 9359 // value 0xff selects 0xff. 9360 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 9361 assert(V.getValueSizeInBits() == 32); 9362 9363 if (V.getNumOperands() != 2) 9364 return ~0; 9365 9366 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 9367 if (!N1) 9368 return ~0; 9369 9370 uint32_t C = N1->getZExtValue(); 9371 9372 switch (V.getOpcode()) { 9373 default: 9374 break; 9375 case ISD::AND: 9376 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9377 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 9378 } 9379 break; 9380 9381 case ISD::OR: 9382 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9383 return (0x03020100 & ~ConstMask) | ConstMask; 9384 } 9385 break; 9386 9387 case ISD::SHL: 9388 if (C % 8) 9389 return ~0; 9390 9391 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 9392 9393 case ISD::SRL: 9394 if (C % 8) 9395 return ~0; 9396 9397 return uint32_t(0x0c0c0c0c03020100ull >> C); 9398 } 9399 9400 return ~0; 9401 } 9402 9403 SDValue SITargetLowering::performAndCombine(SDNode *N, 9404 DAGCombinerInfo &DCI) const { 9405 if (DCI.isBeforeLegalize()) 9406 return SDValue(); 9407 9408 SelectionDAG &DAG = DCI.DAG; 9409 EVT VT = N->getValueType(0); 9410 SDValue LHS = N->getOperand(0); 9411 SDValue RHS = N->getOperand(1); 9412 9413 9414 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9415 if (VT == MVT::i64 && CRHS) { 9416 if (SDValue Split 9417 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9418 return Split; 9419 } 9420 9421 if (CRHS && VT == MVT::i32) { 9422 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9423 // nb = number of trailing zeroes in mask 9424 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9425 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9426 uint64_t Mask = CRHS->getZExtValue(); 9427 unsigned Bits = countPopulation(Mask); 9428 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9429 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9430 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9431 unsigned Shift = CShift->getZExtValue(); 9432 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9433 unsigned Offset = NB + Shift; 9434 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9435 SDLoc SL(N); 9436 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9437 LHS->getOperand(0), 9438 DAG.getConstant(Offset, SL, MVT::i32), 9439 DAG.getConstant(Bits, SL, MVT::i32)); 9440 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9441 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9442 DAG.getValueType(NarrowVT)); 9443 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9444 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9445 return Shl; 9446 } 9447 } 9448 } 9449 9450 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9451 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9452 isa<ConstantSDNode>(LHS.getOperand(2))) { 9453 uint32_t Sel = getConstantPermuteMask(Mask); 9454 if (!Sel) 9455 return SDValue(); 9456 9457 // Select 0xc for all zero bytes 9458 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9459 SDLoc DL(N); 9460 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9461 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9462 } 9463 } 9464 9465 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9466 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9467 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9468 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9469 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9470 9471 SDValue X = LHS.getOperand(0); 9472 SDValue Y = RHS.getOperand(0); 9473 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9474 return SDValue(); 9475 9476 if (LCC == ISD::SETO) { 9477 if (X != LHS.getOperand(1)) 9478 return SDValue(); 9479 9480 if (RCC == ISD::SETUNE) { 9481 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9482 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9483 return SDValue(); 9484 9485 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9486 SIInstrFlags::N_SUBNORMAL | 9487 SIInstrFlags::N_ZERO | 9488 SIInstrFlags::P_ZERO | 9489 SIInstrFlags::P_SUBNORMAL | 9490 SIInstrFlags::P_NORMAL; 9491 9492 static_assert(((~(SIInstrFlags::S_NAN | 9493 SIInstrFlags::Q_NAN | 9494 SIInstrFlags::N_INFINITY | 9495 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9496 "mask not equal"); 9497 9498 SDLoc DL(N); 9499 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9500 X, DAG.getConstant(Mask, DL, MVT::i32)); 9501 } 9502 } 9503 } 9504 9505 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9506 std::swap(LHS, RHS); 9507 9508 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9509 RHS.hasOneUse()) { 9510 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9511 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9512 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9513 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9514 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9515 (RHS.getOperand(0) == LHS.getOperand(0) && 9516 LHS.getOperand(0) == LHS.getOperand(1))) { 9517 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9518 unsigned NewMask = LCC == ISD::SETO ? 9519 Mask->getZExtValue() & ~OrdMask : 9520 Mask->getZExtValue() & OrdMask; 9521 9522 SDLoc DL(N); 9523 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9524 DAG.getConstant(NewMask, DL, MVT::i32)); 9525 } 9526 } 9527 9528 if (VT == MVT::i32 && 9529 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9530 // and x, (sext cc from i1) => select cc, x, 0 9531 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9532 std::swap(LHS, RHS); 9533 if (isBoolSGPR(RHS.getOperand(0))) 9534 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9535 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9536 } 9537 9538 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9539 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9540 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9541 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9542 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9543 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9544 if (LHSMask != ~0u && RHSMask != ~0u) { 9545 // Canonicalize the expression in an attempt to have fewer unique masks 9546 // and therefore fewer registers used to hold the masks. 9547 if (LHSMask > RHSMask) { 9548 std::swap(LHSMask, RHSMask); 9549 std::swap(LHS, RHS); 9550 } 9551 9552 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9553 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9554 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9555 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9556 9557 // Check of we need to combine values from two sources within a byte. 9558 if (!(LHSUsedLanes & RHSUsedLanes) && 9559 // If we select high and lower word keep it for SDWA. 9560 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9561 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9562 // Each byte in each mask is either selector mask 0-3, or has higher 9563 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9564 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9565 // mask which is not 0xff wins. By anding both masks we have a correct 9566 // result except that 0x0c shall be corrected to give 0x0c only. 9567 uint32_t Mask = LHSMask & RHSMask; 9568 for (unsigned I = 0; I < 32; I += 8) { 9569 uint32_t ByteSel = 0xff << I; 9570 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9571 Mask &= (0x0c << I) & 0xffffffff; 9572 } 9573 9574 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9575 // or 0x0c. 9576 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9577 SDLoc DL(N); 9578 9579 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9580 LHS.getOperand(0), RHS.getOperand(0), 9581 DAG.getConstant(Sel, DL, MVT::i32)); 9582 } 9583 } 9584 } 9585 9586 return SDValue(); 9587 } 9588 9589 SDValue SITargetLowering::performOrCombine(SDNode *N, 9590 DAGCombinerInfo &DCI) const { 9591 SelectionDAG &DAG = DCI.DAG; 9592 SDValue LHS = N->getOperand(0); 9593 SDValue RHS = N->getOperand(1); 9594 9595 EVT VT = N->getValueType(0); 9596 if (VT == MVT::i1) { 9597 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9598 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9599 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9600 SDValue Src = LHS.getOperand(0); 9601 if (Src != RHS.getOperand(0)) 9602 return SDValue(); 9603 9604 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9605 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9606 if (!CLHS || !CRHS) 9607 return SDValue(); 9608 9609 // Only 10 bits are used. 9610 static const uint32_t MaxMask = 0x3ff; 9611 9612 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9613 SDLoc DL(N); 9614 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9615 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9616 } 9617 9618 return SDValue(); 9619 } 9620 9621 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9622 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9623 LHS.getOpcode() == AMDGPUISD::PERM && 9624 isa<ConstantSDNode>(LHS.getOperand(2))) { 9625 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9626 if (!Sel) 9627 return SDValue(); 9628 9629 Sel |= LHS.getConstantOperandVal(2); 9630 SDLoc DL(N); 9631 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9632 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9633 } 9634 9635 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9636 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9637 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9638 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9639 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9640 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9641 if (LHSMask != ~0u && RHSMask != ~0u) { 9642 // Canonicalize the expression in an attempt to have fewer unique masks 9643 // and therefore fewer registers used to hold the masks. 9644 if (LHSMask > RHSMask) { 9645 std::swap(LHSMask, RHSMask); 9646 std::swap(LHS, RHS); 9647 } 9648 9649 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9650 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9651 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9652 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9653 9654 // Check of we need to combine values from two sources within a byte. 9655 if (!(LHSUsedLanes & RHSUsedLanes) && 9656 // If we select high and lower word keep it for SDWA. 9657 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9658 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9659 // Kill zero bytes selected by other mask. Zero value is 0xc. 9660 LHSMask &= ~RHSUsedLanes; 9661 RHSMask &= ~LHSUsedLanes; 9662 // Add 4 to each active LHS lane 9663 LHSMask |= LHSUsedLanes & 0x04040404; 9664 // Combine masks 9665 uint32_t Sel = LHSMask | RHSMask; 9666 SDLoc DL(N); 9667 9668 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9669 LHS.getOperand(0), RHS.getOperand(0), 9670 DAG.getConstant(Sel, DL, MVT::i32)); 9671 } 9672 } 9673 } 9674 9675 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9676 return SDValue(); 9677 9678 // TODO: This could be a generic combine with a predicate for extracting the 9679 // high half of an integer being free. 9680 9681 // (or i64:x, (zero_extend i32:y)) -> 9682 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9683 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9684 RHS.getOpcode() != ISD::ZERO_EXTEND) 9685 std::swap(LHS, RHS); 9686 9687 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9688 SDValue ExtSrc = RHS.getOperand(0); 9689 EVT SrcVT = ExtSrc.getValueType(); 9690 if (SrcVT == MVT::i32) { 9691 SDLoc SL(N); 9692 SDValue LowLHS, HiBits; 9693 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9694 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9695 9696 DCI.AddToWorklist(LowOr.getNode()); 9697 DCI.AddToWorklist(HiBits.getNode()); 9698 9699 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9700 LowOr, HiBits); 9701 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9702 } 9703 } 9704 9705 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9706 if (CRHS) { 9707 if (SDValue Split 9708 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, 9709 N->getOperand(0), CRHS)) 9710 return Split; 9711 } 9712 9713 return SDValue(); 9714 } 9715 9716 SDValue SITargetLowering::performXorCombine(SDNode *N, 9717 DAGCombinerInfo &DCI) const { 9718 if (SDValue RV = reassociateScalarOps(N, DCI.DAG)) 9719 return RV; 9720 9721 EVT VT = N->getValueType(0); 9722 if (VT != MVT::i64) 9723 return SDValue(); 9724 9725 SDValue LHS = N->getOperand(0); 9726 SDValue RHS = N->getOperand(1); 9727 9728 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9729 if (CRHS) { 9730 if (SDValue Split 9731 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9732 return Split; 9733 } 9734 9735 return SDValue(); 9736 } 9737 9738 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9739 DAGCombinerInfo &DCI) const { 9740 if (!Subtarget->has16BitInsts() || 9741 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9742 return SDValue(); 9743 9744 EVT VT = N->getValueType(0); 9745 if (VT != MVT::i32) 9746 return SDValue(); 9747 9748 SDValue Src = N->getOperand(0); 9749 if (Src.getValueType() != MVT::i16) 9750 return SDValue(); 9751 9752 return SDValue(); 9753 } 9754 9755 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9756 DAGCombinerInfo &DCI) 9757 const { 9758 SDValue Src = N->getOperand(0); 9759 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9760 9761 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9762 VTSign->getVT() == MVT::i8) || 9763 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9764 VTSign->getVT() == MVT::i16)) && 9765 Src.hasOneUse()) { 9766 auto *M = cast<MemSDNode>(Src); 9767 SDValue Ops[] = { 9768 Src.getOperand(0), // Chain 9769 Src.getOperand(1), // rsrc 9770 Src.getOperand(2), // vindex 9771 Src.getOperand(3), // voffset 9772 Src.getOperand(4), // soffset 9773 Src.getOperand(5), // offset 9774 Src.getOperand(6), 9775 Src.getOperand(7) 9776 }; 9777 // replace with BUFFER_LOAD_BYTE/SHORT 9778 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9779 Src.getOperand(0).getValueType()); 9780 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9781 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9782 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9783 ResList, 9784 Ops, M->getMemoryVT(), 9785 M->getMemOperand()); 9786 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9787 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9788 } 9789 return SDValue(); 9790 } 9791 9792 SDValue SITargetLowering::performClassCombine(SDNode *N, 9793 DAGCombinerInfo &DCI) const { 9794 SelectionDAG &DAG = DCI.DAG; 9795 SDValue Mask = N->getOperand(1); 9796 9797 // fp_class x, 0 -> false 9798 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9799 if (CMask->isZero()) 9800 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9801 } 9802 9803 if (N->getOperand(0).isUndef()) 9804 return DAG.getUNDEF(MVT::i1); 9805 9806 return SDValue(); 9807 } 9808 9809 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9810 DAGCombinerInfo &DCI) const { 9811 EVT VT = N->getValueType(0); 9812 SDValue N0 = N->getOperand(0); 9813 9814 if (N0.isUndef()) 9815 return N0; 9816 9817 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9818 N0.getOpcode() == ISD::SINT_TO_FP)) { 9819 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9820 N->getFlags()); 9821 } 9822 9823 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9824 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9825 N0.getOperand(0), N->getFlags()); 9826 } 9827 9828 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9829 } 9830 9831 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9832 unsigned MaxDepth) const { 9833 unsigned Opcode = Op.getOpcode(); 9834 if (Opcode == ISD::FCANONICALIZE) 9835 return true; 9836 9837 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9838 auto F = CFP->getValueAPF(); 9839 if (F.isNaN() && F.isSignaling()) 9840 return false; 9841 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9842 } 9843 9844 // If source is a result of another standard FP operation it is already in 9845 // canonical form. 9846 if (MaxDepth == 0) 9847 return false; 9848 9849 switch (Opcode) { 9850 // These will flush denorms if required. 9851 case ISD::FADD: 9852 case ISD::FSUB: 9853 case ISD::FMUL: 9854 case ISD::FCEIL: 9855 case ISD::FFLOOR: 9856 case ISD::FMA: 9857 case ISD::FMAD: 9858 case ISD::FSQRT: 9859 case ISD::FDIV: 9860 case ISD::FREM: 9861 case ISD::FP_ROUND: 9862 case ISD::FP_EXTEND: 9863 case AMDGPUISD::FMUL_LEGACY: 9864 case AMDGPUISD::FMAD_FTZ: 9865 case AMDGPUISD::RCP: 9866 case AMDGPUISD::RSQ: 9867 case AMDGPUISD::RSQ_CLAMP: 9868 case AMDGPUISD::RCP_LEGACY: 9869 case AMDGPUISD::RCP_IFLAG: 9870 case AMDGPUISD::DIV_SCALE: 9871 case AMDGPUISD::DIV_FMAS: 9872 case AMDGPUISD::DIV_FIXUP: 9873 case AMDGPUISD::FRACT: 9874 case AMDGPUISD::LDEXP: 9875 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9876 case AMDGPUISD::CVT_F32_UBYTE0: 9877 case AMDGPUISD::CVT_F32_UBYTE1: 9878 case AMDGPUISD::CVT_F32_UBYTE2: 9879 case AMDGPUISD::CVT_F32_UBYTE3: 9880 return true; 9881 9882 // It can/will be lowered or combined as a bit operation. 9883 // Need to check their input recursively to handle. 9884 case ISD::FNEG: 9885 case ISD::FABS: 9886 case ISD::FCOPYSIGN: 9887 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9888 9889 case ISD::FSIN: 9890 case ISD::FCOS: 9891 case ISD::FSINCOS: 9892 return Op.getValueType().getScalarType() != MVT::f16; 9893 9894 case ISD::FMINNUM: 9895 case ISD::FMAXNUM: 9896 case ISD::FMINNUM_IEEE: 9897 case ISD::FMAXNUM_IEEE: 9898 case AMDGPUISD::CLAMP: 9899 case AMDGPUISD::FMED3: 9900 case AMDGPUISD::FMAX3: 9901 case AMDGPUISD::FMIN3: { 9902 // FIXME: Shouldn't treat the generic operations different based these. 9903 // However, we aren't really required to flush the result from 9904 // minnum/maxnum.. 9905 9906 // snans will be quieted, so we only need to worry about denormals. 9907 if (Subtarget->supportsMinMaxDenormModes() || 9908 denormalsEnabledForType(DAG, Op.getValueType())) 9909 return true; 9910 9911 // Flushing may be required. 9912 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9913 // targets need to check their input recursively. 9914 9915 // FIXME: Does this apply with clamp? It's implemented with max. 9916 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9917 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9918 return false; 9919 } 9920 9921 return true; 9922 } 9923 case ISD::SELECT: { 9924 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9925 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9926 } 9927 case ISD::BUILD_VECTOR: { 9928 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9929 SDValue SrcOp = Op.getOperand(i); 9930 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9931 return false; 9932 } 9933 9934 return true; 9935 } 9936 case ISD::EXTRACT_VECTOR_ELT: 9937 case ISD::EXTRACT_SUBVECTOR: { 9938 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9939 } 9940 case ISD::INSERT_VECTOR_ELT: { 9941 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9942 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9943 } 9944 case ISD::UNDEF: 9945 // Could be anything. 9946 return false; 9947 9948 case ISD::BITCAST: 9949 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9950 case ISD::TRUNCATE: { 9951 // Hack round the mess we make when legalizing extract_vector_elt 9952 if (Op.getValueType() == MVT::i16) { 9953 SDValue TruncSrc = Op.getOperand(0); 9954 if (TruncSrc.getValueType() == MVT::i32 && 9955 TruncSrc.getOpcode() == ISD::BITCAST && 9956 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9957 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9958 } 9959 } 9960 return false; 9961 } 9962 case ISD::INTRINSIC_WO_CHAIN: { 9963 unsigned IntrinsicID 9964 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9965 // TODO: Handle more intrinsics 9966 switch (IntrinsicID) { 9967 case Intrinsic::amdgcn_cvt_pkrtz: 9968 case Intrinsic::amdgcn_cubeid: 9969 case Intrinsic::amdgcn_frexp_mant: 9970 case Intrinsic::amdgcn_fdot2: 9971 case Intrinsic::amdgcn_rcp: 9972 case Intrinsic::amdgcn_rsq: 9973 case Intrinsic::amdgcn_rsq_clamp: 9974 case Intrinsic::amdgcn_rcp_legacy: 9975 case Intrinsic::amdgcn_rsq_legacy: 9976 case Intrinsic::amdgcn_trig_preop: 9977 return true; 9978 default: 9979 break; 9980 } 9981 9982 LLVM_FALLTHROUGH; 9983 } 9984 default: 9985 return denormalsEnabledForType(DAG, Op.getValueType()) && 9986 DAG.isKnownNeverSNaN(Op); 9987 } 9988 9989 llvm_unreachable("invalid operation"); 9990 } 9991 9992 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 9993 unsigned MaxDepth) const { 9994 MachineRegisterInfo &MRI = MF.getRegInfo(); 9995 MachineInstr *MI = MRI.getVRegDef(Reg); 9996 unsigned Opcode = MI->getOpcode(); 9997 9998 if (Opcode == AMDGPU::G_FCANONICALIZE) 9999 return true; 10000 10001 Optional<FPValueAndVReg> FCR; 10002 // Constant splat (can be padded with undef) or scalar constant. 10003 if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) { 10004 if (FCR->Value.isSignaling()) 10005 return false; 10006 return !FCR->Value.isDenormal() || 10007 denormalsEnabledForType(MRI.getType(FCR->VReg), MF); 10008 } 10009 10010 if (MaxDepth == 0) 10011 return false; 10012 10013 switch (Opcode) { 10014 case AMDGPU::G_FMINNUM_IEEE: 10015 case AMDGPU::G_FMAXNUM_IEEE: { 10016 if (Subtarget->supportsMinMaxDenormModes() || 10017 denormalsEnabledForType(MRI.getType(Reg), MF)) 10018 return true; 10019 for (const MachineOperand &MO : llvm::drop_begin(MI->operands())) 10020 if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1)) 10021 return false; 10022 return true; 10023 } 10024 default: 10025 return denormalsEnabledForType(MRI.getType(Reg), MF) && 10026 isKnownNeverSNaN(Reg, MRI); 10027 } 10028 10029 llvm_unreachable("invalid operation"); 10030 } 10031 10032 // Constant fold canonicalize. 10033 SDValue SITargetLowering::getCanonicalConstantFP( 10034 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 10035 // Flush denormals to 0 if not enabled. 10036 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 10037 return DAG.getConstantFP(0.0, SL, VT); 10038 10039 if (C.isNaN()) { 10040 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 10041 if (C.isSignaling()) { 10042 // Quiet a signaling NaN. 10043 // FIXME: Is this supposed to preserve payload bits? 10044 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 10045 } 10046 10047 // Make sure it is the canonical NaN bitpattern. 10048 // 10049 // TODO: Can we use -1 as the canonical NaN value since it's an inline 10050 // immediate? 10051 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 10052 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 10053 } 10054 10055 // Already canonical. 10056 return DAG.getConstantFP(C, SL, VT); 10057 } 10058 10059 static bool vectorEltWillFoldAway(SDValue Op) { 10060 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 10061 } 10062 10063 SDValue SITargetLowering::performFCanonicalizeCombine( 10064 SDNode *N, 10065 DAGCombinerInfo &DCI) const { 10066 SelectionDAG &DAG = DCI.DAG; 10067 SDValue N0 = N->getOperand(0); 10068 EVT VT = N->getValueType(0); 10069 10070 // fcanonicalize undef -> qnan 10071 if (N0.isUndef()) { 10072 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 10073 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 10074 } 10075 10076 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 10077 EVT VT = N->getValueType(0); 10078 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 10079 } 10080 10081 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 10082 // (fcanonicalize k) 10083 // 10084 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 10085 10086 // TODO: This could be better with wider vectors that will be split to v2f16, 10087 // and to consider uses since there aren't that many packed operations. 10088 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 10089 isTypeLegal(MVT::v2f16)) { 10090 SDLoc SL(N); 10091 SDValue NewElts[2]; 10092 SDValue Lo = N0.getOperand(0); 10093 SDValue Hi = N0.getOperand(1); 10094 EVT EltVT = Lo.getValueType(); 10095 10096 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 10097 for (unsigned I = 0; I != 2; ++I) { 10098 SDValue Op = N0.getOperand(I); 10099 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 10100 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 10101 CFP->getValueAPF()); 10102 } else if (Op.isUndef()) { 10103 // Handled below based on what the other operand is. 10104 NewElts[I] = Op; 10105 } else { 10106 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 10107 } 10108 } 10109 10110 // If one half is undef, and one is constant, prefer a splat vector rather 10111 // than the normal qNaN. If it's a register, prefer 0.0 since that's 10112 // cheaper to use and may be free with a packed operation. 10113 if (NewElts[0].isUndef()) { 10114 if (isa<ConstantFPSDNode>(NewElts[1])) 10115 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 10116 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 10117 } 10118 10119 if (NewElts[1].isUndef()) { 10120 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 10121 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 10122 } 10123 10124 return DAG.getBuildVector(VT, SL, NewElts); 10125 } 10126 } 10127 10128 unsigned SrcOpc = N0.getOpcode(); 10129 10130 // If it's free to do so, push canonicalizes further up the source, which may 10131 // find a canonical source. 10132 // 10133 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 10134 // sNaNs. 10135 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 10136 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 10137 if (CRHS && N0.hasOneUse()) { 10138 SDLoc SL(N); 10139 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 10140 N0.getOperand(0)); 10141 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 10142 DCI.AddToWorklist(Canon0.getNode()); 10143 10144 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 10145 } 10146 } 10147 10148 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 10149 } 10150 10151 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 10152 switch (Opc) { 10153 case ISD::FMAXNUM: 10154 case ISD::FMAXNUM_IEEE: 10155 return AMDGPUISD::FMAX3; 10156 case ISD::SMAX: 10157 return AMDGPUISD::SMAX3; 10158 case ISD::UMAX: 10159 return AMDGPUISD::UMAX3; 10160 case ISD::FMINNUM: 10161 case ISD::FMINNUM_IEEE: 10162 return AMDGPUISD::FMIN3; 10163 case ISD::SMIN: 10164 return AMDGPUISD::SMIN3; 10165 case ISD::UMIN: 10166 return AMDGPUISD::UMIN3; 10167 default: 10168 llvm_unreachable("Not a min/max opcode"); 10169 } 10170 } 10171 10172 SDValue SITargetLowering::performIntMed3ImmCombine( 10173 SelectionDAG &DAG, const SDLoc &SL, 10174 SDValue Op0, SDValue Op1, bool Signed) const { 10175 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 10176 if (!K1) 10177 return SDValue(); 10178 10179 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 10180 if (!K0) 10181 return SDValue(); 10182 10183 if (Signed) { 10184 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 10185 return SDValue(); 10186 } else { 10187 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 10188 return SDValue(); 10189 } 10190 10191 EVT VT = K0->getValueType(0); 10192 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 10193 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 10194 return DAG.getNode(Med3Opc, SL, VT, 10195 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 10196 } 10197 10198 // If there isn't a 16-bit med3 operation, convert to 32-bit. 10199 if (VT == MVT::i16) { 10200 MVT NVT = MVT::i32; 10201 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 10202 10203 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 10204 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 10205 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 10206 10207 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 10208 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 10209 } 10210 10211 return SDValue(); 10212 } 10213 10214 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 10215 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 10216 return C; 10217 10218 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 10219 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 10220 return C; 10221 } 10222 10223 return nullptr; 10224 } 10225 10226 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 10227 const SDLoc &SL, 10228 SDValue Op0, 10229 SDValue Op1) const { 10230 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 10231 if (!K1) 10232 return SDValue(); 10233 10234 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 10235 if (!K0) 10236 return SDValue(); 10237 10238 // Ordered >= (although NaN inputs should have folded away by now). 10239 if (K0->getValueAPF() > K1->getValueAPF()) 10240 return SDValue(); 10241 10242 const MachineFunction &MF = DAG.getMachineFunction(); 10243 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10244 10245 // TODO: Check IEEE bit enabled? 10246 EVT VT = Op0.getValueType(); 10247 if (Info->getMode().DX10Clamp) { 10248 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 10249 // hardware fmed3 behavior converting to a min. 10250 // FIXME: Should this be allowing -0.0? 10251 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 10252 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 10253 } 10254 10255 // med3 for f16 is only available on gfx9+, and not available for v2f16. 10256 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 10257 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 10258 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 10259 // then give the other result, which is different from med3 with a NaN 10260 // input. 10261 SDValue Var = Op0.getOperand(0); 10262 if (!DAG.isKnownNeverSNaN(Var)) 10263 return SDValue(); 10264 10265 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10266 10267 if ((!K0->hasOneUse() || 10268 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 10269 (!K1->hasOneUse() || 10270 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 10271 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 10272 Var, SDValue(K0, 0), SDValue(K1, 0)); 10273 } 10274 } 10275 10276 return SDValue(); 10277 } 10278 10279 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 10280 DAGCombinerInfo &DCI) const { 10281 SelectionDAG &DAG = DCI.DAG; 10282 10283 EVT VT = N->getValueType(0); 10284 unsigned Opc = N->getOpcode(); 10285 SDValue Op0 = N->getOperand(0); 10286 SDValue Op1 = N->getOperand(1); 10287 10288 // Only do this if the inner op has one use since this will just increases 10289 // register pressure for no benefit. 10290 10291 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 10292 !VT.isVector() && 10293 (VT == MVT::i32 || VT == MVT::f32 || 10294 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 10295 // max(max(a, b), c) -> max3(a, b, c) 10296 // min(min(a, b), c) -> min3(a, b, c) 10297 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 10298 SDLoc DL(N); 10299 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10300 DL, 10301 N->getValueType(0), 10302 Op0.getOperand(0), 10303 Op0.getOperand(1), 10304 Op1); 10305 } 10306 10307 // Try commuted. 10308 // max(a, max(b, c)) -> max3(a, b, c) 10309 // min(a, min(b, c)) -> min3(a, b, c) 10310 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 10311 SDLoc DL(N); 10312 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10313 DL, 10314 N->getValueType(0), 10315 Op0, 10316 Op1.getOperand(0), 10317 Op1.getOperand(1)); 10318 } 10319 } 10320 10321 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 10322 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 10323 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 10324 return Med3; 10325 } 10326 10327 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 10328 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 10329 return Med3; 10330 } 10331 10332 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 10333 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 10334 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 10335 (Opc == AMDGPUISD::FMIN_LEGACY && 10336 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 10337 (VT == MVT::f32 || VT == MVT::f64 || 10338 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 10339 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 10340 Op0.hasOneUse()) { 10341 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 10342 return Res; 10343 } 10344 10345 return SDValue(); 10346 } 10347 10348 static bool isClampZeroToOne(SDValue A, SDValue B) { 10349 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 10350 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 10351 // FIXME: Should this be allowing -0.0? 10352 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 10353 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 10354 } 10355 } 10356 10357 return false; 10358 } 10359 10360 // FIXME: Should only worry about snans for version with chain. 10361 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10362 DAGCombinerInfo &DCI) const { 10363 EVT VT = N->getValueType(0); 10364 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10365 // NaNs. With a NaN input, the order of the operands may change the result. 10366 10367 SelectionDAG &DAG = DCI.DAG; 10368 SDLoc SL(N); 10369 10370 SDValue Src0 = N->getOperand(0); 10371 SDValue Src1 = N->getOperand(1); 10372 SDValue Src2 = N->getOperand(2); 10373 10374 if (isClampZeroToOne(Src0, Src1)) { 10375 // const_a, const_b, x -> clamp is safe in all cases including signaling 10376 // nans. 10377 // FIXME: Should this be allowing -0.0? 10378 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10379 } 10380 10381 const MachineFunction &MF = DAG.getMachineFunction(); 10382 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10383 10384 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10385 // handling no dx10-clamp? 10386 if (Info->getMode().DX10Clamp) { 10387 // If NaNs is clamped to 0, we are free to reorder the inputs. 10388 10389 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10390 std::swap(Src0, Src1); 10391 10392 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10393 std::swap(Src1, Src2); 10394 10395 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10396 std::swap(Src0, Src1); 10397 10398 if (isClampZeroToOne(Src1, Src2)) 10399 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10400 } 10401 10402 return SDValue(); 10403 } 10404 10405 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10406 DAGCombinerInfo &DCI) const { 10407 SDValue Src0 = N->getOperand(0); 10408 SDValue Src1 = N->getOperand(1); 10409 if (Src0.isUndef() && Src1.isUndef()) 10410 return DCI.DAG.getUNDEF(N->getValueType(0)); 10411 return SDValue(); 10412 } 10413 10414 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10415 // expanded into a set of cmp/select instructions. 10416 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10417 unsigned NumElem, 10418 bool IsDivergentIdx, 10419 const GCNSubtarget *Subtarget) { 10420 if (UseDivergentRegisterIndexing) 10421 return false; 10422 10423 unsigned VecSize = EltSize * NumElem; 10424 10425 // Sub-dword vectors of size 2 dword or less have better implementation. 10426 if (VecSize <= 64 && EltSize < 32) 10427 return false; 10428 10429 // Always expand the rest of sub-dword instructions, otherwise it will be 10430 // lowered via memory. 10431 if (EltSize < 32) 10432 return true; 10433 10434 // Always do this if var-idx is divergent, otherwise it will become a loop. 10435 if (IsDivergentIdx) 10436 return true; 10437 10438 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10439 unsigned NumInsts = NumElem /* Number of compares */ + 10440 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10441 10442 // On some architectures (GFX9) movrel is not available and it's better 10443 // to expand. 10444 if (!Subtarget->hasMovrel()) 10445 return NumInsts <= 16; 10446 10447 // If movrel is available, use it instead of expanding for vector of 8 10448 // elements. 10449 return NumInsts <= 15; 10450 } 10451 10452 bool SITargetLowering::shouldExpandVectorDynExt(SDNode *N) const { 10453 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10454 if (isa<ConstantSDNode>(Idx)) 10455 return false; 10456 10457 SDValue Vec = N->getOperand(0); 10458 EVT VecVT = Vec.getValueType(); 10459 EVT EltVT = VecVT.getVectorElementType(); 10460 unsigned EltSize = EltVT.getSizeInBits(); 10461 unsigned NumElem = VecVT.getVectorNumElements(); 10462 10463 return SITargetLowering::shouldExpandVectorDynExt( 10464 EltSize, NumElem, Idx->isDivergent(), getSubtarget()); 10465 } 10466 10467 SDValue SITargetLowering::performExtractVectorEltCombine( 10468 SDNode *N, DAGCombinerInfo &DCI) const { 10469 SDValue Vec = N->getOperand(0); 10470 SelectionDAG &DAG = DCI.DAG; 10471 10472 EVT VecVT = Vec.getValueType(); 10473 EVT EltVT = VecVT.getVectorElementType(); 10474 10475 if ((Vec.getOpcode() == ISD::FNEG || 10476 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10477 SDLoc SL(N); 10478 EVT EltVT = N->getValueType(0); 10479 SDValue Idx = N->getOperand(1); 10480 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10481 Vec.getOperand(0), Idx); 10482 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10483 } 10484 10485 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10486 // => 10487 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10488 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10489 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10490 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10491 SDLoc SL(N); 10492 EVT EltVT = N->getValueType(0); 10493 SDValue Idx = N->getOperand(1); 10494 unsigned Opc = Vec.getOpcode(); 10495 10496 switch(Opc) { 10497 default: 10498 break; 10499 // TODO: Support other binary operations. 10500 case ISD::FADD: 10501 case ISD::FSUB: 10502 case ISD::FMUL: 10503 case ISD::ADD: 10504 case ISD::UMIN: 10505 case ISD::UMAX: 10506 case ISD::SMIN: 10507 case ISD::SMAX: 10508 case ISD::FMAXNUM: 10509 case ISD::FMINNUM: 10510 case ISD::FMAXNUM_IEEE: 10511 case ISD::FMINNUM_IEEE: { 10512 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10513 Vec.getOperand(0), Idx); 10514 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10515 Vec.getOperand(1), Idx); 10516 10517 DCI.AddToWorklist(Elt0.getNode()); 10518 DCI.AddToWorklist(Elt1.getNode()); 10519 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10520 } 10521 } 10522 } 10523 10524 unsigned VecSize = VecVT.getSizeInBits(); 10525 unsigned EltSize = EltVT.getSizeInBits(); 10526 10527 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10528 if (shouldExpandVectorDynExt(N)) { 10529 SDLoc SL(N); 10530 SDValue Idx = N->getOperand(1); 10531 SDValue V; 10532 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10533 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10534 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10535 if (I == 0) 10536 V = Elt; 10537 else 10538 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10539 } 10540 return V; 10541 } 10542 10543 if (!DCI.isBeforeLegalize()) 10544 return SDValue(); 10545 10546 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10547 // elements. This exposes more load reduction opportunities by replacing 10548 // multiple small extract_vector_elements with a single 32-bit extract. 10549 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10550 if (isa<MemSDNode>(Vec) && 10551 EltSize <= 16 && 10552 EltVT.isByteSized() && 10553 VecSize > 32 && 10554 VecSize % 32 == 0 && 10555 Idx) { 10556 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10557 10558 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10559 unsigned EltIdx = BitIndex / 32; 10560 unsigned LeftoverBitIdx = BitIndex % 32; 10561 SDLoc SL(N); 10562 10563 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10564 DCI.AddToWorklist(Cast.getNode()); 10565 10566 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10567 DAG.getConstant(EltIdx, SL, MVT::i32)); 10568 DCI.AddToWorklist(Elt.getNode()); 10569 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10570 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10571 DCI.AddToWorklist(Srl.getNode()); 10572 10573 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10574 DCI.AddToWorklist(Trunc.getNode()); 10575 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10576 } 10577 10578 return SDValue(); 10579 } 10580 10581 SDValue 10582 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10583 DAGCombinerInfo &DCI) const { 10584 SDValue Vec = N->getOperand(0); 10585 SDValue Idx = N->getOperand(2); 10586 EVT VecVT = Vec.getValueType(); 10587 EVT EltVT = VecVT.getVectorElementType(); 10588 10589 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10590 // => BUILD_VECTOR n x select (e, const-idx) 10591 if (!shouldExpandVectorDynExt(N)) 10592 return SDValue(); 10593 10594 SelectionDAG &DAG = DCI.DAG; 10595 SDLoc SL(N); 10596 SDValue Ins = N->getOperand(1); 10597 EVT IdxVT = Idx.getValueType(); 10598 10599 SmallVector<SDValue, 16> Ops; 10600 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10601 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10602 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10603 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10604 Ops.push_back(V); 10605 } 10606 10607 return DAG.getBuildVector(VecVT, SL, Ops); 10608 } 10609 10610 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10611 const SDNode *N0, 10612 const SDNode *N1) const { 10613 EVT VT = N0->getValueType(0); 10614 10615 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10616 // support denormals ever. 10617 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10618 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10619 getSubtarget()->hasMadF16())) && 10620 isOperationLegal(ISD::FMAD, VT)) 10621 return ISD::FMAD; 10622 10623 const TargetOptions &Options = DAG.getTarget().Options; 10624 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10625 (N0->getFlags().hasAllowContract() && 10626 N1->getFlags().hasAllowContract())) && 10627 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10628 return ISD::FMA; 10629 } 10630 10631 return 0; 10632 } 10633 10634 // For a reassociatable opcode perform: 10635 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10636 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10637 SelectionDAG &DAG) const { 10638 EVT VT = N->getValueType(0); 10639 if (VT != MVT::i32 && VT != MVT::i64) 10640 return SDValue(); 10641 10642 if (DAG.isBaseWithConstantOffset(SDValue(N, 0))) 10643 return SDValue(); 10644 10645 unsigned Opc = N->getOpcode(); 10646 SDValue Op0 = N->getOperand(0); 10647 SDValue Op1 = N->getOperand(1); 10648 10649 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10650 return SDValue(); 10651 10652 if (Op0->isDivergent()) 10653 std::swap(Op0, Op1); 10654 10655 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10656 return SDValue(); 10657 10658 SDValue Op2 = Op1.getOperand(1); 10659 Op1 = Op1.getOperand(0); 10660 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10661 return SDValue(); 10662 10663 if (Op1->isDivergent()) 10664 std::swap(Op1, Op2); 10665 10666 SDLoc SL(N); 10667 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10668 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10669 } 10670 10671 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10672 EVT VT, 10673 SDValue N0, SDValue N1, SDValue N2, 10674 bool Signed) { 10675 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10676 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10677 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10678 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10679 } 10680 10681 // Fold (add (mul x, y), z) --> (mad_[iu]64_[iu]32 x, y, z) plus high 10682 // multiplies, if any. 10683 // 10684 // Full 64-bit multiplies that feed into an addition are lowered here instead 10685 // of using the generic expansion. The generic expansion ends up with 10686 // a tree of ADD nodes that prevents us from using the "add" part of the 10687 // MAD instruction. The expansion produced here results in a chain of ADDs 10688 // instead of a tree. 10689 SDValue SITargetLowering::tryFoldToMad64_32(SDNode *N, 10690 DAGCombinerInfo &DCI) const { 10691 assert(N->getOpcode() == ISD::ADD); 10692 10693 SelectionDAG &DAG = DCI.DAG; 10694 EVT VT = N->getValueType(0); 10695 SDLoc SL(N); 10696 SDValue LHS = N->getOperand(0); 10697 SDValue RHS = N->getOperand(1); 10698 10699 if (VT.isVector()) 10700 return SDValue(); 10701 10702 // S_MUL_HI_[IU]32 was added in gfx9, which allows us to keep the overall 10703 // result in scalar registers for uniform values. 10704 if (!N->isDivergent() && Subtarget->hasSMulHi()) 10705 return SDValue(); 10706 10707 unsigned NumBits = VT.getScalarSizeInBits(); 10708 if (NumBits <= 32 || NumBits > 64) 10709 return SDValue(); 10710 10711 if (LHS.getOpcode() != ISD::MUL) { 10712 assert(RHS.getOpcode() == ISD::MUL); 10713 std::swap(LHS, RHS); 10714 } 10715 10716 // Avoid the fold if it would unduly increase the number of multiplies due to 10717 // multiple uses, except on hardware with full-rate multiply-add (which is 10718 // part of full-rate 64-bit ops). 10719 if (!Subtarget->hasFullRate64Ops()) { 10720 unsigned NumUsers = 0; 10721 for (SDNode *Use : LHS->uses()) { 10722 // There is a use that does not feed into addition, so the multiply can't 10723 // be removed. We prefer MUL + ADD + ADDC over MAD + MUL. 10724 if (Use->getOpcode() != ISD::ADD) 10725 return SDValue(); 10726 10727 // We prefer 2xMAD over MUL + 2xADD + 2xADDC (code density), and prefer 10728 // MUL + 3xADD + 3xADDC over 3xMAD. 10729 ++NumUsers; 10730 if (NumUsers >= 3) 10731 return SDValue(); 10732 } 10733 } 10734 10735 SDValue MulLHS = LHS.getOperand(0); 10736 SDValue MulRHS = LHS.getOperand(1); 10737 SDValue AddRHS = RHS; 10738 10739 // Always check whether operands are small unsigned values, since that 10740 // knowledge is useful in more cases. Check for small signed values only if 10741 // doing so can unlock a shorter code sequence. 10742 bool MulLHSUnsigned32 = numBitsUnsigned(MulLHS, DAG) <= 32; 10743 bool MulRHSUnsigned32 = numBitsUnsigned(MulRHS, DAG) <= 32; 10744 10745 bool MulSignedLo = false; 10746 if (!MulLHSUnsigned32 || !MulRHSUnsigned32) { 10747 MulSignedLo = numBitsSigned(MulLHS, DAG) <= 32 && 10748 numBitsSigned(MulRHS, DAG) <= 32; 10749 } 10750 10751 // The operands and final result all have the same number of bits. If 10752 // operands need to be extended, they can be extended with garbage. The 10753 // resulting garbage in the high bits of the mad_[iu]64_[iu]32 result is 10754 // truncated away in the end. 10755 if (VT != MVT::i64) { 10756 MulLHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulLHS); 10757 MulRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulRHS); 10758 AddRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, AddRHS); 10759 } 10760 10761 // The basic code generated is conceptually straightforward. Pseudo code: 10762 // 10763 // accum = mad_64_32 lhs.lo, rhs.lo, accum 10764 // accum.hi = add (mul lhs.hi, rhs.lo), accum.hi 10765 // accum.hi = add (mul lhs.lo, rhs.hi), accum.hi 10766 // 10767 // The second and third lines are optional, depending on whether the factors 10768 // are {sign,zero}-extended or not. 10769 // 10770 // The actual DAG is noisier than the pseudo code, but only due to 10771 // instructions that disassemble values into low and high parts, and 10772 // assemble the final result. 10773 SDValue Zero = DAG.getConstant(0, SL, MVT::i32); 10774 SDValue One = DAG.getConstant(1, SL, MVT::i32); 10775 10776 auto MulLHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulLHS); 10777 auto MulRHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulRHS); 10778 SDValue Accum = 10779 getMad64_32(DAG, SL, MVT::i64, MulLHSLo, MulRHSLo, AddRHS, MulSignedLo); 10780 10781 if (!MulSignedLo && (!MulLHSUnsigned32 || !MulRHSUnsigned32)) { 10782 auto AccumLo = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, Zero); 10783 auto AccumHi = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, One); 10784 10785 if (!MulLHSUnsigned32) { 10786 auto MulLHSHi = 10787 DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulLHS, One); 10788 SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSHi, MulRHSLo); 10789 AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi); 10790 } 10791 10792 if (!MulRHSUnsigned32) { 10793 auto MulRHSHi = 10794 DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulRHS, One); 10795 SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSLo, MulRHSHi); 10796 AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi); 10797 } 10798 10799 Accum = DAG.getBuildVector(MVT::v2i32, SL, {AccumLo, AccumHi}); 10800 Accum = DAG.getBitcast(MVT::i64, Accum); 10801 } 10802 10803 if (VT != MVT::i64) 10804 Accum = DAG.getNode(ISD::TRUNCATE, SL, VT, Accum); 10805 return Accum; 10806 } 10807 10808 SDValue SITargetLowering::performAddCombine(SDNode *N, 10809 DAGCombinerInfo &DCI) const { 10810 SelectionDAG &DAG = DCI.DAG; 10811 EVT VT = N->getValueType(0); 10812 SDLoc SL(N); 10813 SDValue LHS = N->getOperand(0); 10814 SDValue RHS = N->getOperand(1); 10815 10816 if (LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) { 10817 if (Subtarget->hasMad64_32()) { 10818 if (SDValue Folded = tryFoldToMad64_32(N, DCI)) 10819 return Folded; 10820 } 10821 10822 return SDValue(); 10823 } 10824 10825 if (SDValue V = reassociateScalarOps(N, DAG)) { 10826 return V; 10827 } 10828 10829 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10830 return SDValue(); 10831 10832 // add x, zext (setcc) => addcarry x, 0, setcc 10833 // add x, sext (setcc) => subcarry x, 0, setcc 10834 unsigned Opc = LHS.getOpcode(); 10835 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10836 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10837 std::swap(RHS, LHS); 10838 10839 Opc = RHS.getOpcode(); 10840 switch (Opc) { 10841 default: break; 10842 case ISD::ZERO_EXTEND: 10843 case ISD::SIGN_EXTEND: 10844 case ISD::ANY_EXTEND: { 10845 auto Cond = RHS.getOperand(0); 10846 // If this won't be a real VOPC output, we would still need to insert an 10847 // extra instruction anyway. 10848 if (!isBoolSGPR(Cond)) 10849 break; 10850 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10851 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10852 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10853 return DAG.getNode(Opc, SL, VTList, Args); 10854 } 10855 case ISD::ADDCARRY: { 10856 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10857 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10858 if (!C || C->getZExtValue() != 0) break; 10859 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10860 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10861 } 10862 } 10863 return SDValue(); 10864 } 10865 10866 SDValue SITargetLowering::performSubCombine(SDNode *N, 10867 DAGCombinerInfo &DCI) const { 10868 SelectionDAG &DAG = DCI.DAG; 10869 EVT VT = N->getValueType(0); 10870 10871 if (VT != MVT::i32) 10872 return SDValue(); 10873 10874 SDLoc SL(N); 10875 SDValue LHS = N->getOperand(0); 10876 SDValue RHS = N->getOperand(1); 10877 10878 // sub x, zext (setcc) => subcarry x, 0, setcc 10879 // sub x, sext (setcc) => addcarry x, 0, setcc 10880 unsigned Opc = RHS.getOpcode(); 10881 switch (Opc) { 10882 default: break; 10883 case ISD::ZERO_EXTEND: 10884 case ISD::SIGN_EXTEND: 10885 case ISD::ANY_EXTEND: { 10886 auto Cond = RHS.getOperand(0); 10887 // If this won't be a real VOPC output, we would still need to insert an 10888 // extra instruction anyway. 10889 if (!isBoolSGPR(Cond)) 10890 break; 10891 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10892 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10893 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10894 return DAG.getNode(Opc, SL, VTList, Args); 10895 } 10896 } 10897 10898 if (LHS.getOpcode() == ISD::SUBCARRY) { 10899 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10900 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10901 if (!C || !C->isZero()) 10902 return SDValue(); 10903 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10904 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10905 } 10906 return SDValue(); 10907 } 10908 10909 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10910 DAGCombinerInfo &DCI) const { 10911 10912 if (N->getValueType(0) != MVT::i32) 10913 return SDValue(); 10914 10915 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10916 if (!C || C->getZExtValue() != 0) 10917 return SDValue(); 10918 10919 SelectionDAG &DAG = DCI.DAG; 10920 SDValue LHS = N->getOperand(0); 10921 10922 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10923 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10924 unsigned LHSOpc = LHS.getOpcode(); 10925 unsigned Opc = N->getOpcode(); 10926 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10927 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10928 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10929 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10930 } 10931 return SDValue(); 10932 } 10933 10934 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10935 DAGCombinerInfo &DCI) const { 10936 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10937 return SDValue(); 10938 10939 SelectionDAG &DAG = DCI.DAG; 10940 EVT VT = N->getValueType(0); 10941 10942 SDLoc SL(N); 10943 SDValue LHS = N->getOperand(0); 10944 SDValue RHS = N->getOperand(1); 10945 10946 // These should really be instruction patterns, but writing patterns with 10947 // source modifiers is a pain. 10948 10949 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10950 if (LHS.getOpcode() == ISD::FADD) { 10951 SDValue A = LHS.getOperand(0); 10952 if (A == LHS.getOperand(1)) { 10953 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10954 if (FusedOp != 0) { 10955 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10956 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10957 } 10958 } 10959 } 10960 10961 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10962 if (RHS.getOpcode() == ISD::FADD) { 10963 SDValue A = RHS.getOperand(0); 10964 if (A == RHS.getOperand(1)) { 10965 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10966 if (FusedOp != 0) { 10967 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10968 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10969 } 10970 } 10971 } 10972 10973 return SDValue(); 10974 } 10975 10976 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10977 DAGCombinerInfo &DCI) const { 10978 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10979 return SDValue(); 10980 10981 SelectionDAG &DAG = DCI.DAG; 10982 SDLoc SL(N); 10983 EVT VT = N->getValueType(0); 10984 assert(!VT.isVector()); 10985 10986 // Try to get the fneg to fold into the source modifier. This undoes generic 10987 // DAG combines and folds them into the mad. 10988 // 10989 // Only do this if we are not trying to support denormals. v_mad_f32 does 10990 // not support denormals ever. 10991 SDValue LHS = N->getOperand(0); 10992 SDValue RHS = N->getOperand(1); 10993 if (LHS.getOpcode() == ISD::FADD) { 10994 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10995 SDValue A = LHS.getOperand(0); 10996 if (A == LHS.getOperand(1)) { 10997 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10998 if (FusedOp != 0){ 10999 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 11000 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 11001 11002 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 11003 } 11004 } 11005 } 11006 11007 if (RHS.getOpcode() == ISD::FADD) { 11008 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 11009 11010 SDValue A = RHS.getOperand(0); 11011 if (A == RHS.getOperand(1)) { 11012 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 11013 if (FusedOp != 0){ 11014 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 11015 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 11016 } 11017 } 11018 } 11019 11020 return SDValue(); 11021 } 11022 11023 SDValue SITargetLowering::performFMACombine(SDNode *N, 11024 DAGCombinerInfo &DCI) const { 11025 SelectionDAG &DAG = DCI.DAG; 11026 EVT VT = N->getValueType(0); 11027 SDLoc SL(N); 11028 11029 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 11030 return SDValue(); 11031 11032 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 11033 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 11034 SDValue Op1 = N->getOperand(0); 11035 SDValue Op2 = N->getOperand(1); 11036 SDValue FMA = N->getOperand(2); 11037 11038 if (FMA.getOpcode() != ISD::FMA || 11039 Op1.getOpcode() != ISD::FP_EXTEND || 11040 Op2.getOpcode() != ISD::FP_EXTEND) 11041 return SDValue(); 11042 11043 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 11044 // regardless of the denorm mode setting. Therefore, 11045 // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2. 11046 const TargetOptions &Options = DAG.getTarget().Options; 11047 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 11048 (N->getFlags().hasAllowContract() && 11049 FMA->getFlags().hasAllowContract())) { 11050 Op1 = Op1.getOperand(0); 11051 Op2 = Op2.getOperand(0); 11052 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11053 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11054 return SDValue(); 11055 11056 SDValue Vec1 = Op1.getOperand(0); 11057 SDValue Idx1 = Op1.getOperand(1); 11058 SDValue Vec2 = Op2.getOperand(0); 11059 11060 SDValue FMAOp1 = FMA.getOperand(0); 11061 SDValue FMAOp2 = FMA.getOperand(1); 11062 SDValue FMAAcc = FMA.getOperand(2); 11063 11064 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 11065 FMAOp2.getOpcode() != ISD::FP_EXTEND) 11066 return SDValue(); 11067 11068 FMAOp1 = FMAOp1.getOperand(0); 11069 FMAOp2 = FMAOp2.getOperand(0); 11070 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11071 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11072 return SDValue(); 11073 11074 SDValue Vec3 = FMAOp1.getOperand(0); 11075 SDValue Vec4 = FMAOp2.getOperand(0); 11076 SDValue Idx2 = FMAOp1.getOperand(1); 11077 11078 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 11079 // Idx1 and Idx2 cannot be the same. 11080 Idx1 == Idx2) 11081 return SDValue(); 11082 11083 if (Vec1 == Vec2 || Vec3 == Vec4) 11084 return SDValue(); 11085 11086 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 11087 return SDValue(); 11088 11089 if ((Vec1 == Vec3 && Vec2 == Vec4) || 11090 (Vec1 == Vec4 && Vec2 == Vec3)) { 11091 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 11092 DAG.getTargetConstant(0, SL, MVT::i1)); 11093 } 11094 } 11095 return SDValue(); 11096 } 11097 11098 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 11099 DAGCombinerInfo &DCI) const { 11100 SelectionDAG &DAG = DCI.DAG; 11101 SDLoc SL(N); 11102 11103 SDValue LHS = N->getOperand(0); 11104 SDValue RHS = N->getOperand(1); 11105 EVT VT = LHS.getValueType(); 11106 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11107 11108 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 11109 if (!CRHS) { 11110 CRHS = dyn_cast<ConstantSDNode>(LHS); 11111 if (CRHS) { 11112 std::swap(LHS, RHS); 11113 CC = getSetCCSwappedOperands(CC); 11114 } 11115 } 11116 11117 if (CRHS) { 11118 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 11119 isBoolSGPR(LHS.getOperand(0))) { 11120 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 11121 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 11122 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 11123 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 11124 if ((CRHS->isAllOnes() && 11125 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 11126 (CRHS->isZero() && 11127 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 11128 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 11129 DAG.getConstant(-1, SL, MVT::i1)); 11130 if ((CRHS->isAllOnes() && 11131 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 11132 (CRHS->isZero() && 11133 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 11134 return LHS.getOperand(0); 11135 } 11136 11137 const APInt &CRHSVal = CRHS->getAPIntValue(); 11138 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 11139 LHS.getOpcode() == ISD::SELECT && 11140 isa<ConstantSDNode>(LHS.getOperand(1)) && 11141 isa<ConstantSDNode>(LHS.getOperand(2)) && 11142 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 11143 isBoolSGPR(LHS.getOperand(0))) { 11144 // Given CT != FT: 11145 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 11146 // setcc (select cc, CT, CF), CF, ne => cc 11147 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 11148 // setcc (select cc, CT, CF), CT, eq => cc 11149 const APInt &CT = LHS.getConstantOperandAPInt(1); 11150 const APInt &CF = LHS.getConstantOperandAPInt(2); 11151 11152 if ((CF == CRHSVal && CC == ISD::SETEQ) || 11153 (CT == CRHSVal && CC == ISD::SETNE)) 11154 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 11155 DAG.getConstant(-1, SL, MVT::i1)); 11156 if ((CF == CRHSVal && CC == ISD::SETNE) || 11157 (CT == CRHSVal && CC == ISD::SETEQ)) 11158 return LHS.getOperand(0); 11159 } 11160 } 11161 11162 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 11163 VT != MVT::f16)) 11164 return SDValue(); 11165 11166 // Match isinf/isfinite pattern 11167 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 11168 // (fcmp one (fabs x), inf) -> (fp_class x, 11169 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 11170 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 11171 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 11172 if (!CRHS) 11173 return SDValue(); 11174 11175 const APFloat &APF = CRHS->getValueAPF(); 11176 if (APF.isInfinity() && !APF.isNegative()) { 11177 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 11178 SIInstrFlags::N_INFINITY; 11179 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 11180 SIInstrFlags::P_ZERO | 11181 SIInstrFlags::N_NORMAL | 11182 SIInstrFlags::P_NORMAL | 11183 SIInstrFlags::N_SUBNORMAL | 11184 SIInstrFlags::P_SUBNORMAL; 11185 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 11186 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 11187 DAG.getConstant(Mask, SL, MVT::i32)); 11188 } 11189 } 11190 11191 return SDValue(); 11192 } 11193 11194 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 11195 DAGCombinerInfo &DCI) const { 11196 SelectionDAG &DAG = DCI.DAG; 11197 SDLoc SL(N); 11198 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 11199 11200 SDValue Src = N->getOperand(0); 11201 SDValue Shift = N->getOperand(0); 11202 11203 // TODO: Extend type shouldn't matter (assuming legal types). 11204 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 11205 Shift = Shift.getOperand(0); 11206 11207 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 11208 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 11209 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 11210 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 11211 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 11212 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 11213 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 11214 SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0), 11215 SDLoc(Shift.getOperand(0)), MVT::i32); 11216 11217 unsigned ShiftOffset = 8 * Offset; 11218 if (Shift.getOpcode() == ISD::SHL) 11219 ShiftOffset -= C->getZExtValue(); 11220 else 11221 ShiftOffset += C->getZExtValue(); 11222 11223 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 11224 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 11225 MVT::f32, Shifted); 11226 } 11227 } 11228 } 11229 11230 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11231 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 11232 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 11233 // We simplified Src. If this node is not dead, visit it again so it is 11234 // folded properly. 11235 if (N->getOpcode() != ISD::DELETED_NODE) 11236 DCI.AddToWorklist(N); 11237 return SDValue(N, 0); 11238 } 11239 11240 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 11241 if (SDValue DemandedSrc = 11242 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 11243 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 11244 11245 return SDValue(); 11246 } 11247 11248 SDValue SITargetLowering::performClampCombine(SDNode *N, 11249 DAGCombinerInfo &DCI) const { 11250 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 11251 if (!CSrc) 11252 return SDValue(); 11253 11254 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 11255 const APFloat &F = CSrc->getValueAPF(); 11256 APFloat Zero = APFloat::getZero(F.getSemantics()); 11257 if (F < Zero || 11258 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 11259 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 11260 } 11261 11262 APFloat One(F.getSemantics(), "1.0"); 11263 if (F > One) 11264 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 11265 11266 return SDValue(CSrc, 0); 11267 } 11268 11269 11270 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 11271 DAGCombinerInfo &DCI) const { 11272 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 11273 return SDValue(); 11274 switch (N->getOpcode()) { 11275 case ISD::ADD: 11276 return performAddCombine(N, DCI); 11277 case ISD::SUB: 11278 return performSubCombine(N, DCI); 11279 case ISD::ADDCARRY: 11280 case ISD::SUBCARRY: 11281 return performAddCarrySubCarryCombine(N, DCI); 11282 case ISD::FADD: 11283 return performFAddCombine(N, DCI); 11284 case ISD::FSUB: 11285 return performFSubCombine(N, DCI); 11286 case ISD::SETCC: 11287 return performSetCCCombine(N, DCI); 11288 case ISD::FMAXNUM: 11289 case ISD::FMINNUM: 11290 case ISD::FMAXNUM_IEEE: 11291 case ISD::FMINNUM_IEEE: 11292 case ISD::SMAX: 11293 case ISD::SMIN: 11294 case ISD::UMAX: 11295 case ISD::UMIN: 11296 case AMDGPUISD::FMIN_LEGACY: 11297 case AMDGPUISD::FMAX_LEGACY: 11298 return performMinMaxCombine(N, DCI); 11299 case ISD::FMA: 11300 return performFMACombine(N, DCI); 11301 case ISD::AND: 11302 return performAndCombine(N, DCI); 11303 case ISD::OR: 11304 return performOrCombine(N, DCI); 11305 case ISD::XOR: 11306 return performXorCombine(N, DCI); 11307 case ISD::ZERO_EXTEND: 11308 return performZeroExtendCombine(N, DCI); 11309 case ISD::SIGN_EXTEND_INREG: 11310 return performSignExtendInRegCombine(N , DCI); 11311 case AMDGPUISD::FP_CLASS: 11312 return performClassCombine(N, DCI); 11313 case ISD::FCANONICALIZE: 11314 return performFCanonicalizeCombine(N, DCI); 11315 case AMDGPUISD::RCP: 11316 return performRcpCombine(N, DCI); 11317 case AMDGPUISD::FRACT: 11318 case AMDGPUISD::RSQ: 11319 case AMDGPUISD::RCP_LEGACY: 11320 case AMDGPUISD::RCP_IFLAG: 11321 case AMDGPUISD::RSQ_CLAMP: 11322 case AMDGPUISD::LDEXP: { 11323 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 11324 SDValue Src = N->getOperand(0); 11325 if (Src.isUndef()) 11326 return Src; 11327 break; 11328 } 11329 case ISD::SINT_TO_FP: 11330 case ISD::UINT_TO_FP: 11331 return performUCharToFloatCombine(N, DCI); 11332 case AMDGPUISD::CVT_F32_UBYTE0: 11333 case AMDGPUISD::CVT_F32_UBYTE1: 11334 case AMDGPUISD::CVT_F32_UBYTE2: 11335 case AMDGPUISD::CVT_F32_UBYTE3: 11336 return performCvtF32UByteNCombine(N, DCI); 11337 case AMDGPUISD::FMED3: 11338 return performFMed3Combine(N, DCI); 11339 case AMDGPUISD::CVT_PKRTZ_F16_F32: 11340 return performCvtPkRTZCombine(N, DCI); 11341 case AMDGPUISD::CLAMP: 11342 return performClampCombine(N, DCI); 11343 case ISD::SCALAR_TO_VECTOR: { 11344 SelectionDAG &DAG = DCI.DAG; 11345 EVT VT = N->getValueType(0); 11346 11347 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 11348 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 11349 SDLoc SL(N); 11350 SDValue Src = N->getOperand(0); 11351 EVT EltVT = Src.getValueType(); 11352 if (EltVT == MVT::f16) 11353 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 11354 11355 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 11356 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 11357 } 11358 11359 break; 11360 } 11361 case ISD::EXTRACT_VECTOR_ELT: 11362 return performExtractVectorEltCombine(N, DCI); 11363 case ISD::INSERT_VECTOR_ELT: 11364 return performInsertVectorEltCombine(N, DCI); 11365 case ISD::LOAD: { 11366 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 11367 return Widended; 11368 LLVM_FALLTHROUGH; 11369 } 11370 default: { 11371 if (!DCI.isBeforeLegalize()) { 11372 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 11373 return performMemSDNodeCombine(MemNode, DCI); 11374 } 11375 11376 break; 11377 } 11378 } 11379 11380 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 11381 } 11382 11383 /// Helper function for adjustWritemask 11384 static unsigned SubIdx2Lane(unsigned Idx) { 11385 switch (Idx) { 11386 default: return ~0u; 11387 case AMDGPU::sub0: return 0; 11388 case AMDGPU::sub1: return 1; 11389 case AMDGPU::sub2: return 2; 11390 case AMDGPU::sub3: return 3; 11391 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 11392 } 11393 } 11394 11395 /// Adjust the writemask of MIMG instructions 11396 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 11397 SelectionDAG &DAG) const { 11398 unsigned Opcode = Node->getMachineOpcode(); 11399 11400 // Subtract 1 because the vdata output is not a MachineSDNode operand. 11401 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 11402 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 11403 return Node; // not implemented for D16 11404 11405 SDNode *Users[5] = { nullptr }; 11406 unsigned Lane = 0; 11407 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 11408 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 11409 unsigned NewDmask = 0; 11410 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 11411 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 11412 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 11413 Node->getConstantOperandVal(LWEIdx)) 11414 ? true 11415 : false; 11416 unsigned TFCLane = 0; 11417 bool HasChain = Node->getNumValues() > 1; 11418 11419 if (OldDmask == 0) { 11420 // These are folded out, but on the chance it happens don't assert. 11421 return Node; 11422 } 11423 11424 unsigned OldBitsSet = countPopulation(OldDmask); 11425 // Work out which is the TFE/LWE lane if that is enabled. 11426 if (UsesTFC) { 11427 TFCLane = OldBitsSet; 11428 } 11429 11430 // Try to figure out the used register components 11431 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 11432 I != E; ++I) { 11433 11434 // Don't look at users of the chain. 11435 if (I.getUse().getResNo() != 0) 11436 continue; 11437 11438 // Abort if we can't understand the usage 11439 if (!I->isMachineOpcode() || 11440 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 11441 return Node; 11442 11443 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 11444 // Note that subregs are packed, i.e. Lane==0 is the first bit set 11445 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 11446 // set, etc. 11447 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 11448 if (Lane == ~0u) 11449 return Node; 11450 11451 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 11452 if (UsesTFC && Lane == TFCLane) { 11453 Users[Lane] = *I; 11454 } else { 11455 // Set which texture component corresponds to the lane. 11456 unsigned Comp; 11457 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 11458 Comp = countTrailingZeros(Dmask); 11459 Dmask &= ~(1 << Comp); 11460 } 11461 11462 // Abort if we have more than one user per component. 11463 if (Users[Lane]) 11464 return Node; 11465 11466 Users[Lane] = *I; 11467 NewDmask |= 1 << Comp; 11468 } 11469 } 11470 11471 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11472 bool NoChannels = !NewDmask; 11473 if (NoChannels) { 11474 if (!UsesTFC) { 11475 // No uses of the result and not using TFC. Then do nothing. 11476 return Node; 11477 } 11478 // If the original dmask has one channel - then nothing to do 11479 if (OldBitsSet == 1) 11480 return Node; 11481 // Use an arbitrary dmask - required for the instruction to work 11482 NewDmask = 1; 11483 } 11484 // Abort if there's no change 11485 if (NewDmask == OldDmask) 11486 return Node; 11487 11488 unsigned BitsSet = countPopulation(NewDmask); 11489 11490 // Check for TFE or LWE - increase the number of channels by one to account 11491 // for the extra return value 11492 // This will need adjustment for D16 if this is also included in 11493 // adjustWriteMask (this function) but at present D16 are excluded. 11494 unsigned NewChannels = BitsSet + UsesTFC; 11495 11496 int NewOpcode = 11497 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11498 assert(NewOpcode != -1 && 11499 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11500 "failed to find equivalent MIMG op"); 11501 11502 // Adjust the writemask in the node 11503 SmallVector<SDValue, 12> Ops; 11504 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11505 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11506 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11507 11508 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11509 11510 MVT ResultVT = NewChannels == 1 ? 11511 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11512 NewChannels == 5 ? 8 : NewChannels); 11513 SDVTList NewVTList = HasChain ? 11514 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11515 11516 11517 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11518 NewVTList, Ops); 11519 11520 if (HasChain) { 11521 // Update chain. 11522 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11523 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11524 } 11525 11526 if (NewChannels == 1) { 11527 assert(Node->hasNUsesOfValue(1, 0)); 11528 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11529 SDLoc(Node), Users[Lane]->getValueType(0), 11530 SDValue(NewNode, 0)); 11531 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11532 return nullptr; 11533 } 11534 11535 // Update the users of the node with the new indices 11536 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11537 SDNode *User = Users[i]; 11538 if (!User) { 11539 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11540 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11541 if (i || !NoChannels) 11542 continue; 11543 } else { 11544 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11545 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11546 } 11547 11548 switch (Idx) { 11549 default: break; 11550 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11551 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11552 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11553 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11554 } 11555 } 11556 11557 DAG.RemoveDeadNode(Node); 11558 return nullptr; 11559 } 11560 11561 static bool isFrameIndexOp(SDValue Op) { 11562 if (Op.getOpcode() == ISD::AssertZext) 11563 Op = Op.getOperand(0); 11564 11565 return isa<FrameIndexSDNode>(Op); 11566 } 11567 11568 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11569 /// with frame index operands. 11570 /// LLVM assumes that inputs are to these instructions are registers. 11571 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11572 SelectionDAG &DAG) const { 11573 if (Node->getOpcode() == ISD::CopyToReg) { 11574 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11575 SDValue SrcVal = Node->getOperand(2); 11576 11577 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11578 // to try understanding copies to physical registers. 11579 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11580 SDLoc SL(Node); 11581 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11582 SDValue VReg = DAG.getRegister( 11583 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11584 11585 SDNode *Glued = Node->getGluedNode(); 11586 SDValue ToVReg 11587 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11588 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11589 SDValue ToResultReg 11590 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11591 VReg, ToVReg.getValue(1)); 11592 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11593 DAG.RemoveDeadNode(Node); 11594 return ToResultReg.getNode(); 11595 } 11596 } 11597 11598 SmallVector<SDValue, 8> Ops; 11599 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11600 if (!isFrameIndexOp(Node->getOperand(i))) { 11601 Ops.push_back(Node->getOperand(i)); 11602 continue; 11603 } 11604 11605 SDLoc DL(Node); 11606 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11607 Node->getOperand(i).getValueType(), 11608 Node->getOperand(i)), 0)); 11609 } 11610 11611 return DAG.UpdateNodeOperands(Node, Ops); 11612 } 11613 11614 /// Fold the instructions after selecting them. 11615 /// Returns null if users were already updated. 11616 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11617 SelectionDAG &DAG) const { 11618 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11619 unsigned Opcode = Node->getMachineOpcode(); 11620 11621 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11622 !TII->isGather4(Opcode) && 11623 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11624 return adjustWritemask(Node, DAG); 11625 } 11626 11627 if (Opcode == AMDGPU::INSERT_SUBREG || 11628 Opcode == AMDGPU::REG_SEQUENCE) { 11629 legalizeTargetIndependentNode(Node, DAG); 11630 return Node; 11631 } 11632 11633 switch (Opcode) { 11634 case AMDGPU::V_DIV_SCALE_F32_e64: 11635 case AMDGPU::V_DIV_SCALE_F64_e64: { 11636 // Satisfy the operand register constraint when one of the inputs is 11637 // undefined. Ordinarily each undef value will have its own implicit_def of 11638 // a vreg, so force these to use a single register. 11639 SDValue Src0 = Node->getOperand(1); 11640 SDValue Src1 = Node->getOperand(3); 11641 SDValue Src2 = Node->getOperand(5); 11642 11643 if ((Src0.isMachineOpcode() && 11644 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11645 (Src0 == Src1 || Src0 == Src2)) 11646 break; 11647 11648 MVT VT = Src0.getValueType().getSimpleVT(); 11649 const TargetRegisterClass *RC = 11650 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11651 11652 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11653 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11654 11655 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11656 UndefReg, Src0, SDValue()); 11657 11658 // src0 must be the same register as src1 or src2, even if the value is 11659 // undefined, so make sure we don't violate this constraint. 11660 if (Src0.isMachineOpcode() && 11661 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11662 if (Src1.isMachineOpcode() && 11663 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11664 Src0 = Src1; 11665 else if (Src2.isMachineOpcode() && 11666 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11667 Src0 = Src2; 11668 else { 11669 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11670 Src0 = UndefReg; 11671 Src1 = UndefReg; 11672 } 11673 } else 11674 break; 11675 11676 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11677 Ops[1] = Src0; 11678 Ops[3] = Src1; 11679 Ops[5] = Src2; 11680 Ops.push_back(ImpDef.getValue(1)); 11681 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11682 } 11683 default: 11684 break; 11685 } 11686 11687 return Node; 11688 } 11689 11690 // Any MIMG instructions that use tfe or lwe require an initialization of the 11691 // result register that will be written in the case of a memory access failure. 11692 // The required code is also added to tie this init code to the result of the 11693 // img instruction. 11694 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11695 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11696 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11697 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11698 MachineBasicBlock &MBB = *MI.getParent(); 11699 11700 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11701 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11702 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11703 11704 if (!TFE && !LWE) // intersect_ray 11705 return; 11706 11707 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11708 unsigned LWEVal = LWE->getImm(); 11709 unsigned D16Val = D16 ? D16->getImm() : 0; 11710 11711 if (!TFEVal && !LWEVal) 11712 return; 11713 11714 // At least one of TFE or LWE are non-zero 11715 // We have to insert a suitable initialization of the result value and 11716 // tie this to the dest of the image instruction. 11717 11718 const DebugLoc &DL = MI.getDebugLoc(); 11719 11720 int DstIdx = 11721 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11722 11723 // Calculate which dword we have to initialize to 0. 11724 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11725 11726 // check that dmask operand is found. 11727 assert(MO_Dmask && "Expected dmask operand in instruction"); 11728 11729 unsigned dmask = MO_Dmask->getImm(); 11730 // Determine the number of active lanes taking into account the 11731 // Gather4 special case 11732 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11733 11734 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11735 11736 unsigned InitIdx = 11737 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11738 11739 // Abandon attempt if the dst size isn't large enough 11740 // - this is in fact an error but this is picked up elsewhere and 11741 // reported correctly. 11742 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11743 if (DstSize < InitIdx) 11744 return; 11745 11746 // Create a register for the initialization value. 11747 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11748 unsigned NewDst = 0; // Final initialized value will be in here 11749 11750 // If PRTStrictNull feature is enabled (the default) then initialize 11751 // all the result registers to 0, otherwise just the error indication 11752 // register (VGPRn+1) 11753 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11754 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11755 11756 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11757 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11758 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11759 // Initialize dword 11760 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11761 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11762 .addImm(0); 11763 // Insert into the super-reg 11764 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11765 .addReg(PrevDst) 11766 .addReg(SubReg) 11767 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11768 11769 PrevDst = NewDst; 11770 } 11771 11772 // Add as an implicit operand 11773 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11774 11775 // Tie the just added implicit operand to the dst 11776 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11777 } 11778 11779 /// Assign the register class depending on the number of 11780 /// bits set in the writemask 11781 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11782 SDNode *Node) const { 11783 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11784 11785 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11786 11787 if (TII->isVOP3(MI.getOpcode())) { 11788 // Make sure constant bus requirements are respected. 11789 TII->legalizeOperandsVOP3(MRI, MI); 11790 11791 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11792 // This saves a chain-copy of registers and better balance register 11793 // use between vgpr and agpr as agpr tuples tend to be big. 11794 if (MI.getDesc().OpInfo) { 11795 unsigned Opc = MI.getOpcode(); 11796 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11797 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11798 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11799 if (I == -1) 11800 break; 11801 MachineOperand &Op = MI.getOperand(I); 11802 if (!Op.isReg() || !Op.getReg().isVirtual()) 11803 continue; 11804 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11805 if (!TRI->hasAGPRs(RC)) 11806 continue; 11807 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11808 if (!Src || !Src->isCopy() || 11809 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11810 continue; 11811 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11812 // All uses of agpr64 and agpr32 can also accept vgpr except for 11813 // v_accvgpr_read, but we do not produce agpr reads during selection, 11814 // so no use checks are needed. 11815 MRI.setRegClass(Op.getReg(), NewRC); 11816 } 11817 11818 // Resolve the rest of AV operands to AGPRs. 11819 if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) { 11820 if (Src2->isReg() && Src2->getReg().isVirtual()) { 11821 auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg()); 11822 if (TRI->isVectorSuperClass(RC)) { 11823 auto *NewRC = TRI->getEquivalentAGPRClass(RC); 11824 MRI.setRegClass(Src2->getReg(), NewRC); 11825 if (Src2->isTied()) 11826 MRI.setRegClass(MI.getOperand(0).getReg(), NewRC); 11827 } 11828 } 11829 } 11830 } 11831 11832 return; 11833 } 11834 11835 if (TII->isMIMG(MI)) { 11836 if (!MI.mayStore()) 11837 AddIMGInit(MI); 11838 TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::vaddr); 11839 } 11840 } 11841 11842 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11843 uint64_t Val) { 11844 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11845 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11846 } 11847 11848 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11849 const SDLoc &DL, 11850 SDValue Ptr) const { 11851 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11852 11853 // Build the half of the subregister with the constants before building the 11854 // full 128-bit register. If we are building multiple resource descriptors, 11855 // this will allow CSEing of the 2-component register. 11856 const SDValue Ops0[] = { 11857 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11858 buildSMovImm32(DAG, DL, 0), 11859 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11860 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11861 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11862 }; 11863 11864 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11865 MVT::v2i32, Ops0), 0); 11866 11867 // Combine the constants and the pointer. 11868 const SDValue Ops1[] = { 11869 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11870 Ptr, 11871 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11872 SubRegHi, 11873 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11874 }; 11875 11876 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11877 } 11878 11879 /// Return a resource descriptor with the 'Add TID' bit enabled 11880 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11881 /// of the resource descriptor) to create an offset, which is added to 11882 /// the resource pointer. 11883 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11884 SDValue Ptr, uint32_t RsrcDword1, 11885 uint64_t RsrcDword2And3) const { 11886 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11887 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11888 if (RsrcDword1) { 11889 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11890 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11891 0); 11892 } 11893 11894 SDValue DataLo = buildSMovImm32(DAG, DL, 11895 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11896 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11897 11898 const SDValue Ops[] = { 11899 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11900 PtrLo, 11901 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11902 PtrHi, 11903 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11904 DataLo, 11905 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11906 DataHi, 11907 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11908 }; 11909 11910 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11911 } 11912 11913 //===----------------------------------------------------------------------===// 11914 // SI Inline Assembly Support 11915 //===----------------------------------------------------------------------===// 11916 11917 std::pair<unsigned, const TargetRegisterClass *> 11918 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11919 StringRef Constraint, 11920 MVT VT) const { 11921 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11922 11923 const TargetRegisterClass *RC = nullptr; 11924 if (Constraint.size() == 1) { 11925 const unsigned BitWidth = VT.getSizeInBits(); 11926 switch (Constraint[0]) { 11927 default: 11928 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11929 case 's': 11930 case 'r': 11931 switch (BitWidth) { 11932 case 16: 11933 RC = &AMDGPU::SReg_32RegClass; 11934 break; 11935 case 64: 11936 RC = &AMDGPU::SGPR_64RegClass; 11937 break; 11938 default: 11939 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11940 if (!RC) 11941 return std::make_pair(0U, nullptr); 11942 break; 11943 } 11944 break; 11945 case 'v': 11946 switch (BitWidth) { 11947 case 16: 11948 RC = &AMDGPU::VGPR_32RegClass; 11949 break; 11950 default: 11951 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11952 if (!RC) 11953 return std::make_pair(0U, nullptr); 11954 break; 11955 } 11956 break; 11957 case 'a': 11958 if (!Subtarget->hasMAIInsts()) 11959 break; 11960 switch (BitWidth) { 11961 case 16: 11962 RC = &AMDGPU::AGPR_32RegClass; 11963 break; 11964 default: 11965 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11966 if (!RC) 11967 return std::make_pair(0U, nullptr); 11968 break; 11969 } 11970 break; 11971 } 11972 // We actually support i128, i16 and f16 as inline parameters 11973 // even if they are not reported as legal 11974 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11975 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11976 return std::make_pair(0U, RC); 11977 } 11978 11979 if (Constraint.startswith("{") && Constraint.endswith("}")) { 11980 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 11981 if (RegName.consume_front("v")) { 11982 RC = &AMDGPU::VGPR_32RegClass; 11983 } else if (RegName.consume_front("s")) { 11984 RC = &AMDGPU::SGPR_32RegClass; 11985 } else if (RegName.consume_front("a")) { 11986 RC = &AMDGPU::AGPR_32RegClass; 11987 } 11988 11989 if (RC) { 11990 uint32_t Idx; 11991 if (RegName.consume_front("[")) { 11992 uint32_t End; 11993 bool Failed = RegName.consumeInteger(10, Idx); 11994 Failed |= !RegName.consume_front(":"); 11995 Failed |= RegName.consumeInteger(10, End); 11996 Failed |= !RegName.consume_back("]"); 11997 if (!Failed) { 11998 uint32_t Width = (End - Idx + 1) * 32; 11999 MCRegister Reg = RC->getRegister(Idx); 12000 if (SIRegisterInfo::isVGPRClass(RC)) 12001 RC = TRI->getVGPRClassForBitWidth(Width); 12002 else if (SIRegisterInfo::isSGPRClass(RC)) 12003 RC = TRI->getSGPRClassForBitWidth(Width); 12004 else if (SIRegisterInfo::isAGPRClass(RC)) 12005 RC = TRI->getAGPRClassForBitWidth(Width); 12006 if (RC) { 12007 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC); 12008 return std::make_pair(Reg, RC); 12009 } 12010 } 12011 } else { 12012 bool Failed = RegName.getAsInteger(10, Idx); 12013 if (!Failed && Idx < RC->getNumRegs()) 12014 return std::make_pair(RC->getRegister(Idx), RC); 12015 } 12016 } 12017 } 12018 12019 auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 12020 if (Ret.first) 12021 Ret.second = TRI->getPhysRegClass(Ret.first); 12022 12023 return Ret; 12024 } 12025 12026 static bool isImmConstraint(StringRef Constraint) { 12027 if (Constraint.size() == 1) { 12028 switch (Constraint[0]) { 12029 default: break; 12030 case 'I': 12031 case 'J': 12032 case 'A': 12033 case 'B': 12034 case 'C': 12035 return true; 12036 } 12037 } else if (Constraint == "DA" || 12038 Constraint == "DB") { 12039 return true; 12040 } 12041 return false; 12042 } 12043 12044 SITargetLowering::ConstraintType 12045 SITargetLowering::getConstraintType(StringRef Constraint) const { 12046 if (Constraint.size() == 1) { 12047 switch (Constraint[0]) { 12048 default: break; 12049 case 's': 12050 case 'v': 12051 case 'a': 12052 return C_RegisterClass; 12053 } 12054 } 12055 if (isImmConstraint(Constraint)) { 12056 return C_Other; 12057 } 12058 return TargetLowering::getConstraintType(Constraint); 12059 } 12060 12061 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 12062 if (!AMDGPU::isInlinableIntLiteral(Val)) { 12063 Val = Val & maskTrailingOnes<uint64_t>(Size); 12064 } 12065 return Val; 12066 } 12067 12068 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 12069 std::string &Constraint, 12070 std::vector<SDValue> &Ops, 12071 SelectionDAG &DAG) const { 12072 if (isImmConstraint(Constraint)) { 12073 uint64_t Val; 12074 if (getAsmOperandConstVal(Op, Val) && 12075 checkAsmConstraintVal(Op, Constraint, Val)) { 12076 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 12077 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 12078 } 12079 } else { 12080 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12081 } 12082 } 12083 12084 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 12085 unsigned Size = Op.getScalarValueSizeInBits(); 12086 if (Size > 64) 12087 return false; 12088 12089 if (Size == 16 && !Subtarget->has16BitInsts()) 12090 return false; 12091 12092 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12093 Val = C->getSExtValue(); 12094 return true; 12095 } 12096 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 12097 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 12098 return true; 12099 } 12100 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 12101 if (Size != 16 || Op.getNumOperands() != 2) 12102 return false; 12103 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 12104 return false; 12105 if (ConstantSDNode *C = V->getConstantSplatNode()) { 12106 Val = C->getSExtValue(); 12107 return true; 12108 } 12109 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 12110 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 12111 return true; 12112 } 12113 } 12114 12115 return false; 12116 } 12117 12118 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 12119 const std::string &Constraint, 12120 uint64_t Val) const { 12121 if (Constraint.size() == 1) { 12122 switch (Constraint[0]) { 12123 case 'I': 12124 return AMDGPU::isInlinableIntLiteral(Val); 12125 case 'J': 12126 return isInt<16>(Val); 12127 case 'A': 12128 return checkAsmConstraintValA(Op, Val); 12129 case 'B': 12130 return isInt<32>(Val); 12131 case 'C': 12132 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 12133 AMDGPU::isInlinableIntLiteral(Val); 12134 default: 12135 break; 12136 } 12137 } else if (Constraint.size() == 2) { 12138 if (Constraint == "DA") { 12139 int64_t HiBits = static_cast<int32_t>(Val >> 32); 12140 int64_t LoBits = static_cast<int32_t>(Val); 12141 return checkAsmConstraintValA(Op, HiBits, 32) && 12142 checkAsmConstraintValA(Op, LoBits, 32); 12143 } 12144 if (Constraint == "DB") { 12145 return true; 12146 } 12147 } 12148 llvm_unreachable("Invalid asm constraint"); 12149 } 12150 12151 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 12152 uint64_t Val, 12153 unsigned MaxSize) const { 12154 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 12155 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 12156 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 12157 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 12158 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 12159 return true; 12160 } 12161 return false; 12162 } 12163 12164 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 12165 switch (UnalignedClassID) { 12166 case AMDGPU::VReg_64RegClassID: 12167 return AMDGPU::VReg_64_Align2RegClassID; 12168 case AMDGPU::VReg_96RegClassID: 12169 return AMDGPU::VReg_96_Align2RegClassID; 12170 case AMDGPU::VReg_128RegClassID: 12171 return AMDGPU::VReg_128_Align2RegClassID; 12172 case AMDGPU::VReg_160RegClassID: 12173 return AMDGPU::VReg_160_Align2RegClassID; 12174 case AMDGPU::VReg_192RegClassID: 12175 return AMDGPU::VReg_192_Align2RegClassID; 12176 case AMDGPU::VReg_224RegClassID: 12177 return AMDGPU::VReg_224_Align2RegClassID; 12178 case AMDGPU::VReg_256RegClassID: 12179 return AMDGPU::VReg_256_Align2RegClassID; 12180 case AMDGPU::VReg_512RegClassID: 12181 return AMDGPU::VReg_512_Align2RegClassID; 12182 case AMDGPU::VReg_1024RegClassID: 12183 return AMDGPU::VReg_1024_Align2RegClassID; 12184 case AMDGPU::AReg_64RegClassID: 12185 return AMDGPU::AReg_64_Align2RegClassID; 12186 case AMDGPU::AReg_96RegClassID: 12187 return AMDGPU::AReg_96_Align2RegClassID; 12188 case AMDGPU::AReg_128RegClassID: 12189 return AMDGPU::AReg_128_Align2RegClassID; 12190 case AMDGPU::AReg_160RegClassID: 12191 return AMDGPU::AReg_160_Align2RegClassID; 12192 case AMDGPU::AReg_192RegClassID: 12193 return AMDGPU::AReg_192_Align2RegClassID; 12194 case AMDGPU::AReg_256RegClassID: 12195 return AMDGPU::AReg_256_Align2RegClassID; 12196 case AMDGPU::AReg_512RegClassID: 12197 return AMDGPU::AReg_512_Align2RegClassID; 12198 case AMDGPU::AReg_1024RegClassID: 12199 return AMDGPU::AReg_1024_Align2RegClassID; 12200 default: 12201 return -1; 12202 } 12203 } 12204 12205 // Figure out which registers should be reserved for stack access. Only after 12206 // the function is legalized do we know all of the non-spill stack objects or if 12207 // calls are present. 12208 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 12209 MachineRegisterInfo &MRI = MF.getRegInfo(); 12210 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12211 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 12212 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12213 const SIInstrInfo *TII = ST.getInstrInfo(); 12214 12215 if (Info->isEntryFunction()) { 12216 // Callable functions have fixed registers used for stack access. 12217 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 12218 } 12219 12220 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 12221 Info->getStackPtrOffsetReg())); 12222 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 12223 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 12224 12225 // We need to worry about replacing the default register with itself in case 12226 // of MIR testcases missing the MFI. 12227 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 12228 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 12229 12230 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 12231 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 12232 12233 Info->limitOccupancy(MF); 12234 12235 if (ST.isWave32() && !MF.empty()) { 12236 for (auto &MBB : MF) { 12237 for (auto &MI : MBB) { 12238 TII->fixImplicitOperands(MI); 12239 } 12240 } 12241 } 12242 12243 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 12244 // classes if required. Ideally the register class constraints would differ 12245 // per-subtarget, but there's no easy way to achieve that right now. This is 12246 // not a problem for VGPRs because the correctly aligned VGPR class is implied 12247 // from using them as the register class for legal types. 12248 if (ST.needsAlignedVGPRs()) { 12249 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 12250 const Register Reg = Register::index2VirtReg(I); 12251 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 12252 if (!RC) 12253 continue; 12254 int NewClassID = getAlignedAGPRClassID(RC->getID()); 12255 if (NewClassID != -1) 12256 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 12257 } 12258 } 12259 12260 TargetLoweringBase::finalizeLowering(MF); 12261 } 12262 12263 void SITargetLowering::computeKnownBitsForFrameIndex( 12264 const int FI, KnownBits &Known, const MachineFunction &MF) const { 12265 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 12266 12267 // Set the high bits to zero based on the maximum allowed scratch size per 12268 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 12269 // calculation won't overflow, so assume the sign bit is never set. 12270 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 12271 } 12272 12273 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 12274 KnownBits &Known, unsigned Dim) { 12275 unsigned MaxValue = 12276 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 12277 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 12278 } 12279 12280 void SITargetLowering::computeKnownBitsForTargetInstr( 12281 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 12282 const MachineRegisterInfo &MRI, unsigned Depth) const { 12283 const MachineInstr *MI = MRI.getVRegDef(R); 12284 switch (MI->getOpcode()) { 12285 case AMDGPU::G_INTRINSIC: { 12286 switch (MI->getIntrinsicID()) { 12287 case Intrinsic::amdgcn_workitem_id_x: 12288 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 12289 break; 12290 case Intrinsic::amdgcn_workitem_id_y: 12291 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 12292 break; 12293 case Intrinsic::amdgcn_workitem_id_z: 12294 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 12295 break; 12296 case Intrinsic::amdgcn_mbcnt_lo: 12297 case Intrinsic::amdgcn_mbcnt_hi: { 12298 // These return at most the wavefront size - 1. 12299 unsigned Size = MRI.getType(R).getSizeInBits(); 12300 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 12301 break; 12302 } 12303 case Intrinsic::amdgcn_groupstaticsize: { 12304 // We can report everything over the maximum size as 0. We can't report 12305 // based on the actual size because we don't know if it's accurate or not 12306 // at any given point. 12307 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 12308 break; 12309 } 12310 } 12311 break; 12312 } 12313 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 12314 Known.Zero.setHighBits(24); 12315 break; 12316 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 12317 Known.Zero.setHighBits(16); 12318 break; 12319 } 12320 } 12321 12322 Align SITargetLowering::computeKnownAlignForTargetInstr( 12323 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 12324 unsigned Depth) const { 12325 const MachineInstr *MI = MRI.getVRegDef(R); 12326 switch (MI->getOpcode()) { 12327 case AMDGPU::G_INTRINSIC: 12328 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 12329 // FIXME: Can this move to generic code? What about the case where the call 12330 // site specifies a lower alignment? 12331 Intrinsic::ID IID = MI->getIntrinsicID(); 12332 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 12333 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 12334 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 12335 return *RetAlign; 12336 return Align(1); 12337 } 12338 default: 12339 return Align(1); 12340 } 12341 } 12342 12343 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12344 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 12345 const Align CacheLineAlign = Align(64); 12346 12347 // Pre-GFX10 target did not benefit from loop alignment 12348 if (!ML || DisableLoopAlignment || 12349 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 12350 getSubtarget()->hasInstFwdPrefetchBug()) 12351 return PrefAlign; 12352 12353 // On GFX10 I$ is 4 x 64 bytes cache lines. 12354 // By default prefetcher keeps one cache line behind and reads two ahead. 12355 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 12356 // behind and one ahead. 12357 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 12358 // If loop fits 64 bytes it always spans no more than two cache lines and 12359 // does not need an alignment. 12360 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 12361 // Else if loop is less or equal 192 bytes we need two lines behind. 12362 12363 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 12364 const MachineBasicBlock *Header = ML->getHeader(); 12365 if (Header->getAlignment() != PrefAlign) 12366 return Header->getAlignment(); // Already processed. 12367 12368 unsigned LoopSize = 0; 12369 for (const MachineBasicBlock *MBB : ML->blocks()) { 12370 // If inner loop block is aligned assume in average half of the alignment 12371 // size to be added as nops. 12372 if (MBB != Header) 12373 LoopSize += MBB->getAlignment().value() / 2; 12374 12375 for (const MachineInstr &MI : *MBB) { 12376 LoopSize += TII->getInstSizeInBytes(MI); 12377 if (LoopSize > 192) 12378 return PrefAlign; 12379 } 12380 } 12381 12382 if (LoopSize <= 64) 12383 return PrefAlign; 12384 12385 if (LoopSize <= 128) 12386 return CacheLineAlign; 12387 12388 // If any of parent loops is surrounded by prefetch instructions do not 12389 // insert new for inner loop, which would reset parent's settings. 12390 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 12391 if (MachineBasicBlock *Exit = P->getExitBlock()) { 12392 auto I = Exit->getFirstNonDebugInstr(); 12393 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 12394 return CacheLineAlign; 12395 } 12396 } 12397 12398 MachineBasicBlock *Pre = ML->getLoopPreheader(); 12399 MachineBasicBlock *Exit = ML->getExitBlock(); 12400 12401 if (Pre && Exit) { 12402 auto PreTerm = Pre->getFirstTerminator(); 12403 if (PreTerm == Pre->begin() || 12404 std::prev(PreTerm)->getOpcode() != AMDGPU::S_INST_PREFETCH) 12405 BuildMI(*Pre, PreTerm, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH)) 12406 .addImm(1); // prefetch 2 lines behind PC 12407 12408 auto ExitHead = Exit->getFirstNonDebugInstr(); 12409 if (ExitHead == Exit->end() || 12410 ExitHead->getOpcode() != AMDGPU::S_INST_PREFETCH) 12411 BuildMI(*Exit, ExitHead, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH)) 12412 .addImm(2); // prefetch 1 line behind PC 12413 } 12414 12415 return CacheLineAlign; 12416 } 12417 12418 LLVM_ATTRIBUTE_UNUSED 12419 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 12420 assert(N->getOpcode() == ISD::CopyFromReg); 12421 do { 12422 // Follow the chain until we find an INLINEASM node. 12423 N = N->getOperand(0).getNode(); 12424 if (N->getOpcode() == ISD::INLINEASM || 12425 N->getOpcode() == ISD::INLINEASM_BR) 12426 return true; 12427 } while (N->getOpcode() == ISD::CopyFromReg); 12428 return false; 12429 } 12430 12431 bool SITargetLowering::isSDNodeSourceOfDivergence( 12432 const SDNode *N, FunctionLoweringInfo *FLI, 12433 LegacyDivergenceAnalysis *KDA) const { 12434 switch (N->getOpcode()) { 12435 case ISD::CopyFromReg: { 12436 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 12437 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 12438 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12439 Register Reg = R->getReg(); 12440 12441 // FIXME: Why does this need to consider isLiveIn? 12442 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 12443 return !TRI->isSGPRReg(MRI, Reg); 12444 12445 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 12446 return KDA->isDivergent(V); 12447 12448 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 12449 return !TRI->isSGPRReg(MRI, Reg); 12450 } 12451 case ISD::LOAD: { 12452 const LoadSDNode *L = cast<LoadSDNode>(N); 12453 unsigned AS = L->getAddressSpace(); 12454 // A flat load may access private memory. 12455 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 12456 } 12457 case ISD::CALLSEQ_END: 12458 return true; 12459 case ISD::INTRINSIC_WO_CHAIN: 12460 return AMDGPU::isIntrinsicSourceOfDivergence( 12461 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 12462 case ISD::INTRINSIC_W_CHAIN: 12463 return AMDGPU::isIntrinsicSourceOfDivergence( 12464 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 12465 case AMDGPUISD::ATOMIC_CMP_SWAP: 12466 case AMDGPUISD::ATOMIC_INC: 12467 case AMDGPUISD::ATOMIC_DEC: 12468 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12469 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12470 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12471 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12472 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12473 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12474 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12475 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12476 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12477 case AMDGPUISD::BUFFER_ATOMIC_AND: 12478 case AMDGPUISD::BUFFER_ATOMIC_OR: 12479 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12480 case AMDGPUISD::BUFFER_ATOMIC_INC: 12481 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12482 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12483 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12484 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12485 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12486 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12487 // Target-specific read-modify-write atomics are sources of divergence. 12488 return true; 12489 default: 12490 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12491 // Generic read-modify-write atomics are sources of divergence. 12492 return A->readMem() && A->writeMem(); 12493 } 12494 return false; 12495 } 12496 } 12497 12498 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12499 EVT VT) const { 12500 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12501 case MVT::f32: 12502 return hasFP32Denormals(DAG.getMachineFunction()); 12503 case MVT::f64: 12504 case MVT::f16: 12505 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12506 default: 12507 return false; 12508 } 12509 } 12510 12511 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12512 MachineFunction &MF) const { 12513 switch (Ty.getScalarSizeInBits()) { 12514 case 32: 12515 return hasFP32Denormals(MF); 12516 case 64: 12517 case 16: 12518 return hasFP64FP16Denormals(MF); 12519 default: 12520 return false; 12521 } 12522 } 12523 12524 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12525 const SelectionDAG &DAG, 12526 bool SNaN, 12527 unsigned Depth) const { 12528 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12529 const MachineFunction &MF = DAG.getMachineFunction(); 12530 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12531 12532 if (Info->getMode().DX10Clamp) 12533 return true; // Clamped to 0. 12534 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12535 } 12536 12537 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12538 SNaN, Depth); 12539 } 12540 12541 // Global FP atomic instructions have a hardcoded FP mode and do not support 12542 // FP32 denormals, and only support v2f16 denormals. 12543 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12544 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12545 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12546 if (&Flt == &APFloat::IEEEsingle()) 12547 return DenormMode == DenormalMode::getPreserveSign(); 12548 return DenormMode == DenormalMode::getIEEE(); 12549 } 12550 12551 TargetLowering::AtomicExpansionKind 12552 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12553 unsigned AS = RMW->getPointerAddressSpace(); 12554 if (AS == AMDGPUAS::PRIVATE_ADDRESS) 12555 return AtomicExpansionKind::NotAtomic; 12556 12557 auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) { 12558 OptimizationRemarkEmitter ORE(RMW->getFunction()); 12559 LLVMContext &Ctx = RMW->getFunction()->getContext(); 12560 SmallVector<StringRef> SSNs; 12561 Ctx.getSyncScopeNames(SSNs); 12562 auto MemScope = SSNs[RMW->getSyncScopeID()].empty() 12563 ? "system" 12564 : SSNs[RMW->getSyncScopeID()]; 12565 ORE.emit([&]() { 12566 return OptimizationRemark(DEBUG_TYPE, "Passed", RMW) 12567 << "Hardware instruction generated for atomic " 12568 << RMW->getOperationName(RMW->getOperation()) 12569 << " operation at memory scope " << MemScope 12570 << " due to an unsafe request."; 12571 }); 12572 return Kind; 12573 }; 12574 12575 switch (RMW->getOperation()) { 12576 case AtomicRMWInst::FAdd: { 12577 Type *Ty = RMW->getType(); 12578 12579 // We don't have a way to support 16-bit atomics now, so just leave them 12580 // as-is. 12581 if (Ty->isHalfTy()) 12582 return AtomicExpansionKind::None; 12583 12584 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12585 return AtomicExpansionKind::CmpXChg; 12586 12587 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12588 Subtarget->hasAtomicFaddInsts()) { 12589 if (Subtarget->hasGFX940Insts()) 12590 return AtomicExpansionKind::None; 12591 12592 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12593 // floating point atomic instructions. May generate more efficient code, 12594 // but may not respect rounding and denormal modes, and may give incorrect 12595 // results for certain memory destinations. 12596 if (RMW->getFunction() 12597 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12598 .getValueAsString() != "true") 12599 return AtomicExpansionKind::CmpXChg; 12600 12601 if (Subtarget->hasGFX90AInsts()) { 12602 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) 12603 return AtomicExpansionKind::CmpXChg; 12604 12605 auto SSID = RMW->getSyncScopeID(); 12606 if (SSID == SyncScope::System || 12607 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12608 return AtomicExpansionKind::CmpXChg; 12609 12610 return ReportUnsafeHWInst(AtomicExpansionKind::None); 12611 } 12612 12613 if (AS == AMDGPUAS::FLAT_ADDRESS) 12614 return AtomicExpansionKind::CmpXChg; 12615 12616 return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12617 : AtomicExpansionKind::CmpXChg; 12618 } 12619 12620 // DS FP atomics do respect the denormal mode, but the rounding mode is 12621 // fixed to round-to-nearest-even. 12622 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12623 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) { 12624 if (!Ty->isDoubleTy()) 12625 return AtomicExpansionKind::None; 12626 12627 if (fpModeMatchesGlobalFPAtomicMode(RMW)) 12628 return AtomicExpansionKind::None; 12629 12630 return RMW->getFunction() 12631 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12632 .getValueAsString() == "true" 12633 ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12634 : AtomicExpansionKind::CmpXChg; 12635 } 12636 12637 return AtomicExpansionKind::CmpXChg; 12638 } 12639 default: 12640 break; 12641 } 12642 12643 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12644 } 12645 12646 TargetLowering::AtomicExpansionKind 12647 SITargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 12648 return LI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12649 ? AtomicExpansionKind::NotAtomic 12650 : AtomicExpansionKind::None; 12651 } 12652 12653 TargetLowering::AtomicExpansionKind 12654 SITargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 12655 return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12656 ? AtomicExpansionKind::NotAtomic 12657 : AtomicExpansionKind::None; 12658 } 12659 12660 TargetLowering::AtomicExpansionKind 12661 SITargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CmpX) const { 12662 return CmpX->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12663 ? AtomicExpansionKind::NotAtomic 12664 : AtomicExpansionKind::None; 12665 } 12666 12667 const TargetRegisterClass * 12668 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12669 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12670 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12671 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12672 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12673 : &AMDGPU::SReg_32RegClass; 12674 if (!TRI->isSGPRClass(RC) && !isDivergent) 12675 return TRI->getEquivalentSGPRClass(RC); 12676 else if (TRI->isSGPRClass(RC) && isDivergent) 12677 return TRI->getEquivalentVGPRClass(RC); 12678 12679 return RC; 12680 } 12681 12682 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12683 // uniform values (as produced by the mask results of control flow intrinsics) 12684 // used outside of divergent blocks. The phi users need to also be treated as 12685 // always uniform. 12686 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12687 unsigned WaveSize) { 12688 // FIXME: We assume we never cast the mask results of a control flow 12689 // intrinsic. 12690 // Early exit if the type won't be consistent as a compile time hack. 12691 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12692 if (!IT || IT->getBitWidth() != WaveSize) 12693 return false; 12694 12695 if (!isa<Instruction>(V)) 12696 return false; 12697 if (!Visited.insert(V).second) 12698 return false; 12699 bool Result = false; 12700 for (auto U : V->users()) { 12701 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12702 if (V == U->getOperand(1)) { 12703 switch (Intrinsic->getIntrinsicID()) { 12704 default: 12705 Result = false; 12706 break; 12707 case Intrinsic::amdgcn_if_break: 12708 case Intrinsic::amdgcn_if: 12709 case Intrinsic::amdgcn_else: 12710 Result = true; 12711 break; 12712 } 12713 } 12714 if (V == U->getOperand(0)) { 12715 switch (Intrinsic->getIntrinsicID()) { 12716 default: 12717 Result = false; 12718 break; 12719 case Intrinsic::amdgcn_end_cf: 12720 case Intrinsic::amdgcn_loop: 12721 Result = true; 12722 break; 12723 } 12724 } 12725 } else { 12726 Result = hasCFUser(U, Visited, WaveSize); 12727 } 12728 if (Result) 12729 break; 12730 } 12731 return Result; 12732 } 12733 12734 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12735 const Value *V) const { 12736 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12737 if (CI->isInlineAsm()) { 12738 // FIXME: This cannot give a correct answer. This should only trigger in 12739 // the case where inline asm returns mixed SGPR and VGPR results, used 12740 // outside the defining block. We don't have a specific result to 12741 // consider, so this assumes if any value is SGPR, the overall register 12742 // also needs to be SGPR. 12743 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12744 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12745 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12746 for (auto &TC : TargetConstraints) { 12747 if (TC.Type == InlineAsm::isOutput) { 12748 ComputeConstraintToUse(TC, SDValue()); 12749 const TargetRegisterClass *RC = getRegForInlineAsmConstraint( 12750 SIRI, TC.ConstraintCode, TC.ConstraintVT).second; 12751 if (RC && SIRI->isSGPRClass(RC)) 12752 return true; 12753 } 12754 } 12755 } 12756 } 12757 SmallPtrSet<const Value *, 16> Visited; 12758 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12759 } 12760 12761 std::pair<InstructionCost, MVT> 12762 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12763 Type *Ty) const { 12764 std::pair<InstructionCost, MVT> Cost = 12765 TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12766 auto Size = DL.getTypeSizeInBits(Ty); 12767 // Maximum load or store can handle 8 dwords for scalar and 4 for 12768 // vector ALU. Let's assume anything above 8 dwords is expensive 12769 // even if legal. 12770 if (Size <= 256) 12771 return Cost; 12772 12773 Cost.first += (Size + 255) / 256; 12774 return Cost; 12775 } 12776 12777 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const { 12778 SDNode::use_iterator I = N->use_begin(), E = N->use_end(); 12779 for (; I != E; ++I) { 12780 if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) { 12781 if (getBasePtrIndex(M) == I.getOperandNo()) 12782 return true; 12783 } 12784 } 12785 return false; 12786 } 12787 12788 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0, 12789 SDValue N1) const { 12790 if (!N0.hasOneUse()) 12791 return false; 12792 // Take care of the opportunity to keep N0 uniform 12793 if (N0->isDivergent() || !N1->isDivergent()) 12794 return true; 12795 // Check if we have a good chance to form the memory access pattern with the 12796 // base and offset 12797 return (DAG.isBaseWithConstantOffset(N0) && 12798 hasMemSDNodeUser(*N0->use_begin())); 12799 } 12800 12801 MachineMemOperand::Flags 12802 SITargetLowering::getTargetMMOFlags(const Instruction &I) const { 12803 // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load. 12804 if (I.getMetadata("amdgpu.noclobber")) 12805 return MONoClobber; 12806 return MachineMemOperand::MONone; 12807 } 12808