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::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1585 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1586 switch (Op) { 1587 case ISD::LOAD: 1588 case ISD::STORE: 1589 1590 // These operations are done with 32-bit instructions anyway. 1591 case ISD::AND: 1592 case ISD::OR: 1593 case ISD::XOR: 1594 case ISD::SELECT: 1595 // TODO: Extensions? 1596 return true; 1597 default: 1598 return false; 1599 } 1600 } 1601 1602 // SimplifySetCC uses this function to determine whether or not it should 1603 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1604 if (VT == MVT::i1 && Op == ISD::SETCC) 1605 return false; 1606 1607 return TargetLowering::isTypeDesirableForOp(Op, VT); 1608 } 1609 1610 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1611 const SDLoc &SL, 1612 SDValue Chain, 1613 uint64_t Offset) const { 1614 const DataLayout &DL = DAG.getDataLayout(); 1615 MachineFunction &MF = DAG.getMachineFunction(); 1616 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1617 1618 const ArgDescriptor *InputPtrReg; 1619 const TargetRegisterClass *RC; 1620 LLT ArgTy; 1621 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1622 1623 std::tie(InputPtrReg, RC, ArgTy) = 1624 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1625 1626 // We may not have the kernarg segment argument if we have no kernel 1627 // arguments. 1628 if (!InputPtrReg) 1629 return DAG.getConstant(0, SL, PtrVT); 1630 1631 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1632 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1633 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1634 1635 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1636 } 1637 1638 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1639 const SDLoc &SL) const { 1640 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1641 FIRST_IMPLICIT); 1642 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1643 } 1644 1645 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1646 const SDLoc &SL, SDValue Val, 1647 bool Signed, 1648 const ISD::InputArg *Arg) const { 1649 // First, if it is a widened vector, narrow it. 1650 if (VT.isVector() && 1651 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1652 EVT NarrowedVT = 1653 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1654 VT.getVectorNumElements()); 1655 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1656 DAG.getConstant(0, SL, MVT::i32)); 1657 } 1658 1659 // Then convert the vector elements or scalar value. 1660 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1661 VT.bitsLT(MemVT)) { 1662 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1663 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1664 } 1665 1666 if (MemVT.isFloatingPoint()) 1667 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1668 else if (Signed) 1669 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1670 else 1671 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1672 1673 return Val; 1674 } 1675 1676 SDValue SITargetLowering::lowerKernargMemParameter( 1677 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1678 uint64_t Offset, Align Alignment, bool Signed, 1679 const ISD::InputArg *Arg) const { 1680 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1681 1682 // Try to avoid using an extload by loading earlier than the argument address, 1683 // and extracting the relevant bits. The load should hopefully be merged with 1684 // the previous argument. 1685 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1686 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1687 int64_t AlignDownOffset = alignDown(Offset, 4); 1688 int64_t OffsetDiff = Offset - AlignDownOffset; 1689 1690 EVT IntVT = MemVT.changeTypeToInteger(); 1691 1692 // TODO: If we passed in the base kernel offset we could have a better 1693 // alignment than 4, but we don't really need it. 1694 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1695 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1696 MachineMemOperand::MODereferenceable | 1697 MachineMemOperand::MOInvariant); 1698 1699 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1700 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1701 1702 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1703 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1704 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1705 1706 1707 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1708 } 1709 1710 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1711 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1712 MachineMemOperand::MODereferenceable | 1713 MachineMemOperand::MOInvariant); 1714 1715 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1716 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1717 } 1718 1719 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1720 const SDLoc &SL, SDValue Chain, 1721 const ISD::InputArg &Arg) const { 1722 MachineFunction &MF = DAG.getMachineFunction(); 1723 MachineFrameInfo &MFI = MF.getFrameInfo(); 1724 1725 if (Arg.Flags.isByVal()) { 1726 unsigned Size = Arg.Flags.getByValSize(); 1727 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1728 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1729 } 1730 1731 unsigned ArgOffset = VA.getLocMemOffset(); 1732 unsigned ArgSize = VA.getValVT().getStoreSize(); 1733 1734 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1735 1736 // Create load nodes to retrieve arguments from the stack. 1737 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1738 SDValue ArgValue; 1739 1740 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1741 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1742 MVT MemVT = VA.getValVT(); 1743 1744 switch (VA.getLocInfo()) { 1745 default: 1746 break; 1747 case CCValAssign::BCvt: 1748 MemVT = VA.getLocVT(); 1749 break; 1750 case CCValAssign::SExt: 1751 ExtType = ISD::SEXTLOAD; 1752 break; 1753 case CCValAssign::ZExt: 1754 ExtType = ISD::ZEXTLOAD; 1755 break; 1756 case CCValAssign::AExt: 1757 ExtType = ISD::EXTLOAD; 1758 break; 1759 } 1760 1761 ArgValue = DAG.getExtLoad( 1762 ExtType, SL, VA.getLocVT(), Chain, FIN, 1763 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1764 MemVT); 1765 return ArgValue; 1766 } 1767 1768 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1769 const SIMachineFunctionInfo &MFI, 1770 EVT VT, 1771 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1772 const ArgDescriptor *Reg; 1773 const TargetRegisterClass *RC; 1774 LLT Ty; 1775 1776 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1777 if (!Reg) { 1778 if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) { 1779 // It's possible for a kernarg intrinsic call to appear in a kernel with 1780 // no allocated segment, in which case we do not add the user sgpr 1781 // argument, so just return null. 1782 return DAG.getConstant(0, SDLoc(), VT); 1783 } 1784 1785 // It's undefined behavior if a function marked with the amdgpu-no-* 1786 // attributes uses the corresponding intrinsic. 1787 return DAG.getUNDEF(VT); 1788 } 1789 1790 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1791 } 1792 1793 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1794 CallingConv::ID CallConv, 1795 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1796 FunctionType *FType, 1797 SIMachineFunctionInfo *Info) { 1798 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1799 const ISD::InputArg *Arg = &Ins[I]; 1800 1801 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1802 "vector type argument should have been split"); 1803 1804 // First check if it's a PS input addr. 1805 if (CallConv == CallingConv::AMDGPU_PS && 1806 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1807 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1808 1809 // Inconveniently only the first part of the split is marked as isSplit, 1810 // so skip to the end. We only want to increment PSInputNum once for the 1811 // entire split argument. 1812 if (Arg->Flags.isSplit()) { 1813 while (!Arg->Flags.isSplitEnd()) { 1814 assert((!Arg->VT.isVector() || 1815 Arg->VT.getScalarSizeInBits() == 16) && 1816 "unexpected vector split in ps argument type"); 1817 if (!SkipArg) 1818 Splits.push_back(*Arg); 1819 Arg = &Ins[++I]; 1820 } 1821 } 1822 1823 if (SkipArg) { 1824 // We can safely skip PS inputs. 1825 Skipped.set(Arg->getOrigArgIndex()); 1826 ++PSInputNum; 1827 continue; 1828 } 1829 1830 Info->markPSInputAllocated(PSInputNum); 1831 if (Arg->Used) 1832 Info->markPSInputEnabled(PSInputNum); 1833 1834 ++PSInputNum; 1835 } 1836 1837 Splits.push_back(*Arg); 1838 } 1839 } 1840 1841 // Allocate special inputs passed in VGPRs. 1842 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1843 MachineFunction &MF, 1844 const SIRegisterInfo &TRI, 1845 SIMachineFunctionInfo &Info) const { 1846 const LLT S32 = LLT::scalar(32); 1847 MachineRegisterInfo &MRI = MF.getRegInfo(); 1848 1849 if (Info.hasWorkItemIDX()) { 1850 Register Reg = AMDGPU::VGPR0; 1851 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1852 1853 CCInfo.AllocateReg(Reg); 1854 unsigned Mask = (Subtarget->hasPackedTID() && 1855 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 1856 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1857 } 1858 1859 if (Info.hasWorkItemIDY()) { 1860 assert(Info.hasWorkItemIDX()); 1861 if (Subtarget->hasPackedTID()) { 1862 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1863 0x3ff << 10)); 1864 } else { 1865 unsigned Reg = AMDGPU::VGPR1; 1866 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1867 1868 CCInfo.AllocateReg(Reg); 1869 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1870 } 1871 } 1872 1873 if (Info.hasWorkItemIDZ()) { 1874 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 1875 if (Subtarget->hasPackedTID()) { 1876 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1877 0x3ff << 20)); 1878 } else { 1879 unsigned Reg = AMDGPU::VGPR2; 1880 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1881 1882 CCInfo.AllocateReg(Reg); 1883 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1884 } 1885 } 1886 } 1887 1888 // Try to allocate a VGPR at the end of the argument list, or if no argument 1889 // VGPRs are left allocating a stack slot. 1890 // If \p Mask is is given it indicates bitfield position in the register. 1891 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1892 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1893 ArgDescriptor Arg = ArgDescriptor()) { 1894 if (Arg.isSet()) 1895 return ArgDescriptor::createArg(Arg, Mask); 1896 1897 ArrayRef<MCPhysReg> ArgVGPRs 1898 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1899 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1900 if (RegIdx == ArgVGPRs.size()) { 1901 // Spill to stack required. 1902 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1903 1904 return ArgDescriptor::createStack(Offset, Mask); 1905 } 1906 1907 unsigned Reg = ArgVGPRs[RegIdx]; 1908 Reg = CCInfo.AllocateReg(Reg); 1909 assert(Reg != AMDGPU::NoRegister); 1910 1911 MachineFunction &MF = CCInfo.getMachineFunction(); 1912 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1913 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1914 return ArgDescriptor::createRegister(Reg, Mask); 1915 } 1916 1917 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1918 const TargetRegisterClass *RC, 1919 unsigned NumArgRegs) { 1920 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1921 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1922 if (RegIdx == ArgSGPRs.size()) 1923 report_fatal_error("ran out of SGPRs for arguments"); 1924 1925 unsigned Reg = ArgSGPRs[RegIdx]; 1926 Reg = CCInfo.AllocateReg(Reg); 1927 assert(Reg != AMDGPU::NoRegister); 1928 1929 MachineFunction &MF = CCInfo.getMachineFunction(); 1930 MF.addLiveIn(Reg, RC); 1931 return ArgDescriptor::createRegister(Reg); 1932 } 1933 1934 // If this has a fixed position, we still should allocate the register in the 1935 // CCInfo state. Technically we could get away with this for values passed 1936 // outside of the normal argument range. 1937 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 1938 const TargetRegisterClass *RC, 1939 MCRegister Reg) { 1940 Reg = CCInfo.AllocateReg(Reg); 1941 assert(Reg != AMDGPU::NoRegister); 1942 MachineFunction &MF = CCInfo.getMachineFunction(); 1943 MF.addLiveIn(Reg, RC); 1944 } 1945 1946 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 1947 if (Arg) { 1948 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 1949 Arg.getRegister()); 1950 } else 1951 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1952 } 1953 1954 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 1955 if (Arg) { 1956 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 1957 Arg.getRegister()); 1958 } else 1959 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1960 } 1961 1962 /// Allocate implicit function VGPR arguments at the end of allocated user 1963 /// arguments. 1964 void SITargetLowering::allocateSpecialInputVGPRs( 1965 CCState &CCInfo, MachineFunction &MF, 1966 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1967 const unsigned Mask = 0x3ff; 1968 ArgDescriptor Arg; 1969 1970 if (Info.hasWorkItemIDX()) { 1971 Arg = allocateVGPR32Input(CCInfo, Mask); 1972 Info.setWorkItemIDX(Arg); 1973 } 1974 1975 if (Info.hasWorkItemIDY()) { 1976 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1977 Info.setWorkItemIDY(Arg); 1978 } 1979 1980 if (Info.hasWorkItemIDZ()) 1981 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1982 } 1983 1984 /// Allocate implicit function VGPR arguments in fixed registers. 1985 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1986 CCState &CCInfo, MachineFunction &MF, 1987 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1988 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1989 if (!Reg) 1990 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1991 1992 const unsigned Mask = 0x3ff; 1993 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1994 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1995 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1996 } 1997 1998 void SITargetLowering::allocateSpecialInputSGPRs( 1999 CCState &CCInfo, 2000 MachineFunction &MF, 2001 const SIRegisterInfo &TRI, 2002 SIMachineFunctionInfo &Info) const { 2003 auto &ArgInfo = Info.getArgInfo(); 2004 2005 // TODO: Unify handling with private memory pointers. 2006 if (Info.hasDispatchPtr()) 2007 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 2008 2009 if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) 2010 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 2011 2012 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 2013 // constant offset from the kernarg segment. 2014 if (Info.hasImplicitArgPtr()) 2015 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 2016 2017 if (Info.hasDispatchID()) 2018 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 2019 2020 // flat_scratch_init is not applicable for non-kernel functions. 2021 2022 if (Info.hasWorkGroupIDX()) 2023 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2024 2025 if (Info.hasWorkGroupIDY()) 2026 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2027 2028 if (Info.hasWorkGroupIDZ()) 2029 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2030 } 2031 2032 // Allocate special inputs passed in user SGPRs. 2033 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2034 MachineFunction &MF, 2035 const SIRegisterInfo &TRI, 2036 SIMachineFunctionInfo &Info) const { 2037 if (Info.hasImplicitBufferPtr()) { 2038 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2039 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2040 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2041 } 2042 2043 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2044 if (Info.hasPrivateSegmentBuffer()) { 2045 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2046 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2047 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2048 } 2049 2050 if (Info.hasDispatchPtr()) { 2051 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2052 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2053 CCInfo.AllocateReg(DispatchPtrReg); 2054 } 2055 2056 if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) { 2057 Register QueuePtrReg = Info.addQueuePtr(TRI); 2058 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2059 CCInfo.AllocateReg(QueuePtrReg); 2060 } 2061 2062 if (Info.hasKernargSegmentPtr()) { 2063 MachineRegisterInfo &MRI = MF.getRegInfo(); 2064 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2065 CCInfo.AllocateReg(InputPtrReg); 2066 2067 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2068 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2069 } 2070 2071 if (Info.hasDispatchID()) { 2072 Register DispatchIDReg = Info.addDispatchID(TRI); 2073 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2074 CCInfo.AllocateReg(DispatchIDReg); 2075 } 2076 2077 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2078 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2079 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2080 CCInfo.AllocateReg(FlatScratchInitReg); 2081 } 2082 2083 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2084 // these from the dispatch pointer. 2085 } 2086 2087 // Allocate special input registers that are initialized per-wave. 2088 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2089 MachineFunction &MF, 2090 SIMachineFunctionInfo &Info, 2091 CallingConv::ID CallConv, 2092 bool IsShader) const { 2093 if (Info.hasWorkGroupIDX()) { 2094 Register Reg = Info.addWorkGroupIDX(); 2095 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2096 CCInfo.AllocateReg(Reg); 2097 } 2098 2099 if (Info.hasWorkGroupIDY()) { 2100 Register Reg = Info.addWorkGroupIDY(); 2101 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2102 CCInfo.AllocateReg(Reg); 2103 } 2104 2105 if (Info.hasWorkGroupIDZ()) { 2106 Register Reg = Info.addWorkGroupIDZ(); 2107 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2108 CCInfo.AllocateReg(Reg); 2109 } 2110 2111 if (Info.hasWorkGroupInfo()) { 2112 Register Reg = Info.addWorkGroupInfo(); 2113 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2114 CCInfo.AllocateReg(Reg); 2115 } 2116 2117 if (Info.hasPrivateSegmentWaveByteOffset()) { 2118 // Scratch wave offset passed in system SGPR. 2119 unsigned PrivateSegmentWaveByteOffsetReg; 2120 2121 if (IsShader) { 2122 PrivateSegmentWaveByteOffsetReg = 2123 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2124 2125 // This is true if the scratch wave byte offset doesn't have a fixed 2126 // location. 2127 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2128 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2129 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2130 } 2131 } else 2132 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2133 2134 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2135 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2136 } 2137 } 2138 2139 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2140 MachineFunction &MF, 2141 const SIRegisterInfo &TRI, 2142 SIMachineFunctionInfo &Info) { 2143 // Now that we've figured out where the scratch register inputs are, see if 2144 // should reserve the arguments and use them directly. 2145 MachineFrameInfo &MFI = MF.getFrameInfo(); 2146 bool HasStackObjects = MFI.hasStackObjects(); 2147 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2148 2149 // Record that we know we have non-spill stack objects so we don't need to 2150 // check all stack objects later. 2151 if (HasStackObjects) 2152 Info.setHasNonSpillStackObjects(true); 2153 2154 // Everything live out of a block is spilled with fast regalloc, so it's 2155 // almost certain that spilling will be required. 2156 if (TM.getOptLevel() == CodeGenOpt::None) 2157 HasStackObjects = true; 2158 2159 // For now assume stack access is needed in any callee functions, so we need 2160 // the scratch registers to pass in. 2161 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2162 2163 if (!ST.enableFlatScratch()) { 2164 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2165 // If we have stack objects, we unquestionably need the private buffer 2166 // resource. For the Code Object V2 ABI, this will be the first 4 user 2167 // SGPR inputs. We can reserve those and use them directly. 2168 2169 Register PrivateSegmentBufferReg = 2170 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2171 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2172 } else { 2173 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2174 // We tentatively reserve the last registers (skipping the last registers 2175 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2176 // we'll replace these with the ones immediately after those which were 2177 // really allocated. In the prologue copies will be inserted from the 2178 // argument to these reserved registers. 2179 2180 // Without HSA, relocations are used for the scratch pointer and the 2181 // buffer resource setup is always inserted in the prologue. Scratch wave 2182 // offset is still in an input SGPR. 2183 Info.setScratchRSrcReg(ReservedBufferReg); 2184 } 2185 } 2186 2187 MachineRegisterInfo &MRI = MF.getRegInfo(); 2188 2189 // For entry functions we have to set up the stack pointer if we use it, 2190 // whereas non-entry functions get this "for free". This means there is no 2191 // intrinsic advantage to using S32 over S34 in cases where we do not have 2192 // calls but do need a frame pointer (i.e. if we are requested to have one 2193 // because frame pointer elimination is disabled). To keep things simple we 2194 // only ever use S32 as the call ABI stack pointer, and so using it does not 2195 // imply we need a separate frame pointer. 2196 // 2197 // Try to use s32 as the SP, but move it if it would interfere with input 2198 // arguments. This won't work with calls though. 2199 // 2200 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2201 // registers. 2202 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2203 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2204 } else { 2205 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2206 2207 if (MFI.hasCalls()) 2208 report_fatal_error("call in graphics shader with too many input SGPRs"); 2209 2210 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2211 if (!MRI.isLiveIn(Reg)) { 2212 Info.setStackPtrOffsetReg(Reg); 2213 break; 2214 } 2215 } 2216 2217 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2218 report_fatal_error("failed to find register for SP"); 2219 } 2220 2221 // hasFP should be accurate for entry functions even before the frame is 2222 // finalized, because it does not rely on the known stack size, only 2223 // properties like whether variable sized objects are present. 2224 if (ST.getFrameLowering()->hasFP(MF)) { 2225 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2226 } 2227 } 2228 2229 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2230 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2231 return !Info->isEntryFunction(); 2232 } 2233 2234 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2235 2236 } 2237 2238 void SITargetLowering::insertCopiesSplitCSR( 2239 MachineBasicBlock *Entry, 2240 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2241 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2242 2243 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2244 if (!IStart) 2245 return; 2246 2247 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2248 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2249 MachineBasicBlock::iterator MBBI = Entry->begin(); 2250 for (const MCPhysReg *I = IStart; *I; ++I) { 2251 const TargetRegisterClass *RC = nullptr; 2252 if (AMDGPU::SReg_64RegClass.contains(*I)) 2253 RC = &AMDGPU::SGPR_64RegClass; 2254 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2255 RC = &AMDGPU::SGPR_32RegClass; 2256 else 2257 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2258 2259 Register NewVR = MRI->createVirtualRegister(RC); 2260 // Create copy from CSR to a virtual register. 2261 Entry->addLiveIn(*I); 2262 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2263 .addReg(*I); 2264 2265 // Insert the copy-back instructions right before the terminator. 2266 for (auto *Exit : Exits) 2267 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2268 TII->get(TargetOpcode::COPY), *I) 2269 .addReg(NewVR); 2270 } 2271 } 2272 2273 SDValue SITargetLowering::LowerFormalArguments( 2274 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2275 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2276 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2277 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2278 2279 MachineFunction &MF = DAG.getMachineFunction(); 2280 const Function &Fn = MF.getFunction(); 2281 FunctionType *FType = MF.getFunction().getFunctionType(); 2282 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2283 2284 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2285 DiagnosticInfoUnsupported NoGraphicsHSA( 2286 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2287 DAG.getContext()->diagnose(NoGraphicsHSA); 2288 return DAG.getEntryNode(); 2289 } 2290 2291 Info->allocateModuleLDSGlobal(Fn); 2292 2293 SmallVector<ISD::InputArg, 16> Splits; 2294 SmallVector<CCValAssign, 16> ArgLocs; 2295 BitVector Skipped(Ins.size()); 2296 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2297 *DAG.getContext()); 2298 2299 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2300 bool IsKernel = AMDGPU::isKernel(CallConv); 2301 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2302 2303 if (IsGraphics) { 2304 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2305 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2306 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2307 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2308 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2309 !Info->hasWorkItemIDZ()); 2310 } 2311 2312 if (CallConv == CallingConv::AMDGPU_PS) { 2313 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2314 2315 // At least one interpolation mode must be enabled or else the GPU will 2316 // hang. 2317 // 2318 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2319 // set PSInputAddr, the user wants to enable some bits after the compilation 2320 // based on run-time states. Since we can't know what the final PSInputEna 2321 // will look like, so we shouldn't do anything here and the user should take 2322 // responsibility for the correct programming. 2323 // 2324 // Otherwise, the following restrictions apply: 2325 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2326 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2327 // enabled too. 2328 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2329 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2330 CCInfo.AllocateReg(AMDGPU::VGPR0); 2331 CCInfo.AllocateReg(AMDGPU::VGPR1); 2332 Info->markPSInputAllocated(0); 2333 Info->markPSInputEnabled(0); 2334 } 2335 if (Subtarget->isAmdPalOS()) { 2336 // For isAmdPalOS, the user does not enable some bits after compilation 2337 // based on run-time states; the register values being generated here are 2338 // the final ones set in hardware. Therefore we need to apply the 2339 // workaround to PSInputAddr and PSInputEnable together. (The case where 2340 // a bit is set in PSInputAddr but not PSInputEnable is where the 2341 // frontend set up an input arg for a particular interpolation mode, but 2342 // nothing uses that input arg. Really we should have an earlier pass 2343 // that removes such an arg.) 2344 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2345 if ((PsInputBits & 0x7F) == 0 || 2346 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2347 Info->markPSInputEnabled( 2348 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2349 } 2350 } else if (IsKernel) { 2351 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2352 } else { 2353 Splits.append(Ins.begin(), Ins.end()); 2354 } 2355 2356 if (IsEntryFunc) { 2357 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2358 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2359 } else if (!IsGraphics) { 2360 // For the fixed ABI, pass workitem IDs in the last argument register. 2361 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2362 } 2363 2364 if (IsKernel) { 2365 analyzeFormalArgumentsCompute(CCInfo, Ins); 2366 } else { 2367 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2368 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2369 } 2370 2371 SmallVector<SDValue, 16> Chains; 2372 2373 // FIXME: This is the minimum kernel argument alignment. We should improve 2374 // this to the maximum alignment of the arguments. 2375 // 2376 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2377 // kern arg offset. 2378 const Align KernelArgBaseAlign = Align(16); 2379 2380 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2381 const ISD::InputArg &Arg = Ins[i]; 2382 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2383 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2384 continue; 2385 } 2386 2387 CCValAssign &VA = ArgLocs[ArgIdx++]; 2388 MVT VT = VA.getLocVT(); 2389 2390 if (IsEntryFunc && VA.isMemLoc()) { 2391 VT = Ins[i].VT; 2392 EVT MemVT = VA.getLocVT(); 2393 2394 const uint64_t Offset = VA.getLocMemOffset(); 2395 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2396 2397 if (Arg.Flags.isByRef()) { 2398 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2399 2400 const GCNTargetMachine &TM = 2401 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2402 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2403 Arg.Flags.getPointerAddrSpace())) { 2404 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2405 Arg.Flags.getPointerAddrSpace()); 2406 } 2407 2408 InVals.push_back(Ptr); 2409 continue; 2410 } 2411 2412 SDValue Arg = lowerKernargMemParameter( 2413 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2414 Chains.push_back(Arg.getValue(1)); 2415 2416 auto *ParamTy = 2417 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2418 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2419 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2420 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2421 // On SI local pointers are just offsets into LDS, so they are always 2422 // less than 16-bits. On CI and newer they could potentially be 2423 // real pointers, so we can't guarantee their size. 2424 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2425 DAG.getValueType(MVT::i16)); 2426 } 2427 2428 InVals.push_back(Arg); 2429 continue; 2430 } else if (!IsEntryFunc && VA.isMemLoc()) { 2431 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2432 InVals.push_back(Val); 2433 if (!Arg.Flags.isByVal()) 2434 Chains.push_back(Val.getValue(1)); 2435 continue; 2436 } 2437 2438 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2439 2440 Register Reg = VA.getLocReg(); 2441 const TargetRegisterClass *RC = nullptr; 2442 if (AMDGPU::VGPR_32RegClass.contains(Reg)) 2443 RC = &AMDGPU::VGPR_32RegClass; 2444 else if (AMDGPU::SGPR_32RegClass.contains(Reg)) 2445 RC = &AMDGPU::SGPR_32RegClass; 2446 else 2447 llvm_unreachable("Unexpected register class in LowerFormalArguments!"); 2448 EVT ValVT = VA.getValVT(); 2449 2450 Reg = MF.addLiveIn(Reg, RC); 2451 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2452 2453 if (Arg.Flags.isSRet()) { 2454 // The return object should be reasonably addressable. 2455 2456 // FIXME: This helps when the return is a real sret. If it is a 2457 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2458 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2459 unsigned NumBits 2460 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2461 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2462 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2463 } 2464 2465 // If this is an 8 or 16-bit value, it is really passed promoted 2466 // to 32 bits. Insert an assert[sz]ext to capture this, then 2467 // truncate to the right size. 2468 switch (VA.getLocInfo()) { 2469 case CCValAssign::Full: 2470 break; 2471 case CCValAssign::BCvt: 2472 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2473 break; 2474 case CCValAssign::SExt: 2475 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2476 DAG.getValueType(ValVT)); 2477 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2478 break; 2479 case CCValAssign::ZExt: 2480 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2481 DAG.getValueType(ValVT)); 2482 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2483 break; 2484 case CCValAssign::AExt: 2485 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2486 break; 2487 default: 2488 llvm_unreachable("Unknown loc info!"); 2489 } 2490 2491 InVals.push_back(Val); 2492 } 2493 2494 // Start adding system SGPRs. 2495 if (IsEntryFunc) { 2496 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2497 } else { 2498 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2499 if (!IsGraphics) 2500 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2501 } 2502 2503 auto &ArgUsageInfo = 2504 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2505 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2506 2507 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2508 Info->setBytesInStackArgArea(StackArgSize); 2509 2510 return Chains.empty() ? Chain : 2511 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2512 } 2513 2514 // TODO: If return values can't fit in registers, we should return as many as 2515 // possible in registers before passing on stack. 2516 bool SITargetLowering::CanLowerReturn( 2517 CallingConv::ID CallConv, 2518 MachineFunction &MF, bool IsVarArg, 2519 const SmallVectorImpl<ISD::OutputArg> &Outs, 2520 LLVMContext &Context) const { 2521 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2522 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2523 // for shaders. Vector types should be explicitly handled by CC. 2524 if (AMDGPU::isEntryFunctionCC(CallConv)) 2525 return true; 2526 2527 SmallVector<CCValAssign, 16> RVLocs; 2528 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2529 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2530 } 2531 2532 SDValue 2533 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2534 bool isVarArg, 2535 const SmallVectorImpl<ISD::OutputArg> &Outs, 2536 const SmallVectorImpl<SDValue> &OutVals, 2537 const SDLoc &DL, SelectionDAG &DAG) const { 2538 MachineFunction &MF = DAG.getMachineFunction(); 2539 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2540 2541 if (AMDGPU::isKernel(CallConv)) { 2542 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2543 OutVals, DL, DAG); 2544 } 2545 2546 bool IsShader = AMDGPU::isShader(CallConv); 2547 2548 Info->setIfReturnsVoid(Outs.empty()); 2549 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2550 2551 // CCValAssign - represent the assignment of the return value to a location. 2552 SmallVector<CCValAssign, 48> RVLocs; 2553 SmallVector<ISD::OutputArg, 48> Splits; 2554 2555 // CCState - Info about the registers and stack slots. 2556 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2557 *DAG.getContext()); 2558 2559 // Analyze outgoing return values. 2560 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2561 2562 SDValue Flag; 2563 SmallVector<SDValue, 48> RetOps; 2564 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2565 2566 // Copy the result values into the output registers. 2567 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2568 ++I, ++RealRVLocIdx) { 2569 CCValAssign &VA = RVLocs[I]; 2570 assert(VA.isRegLoc() && "Can only return in registers!"); 2571 // TODO: Partially return in registers if return values don't fit. 2572 SDValue Arg = OutVals[RealRVLocIdx]; 2573 2574 // Copied from other backends. 2575 switch (VA.getLocInfo()) { 2576 case CCValAssign::Full: 2577 break; 2578 case CCValAssign::BCvt: 2579 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2580 break; 2581 case CCValAssign::SExt: 2582 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2583 break; 2584 case CCValAssign::ZExt: 2585 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2586 break; 2587 case CCValAssign::AExt: 2588 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2589 break; 2590 default: 2591 llvm_unreachable("Unknown loc info!"); 2592 } 2593 2594 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2595 Flag = Chain.getValue(1); 2596 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2597 } 2598 2599 // FIXME: Does sret work properly? 2600 if (!Info->isEntryFunction()) { 2601 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2602 const MCPhysReg *I = 2603 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2604 if (I) { 2605 for (; *I; ++I) { 2606 if (AMDGPU::SReg_64RegClass.contains(*I)) 2607 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2608 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2609 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2610 else 2611 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2612 } 2613 } 2614 } 2615 2616 // Update chain and glue. 2617 RetOps[0] = Chain; 2618 if (Flag.getNode()) 2619 RetOps.push_back(Flag); 2620 2621 unsigned Opc = AMDGPUISD::ENDPGM; 2622 if (!IsWaveEnd) 2623 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2624 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2625 } 2626 2627 SDValue SITargetLowering::LowerCallResult( 2628 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2629 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2630 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2631 SDValue ThisVal) const { 2632 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2633 2634 // Assign locations to each value returned by this call. 2635 SmallVector<CCValAssign, 16> RVLocs; 2636 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2637 *DAG.getContext()); 2638 CCInfo.AnalyzeCallResult(Ins, RetCC); 2639 2640 // Copy all of the result registers out of their specified physreg. 2641 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2642 CCValAssign VA = RVLocs[i]; 2643 SDValue Val; 2644 2645 if (VA.isRegLoc()) { 2646 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2647 Chain = Val.getValue(1); 2648 InFlag = Val.getValue(2); 2649 } else if (VA.isMemLoc()) { 2650 report_fatal_error("TODO: return values in memory"); 2651 } else 2652 llvm_unreachable("unknown argument location type"); 2653 2654 switch (VA.getLocInfo()) { 2655 case CCValAssign::Full: 2656 break; 2657 case CCValAssign::BCvt: 2658 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2659 break; 2660 case CCValAssign::ZExt: 2661 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2662 DAG.getValueType(VA.getValVT())); 2663 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2664 break; 2665 case CCValAssign::SExt: 2666 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2667 DAG.getValueType(VA.getValVT())); 2668 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2669 break; 2670 case CCValAssign::AExt: 2671 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2672 break; 2673 default: 2674 llvm_unreachable("Unknown loc info!"); 2675 } 2676 2677 InVals.push_back(Val); 2678 } 2679 2680 return Chain; 2681 } 2682 2683 // Add code to pass special inputs required depending on used features separate 2684 // from the explicit user arguments present in the IR. 2685 void SITargetLowering::passSpecialInputs( 2686 CallLoweringInfo &CLI, 2687 CCState &CCInfo, 2688 const SIMachineFunctionInfo &Info, 2689 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2690 SmallVectorImpl<SDValue> &MemOpChains, 2691 SDValue Chain) const { 2692 // If we don't have a call site, this was a call inserted by 2693 // legalization. These can never use special inputs. 2694 if (!CLI.CB) 2695 return; 2696 2697 SelectionDAG &DAG = CLI.DAG; 2698 const SDLoc &DL = CLI.DL; 2699 const Function &F = DAG.getMachineFunction().getFunction(); 2700 2701 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2702 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2703 2704 const AMDGPUFunctionArgInfo *CalleeArgInfo 2705 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2706 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2707 auto &ArgUsageInfo = 2708 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2709 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2710 } 2711 2712 // TODO: Unify with private memory register handling. This is complicated by 2713 // the fact that at least in kernels, the input argument is not necessarily 2714 // in the same location as the input. 2715 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue, 2716 StringLiteral> ImplicitAttrs[] = { 2717 {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"}, 2718 {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" }, 2719 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"}, 2720 {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"}, 2721 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"}, 2722 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"}, 2723 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"} 2724 }; 2725 2726 for (auto Attr : ImplicitAttrs) { 2727 const ArgDescriptor *OutgoingArg; 2728 const TargetRegisterClass *ArgRC; 2729 LLT ArgTy; 2730 2731 AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first; 2732 2733 // If the callee does not use the attribute value, skip copying the value. 2734 if (CLI.CB->hasFnAttr(Attr.second)) 2735 continue; 2736 2737 std::tie(OutgoingArg, ArgRC, ArgTy) = 2738 CalleeArgInfo->getPreloadedValue(InputID); 2739 if (!OutgoingArg) 2740 continue; 2741 2742 const ArgDescriptor *IncomingArg; 2743 const TargetRegisterClass *IncomingArgRC; 2744 LLT Ty; 2745 std::tie(IncomingArg, IncomingArgRC, Ty) = 2746 CallerArgInfo.getPreloadedValue(InputID); 2747 assert(IncomingArgRC == ArgRC); 2748 2749 // All special arguments are ints for now. 2750 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2751 SDValue InputReg; 2752 2753 if (IncomingArg) { 2754 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2755 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) { 2756 // The implicit arg ptr is special because it doesn't have a corresponding 2757 // input for kernels, and is computed from the kernarg segment pointer. 2758 InputReg = getImplicitArgPtr(DAG, DL); 2759 } else { 2760 // We may have proven the input wasn't needed, although the ABI is 2761 // requiring it. We just need to allocate the register appropriately. 2762 InputReg = DAG.getUNDEF(ArgVT); 2763 } 2764 2765 if (OutgoingArg->isRegister()) { 2766 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2767 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2768 report_fatal_error("failed to allocate implicit input argument"); 2769 } else { 2770 unsigned SpecialArgOffset = 2771 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2772 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2773 SpecialArgOffset); 2774 MemOpChains.push_back(ArgStore); 2775 } 2776 } 2777 2778 // Pack workitem IDs into a single register or pass it as is if already 2779 // packed. 2780 const ArgDescriptor *OutgoingArg; 2781 const TargetRegisterClass *ArgRC; 2782 LLT Ty; 2783 2784 std::tie(OutgoingArg, ArgRC, Ty) = 2785 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2786 if (!OutgoingArg) 2787 std::tie(OutgoingArg, ArgRC, Ty) = 2788 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2789 if (!OutgoingArg) 2790 std::tie(OutgoingArg, ArgRC, Ty) = 2791 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2792 if (!OutgoingArg) 2793 return; 2794 2795 const ArgDescriptor *IncomingArgX = std::get<0>( 2796 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2797 const ArgDescriptor *IncomingArgY = std::get<0>( 2798 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2799 const ArgDescriptor *IncomingArgZ = std::get<0>( 2800 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2801 2802 SDValue InputReg; 2803 SDLoc SL; 2804 2805 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x"); 2806 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y"); 2807 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z"); 2808 2809 // If incoming ids are not packed we need to pack them. 2810 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX && 2811 NeedWorkItemIDX) { 2812 if (Subtarget->getMaxWorkitemID(F, 0) != 0) { 2813 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2814 } else { 2815 InputReg = DAG.getConstant(0, DL, MVT::i32); 2816 } 2817 } 2818 2819 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY && 2820 NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) { 2821 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2822 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2823 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2824 InputReg = InputReg.getNode() ? 2825 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2826 } 2827 2828 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ && 2829 NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) { 2830 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2831 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2832 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2833 InputReg = InputReg.getNode() ? 2834 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2835 } 2836 2837 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) { 2838 if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) { 2839 // We're in a situation where the outgoing function requires the workitem 2840 // ID, but the calling function does not have it (e.g a graphics function 2841 // calling a C calling convention function). This is illegal, but we need 2842 // to produce something. 2843 InputReg = DAG.getUNDEF(MVT::i32); 2844 } else { 2845 // Workitem ids are already packed, any of present incoming arguments 2846 // will carry all required fields. 2847 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2848 IncomingArgX ? *IncomingArgX : 2849 IncomingArgY ? *IncomingArgY : 2850 *IncomingArgZ, ~0u); 2851 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2852 } 2853 } 2854 2855 if (OutgoingArg->isRegister()) { 2856 if (InputReg) 2857 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2858 2859 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2860 } else { 2861 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2862 if (InputReg) { 2863 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2864 SpecialArgOffset); 2865 MemOpChains.push_back(ArgStore); 2866 } 2867 } 2868 } 2869 2870 static bool canGuaranteeTCO(CallingConv::ID CC) { 2871 return CC == CallingConv::Fast; 2872 } 2873 2874 /// Return true if we might ever do TCO for calls with this calling convention. 2875 static bool mayTailCallThisCC(CallingConv::ID CC) { 2876 switch (CC) { 2877 case CallingConv::C: 2878 case CallingConv::AMDGPU_Gfx: 2879 return true; 2880 default: 2881 return canGuaranteeTCO(CC); 2882 } 2883 } 2884 2885 bool SITargetLowering::isEligibleForTailCallOptimization( 2886 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2887 const SmallVectorImpl<ISD::OutputArg> &Outs, 2888 const SmallVectorImpl<SDValue> &OutVals, 2889 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2890 if (!mayTailCallThisCC(CalleeCC)) 2891 return false; 2892 2893 // For a divergent call target, we need to do a waterfall loop over the 2894 // possible callees which precludes us from using a simple jump. 2895 if (Callee->isDivergent()) 2896 return false; 2897 2898 MachineFunction &MF = DAG.getMachineFunction(); 2899 const Function &CallerF = MF.getFunction(); 2900 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2901 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2902 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2903 2904 // Kernels aren't callable, and don't have a live in return address so it 2905 // doesn't make sense to do a tail call with entry functions. 2906 if (!CallerPreserved) 2907 return false; 2908 2909 bool CCMatch = CallerCC == CalleeCC; 2910 2911 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2912 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2913 return true; 2914 return false; 2915 } 2916 2917 // TODO: Can we handle var args? 2918 if (IsVarArg) 2919 return false; 2920 2921 for (const Argument &Arg : CallerF.args()) { 2922 if (Arg.hasByValAttr()) 2923 return false; 2924 } 2925 2926 LLVMContext &Ctx = *DAG.getContext(); 2927 2928 // Check that the call results are passed in the same way. 2929 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2930 CCAssignFnForCall(CalleeCC, IsVarArg), 2931 CCAssignFnForCall(CallerCC, IsVarArg))) 2932 return false; 2933 2934 // The callee has to preserve all registers the caller needs to preserve. 2935 if (!CCMatch) { 2936 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2937 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2938 return false; 2939 } 2940 2941 // Nothing more to check if the callee is taking no arguments. 2942 if (Outs.empty()) 2943 return true; 2944 2945 SmallVector<CCValAssign, 16> ArgLocs; 2946 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2947 2948 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2949 2950 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2951 // If the stack arguments for this call do not fit into our own save area then 2952 // the call cannot be made tail. 2953 // TODO: Is this really necessary? 2954 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2955 return false; 2956 2957 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2958 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2959 } 2960 2961 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2962 if (!CI->isTailCall()) 2963 return false; 2964 2965 const Function *ParentFn = CI->getParent()->getParent(); 2966 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2967 return false; 2968 return true; 2969 } 2970 2971 // The wave scratch offset register is used as the global base pointer. 2972 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2973 SmallVectorImpl<SDValue> &InVals) const { 2974 SelectionDAG &DAG = CLI.DAG; 2975 const SDLoc &DL = CLI.DL; 2976 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2977 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2978 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2979 SDValue Chain = CLI.Chain; 2980 SDValue Callee = CLI.Callee; 2981 bool &IsTailCall = CLI.IsTailCall; 2982 CallingConv::ID CallConv = CLI.CallConv; 2983 bool IsVarArg = CLI.IsVarArg; 2984 bool IsSibCall = false; 2985 bool IsThisReturn = false; 2986 MachineFunction &MF = DAG.getMachineFunction(); 2987 2988 if (Callee.isUndef() || isNullConstant(Callee)) { 2989 if (!CLI.IsTailCall) { 2990 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2991 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2992 } 2993 2994 return Chain; 2995 } 2996 2997 if (IsVarArg) { 2998 return lowerUnhandledCall(CLI, InVals, 2999 "unsupported call to variadic function "); 3000 } 3001 3002 if (!CLI.CB) 3003 report_fatal_error("unsupported libcall legalization"); 3004 3005 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 3006 return lowerUnhandledCall(CLI, InVals, 3007 "unsupported required tail call to function "); 3008 } 3009 3010 if (AMDGPU::isShader(CallConv)) { 3011 // Note the issue is with the CC of the called function, not of the call 3012 // itself. 3013 return lowerUnhandledCall(CLI, InVals, 3014 "unsupported call to a shader function "); 3015 } 3016 3017 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 3018 CallConv != CallingConv::AMDGPU_Gfx) { 3019 // Only allow calls with specific calling conventions. 3020 return lowerUnhandledCall(CLI, InVals, 3021 "unsupported calling convention for call from " 3022 "graphics shader of function "); 3023 } 3024 3025 if (IsTailCall) { 3026 IsTailCall = isEligibleForTailCallOptimization( 3027 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3028 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 3029 report_fatal_error("failed to perform tail call elimination on a call " 3030 "site marked musttail"); 3031 } 3032 3033 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3034 3035 // A sibling call is one where we're under the usual C ABI and not planning 3036 // to change that but can still do a tail call: 3037 if (!TailCallOpt && IsTailCall) 3038 IsSibCall = true; 3039 3040 if (IsTailCall) 3041 ++NumTailCalls; 3042 } 3043 3044 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3045 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3046 SmallVector<SDValue, 8> MemOpChains; 3047 3048 // Analyze operands of the call, assigning locations to each operand. 3049 SmallVector<CCValAssign, 16> ArgLocs; 3050 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3051 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3052 3053 if (CallConv != CallingConv::AMDGPU_Gfx) { 3054 // With a fixed ABI, allocate fixed registers before user arguments. 3055 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3056 } 3057 3058 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3059 3060 // Get a count of how many bytes are to be pushed on the stack. 3061 unsigned NumBytes = CCInfo.getNextStackOffset(); 3062 3063 if (IsSibCall) { 3064 // Since we're not changing the ABI to make this a tail call, the memory 3065 // operands are already available in the caller's incoming argument space. 3066 NumBytes = 0; 3067 } 3068 3069 // FPDiff is the byte offset of the call's argument area from the callee's. 3070 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3071 // by this amount for a tail call. In a sibling call it must be 0 because the 3072 // caller will deallocate the entire stack and the callee still expects its 3073 // arguments to begin at SP+0. Completely unused for non-tail calls. 3074 int32_t FPDiff = 0; 3075 MachineFrameInfo &MFI = MF.getFrameInfo(); 3076 3077 // Adjust the stack pointer for the new arguments... 3078 // These operations are automatically eliminated by the prolog/epilog pass 3079 if (!IsSibCall) { 3080 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3081 3082 if (!Subtarget->enableFlatScratch()) { 3083 SmallVector<SDValue, 4> CopyFromChains; 3084 3085 // In the HSA case, this should be an identity copy. 3086 SDValue ScratchRSrcReg 3087 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3088 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3089 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3090 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3091 } 3092 } 3093 3094 MVT PtrVT = MVT::i32; 3095 3096 // Walk the register/memloc assignments, inserting copies/loads. 3097 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3098 CCValAssign &VA = ArgLocs[i]; 3099 SDValue Arg = OutVals[i]; 3100 3101 // Promote the value if needed. 3102 switch (VA.getLocInfo()) { 3103 case CCValAssign::Full: 3104 break; 3105 case CCValAssign::BCvt: 3106 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3107 break; 3108 case CCValAssign::ZExt: 3109 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3110 break; 3111 case CCValAssign::SExt: 3112 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3113 break; 3114 case CCValAssign::AExt: 3115 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3116 break; 3117 case CCValAssign::FPExt: 3118 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3119 break; 3120 default: 3121 llvm_unreachable("Unknown loc info!"); 3122 } 3123 3124 if (VA.isRegLoc()) { 3125 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3126 } else { 3127 assert(VA.isMemLoc()); 3128 3129 SDValue DstAddr; 3130 MachinePointerInfo DstInfo; 3131 3132 unsigned LocMemOffset = VA.getLocMemOffset(); 3133 int32_t Offset = LocMemOffset; 3134 3135 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3136 MaybeAlign Alignment; 3137 3138 if (IsTailCall) { 3139 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3140 unsigned OpSize = Flags.isByVal() ? 3141 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3142 3143 // FIXME: We can have better than the minimum byval required alignment. 3144 Alignment = 3145 Flags.isByVal() 3146 ? Flags.getNonZeroByValAlign() 3147 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3148 3149 Offset = Offset + FPDiff; 3150 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3151 3152 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3153 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3154 3155 // Make sure any stack arguments overlapping with where we're storing 3156 // are loaded before this eventual operation. Otherwise they'll be 3157 // clobbered. 3158 3159 // FIXME: Why is this really necessary? This seems to just result in a 3160 // lot of code to copy the stack and write them back to the same 3161 // locations, which are supposed to be immutable? 3162 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3163 } else { 3164 // Stores to the argument stack area are relative to the stack pointer. 3165 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(), 3166 MVT::i32); 3167 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff); 3168 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3169 Alignment = 3170 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3171 } 3172 3173 if (Outs[i].Flags.isByVal()) { 3174 SDValue SizeNode = 3175 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3176 SDValue Cpy = 3177 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3178 Outs[i].Flags.getNonZeroByValAlign(), 3179 /*isVol = */ false, /*AlwaysInline = */ true, 3180 /*isTailCall = */ false, DstInfo, 3181 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3182 3183 MemOpChains.push_back(Cpy); 3184 } else { 3185 SDValue Store = 3186 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3187 MemOpChains.push_back(Store); 3188 } 3189 } 3190 } 3191 3192 if (!MemOpChains.empty()) 3193 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3194 3195 // Build a sequence of copy-to-reg nodes chained together with token chain 3196 // and flag operands which copy the outgoing args into the appropriate regs. 3197 SDValue InFlag; 3198 for (auto &RegToPass : RegsToPass) { 3199 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3200 RegToPass.second, InFlag); 3201 InFlag = Chain.getValue(1); 3202 } 3203 3204 3205 // We don't usually want to end the call-sequence here because we would tidy 3206 // the frame up *after* the call, however in the ABI-changing tail-call case 3207 // we've carefully laid out the parameters so that when sp is reset they'll be 3208 // in the correct location. 3209 if (IsTailCall && !IsSibCall) { 3210 Chain = DAG.getCALLSEQ_END(Chain, 3211 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3212 DAG.getTargetConstant(0, DL, MVT::i32), 3213 InFlag, DL); 3214 InFlag = Chain.getValue(1); 3215 } 3216 3217 std::vector<SDValue> Ops; 3218 Ops.push_back(Chain); 3219 Ops.push_back(Callee); 3220 // Add a redundant copy of the callee global which will not be legalized, as 3221 // we need direct access to the callee later. 3222 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3223 const GlobalValue *GV = GSD->getGlobal(); 3224 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3225 } else { 3226 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3227 } 3228 3229 if (IsTailCall) { 3230 // Each tail call may have to adjust the stack by a different amount, so 3231 // this information must travel along with the operation for eventual 3232 // consumption by emitEpilogue. 3233 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3234 } 3235 3236 // Add argument registers to the end of the list so that they are known live 3237 // into the call. 3238 for (auto &RegToPass : RegsToPass) { 3239 Ops.push_back(DAG.getRegister(RegToPass.first, 3240 RegToPass.second.getValueType())); 3241 } 3242 3243 // Add a register mask operand representing the call-preserved registers. 3244 3245 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3246 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3247 assert(Mask && "Missing call preserved mask for calling convention"); 3248 Ops.push_back(DAG.getRegisterMask(Mask)); 3249 3250 if (InFlag.getNode()) 3251 Ops.push_back(InFlag); 3252 3253 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3254 3255 // If we're doing a tall call, use a TC_RETURN here rather than an 3256 // actual call instruction. 3257 if (IsTailCall) { 3258 MFI.setHasTailCall(); 3259 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3260 } 3261 3262 // Returns a chain and a flag for retval copy to use. 3263 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3264 Chain = Call.getValue(0); 3265 InFlag = Call.getValue(1); 3266 3267 uint64_t CalleePopBytes = NumBytes; 3268 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3269 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3270 InFlag, DL); 3271 if (!Ins.empty()) 3272 InFlag = Chain.getValue(1); 3273 3274 // Handle result values, copying them out of physregs into vregs that we 3275 // return. 3276 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3277 InVals, IsThisReturn, 3278 IsThisReturn ? OutVals[0] : SDValue()); 3279 } 3280 3281 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3282 // except for applying the wave size scale to the increment amount. 3283 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3284 SDValue Op, SelectionDAG &DAG) const { 3285 const MachineFunction &MF = DAG.getMachineFunction(); 3286 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3287 3288 SDLoc dl(Op); 3289 EVT VT = Op.getValueType(); 3290 SDValue Tmp1 = Op; 3291 SDValue Tmp2 = Op.getValue(1); 3292 SDValue Tmp3 = Op.getOperand(2); 3293 SDValue Chain = Tmp1.getOperand(0); 3294 3295 Register SPReg = Info->getStackPtrOffsetReg(); 3296 3297 // Chain the dynamic stack allocation so that it doesn't modify the stack 3298 // pointer when other instructions are using the stack. 3299 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3300 3301 SDValue Size = Tmp2.getOperand(1); 3302 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3303 Chain = SP.getValue(1); 3304 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3305 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3306 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3307 unsigned Opc = 3308 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3309 ISD::ADD : ISD::SUB; 3310 3311 SDValue ScaledSize = DAG.getNode( 3312 ISD::SHL, dl, VT, Size, 3313 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3314 3315 Align StackAlign = TFL->getStackAlign(); 3316 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3317 if (Alignment && *Alignment > StackAlign) { 3318 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3319 DAG.getConstant(-(uint64_t)Alignment->value() 3320 << ST.getWavefrontSizeLog2(), 3321 dl, VT)); 3322 } 3323 3324 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3325 Tmp2 = DAG.getCALLSEQ_END( 3326 Chain, DAG.getIntPtrConstant(0, dl, true), 3327 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3328 3329 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3330 } 3331 3332 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3333 SelectionDAG &DAG) const { 3334 // We only handle constant sizes here to allow non-entry block, static sized 3335 // allocas. A truly dynamic value is more difficult to support because we 3336 // don't know if the size value is uniform or not. If the size isn't uniform, 3337 // we would need to do a wave reduction to get the maximum size to know how 3338 // much to increment the uniform stack pointer. 3339 SDValue Size = Op.getOperand(1); 3340 if (isa<ConstantSDNode>(Size)) 3341 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3342 3343 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3344 } 3345 3346 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3347 const MachineFunction &MF) const { 3348 Register Reg = StringSwitch<Register>(RegName) 3349 .Case("m0", AMDGPU::M0) 3350 .Case("exec", AMDGPU::EXEC) 3351 .Case("exec_lo", AMDGPU::EXEC_LO) 3352 .Case("exec_hi", AMDGPU::EXEC_HI) 3353 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3354 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3355 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3356 .Default(Register()); 3357 3358 if (Reg == AMDGPU::NoRegister) { 3359 report_fatal_error(Twine("invalid register name \"" 3360 + StringRef(RegName) + "\".")); 3361 3362 } 3363 3364 if (!Subtarget->hasFlatScrRegister() && 3365 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3366 report_fatal_error(Twine("invalid register \"" 3367 + StringRef(RegName) + "\" for subtarget.")); 3368 } 3369 3370 switch (Reg) { 3371 case AMDGPU::M0: 3372 case AMDGPU::EXEC_LO: 3373 case AMDGPU::EXEC_HI: 3374 case AMDGPU::FLAT_SCR_LO: 3375 case AMDGPU::FLAT_SCR_HI: 3376 if (VT.getSizeInBits() == 32) 3377 return Reg; 3378 break; 3379 case AMDGPU::EXEC: 3380 case AMDGPU::FLAT_SCR: 3381 if (VT.getSizeInBits() == 64) 3382 return Reg; 3383 break; 3384 default: 3385 llvm_unreachable("missing register type checking"); 3386 } 3387 3388 report_fatal_error(Twine("invalid type for register \"" 3389 + StringRef(RegName) + "\".")); 3390 } 3391 3392 // If kill is not the last instruction, split the block so kill is always a 3393 // proper terminator. 3394 MachineBasicBlock * 3395 SITargetLowering::splitKillBlock(MachineInstr &MI, 3396 MachineBasicBlock *BB) const { 3397 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3398 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3399 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3400 return SplitBB; 3401 } 3402 3403 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3404 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3405 // be the first instruction in the remainder block. 3406 // 3407 /// \returns { LoopBody, Remainder } 3408 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3409 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3410 MachineFunction *MF = MBB.getParent(); 3411 MachineBasicBlock::iterator I(&MI); 3412 3413 // To insert the loop we need to split the block. Move everything after this 3414 // point to a new block, and insert a new empty block between the two. 3415 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3416 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3417 MachineFunction::iterator MBBI(MBB); 3418 ++MBBI; 3419 3420 MF->insert(MBBI, LoopBB); 3421 MF->insert(MBBI, RemainderBB); 3422 3423 LoopBB->addSuccessor(LoopBB); 3424 LoopBB->addSuccessor(RemainderBB); 3425 3426 // Move the rest of the block into a new block. 3427 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3428 3429 if (InstInLoop) { 3430 auto Next = std::next(I); 3431 3432 // Move instruction to loop body. 3433 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3434 3435 // Move the rest of the block. 3436 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3437 } else { 3438 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3439 } 3440 3441 MBB.addSuccessor(LoopBB); 3442 3443 return std::make_pair(LoopBB, RemainderBB); 3444 } 3445 3446 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3447 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3448 MachineBasicBlock *MBB = MI.getParent(); 3449 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3450 auto I = MI.getIterator(); 3451 auto E = std::next(I); 3452 3453 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3454 .addImm(0); 3455 3456 MIBundleBuilder Bundler(*MBB, I, E); 3457 finalizeBundle(*MBB, Bundler.begin()); 3458 } 3459 3460 MachineBasicBlock * 3461 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3462 MachineBasicBlock *BB) const { 3463 const DebugLoc &DL = MI.getDebugLoc(); 3464 3465 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3466 3467 MachineBasicBlock *LoopBB; 3468 MachineBasicBlock *RemainderBB; 3469 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3470 3471 // Apparently kill flags are only valid if the def is in the same block? 3472 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3473 Src->setIsKill(false); 3474 3475 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3476 3477 MachineBasicBlock::iterator I = LoopBB->end(); 3478 3479 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3480 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3481 3482 // Clear TRAP_STS.MEM_VIOL 3483 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3484 .addImm(0) 3485 .addImm(EncodedReg); 3486 3487 bundleInstWithWaitcnt(MI); 3488 3489 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3490 3491 // Load and check TRAP_STS.MEM_VIOL 3492 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3493 .addImm(EncodedReg); 3494 3495 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3496 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3497 .addReg(Reg, RegState::Kill) 3498 .addImm(0); 3499 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3500 .addMBB(LoopBB); 3501 3502 return RemainderBB; 3503 } 3504 3505 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3506 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3507 // will only do one iteration. In the worst case, this will loop 64 times. 3508 // 3509 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3510 static MachineBasicBlock::iterator 3511 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3512 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3513 const DebugLoc &DL, const MachineOperand &Idx, 3514 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3515 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3516 Register &SGPRIdxReg) { 3517 3518 MachineFunction *MF = OrigBB.getParent(); 3519 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3520 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3521 MachineBasicBlock::iterator I = LoopBB.begin(); 3522 3523 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3524 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3525 Register NewExec = MRI.createVirtualRegister(BoolRC); 3526 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3527 Register CondReg = MRI.createVirtualRegister(BoolRC); 3528 3529 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3530 .addReg(InitReg) 3531 .addMBB(&OrigBB) 3532 .addReg(ResultReg) 3533 .addMBB(&LoopBB); 3534 3535 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3536 .addReg(InitSaveExecReg) 3537 .addMBB(&OrigBB) 3538 .addReg(NewExec) 3539 .addMBB(&LoopBB); 3540 3541 // Read the next variant <- also loop target. 3542 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3543 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3544 3545 // Compare the just read M0 value to all possible Idx values. 3546 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3547 .addReg(CurrentIdxReg) 3548 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3549 3550 // Update EXEC, save the original EXEC value to VCC. 3551 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3552 : AMDGPU::S_AND_SAVEEXEC_B64), 3553 NewExec) 3554 .addReg(CondReg, RegState::Kill); 3555 3556 MRI.setSimpleHint(NewExec, CondReg); 3557 3558 if (UseGPRIdxMode) { 3559 if (Offset == 0) { 3560 SGPRIdxReg = CurrentIdxReg; 3561 } else { 3562 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3563 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3564 .addReg(CurrentIdxReg, RegState::Kill) 3565 .addImm(Offset); 3566 } 3567 } else { 3568 // Move index from VCC into M0 3569 if (Offset == 0) { 3570 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3571 .addReg(CurrentIdxReg, RegState::Kill); 3572 } else { 3573 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3574 .addReg(CurrentIdxReg, RegState::Kill) 3575 .addImm(Offset); 3576 } 3577 } 3578 3579 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3580 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3581 MachineInstr *InsertPt = 3582 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3583 : AMDGPU::S_XOR_B64_term), Exec) 3584 .addReg(Exec) 3585 .addReg(NewExec); 3586 3587 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3588 // s_cbranch_scc0? 3589 3590 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3591 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3592 .addMBB(&LoopBB); 3593 3594 return InsertPt->getIterator(); 3595 } 3596 3597 // This has slightly sub-optimal regalloc when the source vector is killed by 3598 // the read. The register allocator does not understand that the kill is 3599 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3600 // subregister from it, using 1 more VGPR than necessary. This was saved when 3601 // this was expanded after register allocation. 3602 static MachineBasicBlock::iterator 3603 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3604 unsigned InitResultReg, unsigned PhiReg, int Offset, 3605 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3606 MachineFunction *MF = MBB.getParent(); 3607 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3608 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3609 MachineRegisterInfo &MRI = MF->getRegInfo(); 3610 const DebugLoc &DL = MI.getDebugLoc(); 3611 MachineBasicBlock::iterator I(&MI); 3612 3613 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3614 Register DstReg = MI.getOperand(0).getReg(); 3615 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3616 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3617 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3618 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3619 3620 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3621 3622 // Save the EXEC mask 3623 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3624 .addReg(Exec); 3625 3626 MachineBasicBlock *LoopBB; 3627 MachineBasicBlock *RemainderBB; 3628 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3629 3630 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3631 3632 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3633 InitResultReg, DstReg, PhiReg, TmpExec, 3634 Offset, UseGPRIdxMode, SGPRIdxReg); 3635 3636 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3637 MachineFunction::iterator MBBI(LoopBB); 3638 ++MBBI; 3639 MF->insert(MBBI, LandingPad); 3640 LoopBB->removeSuccessor(RemainderBB); 3641 LandingPad->addSuccessor(RemainderBB); 3642 LoopBB->addSuccessor(LandingPad); 3643 MachineBasicBlock::iterator First = LandingPad->begin(); 3644 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3645 .addReg(SaveExec); 3646 3647 return InsPt; 3648 } 3649 3650 // Returns subreg index, offset 3651 static std::pair<unsigned, int> 3652 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3653 const TargetRegisterClass *SuperRC, 3654 unsigned VecReg, 3655 int Offset) { 3656 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3657 3658 // Skip out of bounds offsets, or else we would end up using an undefined 3659 // register. 3660 if (Offset >= NumElts || Offset < 0) 3661 return std::make_pair(AMDGPU::sub0, Offset); 3662 3663 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3664 } 3665 3666 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3667 MachineRegisterInfo &MRI, MachineInstr &MI, 3668 int Offset) { 3669 MachineBasicBlock *MBB = MI.getParent(); 3670 const DebugLoc &DL = MI.getDebugLoc(); 3671 MachineBasicBlock::iterator I(&MI); 3672 3673 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3674 3675 assert(Idx->getReg() != AMDGPU::NoRegister); 3676 3677 if (Offset == 0) { 3678 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3679 } else { 3680 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3681 .add(*Idx) 3682 .addImm(Offset); 3683 } 3684 } 3685 3686 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3687 MachineRegisterInfo &MRI, MachineInstr &MI, 3688 int Offset) { 3689 MachineBasicBlock *MBB = MI.getParent(); 3690 const DebugLoc &DL = MI.getDebugLoc(); 3691 MachineBasicBlock::iterator I(&MI); 3692 3693 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3694 3695 if (Offset == 0) 3696 return Idx->getReg(); 3697 3698 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3699 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3700 .add(*Idx) 3701 .addImm(Offset); 3702 return Tmp; 3703 } 3704 3705 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3706 MachineBasicBlock &MBB, 3707 const GCNSubtarget &ST) { 3708 const SIInstrInfo *TII = ST.getInstrInfo(); 3709 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3710 MachineFunction *MF = MBB.getParent(); 3711 MachineRegisterInfo &MRI = MF->getRegInfo(); 3712 3713 Register Dst = MI.getOperand(0).getReg(); 3714 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3715 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3716 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3717 3718 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3719 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3720 3721 unsigned SubReg; 3722 std::tie(SubReg, Offset) 3723 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3724 3725 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3726 3727 // Check for a SGPR index. 3728 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3729 MachineBasicBlock::iterator I(&MI); 3730 const DebugLoc &DL = MI.getDebugLoc(); 3731 3732 if (UseGPRIdxMode) { 3733 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3734 // to avoid interfering with other uses, so probably requires a new 3735 // optimization pass. 3736 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3737 3738 const MCInstrDesc &GPRIDXDesc = 3739 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3740 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3741 .addReg(SrcReg) 3742 .addReg(Idx) 3743 .addImm(SubReg); 3744 } else { 3745 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3746 3747 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3748 .addReg(SrcReg, 0, SubReg) 3749 .addReg(SrcReg, RegState::Implicit); 3750 } 3751 3752 MI.eraseFromParent(); 3753 3754 return &MBB; 3755 } 3756 3757 // Control flow needs to be inserted if indexing with a VGPR. 3758 const DebugLoc &DL = MI.getDebugLoc(); 3759 MachineBasicBlock::iterator I(&MI); 3760 3761 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3762 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3763 3764 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3765 3766 Register SGPRIdxReg; 3767 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3768 UseGPRIdxMode, SGPRIdxReg); 3769 3770 MachineBasicBlock *LoopBB = InsPt->getParent(); 3771 3772 if (UseGPRIdxMode) { 3773 const MCInstrDesc &GPRIDXDesc = 3774 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3775 3776 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3777 .addReg(SrcReg) 3778 .addReg(SGPRIdxReg) 3779 .addImm(SubReg); 3780 } else { 3781 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3782 .addReg(SrcReg, 0, SubReg) 3783 .addReg(SrcReg, RegState::Implicit); 3784 } 3785 3786 MI.eraseFromParent(); 3787 3788 return LoopBB; 3789 } 3790 3791 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3792 MachineBasicBlock &MBB, 3793 const GCNSubtarget &ST) { 3794 const SIInstrInfo *TII = ST.getInstrInfo(); 3795 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3796 MachineFunction *MF = MBB.getParent(); 3797 MachineRegisterInfo &MRI = MF->getRegInfo(); 3798 3799 Register Dst = MI.getOperand(0).getReg(); 3800 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3801 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3802 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3803 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3804 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3805 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3806 3807 // This can be an immediate, but will be folded later. 3808 assert(Val->getReg()); 3809 3810 unsigned SubReg; 3811 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3812 SrcVec->getReg(), 3813 Offset); 3814 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3815 3816 if (Idx->getReg() == AMDGPU::NoRegister) { 3817 MachineBasicBlock::iterator I(&MI); 3818 const DebugLoc &DL = MI.getDebugLoc(); 3819 3820 assert(Offset == 0); 3821 3822 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3823 .add(*SrcVec) 3824 .add(*Val) 3825 .addImm(SubReg); 3826 3827 MI.eraseFromParent(); 3828 return &MBB; 3829 } 3830 3831 // Check for a SGPR index. 3832 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3833 MachineBasicBlock::iterator I(&MI); 3834 const DebugLoc &DL = MI.getDebugLoc(); 3835 3836 if (UseGPRIdxMode) { 3837 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3838 3839 const MCInstrDesc &GPRIDXDesc = 3840 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3841 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3842 .addReg(SrcVec->getReg()) 3843 .add(*Val) 3844 .addReg(Idx) 3845 .addImm(SubReg); 3846 } else { 3847 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3848 3849 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3850 TRI.getRegSizeInBits(*VecRC), 32, false); 3851 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3852 .addReg(SrcVec->getReg()) 3853 .add(*Val) 3854 .addImm(SubReg); 3855 } 3856 MI.eraseFromParent(); 3857 return &MBB; 3858 } 3859 3860 // Control flow needs to be inserted if indexing with a VGPR. 3861 if (Val->isReg()) 3862 MRI.clearKillFlags(Val->getReg()); 3863 3864 const DebugLoc &DL = MI.getDebugLoc(); 3865 3866 Register PhiReg = MRI.createVirtualRegister(VecRC); 3867 3868 Register SGPRIdxReg; 3869 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3870 UseGPRIdxMode, SGPRIdxReg); 3871 MachineBasicBlock *LoopBB = InsPt->getParent(); 3872 3873 if (UseGPRIdxMode) { 3874 const MCInstrDesc &GPRIDXDesc = 3875 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3876 3877 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3878 .addReg(PhiReg) 3879 .add(*Val) 3880 .addReg(SGPRIdxReg) 3881 .addImm(AMDGPU::sub0); 3882 } else { 3883 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3884 TRI.getRegSizeInBits(*VecRC), 32, false); 3885 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3886 .addReg(PhiReg) 3887 .add(*Val) 3888 .addImm(AMDGPU::sub0); 3889 } 3890 3891 MI.eraseFromParent(); 3892 return LoopBB; 3893 } 3894 3895 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3896 MachineInstr &MI, MachineBasicBlock *BB) const { 3897 3898 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3899 MachineFunction *MF = BB->getParent(); 3900 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3901 3902 switch (MI.getOpcode()) { 3903 case AMDGPU::S_UADDO_PSEUDO: 3904 case AMDGPU::S_USUBO_PSEUDO: { 3905 const DebugLoc &DL = MI.getDebugLoc(); 3906 MachineOperand &Dest0 = MI.getOperand(0); 3907 MachineOperand &Dest1 = MI.getOperand(1); 3908 MachineOperand &Src0 = MI.getOperand(2); 3909 MachineOperand &Src1 = MI.getOperand(3); 3910 3911 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3912 ? AMDGPU::S_ADD_I32 3913 : AMDGPU::S_SUB_I32; 3914 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3915 3916 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3917 .addImm(1) 3918 .addImm(0); 3919 3920 MI.eraseFromParent(); 3921 return BB; 3922 } 3923 case AMDGPU::S_ADD_U64_PSEUDO: 3924 case AMDGPU::S_SUB_U64_PSEUDO: { 3925 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3926 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3927 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3928 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3929 const DebugLoc &DL = MI.getDebugLoc(); 3930 3931 MachineOperand &Dest = MI.getOperand(0); 3932 MachineOperand &Src0 = MI.getOperand(1); 3933 MachineOperand &Src1 = MI.getOperand(2); 3934 3935 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3936 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3937 3938 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3939 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3940 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3941 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3942 3943 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3944 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3945 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3946 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3947 3948 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3949 3950 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3951 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3952 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3953 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3954 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3955 .addReg(DestSub0) 3956 .addImm(AMDGPU::sub0) 3957 .addReg(DestSub1) 3958 .addImm(AMDGPU::sub1); 3959 MI.eraseFromParent(); 3960 return BB; 3961 } 3962 case AMDGPU::V_ADD_U64_PSEUDO: 3963 case AMDGPU::V_SUB_U64_PSEUDO: { 3964 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3965 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3966 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3967 const DebugLoc &DL = MI.getDebugLoc(); 3968 3969 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3970 3971 MachineOperand &Dest = MI.getOperand(0); 3972 MachineOperand &Src0 = MI.getOperand(1); 3973 MachineOperand &Src1 = MI.getOperand(2); 3974 3975 if (IsAdd && ST.hasLshlAddB64()) { 3976 auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64), 3977 Dest.getReg()) 3978 .add(Src0) 3979 .addImm(0) 3980 .add(Src1); 3981 TII->legalizeOperands(*Add); 3982 MI.eraseFromParent(); 3983 return BB; 3984 } 3985 3986 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3987 3988 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3989 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3990 3991 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3992 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3993 3994 const TargetRegisterClass *Src0RC = Src0.isReg() 3995 ? MRI.getRegClass(Src0.getReg()) 3996 : &AMDGPU::VReg_64RegClass; 3997 const TargetRegisterClass *Src1RC = Src1.isReg() 3998 ? MRI.getRegClass(Src1.getReg()) 3999 : &AMDGPU::VReg_64RegClass; 4000 4001 const TargetRegisterClass *Src0SubRC = 4002 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 4003 const TargetRegisterClass *Src1SubRC = 4004 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 4005 4006 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 4007 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 4008 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 4009 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 4010 4011 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 4012 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 4013 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 4014 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 4015 4016 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 4017 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 4018 .addReg(CarryReg, RegState::Define) 4019 .add(SrcReg0Sub0) 4020 .add(SrcReg1Sub0) 4021 .addImm(0); // clamp bit 4022 4023 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 4024 MachineInstr *HiHalf = 4025 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 4026 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 4027 .add(SrcReg0Sub1) 4028 .add(SrcReg1Sub1) 4029 .addReg(CarryReg, RegState::Kill) 4030 .addImm(0); // clamp bit 4031 4032 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4033 .addReg(DestSub0) 4034 .addImm(AMDGPU::sub0) 4035 .addReg(DestSub1) 4036 .addImm(AMDGPU::sub1); 4037 TII->legalizeOperands(*LoHalf); 4038 TII->legalizeOperands(*HiHalf); 4039 MI.eraseFromParent(); 4040 return BB; 4041 } 4042 case AMDGPU::S_ADD_CO_PSEUDO: 4043 case AMDGPU::S_SUB_CO_PSEUDO: { 4044 // This pseudo has a chance to be selected 4045 // only from uniform add/subcarry node. All the VGPR operands 4046 // therefore assumed to be splat vectors. 4047 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4048 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4049 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4050 MachineBasicBlock::iterator MII = MI; 4051 const DebugLoc &DL = MI.getDebugLoc(); 4052 MachineOperand &Dest = MI.getOperand(0); 4053 MachineOperand &CarryDest = MI.getOperand(1); 4054 MachineOperand &Src0 = MI.getOperand(2); 4055 MachineOperand &Src1 = MI.getOperand(3); 4056 MachineOperand &Src2 = MI.getOperand(4); 4057 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4058 ? AMDGPU::S_ADDC_U32 4059 : AMDGPU::S_SUBB_U32; 4060 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4061 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4062 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4063 .addReg(Src0.getReg()); 4064 Src0.setReg(RegOp0); 4065 } 4066 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4067 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4068 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4069 .addReg(Src1.getReg()); 4070 Src1.setReg(RegOp1); 4071 } 4072 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4073 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4074 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4075 .addReg(Src2.getReg()); 4076 Src2.setReg(RegOp2); 4077 } 4078 4079 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4080 unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC); 4081 assert(WaveSize == 64 || WaveSize == 32); 4082 4083 if (WaveSize == 64) { 4084 if (ST.hasScalarCompareEq64()) { 4085 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4086 .addReg(Src2.getReg()) 4087 .addImm(0); 4088 } else { 4089 const TargetRegisterClass *SubRC = 4090 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4091 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4092 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4093 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4094 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4095 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4096 4097 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4098 .add(Src2Sub0) 4099 .add(Src2Sub1); 4100 4101 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4102 .addReg(Src2_32, RegState::Kill) 4103 .addImm(0); 4104 } 4105 } else { 4106 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4107 .addReg(Src2.getReg()) 4108 .addImm(0); 4109 } 4110 4111 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4112 4113 unsigned SelOpc = 4114 (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32; 4115 4116 BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg()) 4117 .addImm(-1) 4118 .addImm(0); 4119 4120 MI.eraseFromParent(); 4121 return BB; 4122 } 4123 case AMDGPU::SI_INIT_M0: { 4124 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4125 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4126 .add(MI.getOperand(0)); 4127 MI.eraseFromParent(); 4128 return BB; 4129 } 4130 case AMDGPU::GET_GROUPSTATICSIZE: { 4131 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4132 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4133 DebugLoc DL = MI.getDebugLoc(); 4134 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4135 .add(MI.getOperand(0)) 4136 .addImm(MFI->getLDSSize()); 4137 MI.eraseFromParent(); 4138 return BB; 4139 } 4140 case AMDGPU::SI_INDIRECT_SRC_V1: 4141 case AMDGPU::SI_INDIRECT_SRC_V2: 4142 case AMDGPU::SI_INDIRECT_SRC_V4: 4143 case AMDGPU::SI_INDIRECT_SRC_V8: 4144 case AMDGPU::SI_INDIRECT_SRC_V16: 4145 case AMDGPU::SI_INDIRECT_SRC_V32: 4146 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4147 case AMDGPU::SI_INDIRECT_DST_V1: 4148 case AMDGPU::SI_INDIRECT_DST_V2: 4149 case AMDGPU::SI_INDIRECT_DST_V4: 4150 case AMDGPU::SI_INDIRECT_DST_V8: 4151 case AMDGPU::SI_INDIRECT_DST_V16: 4152 case AMDGPU::SI_INDIRECT_DST_V32: 4153 return emitIndirectDst(MI, *BB, *getSubtarget()); 4154 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4155 case AMDGPU::SI_KILL_I1_PSEUDO: 4156 return splitKillBlock(MI, BB); 4157 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4158 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4159 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4160 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4161 4162 Register Dst = MI.getOperand(0).getReg(); 4163 Register Src0 = MI.getOperand(1).getReg(); 4164 Register Src1 = MI.getOperand(2).getReg(); 4165 const DebugLoc &DL = MI.getDebugLoc(); 4166 Register SrcCond = MI.getOperand(3).getReg(); 4167 4168 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4169 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4170 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4171 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4172 4173 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4174 .addReg(SrcCond); 4175 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4176 .addImm(0) 4177 .addReg(Src0, 0, AMDGPU::sub0) 4178 .addImm(0) 4179 .addReg(Src1, 0, AMDGPU::sub0) 4180 .addReg(SrcCondCopy); 4181 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4182 .addImm(0) 4183 .addReg(Src0, 0, AMDGPU::sub1) 4184 .addImm(0) 4185 .addReg(Src1, 0, AMDGPU::sub1) 4186 .addReg(SrcCondCopy); 4187 4188 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4189 .addReg(DstLo) 4190 .addImm(AMDGPU::sub0) 4191 .addReg(DstHi) 4192 .addImm(AMDGPU::sub1); 4193 MI.eraseFromParent(); 4194 return BB; 4195 } 4196 case AMDGPU::SI_BR_UNDEF: { 4197 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4198 const DebugLoc &DL = MI.getDebugLoc(); 4199 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4200 .add(MI.getOperand(0)); 4201 Br->getOperand(1).setIsUndef(true); // read undef SCC 4202 MI.eraseFromParent(); 4203 return BB; 4204 } 4205 case AMDGPU::ADJCALLSTACKUP: 4206 case AMDGPU::ADJCALLSTACKDOWN: { 4207 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4208 MachineInstrBuilder MIB(*MF, &MI); 4209 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4210 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4211 return BB; 4212 } 4213 case AMDGPU::SI_CALL_ISEL: { 4214 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4215 const DebugLoc &DL = MI.getDebugLoc(); 4216 4217 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4218 4219 MachineInstrBuilder MIB; 4220 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4221 4222 for (const MachineOperand &MO : MI.operands()) 4223 MIB.add(MO); 4224 4225 MIB.cloneMemRefs(MI); 4226 MI.eraseFromParent(); 4227 return BB; 4228 } 4229 case AMDGPU::V_ADD_CO_U32_e32: 4230 case AMDGPU::V_SUB_CO_U32_e32: 4231 case AMDGPU::V_SUBREV_CO_U32_e32: { 4232 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4233 const DebugLoc &DL = MI.getDebugLoc(); 4234 unsigned Opc = MI.getOpcode(); 4235 4236 bool NeedClampOperand = false; 4237 if (TII->pseudoToMCOpcode(Opc) == -1) { 4238 Opc = AMDGPU::getVOPe64(Opc); 4239 NeedClampOperand = true; 4240 } 4241 4242 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4243 if (TII->isVOP3(*I)) { 4244 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4245 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4246 I.addReg(TRI->getVCC(), RegState::Define); 4247 } 4248 I.add(MI.getOperand(1)) 4249 .add(MI.getOperand(2)); 4250 if (NeedClampOperand) 4251 I.addImm(0); // clamp bit for e64 encoding 4252 4253 TII->legalizeOperands(*I); 4254 4255 MI.eraseFromParent(); 4256 return BB; 4257 } 4258 case AMDGPU::V_ADDC_U32_e32: 4259 case AMDGPU::V_SUBB_U32_e32: 4260 case AMDGPU::V_SUBBREV_U32_e32: 4261 // These instructions have an implicit use of vcc which counts towards the 4262 // constant bus limit. 4263 TII->legalizeOperands(MI); 4264 return BB; 4265 case AMDGPU::DS_GWS_INIT: 4266 case AMDGPU::DS_GWS_SEMA_BR: 4267 case AMDGPU::DS_GWS_BARRIER: 4268 TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::data0); 4269 LLVM_FALLTHROUGH; 4270 case AMDGPU::DS_GWS_SEMA_V: 4271 case AMDGPU::DS_GWS_SEMA_P: 4272 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4273 // A s_waitcnt 0 is required to be the instruction immediately following. 4274 if (getSubtarget()->hasGWSAutoReplay()) { 4275 bundleInstWithWaitcnt(MI); 4276 return BB; 4277 } 4278 4279 return emitGWSMemViolTestLoop(MI, BB); 4280 case AMDGPU::S_SETREG_B32: { 4281 // Try to optimize cases that only set the denormal mode or rounding mode. 4282 // 4283 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4284 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4285 // instead. 4286 // 4287 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4288 // allow you to have a no side effect instruction in the output of a 4289 // sideeffecting pattern. 4290 unsigned ID, Offset, Width; 4291 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4292 if (ID != AMDGPU::Hwreg::ID_MODE) 4293 return BB; 4294 4295 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4296 const unsigned SetMask = WidthMask << Offset; 4297 4298 if (getSubtarget()->hasDenormModeInst()) { 4299 unsigned SetDenormOp = 0; 4300 unsigned SetRoundOp = 0; 4301 4302 // The dedicated instructions can only set the whole denorm or round mode 4303 // at once, not a subset of bits in either. 4304 if (SetMask == 4305 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4306 // If this fully sets both the round and denorm mode, emit the two 4307 // dedicated instructions for these. 4308 SetRoundOp = AMDGPU::S_ROUND_MODE; 4309 SetDenormOp = AMDGPU::S_DENORM_MODE; 4310 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4311 SetRoundOp = AMDGPU::S_ROUND_MODE; 4312 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4313 SetDenormOp = AMDGPU::S_DENORM_MODE; 4314 } 4315 4316 if (SetRoundOp || SetDenormOp) { 4317 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4318 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4319 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4320 unsigned ImmVal = Def->getOperand(1).getImm(); 4321 if (SetRoundOp) { 4322 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4323 .addImm(ImmVal & 0xf); 4324 4325 // If we also have the denorm mode, get just the denorm mode bits. 4326 ImmVal >>= 4; 4327 } 4328 4329 if (SetDenormOp) { 4330 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4331 .addImm(ImmVal & 0xf); 4332 } 4333 4334 MI.eraseFromParent(); 4335 return BB; 4336 } 4337 } 4338 } 4339 4340 // If only FP bits are touched, used the no side effects pseudo. 4341 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4342 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4343 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4344 4345 return BB; 4346 } 4347 default: 4348 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4349 } 4350 } 4351 4352 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4353 return isTypeLegal(VT.getScalarType()); 4354 } 4355 4356 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4357 // This currently forces unfolding various combinations of fsub into fma with 4358 // free fneg'd operands. As long as we have fast FMA (controlled by 4359 // isFMAFasterThanFMulAndFAdd), we should perform these. 4360 4361 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4362 // most of these combines appear to be cycle neutral but save on instruction 4363 // count / code size. 4364 return true; 4365 } 4366 4367 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; } 4368 4369 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4370 EVT VT) const { 4371 if (!VT.isVector()) { 4372 return MVT::i1; 4373 } 4374 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4375 } 4376 4377 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4378 // TODO: Should i16 be used always if legal? For now it would force VALU 4379 // shifts. 4380 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4381 } 4382 4383 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4384 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4385 ? Ty.changeElementSize(16) 4386 : Ty.changeElementSize(32); 4387 } 4388 4389 // Answering this is somewhat tricky and depends on the specific device which 4390 // have different rates for fma or all f64 operations. 4391 // 4392 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4393 // regardless of which device (although the number of cycles differs between 4394 // devices), so it is always profitable for f64. 4395 // 4396 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4397 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4398 // which we can always do even without fused FP ops since it returns the same 4399 // result as the separate operations and since it is always full 4400 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4401 // however does not support denormals, so we do report fma as faster if we have 4402 // a fast fma device and require denormals. 4403 // 4404 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4405 EVT VT) const { 4406 VT = VT.getScalarType(); 4407 4408 switch (VT.getSimpleVT().SimpleTy) { 4409 case MVT::f32: { 4410 // If mad is not available this depends only on if f32 fma is full rate. 4411 if (!Subtarget->hasMadMacF32Insts()) 4412 return Subtarget->hasFastFMAF32(); 4413 4414 // Otherwise f32 mad is always full rate and returns the same result as 4415 // the separate operations so should be preferred over fma. 4416 // However does not support denormals. 4417 if (hasFP32Denormals(MF)) 4418 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4419 4420 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4421 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4422 } 4423 case MVT::f64: 4424 return true; 4425 case MVT::f16: 4426 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4427 default: 4428 break; 4429 } 4430 4431 return false; 4432 } 4433 4434 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4435 LLT Ty) const { 4436 switch (Ty.getScalarSizeInBits()) { 4437 case 16: 4438 return isFMAFasterThanFMulAndFAdd(MF, MVT::f16); 4439 case 32: 4440 return isFMAFasterThanFMulAndFAdd(MF, MVT::f32); 4441 case 64: 4442 return isFMAFasterThanFMulAndFAdd(MF, MVT::f64); 4443 default: 4444 break; 4445 } 4446 4447 return false; 4448 } 4449 4450 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const { 4451 if (!Ty.isScalar()) 4452 return false; 4453 4454 if (Ty.getScalarSizeInBits() == 16) 4455 return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF()); 4456 if (Ty.getScalarSizeInBits() == 32) 4457 return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF()); 4458 4459 return false; 4460 } 4461 4462 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4463 const SDNode *N) const { 4464 // TODO: Check future ftz flag 4465 // v_mad_f32/v_mac_f32 do not support denormals. 4466 EVT VT = N->getValueType(0); 4467 if (VT == MVT::f32) 4468 return Subtarget->hasMadMacF32Insts() && 4469 !hasFP32Denormals(DAG.getMachineFunction()); 4470 if (VT == MVT::f16) { 4471 return Subtarget->hasMadF16() && 4472 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4473 } 4474 4475 return false; 4476 } 4477 4478 //===----------------------------------------------------------------------===// 4479 // Custom DAG Lowering Operations 4480 //===----------------------------------------------------------------------===// 4481 4482 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4483 // wider vector type is legal. 4484 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4485 SelectionDAG &DAG) const { 4486 unsigned Opc = Op.getOpcode(); 4487 EVT VT = Op.getValueType(); 4488 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4489 4490 SDValue Lo, Hi; 4491 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4492 4493 SDLoc SL(Op); 4494 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4495 Op->getFlags()); 4496 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4497 Op->getFlags()); 4498 4499 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4500 } 4501 4502 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4503 // wider vector type is legal. 4504 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4505 SelectionDAG &DAG) const { 4506 unsigned Opc = Op.getOpcode(); 4507 EVT VT = Op.getValueType(); 4508 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4509 VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 || 4510 VT == MVT::v16f32 || VT == MVT::v32f32); 4511 4512 SDValue Lo0, Hi0; 4513 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4514 SDValue Lo1, Hi1; 4515 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4516 4517 SDLoc SL(Op); 4518 4519 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4520 Op->getFlags()); 4521 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4522 Op->getFlags()); 4523 4524 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4525 } 4526 4527 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4528 SelectionDAG &DAG) const { 4529 unsigned Opc = Op.getOpcode(); 4530 EVT VT = Op.getValueType(); 4531 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 || 4532 VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 || 4533 VT == MVT::v16f32 || VT == MVT::v32f32); 4534 4535 SDValue Lo0, Hi0; 4536 SDValue Op0 = Op.getOperand(0); 4537 std::tie(Lo0, Hi0) = Op0.getValueType().isVector() 4538 ? DAG.SplitVectorOperand(Op.getNode(), 0) 4539 : std::make_pair(Op0, Op0); 4540 SDValue Lo1, Hi1; 4541 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4542 SDValue Lo2, Hi2; 4543 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4544 4545 SDLoc SL(Op); 4546 auto ResVT = DAG.GetSplitDestVTs(VT); 4547 4548 SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2, 4549 Op->getFlags()); 4550 SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2, 4551 Op->getFlags()); 4552 4553 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4554 } 4555 4556 4557 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4558 switch (Op.getOpcode()) { 4559 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4560 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4561 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4562 case ISD::LOAD: { 4563 SDValue Result = LowerLOAD(Op, DAG); 4564 assert((!Result.getNode() || 4565 Result.getNode()->getNumValues() == 2) && 4566 "Load should return a value and a chain"); 4567 return Result; 4568 } 4569 4570 case ISD::FSIN: 4571 case ISD::FCOS: 4572 return LowerTrig(Op, DAG); 4573 case ISD::SELECT: return LowerSELECT(Op, DAG); 4574 case ISD::FDIV: return LowerFDIV(Op, DAG); 4575 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4576 case ISD::STORE: return LowerSTORE(Op, DAG); 4577 case ISD::GlobalAddress: { 4578 MachineFunction &MF = DAG.getMachineFunction(); 4579 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4580 return LowerGlobalAddress(MFI, Op, DAG); 4581 } 4582 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4583 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4584 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4585 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4586 case ISD::INSERT_SUBVECTOR: 4587 return lowerINSERT_SUBVECTOR(Op, DAG); 4588 case ISD::INSERT_VECTOR_ELT: 4589 return lowerINSERT_VECTOR_ELT(Op, DAG); 4590 case ISD::EXTRACT_VECTOR_ELT: 4591 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4592 case ISD::VECTOR_SHUFFLE: 4593 return lowerVECTOR_SHUFFLE(Op, DAG); 4594 case ISD::SCALAR_TO_VECTOR: 4595 return lowerSCALAR_TO_VECTOR(Op, DAG); 4596 case ISD::BUILD_VECTOR: 4597 return lowerBUILD_VECTOR(Op, DAG); 4598 case ISD::FP_ROUND: 4599 return lowerFP_ROUND(Op, DAG); 4600 case ISD::FPTRUNC_ROUND: { 4601 unsigned Opc; 4602 SDLoc DL(Op); 4603 4604 if (Op.getOperand(0)->getValueType(0) != MVT::f32) 4605 return SDValue(); 4606 4607 // Get the rounding mode from the last operand 4608 int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4609 if (RoundMode == (int)RoundingMode::TowardPositive) 4610 Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD; 4611 else if (RoundMode == (int)RoundingMode::TowardNegative) 4612 Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD; 4613 else 4614 return SDValue(); 4615 4616 return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0)); 4617 } 4618 case ISD::TRAP: 4619 return lowerTRAP(Op, DAG); 4620 case ISD::DEBUGTRAP: 4621 return lowerDEBUGTRAP(Op, DAG); 4622 case ISD::FABS: 4623 case ISD::FNEG: 4624 case ISD::FCANONICALIZE: 4625 case ISD::BSWAP: 4626 return splitUnaryVectorOp(Op, DAG); 4627 case ISD::FMINNUM: 4628 case ISD::FMAXNUM: 4629 return lowerFMINNUM_FMAXNUM(Op, DAG); 4630 case ISD::FMA: 4631 return splitTernaryVectorOp(Op, DAG); 4632 case ISD::FP_TO_SINT: 4633 case ISD::FP_TO_UINT: 4634 return LowerFP_TO_INT(Op, DAG); 4635 case ISD::SHL: 4636 case ISD::SRA: 4637 case ISD::SRL: 4638 case ISD::ADD: 4639 case ISD::SUB: 4640 case ISD::MUL: 4641 case ISD::SMIN: 4642 case ISD::SMAX: 4643 case ISD::UMIN: 4644 case ISD::UMAX: 4645 case ISD::FADD: 4646 case ISD::FMUL: 4647 case ISD::FMINNUM_IEEE: 4648 case ISD::FMAXNUM_IEEE: 4649 case ISD::UADDSAT: 4650 case ISD::USUBSAT: 4651 case ISD::SADDSAT: 4652 case ISD::SSUBSAT: 4653 return splitBinaryVectorOp(Op, DAG); 4654 case ISD::SMULO: 4655 case ISD::UMULO: 4656 return lowerXMULO(Op, DAG); 4657 case ISD::SMUL_LOHI: 4658 case ISD::UMUL_LOHI: 4659 return lowerXMUL_LOHI(Op, DAG); 4660 case ISD::DYNAMIC_STACKALLOC: 4661 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4662 } 4663 return SDValue(); 4664 } 4665 4666 // Used for D16: Casts the result of an instruction into the right vector, 4667 // packs values if loads return unpacked values. 4668 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4669 const SDLoc &DL, 4670 SelectionDAG &DAG, bool Unpacked) { 4671 if (!LoadVT.isVector()) 4672 return Result; 4673 4674 // Cast back to the original packed type or to a larger type that is a 4675 // multiple of 32 bit for D16. Widening the return type is a required for 4676 // legalization. 4677 EVT FittingLoadVT = LoadVT; 4678 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4679 FittingLoadVT = 4680 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4681 LoadVT.getVectorNumElements() + 1); 4682 } 4683 4684 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4685 // Truncate to v2i16/v4i16. 4686 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4687 4688 // Workaround legalizer not scalarizing truncate after vector op 4689 // legalization but not creating intermediate vector trunc. 4690 SmallVector<SDValue, 4> Elts; 4691 DAG.ExtractVectorElements(Result, Elts); 4692 for (SDValue &Elt : Elts) 4693 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4694 4695 // Pad illegal v1i16/v3fi6 to v4i16 4696 if ((LoadVT.getVectorNumElements() % 2) == 1) 4697 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4698 4699 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4700 4701 // Bitcast to original type (v2f16/v4f16). 4702 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4703 } 4704 4705 // Cast back to the original packed type. 4706 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4707 } 4708 4709 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4710 MemSDNode *M, 4711 SelectionDAG &DAG, 4712 ArrayRef<SDValue> Ops, 4713 bool IsIntrinsic) const { 4714 SDLoc DL(M); 4715 4716 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4717 EVT LoadVT = M->getValueType(0); 4718 4719 EVT EquivLoadVT = LoadVT; 4720 if (LoadVT.isVector()) { 4721 if (Unpacked) { 4722 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4723 LoadVT.getVectorNumElements()); 4724 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4725 // Widen v3f16 to legal type 4726 EquivLoadVT = 4727 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4728 LoadVT.getVectorNumElements() + 1); 4729 } 4730 } 4731 4732 // Change from v4f16/v2f16 to EquivLoadVT. 4733 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4734 4735 SDValue Load 4736 = DAG.getMemIntrinsicNode( 4737 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4738 VTList, Ops, M->getMemoryVT(), 4739 M->getMemOperand()); 4740 4741 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4742 4743 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4744 } 4745 4746 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4747 SelectionDAG &DAG, 4748 ArrayRef<SDValue> Ops) const { 4749 SDLoc DL(M); 4750 EVT LoadVT = M->getValueType(0); 4751 EVT EltType = LoadVT.getScalarType(); 4752 EVT IntVT = LoadVT.changeTypeToInteger(); 4753 4754 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4755 4756 unsigned Opc = 4757 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4758 4759 if (IsD16) { 4760 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4761 } 4762 4763 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4764 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4765 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4766 4767 if (isTypeLegal(LoadVT)) { 4768 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4769 M->getMemOperand(), DAG); 4770 } 4771 4772 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4773 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4774 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4775 M->getMemOperand(), DAG); 4776 return DAG.getMergeValues( 4777 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4778 DL); 4779 } 4780 4781 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4782 SDNode *N, SelectionDAG &DAG) { 4783 EVT VT = N->getValueType(0); 4784 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4785 unsigned CondCode = CD->getZExtValue(); 4786 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4787 return DAG.getUNDEF(VT); 4788 4789 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4790 4791 SDValue LHS = N->getOperand(1); 4792 SDValue RHS = N->getOperand(2); 4793 4794 SDLoc DL(N); 4795 4796 EVT CmpVT = LHS.getValueType(); 4797 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4798 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4799 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4800 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4801 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4802 } 4803 4804 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4805 4806 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4807 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4808 4809 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4810 DAG.getCondCode(CCOpcode)); 4811 if (VT.bitsEq(CCVT)) 4812 return SetCC; 4813 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4814 } 4815 4816 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4817 SDNode *N, SelectionDAG &DAG) { 4818 EVT VT = N->getValueType(0); 4819 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4820 4821 unsigned CondCode = CD->getZExtValue(); 4822 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4823 return DAG.getUNDEF(VT); 4824 4825 SDValue Src0 = N->getOperand(1); 4826 SDValue Src1 = N->getOperand(2); 4827 EVT CmpVT = Src0.getValueType(); 4828 SDLoc SL(N); 4829 4830 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4831 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4832 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4833 } 4834 4835 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4836 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4837 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4838 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4839 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4840 Src1, DAG.getCondCode(CCOpcode)); 4841 if (VT.bitsEq(CCVT)) 4842 return SetCC; 4843 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4844 } 4845 4846 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4847 SelectionDAG &DAG) { 4848 EVT VT = N->getValueType(0); 4849 SDValue Src = N->getOperand(1); 4850 SDLoc SL(N); 4851 4852 if (Src.getOpcode() == ISD::SETCC) { 4853 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4854 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4855 Src.getOperand(1), Src.getOperand(2)); 4856 } 4857 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4858 // (ballot 0) -> 0 4859 if (Arg->isZero()) 4860 return DAG.getConstant(0, SL, VT); 4861 4862 // (ballot 1) -> EXEC/EXEC_LO 4863 if (Arg->isOne()) { 4864 Register Exec; 4865 if (VT.getScalarSizeInBits() == 32) 4866 Exec = AMDGPU::EXEC_LO; 4867 else if (VT.getScalarSizeInBits() == 64) 4868 Exec = AMDGPU::EXEC; 4869 else 4870 return SDValue(); 4871 4872 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4873 } 4874 } 4875 4876 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4877 // ISD::SETNE) 4878 return DAG.getNode( 4879 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4880 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4881 } 4882 4883 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4884 SmallVectorImpl<SDValue> &Results, 4885 SelectionDAG &DAG) const { 4886 switch (N->getOpcode()) { 4887 case ISD::INSERT_VECTOR_ELT: { 4888 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4889 Results.push_back(Res); 4890 return; 4891 } 4892 case ISD::EXTRACT_VECTOR_ELT: { 4893 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4894 Results.push_back(Res); 4895 return; 4896 } 4897 case ISD::INTRINSIC_WO_CHAIN: { 4898 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4899 switch (IID) { 4900 case Intrinsic::amdgcn_cvt_pkrtz: { 4901 SDValue Src0 = N->getOperand(1); 4902 SDValue Src1 = N->getOperand(2); 4903 SDLoc SL(N); 4904 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4905 Src0, Src1); 4906 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4907 return; 4908 } 4909 case Intrinsic::amdgcn_cvt_pknorm_i16: 4910 case Intrinsic::amdgcn_cvt_pknorm_u16: 4911 case Intrinsic::amdgcn_cvt_pk_i16: 4912 case Intrinsic::amdgcn_cvt_pk_u16: { 4913 SDValue Src0 = N->getOperand(1); 4914 SDValue Src1 = N->getOperand(2); 4915 SDLoc SL(N); 4916 unsigned Opcode; 4917 4918 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4919 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4920 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4921 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4922 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4923 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4924 else 4925 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4926 4927 EVT VT = N->getValueType(0); 4928 if (isTypeLegal(VT)) 4929 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4930 else { 4931 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4932 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4933 } 4934 return; 4935 } 4936 } 4937 break; 4938 } 4939 case ISD::INTRINSIC_W_CHAIN: { 4940 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4941 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4942 // FIXME: Hacky 4943 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4944 Results.push_back(Res.getOperand(I)); 4945 } 4946 } else { 4947 Results.push_back(Res); 4948 Results.push_back(Res.getValue(1)); 4949 } 4950 return; 4951 } 4952 4953 break; 4954 } 4955 case ISD::SELECT: { 4956 SDLoc SL(N); 4957 EVT VT = N->getValueType(0); 4958 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4959 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4960 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4961 4962 EVT SelectVT = NewVT; 4963 if (NewVT.bitsLT(MVT::i32)) { 4964 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4965 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4966 SelectVT = MVT::i32; 4967 } 4968 4969 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4970 N->getOperand(0), LHS, RHS); 4971 4972 if (NewVT != SelectVT) 4973 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4974 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4975 return; 4976 } 4977 case ISD::FNEG: { 4978 if (N->getValueType(0) != MVT::v2f16) 4979 break; 4980 4981 SDLoc SL(N); 4982 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4983 4984 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4985 BC, 4986 DAG.getConstant(0x80008000, SL, MVT::i32)); 4987 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4988 return; 4989 } 4990 case ISD::FABS: { 4991 if (N->getValueType(0) != MVT::v2f16) 4992 break; 4993 4994 SDLoc SL(N); 4995 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4996 4997 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4998 BC, 4999 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 5000 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5001 return; 5002 } 5003 default: 5004 break; 5005 } 5006 } 5007 5008 /// Helper function for LowerBRCOND 5009 static SDNode *findUser(SDValue Value, unsigned Opcode) { 5010 5011 SDNode *Parent = Value.getNode(); 5012 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 5013 I != E; ++I) { 5014 5015 if (I.getUse().get() != Value) 5016 continue; 5017 5018 if (I->getOpcode() == Opcode) 5019 return *I; 5020 } 5021 return nullptr; 5022 } 5023 5024 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 5025 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 5026 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 5027 case Intrinsic::amdgcn_if: 5028 return AMDGPUISD::IF; 5029 case Intrinsic::amdgcn_else: 5030 return AMDGPUISD::ELSE; 5031 case Intrinsic::amdgcn_loop: 5032 return AMDGPUISD::LOOP; 5033 case Intrinsic::amdgcn_end_cf: 5034 llvm_unreachable("should not occur"); 5035 default: 5036 return 0; 5037 } 5038 } 5039 5040 // break, if_break, else_break are all only used as inputs to loop, not 5041 // directly as branch conditions. 5042 return 0; 5043 } 5044 5045 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 5046 const Triple &TT = getTargetMachine().getTargetTriple(); 5047 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5048 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5049 AMDGPU::shouldEmitConstantsToTextSection(TT); 5050 } 5051 5052 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 5053 // FIXME: Either avoid relying on address space here or change the default 5054 // address space for functions to avoid the explicit check. 5055 return (GV->getValueType()->isFunctionTy() || 5056 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 5057 !shouldEmitFixup(GV) && 5058 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 5059 } 5060 5061 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 5062 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 5063 } 5064 5065 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 5066 if (!GV->hasExternalLinkage()) 5067 return true; 5068 5069 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5070 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5071 } 5072 5073 /// This transforms the control flow intrinsics to get the branch destination as 5074 /// last parameter, also switches branch target with BR if the need arise 5075 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5076 SelectionDAG &DAG) const { 5077 SDLoc DL(BRCOND); 5078 5079 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5080 SDValue Target = BRCOND.getOperand(2); 5081 SDNode *BR = nullptr; 5082 SDNode *SetCC = nullptr; 5083 5084 if (Intr->getOpcode() == ISD::SETCC) { 5085 // As long as we negate the condition everything is fine 5086 SetCC = Intr; 5087 Intr = SetCC->getOperand(0).getNode(); 5088 5089 } else { 5090 // Get the target from BR if we don't negate the condition 5091 BR = findUser(BRCOND, ISD::BR); 5092 assert(BR && "brcond missing unconditional branch user"); 5093 Target = BR->getOperand(1); 5094 } 5095 5096 unsigned CFNode = isCFIntrinsic(Intr); 5097 if (CFNode == 0) { 5098 // This is a uniform branch so we don't need to legalize. 5099 return BRCOND; 5100 } 5101 5102 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5103 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5104 5105 assert(!SetCC || 5106 (SetCC->getConstantOperandVal(1) == 1 && 5107 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5108 ISD::SETNE)); 5109 5110 // operands of the new intrinsic call 5111 SmallVector<SDValue, 4> Ops; 5112 if (HaveChain) 5113 Ops.push_back(BRCOND.getOperand(0)); 5114 5115 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5116 Ops.push_back(Target); 5117 5118 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5119 5120 // build the new intrinsic call 5121 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5122 5123 if (!HaveChain) { 5124 SDValue Ops[] = { 5125 SDValue(Result, 0), 5126 BRCOND.getOperand(0) 5127 }; 5128 5129 Result = DAG.getMergeValues(Ops, DL).getNode(); 5130 } 5131 5132 if (BR) { 5133 // Give the branch instruction our target 5134 SDValue Ops[] = { 5135 BR->getOperand(0), 5136 BRCOND.getOperand(2) 5137 }; 5138 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5139 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5140 } 5141 5142 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5143 5144 // Copy the intrinsic results to registers 5145 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5146 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5147 if (!CopyToReg) 5148 continue; 5149 5150 Chain = DAG.getCopyToReg( 5151 Chain, DL, 5152 CopyToReg->getOperand(1), 5153 SDValue(Result, i - 1), 5154 SDValue()); 5155 5156 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5157 } 5158 5159 // Remove the old intrinsic from the chain 5160 DAG.ReplaceAllUsesOfValueWith( 5161 SDValue(Intr, Intr->getNumValues() - 1), 5162 Intr->getOperand(0)); 5163 5164 return Chain; 5165 } 5166 5167 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5168 SelectionDAG &DAG) const { 5169 MVT VT = Op.getSimpleValueType(); 5170 SDLoc DL(Op); 5171 // Checking the depth 5172 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5173 return DAG.getConstant(0, DL, VT); 5174 5175 MachineFunction &MF = DAG.getMachineFunction(); 5176 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5177 // Check for kernel and shader functions 5178 if (Info->isEntryFunction()) 5179 return DAG.getConstant(0, DL, VT); 5180 5181 MachineFrameInfo &MFI = MF.getFrameInfo(); 5182 // There is a call to @llvm.returnaddress in this function 5183 MFI.setReturnAddressIsTaken(true); 5184 5185 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5186 // Get the return address reg and mark it as an implicit live-in 5187 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5188 5189 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5190 } 5191 5192 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5193 SDValue Op, 5194 const SDLoc &DL, 5195 EVT VT) const { 5196 return Op.getValueType().bitsLE(VT) ? 5197 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5198 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5199 DAG.getTargetConstant(0, DL, MVT::i32)); 5200 } 5201 5202 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5203 assert(Op.getValueType() == MVT::f16 && 5204 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5205 5206 SDValue Src = Op.getOperand(0); 5207 EVT SrcVT = Src.getValueType(); 5208 if (SrcVT != MVT::f64) 5209 return Op; 5210 5211 SDLoc DL(Op); 5212 5213 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5214 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5215 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5216 } 5217 5218 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5219 SelectionDAG &DAG) const { 5220 EVT VT = Op.getValueType(); 5221 const MachineFunction &MF = DAG.getMachineFunction(); 5222 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5223 bool IsIEEEMode = Info->getMode().IEEE; 5224 5225 // FIXME: Assert during selection that this is only selected for 5226 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5227 // mode functions, but this happens to be OK since it's only done in cases 5228 // where there is known no sNaN. 5229 if (IsIEEEMode) 5230 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5231 5232 if (VT == MVT::v4f16 || VT == MVT::v8f16) 5233 return splitBinaryVectorOp(Op, DAG); 5234 return Op; 5235 } 5236 5237 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5238 EVT VT = Op.getValueType(); 5239 SDLoc SL(Op); 5240 SDValue LHS = Op.getOperand(0); 5241 SDValue RHS = Op.getOperand(1); 5242 bool isSigned = Op.getOpcode() == ISD::SMULO; 5243 5244 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5245 const APInt &C = RHSC->getAPIntValue(); 5246 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5247 if (C.isPowerOf2()) { 5248 // smulo(x, signed_min) is same as umulo(x, signed_min). 5249 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5250 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5251 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5252 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5253 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5254 SL, VT, Result, ShiftAmt), 5255 LHS, ISD::SETNE); 5256 return DAG.getMergeValues({ Result, Overflow }, SL); 5257 } 5258 } 5259 5260 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5261 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5262 SL, VT, LHS, RHS); 5263 5264 SDValue Sign = isSigned 5265 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5266 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5267 : DAG.getConstant(0, SL, VT); 5268 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5269 5270 return DAG.getMergeValues({ Result, Overflow }, SL); 5271 } 5272 5273 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const { 5274 if (Op->isDivergent()) { 5275 // Select to V_MAD_[IU]64_[IU]32. 5276 return Op; 5277 } 5278 if (Subtarget->hasSMulHi()) { 5279 // Expand to S_MUL_I32 + S_MUL_HI_[IU]32. 5280 return SDValue(); 5281 } 5282 // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to 5283 // calculate the high part, so we might as well do the whole thing with 5284 // V_MAD_[IU]64_[IU]32. 5285 return Op; 5286 } 5287 5288 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5289 if (!Subtarget->isTrapHandlerEnabled() || 5290 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5291 return lowerTrapEndpgm(Op, DAG); 5292 5293 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5294 switch (*HsaAbiVer) { 5295 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5296 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5297 return lowerTrapHsaQueuePtr(Op, DAG); 5298 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5299 case ELF::ELFABIVERSION_AMDGPU_HSA_V5: 5300 return Subtarget->supportsGetDoorbellID() ? 5301 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5302 } 5303 } 5304 5305 llvm_unreachable("Unknown trap handler"); 5306 } 5307 5308 SDValue SITargetLowering::lowerTrapEndpgm( 5309 SDValue Op, SelectionDAG &DAG) const { 5310 SDLoc SL(Op); 5311 SDValue Chain = Op.getOperand(0); 5312 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5313 } 5314 5315 SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT, 5316 const SDLoc &DL, Align Alignment, ImplicitParameter Param) const { 5317 MachineFunction &MF = DAG.getMachineFunction(); 5318 uint64_t Offset = getImplicitParameterOffset(MF, Param); 5319 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset); 5320 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5321 return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment, 5322 MachineMemOperand::MODereferenceable | 5323 MachineMemOperand::MOInvariant); 5324 } 5325 5326 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5327 SDValue Op, SelectionDAG &DAG) const { 5328 SDLoc SL(Op); 5329 SDValue Chain = Op.getOperand(0); 5330 5331 SDValue QueuePtr; 5332 // For code object version 5, QueuePtr is passed through implicit kernarg. 5333 if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) { 5334 QueuePtr = 5335 loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR); 5336 } else { 5337 MachineFunction &MF = DAG.getMachineFunction(); 5338 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5339 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5340 5341 if (UserSGPR == AMDGPU::NoRegister) { 5342 // We probably are in a function incorrectly marked with 5343 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the 5344 // trap, so just use a null pointer. 5345 QueuePtr = DAG.getConstant(0, SL, MVT::i64); 5346 } else { 5347 QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR, 5348 MVT::i64); 5349 } 5350 } 5351 5352 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5353 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5354 QueuePtr, SDValue()); 5355 5356 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5357 SDValue Ops[] = { 5358 ToReg, 5359 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5360 SGPR01, 5361 ToReg.getValue(1) 5362 }; 5363 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5364 } 5365 5366 SDValue SITargetLowering::lowerTrapHsa( 5367 SDValue Op, SelectionDAG &DAG) const { 5368 SDLoc SL(Op); 5369 SDValue Chain = Op.getOperand(0); 5370 5371 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5372 SDValue Ops[] = { 5373 Chain, 5374 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5375 }; 5376 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5377 } 5378 5379 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5380 SDLoc SL(Op); 5381 SDValue Chain = Op.getOperand(0); 5382 MachineFunction &MF = DAG.getMachineFunction(); 5383 5384 if (!Subtarget->isTrapHandlerEnabled() || 5385 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5386 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5387 "debugtrap handler not supported", 5388 Op.getDebugLoc(), 5389 DS_Warning); 5390 LLVMContext &Ctx = MF.getFunction().getContext(); 5391 Ctx.diagnose(NoTrap); 5392 return Chain; 5393 } 5394 5395 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5396 SDValue Ops[] = { 5397 Chain, 5398 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5399 }; 5400 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5401 } 5402 5403 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5404 SelectionDAG &DAG) const { 5405 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5406 if (Subtarget->hasApertureRegs()) { 5407 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5408 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5409 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5410 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5411 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5412 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5413 unsigned Encoding = 5414 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5415 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5416 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5417 5418 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5419 SDValue ApertureReg = SDValue( 5420 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5421 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5422 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5423 } 5424 5425 // For code object version 5, private_base and shared_base are passed through 5426 // implicit kernargs. 5427 if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) { 5428 ImplicitParameter Param = 5429 (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE; 5430 return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param); 5431 } 5432 5433 MachineFunction &MF = DAG.getMachineFunction(); 5434 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5435 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5436 if (UserSGPR == AMDGPU::NoRegister) { 5437 // We probably are in a function incorrectly marked with 5438 // amdgpu-no-queue-ptr. This is undefined. 5439 return DAG.getUNDEF(MVT::i32); 5440 } 5441 5442 SDValue QueuePtr = CreateLiveInRegister( 5443 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5444 5445 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5446 // private_segment_aperture_base_hi. 5447 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5448 5449 SDValue Ptr = 5450 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5451 5452 // TODO: Use custom target PseudoSourceValue. 5453 // TODO: We should use the value from the IR intrinsic call, but it might not 5454 // be available and how do we get it? 5455 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5456 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5457 commonAlignment(Align(64), StructOffset), 5458 MachineMemOperand::MODereferenceable | 5459 MachineMemOperand::MOInvariant); 5460 } 5461 5462 /// Return true if the value is a known valid address, such that a null check is 5463 /// not necessary. 5464 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG, 5465 const AMDGPUTargetMachine &TM, unsigned AddrSpace) { 5466 if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) || 5467 isa<BasicBlockSDNode>(Val)) 5468 return true; 5469 5470 if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val)) 5471 return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace); 5472 5473 // TODO: Search through arithmetic, handle arguments and loads 5474 // marked nonnull. 5475 return false; 5476 } 5477 5478 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5479 SelectionDAG &DAG) const { 5480 SDLoc SL(Op); 5481 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5482 5483 SDValue Src = ASC->getOperand(0); 5484 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5485 unsigned SrcAS = ASC->getSrcAddressSpace(); 5486 5487 const AMDGPUTargetMachine &TM = 5488 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5489 5490 // flat -> local/private 5491 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) { 5492 unsigned DestAS = ASC->getDestAddressSpace(); 5493 5494 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5495 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5496 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5497 5498 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5499 return Ptr; 5500 5501 unsigned NullVal = TM.getNullPointerValue(DestAS); 5502 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5503 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5504 5505 return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr, 5506 SegmentNullPtr); 5507 } 5508 } 5509 5510 // local/private -> flat 5511 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5512 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5513 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5514 5515 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5516 SDValue CvtPtr = 5517 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5518 CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr); 5519 5520 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5521 return CvtPtr; 5522 5523 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5524 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5525 5526 SDValue NonNull 5527 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5528 5529 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr, 5530 FlatNullPtr); 5531 } 5532 } 5533 5534 if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5535 Op.getValueType() == MVT::i64) { 5536 const SIMachineFunctionInfo *Info = 5537 DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>(); 5538 SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32); 5539 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi); 5540 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 5541 } 5542 5543 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5544 Src.getValueType() == MVT::i64) 5545 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5546 5547 // global <-> flat are no-ops and never emitted. 5548 5549 const MachineFunction &MF = DAG.getMachineFunction(); 5550 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5551 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5552 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5553 5554 return DAG.getUNDEF(ASC->getValueType(0)); 5555 } 5556 5557 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5558 // the small vector and inserting them into the big vector. That is better than 5559 // the default expansion of doing it via a stack slot. Even though the use of 5560 // the stack slot would be optimized away afterwards, the stack slot itself 5561 // remains. 5562 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5563 SelectionDAG &DAG) const { 5564 SDValue Vec = Op.getOperand(0); 5565 SDValue Ins = Op.getOperand(1); 5566 SDValue Idx = Op.getOperand(2); 5567 EVT VecVT = Vec.getValueType(); 5568 EVT InsVT = Ins.getValueType(); 5569 EVT EltVT = VecVT.getVectorElementType(); 5570 unsigned InsNumElts = InsVT.getVectorNumElements(); 5571 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5572 SDLoc SL(Op); 5573 5574 for (unsigned I = 0; I != InsNumElts; ++I) { 5575 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5576 DAG.getConstant(I, SL, MVT::i32)); 5577 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5578 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5579 } 5580 return Vec; 5581 } 5582 5583 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5584 SelectionDAG &DAG) const { 5585 SDValue Vec = Op.getOperand(0); 5586 SDValue InsVal = Op.getOperand(1); 5587 SDValue Idx = Op.getOperand(2); 5588 EVT VecVT = Vec.getValueType(); 5589 EVT EltVT = VecVT.getVectorElementType(); 5590 unsigned VecSize = VecVT.getSizeInBits(); 5591 unsigned EltSize = EltVT.getSizeInBits(); 5592 SDLoc SL(Op); 5593 5594 // Specially handle the case of v4i16 with static indexing. 5595 unsigned NumElts = VecVT.getVectorNumElements(); 5596 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5597 if (NumElts == 4 && EltSize == 16 && KIdx) { 5598 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5599 5600 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5601 DAG.getConstant(0, SL, MVT::i32)); 5602 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5603 DAG.getConstant(1, SL, MVT::i32)); 5604 5605 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5606 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5607 5608 unsigned Idx = KIdx->getZExtValue(); 5609 bool InsertLo = Idx < 2; 5610 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5611 InsertLo ? LoVec : HiVec, 5612 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5613 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5614 5615 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5616 5617 SDValue Concat = InsertLo ? 5618 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5619 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5620 5621 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5622 } 5623 5624 // Static indexing does not lower to stack access, and hence there is no need 5625 // for special custom lowering to avoid stack access. 5626 if (isa<ConstantSDNode>(Idx)) 5627 return SDValue(); 5628 5629 // Avoid stack access for dynamic indexing by custom lowering to 5630 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5631 5632 assert(VecSize <= 64 && "Expected target vector size to be <= 64 bits"); 5633 5634 MVT IntVT = MVT::getIntegerVT(VecSize); 5635 5636 // Convert vector index to bit-index and get the required bit mask. 5637 assert(isPowerOf2_32(EltSize)); 5638 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5639 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5640 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5641 DAG.getConstant(0xffff, SL, IntVT), 5642 ScaledIdx); 5643 5644 // 1. Create a congruent vector with the target value in each element. 5645 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5646 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5647 5648 // 2. Mask off all other indicies except the required index within (1). 5649 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5650 5651 // 3. Mask off the required index within the target vector. 5652 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5653 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5654 DAG.getNOT(SL, BFM, IntVT), BCVec); 5655 5656 // 4. Get (2) and (3) ORed into the target vector. 5657 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5658 5659 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5660 } 5661 5662 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5663 SelectionDAG &DAG) const { 5664 SDLoc SL(Op); 5665 5666 EVT ResultVT = Op.getValueType(); 5667 SDValue Vec = Op.getOperand(0); 5668 SDValue Idx = Op.getOperand(1); 5669 EVT VecVT = Vec.getValueType(); 5670 unsigned VecSize = VecVT.getSizeInBits(); 5671 EVT EltVT = VecVT.getVectorElementType(); 5672 5673 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5674 5675 // Make sure we do any optimizations that will make it easier to fold 5676 // source modifiers before obscuring it with bit operations. 5677 5678 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5679 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5680 return Combined; 5681 5682 if (VecSize == 128) { 5683 SDValue Lo, Hi; 5684 EVT LoVT, HiVT; 5685 SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec); 5686 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5687 Lo = 5688 DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5689 V2, DAG.getConstant(0, SL, MVT::i32))); 5690 Hi = 5691 DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5692 V2, DAG.getConstant(1, SL, MVT::i32))); 5693 EVT IdxVT = Idx.getValueType(); 5694 unsigned NElem = VecVT.getVectorNumElements(); 5695 assert(isPowerOf2_32(NElem)); 5696 SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT); 5697 SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask); 5698 SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT); 5699 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx); 5700 } 5701 5702 assert(VecSize <= 64); 5703 5704 MVT IntVT = MVT::getIntegerVT(VecSize); 5705 5706 // If Vec is just a SCALAR_TO_VECTOR, then use the scalar integer directly. 5707 SDValue VecBC = peekThroughBitcasts(Vec); 5708 if (VecBC.getOpcode() == ISD::SCALAR_TO_VECTOR) { 5709 SDValue Src = VecBC.getOperand(0); 5710 Src = DAG.getBitcast(Src.getValueType().changeTypeToInteger(), Src); 5711 Vec = DAG.getAnyExtOrTrunc(Src, SL, IntVT); 5712 } 5713 5714 unsigned EltSize = EltVT.getSizeInBits(); 5715 assert(isPowerOf2_32(EltSize)); 5716 5717 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5718 5719 // Convert vector index to bit-index (* EltSize) 5720 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5721 5722 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5723 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5724 5725 if (ResultVT == MVT::f16) { 5726 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5727 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5728 } 5729 5730 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5731 } 5732 5733 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5734 assert(Elt % 2 == 0); 5735 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5736 } 5737 5738 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5739 SelectionDAG &DAG) const { 5740 SDLoc SL(Op); 5741 EVT ResultVT = Op.getValueType(); 5742 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5743 5744 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5745 EVT EltVT = PackVT.getVectorElementType(); 5746 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5747 5748 // vector_shuffle <0,1,6,7> lhs, rhs 5749 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5750 // 5751 // vector_shuffle <6,7,2,3> lhs, rhs 5752 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5753 // 5754 // vector_shuffle <6,7,0,1> lhs, rhs 5755 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5756 5757 // Avoid scalarizing when both halves are reading from consecutive elements. 5758 SmallVector<SDValue, 4> Pieces; 5759 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5760 if (elementPairIsContiguous(SVN->getMask(), I)) { 5761 const int Idx = SVN->getMaskElt(I); 5762 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5763 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5764 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5765 PackVT, SVN->getOperand(VecIdx), 5766 DAG.getConstant(EltIdx, SL, MVT::i32)); 5767 Pieces.push_back(SubVec); 5768 } else { 5769 const int Idx0 = SVN->getMaskElt(I); 5770 const int Idx1 = SVN->getMaskElt(I + 1); 5771 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5772 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5773 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5774 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5775 5776 SDValue Vec0 = SVN->getOperand(VecIdx0); 5777 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5778 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5779 5780 SDValue Vec1 = SVN->getOperand(VecIdx1); 5781 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5782 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5783 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5784 } 5785 } 5786 5787 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5788 } 5789 5790 SDValue SITargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op, 5791 SelectionDAG &DAG) const { 5792 SDValue SVal = Op.getOperand(0); 5793 EVT ResultVT = Op.getValueType(); 5794 EVT SValVT = SVal.getValueType(); 5795 SDValue UndefVal = DAG.getUNDEF(SValVT); 5796 SDLoc SL(Op); 5797 5798 SmallVector<SDValue, 8> VElts; 5799 VElts.push_back(SVal); 5800 for (int I = 1, E = ResultVT.getVectorNumElements(); I < E; ++I) 5801 VElts.push_back(UndefVal); 5802 5803 return DAG.getBuildVector(ResultVT, SL, VElts); 5804 } 5805 5806 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5807 SelectionDAG &DAG) const { 5808 SDLoc SL(Op); 5809 EVT VT = Op.getValueType(); 5810 5811 if (VT == MVT::v4i16 || VT == MVT::v4f16 || 5812 VT == MVT::v8i16 || VT == MVT::v8f16) { 5813 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 5814 VT.getVectorNumElements() / 2); 5815 MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits()); 5816 5817 // Turn into pair of packed build_vectors. 5818 // TODO: Special case for constants that can be materialized with s_mov_b64. 5819 SmallVector<SDValue, 4> LoOps, HiOps; 5820 for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) { 5821 LoOps.push_back(Op.getOperand(I)); 5822 HiOps.push_back(Op.getOperand(I + E)); 5823 } 5824 SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps); 5825 SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps); 5826 5827 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo); 5828 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi); 5829 5830 SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL, 5831 { CastLo, CastHi }); 5832 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5833 } 5834 5835 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5836 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5837 5838 SDValue Lo = Op.getOperand(0); 5839 SDValue Hi = Op.getOperand(1); 5840 5841 // Avoid adding defined bits with the zero_extend. 5842 if (Hi.isUndef()) { 5843 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5844 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5845 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5846 } 5847 5848 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5849 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5850 5851 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5852 DAG.getConstant(16, SL, MVT::i32)); 5853 if (Lo.isUndef()) 5854 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5855 5856 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5857 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5858 5859 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5860 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5861 } 5862 5863 bool 5864 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5865 // We can fold offsets for anything that doesn't require a GOT relocation. 5866 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5867 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5868 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5869 !shouldEmitGOTReloc(GA->getGlobal()); 5870 } 5871 5872 static SDValue 5873 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5874 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5875 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5876 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5877 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5878 // lowered to the following code sequence: 5879 // 5880 // For constant address space: 5881 // s_getpc_b64 s[0:1] 5882 // s_add_u32 s0, s0, $symbol 5883 // s_addc_u32 s1, s1, 0 5884 // 5885 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5886 // a fixup or relocation is emitted to replace $symbol with a literal 5887 // constant, which is a pc-relative offset from the encoding of the $symbol 5888 // operand to the global variable. 5889 // 5890 // For global address space: 5891 // s_getpc_b64 s[0:1] 5892 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5893 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5894 // 5895 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5896 // fixups or relocations are emitted to replace $symbol@*@lo and 5897 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5898 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5899 // operand to the global variable. 5900 // 5901 // What we want here is an offset from the value returned by s_getpc 5902 // (which is the address of the s_add_u32 instruction) to the global 5903 // variable, but since the encoding of $symbol starts 4 bytes after the start 5904 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5905 // small. This requires us to add 4 to the global variable offset in order to 5906 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5907 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5908 // instruction. 5909 SDValue PtrLo = 5910 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5911 SDValue PtrHi; 5912 if (GAFlags == SIInstrInfo::MO_NONE) { 5913 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5914 } else { 5915 PtrHi = 5916 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5917 } 5918 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5919 } 5920 5921 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5922 SDValue Op, 5923 SelectionDAG &DAG) const { 5924 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5925 SDLoc DL(GSD); 5926 EVT PtrVT = Op.getValueType(); 5927 5928 const GlobalValue *GV = GSD->getGlobal(); 5929 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5930 shouldUseLDSConstAddress(GV)) || 5931 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5932 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5933 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5934 GV->hasExternalLinkage()) { 5935 Type *Ty = GV->getValueType(); 5936 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5937 // zero-sized type in other languages to declare the dynamic shared 5938 // memory which size is not known at the compile time. They will be 5939 // allocated by the runtime and placed directly after the static 5940 // allocated ones. They all share the same offset. 5941 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5942 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5943 // Adjust alignment for that dynamic shared memory array. 5944 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5945 return SDValue( 5946 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5947 } 5948 } 5949 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5950 } 5951 5952 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5953 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5954 SIInstrInfo::MO_ABS32_LO); 5955 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5956 } 5957 5958 if (shouldEmitFixup(GV)) 5959 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5960 else if (shouldEmitPCReloc(GV)) 5961 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5962 SIInstrInfo::MO_REL32); 5963 5964 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5965 SIInstrInfo::MO_GOTPCREL32); 5966 5967 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5968 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5969 const DataLayout &DataLayout = DAG.getDataLayout(); 5970 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5971 MachinePointerInfo PtrInfo 5972 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5973 5974 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5975 MachineMemOperand::MODereferenceable | 5976 MachineMemOperand::MOInvariant); 5977 } 5978 5979 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5980 const SDLoc &DL, SDValue V) const { 5981 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5982 // the destination register. 5983 // 5984 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5985 // so we will end up with redundant moves to m0. 5986 // 5987 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5988 5989 // A Null SDValue creates a glue result. 5990 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5991 V, Chain); 5992 return SDValue(M0, 0); 5993 } 5994 5995 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5996 SDValue Op, 5997 MVT VT, 5998 unsigned Offset) const { 5999 SDLoc SL(Op); 6000 SDValue Param = lowerKernargMemParameter( 6001 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 6002 // The local size values will have the hi 16-bits as zero. 6003 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 6004 DAG.getValueType(VT)); 6005 } 6006 6007 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6008 EVT VT) { 6009 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6010 "non-hsa intrinsic with hsa target", 6011 DL.getDebugLoc()); 6012 DAG.getContext()->diagnose(BadIntrin); 6013 return DAG.getUNDEF(VT); 6014 } 6015 6016 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6017 EVT VT) { 6018 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6019 "intrinsic not supported on subtarget", 6020 DL.getDebugLoc()); 6021 DAG.getContext()->diagnose(BadIntrin); 6022 return DAG.getUNDEF(VT); 6023 } 6024 6025 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 6026 ArrayRef<SDValue> Elts) { 6027 assert(!Elts.empty()); 6028 MVT Type; 6029 unsigned NumElts = Elts.size(); 6030 6031 if (NumElts <= 8) { 6032 Type = MVT::getVectorVT(MVT::f32, NumElts); 6033 } else { 6034 assert(Elts.size() <= 16); 6035 Type = MVT::v16f32; 6036 NumElts = 16; 6037 } 6038 6039 SmallVector<SDValue, 16> VecElts(NumElts); 6040 for (unsigned i = 0; i < Elts.size(); ++i) { 6041 SDValue Elt = Elts[i]; 6042 if (Elt.getValueType() != MVT::f32) 6043 Elt = DAG.getBitcast(MVT::f32, Elt); 6044 VecElts[i] = Elt; 6045 } 6046 for (unsigned i = Elts.size(); i < NumElts; ++i) 6047 VecElts[i] = DAG.getUNDEF(MVT::f32); 6048 6049 if (NumElts == 1) 6050 return VecElts[0]; 6051 return DAG.getBuildVector(Type, DL, VecElts); 6052 } 6053 6054 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 6055 SDValue Src, int ExtraElts) { 6056 EVT SrcVT = Src.getValueType(); 6057 6058 SmallVector<SDValue, 8> Elts; 6059 6060 if (SrcVT.isVector()) 6061 DAG.ExtractVectorElements(Src, Elts); 6062 else 6063 Elts.push_back(Src); 6064 6065 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 6066 while (ExtraElts--) 6067 Elts.push_back(Undef); 6068 6069 return DAG.getBuildVector(CastVT, DL, Elts); 6070 } 6071 6072 // Re-construct the required return value for a image load intrinsic. 6073 // This is more complicated due to the optional use TexFailCtrl which means the required 6074 // return type is an aggregate 6075 static SDValue constructRetValue(SelectionDAG &DAG, 6076 MachineSDNode *Result, 6077 ArrayRef<EVT> ResultTypes, 6078 bool IsTexFail, bool Unpacked, bool IsD16, 6079 int DMaskPop, int NumVDataDwords, 6080 const SDLoc &DL) { 6081 // Determine the required return type. This is the same regardless of IsTexFail flag 6082 EVT ReqRetVT = ResultTypes[0]; 6083 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 6084 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6085 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 6086 6087 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6088 DMaskPop : (DMaskPop + 1) / 2; 6089 6090 MVT DataDwordVT = NumDataDwords == 1 ? 6091 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 6092 6093 MVT MaskPopVT = MaskPopDwords == 1 ? 6094 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 6095 6096 SDValue Data(Result, 0); 6097 SDValue TexFail; 6098 6099 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 6100 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 6101 if (MaskPopVT.isVector()) { 6102 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 6103 SDValue(Result, 0), ZeroIdx); 6104 } else { 6105 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 6106 SDValue(Result, 0), ZeroIdx); 6107 } 6108 } 6109 6110 if (DataDwordVT.isVector()) 6111 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 6112 NumDataDwords - MaskPopDwords); 6113 6114 if (IsD16) 6115 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 6116 6117 EVT LegalReqRetVT = ReqRetVT; 6118 if (!ReqRetVT.isVector()) { 6119 if (!Data.getValueType().isInteger()) 6120 Data = DAG.getNode(ISD::BITCAST, DL, 6121 Data.getValueType().changeTypeToInteger(), Data); 6122 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 6123 } else { 6124 // We need to widen the return vector to a legal type 6125 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 6126 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 6127 LegalReqRetVT = 6128 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 6129 ReqRetVT.getVectorNumElements() + 1); 6130 } 6131 } 6132 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 6133 6134 if (IsTexFail) { 6135 TexFail = 6136 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 6137 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 6138 6139 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 6140 } 6141 6142 if (Result->getNumValues() == 1) 6143 return Data; 6144 6145 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 6146 } 6147 6148 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 6149 SDValue *LWE, bool &IsTexFail) { 6150 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 6151 6152 uint64_t Value = TexFailCtrlConst->getZExtValue(); 6153 if (Value) { 6154 IsTexFail = true; 6155 } 6156 6157 SDLoc DL(TexFailCtrlConst); 6158 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 6159 Value &= ~(uint64_t)0x1; 6160 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 6161 Value &= ~(uint64_t)0x2; 6162 6163 return Value == 0; 6164 } 6165 6166 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op, 6167 MVT PackVectorVT, 6168 SmallVectorImpl<SDValue> &PackedAddrs, 6169 unsigned DimIdx, unsigned EndIdx, 6170 unsigned NumGradients) { 6171 SDLoc DL(Op); 6172 for (unsigned I = DimIdx; I < EndIdx; I++) { 6173 SDValue Addr = Op.getOperand(I); 6174 6175 // Gradients are packed with undef for each coordinate. 6176 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 6177 // 1D: undef,dx/dh; undef,dx/dv 6178 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 6179 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 6180 if (((I + 1) >= EndIdx) || 6181 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 6182 I == DimIdx + NumGradients - 1))) { 6183 if (Addr.getValueType() != MVT::i16) 6184 Addr = DAG.getBitcast(MVT::i16, Addr); 6185 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 6186 } else { 6187 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 6188 I++; 6189 } 6190 Addr = DAG.getBitcast(MVT::f32, Addr); 6191 PackedAddrs.push_back(Addr); 6192 } 6193 } 6194 6195 SDValue SITargetLowering::lowerImage(SDValue Op, 6196 const AMDGPU::ImageDimIntrinsicInfo *Intr, 6197 SelectionDAG &DAG, bool WithChain) const { 6198 SDLoc DL(Op); 6199 MachineFunction &MF = DAG.getMachineFunction(); 6200 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 6201 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 6202 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 6203 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 6204 unsigned IntrOpcode = Intr->BaseOpcode; 6205 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6206 6207 SmallVector<EVT, 3> ResultTypes(Op->values()); 6208 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 6209 bool IsD16 = false; 6210 bool IsG16 = false; 6211 bool IsA16 = false; 6212 SDValue VData; 6213 int NumVDataDwords; 6214 bool AdjustRetType = false; 6215 6216 // Offset of intrinsic arguments 6217 const unsigned ArgOffset = WithChain ? 2 : 1; 6218 6219 unsigned DMask; 6220 unsigned DMaskLanes = 0; 6221 6222 if (BaseOpcode->Atomic) { 6223 VData = Op.getOperand(2); 6224 6225 bool Is64Bit = VData.getValueType() == MVT::i64; 6226 if (BaseOpcode->AtomicX2) { 6227 SDValue VData2 = Op.getOperand(3); 6228 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6229 {VData, VData2}); 6230 if (Is64Bit) 6231 VData = DAG.getBitcast(MVT::v4i32, VData); 6232 6233 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6234 DMask = Is64Bit ? 0xf : 0x3; 6235 NumVDataDwords = Is64Bit ? 4 : 2; 6236 } else { 6237 DMask = Is64Bit ? 0x3 : 0x1; 6238 NumVDataDwords = Is64Bit ? 2 : 1; 6239 } 6240 } else { 6241 auto *DMaskConst = 6242 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6243 DMask = DMaskConst->getZExtValue(); 6244 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6245 6246 if (BaseOpcode->Store) { 6247 VData = Op.getOperand(2); 6248 6249 MVT StoreVT = VData.getSimpleValueType(); 6250 if (StoreVT.getScalarType() == MVT::f16) { 6251 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6252 return Op; // D16 is unsupported for this instruction 6253 6254 IsD16 = true; 6255 VData = handleD16VData(VData, DAG, true); 6256 } 6257 6258 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6259 } else { 6260 // Work out the num dwords based on the dmask popcount and underlying type 6261 // and whether packing is supported. 6262 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6263 if (LoadVT.getScalarType() == MVT::f16) { 6264 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6265 return Op; // D16 is unsupported for this instruction 6266 6267 IsD16 = true; 6268 } 6269 6270 // Confirm that the return type is large enough for the dmask specified 6271 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6272 (!LoadVT.isVector() && DMaskLanes > 1)) 6273 return Op; 6274 6275 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6276 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6277 // instructions. 6278 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6279 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6280 NumVDataDwords = (DMaskLanes + 1) / 2; 6281 else 6282 NumVDataDwords = DMaskLanes; 6283 6284 AdjustRetType = true; 6285 } 6286 } 6287 6288 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6289 SmallVector<SDValue, 4> VAddrs; 6290 6291 // Check for 16 bit addresses or derivatives and pack if true. 6292 MVT VAddrVT = 6293 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6294 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6295 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6296 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6297 6298 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6299 VAddrScalarVT = VAddrVT.getScalarType(); 6300 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6301 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6302 6303 // Push back extra arguments. 6304 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) { 6305 if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) { 6306 assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument"); 6307 // Special handling of bias when A16 is on. Bias is of type half but 6308 // occupies full 32-bit. 6309 SDValue Bias = DAG.getBuildVector( 6310 MVT::v2f16, DL, 6311 {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)}); 6312 VAddrs.push_back(Bias); 6313 } else { 6314 assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) && 6315 "Bias needs to be converted to 16 bit in A16 mode"); 6316 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6317 } 6318 } 6319 6320 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) { 6321 // 16 bit gradients are supported, but are tied to the A16 control 6322 // so both gradients and addresses must be 16 bit 6323 LLVM_DEBUG( 6324 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6325 "require 16 bit args for both gradients and addresses"); 6326 return Op; 6327 } 6328 6329 if (IsA16) { 6330 if (!ST->hasA16()) { 6331 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6332 "support 16 bit addresses\n"); 6333 return Op; 6334 } 6335 } 6336 6337 // We've dealt with incorrect input so we know that if IsA16, IsG16 6338 // are set then we have to compress/pack operands (either address, 6339 // gradient or both) 6340 // In the case where a16 and gradients are tied (no G16 support) then we 6341 // have already verified that both IsA16 and IsG16 are true 6342 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) { 6343 // Activate g16 6344 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6345 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6346 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6347 } 6348 6349 // Add gradients (packed or unpacked) 6350 if (IsG16) { 6351 // Pack the gradients 6352 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6353 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs, 6354 ArgOffset + Intr->GradientStart, 6355 ArgOffset + Intr->CoordStart, Intr->NumGradients); 6356 } else { 6357 for (unsigned I = ArgOffset + Intr->GradientStart; 6358 I < ArgOffset + Intr->CoordStart; I++) 6359 VAddrs.push_back(Op.getOperand(I)); 6360 } 6361 6362 // Add addresses (packed or unpacked) 6363 if (IsA16) { 6364 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs, 6365 ArgOffset + Intr->CoordStart, VAddrEnd, 6366 0 /* No gradients */); 6367 } else { 6368 // Add uncompressed address 6369 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6370 VAddrs.push_back(Op.getOperand(I)); 6371 } 6372 6373 // If the register allocator cannot place the address registers contiguously 6374 // without introducing moves, then using the non-sequential address encoding 6375 // is always preferable, since it saves VALU instructions and is usually a 6376 // wash in terms of code size or even better. 6377 // 6378 // However, we currently have no way of hinting to the register allocator that 6379 // MIMG addresses should be placed contiguously when it is possible to do so, 6380 // so force non-NSA for the common 2-address case as a heuristic. 6381 // 6382 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6383 // allocation when possible. 6384 bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) && 6385 VAddrs.size() >= 3 && 6386 VAddrs.size() <= (unsigned)ST->getNSAMaxSize(); 6387 SDValue VAddr; 6388 if (!UseNSA) 6389 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6390 6391 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6392 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6393 SDValue Unorm; 6394 if (!BaseOpcode->Sampler) { 6395 Unorm = True; 6396 } else { 6397 auto UnormConst = 6398 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6399 6400 Unorm = UnormConst->getZExtValue() ? True : False; 6401 } 6402 6403 SDValue TFE; 6404 SDValue LWE; 6405 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6406 bool IsTexFail = false; 6407 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6408 return Op; 6409 6410 if (IsTexFail) { 6411 if (!DMaskLanes) { 6412 // Expecting to get an error flag since TFC is on - and dmask is 0 6413 // Force dmask to be at least 1 otherwise the instruction will fail 6414 DMask = 0x1; 6415 DMaskLanes = 1; 6416 NumVDataDwords = 1; 6417 } 6418 NumVDataDwords += 1; 6419 AdjustRetType = true; 6420 } 6421 6422 // Has something earlier tagged that the return type needs adjusting 6423 // This happens if the instruction is a load or has set TexFailCtrl flags 6424 if (AdjustRetType) { 6425 // NumVDataDwords reflects the true number of dwords required in the return type 6426 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6427 // This is a no-op load. This can be eliminated 6428 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6429 if (isa<MemSDNode>(Op)) 6430 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6431 return Undef; 6432 } 6433 6434 EVT NewVT = NumVDataDwords > 1 ? 6435 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6436 : MVT::i32; 6437 6438 ResultTypes[0] = NewVT; 6439 if (ResultTypes.size() == 3) { 6440 // Original result was aggregate type used for TexFailCtrl results 6441 // The actual instruction returns as a vector type which has now been 6442 // created. Remove the aggregate result. 6443 ResultTypes.erase(&ResultTypes[1]); 6444 } 6445 } 6446 6447 unsigned CPol = cast<ConstantSDNode>( 6448 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6449 if (BaseOpcode->Atomic) 6450 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6451 if (CPol & ~AMDGPU::CPol::ALL) 6452 return Op; 6453 6454 SmallVector<SDValue, 26> Ops; 6455 if (BaseOpcode->Store || BaseOpcode->Atomic) 6456 Ops.push_back(VData); // vdata 6457 if (UseNSA) 6458 append_range(Ops, VAddrs); 6459 else 6460 Ops.push_back(VAddr); 6461 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6462 if (BaseOpcode->Sampler) 6463 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6464 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6465 if (IsGFX10Plus) 6466 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6467 Ops.push_back(Unorm); 6468 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6469 Ops.push_back(IsA16 && // r128, a16 for gfx9 6470 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6471 if (IsGFX10Plus) 6472 Ops.push_back(IsA16 ? True : False); 6473 if (!Subtarget->hasGFX90AInsts()) { 6474 Ops.push_back(TFE); //tfe 6475 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6476 report_fatal_error("TFE is not supported on this GPU"); 6477 } 6478 Ops.push_back(LWE); // lwe 6479 if (!IsGFX10Plus) 6480 Ops.push_back(DimInfo->DA ? True : False); 6481 if (BaseOpcode->HasD16) 6482 Ops.push_back(IsD16 ? True : False); 6483 if (isa<MemSDNode>(Op)) 6484 Ops.push_back(Op.getOperand(0)); // chain 6485 6486 int NumVAddrDwords = 6487 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6488 int Opcode = -1; 6489 6490 if (IsGFX10Plus) { 6491 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6492 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6493 : AMDGPU::MIMGEncGfx10Default, 6494 NumVDataDwords, NumVAddrDwords); 6495 } else { 6496 if (Subtarget->hasGFX90AInsts()) { 6497 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6498 NumVDataDwords, NumVAddrDwords); 6499 if (Opcode == -1) 6500 report_fatal_error( 6501 "requested image instruction is not supported on this GPU"); 6502 } 6503 if (Opcode == -1 && 6504 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6505 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6506 NumVDataDwords, NumVAddrDwords); 6507 if (Opcode == -1) 6508 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6509 NumVDataDwords, NumVAddrDwords); 6510 } 6511 assert(Opcode != -1); 6512 6513 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6514 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6515 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6516 DAG.setNodeMemRefs(NewNode, {MemRef}); 6517 } 6518 6519 if (BaseOpcode->AtomicX2) { 6520 SmallVector<SDValue, 1> Elt; 6521 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6522 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6523 } 6524 if (BaseOpcode->Store) 6525 return SDValue(NewNode, 0); 6526 return constructRetValue(DAG, NewNode, 6527 OrigResultTypes, IsTexFail, 6528 Subtarget->hasUnpackedD16VMem(), IsD16, 6529 DMaskLanes, NumVDataDwords, DL); 6530 } 6531 6532 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6533 SDValue Offset, SDValue CachePolicy, 6534 SelectionDAG &DAG) const { 6535 MachineFunction &MF = DAG.getMachineFunction(); 6536 6537 const DataLayout &DataLayout = DAG.getDataLayout(); 6538 Align Alignment = 6539 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6540 6541 MachineMemOperand *MMO = MF.getMachineMemOperand( 6542 MachinePointerInfo(), 6543 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6544 MachineMemOperand::MOInvariant, 6545 VT.getStoreSize(), Alignment); 6546 6547 if (!Offset->isDivergent()) { 6548 SDValue Ops[] = { 6549 Rsrc, 6550 Offset, // Offset 6551 CachePolicy 6552 }; 6553 6554 // Widen vec3 load to vec4. 6555 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6556 EVT WidenedVT = 6557 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6558 auto WidenedOp = DAG.getMemIntrinsicNode( 6559 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6560 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6561 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6562 DAG.getVectorIdxConstant(0, DL)); 6563 return Subvector; 6564 } 6565 6566 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6567 DAG.getVTList(VT), Ops, VT, MMO); 6568 } 6569 6570 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6571 // assume that the buffer is unswizzled. 6572 SmallVector<SDValue, 4> Loads; 6573 unsigned NumLoads = 1; 6574 MVT LoadVT = VT.getSimpleVT(); 6575 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6576 assert((LoadVT.getScalarType() == MVT::i32 || 6577 LoadVT.getScalarType() == MVT::f32)); 6578 6579 if (NumElts == 8 || NumElts == 16) { 6580 NumLoads = NumElts / 4; 6581 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6582 } 6583 6584 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6585 SDValue Ops[] = { 6586 DAG.getEntryNode(), // Chain 6587 Rsrc, // rsrc 6588 DAG.getConstant(0, DL, MVT::i32), // vindex 6589 {}, // voffset 6590 {}, // soffset 6591 {}, // offset 6592 CachePolicy, // cachepolicy 6593 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6594 }; 6595 6596 // Use the alignment to ensure that the required offsets will fit into the 6597 // immediate offsets. 6598 setBufferOffsets(Offset, DAG, &Ops[3], 6599 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6600 6601 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6602 for (unsigned i = 0; i < NumLoads; ++i) { 6603 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6604 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6605 LoadVT, MMO, DAG)); 6606 } 6607 6608 if (NumElts == 8 || NumElts == 16) 6609 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6610 6611 return Loads[0]; 6612 } 6613 6614 SDValue SITargetLowering::lowerWorkitemID(SelectionDAG &DAG, SDValue Op, 6615 unsigned Dim, 6616 const ArgDescriptor &Arg) const { 6617 SDLoc SL(Op); 6618 MachineFunction &MF = DAG.getMachineFunction(); 6619 unsigned MaxID = Subtarget->getMaxWorkitemID(MF.getFunction(), Dim); 6620 if (MaxID == 0) 6621 return DAG.getConstant(0, SL, MVT::i32); 6622 6623 SDValue Val = loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6624 SDLoc(DAG.getEntryNode()), Arg); 6625 6626 // Don't bother inserting AssertZext for packed IDs since we're emitting the 6627 // masking operations anyway. 6628 // 6629 // TODO: We could assert the top bit is 0 for the source copy. 6630 if (Arg.isMasked()) 6631 return Val; 6632 6633 // Preserve the known bits after expansion to a copy. 6634 EVT SmallVT = 6635 EVT::getIntegerVT(*DAG.getContext(), 32 - countLeadingZeros(MaxID)); 6636 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Val, 6637 DAG.getValueType(SmallVT)); 6638 } 6639 6640 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6641 SelectionDAG &DAG) const { 6642 MachineFunction &MF = DAG.getMachineFunction(); 6643 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6644 6645 EVT VT = Op.getValueType(); 6646 SDLoc DL(Op); 6647 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6648 6649 // TODO: Should this propagate fast-math-flags? 6650 6651 switch (IntrinsicID) { 6652 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6653 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6654 return emitNonHSAIntrinsicError(DAG, DL, VT); 6655 return getPreloadedValue(DAG, *MFI, VT, 6656 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6657 } 6658 case Intrinsic::amdgcn_dispatch_ptr: 6659 case Intrinsic::amdgcn_queue_ptr: { 6660 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6661 DiagnosticInfoUnsupported BadIntrin( 6662 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6663 DL.getDebugLoc()); 6664 DAG.getContext()->diagnose(BadIntrin); 6665 return DAG.getUNDEF(VT); 6666 } 6667 6668 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6669 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6670 return getPreloadedValue(DAG, *MFI, VT, RegID); 6671 } 6672 case Intrinsic::amdgcn_implicitarg_ptr: { 6673 if (MFI->isEntryFunction()) 6674 return getImplicitArgPtr(DAG, DL); 6675 return getPreloadedValue(DAG, *MFI, VT, 6676 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6677 } 6678 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6679 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6680 // This only makes sense to call in a kernel, so just lower to null. 6681 return DAG.getConstant(0, DL, VT); 6682 } 6683 6684 return getPreloadedValue(DAG, *MFI, VT, 6685 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6686 } 6687 case Intrinsic::amdgcn_dispatch_id: { 6688 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6689 } 6690 case Intrinsic::amdgcn_rcp: 6691 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6692 case Intrinsic::amdgcn_rsq: 6693 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6694 case Intrinsic::amdgcn_rsq_legacy: 6695 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6696 return emitRemovedIntrinsicError(DAG, DL, VT); 6697 return SDValue(); 6698 case Intrinsic::amdgcn_rcp_legacy: 6699 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6700 return emitRemovedIntrinsicError(DAG, DL, VT); 6701 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6702 case Intrinsic::amdgcn_rsq_clamp: { 6703 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6704 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6705 6706 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6707 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6708 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6709 6710 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6711 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6712 DAG.getConstantFP(Max, DL, VT)); 6713 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6714 DAG.getConstantFP(Min, DL, VT)); 6715 } 6716 case Intrinsic::r600_read_ngroups_x: 6717 if (Subtarget->isAmdHsaOS()) 6718 return emitNonHSAIntrinsicError(DAG, DL, VT); 6719 6720 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6721 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6722 false); 6723 case Intrinsic::r600_read_ngroups_y: 6724 if (Subtarget->isAmdHsaOS()) 6725 return emitNonHSAIntrinsicError(DAG, DL, VT); 6726 6727 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6728 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6729 false); 6730 case Intrinsic::r600_read_ngroups_z: 6731 if (Subtarget->isAmdHsaOS()) 6732 return emitNonHSAIntrinsicError(DAG, DL, VT); 6733 6734 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6735 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6736 false); 6737 case Intrinsic::r600_read_global_size_x: 6738 if (Subtarget->isAmdHsaOS()) 6739 return emitNonHSAIntrinsicError(DAG, DL, VT); 6740 6741 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6742 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6743 Align(4), false); 6744 case Intrinsic::r600_read_global_size_y: 6745 if (Subtarget->isAmdHsaOS()) 6746 return emitNonHSAIntrinsicError(DAG, DL, VT); 6747 6748 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6749 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6750 Align(4), false); 6751 case Intrinsic::r600_read_global_size_z: 6752 if (Subtarget->isAmdHsaOS()) 6753 return emitNonHSAIntrinsicError(DAG, DL, VT); 6754 6755 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6756 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6757 Align(4), false); 6758 case Intrinsic::r600_read_local_size_x: 6759 if (Subtarget->isAmdHsaOS()) 6760 return emitNonHSAIntrinsicError(DAG, DL, VT); 6761 6762 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6763 SI::KernelInputOffsets::LOCAL_SIZE_X); 6764 case Intrinsic::r600_read_local_size_y: 6765 if (Subtarget->isAmdHsaOS()) 6766 return emitNonHSAIntrinsicError(DAG, DL, VT); 6767 6768 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6769 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6770 case Intrinsic::r600_read_local_size_z: 6771 if (Subtarget->isAmdHsaOS()) 6772 return emitNonHSAIntrinsicError(DAG, DL, VT); 6773 6774 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6775 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6776 case Intrinsic::amdgcn_workgroup_id_x: 6777 return getPreloadedValue(DAG, *MFI, VT, 6778 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6779 case Intrinsic::amdgcn_workgroup_id_y: 6780 return getPreloadedValue(DAG, *MFI, VT, 6781 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6782 case Intrinsic::amdgcn_workgroup_id_z: 6783 return getPreloadedValue(DAG, *MFI, VT, 6784 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6785 case Intrinsic::amdgcn_workitem_id_x: 6786 return lowerWorkitemID(DAG, Op, 0, MFI->getArgInfo().WorkItemIDX); 6787 case Intrinsic::amdgcn_workitem_id_y: 6788 return lowerWorkitemID(DAG, Op, 1, MFI->getArgInfo().WorkItemIDY); 6789 case Intrinsic::amdgcn_workitem_id_z: 6790 return lowerWorkitemID(DAG, Op, 2, MFI->getArgInfo().WorkItemIDZ); 6791 case Intrinsic::amdgcn_wavefrontsize: 6792 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6793 SDLoc(Op), MVT::i32); 6794 case Intrinsic::amdgcn_s_buffer_load: { 6795 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6796 if (CPol & ~AMDGPU::CPol::ALL) 6797 return Op; 6798 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6799 DAG); 6800 } 6801 case Intrinsic::amdgcn_fdiv_fast: 6802 return lowerFDIV_FAST(Op, DAG); 6803 case Intrinsic::amdgcn_sin: 6804 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6805 6806 case Intrinsic::amdgcn_cos: 6807 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6808 6809 case Intrinsic::amdgcn_mul_u24: 6810 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6811 case Intrinsic::amdgcn_mul_i24: 6812 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6813 6814 case Intrinsic::amdgcn_log_clamp: { 6815 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6816 return SDValue(); 6817 6818 return emitRemovedIntrinsicError(DAG, DL, VT); 6819 } 6820 case Intrinsic::amdgcn_ldexp: 6821 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6822 Op.getOperand(1), Op.getOperand(2)); 6823 6824 case Intrinsic::amdgcn_fract: 6825 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6826 6827 case Intrinsic::amdgcn_class: 6828 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6829 Op.getOperand(1), Op.getOperand(2)); 6830 case Intrinsic::amdgcn_div_fmas: 6831 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6832 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6833 Op.getOperand(4)); 6834 6835 case Intrinsic::amdgcn_div_fixup: 6836 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6837 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6838 6839 case Intrinsic::amdgcn_div_scale: { 6840 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6841 6842 // Translate to the operands expected by the machine instruction. The 6843 // first parameter must be the same as the first instruction. 6844 SDValue Numerator = Op.getOperand(1); 6845 SDValue Denominator = Op.getOperand(2); 6846 6847 // Note this order is opposite of the machine instruction's operations, 6848 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6849 // intrinsic has the numerator as the first operand to match a normal 6850 // division operation. 6851 6852 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator; 6853 6854 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6855 Denominator, Numerator); 6856 } 6857 case Intrinsic::amdgcn_icmp: { 6858 // There is a Pat that handles this variant, so return it as-is. 6859 if (Op.getOperand(1).getValueType() == MVT::i1 && 6860 Op.getConstantOperandVal(2) == 0 && 6861 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6862 return Op; 6863 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6864 } 6865 case Intrinsic::amdgcn_fcmp: { 6866 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6867 } 6868 case Intrinsic::amdgcn_ballot: 6869 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6870 case Intrinsic::amdgcn_fmed3: 6871 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6872 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6873 case Intrinsic::amdgcn_fdot2: 6874 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6875 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6876 Op.getOperand(4)); 6877 case Intrinsic::amdgcn_fmul_legacy: 6878 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6879 Op.getOperand(1), Op.getOperand(2)); 6880 case Intrinsic::amdgcn_sffbh: 6881 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6882 case Intrinsic::amdgcn_sbfe: 6883 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6884 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6885 case Intrinsic::amdgcn_ubfe: 6886 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6887 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6888 case Intrinsic::amdgcn_cvt_pkrtz: 6889 case Intrinsic::amdgcn_cvt_pknorm_i16: 6890 case Intrinsic::amdgcn_cvt_pknorm_u16: 6891 case Intrinsic::amdgcn_cvt_pk_i16: 6892 case Intrinsic::amdgcn_cvt_pk_u16: { 6893 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6894 EVT VT = Op.getValueType(); 6895 unsigned Opcode; 6896 6897 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6898 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6899 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6900 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6901 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6902 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6903 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6904 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6905 else 6906 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6907 6908 if (isTypeLegal(VT)) 6909 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6910 6911 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6912 Op.getOperand(1), Op.getOperand(2)); 6913 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6914 } 6915 case Intrinsic::amdgcn_fmad_ftz: 6916 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6917 Op.getOperand(2), Op.getOperand(3)); 6918 6919 case Intrinsic::amdgcn_if_break: 6920 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6921 Op->getOperand(1), Op->getOperand(2)), 0); 6922 6923 case Intrinsic::amdgcn_groupstaticsize: { 6924 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6925 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6926 return Op; 6927 6928 const Module *M = MF.getFunction().getParent(); 6929 const GlobalValue *GV = 6930 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6931 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6932 SIInstrInfo::MO_ABS32_LO); 6933 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6934 } 6935 case Intrinsic::amdgcn_is_shared: 6936 case Intrinsic::amdgcn_is_private: { 6937 SDLoc SL(Op); 6938 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6939 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6940 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6941 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6942 Op.getOperand(1)); 6943 6944 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6945 DAG.getConstant(1, SL, MVT::i32)); 6946 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6947 } 6948 case Intrinsic::amdgcn_perm: 6949 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1), 6950 Op.getOperand(2), Op.getOperand(3)); 6951 case Intrinsic::amdgcn_reloc_constant: { 6952 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6953 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6954 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6955 auto RelocSymbol = cast<GlobalVariable>( 6956 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6957 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6958 SIInstrInfo::MO_ABS32_LO); 6959 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6960 } 6961 default: 6962 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6963 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6964 return lowerImage(Op, ImageDimIntr, DAG, false); 6965 6966 return Op; 6967 } 6968 } 6969 6970 /// Update \p MMO based on the offset inputs to an intrinsic. 6971 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset, 6972 SDValue SOffset, SDValue Offset, 6973 SDValue VIndex = SDValue()) { 6974 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6975 !isa<ConstantSDNode>(Offset)) { 6976 // The combined offset is not known to be constant, so we cannot represent 6977 // it in the MMO. Give up. 6978 MMO->setValue((Value *)nullptr); 6979 return; 6980 } 6981 6982 if (VIndex && (!isa<ConstantSDNode>(VIndex) || 6983 !cast<ConstantSDNode>(VIndex)->isZero())) { 6984 // The strided index component of the address is not known to be zero, so we 6985 // cannot represent it in the MMO. Give up. 6986 MMO->setValue((Value *)nullptr); 6987 return; 6988 } 6989 6990 MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() + 6991 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6992 cast<ConstantSDNode>(Offset)->getSExtValue()); 6993 } 6994 6995 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6996 SelectionDAG &DAG, 6997 unsigned NewOpcode) const { 6998 SDLoc DL(Op); 6999 7000 SDValue VData = Op.getOperand(2); 7001 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7002 SDValue Ops[] = { 7003 Op.getOperand(0), // Chain 7004 VData, // vdata 7005 Op.getOperand(3), // rsrc 7006 DAG.getConstant(0, DL, MVT::i32), // vindex 7007 Offsets.first, // voffset 7008 Op.getOperand(5), // soffset 7009 Offsets.second, // offset 7010 Op.getOperand(6), // cachepolicy 7011 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7012 }; 7013 7014 auto *M = cast<MemSDNode>(Op); 7015 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 7016 7017 EVT MemVT = VData.getValueType(); 7018 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7019 M->getMemOperand()); 7020 } 7021 7022 // Return a value to use for the idxen operand by examining the vindex operand. 7023 static unsigned getIdxEn(SDValue VIndex) { 7024 if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex)) 7025 // No need to set idxen if vindex is known to be zero. 7026 return VIndexC->getZExtValue() != 0; 7027 return 1; 7028 } 7029 7030 SDValue 7031 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 7032 unsigned NewOpcode) const { 7033 SDLoc DL(Op); 7034 7035 SDValue VData = Op.getOperand(2); 7036 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7037 SDValue Ops[] = { 7038 Op.getOperand(0), // Chain 7039 VData, // vdata 7040 Op.getOperand(3), // rsrc 7041 Op.getOperand(4), // vindex 7042 Offsets.first, // voffset 7043 Op.getOperand(6), // soffset 7044 Offsets.second, // offset 7045 Op.getOperand(7), // cachepolicy 7046 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7047 }; 7048 7049 auto *M = cast<MemSDNode>(Op); 7050 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7051 7052 EVT MemVT = VData.getValueType(); 7053 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7054 M->getMemOperand()); 7055 } 7056 7057 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 7058 SelectionDAG &DAG) const { 7059 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7060 SDLoc DL(Op); 7061 7062 switch (IntrID) { 7063 case Intrinsic::amdgcn_ds_ordered_add: 7064 case Intrinsic::amdgcn_ds_ordered_swap: { 7065 MemSDNode *M = cast<MemSDNode>(Op); 7066 SDValue Chain = M->getOperand(0); 7067 SDValue M0 = M->getOperand(2); 7068 SDValue Value = M->getOperand(3); 7069 unsigned IndexOperand = M->getConstantOperandVal(7); 7070 unsigned WaveRelease = M->getConstantOperandVal(8); 7071 unsigned WaveDone = M->getConstantOperandVal(9); 7072 7073 unsigned OrderedCountIndex = IndexOperand & 0x3f; 7074 IndexOperand &= ~0x3f; 7075 unsigned CountDw = 0; 7076 7077 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 7078 CountDw = (IndexOperand >> 24) & 0xf; 7079 IndexOperand &= ~(0xf << 24); 7080 7081 if (CountDw < 1 || CountDw > 4) { 7082 report_fatal_error( 7083 "ds_ordered_count: dword count must be between 1 and 4"); 7084 } 7085 } 7086 7087 if (IndexOperand) 7088 report_fatal_error("ds_ordered_count: bad index operand"); 7089 7090 if (WaveDone && !WaveRelease) 7091 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 7092 7093 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 7094 unsigned ShaderType = 7095 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 7096 unsigned Offset0 = OrderedCountIndex << 2; 7097 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 7098 (Instruction << 4); 7099 7100 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 7101 Offset1 |= (CountDw - 1) << 6; 7102 7103 unsigned Offset = Offset0 | (Offset1 << 8); 7104 7105 SDValue Ops[] = { 7106 Chain, 7107 Value, 7108 DAG.getTargetConstant(Offset, DL, MVT::i16), 7109 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 7110 }; 7111 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 7112 M->getVTList(), Ops, M->getMemoryVT(), 7113 M->getMemOperand()); 7114 } 7115 case Intrinsic::amdgcn_ds_fadd: { 7116 MemSDNode *M = cast<MemSDNode>(Op); 7117 unsigned Opc; 7118 switch (IntrID) { 7119 case Intrinsic::amdgcn_ds_fadd: 7120 Opc = ISD::ATOMIC_LOAD_FADD; 7121 break; 7122 } 7123 7124 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 7125 M->getOperand(0), M->getOperand(2), M->getOperand(3), 7126 M->getMemOperand()); 7127 } 7128 case Intrinsic::amdgcn_atomic_inc: 7129 case Intrinsic::amdgcn_atomic_dec: 7130 case Intrinsic::amdgcn_ds_fmin: 7131 case Intrinsic::amdgcn_ds_fmax: { 7132 MemSDNode *M = cast<MemSDNode>(Op); 7133 unsigned Opc; 7134 switch (IntrID) { 7135 case Intrinsic::amdgcn_atomic_inc: 7136 Opc = AMDGPUISD::ATOMIC_INC; 7137 break; 7138 case Intrinsic::amdgcn_atomic_dec: 7139 Opc = AMDGPUISD::ATOMIC_DEC; 7140 break; 7141 case Intrinsic::amdgcn_ds_fmin: 7142 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 7143 break; 7144 case Intrinsic::amdgcn_ds_fmax: 7145 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 7146 break; 7147 default: 7148 llvm_unreachable("Unknown intrinsic!"); 7149 } 7150 SDValue Ops[] = { 7151 M->getOperand(0), // Chain 7152 M->getOperand(2), // Ptr 7153 M->getOperand(3) // Value 7154 }; 7155 7156 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 7157 M->getMemoryVT(), M->getMemOperand()); 7158 } 7159 case Intrinsic::amdgcn_buffer_load: 7160 case Intrinsic::amdgcn_buffer_load_format: { 7161 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 7162 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7163 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7164 SDValue Ops[] = { 7165 Op.getOperand(0), // Chain 7166 Op.getOperand(2), // rsrc 7167 Op.getOperand(3), // vindex 7168 SDValue(), // voffset -- will be set by setBufferOffsets 7169 SDValue(), // soffset -- will be set by setBufferOffsets 7170 SDValue(), // offset -- will be set by setBufferOffsets 7171 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7172 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7173 }; 7174 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 7175 7176 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 7177 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 7178 7179 EVT VT = Op.getValueType(); 7180 EVT IntVT = VT.changeTypeToInteger(); 7181 auto *M = cast<MemSDNode>(Op); 7182 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7183 EVT LoadVT = Op.getValueType(); 7184 7185 if (LoadVT.getScalarType() == MVT::f16) 7186 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 7187 M, DAG, Ops); 7188 7189 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 7190 if (LoadVT.getScalarType() == MVT::i8 || 7191 LoadVT.getScalarType() == MVT::i16) 7192 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 7193 7194 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 7195 M->getMemOperand(), DAG); 7196 } 7197 case Intrinsic::amdgcn_raw_buffer_load: 7198 case Intrinsic::amdgcn_raw_buffer_load_format: { 7199 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 7200 7201 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7202 SDValue Ops[] = { 7203 Op.getOperand(0), // Chain 7204 Op.getOperand(2), // rsrc 7205 DAG.getConstant(0, DL, MVT::i32), // vindex 7206 Offsets.first, // voffset 7207 Op.getOperand(4), // soffset 7208 Offsets.second, // offset 7209 Op.getOperand(5), // cachepolicy, swizzled buffer 7210 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7211 }; 7212 7213 auto *M = cast<MemSDNode>(Op); 7214 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]); 7215 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 7216 } 7217 case Intrinsic::amdgcn_struct_buffer_load: 7218 case Intrinsic::amdgcn_struct_buffer_load_format: { 7219 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7220 7221 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7222 SDValue Ops[] = { 7223 Op.getOperand(0), // Chain 7224 Op.getOperand(2), // rsrc 7225 Op.getOperand(3), // vindex 7226 Offsets.first, // voffset 7227 Op.getOperand(5), // soffset 7228 Offsets.second, // offset 7229 Op.getOperand(6), // cachepolicy, swizzled buffer 7230 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7231 }; 7232 7233 auto *M = cast<MemSDNode>(Op); 7234 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7235 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7236 } 7237 case Intrinsic::amdgcn_tbuffer_load: { 7238 MemSDNode *M = cast<MemSDNode>(Op); 7239 EVT LoadVT = Op.getValueType(); 7240 7241 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7242 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7243 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7244 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7245 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7246 SDValue Ops[] = { 7247 Op.getOperand(0), // Chain 7248 Op.getOperand(2), // rsrc 7249 Op.getOperand(3), // vindex 7250 Op.getOperand(4), // voffset 7251 Op.getOperand(5), // soffset 7252 Op.getOperand(6), // offset 7253 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7254 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7255 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7256 }; 7257 7258 if (LoadVT.getScalarType() == MVT::f16) 7259 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7260 M, DAG, Ops); 7261 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7262 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7263 DAG); 7264 } 7265 case Intrinsic::amdgcn_raw_tbuffer_load: { 7266 MemSDNode *M = cast<MemSDNode>(Op); 7267 EVT LoadVT = Op.getValueType(); 7268 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7269 7270 SDValue Ops[] = { 7271 Op.getOperand(0), // Chain 7272 Op.getOperand(2), // rsrc 7273 DAG.getConstant(0, DL, MVT::i32), // vindex 7274 Offsets.first, // voffset 7275 Op.getOperand(4), // soffset 7276 Offsets.second, // offset 7277 Op.getOperand(5), // format 7278 Op.getOperand(6), // cachepolicy, swizzled buffer 7279 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7280 }; 7281 7282 if (LoadVT.getScalarType() == MVT::f16) 7283 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7284 M, DAG, Ops); 7285 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7286 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7287 DAG); 7288 } 7289 case Intrinsic::amdgcn_struct_tbuffer_load: { 7290 MemSDNode *M = cast<MemSDNode>(Op); 7291 EVT LoadVT = Op.getValueType(); 7292 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7293 7294 SDValue Ops[] = { 7295 Op.getOperand(0), // Chain 7296 Op.getOperand(2), // rsrc 7297 Op.getOperand(3), // vindex 7298 Offsets.first, // voffset 7299 Op.getOperand(5), // soffset 7300 Offsets.second, // offset 7301 Op.getOperand(6), // format 7302 Op.getOperand(7), // cachepolicy, swizzled buffer 7303 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7304 }; 7305 7306 if (LoadVT.getScalarType() == MVT::f16) 7307 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7308 M, DAG, Ops); 7309 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7310 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7311 DAG); 7312 } 7313 case Intrinsic::amdgcn_buffer_atomic_swap: 7314 case Intrinsic::amdgcn_buffer_atomic_add: 7315 case Intrinsic::amdgcn_buffer_atomic_sub: 7316 case Intrinsic::amdgcn_buffer_atomic_csub: 7317 case Intrinsic::amdgcn_buffer_atomic_smin: 7318 case Intrinsic::amdgcn_buffer_atomic_umin: 7319 case Intrinsic::amdgcn_buffer_atomic_smax: 7320 case Intrinsic::amdgcn_buffer_atomic_umax: 7321 case Intrinsic::amdgcn_buffer_atomic_and: 7322 case Intrinsic::amdgcn_buffer_atomic_or: 7323 case Intrinsic::amdgcn_buffer_atomic_xor: 7324 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7325 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7326 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7327 SDValue Ops[] = { 7328 Op.getOperand(0), // Chain 7329 Op.getOperand(2), // vdata 7330 Op.getOperand(3), // rsrc 7331 Op.getOperand(4), // vindex 7332 SDValue(), // voffset -- will be set by setBufferOffsets 7333 SDValue(), // soffset -- will be set by setBufferOffsets 7334 SDValue(), // offset -- will be set by setBufferOffsets 7335 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7336 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7337 }; 7338 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7339 7340 EVT VT = Op.getValueType(); 7341 7342 auto *M = cast<MemSDNode>(Op); 7343 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7344 unsigned Opcode = 0; 7345 7346 switch (IntrID) { 7347 case Intrinsic::amdgcn_buffer_atomic_swap: 7348 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7349 break; 7350 case Intrinsic::amdgcn_buffer_atomic_add: 7351 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7352 break; 7353 case Intrinsic::amdgcn_buffer_atomic_sub: 7354 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7355 break; 7356 case Intrinsic::amdgcn_buffer_atomic_csub: 7357 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7358 break; 7359 case Intrinsic::amdgcn_buffer_atomic_smin: 7360 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7361 break; 7362 case Intrinsic::amdgcn_buffer_atomic_umin: 7363 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7364 break; 7365 case Intrinsic::amdgcn_buffer_atomic_smax: 7366 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7367 break; 7368 case Intrinsic::amdgcn_buffer_atomic_umax: 7369 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7370 break; 7371 case Intrinsic::amdgcn_buffer_atomic_and: 7372 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7373 break; 7374 case Intrinsic::amdgcn_buffer_atomic_or: 7375 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7376 break; 7377 case Intrinsic::amdgcn_buffer_atomic_xor: 7378 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7379 break; 7380 case Intrinsic::amdgcn_buffer_atomic_fadd: 7381 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7382 DiagnosticInfoUnsupported 7383 NoFpRet(DAG.getMachineFunction().getFunction(), 7384 "return versions of fp atomics not supported", 7385 DL.getDebugLoc(), DS_Error); 7386 DAG.getContext()->diagnose(NoFpRet); 7387 return SDValue(); 7388 } 7389 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7390 break; 7391 default: 7392 llvm_unreachable("unhandled atomic opcode"); 7393 } 7394 7395 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7396 M->getMemOperand()); 7397 } 7398 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7399 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7400 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7401 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7402 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7403 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7404 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7405 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7406 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7407 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7408 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7409 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7410 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7411 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7412 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7413 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7414 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7415 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7416 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7417 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7418 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7419 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7420 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7421 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7422 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7423 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7424 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7425 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7426 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7427 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7428 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7429 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7430 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7431 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7432 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7433 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7434 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7435 return lowerStructBufferAtomicIntrin(Op, DAG, 7436 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7437 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7438 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7439 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7440 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7441 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7442 return lowerStructBufferAtomicIntrin(Op, DAG, 7443 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7444 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7445 return lowerStructBufferAtomicIntrin(Op, DAG, 7446 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7447 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7448 return lowerStructBufferAtomicIntrin(Op, DAG, 7449 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7450 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7451 return lowerStructBufferAtomicIntrin(Op, DAG, 7452 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7453 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7454 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7455 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7456 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7457 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7458 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7459 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7460 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7461 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7462 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7463 7464 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7465 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7466 unsigned IdxEn = getIdxEn(Op.getOperand(5)); 7467 SDValue Ops[] = { 7468 Op.getOperand(0), // Chain 7469 Op.getOperand(2), // src 7470 Op.getOperand(3), // cmp 7471 Op.getOperand(4), // rsrc 7472 Op.getOperand(5), // vindex 7473 SDValue(), // voffset -- will be set by setBufferOffsets 7474 SDValue(), // soffset -- will be set by setBufferOffsets 7475 SDValue(), // offset -- will be set by setBufferOffsets 7476 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7477 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7478 }; 7479 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7480 7481 EVT VT = Op.getValueType(); 7482 auto *M = cast<MemSDNode>(Op); 7483 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7484 7485 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7486 Op->getVTList(), Ops, VT, M->getMemOperand()); 7487 } 7488 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7489 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7490 SDValue Ops[] = { 7491 Op.getOperand(0), // Chain 7492 Op.getOperand(2), // src 7493 Op.getOperand(3), // cmp 7494 Op.getOperand(4), // rsrc 7495 DAG.getConstant(0, DL, MVT::i32), // vindex 7496 Offsets.first, // voffset 7497 Op.getOperand(6), // soffset 7498 Offsets.second, // offset 7499 Op.getOperand(7), // cachepolicy 7500 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7501 }; 7502 EVT VT = Op.getValueType(); 7503 auto *M = cast<MemSDNode>(Op); 7504 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]); 7505 7506 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7507 Op->getVTList(), Ops, VT, M->getMemOperand()); 7508 } 7509 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7510 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7511 SDValue Ops[] = { 7512 Op.getOperand(0), // Chain 7513 Op.getOperand(2), // src 7514 Op.getOperand(3), // cmp 7515 Op.getOperand(4), // rsrc 7516 Op.getOperand(5), // vindex 7517 Offsets.first, // voffset 7518 Op.getOperand(7), // soffset 7519 Offsets.second, // offset 7520 Op.getOperand(8), // cachepolicy 7521 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7522 }; 7523 EVT VT = Op.getValueType(); 7524 auto *M = cast<MemSDNode>(Op); 7525 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7526 7527 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7528 Op->getVTList(), Ops, VT, M->getMemOperand()); 7529 } 7530 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7531 MemSDNode *M = cast<MemSDNode>(Op); 7532 SDValue NodePtr = M->getOperand(2); 7533 SDValue RayExtent = M->getOperand(3); 7534 SDValue RayOrigin = M->getOperand(4); 7535 SDValue RayDir = M->getOperand(5); 7536 SDValue RayInvDir = M->getOperand(6); 7537 SDValue TDescr = M->getOperand(7); 7538 7539 assert(NodePtr.getValueType() == MVT::i32 || 7540 NodePtr.getValueType() == MVT::i64); 7541 assert(RayDir.getValueType() == MVT::v3f16 || 7542 RayDir.getValueType() == MVT::v3f32); 7543 7544 if (!Subtarget->hasGFX10_AEncoding()) { 7545 emitRemovedIntrinsicError(DAG, DL, Op.getValueType()); 7546 return SDValue(); 7547 } 7548 7549 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7550 const bool Is64 = NodePtr.getValueType() == MVT::i64; 7551 const unsigned NumVDataDwords = 4; 7552 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11); 7553 const bool UseNSA = Subtarget->hasNSAEncoding() && 7554 NumVAddrDwords <= Subtarget->getNSAMaxSize(); 7555 const unsigned BaseOpcodes[2][2] = { 7556 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16}, 7557 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY, 7558 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}}; 7559 int Opcode; 7560 if (UseNSA) { 7561 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16], 7562 AMDGPU::MIMGEncGfx10NSA, NumVDataDwords, 7563 NumVAddrDwords); 7564 } else { 7565 Opcode = AMDGPU::getMIMGOpcode( 7566 BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords, 7567 PowerOf2Ceil(NumVAddrDwords)); 7568 } 7569 assert(Opcode != -1); 7570 7571 SmallVector<SDValue, 16> Ops; 7572 7573 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7574 SmallVector<SDValue, 3> Lanes; 7575 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7576 if (Lanes[0].getValueSizeInBits() == 32) { 7577 for (unsigned I = 0; I < 3; ++I) 7578 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7579 } else { 7580 if (IsAligned) { 7581 Ops.push_back( 7582 DAG.getBitcast(MVT::i32, 7583 DAG.getBuildVector(MVT::v2f16, DL, 7584 { Lanes[0], Lanes[1] }))); 7585 Ops.push_back(Lanes[2]); 7586 } else { 7587 SDValue Elt0 = Ops.pop_back_val(); 7588 Ops.push_back( 7589 DAG.getBitcast(MVT::i32, 7590 DAG.getBuildVector(MVT::v2f16, DL, 7591 { Elt0, Lanes[0] }))); 7592 Ops.push_back( 7593 DAG.getBitcast(MVT::i32, 7594 DAG.getBuildVector(MVT::v2f16, DL, 7595 { Lanes[1], Lanes[2] }))); 7596 } 7597 } 7598 }; 7599 7600 if (Is64) 7601 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7602 else 7603 Ops.push_back(NodePtr); 7604 7605 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7606 packLanes(RayOrigin, true); 7607 packLanes(RayDir, true); 7608 packLanes(RayInvDir, false); 7609 7610 if (!UseNSA) { 7611 // Build a single vector containing all the operands so far prepared. 7612 if (NumVAddrDwords > 8) { 7613 SDValue Undef = DAG.getUNDEF(MVT::i32); 7614 Ops.append(16 - Ops.size(), Undef); 7615 } 7616 assert(Ops.size() == 8 || Ops.size() == 16); 7617 SDValue MergedOps = DAG.getBuildVector( 7618 Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops); 7619 Ops.clear(); 7620 Ops.push_back(MergedOps); 7621 } 7622 7623 Ops.push_back(TDescr); 7624 if (IsA16) 7625 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7626 Ops.push_back(M->getChain()); 7627 7628 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7629 MachineMemOperand *MemRef = M->getMemOperand(); 7630 DAG.setNodeMemRefs(NewNode, {MemRef}); 7631 return SDValue(NewNode, 0); 7632 } 7633 case Intrinsic::amdgcn_global_atomic_fadd: 7634 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7635 DiagnosticInfoUnsupported 7636 NoFpRet(DAG.getMachineFunction().getFunction(), 7637 "return versions of fp atomics not supported", 7638 DL.getDebugLoc(), DS_Error); 7639 DAG.getContext()->diagnose(NoFpRet); 7640 return SDValue(); 7641 } 7642 LLVM_FALLTHROUGH; 7643 case Intrinsic::amdgcn_global_atomic_fmin: 7644 case Intrinsic::amdgcn_global_atomic_fmax: 7645 case Intrinsic::amdgcn_flat_atomic_fadd: 7646 case Intrinsic::amdgcn_flat_atomic_fmin: 7647 case Intrinsic::amdgcn_flat_atomic_fmax: { 7648 MemSDNode *M = cast<MemSDNode>(Op); 7649 SDValue Ops[] = { 7650 M->getOperand(0), // Chain 7651 M->getOperand(2), // Ptr 7652 M->getOperand(3) // Value 7653 }; 7654 unsigned Opcode = 0; 7655 switch (IntrID) { 7656 case Intrinsic::amdgcn_global_atomic_fadd: 7657 case Intrinsic::amdgcn_flat_atomic_fadd: { 7658 EVT VT = Op.getOperand(3).getValueType(); 7659 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7660 DAG.getVTList(VT, MVT::Other), Ops, 7661 M->getMemOperand()); 7662 } 7663 case Intrinsic::amdgcn_global_atomic_fmin: 7664 case Intrinsic::amdgcn_flat_atomic_fmin: { 7665 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7666 break; 7667 } 7668 case Intrinsic::amdgcn_global_atomic_fmax: 7669 case Intrinsic::amdgcn_flat_atomic_fmax: { 7670 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7671 break; 7672 } 7673 default: 7674 llvm_unreachable("unhandled atomic opcode"); 7675 } 7676 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7677 M->getVTList(), Ops, M->getMemoryVT(), 7678 M->getMemOperand()); 7679 } 7680 default: 7681 7682 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7683 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7684 return lowerImage(Op, ImageDimIntr, DAG, true); 7685 7686 return SDValue(); 7687 } 7688 } 7689 7690 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7691 // dwordx4 if on SI. 7692 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7693 SDVTList VTList, 7694 ArrayRef<SDValue> Ops, EVT MemVT, 7695 MachineMemOperand *MMO, 7696 SelectionDAG &DAG) const { 7697 EVT VT = VTList.VTs[0]; 7698 EVT WidenedVT = VT; 7699 EVT WidenedMemVT = MemVT; 7700 if (!Subtarget->hasDwordx3LoadStores() && 7701 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7702 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7703 WidenedVT.getVectorElementType(), 4); 7704 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7705 WidenedMemVT.getVectorElementType(), 4); 7706 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7707 } 7708 7709 assert(VTList.NumVTs == 2); 7710 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7711 7712 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7713 WidenedMemVT, MMO); 7714 if (WidenedVT != VT) { 7715 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7716 DAG.getVectorIdxConstant(0, DL)); 7717 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7718 } 7719 return NewOp; 7720 } 7721 7722 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7723 bool ImageStore) const { 7724 EVT StoreVT = VData.getValueType(); 7725 7726 // No change for f16 and legal vector D16 types. 7727 if (!StoreVT.isVector()) 7728 return VData; 7729 7730 SDLoc DL(VData); 7731 unsigned NumElements = StoreVT.getVectorNumElements(); 7732 7733 if (Subtarget->hasUnpackedD16VMem()) { 7734 // We need to unpack the packed data to store. 7735 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7736 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7737 7738 EVT EquivStoreVT = 7739 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7740 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7741 return DAG.UnrollVectorOp(ZExt.getNode()); 7742 } 7743 7744 // The sq block of gfx8.1 does not estimate register use correctly for d16 7745 // image store instructions. The data operand is computed as if it were not a 7746 // d16 image instruction. 7747 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7748 // Bitcast to i16 7749 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7750 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7751 7752 // Decompose into scalars 7753 SmallVector<SDValue, 4> Elts; 7754 DAG.ExtractVectorElements(IntVData, Elts); 7755 7756 // Group pairs of i16 into v2i16 and bitcast to i32 7757 SmallVector<SDValue, 4> PackedElts; 7758 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7759 SDValue Pair = 7760 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7761 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7762 PackedElts.push_back(IntPair); 7763 } 7764 if ((NumElements % 2) == 1) { 7765 // Handle v3i16 7766 unsigned I = Elts.size() / 2; 7767 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7768 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7769 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7770 PackedElts.push_back(IntPair); 7771 } 7772 7773 // Pad using UNDEF 7774 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7775 7776 // Build final vector 7777 EVT VecVT = 7778 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7779 return DAG.getBuildVector(VecVT, DL, PackedElts); 7780 } 7781 7782 if (NumElements == 3) { 7783 EVT IntStoreVT = 7784 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7785 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7786 7787 EVT WidenedStoreVT = EVT::getVectorVT( 7788 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7789 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7790 WidenedStoreVT.getStoreSizeInBits()); 7791 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7792 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7793 } 7794 7795 assert(isTypeLegal(StoreVT)); 7796 return VData; 7797 } 7798 7799 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7800 SelectionDAG &DAG) const { 7801 SDLoc DL(Op); 7802 SDValue Chain = Op.getOperand(0); 7803 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7804 MachineFunction &MF = DAG.getMachineFunction(); 7805 7806 switch (IntrinsicID) { 7807 case Intrinsic::amdgcn_exp_compr: { 7808 SDValue Src0 = Op.getOperand(4); 7809 SDValue Src1 = Op.getOperand(5); 7810 // Hack around illegal type on SI by directly selecting it. 7811 if (isTypeLegal(Src0.getValueType())) 7812 return SDValue(); 7813 7814 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7815 SDValue Undef = DAG.getUNDEF(MVT::f32); 7816 const SDValue Ops[] = { 7817 Op.getOperand(2), // tgt 7818 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7819 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7820 Undef, // src2 7821 Undef, // src3 7822 Op.getOperand(7), // vm 7823 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7824 Op.getOperand(3), // en 7825 Op.getOperand(0) // Chain 7826 }; 7827 7828 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7829 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7830 } 7831 case Intrinsic::amdgcn_s_barrier: { 7832 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7833 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7834 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7835 if (WGSize <= ST.getWavefrontSize()) 7836 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7837 Op.getOperand(0)), 0); 7838 } 7839 return SDValue(); 7840 }; 7841 case Intrinsic::amdgcn_tbuffer_store: { 7842 SDValue VData = Op.getOperand(2); 7843 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7844 if (IsD16) 7845 VData = handleD16VData(VData, DAG); 7846 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7847 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7848 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7849 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7850 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7851 SDValue Ops[] = { 7852 Chain, 7853 VData, // vdata 7854 Op.getOperand(3), // rsrc 7855 Op.getOperand(4), // vindex 7856 Op.getOperand(5), // voffset 7857 Op.getOperand(6), // soffset 7858 Op.getOperand(7), // offset 7859 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7860 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7861 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7862 }; 7863 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7864 AMDGPUISD::TBUFFER_STORE_FORMAT; 7865 MemSDNode *M = cast<MemSDNode>(Op); 7866 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7867 M->getMemoryVT(), M->getMemOperand()); 7868 } 7869 7870 case Intrinsic::amdgcn_struct_tbuffer_store: { 7871 SDValue VData = Op.getOperand(2); 7872 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7873 if (IsD16) 7874 VData = handleD16VData(VData, DAG); 7875 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7876 SDValue Ops[] = { 7877 Chain, 7878 VData, // vdata 7879 Op.getOperand(3), // rsrc 7880 Op.getOperand(4), // vindex 7881 Offsets.first, // voffset 7882 Op.getOperand(6), // soffset 7883 Offsets.second, // offset 7884 Op.getOperand(7), // format 7885 Op.getOperand(8), // cachepolicy, swizzled buffer 7886 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7887 }; 7888 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7889 AMDGPUISD::TBUFFER_STORE_FORMAT; 7890 MemSDNode *M = cast<MemSDNode>(Op); 7891 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7892 M->getMemoryVT(), M->getMemOperand()); 7893 } 7894 7895 case Intrinsic::amdgcn_raw_tbuffer_store: { 7896 SDValue VData = Op.getOperand(2); 7897 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7898 if (IsD16) 7899 VData = handleD16VData(VData, DAG); 7900 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7901 SDValue Ops[] = { 7902 Chain, 7903 VData, // vdata 7904 Op.getOperand(3), // rsrc 7905 DAG.getConstant(0, DL, MVT::i32), // vindex 7906 Offsets.first, // voffset 7907 Op.getOperand(5), // soffset 7908 Offsets.second, // offset 7909 Op.getOperand(6), // format 7910 Op.getOperand(7), // cachepolicy, swizzled buffer 7911 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7912 }; 7913 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7914 AMDGPUISD::TBUFFER_STORE_FORMAT; 7915 MemSDNode *M = cast<MemSDNode>(Op); 7916 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7917 M->getMemoryVT(), M->getMemOperand()); 7918 } 7919 7920 case Intrinsic::amdgcn_buffer_store: 7921 case Intrinsic::amdgcn_buffer_store_format: { 7922 SDValue VData = Op.getOperand(2); 7923 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7924 if (IsD16) 7925 VData = handleD16VData(VData, DAG); 7926 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7927 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7928 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7929 SDValue Ops[] = { 7930 Chain, 7931 VData, 7932 Op.getOperand(3), // rsrc 7933 Op.getOperand(4), // vindex 7934 SDValue(), // voffset -- will be set by setBufferOffsets 7935 SDValue(), // soffset -- will be set by setBufferOffsets 7936 SDValue(), // offset -- will be set by setBufferOffsets 7937 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7938 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7939 }; 7940 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7941 7942 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7943 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7944 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7945 MemSDNode *M = cast<MemSDNode>(Op); 7946 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7947 7948 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7949 EVT VDataType = VData.getValueType().getScalarType(); 7950 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7951 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7952 7953 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7954 M->getMemoryVT(), M->getMemOperand()); 7955 } 7956 7957 case Intrinsic::amdgcn_raw_buffer_store: 7958 case Intrinsic::amdgcn_raw_buffer_store_format: { 7959 const bool IsFormat = 7960 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7961 7962 SDValue VData = Op.getOperand(2); 7963 EVT VDataVT = VData.getValueType(); 7964 EVT EltType = VDataVT.getScalarType(); 7965 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7966 if (IsD16) { 7967 VData = handleD16VData(VData, DAG); 7968 VDataVT = VData.getValueType(); 7969 } 7970 7971 if (!isTypeLegal(VDataVT)) { 7972 VData = 7973 DAG.getNode(ISD::BITCAST, DL, 7974 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7975 } 7976 7977 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7978 SDValue Ops[] = { 7979 Chain, 7980 VData, 7981 Op.getOperand(3), // rsrc 7982 DAG.getConstant(0, DL, MVT::i32), // vindex 7983 Offsets.first, // voffset 7984 Op.getOperand(5), // soffset 7985 Offsets.second, // offset 7986 Op.getOperand(6), // cachepolicy, swizzled buffer 7987 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7988 }; 7989 unsigned Opc = 7990 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7991 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7992 MemSDNode *M = cast<MemSDNode>(Op); 7993 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 7994 7995 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7996 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7997 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7998 7999 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8000 M->getMemoryVT(), M->getMemOperand()); 8001 } 8002 8003 case Intrinsic::amdgcn_struct_buffer_store: 8004 case Intrinsic::amdgcn_struct_buffer_store_format: { 8005 const bool IsFormat = 8006 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 8007 8008 SDValue VData = Op.getOperand(2); 8009 EVT VDataVT = VData.getValueType(); 8010 EVT EltType = VDataVT.getScalarType(); 8011 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 8012 8013 if (IsD16) { 8014 VData = handleD16VData(VData, DAG); 8015 VDataVT = VData.getValueType(); 8016 } 8017 8018 if (!isTypeLegal(VDataVT)) { 8019 VData = 8020 DAG.getNode(ISD::BITCAST, DL, 8021 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 8022 } 8023 8024 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 8025 SDValue Ops[] = { 8026 Chain, 8027 VData, 8028 Op.getOperand(3), // rsrc 8029 Op.getOperand(4), // vindex 8030 Offsets.first, // voffset 8031 Op.getOperand(6), // soffset 8032 Offsets.second, // offset 8033 Op.getOperand(7), // cachepolicy, swizzled buffer 8034 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 8035 }; 8036 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 8037 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8038 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8039 MemSDNode *M = cast<MemSDNode>(Op); 8040 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8041 8042 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8043 EVT VDataType = VData.getValueType().getScalarType(); 8044 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8045 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8046 8047 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8048 M->getMemoryVT(), M->getMemOperand()); 8049 } 8050 case Intrinsic::amdgcn_raw_buffer_load_lds: 8051 case Intrinsic::amdgcn_struct_buffer_load_lds: { 8052 unsigned Opc; 8053 bool HasVIndex = IntrinsicID == Intrinsic::amdgcn_struct_buffer_load_lds; 8054 unsigned OpOffset = HasVIndex ? 1 : 0; 8055 SDValue VOffset = Op.getOperand(5 + OpOffset); 8056 auto CVOffset = dyn_cast<ConstantSDNode>(VOffset); 8057 bool HasVOffset = !CVOffset || !CVOffset->isZero(); 8058 unsigned Size = Op->getConstantOperandVal(4); 8059 8060 switch (Size) { 8061 default: 8062 return SDValue(); 8063 case 1: 8064 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_BOTHEN 8065 : AMDGPU::BUFFER_LOAD_UBYTE_LDS_IDXEN 8066 : HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFEN 8067 : AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFSET; 8068 break; 8069 case 2: 8070 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_BOTHEN 8071 : AMDGPU::BUFFER_LOAD_USHORT_LDS_IDXEN 8072 : HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFEN 8073 : AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFSET; 8074 break; 8075 case 4: 8076 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_BOTHEN 8077 : AMDGPU::BUFFER_LOAD_DWORD_LDS_IDXEN 8078 : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFEN 8079 : AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFSET; 8080 break; 8081 } 8082 8083 SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 8084 8085 SmallVector<SDValue, 8> Ops; 8086 8087 if (HasVIndex && HasVOffset) 8088 Ops.push_back(DAG.getBuildVector(MVT::v2i32, DL, 8089 { Op.getOperand(5), // VIndex 8090 VOffset })); 8091 else if (HasVIndex) 8092 Ops.push_back(Op.getOperand(5)); 8093 else if (HasVOffset) 8094 Ops.push_back(VOffset); 8095 8096 Ops.push_back(Op.getOperand(2)); // rsrc 8097 Ops.push_back(Op.getOperand(6 + OpOffset)); // soffset 8098 Ops.push_back(Op.getOperand(7 + OpOffset)); // imm offset 8099 unsigned Aux = Op.getConstantOperandVal(8 + OpOffset); 8100 Ops.push_back( 8101 DAG.getTargetConstant(Aux & AMDGPU::CPol::ALL, DL, MVT::i8)); // cpol 8102 Ops.push_back( 8103 DAG.getTargetConstant((Aux >> 3) & 1, DL, MVT::i8)); // swz 8104 Ops.push_back(M0Val.getValue(0)); // Chain 8105 Ops.push_back(M0Val.getValue(1)); // Glue 8106 8107 auto *M = cast<MemSDNode>(Op); 8108 MachineMemOperand *LoadMMO = M->getMemOperand(); 8109 MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo(); 8110 LoadPtrI.Offset = Op->getConstantOperandVal(7 + OpOffset); 8111 MachinePointerInfo StorePtrI = LoadPtrI; 8112 StorePtrI.V = nullptr; 8113 StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS; 8114 8115 auto F = LoadMMO->getFlags() & 8116 ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad); 8117 LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad, 8118 Size, LoadMMO->getBaseAlign()); 8119 8120 MachineMemOperand *StoreMMO = 8121 MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore, 8122 sizeof(int32_t), LoadMMO->getBaseAlign()); 8123 8124 auto Load = DAG.getMachineNode(Opc, DL, M->getVTList(), Ops); 8125 DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO}); 8126 8127 return SDValue(Load, 0); 8128 } 8129 case Intrinsic::amdgcn_global_load_lds: { 8130 unsigned Opc; 8131 unsigned Size = Op->getConstantOperandVal(4); 8132 switch (Size) { 8133 default: 8134 return SDValue(); 8135 case 1: 8136 Opc = AMDGPU::GLOBAL_LOAD_LDS_UBYTE; 8137 break; 8138 case 2: 8139 Opc = AMDGPU::GLOBAL_LOAD_LDS_USHORT; 8140 break; 8141 case 4: 8142 Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORD; 8143 break; 8144 } 8145 8146 auto *M = cast<MemSDNode>(Op); 8147 SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 8148 8149 SmallVector<SDValue, 6> Ops; 8150 8151 SDValue Addr = Op.getOperand(2); // Global ptr 8152 SDValue VOffset; 8153 // Try to split SAddr and VOffset. Global and LDS pointers share the same 8154 // immediate offset, so we cannot use a regular SelectGlobalSAddr(). 8155 if (Addr->isDivergent() && Addr.getOpcode() == ISD::ADD) { 8156 SDValue LHS = Addr.getOperand(0); 8157 SDValue RHS = Addr.getOperand(1); 8158 8159 if (LHS->isDivergent()) 8160 std::swap(LHS, RHS); 8161 8162 if (!LHS->isDivergent() && RHS.getOpcode() == ISD::ZERO_EXTEND && 8163 RHS.getOperand(0).getValueType() == MVT::i32) { 8164 // add (i64 sgpr), (zero_extend (i32 vgpr)) 8165 Addr = LHS; 8166 VOffset = RHS.getOperand(0); 8167 } 8168 } 8169 8170 Ops.push_back(Addr); 8171 if (!Addr->isDivergent()) { 8172 Opc = AMDGPU::getGlobalSaddrOp(Opc); 8173 if (!VOffset) 8174 VOffset = SDValue( 8175 DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, DL, MVT::i32, 8176 DAG.getTargetConstant(0, DL, MVT::i32)), 0); 8177 Ops.push_back(VOffset); 8178 } 8179 8180 Ops.push_back(Op.getOperand(5)); // Offset 8181 Ops.push_back(Op.getOperand(6)); // CPol 8182 Ops.push_back(M0Val.getValue(0)); // Chain 8183 Ops.push_back(M0Val.getValue(1)); // Glue 8184 8185 MachineMemOperand *LoadMMO = M->getMemOperand(); 8186 MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo(); 8187 LoadPtrI.Offset = Op->getConstantOperandVal(5); 8188 MachinePointerInfo StorePtrI = LoadPtrI; 8189 LoadPtrI.AddrSpace = AMDGPUAS::GLOBAL_ADDRESS; 8190 StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS; 8191 auto F = LoadMMO->getFlags() & 8192 ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad); 8193 LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad, 8194 Size, LoadMMO->getBaseAlign()); 8195 MachineMemOperand *StoreMMO = 8196 MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore, 8197 sizeof(int32_t), Align(4)); 8198 8199 auto Load = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops); 8200 DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO}); 8201 8202 return SDValue(Load, 0); 8203 } 8204 case Intrinsic::amdgcn_end_cf: 8205 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 8206 Op->getOperand(2), Chain), 0); 8207 8208 default: { 8209 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 8210 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 8211 return lowerImage(Op, ImageDimIntr, DAG, true); 8212 8213 return Op; 8214 } 8215 } 8216 } 8217 8218 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 8219 // offset (the offset that is included in bounds checking and swizzling, to be 8220 // split between the instruction's voffset and immoffset fields) and soffset 8221 // (the offset that is excluded from bounds checking and swizzling, to go in 8222 // the instruction's soffset field). This function takes the first kind of 8223 // offset and figures out how to split it between voffset and immoffset. 8224 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 8225 SDValue Offset, SelectionDAG &DAG) const { 8226 SDLoc DL(Offset); 8227 const unsigned MaxImm = 4095; 8228 SDValue N0 = Offset; 8229 ConstantSDNode *C1 = nullptr; 8230 8231 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 8232 N0 = SDValue(); 8233 else if (DAG.isBaseWithConstantOffset(N0)) { 8234 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 8235 N0 = N0.getOperand(0); 8236 } 8237 8238 if (C1) { 8239 unsigned ImmOffset = C1->getZExtValue(); 8240 // If the immediate value is too big for the immoffset field, put the value 8241 // and -4096 into the immoffset field so that the value that is copied/added 8242 // for the voffset field is a multiple of 4096, and it stands more chance 8243 // of being CSEd with the copy/add for another similar load/store. 8244 // However, do not do that rounding down to a multiple of 4096 if that is a 8245 // negative number, as it appears to be illegal to have a negative offset 8246 // in the vgpr, even if adding the immediate offset makes it positive. 8247 unsigned Overflow = ImmOffset & ~MaxImm; 8248 ImmOffset -= Overflow; 8249 if ((int32_t)Overflow < 0) { 8250 Overflow += ImmOffset; 8251 ImmOffset = 0; 8252 } 8253 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 8254 if (Overflow) { 8255 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 8256 if (!N0) 8257 N0 = OverflowVal; 8258 else { 8259 SDValue Ops[] = { N0, OverflowVal }; 8260 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 8261 } 8262 } 8263 } 8264 if (!N0) 8265 N0 = DAG.getConstant(0, DL, MVT::i32); 8266 if (!C1) 8267 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 8268 return {N0, SDValue(C1, 0)}; 8269 } 8270 8271 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 8272 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 8273 // pointed to by Offsets. 8274 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 8275 SelectionDAG &DAG, SDValue *Offsets, 8276 Align Alignment) const { 8277 SDLoc DL(CombinedOffset); 8278 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 8279 uint32_t Imm = C->getZExtValue(); 8280 uint32_t SOffset, ImmOffset; 8281 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 8282 Alignment)) { 8283 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 8284 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8285 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8286 return; 8287 } 8288 } 8289 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 8290 SDValue N0 = CombinedOffset.getOperand(0); 8291 SDValue N1 = CombinedOffset.getOperand(1); 8292 uint32_t SOffset, ImmOffset; 8293 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 8294 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 8295 Subtarget, Alignment)) { 8296 Offsets[0] = N0; 8297 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8298 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8299 return; 8300 } 8301 } 8302 Offsets[0] = CombinedOffset; 8303 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 8304 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 8305 } 8306 8307 // Handle 8 bit and 16 bit buffer loads 8308 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 8309 EVT LoadVT, SDLoc DL, 8310 ArrayRef<SDValue> Ops, 8311 MemSDNode *M) const { 8312 EVT IntVT = LoadVT.changeTypeToInteger(); 8313 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 8314 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 8315 8316 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 8317 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 8318 Ops, IntVT, 8319 M->getMemOperand()); 8320 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 8321 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 8322 8323 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 8324 } 8325 8326 // Handle 8 bit and 16 bit buffer stores 8327 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 8328 EVT VDataType, SDLoc DL, 8329 SDValue Ops[], 8330 MemSDNode *M) const { 8331 if (VDataType == MVT::f16) 8332 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 8333 8334 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 8335 Ops[1] = BufferStoreExt; 8336 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 8337 AMDGPUISD::BUFFER_STORE_SHORT; 8338 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 8339 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 8340 M->getMemOperand()); 8341 } 8342 8343 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 8344 ISD::LoadExtType ExtType, SDValue Op, 8345 const SDLoc &SL, EVT VT) { 8346 if (VT.bitsLT(Op.getValueType())) 8347 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 8348 8349 switch (ExtType) { 8350 case ISD::SEXTLOAD: 8351 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 8352 case ISD::ZEXTLOAD: 8353 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 8354 case ISD::EXTLOAD: 8355 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 8356 case ISD::NON_EXTLOAD: 8357 return Op; 8358 } 8359 8360 llvm_unreachable("invalid ext type"); 8361 } 8362 8363 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 8364 SelectionDAG &DAG = DCI.DAG; 8365 if (Ld->getAlign() < Align(4) || Ld->isDivergent()) 8366 return SDValue(); 8367 8368 // FIXME: Constant loads should all be marked invariant. 8369 unsigned AS = Ld->getAddressSpace(); 8370 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 8371 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 8372 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 8373 return SDValue(); 8374 8375 // Don't do this early, since it may interfere with adjacent load merging for 8376 // illegal types. We can avoid losing alignment information for exotic types 8377 // pre-legalize. 8378 EVT MemVT = Ld->getMemoryVT(); 8379 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 8380 MemVT.getSizeInBits() >= 32) 8381 return SDValue(); 8382 8383 SDLoc SL(Ld); 8384 8385 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 8386 "unexpected vector extload"); 8387 8388 // TODO: Drop only high part of range. 8389 SDValue Ptr = Ld->getBasePtr(); 8390 SDValue NewLoad = DAG.getLoad( 8391 ISD::UNINDEXED, ISD::NON_EXTLOAD, MVT::i32, SL, Ld->getChain(), Ptr, 8392 Ld->getOffset(), Ld->getPointerInfo(), MVT::i32, Ld->getAlign(), 8393 Ld->getMemOperand()->getFlags(), Ld->getAAInfo(), 8394 nullptr); // Drop ranges 8395 8396 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 8397 if (MemVT.isFloatingPoint()) { 8398 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 8399 "unexpected fp extload"); 8400 TruncVT = MemVT.changeTypeToInteger(); 8401 } 8402 8403 SDValue Cvt = NewLoad; 8404 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 8405 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 8406 DAG.getValueType(TruncVT)); 8407 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 8408 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 8409 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 8410 } else { 8411 assert(Ld->getExtensionType() == ISD::EXTLOAD); 8412 } 8413 8414 EVT VT = Ld->getValueType(0); 8415 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8416 8417 DCI.AddToWorklist(Cvt.getNode()); 8418 8419 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8420 // the appropriate extension from the 32-bit load. 8421 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8422 DCI.AddToWorklist(Cvt.getNode()); 8423 8424 // Handle conversion back to floating point if necessary. 8425 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8426 8427 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8428 } 8429 8430 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8431 SDLoc DL(Op); 8432 LoadSDNode *Load = cast<LoadSDNode>(Op); 8433 ISD::LoadExtType ExtType = Load->getExtensionType(); 8434 EVT MemVT = Load->getMemoryVT(); 8435 8436 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8437 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8438 return SDValue(); 8439 8440 // FIXME: Copied from PPC 8441 // First, load into 32 bits, then truncate to 1 bit. 8442 8443 SDValue Chain = Load->getChain(); 8444 SDValue BasePtr = Load->getBasePtr(); 8445 MachineMemOperand *MMO = Load->getMemOperand(); 8446 8447 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8448 8449 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8450 BasePtr, RealMemVT, MMO); 8451 8452 if (!MemVT.isVector()) { 8453 SDValue Ops[] = { 8454 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8455 NewLD.getValue(1) 8456 }; 8457 8458 return DAG.getMergeValues(Ops, DL); 8459 } 8460 8461 SmallVector<SDValue, 3> Elts; 8462 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8463 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8464 DAG.getConstant(I, DL, MVT::i32)); 8465 8466 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8467 } 8468 8469 SDValue Ops[] = { 8470 DAG.getBuildVector(MemVT, DL, Elts), 8471 NewLD.getValue(1) 8472 }; 8473 8474 return DAG.getMergeValues(Ops, DL); 8475 } 8476 8477 if (!MemVT.isVector()) 8478 return SDValue(); 8479 8480 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8481 "Custom lowering for non-i32 vectors hasn't been implemented."); 8482 8483 Align Alignment = Load->getAlign(); 8484 unsigned AS = Load->getAddressSpace(); 8485 if (Subtarget->hasLDSMisalignedBug() && AS == AMDGPUAS::FLAT_ADDRESS && 8486 Alignment.value() < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8487 return SplitVectorLoad(Op, DAG); 8488 } 8489 8490 MachineFunction &MF = DAG.getMachineFunction(); 8491 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8492 // If there is a possibility that flat instruction access scratch memory 8493 // then we need to use the same legalization rules we use for private. 8494 if (AS == AMDGPUAS::FLAT_ADDRESS && 8495 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8496 AS = MFI->hasFlatScratchInit() ? 8497 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8498 8499 unsigned NumElements = MemVT.getVectorNumElements(); 8500 8501 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8502 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8503 if (!Op->isDivergent() && Alignment >= Align(4) && NumElements < 32) { 8504 if (MemVT.isPow2VectorType()) 8505 return SDValue(); 8506 return WidenOrSplitVectorLoad(Op, DAG); 8507 } 8508 // Non-uniform loads will be selected to MUBUF instructions, so they 8509 // have the same legalization requirements as global and private 8510 // loads. 8511 // 8512 } 8513 8514 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8515 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8516 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8517 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8518 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8519 Alignment >= Align(4) && NumElements < 32) { 8520 if (MemVT.isPow2VectorType()) 8521 return SDValue(); 8522 return WidenOrSplitVectorLoad(Op, DAG); 8523 } 8524 // Non-uniform loads will be selected to MUBUF instructions, so they 8525 // have the same legalization requirements as global and private 8526 // loads. 8527 // 8528 } 8529 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8530 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8531 AS == AMDGPUAS::GLOBAL_ADDRESS || 8532 AS == AMDGPUAS::FLAT_ADDRESS) { 8533 if (NumElements > 4) 8534 return SplitVectorLoad(Op, DAG); 8535 // v3 loads not supported on SI. 8536 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8537 return WidenOrSplitVectorLoad(Op, DAG); 8538 8539 // v3 and v4 loads are supported for private and global memory. 8540 return SDValue(); 8541 } 8542 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8543 // Depending on the setting of the private_element_size field in the 8544 // resource descriptor, we can only make private accesses up to a certain 8545 // size. 8546 switch (Subtarget->getMaxPrivateElementSize()) { 8547 case 4: { 8548 SDValue Ops[2]; 8549 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8550 return DAG.getMergeValues(Ops, DL); 8551 } 8552 case 8: 8553 if (NumElements > 2) 8554 return SplitVectorLoad(Op, DAG); 8555 return SDValue(); 8556 case 16: 8557 // Same as global/flat 8558 if (NumElements > 4) 8559 return SplitVectorLoad(Op, DAG); 8560 // v3 loads not supported on SI. 8561 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8562 return WidenOrSplitVectorLoad(Op, DAG); 8563 8564 return SDValue(); 8565 default: 8566 llvm_unreachable("unsupported private_element_size"); 8567 } 8568 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8569 bool Fast = false; 8570 auto Flags = Load->getMemOperand()->getFlags(); 8571 if (allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8572 Load->getAlign(), Flags, &Fast) && 8573 Fast) 8574 return SDValue(); 8575 8576 if (MemVT.isVector()) 8577 return SplitVectorLoad(Op, DAG); 8578 } 8579 8580 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8581 MemVT, *Load->getMemOperand())) { 8582 SDValue Ops[2]; 8583 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8584 return DAG.getMergeValues(Ops, DL); 8585 } 8586 8587 return SDValue(); 8588 } 8589 8590 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8591 EVT VT = Op.getValueType(); 8592 if (VT.getSizeInBits() == 128) 8593 return splitTernaryVectorOp(Op, DAG); 8594 8595 assert(VT.getSizeInBits() == 64); 8596 8597 SDLoc DL(Op); 8598 SDValue Cond = Op.getOperand(0); 8599 8600 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8601 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8602 8603 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8604 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8605 8606 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8607 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8608 8609 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8610 8611 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8612 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8613 8614 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8615 8616 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8617 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8618 } 8619 8620 // Catch division cases where we can use shortcuts with rcp and rsq 8621 // instructions. 8622 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8623 SelectionDAG &DAG) const { 8624 SDLoc SL(Op); 8625 SDValue LHS = Op.getOperand(0); 8626 SDValue RHS = Op.getOperand(1); 8627 EVT VT = Op.getValueType(); 8628 const SDNodeFlags Flags = Op->getFlags(); 8629 8630 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8631 8632 // Without !fpmath accuracy information, we can't do more because we don't 8633 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8634 if (!AllowInaccurateRcp) 8635 return SDValue(); 8636 8637 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8638 if (CLHS->isExactlyValue(1.0)) { 8639 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8640 // the CI documentation has a worst case error of 1 ulp. 8641 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8642 // use it as long as we aren't trying to use denormals. 8643 // 8644 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8645 8646 // 1.0 / sqrt(x) -> rsq(x) 8647 8648 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8649 // error seems really high at 2^29 ULP. 8650 if (RHS.getOpcode() == ISD::FSQRT) 8651 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8652 8653 // 1.0 / x -> rcp(x) 8654 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8655 } 8656 8657 // Same as for 1.0, but expand the sign out of the constant. 8658 if (CLHS->isExactlyValue(-1.0)) { 8659 // -1.0 / x -> rcp (fneg x) 8660 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8661 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8662 } 8663 } 8664 8665 // Turn into multiply by the reciprocal. 8666 // x / y -> x * (1.0 / y) 8667 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8668 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8669 } 8670 8671 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8672 SelectionDAG &DAG) const { 8673 SDLoc SL(Op); 8674 SDValue X = Op.getOperand(0); 8675 SDValue Y = Op.getOperand(1); 8676 EVT VT = Op.getValueType(); 8677 const SDNodeFlags Flags = Op->getFlags(); 8678 8679 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8680 DAG.getTarget().Options.UnsafeFPMath; 8681 if (!AllowInaccurateDiv) 8682 return SDValue(); 8683 8684 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8685 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8686 8687 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8688 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8689 8690 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8691 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8692 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8693 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8694 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8695 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8696 } 8697 8698 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8699 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8700 SDNodeFlags Flags) { 8701 if (GlueChain->getNumValues() <= 1) { 8702 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8703 } 8704 8705 assert(GlueChain->getNumValues() == 3); 8706 8707 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8708 switch (Opcode) { 8709 default: llvm_unreachable("no chain equivalent for opcode"); 8710 case ISD::FMUL: 8711 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8712 break; 8713 } 8714 8715 return DAG.getNode(Opcode, SL, VTList, 8716 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8717 Flags); 8718 } 8719 8720 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8721 EVT VT, SDValue A, SDValue B, SDValue C, 8722 SDValue GlueChain, SDNodeFlags Flags) { 8723 if (GlueChain->getNumValues() <= 1) { 8724 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8725 } 8726 8727 assert(GlueChain->getNumValues() == 3); 8728 8729 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8730 switch (Opcode) { 8731 default: llvm_unreachable("no chain equivalent for opcode"); 8732 case ISD::FMA: 8733 Opcode = AMDGPUISD::FMA_W_CHAIN; 8734 break; 8735 } 8736 8737 return DAG.getNode(Opcode, SL, VTList, 8738 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8739 Flags); 8740 } 8741 8742 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8743 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8744 return FastLowered; 8745 8746 SDLoc SL(Op); 8747 SDValue Src0 = Op.getOperand(0); 8748 SDValue Src1 = Op.getOperand(1); 8749 8750 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8751 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8752 8753 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8754 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8755 8756 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8757 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8758 8759 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8760 } 8761 8762 // Faster 2.5 ULP division that does not support denormals. 8763 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8764 SDLoc SL(Op); 8765 SDValue LHS = Op.getOperand(1); 8766 SDValue RHS = Op.getOperand(2); 8767 8768 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8769 8770 const APFloat K0Val(BitsToFloat(0x6f800000)); 8771 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8772 8773 const APFloat K1Val(BitsToFloat(0x2f800000)); 8774 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8775 8776 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8777 8778 EVT SetCCVT = 8779 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8780 8781 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8782 8783 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8784 8785 // TODO: Should this propagate fast-math-flags? 8786 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8787 8788 // rcp does not support denormals. 8789 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8790 8791 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8792 8793 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8794 } 8795 8796 // Returns immediate value for setting the F32 denorm mode when using the 8797 // S_DENORM_MODE instruction. 8798 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8799 const SDLoc &SL, const GCNSubtarget *ST) { 8800 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8801 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8802 ? FP_DENORM_FLUSH_NONE 8803 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8804 8805 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8806 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8807 } 8808 8809 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8810 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8811 return FastLowered; 8812 8813 // The selection matcher assumes anything with a chain selecting to a 8814 // mayRaiseFPException machine instruction. Since we're introducing a chain 8815 // here, we need to explicitly report nofpexcept for the regular fdiv 8816 // lowering. 8817 SDNodeFlags Flags = Op->getFlags(); 8818 Flags.setNoFPExcept(true); 8819 8820 SDLoc SL(Op); 8821 SDValue LHS = Op.getOperand(0); 8822 SDValue RHS = Op.getOperand(1); 8823 8824 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8825 8826 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8827 8828 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8829 {RHS, RHS, LHS}, Flags); 8830 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8831 {LHS, RHS, LHS}, Flags); 8832 8833 // Denominator is scaled to not be denormal, so using rcp is ok. 8834 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8835 DenominatorScaled, Flags); 8836 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8837 DenominatorScaled, Flags); 8838 8839 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8840 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8841 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8842 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8843 8844 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8845 8846 if (!HasFP32Denormals) { 8847 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8848 // lowering. The chain dependence is insufficient, and we need glue. We do 8849 // not need the glue variants in a strictfp function. 8850 8851 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8852 8853 SDNode *EnableDenorm; 8854 if (Subtarget->hasDenormModeInst()) { 8855 const SDValue EnableDenormValue = 8856 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8857 8858 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8859 DAG.getEntryNode(), EnableDenormValue).getNode(); 8860 } else { 8861 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8862 SL, MVT::i32); 8863 EnableDenorm = 8864 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8865 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8866 } 8867 8868 SDValue Ops[3] = { 8869 NegDivScale0, 8870 SDValue(EnableDenorm, 0), 8871 SDValue(EnableDenorm, 1) 8872 }; 8873 8874 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8875 } 8876 8877 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8878 ApproxRcp, One, NegDivScale0, Flags); 8879 8880 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8881 ApproxRcp, Fma0, Flags); 8882 8883 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8884 Fma1, Fma1, Flags); 8885 8886 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8887 NumeratorScaled, Mul, Flags); 8888 8889 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8890 Fma2, Fma1, Mul, Fma2, Flags); 8891 8892 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8893 NumeratorScaled, Fma3, Flags); 8894 8895 if (!HasFP32Denormals) { 8896 SDNode *DisableDenorm; 8897 if (Subtarget->hasDenormModeInst()) { 8898 const SDValue DisableDenormValue = 8899 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8900 8901 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8902 Fma4.getValue(1), DisableDenormValue, 8903 Fma4.getValue(2)).getNode(); 8904 } else { 8905 const SDValue DisableDenormValue = 8906 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8907 8908 DisableDenorm = DAG.getMachineNode( 8909 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8910 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8911 } 8912 8913 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8914 SDValue(DisableDenorm, 0), DAG.getRoot()); 8915 DAG.setRoot(OutputChain); 8916 } 8917 8918 SDValue Scale = NumeratorScaled.getValue(1); 8919 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8920 {Fma4, Fma1, Fma3, Scale}, Flags); 8921 8922 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8923 } 8924 8925 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8926 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8927 return FastLowered; 8928 8929 SDLoc SL(Op); 8930 SDValue X = Op.getOperand(0); 8931 SDValue Y = Op.getOperand(1); 8932 8933 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8934 8935 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8936 8937 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8938 8939 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8940 8941 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8942 8943 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8944 8945 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8946 8947 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8948 8949 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8950 8951 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8952 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8953 8954 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8955 NegDivScale0, Mul, DivScale1); 8956 8957 SDValue Scale; 8958 8959 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8960 // Workaround a hardware bug on SI where the condition output from div_scale 8961 // is not usable. 8962 8963 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8964 8965 // Figure out if the scale to use for div_fmas. 8966 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8967 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8968 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8969 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8970 8971 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8972 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8973 8974 SDValue Scale0Hi 8975 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8976 SDValue Scale1Hi 8977 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8978 8979 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8980 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8981 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8982 } else { 8983 Scale = DivScale1.getValue(1); 8984 } 8985 8986 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8987 Fma4, Fma3, Mul, Scale); 8988 8989 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8990 } 8991 8992 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8993 EVT VT = Op.getValueType(); 8994 8995 if (VT == MVT::f32) 8996 return LowerFDIV32(Op, DAG); 8997 8998 if (VT == MVT::f64) 8999 return LowerFDIV64(Op, DAG); 9000 9001 if (VT == MVT::f16) 9002 return LowerFDIV16(Op, DAG); 9003 9004 llvm_unreachable("Unexpected type for fdiv"); 9005 } 9006 9007 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 9008 SDLoc DL(Op); 9009 StoreSDNode *Store = cast<StoreSDNode>(Op); 9010 EVT VT = Store->getMemoryVT(); 9011 9012 if (VT == MVT::i1) { 9013 return DAG.getTruncStore(Store->getChain(), DL, 9014 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 9015 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 9016 } 9017 9018 assert(VT.isVector() && 9019 Store->getValue().getValueType().getScalarType() == MVT::i32); 9020 9021 unsigned AS = Store->getAddressSpace(); 9022 if (Subtarget->hasLDSMisalignedBug() && 9023 AS == AMDGPUAS::FLAT_ADDRESS && 9024 Store->getAlign().value() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 9025 return SplitVectorStore(Op, DAG); 9026 } 9027 9028 MachineFunction &MF = DAG.getMachineFunction(); 9029 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 9030 // If there is a possibility that flat instruction access scratch memory 9031 // then we need to use the same legalization rules we use for private. 9032 if (AS == AMDGPUAS::FLAT_ADDRESS && 9033 !Subtarget->hasMultiDwordFlatScratchAddressing()) 9034 AS = MFI->hasFlatScratchInit() ? 9035 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 9036 9037 unsigned NumElements = VT.getVectorNumElements(); 9038 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 9039 AS == AMDGPUAS::FLAT_ADDRESS) { 9040 if (NumElements > 4) 9041 return SplitVectorStore(Op, DAG); 9042 // v3 stores not supported on SI. 9043 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 9044 return SplitVectorStore(Op, DAG); 9045 9046 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 9047 VT, *Store->getMemOperand())) 9048 return expandUnalignedStore(Store, DAG); 9049 9050 return SDValue(); 9051 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 9052 switch (Subtarget->getMaxPrivateElementSize()) { 9053 case 4: 9054 return scalarizeVectorStore(Store, DAG); 9055 case 8: 9056 if (NumElements > 2) 9057 return SplitVectorStore(Op, DAG); 9058 return SDValue(); 9059 case 16: 9060 if (NumElements > 4 || 9061 (NumElements == 3 && !Subtarget->enableFlatScratch())) 9062 return SplitVectorStore(Op, DAG); 9063 return SDValue(); 9064 default: 9065 llvm_unreachable("unsupported private_element_size"); 9066 } 9067 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 9068 bool Fast = false; 9069 auto Flags = Store->getMemOperand()->getFlags(); 9070 if (allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 9071 Store->getAlign(), Flags, &Fast) && 9072 Fast) 9073 return SDValue(); 9074 9075 if (VT.isVector()) 9076 return SplitVectorStore(Op, DAG); 9077 9078 return expandUnalignedStore(Store, DAG); 9079 } 9080 9081 // Probably an invalid store. If so we'll end up emitting a selection error. 9082 return SDValue(); 9083 } 9084 9085 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 9086 SDLoc DL(Op); 9087 EVT VT = Op.getValueType(); 9088 SDValue Arg = Op.getOperand(0); 9089 SDValue TrigVal; 9090 9091 // Propagate fast-math flags so that the multiply we introduce can be folded 9092 // if Arg is already the result of a multiply by constant. 9093 auto Flags = Op->getFlags(); 9094 9095 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 9096 9097 if (Subtarget->hasTrigReducedRange()) { 9098 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9099 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 9100 } else { 9101 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9102 } 9103 9104 switch (Op.getOpcode()) { 9105 case ISD::FCOS: 9106 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 9107 case ISD::FSIN: 9108 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 9109 default: 9110 llvm_unreachable("Wrong trig opcode"); 9111 } 9112 } 9113 9114 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 9115 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 9116 assert(AtomicNode->isCompareAndSwap()); 9117 unsigned AS = AtomicNode->getAddressSpace(); 9118 9119 // No custom lowering required for local address space 9120 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 9121 return Op; 9122 9123 // Non-local address space requires custom lowering for atomic compare 9124 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 9125 SDLoc DL(Op); 9126 SDValue ChainIn = Op.getOperand(0); 9127 SDValue Addr = Op.getOperand(1); 9128 SDValue Old = Op.getOperand(2); 9129 SDValue New = Op.getOperand(3); 9130 EVT VT = Op.getValueType(); 9131 MVT SimpleVT = VT.getSimpleVT(); 9132 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 9133 9134 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 9135 SDValue Ops[] = { ChainIn, Addr, NewOld }; 9136 9137 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 9138 Ops, VT, AtomicNode->getMemOperand()); 9139 } 9140 9141 //===----------------------------------------------------------------------===// 9142 // Custom DAG optimizations 9143 //===----------------------------------------------------------------------===// 9144 9145 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 9146 DAGCombinerInfo &DCI) const { 9147 EVT VT = N->getValueType(0); 9148 EVT ScalarVT = VT.getScalarType(); 9149 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 9150 return SDValue(); 9151 9152 SelectionDAG &DAG = DCI.DAG; 9153 SDLoc DL(N); 9154 9155 SDValue Src = N->getOperand(0); 9156 EVT SrcVT = Src.getValueType(); 9157 9158 // TODO: We could try to match extracting the higher bytes, which would be 9159 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 9160 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 9161 // about in practice. 9162 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 9163 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 9164 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 9165 DCI.AddToWorklist(Cvt.getNode()); 9166 9167 // For the f16 case, fold to a cast to f32 and then cast back to f16. 9168 if (ScalarVT != MVT::f32) { 9169 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 9170 DAG.getTargetConstant(0, DL, MVT::i32)); 9171 } 9172 return Cvt; 9173 } 9174 } 9175 9176 return SDValue(); 9177 } 9178 9179 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 9180 9181 // This is a variant of 9182 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 9183 // 9184 // The normal DAG combiner will do this, but only if the add has one use since 9185 // that would increase the number of instructions. 9186 // 9187 // This prevents us from seeing a constant offset that can be folded into a 9188 // memory instruction's addressing mode. If we know the resulting add offset of 9189 // a pointer can be folded into an addressing offset, we can replace the pointer 9190 // operand with the add of new constant offset. This eliminates one of the uses, 9191 // and may allow the remaining use to also be simplified. 9192 // 9193 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 9194 unsigned AddrSpace, 9195 EVT MemVT, 9196 DAGCombinerInfo &DCI) const { 9197 SDValue N0 = N->getOperand(0); 9198 SDValue N1 = N->getOperand(1); 9199 9200 // We only do this to handle cases where it's profitable when there are 9201 // multiple uses of the add, so defer to the standard combine. 9202 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 9203 N0->hasOneUse()) 9204 return SDValue(); 9205 9206 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 9207 if (!CN1) 9208 return SDValue(); 9209 9210 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 9211 if (!CAdd) 9212 return SDValue(); 9213 9214 // If the resulting offset is too large, we can't fold it into the addressing 9215 // mode offset. 9216 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 9217 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 9218 9219 AddrMode AM; 9220 AM.HasBaseReg = true; 9221 AM.BaseOffs = Offset.getSExtValue(); 9222 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 9223 return SDValue(); 9224 9225 SelectionDAG &DAG = DCI.DAG; 9226 SDLoc SL(N); 9227 EVT VT = N->getValueType(0); 9228 9229 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 9230 SDValue COffset = DAG.getConstant(Offset, SL, VT); 9231 9232 SDNodeFlags Flags; 9233 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 9234 (N0.getOpcode() == ISD::OR || 9235 N0->getFlags().hasNoUnsignedWrap())); 9236 9237 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 9238 } 9239 9240 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 9241 /// by the chain and intrinsic ID. Theoretically we would also need to check the 9242 /// specific intrinsic, but they all place the pointer operand first. 9243 static unsigned getBasePtrIndex(const MemSDNode *N) { 9244 switch (N->getOpcode()) { 9245 case ISD::STORE: 9246 case ISD::INTRINSIC_W_CHAIN: 9247 case ISD::INTRINSIC_VOID: 9248 return 2; 9249 default: 9250 return 1; 9251 } 9252 } 9253 9254 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 9255 DAGCombinerInfo &DCI) const { 9256 SelectionDAG &DAG = DCI.DAG; 9257 SDLoc SL(N); 9258 9259 unsigned PtrIdx = getBasePtrIndex(N); 9260 SDValue Ptr = N->getOperand(PtrIdx); 9261 9262 // TODO: We could also do this for multiplies. 9263 if (Ptr.getOpcode() == ISD::SHL) { 9264 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 9265 N->getMemoryVT(), DCI); 9266 if (NewPtr) { 9267 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 9268 9269 NewOps[PtrIdx] = NewPtr; 9270 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 9271 } 9272 } 9273 9274 return SDValue(); 9275 } 9276 9277 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 9278 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 9279 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 9280 (Opc == ISD::XOR && Val == 0); 9281 } 9282 9283 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 9284 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 9285 // integer combine opportunities since most 64-bit operations are decomposed 9286 // this way. TODO: We won't want this for SALU especially if it is an inline 9287 // immediate. 9288 SDValue SITargetLowering::splitBinaryBitConstantOp( 9289 DAGCombinerInfo &DCI, 9290 const SDLoc &SL, 9291 unsigned Opc, SDValue LHS, 9292 const ConstantSDNode *CRHS) const { 9293 uint64_t Val = CRHS->getZExtValue(); 9294 uint32_t ValLo = Lo_32(Val); 9295 uint32_t ValHi = Hi_32(Val); 9296 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9297 9298 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 9299 bitOpWithConstantIsReducible(Opc, ValHi)) || 9300 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 9301 // If we need to materialize a 64-bit immediate, it will be split up later 9302 // anyway. Avoid creating the harder to understand 64-bit immediate 9303 // materialization. 9304 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 9305 } 9306 9307 return SDValue(); 9308 } 9309 9310 // Returns true if argument is a boolean value which is not serialized into 9311 // memory or argument and does not require v_cndmask_b32 to be deserialized. 9312 static bool isBoolSGPR(SDValue V) { 9313 if (V.getValueType() != MVT::i1) 9314 return false; 9315 switch (V.getOpcode()) { 9316 default: 9317 break; 9318 case ISD::SETCC: 9319 case AMDGPUISD::FP_CLASS: 9320 return true; 9321 case ISD::AND: 9322 case ISD::OR: 9323 case ISD::XOR: 9324 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 9325 } 9326 return false; 9327 } 9328 9329 // If a constant has all zeroes or all ones within each byte return it. 9330 // Otherwise return 0. 9331 static uint32_t getConstantPermuteMask(uint32_t C) { 9332 // 0xff for any zero byte in the mask 9333 uint32_t ZeroByteMask = 0; 9334 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 9335 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 9336 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 9337 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 9338 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 9339 if ((NonZeroByteMask & C) != NonZeroByteMask) 9340 return 0; // Partial bytes selected. 9341 return C; 9342 } 9343 9344 // Check if a node selects whole bytes from its operand 0 starting at a byte 9345 // boundary while masking the rest. Returns select mask as in the v_perm_b32 9346 // or -1 if not succeeded. 9347 // Note byte select encoding: 9348 // value 0-3 selects corresponding source byte; 9349 // value 0xc selects zero; 9350 // value 0xff selects 0xff. 9351 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 9352 assert(V.getValueSizeInBits() == 32); 9353 9354 if (V.getNumOperands() != 2) 9355 return ~0; 9356 9357 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 9358 if (!N1) 9359 return ~0; 9360 9361 uint32_t C = N1->getZExtValue(); 9362 9363 switch (V.getOpcode()) { 9364 default: 9365 break; 9366 case ISD::AND: 9367 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9368 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 9369 } 9370 break; 9371 9372 case ISD::OR: 9373 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9374 return (0x03020100 & ~ConstMask) | ConstMask; 9375 } 9376 break; 9377 9378 case ISD::SHL: 9379 if (C % 8) 9380 return ~0; 9381 9382 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 9383 9384 case ISD::SRL: 9385 if (C % 8) 9386 return ~0; 9387 9388 return uint32_t(0x0c0c0c0c03020100ull >> C); 9389 } 9390 9391 return ~0; 9392 } 9393 9394 SDValue SITargetLowering::performAndCombine(SDNode *N, 9395 DAGCombinerInfo &DCI) const { 9396 if (DCI.isBeforeLegalize()) 9397 return SDValue(); 9398 9399 SelectionDAG &DAG = DCI.DAG; 9400 EVT VT = N->getValueType(0); 9401 SDValue LHS = N->getOperand(0); 9402 SDValue RHS = N->getOperand(1); 9403 9404 9405 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9406 if (VT == MVT::i64 && CRHS) { 9407 if (SDValue Split 9408 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9409 return Split; 9410 } 9411 9412 if (CRHS && VT == MVT::i32) { 9413 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9414 // nb = number of trailing zeroes in mask 9415 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9416 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9417 uint64_t Mask = CRHS->getZExtValue(); 9418 unsigned Bits = countPopulation(Mask); 9419 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9420 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9421 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9422 unsigned Shift = CShift->getZExtValue(); 9423 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9424 unsigned Offset = NB + Shift; 9425 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9426 SDLoc SL(N); 9427 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9428 LHS->getOperand(0), 9429 DAG.getConstant(Offset, SL, MVT::i32), 9430 DAG.getConstant(Bits, SL, MVT::i32)); 9431 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9432 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9433 DAG.getValueType(NarrowVT)); 9434 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9435 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9436 return Shl; 9437 } 9438 } 9439 } 9440 9441 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9442 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9443 isa<ConstantSDNode>(LHS.getOperand(2))) { 9444 uint32_t Sel = getConstantPermuteMask(Mask); 9445 if (!Sel) 9446 return SDValue(); 9447 9448 // Select 0xc for all zero bytes 9449 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9450 SDLoc DL(N); 9451 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9452 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9453 } 9454 } 9455 9456 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9457 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9458 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9459 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9460 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9461 9462 SDValue X = LHS.getOperand(0); 9463 SDValue Y = RHS.getOperand(0); 9464 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9465 return SDValue(); 9466 9467 if (LCC == ISD::SETO) { 9468 if (X != LHS.getOperand(1)) 9469 return SDValue(); 9470 9471 if (RCC == ISD::SETUNE) { 9472 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9473 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9474 return SDValue(); 9475 9476 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9477 SIInstrFlags::N_SUBNORMAL | 9478 SIInstrFlags::N_ZERO | 9479 SIInstrFlags::P_ZERO | 9480 SIInstrFlags::P_SUBNORMAL | 9481 SIInstrFlags::P_NORMAL; 9482 9483 static_assert(((~(SIInstrFlags::S_NAN | 9484 SIInstrFlags::Q_NAN | 9485 SIInstrFlags::N_INFINITY | 9486 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9487 "mask not equal"); 9488 9489 SDLoc DL(N); 9490 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9491 X, DAG.getConstant(Mask, DL, MVT::i32)); 9492 } 9493 } 9494 } 9495 9496 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9497 std::swap(LHS, RHS); 9498 9499 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9500 RHS.hasOneUse()) { 9501 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9502 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9503 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9504 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9505 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9506 (RHS.getOperand(0) == LHS.getOperand(0) && 9507 LHS.getOperand(0) == LHS.getOperand(1))) { 9508 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9509 unsigned NewMask = LCC == ISD::SETO ? 9510 Mask->getZExtValue() & ~OrdMask : 9511 Mask->getZExtValue() & OrdMask; 9512 9513 SDLoc DL(N); 9514 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9515 DAG.getConstant(NewMask, DL, MVT::i32)); 9516 } 9517 } 9518 9519 if (VT == MVT::i32 && 9520 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9521 // and x, (sext cc from i1) => select cc, x, 0 9522 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9523 std::swap(LHS, RHS); 9524 if (isBoolSGPR(RHS.getOperand(0))) 9525 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9526 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9527 } 9528 9529 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9530 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9531 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9532 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9533 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9534 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9535 if (LHSMask != ~0u && RHSMask != ~0u) { 9536 // Canonicalize the expression in an attempt to have fewer unique masks 9537 // and therefore fewer registers used to hold the masks. 9538 if (LHSMask > RHSMask) { 9539 std::swap(LHSMask, RHSMask); 9540 std::swap(LHS, RHS); 9541 } 9542 9543 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9544 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9545 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9546 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9547 9548 // Check of we need to combine values from two sources within a byte. 9549 if (!(LHSUsedLanes & RHSUsedLanes) && 9550 // If we select high and lower word keep it for SDWA. 9551 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9552 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9553 // Each byte in each mask is either selector mask 0-3, or has higher 9554 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9555 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9556 // mask which is not 0xff wins. By anding both masks we have a correct 9557 // result except that 0x0c shall be corrected to give 0x0c only. 9558 uint32_t Mask = LHSMask & RHSMask; 9559 for (unsigned I = 0; I < 32; I += 8) { 9560 uint32_t ByteSel = 0xff << I; 9561 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9562 Mask &= (0x0c << I) & 0xffffffff; 9563 } 9564 9565 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9566 // or 0x0c. 9567 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9568 SDLoc DL(N); 9569 9570 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9571 LHS.getOperand(0), RHS.getOperand(0), 9572 DAG.getConstant(Sel, DL, MVT::i32)); 9573 } 9574 } 9575 } 9576 9577 return SDValue(); 9578 } 9579 9580 SDValue SITargetLowering::performOrCombine(SDNode *N, 9581 DAGCombinerInfo &DCI) const { 9582 SelectionDAG &DAG = DCI.DAG; 9583 SDValue LHS = N->getOperand(0); 9584 SDValue RHS = N->getOperand(1); 9585 9586 EVT VT = N->getValueType(0); 9587 if (VT == MVT::i1) { 9588 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9589 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9590 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9591 SDValue Src = LHS.getOperand(0); 9592 if (Src != RHS.getOperand(0)) 9593 return SDValue(); 9594 9595 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9596 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9597 if (!CLHS || !CRHS) 9598 return SDValue(); 9599 9600 // Only 10 bits are used. 9601 static const uint32_t MaxMask = 0x3ff; 9602 9603 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9604 SDLoc DL(N); 9605 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9606 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9607 } 9608 9609 return SDValue(); 9610 } 9611 9612 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9613 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9614 LHS.getOpcode() == AMDGPUISD::PERM && 9615 isa<ConstantSDNode>(LHS.getOperand(2))) { 9616 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9617 if (!Sel) 9618 return SDValue(); 9619 9620 Sel |= LHS.getConstantOperandVal(2); 9621 SDLoc DL(N); 9622 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9623 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9624 } 9625 9626 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9627 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9628 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9629 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9630 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9631 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9632 if (LHSMask != ~0u && RHSMask != ~0u) { 9633 // Canonicalize the expression in an attempt to have fewer unique masks 9634 // and therefore fewer registers used to hold the masks. 9635 if (LHSMask > RHSMask) { 9636 std::swap(LHSMask, RHSMask); 9637 std::swap(LHS, RHS); 9638 } 9639 9640 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9641 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9642 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9643 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9644 9645 // Check of we need to combine values from two sources within a byte. 9646 if (!(LHSUsedLanes & RHSUsedLanes) && 9647 // If we select high and lower word keep it for SDWA. 9648 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9649 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9650 // Kill zero bytes selected by other mask. Zero value is 0xc. 9651 LHSMask &= ~RHSUsedLanes; 9652 RHSMask &= ~LHSUsedLanes; 9653 // Add 4 to each active LHS lane 9654 LHSMask |= LHSUsedLanes & 0x04040404; 9655 // Combine masks 9656 uint32_t Sel = LHSMask | RHSMask; 9657 SDLoc DL(N); 9658 9659 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9660 LHS.getOperand(0), RHS.getOperand(0), 9661 DAG.getConstant(Sel, DL, MVT::i32)); 9662 } 9663 } 9664 } 9665 9666 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9667 return SDValue(); 9668 9669 // TODO: This could be a generic combine with a predicate for extracting the 9670 // high half of an integer being free. 9671 9672 // (or i64:x, (zero_extend i32:y)) -> 9673 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9674 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9675 RHS.getOpcode() != ISD::ZERO_EXTEND) 9676 std::swap(LHS, RHS); 9677 9678 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9679 SDValue ExtSrc = RHS.getOperand(0); 9680 EVT SrcVT = ExtSrc.getValueType(); 9681 if (SrcVT == MVT::i32) { 9682 SDLoc SL(N); 9683 SDValue LowLHS, HiBits; 9684 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9685 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9686 9687 DCI.AddToWorklist(LowOr.getNode()); 9688 DCI.AddToWorklist(HiBits.getNode()); 9689 9690 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9691 LowOr, HiBits); 9692 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9693 } 9694 } 9695 9696 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9697 if (CRHS) { 9698 if (SDValue Split 9699 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, 9700 N->getOperand(0), CRHS)) 9701 return Split; 9702 } 9703 9704 return SDValue(); 9705 } 9706 9707 SDValue SITargetLowering::performXorCombine(SDNode *N, 9708 DAGCombinerInfo &DCI) const { 9709 if (SDValue RV = reassociateScalarOps(N, DCI.DAG)) 9710 return RV; 9711 9712 EVT VT = N->getValueType(0); 9713 if (VT != MVT::i64) 9714 return SDValue(); 9715 9716 SDValue LHS = N->getOperand(0); 9717 SDValue RHS = N->getOperand(1); 9718 9719 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9720 if (CRHS) { 9721 if (SDValue Split 9722 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9723 return Split; 9724 } 9725 9726 return SDValue(); 9727 } 9728 9729 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9730 DAGCombinerInfo &DCI) const { 9731 if (!Subtarget->has16BitInsts() || 9732 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9733 return SDValue(); 9734 9735 EVT VT = N->getValueType(0); 9736 if (VT != MVT::i32) 9737 return SDValue(); 9738 9739 SDValue Src = N->getOperand(0); 9740 if (Src.getValueType() != MVT::i16) 9741 return SDValue(); 9742 9743 return SDValue(); 9744 } 9745 9746 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9747 DAGCombinerInfo &DCI) 9748 const { 9749 SDValue Src = N->getOperand(0); 9750 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9751 9752 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9753 VTSign->getVT() == MVT::i8) || 9754 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9755 VTSign->getVT() == MVT::i16)) && 9756 Src.hasOneUse()) { 9757 auto *M = cast<MemSDNode>(Src); 9758 SDValue Ops[] = { 9759 Src.getOperand(0), // Chain 9760 Src.getOperand(1), // rsrc 9761 Src.getOperand(2), // vindex 9762 Src.getOperand(3), // voffset 9763 Src.getOperand(4), // soffset 9764 Src.getOperand(5), // offset 9765 Src.getOperand(6), 9766 Src.getOperand(7) 9767 }; 9768 // replace with BUFFER_LOAD_BYTE/SHORT 9769 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9770 Src.getOperand(0).getValueType()); 9771 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9772 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9773 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9774 ResList, 9775 Ops, M->getMemoryVT(), 9776 M->getMemOperand()); 9777 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9778 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9779 } 9780 return SDValue(); 9781 } 9782 9783 SDValue SITargetLowering::performClassCombine(SDNode *N, 9784 DAGCombinerInfo &DCI) const { 9785 SelectionDAG &DAG = DCI.DAG; 9786 SDValue Mask = N->getOperand(1); 9787 9788 // fp_class x, 0 -> false 9789 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9790 if (CMask->isZero()) 9791 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9792 } 9793 9794 if (N->getOperand(0).isUndef()) 9795 return DAG.getUNDEF(MVT::i1); 9796 9797 return SDValue(); 9798 } 9799 9800 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9801 DAGCombinerInfo &DCI) const { 9802 EVT VT = N->getValueType(0); 9803 SDValue N0 = N->getOperand(0); 9804 9805 if (N0.isUndef()) 9806 return N0; 9807 9808 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9809 N0.getOpcode() == ISD::SINT_TO_FP)) { 9810 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9811 N->getFlags()); 9812 } 9813 9814 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9815 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9816 N0.getOperand(0), N->getFlags()); 9817 } 9818 9819 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9820 } 9821 9822 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9823 unsigned MaxDepth) const { 9824 unsigned Opcode = Op.getOpcode(); 9825 if (Opcode == ISD::FCANONICALIZE) 9826 return true; 9827 9828 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9829 auto F = CFP->getValueAPF(); 9830 if (F.isNaN() && F.isSignaling()) 9831 return false; 9832 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9833 } 9834 9835 // If source is a result of another standard FP operation it is already in 9836 // canonical form. 9837 if (MaxDepth == 0) 9838 return false; 9839 9840 switch (Opcode) { 9841 // These will flush denorms if required. 9842 case ISD::FADD: 9843 case ISD::FSUB: 9844 case ISD::FMUL: 9845 case ISD::FCEIL: 9846 case ISD::FFLOOR: 9847 case ISD::FMA: 9848 case ISD::FMAD: 9849 case ISD::FSQRT: 9850 case ISD::FDIV: 9851 case ISD::FREM: 9852 case ISD::FP_ROUND: 9853 case ISD::FP_EXTEND: 9854 case AMDGPUISD::FMUL_LEGACY: 9855 case AMDGPUISD::FMAD_FTZ: 9856 case AMDGPUISD::RCP: 9857 case AMDGPUISD::RSQ: 9858 case AMDGPUISD::RSQ_CLAMP: 9859 case AMDGPUISD::RCP_LEGACY: 9860 case AMDGPUISD::RCP_IFLAG: 9861 case AMDGPUISD::DIV_SCALE: 9862 case AMDGPUISD::DIV_FMAS: 9863 case AMDGPUISD::DIV_FIXUP: 9864 case AMDGPUISD::FRACT: 9865 case AMDGPUISD::LDEXP: 9866 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9867 case AMDGPUISD::CVT_F32_UBYTE0: 9868 case AMDGPUISD::CVT_F32_UBYTE1: 9869 case AMDGPUISD::CVT_F32_UBYTE2: 9870 case AMDGPUISD::CVT_F32_UBYTE3: 9871 return true; 9872 9873 // It can/will be lowered or combined as a bit operation. 9874 // Need to check their input recursively to handle. 9875 case ISD::FNEG: 9876 case ISD::FABS: 9877 case ISD::FCOPYSIGN: 9878 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9879 9880 case ISD::FSIN: 9881 case ISD::FCOS: 9882 case ISD::FSINCOS: 9883 return Op.getValueType().getScalarType() != MVT::f16; 9884 9885 case ISD::FMINNUM: 9886 case ISD::FMAXNUM: 9887 case ISD::FMINNUM_IEEE: 9888 case ISD::FMAXNUM_IEEE: 9889 case AMDGPUISD::CLAMP: 9890 case AMDGPUISD::FMED3: 9891 case AMDGPUISD::FMAX3: 9892 case AMDGPUISD::FMIN3: { 9893 // FIXME: Shouldn't treat the generic operations different based these. 9894 // However, we aren't really required to flush the result from 9895 // minnum/maxnum.. 9896 9897 // snans will be quieted, so we only need to worry about denormals. 9898 if (Subtarget->supportsMinMaxDenormModes() || 9899 denormalsEnabledForType(DAG, Op.getValueType())) 9900 return true; 9901 9902 // Flushing may be required. 9903 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9904 // targets need to check their input recursively. 9905 9906 // FIXME: Does this apply with clamp? It's implemented with max. 9907 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9908 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9909 return false; 9910 } 9911 9912 return true; 9913 } 9914 case ISD::SELECT: { 9915 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9916 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9917 } 9918 case ISD::BUILD_VECTOR: { 9919 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9920 SDValue SrcOp = Op.getOperand(i); 9921 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9922 return false; 9923 } 9924 9925 return true; 9926 } 9927 case ISD::EXTRACT_VECTOR_ELT: 9928 case ISD::EXTRACT_SUBVECTOR: { 9929 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9930 } 9931 case ISD::INSERT_VECTOR_ELT: { 9932 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9933 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9934 } 9935 case ISD::UNDEF: 9936 // Could be anything. 9937 return false; 9938 9939 case ISD::BITCAST: 9940 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9941 case ISD::TRUNCATE: { 9942 // Hack round the mess we make when legalizing extract_vector_elt 9943 if (Op.getValueType() == MVT::i16) { 9944 SDValue TruncSrc = Op.getOperand(0); 9945 if (TruncSrc.getValueType() == MVT::i32 && 9946 TruncSrc.getOpcode() == ISD::BITCAST && 9947 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9948 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9949 } 9950 } 9951 return false; 9952 } 9953 case ISD::INTRINSIC_WO_CHAIN: { 9954 unsigned IntrinsicID 9955 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9956 // TODO: Handle more intrinsics 9957 switch (IntrinsicID) { 9958 case Intrinsic::amdgcn_cvt_pkrtz: 9959 case Intrinsic::amdgcn_cubeid: 9960 case Intrinsic::amdgcn_frexp_mant: 9961 case Intrinsic::amdgcn_fdot2: 9962 case Intrinsic::amdgcn_rcp: 9963 case Intrinsic::amdgcn_rsq: 9964 case Intrinsic::amdgcn_rsq_clamp: 9965 case Intrinsic::amdgcn_rcp_legacy: 9966 case Intrinsic::amdgcn_rsq_legacy: 9967 case Intrinsic::amdgcn_trig_preop: 9968 return true; 9969 default: 9970 break; 9971 } 9972 9973 LLVM_FALLTHROUGH; 9974 } 9975 default: 9976 return denormalsEnabledForType(DAG, Op.getValueType()) && 9977 DAG.isKnownNeverSNaN(Op); 9978 } 9979 9980 llvm_unreachable("invalid operation"); 9981 } 9982 9983 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 9984 unsigned MaxDepth) const { 9985 MachineRegisterInfo &MRI = MF.getRegInfo(); 9986 MachineInstr *MI = MRI.getVRegDef(Reg); 9987 unsigned Opcode = MI->getOpcode(); 9988 9989 if (Opcode == AMDGPU::G_FCANONICALIZE) 9990 return true; 9991 9992 Optional<FPValueAndVReg> FCR; 9993 // Constant splat (can be padded with undef) or scalar constant. 9994 if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) { 9995 if (FCR->Value.isSignaling()) 9996 return false; 9997 return !FCR->Value.isDenormal() || 9998 denormalsEnabledForType(MRI.getType(FCR->VReg), MF); 9999 } 10000 10001 if (MaxDepth == 0) 10002 return false; 10003 10004 switch (Opcode) { 10005 case AMDGPU::G_FMINNUM_IEEE: 10006 case AMDGPU::G_FMAXNUM_IEEE: { 10007 if (Subtarget->supportsMinMaxDenormModes() || 10008 denormalsEnabledForType(MRI.getType(Reg), MF)) 10009 return true; 10010 for (const MachineOperand &MO : llvm::drop_begin(MI->operands())) 10011 if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1)) 10012 return false; 10013 return true; 10014 } 10015 default: 10016 return denormalsEnabledForType(MRI.getType(Reg), MF) && 10017 isKnownNeverSNaN(Reg, MRI); 10018 } 10019 10020 llvm_unreachable("invalid operation"); 10021 } 10022 10023 // Constant fold canonicalize. 10024 SDValue SITargetLowering::getCanonicalConstantFP( 10025 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 10026 // Flush denormals to 0 if not enabled. 10027 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 10028 return DAG.getConstantFP(0.0, SL, VT); 10029 10030 if (C.isNaN()) { 10031 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 10032 if (C.isSignaling()) { 10033 // Quiet a signaling NaN. 10034 // FIXME: Is this supposed to preserve payload bits? 10035 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 10036 } 10037 10038 // Make sure it is the canonical NaN bitpattern. 10039 // 10040 // TODO: Can we use -1 as the canonical NaN value since it's an inline 10041 // immediate? 10042 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 10043 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 10044 } 10045 10046 // Already canonical. 10047 return DAG.getConstantFP(C, SL, VT); 10048 } 10049 10050 static bool vectorEltWillFoldAway(SDValue Op) { 10051 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 10052 } 10053 10054 SDValue SITargetLowering::performFCanonicalizeCombine( 10055 SDNode *N, 10056 DAGCombinerInfo &DCI) const { 10057 SelectionDAG &DAG = DCI.DAG; 10058 SDValue N0 = N->getOperand(0); 10059 EVT VT = N->getValueType(0); 10060 10061 // fcanonicalize undef -> qnan 10062 if (N0.isUndef()) { 10063 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 10064 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 10065 } 10066 10067 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 10068 EVT VT = N->getValueType(0); 10069 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 10070 } 10071 10072 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 10073 // (fcanonicalize k) 10074 // 10075 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 10076 10077 // TODO: This could be better with wider vectors that will be split to v2f16, 10078 // and to consider uses since there aren't that many packed operations. 10079 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 10080 isTypeLegal(MVT::v2f16)) { 10081 SDLoc SL(N); 10082 SDValue NewElts[2]; 10083 SDValue Lo = N0.getOperand(0); 10084 SDValue Hi = N0.getOperand(1); 10085 EVT EltVT = Lo.getValueType(); 10086 10087 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 10088 for (unsigned I = 0; I != 2; ++I) { 10089 SDValue Op = N0.getOperand(I); 10090 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 10091 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 10092 CFP->getValueAPF()); 10093 } else if (Op.isUndef()) { 10094 // Handled below based on what the other operand is. 10095 NewElts[I] = Op; 10096 } else { 10097 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 10098 } 10099 } 10100 10101 // If one half is undef, and one is constant, prefer a splat vector rather 10102 // than the normal qNaN. If it's a register, prefer 0.0 since that's 10103 // cheaper to use and may be free with a packed operation. 10104 if (NewElts[0].isUndef()) { 10105 if (isa<ConstantFPSDNode>(NewElts[1])) 10106 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 10107 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 10108 } 10109 10110 if (NewElts[1].isUndef()) { 10111 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 10112 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 10113 } 10114 10115 return DAG.getBuildVector(VT, SL, NewElts); 10116 } 10117 } 10118 10119 unsigned SrcOpc = N0.getOpcode(); 10120 10121 // If it's free to do so, push canonicalizes further up the source, which may 10122 // find a canonical source. 10123 // 10124 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 10125 // sNaNs. 10126 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 10127 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 10128 if (CRHS && N0.hasOneUse()) { 10129 SDLoc SL(N); 10130 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 10131 N0.getOperand(0)); 10132 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 10133 DCI.AddToWorklist(Canon0.getNode()); 10134 10135 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 10136 } 10137 } 10138 10139 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 10140 } 10141 10142 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 10143 switch (Opc) { 10144 case ISD::FMAXNUM: 10145 case ISD::FMAXNUM_IEEE: 10146 return AMDGPUISD::FMAX3; 10147 case ISD::SMAX: 10148 return AMDGPUISD::SMAX3; 10149 case ISD::UMAX: 10150 return AMDGPUISD::UMAX3; 10151 case ISD::FMINNUM: 10152 case ISD::FMINNUM_IEEE: 10153 return AMDGPUISD::FMIN3; 10154 case ISD::SMIN: 10155 return AMDGPUISD::SMIN3; 10156 case ISD::UMIN: 10157 return AMDGPUISD::UMIN3; 10158 default: 10159 llvm_unreachable("Not a min/max opcode"); 10160 } 10161 } 10162 10163 SDValue SITargetLowering::performIntMed3ImmCombine( 10164 SelectionDAG &DAG, const SDLoc &SL, 10165 SDValue Op0, SDValue Op1, bool Signed) const { 10166 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 10167 if (!K1) 10168 return SDValue(); 10169 10170 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 10171 if (!K0) 10172 return SDValue(); 10173 10174 if (Signed) { 10175 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 10176 return SDValue(); 10177 } else { 10178 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 10179 return SDValue(); 10180 } 10181 10182 EVT VT = K0->getValueType(0); 10183 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 10184 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 10185 return DAG.getNode(Med3Opc, SL, VT, 10186 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 10187 } 10188 10189 // If there isn't a 16-bit med3 operation, convert to 32-bit. 10190 if (VT == MVT::i16) { 10191 MVT NVT = MVT::i32; 10192 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 10193 10194 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 10195 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 10196 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 10197 10198 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 10199 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 10200 } 10201 10202 return SDValue(); 10203 } 10204 10205 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 10206 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 10207 return C; 10208 10209 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 10210 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 10211 return C; 10212 } 10213 10214 return nullptr; 10215 } 10216 10217 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 10218 const SDLoc &SL, 10219 SDValue Op0, 10220 SDValue Op1) const { 10221 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 10222 if (!K1) 10223 return SDValue(); 10224 10225 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 10226 if (!K0) 10227 return SDValue(); 10228 10229 // Ordered >= (although NaN inputs should have folded away by now). 10230 if (K0->getValueAPF() > K1->getValueAPF()) 10231 return SDValue(); 10232 10233 const MachineFunction &MF = DAG.getMachineFunction(); 10234 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10235 10236 // TODO: Check IEEE bit enabled? 10237 EVT VT = Op0.getValueType(); 10238 if (Info->getMode().DX10Clamp) { 10239 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 10240 // hardware fmed3 behavior converting to a min. 10241 // FIXME: Should this be allowing -0.0? 10242 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 10243 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 10244 } 10245 10246 // med3 for f16 is only available on gfx9+, and not available for v2f16. 10247 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 10248 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 10249 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 10250 // then give the other result, which is different from med3 with a NaN 10251 // input. 10252 SDValue Var = Op0.getOperand(0); 10253 if (!DAG.isKnownNeverSNaN(Var)) 10254 return SDValue(); 10255 10256 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10257 10258 if ((!K0->hasOneUse() || 10259 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 10260 (!K1->hasOneUse() || 10261 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 10262 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 10263 Var, SDValue(K0, 0), SDValue(K1, 0)); 10264 } 10265 } 10266 10267 return SDValue(); 10268 } 10269 10270 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 10271 DAGCombinerInfo &DCI) const { 10272 SelectionDAG &DAG = DCI.DAG; 10273 10274 EVT VT = N->getValueType(0); 10275 unsigned Opc = N->getOpcode(); 10276 SDValue Op0 = N->getOperand(0); 10277 SDValue Op1 = N->getOperand(1); 10278 10279 // Only do this if the inner op has one use since this will just increases 10280 // register pressure for no benefit. 10281 10282 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 10283 !VT.isVector() && 10284 (VT == MVT::i32 || VT == MVT::f32 || 10285 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 10286 // max(max(a, b), c) -> max3(a, b, c) 10287 // min(min(a, b), c) -> min3(a, b, c) 10288 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 10289 SDLoc DL(N); 10290 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10291 DL, 10292 N->getValueType(0), 10293 Op0.getOperand(0), 10294 Op0.getOperand(1), 10295 Op1); 10296 } 10297 10298 // Try commuted. 10299 // max(a, max(b, c)) -> max3(a, b, c) 10300 // min(a, min(b, c)) -> min3(a, b, c) 10301 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 10302 SDLoc DL(N); 10303 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10304 DL, 10305 N->getValueType(0), 10306 Op0, 10307 Op1.getOperand(0), 10308 Op1.getOperand(1)); 10309 } 10310 } 10311 10312 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 10313 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 10314 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 10315 return Med3; 10316 } 10317 10318 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 10319 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 10320 return Med3; 10321 } 10322 10323 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 10324 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 10325 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 10326 (Opc == AMDGPUISD::FMIN_LEGACY && 10327 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 10328 (VT == MVT::f32 || VT == MVT::f64 || 10329 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 10330 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 10331 Op0.hasOneUse()) { 10332 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 10333 return Res; 10334 } 10335 10336 return SDValue(); 10337 } 10338 10339 static bool isClampZeroToOne(SDValue A, SDValue B) { 10340 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 10341 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 10342 // FIXME: Should this be allowing -0.0? 10343 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 10344 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 10345 } 10346 } 10347 10348 return false; 10349 } 10350 10351 // FIXME: Should only worry about snans for version with chain. 10352 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10353 DAGCombinerInfo &DCI) const { 10354 EVT VT = N->getValueType(0); 10355 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10356 // NaNs. With a NaN input, the order of the operands may change the result. 10357 10358 SelectionDAG &DAG = DCI.DAG; 10359 SDLoc SL(N); 10360 10361 SDValue Src0 = N->getOperand(0); 10362 SDValue Src1 = N->getOperand(1); 10363 SDValue Src2 = N->getOperand(2); 10364 10365 if (isClampZeroToOne(Src0, Src1)) { 10366 // const_a, const_b, x -> clamp is safe in all cases including signaling 10367 // nans. 10368 // FIXME: Should this be allowing -0.0? 10369 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10370 } 10371 10372 const MachineFunction &MF = DAG.getMachineFunction(); 10373 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10374 10375 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10376 // handling no dx10-clamp? 10377 if (Info->getMode().DX10Clamp) { 10378 // If NaNs is clamped to 0, we are free to reorder the inputs. 10379 10380 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10381 std::swap(Src0, Src1); 10382 10383 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10384 std::swap(Src1, Src2); 10385 10386 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10387 std::swap(Src0, Src1); 10388 10389 if (isClampZeroToOne(Src1, Src2)) 10390 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10391 } 10392 10393 return SDValue(); 10394 } 10395 10396 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10397 DAGCombinerInfo &DCI) const { 10398 SDValue Src0 = N->getOperand(0); 10399 SDValue Src1 = N->getOperand(1); 10400 if (Src0.isUndef() && Src1.isUndef()) 10401 return DCI.DAG.getUNDEF(N->getValueType(0)); 10402 return SDValue(); 10403 } 10404 10405 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10406 // expanded into a set of cmp/select instructions. 10407 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10408 unsigned NumElem, 10409 bool IsDivergentIdx, 10410 const GCNSubtarget *Subtarget) { 10411 if (UseDivergentRegisterIndexing) 10412 return false; 10413 10414 unsigned VecSize = EltSize * NumElem; 10415 10416 // Sub-dword vectors of size 2 dword or less have better implementation. 10417 if (VecSize <= 64 && EltSize < 32) 10418 return false; 10419 10420 // Always expand the rest of sub-dword instructions, otherwise it will be 10421 // lowered via memory. 10422 if (EltSize < 32) 10423 return true; 10424 10425 // Always do this if var-idx is divergent, otherwise it will become a loop. 10426 if (IsDivergentIdx) 10427 return true; 10428 10429 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10430 unsigned NumInsts = NumElem /* Number of compares */ + 10431 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10432 10433 // On some architectures (GFX9) movrel is not available and it's better 10434 // to expand. 10435 if (!Subtarget->hasMovrel()) 10436 return NumInsts <= 16; 10437 10438 // If movrel is available, use it instead of expanding for vector of 8 10439 // elements. 10440 return NumInsts <= 15; 10441 } 10442 10443 bool SITargetLowering::shouldExpandVectorDynExt(SDNode *N) const { 10444 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10445 if (isa<ConstantSDNode>(Idx)) 10446 return false; 10447 10448 SDValue Vec = N->getOperand(0); 10449 EVT VecVT = Vec.getValueType(); 10450 EVT EltVT = VecVT.getVectorElementType(); 10451 unsigned EltSize = EltVT.getSizeInBits(); 10452 unsigned NumElem = VecVT.getVectorNumElements(); 10453 10454 return SITargetLowering::shouldExpandVectorDynExt( 10455 EltSize, NumElem, Idx->isDivergent(), getSubtarget()); 10456 } 10457 10458 SDValue SITargetLowering::performExtractVectorEltCombine( 10459 SDNode *N, DAGCombinerInfo &DCI) const { 10460 SDValue Vec = N->getOperand(0); 10461 SelectionDAG &DAG = DCI.DAG; 10462 10463 EVT VecVT = Vec.getValueType(); 10464 EVT EltVT = VecVT.getVectorElementType(); 10465 10466 if ((Vec.getOpcode() == ISD::FNEG || 10467 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10468 SDLoc SL(N); 10469 EVT EltVT = N->getValueType(0); 10470 SDValue Idx = N->getOperand(1); 10471 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10472 Vec.getOperand(0), Idx); 10473 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10474 } 10475 10476 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10477 // => 10478 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10479 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10480 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10481 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10482 SDLoc SL(N); 10483 EVT EltVT = N->getValueType(0); 10484 SDValue Idx = N->getOperand(1); 10485 unsigned Opc = Vec.getOpcode(); 10486 10487 switch(Opc) { 10488 default: 10489 break; 10490 // TODO: Support other binary operations. 10491 case ISD::FADD: 10492 case ISD::FSUB: 10493 case ISD::FMUL: 10494 case ISD::ADD: 10495 case ISD::UMIN: 10496 case ISD::UMAX: 10497 case ISD::SMIN: 10498 case ISD::SMAX: 10499 case ISD::FMAXNUM: 10500 case ISD::FMINNUM: 10501 case ISD::FMAXNUM_IEEE: 10502 case ISD::FMINNUM_IEEE: { 10503 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10504 Vec.getOperand(0), Idx); 10505 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10506 Vec.getOperand(1), Idx); 10507 10508 DCI.AddToWorklist(Elt0.getNode()); 10509 DCI.AddToWorklist(Elt1.getNode()); 10510 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10511 } 10512 } 10513 } 10514 10515 unsigned VecSize = VecVT.getSizeInBits(); 10516 unsigned EltSize = EltVT.getSizeInBits(); 10517 10518 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10519 if (shouldExpandVectorDynExt(N)) { 10520 SDLoc SL(N); 10521 SDValue Idx = N->getOperand(1); 10522 SDValue V; 10523 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10524 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10525 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10526 if (I == 0) 10527 V = Elt; 10528 else 10529 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10530 } 10531 return V; 10532 } 10533 10534 if (!DCI.isBeforeLegalize()) 10535 return SDValue(); 10536 10537 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10538 // elements. This exposes more load reduction opportunities by replacing 10539 // multiple small extract_vector_elements with a single 32-bit extract. 10540 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10541 if (isa<MemSDNode>(Vec) && 10542 EltSize <= 16 && 10543 EltVT.isByteSized() && 10544 VecSize > 32 && 10545 VecSize % 32 == 0 && 10546 Idx) { 10547 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10548 10549 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10550 unsigned EltIdx = BitIndex / 32; 10551 unsigned LeftoverBitIdx = BitIndex % 32; 10552 SDLoc SL(N); 10553 10554 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10555 DCI.AddToWorklist(Cast.getNode()); 10556 10557 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10558 DAG.getConstant(EltIdx, SL, MVT::i32)); 10559 DCI.AddToWorklist(Elt.getNode()); 10560 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10561 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10562 DCI.AddToWorklist(Srl.getNode()); 10563 10564 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10565 DCI.AddToWorklist(Trunc.getNode()); 10566 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10567 } 10568 10569 return SDValue(); 10570 } 10571 10572 SDValue 10573 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10574 DAGCombinerInfo &DCI) const { 10575 SDValue Vec = N->getOperand(0); 10576 SDValue Idx = N->getOperand(2); 10577 EVT VecVT = Vec.getValueType(); 10578 EVT EltVT = VecVT.getVectorElementType(); 10579 10580 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10581 // => BUILD_VECTOR n x select (e, const-idx) 10582 if (!shouldExpandVectorDynExt(N)) 10583 return SDValue(); 10584 10585 SelectionDAG &DAG = DCI.DAG; 10586 SDLoc SL(N); 10587 SDValue Ins = N->getOperand(1); 10588 EVT IdxVT = Idx.getValueType(); 10589 10590 SmallVector<SDValue, 16> Ops; 10591 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10592 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10593 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10594 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10595 Ops.push_back(V); 10596 } 10597 10598 return DAG.getBuildVector(VecVT, SL, Ops); 10599 } 10600 10601 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10602 const SDNode *N0, 10603 const SDNode *N1) const { 10604 EVT VT = N0->getValueType(0); 10605 10606 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10607 // support denormals ever. 10608 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10609 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10610 getSubtarget()->hasMadF16())) && 10611 isOperationLegal(ISD::FMAD, VT)) 10612 return ISD::FMAD; 10613 10614 const TargetOptions &Options = DAG.getTarget().Options; 10615 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10616 (N0->getFlags().hasAllowContract() && 10617 N1->getFlags().hasAllowContract())) && 10618 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10619 return ISD::FMA; 10620 } 10621 10622 return 0; 10623 } 10624 10625 // For a reassociatable opcode perform: 10626 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10627 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10628 SelectionDAG &DAG) const { 10629 EVT VT = N->getValueType(0); 10630 if (VT != MVT::i32 && VT != MVT::i64) 10631 return SDValue(); 10632 10633 if (DAG.isBaseWithConstantOffset(SDValue(N, 0))) 10634 return SDValue(); 10635 10636 unsigned Opc = N->getOpcode(); 10637 SDValue Op0 = N->getOperand(0); 10638 SDValue Op1 = N->getOperand(1); 10639 10640 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10641 return SDValue(); 10642 10643 if (Op0->isDivergent()) 10644 std::swap(Op0, Op1); 10645 10646 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10647 return SDValue(); 10648 10649 SDValue Op2 = Op1.getOperand(1); 10650 Op1 = Op1.getOperand(0); 10651 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10652 return SDValue(); 10653 10654 if (Op1->isDivergent()) 10655 std::swap(Op1, Op2); 10656 10657 SDLoc SL(N); 10658 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10659 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10660 } 10661 10662 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10663 EVT VT, 10664 SDValue N0, SDValue N1, SDValue N2, 10665 bool Signed) { 10666 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10667 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10668 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10669 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10670 } 10671 10672 // Fold (add (mul x, y), z) --> (mad_[iu]64_[iu]32 x, y, z) plus high 10673 // multiplies, if any. 10674 // 10675 // Full 64-bit multiplies that feed into an addition are lowered here instead 10676 // of using the generic expansion. The generic expansion ends up with 10677 // a tree of ADD nodes that prevents us from using the "add" part of the 10678 // MAD instruction. The expansion produced here results in a chain of ADDs 10679 // instead of a tree. 10680 SDValue SITargetLowering::tryFoldToMad64_32(SDNode *N, 10681 DAGCombinerInfo &DCI) const { 10682 assert(N->getOpcode() == ISD::ADD); 10683 10684 SelectionDAG &DAG = DCI.DAG; 10685 EVT VT = N->getValueType(0); 10686 SDLoc SL(N); 10687 SDValue LHS = N->getOperand(0); 10688 SDValue RHS = N->getOperand(1); 10689 10690 if (VT.isVector()) 10691 return SDValue(); 10692 10693 // S_MUL_HI_[IU]32 was added in gfx9, which allows us to keep the overall 10694 // result in scalar registers for uniform values. 10695 if (!N->isDivergent() && Subtarget->hasSMulHi()) 10696 return SDValue(); 10697 10698 unsigned NumBits = VT.getScalarSizeInBits(); 10699 if (NumBits <= 32 || NumBits > 64) 10700 return SDValue(); 10701 10702 if (LHS.getOpcode() != ISD::MUL) { 10703 assert(RHS.getOpcode() == ISD::MUL); 10704 std::swap(LHS, RHS); 10705 } 10706 10707 // Avoid the fold if it would unduly increase the number of multiplies due to 10708 // multiple uses, except on hardware with full-rate multiply-add (which is 10709 // part of full-rate 64-bit ops). 10710 if (!Subtarget->hasFullRate64Ops()) { 10711 unsigned NumUsers = 0; 10712 for (SDNode *Use : LHS->uses()) { 10713 // There is a use that does not feed into addition, so the multiply can't 10714 // be removed. We prefer MUL + ADD + ADDC over MAD + MUL. 10715 if (Use->getOpcode() != ISD::ADD) 10716 return SDValue(); 10717 10718 // We prefer 2xMAD over MUL + 2xADD + 2xADDC (code density), and prefer 10719 // MUL + 3xADD + 3xADDC over 3xMAD. 10720 ++NumUsers; 10721 if (NumUsers >= 3) 10722 return SDValue(); 10723 } 10724 } 10725 10726 SDValue MulLHS = LHS.getOperand(0); 10727 SDValue MulRHS = LHS.getOperand(1); 10728 SDValue AddRHS = RHS; 10729 10730 // Always check whether operands are small unsigned values, since that 10731 // knowledge is useful in more cases. Check for small signed values only if 10732 // doing so can unlock a shorter code sequence. 10733 bool MulLHSUnsigned32 = numBitsUnsigned(MulLHS, DAG) <= 32; 10734 bool MulRHSUnsigned32 = numBitsUnsigned(MulRHS, DAG) <= 32; 10735 10736 bool MulSignedLo = false; 10737 if (!MulLHSUnsigned32 || !MulRHSUnsigned32) { 10738 MulSignedLo = numBitsSigned(MulLHS, DAG) <= 32 && 10739 numBitsSigned(MulRHS, DAG) <= 32; 10740 } 10741 10742 // The operands and final result all have the same number of bits. If 10743 // operands need to be extended, they can be extended with garbage. The 10744 // resulting garbage in the high bits of the mad_[iu]64_[iu]32 result is 10745 // truncated away in the end. 10746 if (VT != MVT::i64) { 10747 MulLHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulLHS); 10748 MulRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulRHS); 10749 AddRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, AddRHS); 10750 } 10751 10752 // The basic code generated is conceptually straightforward. Pseudo code: 10753 // 10754 // accum = mad_64_32 lhs.lo, rhs.lo, accum 10755 // accum.hi = add (mul lhs.hi, rhs.lo), accum.hi 10756 // accum.hi = add (mul lhs.lo, rhs.hi), accum.hi 10757 // 10758 // The second and third lines are optional, depending on whether the factors 10759 // are {sign,zero}-extended or not. 10760 // 10761 // The actual DAG is noisier than the pseudo code, but only due to 10762 // instructions that disassemble values into low and high parts, and 10763 // assemble the final result. 10764 SDValue Zero = DAG.getConstant(0, SL, MVT::i32); 10765 SDValue One = DAG.getConstant(1, SL, MVT::i32); 10766 10767 auto MulLHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulLHS); 10768 auto MulRHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulRHS); 10769 SDValue Accum = 10770 getMad64_32(DAG, SL, MVT::i64, MulLHSLo, MulRHSLo, AddRHS, MulSignedLo); 10771 10772 if (!MulSignedLo && (!MulLHSUnsigned32 || !MulRHSUnsigned32)) { 10773 auto AccumLo = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, Zero); 10774 auto AccumHi = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, One); 10775 10776 if (!MulLHSUnsigned32) { 10777 auto MulLHSHi = 10778 DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulLHS, One); 10779 SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSHi, MulRHSLo); 10780 AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi); 10781 } 10782 10783 if (!MulRHSUnsigned32) { 10784 auto MulRHSHi = 10785 DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulRHS, One); 10786 SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSLo, MulRHSHi); 10787 AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi); 10788 } 10789 10790 Accum = DAG.getBuildVector(MVT::v2i32, SL, {AccumLo, AccumHi}); 10791 Accum = DAG.getBitcast(MVT::i64, Accum); 10792 } 10793 10794 if (VT != MVT::i64) 10795 Accum = DAG.getNode(ISD::TRUNCATE, SL, VT, Accum); 10796 return Accum; 10797 } 10798 10799 SDValue SITargetLowering::performAddCombine(SDNode *N, 10800 DAGCombinerInfo &DCI) const { 10801 SelectionDAG &DAG = DCI.DAG; 10802 EVT VT = N->getValueType(0); 10803 SDLoc SL(N); 10804 SDValue LHS = N->getOperand(0); 10805 SDValue RHS = N->getOperand(1); 10806 10807 if (LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) { 10808 if (Subtarget->hasMad64_32()) { 10809 if (SDValue Folded = tryFoldToMad64_32(N, DCI)) 10810 return Folded; 10811 } 10812 10813 return SDValue(); 10814 } 10815 10816 if (SDValue V = reassociateScalarOps(N, DAG)) { 10817 return V; 10818 } 10819 10820 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10821 return SDValue(); 10822 10823 // add x, zext (setcc) => addcarry x, 0, setcc 10824 // add x, sext (setcc) => subcarry x, 0, setcc 10825 unsigned Opc = LHS.getOpcode(); 10826 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10827 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10828 std::swap(RHS, LHS); 10829 10830 Opc = RHS.getOpcode(); 10831 switch (Opc) { 10832 default: break; 10833 case ISD::ZERO_EXTEND: 10834 case ISD::SIGN_EXTEND: 10835 case ISD::ANY_EXTEND: { 10836 auto Cond = RHS.getOperand(0); 10837 // If this won't be a real VOPC output, we would still need to insert an 10838 // extra instruction anyway. 10839 if (!isBoolSGPR(Cond)) 10840 break; 10841 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10842 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10843 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10844 return DAG.getNode(Opc, SL, VTList, Args); 10845 } 10846 case ISD::ADDCARRY: { 10847 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10848 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10849 if (!C || C->getZExtValue() != 0) break; 10850 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10851 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10852 } 10853 } 10854 return SDValue(); 10855 } 10856 10857 SDValue SITargetLowering::performSubCombine(SDNode *N, 10858 DAGCombinerInfo &DCI) const { 10859 SelectionDAG &DAG = DCI.DAG; 10860 EVT VT = N->getValueType(0); 10861 10862 if (VT != MVT::i32) 10863 return SDValue(); 10864 10865 SDLoc SL(N); 10866 SDValue LHS = N->getOperand(0); 10867 SDValue RHS = N->getOperand(1); 10868 10869 // sub x, zext (setcc) => subcarry x, 0, setcc 10870 // sub x, sext (setcc) => addcarry x, 0, setcc 10871 unsigned Opc = RHS.getOpcode(); 10872 switch (Opc) { 10873 default: break; 10874 case ISD::ZERO_EXTEND: 10875 case ISD::SIGN_EXTEND: 10876 case ISD::ANY_EXTEND: { 10877 auto Cond = RHS.getOperand(0); 10878 // If this won't be a real VOPC output, we would still need to insert an 10879 // extra instruction anyway. 10880 if (!isBoolSGPR(Cond)) 10881 break; 10882 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10883 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10884 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10885 return DAG.getNode(Opc, SL, VTList, Args); 10886 } 10887 } 10888 10889 if (LHS.getOpcode() == ISD::SUBCARRY) { 10890 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10891 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10892 if (!C || !C->isZero()) 10893 return SDValue(); 10894 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10895 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10896 } 10897 return SDValue(); 10898 } 10899 10900 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10901 DAGCombinerInfo &DCI) const { 10902 10903 if (N->getValueType(0) != MVT::i32) 10904 return SDValue(); 10905 10906 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10907 if (!C || C->getZExtValue() != 0) 10908 return SDValue(); 10909 10910 SelectionDAG &DAG = DCI.DAG; 10911 SDValue LHS = N->getOperand(0); 10912 10913 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10914 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10915 unsigned LHSOpc = LHS.getOpcode(); 10916 unsigned Opc = N->getOpcode(); 10917 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10918 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10919 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10920 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10921 } 10922 return SDValue(); 10923 } 10924 10925 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10926 DAGCombinerInfo &DCI) const { 10927 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10928 return SDValue(); 10929 10930 SelectionDAG &DAG = DCI.DAG; 10931 EVT VT = N->getValueType(0); 10932 10933 SDLoc SL(N); 10934 SDValue LHS = N->getOperand(0); 10935 SDValue RHS = N->getOperand(1); 10936 10937 // These should really be instruction patterns, but writing patterns with 10938 // source modifiers is a pain. 10939 10940 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10941 if (LHS.getOpcode() == ISD::FADD) { 10942 SDValue A = LHS.getOperand(0); 10943 if (A == LHS.getOperand(1)) { 10944 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10945 if (FusedOp != 0) { 10946 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10947 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10948 } 10949 } 10950 } 10951 10952 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10953 if (RHS.getOpcode() == ISD::FADD) { 10954 SDValue A = RHS.getOperand(0); 10955 if (A == RHS.getOperand(1)) { 10956 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10957 if (FusedOp != 0) { 10958 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10959 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10960 } 10961 } 10962 } 10963 10964 return SDValue(); 10965 } 10966 10967 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10968 DAGCombinerInfo &DCI) const { 10969 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10970 return SDValue(); 10971 10972 SelectionDAG &DAG = DCI.DAG; 10973 SDLoc SL(N); 10974 EVT VT = N->getValueType(0); 10975 assert(!VT.isVector()); 10976 10977 // Try to get the fneg to fold into the source modifier. This undoes generic 10978 // DAG combines and folds them into the mad. 10979 // 10980 // Only do this if we are not trying to support denormals. v_mad_f32 does 10981 // not support denormals ever. 10982 SDValue LHS = N->getOperand(0); 10983 SDValue RHS = N->getOperand(1); 10984 if (LHS.getOpcode() == ISD::FADD) { 10985 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10986 SDValue A = LHS.getOperand(0); 10987 if (A == LHS.getOperand(1)) { 10988 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10989 if (FusedOp != 0){ 10990 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10991 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10992 10993 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10994 } 10995 } 10996 } 10997 10998 if (RHS.getOpcode() == ISD::FADD) { 10999 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 11000 11001 SDValue A = RHS.getOperand(0); 11002 if (A == RHS.getOperand(1)) { 11003 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 11004 if (FusedOp != 0){ 11005 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 11006 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 11007 } 11008 } 11009 } 11010 11011 return SDValue(); 11012 } 11013 11014 SDValue SITargetLowering::performFMACombine(SDNode *N, 11015 DAGCombinerInfo &DCI) const { 11016 SelectionDAG &DAG = DCI.DAG; 11017 EVT VT = N->getValueType(0); 11018 SDLoc SL(N); 11019 11020 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 11021 return SDValue(); 11022 11023 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 11024 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 11025 SDValue Op1 = N->getOperand(0); 11026 SDValue Op2 = N->getOperand(1); 11027 SDValue FMA = N->getOperand(2); 11028 11029 if (FMA.getOpcode() != ISD::FMA || 11030 Op1.getOpcode() != ISD::FP_EXTEND || 11031 Op2.getOpcode() != ISD::FP_EXTEND) 11032 return SDValue(); 11033 11034 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 11035 // regardless of the denorm mode setting. Therefore, 11036 // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2. 11037 const TargetOptions &Options = DAG.getTarget().Options; 11038 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 11039 (N->getFlags().hasAllowContract() && 11040 FMA->getFlags().hasAllowContract())) { 11041 Op1 = Op1.getOperand(0); 11042 Op2 = Op2.getOperand(0); 11043 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11044 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11045 return SDValue(); 11046 11047 SDValue Vec1 = Op1.getOperand(0); 11048 SDValue Idx1 = Op1.getOperand(1); 11049 SDValue Vec2 = Op2.getOperand(0); 11050 11051 SDValue FMAOp1 = FMA.getOperand(0); 11052 SDValue FMAOp2 = FMA.getOperand(1); 11053 SDValue FMAAcc = FMA.getOperand(2); 11054 11055 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 11056 FMAOp2.getOpcode() != ISD::FP_EXTEND) 11057 return SDValue(); 11058 11059 FMAOp1 = FMAOp1.getOperand(0); 11060 FMAOp2 = FMAOp2.getOperand(0); 11061 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11062 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11063 return SDValue(); 11064 11065 SDValue Vec3 = FMAOp1.getOperand(0); 11066 SDValue Vec4 = FMAOp2.getOperand(0); 11067 SDValue Idx2 = FMAOp1.getOperand(1); 11068 11069 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 11070 // Idx1 and Idx2 cannot be the same. 11071 Idx1 == Idx2) 11072 return SDValue(); 11073 11074 if (Vec1 == Vec2 || Vec3 == Vec4) 11075 return SDValue(); 11076 11077 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 11078 return SDValue(); 11079 11080 if ((Vec1 == Vec3 && Vec2 == Vec4) || 11081 (Vec1 == Vec4 && Vec2 == Vec3)) { 11082 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 11083 DAG.getTargetConstant(0, SL, MVT::i1)); 11084 } 11085 } 11086 return SDValue(); 11087 } 11088 11089 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 11090 DAGCombinerInfo &DCI) const { 11091 SelectionDAG &DAG = DCI.DAG; 11092 SDLoc SL(N); 11093 11094 SDValue LHS = N->getOperand(0); 11095 SDValue RHS = N->getOperand(1); 11096 EVT VT = LHS.getValueType(); 11097 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11098 11099 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 11100 if (!CRHS) { 11101 CRHS = dyn_cast<ConstantSDNode>(LHS); 11102 if (CRHS) { 11103 std::swap(LHS, RHS); 11104 CC = getSetCCSwappedOperands(CC); 11105 } 11106 } 11107 11108 if (CRHS) { 11109 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 11110 isBoolSGPR(LHS.getOperand(0))) { 11111 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 11112 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 11113 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 11114 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 11115 if ((CRHS->isAllOnes() && 11116 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 11117 (CRHS->isZero() && 11118 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 11119 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 11120 DAG.getConstant(-1, SL, MVT::i1)); 11121 if ((CRHS->isAllOnes() && 11122 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 11123 (CRHS->isZero() && 11124 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 11125 return LHS.getOperand(0); 11126 } 11127 11128 const APInt &CRHSVal = CRHS->getAPIntValue(); 11129 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 11130 LHS.getOpcode() == ISD::SELECT && 11131 isa<ConstantSDNode>(LHS.getOperand(1)) && 11132 isa<ConstantSDNode>(LHS.getOperand(2)) && 11133 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 11134 isBoolSGPR(LHS.getOperand(0))) { 11135 // Given CT != FT: 11136 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 11137 // setcc (select cc, CT, CF), CF, ne => cc 11138 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 11139 // setcc (select cc, CT, CF), CT, eq => cc 11140 const APInt &CT = LHS.getConstantOperandAPInt(1); 11141 const APInt &CF = LHS.getConstantOperandAPInt(2); 11142 11143 if ((CF == CRHSVal && CC == ISD::SETEQ) || 11144 (CT == CRHSVal && CC == ISD::SETNE)) 11145 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 11146 DAG.getConstant(-1, SL, MVT::i1)); 11147 if ((CF == CRHSVal && CC == ISD::SETNE) || 11148 (CT == CRHSVal && CC == ISD::SETEQ)) 11149 return LHS.getOperand(0); 11150 } 11151 } 11152 11153 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 11154 VT != MVT::f16)) 11155 return SDValue(); 11156 11157 // Match isinf/isfinite pattern 11158 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 11159 // (fcmp one (fabs x), inf) -> (fp_class x, 11160 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 11161 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 11162 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 11163 if (!CRHS) 11164 return SDValue(); 11165 11166 const APFloat &APF = CRHS->getValueAPF(); 11167 if (APF.isInfinity() && !APF.isNegative()) { 11168 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 11169 SIInstrFlags::N_INFINITY; 11170 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 11171 SIInstrFlags::P_ZERO | 11172 SIInstrFlags::N_NORMAL | 11173 SIInstrFlags::P_NORMAL | 11174 SIInstrFlags::N_SUBNORMAL | 11175 SIInstrFlags::P_SUBNORMAL; 11176 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 11177 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 11178 DAG.getConstant(Mask, SL, MVT::i32)); 11179 } 11180 } 11181 11182 return SDValue(); 11183 } 11184 11185 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 11186 DAGCombinerInfo &DCI) const { 11187 SelectionDAG &DAG = DCI.DAG; 11188 SDLoc SL(N); 11189 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 11190 11191 SDValue Src = N->getOperand(0); 11192 SDValue Shift = N->getOperand(0); 11193 11194 // TODO: Extend type shouldn't matter (assuming legal types). 11195 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 11196 Shift = Shift.getOperand(0); 11197 11198 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 11199 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 11200 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 11201 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 11202 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 11203 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 11204 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 11205 SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0), 11206 SDLoc(Shift.getOperand(0)), MVT::i32); 11207 11208 unsigned ShiftOffset = 8 * Offset; 11209 if (Shift.getOpcode() == ISD::SHL) 11210 ShiftOffset -= C->getZExtValue(); 11211 else 11212 ShiftOffset += C->getZExtValue(); 11213 11214 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 11215 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 11216 MVT::f32, Shifted); 11217 } 11218 } 11219 } 11220 11221 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11222 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 11223 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 11224 // We simplified Src. If this node is not dead, visit it again so it is 11225 // folded properly. 11226 if (N->getOpcode() != ISD::DELETED_NODE) 11227 DCI.AddToWorklist(N); 11228 return SDValue(N, 0); 11229 } 11230 11231 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 11232 if (SDValue DemandedSrc = 11233 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 11234 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 11235 11236 return SDValue(); 11237 } 11238 11239 SDValue SITargetLowering::performClampCombine(SDNode *N, 11240 DAGCombinerInfo &DCI) const { 11241 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 11242 if (!CSrc) 11243 return SDValue(); 11244 11245 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 11246 const APFloat &F = CSrc->getValueAPF(); 11247 APFloat Zero = APFloat::getZero(F.getSemantics()); 11248 if (F < Zero || 11249 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 11250 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 11251 } 11252 11253 APFloat One(F.getSemantics(), "1.0"); 11254 if (F > One) 11255 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 11256 11257 return SDValue(CSrc, 0); 11258 } 11259 11260 11261 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 11262 DAGCombinerInfo &DCI) const { 11263 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 11264 return SDValue(); 11265 switch (N->getOpcode()) { 11266 case ISD::ADD: 11267 return performAddCombine(N, DCI); 11268 case ISD::SUB: 11269 return performSubCombine(N, DCI); 11270 case ISD::ADDCARRY: 11271 case ISD::SUBCARRY: 11272 return performAddCarrySubCarryCombine(N, DCI); 11273 case ISD::FADD: 11274 return performFAddCombine(N, DCI); 11275 case ISD::FSUB: 11276 return performFSubCombine(N, DCI); 11277 case ISD::SETCC: 11278 return performSetCCCombine(N, DCI); 11279 case ISD::FMAXNUM: 11280 case ISD::FMINNUM: 11281 case ISD::FMAXNUM_IEEE: 11282 case ISD::FMINNUM_IEEE: 11283 case ISD::SMAX: 11284 case ISD::SMIN: 11285 case ISD::UMAX: 11286 case ISD::UMIN: 11287 case AMDGPUISD::FMIN_LEGACY: 11288 case AMDGPUISD::FMAX_LEGACY: 11289 return performMinMaxCombine(N, DCI); 11290 case ISD::FMA: 11291 return performFMACombine(N, DCI); 11292 case ISD::AND: 11293 return performAndCombine(N, DCI); 11294 case ISD::OR: 11295 return performOrCombine(N, DCI); 11296 case ISD::XOR: 11297 return performXorCombine(N, DCI); 11298 case ISD::ZERO_EXTEND: 11299 return performZeroExtendCombine(N, DCI); 11300 case ISD::SIGN_EXTEND_INREG: 11301 return performSignExtendInRegCombine(N , DCI); 11302 case AMDGPUISD::FP_CLASS: 11303 return performClassCombine(N, DCI); 11304 case ISD::FCANONICALIZE: 11305 return performFCanonicalizeCombine(N, DCI); 11306 case AMDGPUISD::RCP: 11307 return performRcpCombine(N, DCI); 11308 case AMDGPUISD::FRACT: 11309 case AMDGPUISD::RSQ: 11310 case AMDGPUISD::RCP_LEGACY: 11311 case AMDGPUISD::RCP_IFLAG: 11312 case AMDGPUISD::RSQ_CLAMP: 11313 case AMDGPUISD::LDEXP: { 11314 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 11315 SDValue Src = N->getOperand(0); 11316 if (Src.isUndef()) 11317 return Src; 11318 break; 11319 } 11320 case ISD::SINT_TO_FP: 11321 case ISD::UINT_TO_FP: 11322 return performUCharToFloatCombine(N, DCI); 11323 case AMDGPUISD::CVT_F32_UBYTE0: 11324 case AMDGPUISD::CVT_F32_UBYTE1: 11325 case AMDGPUISD::CVT_F32_UBYTE2: 11326 case AMDGPUISD::CVT_F32_UBYTE3: 11327 return performCvtF32UByteNCombine(N, DCI); 11328 case AMDGPUISD::FMED3: 11329 return performFMed3Combine(N, DCI); 11330 case AMDGPUISD::CVT_PKRTZ_F16_F32: 11331 return performCvtPkRTZCombine(N, DCI); 11332 case AMDGPUISD::CLAMP: 11333 return performClampCombine(N, DCI); 11334 case ISD::SCALAR_TO_VECTOR: { 11335 SelectionDAG &DAG = DCI.DAG; 11336 EVT VT = N->getValueType(0); 11337 11338 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 11339 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 11340 SDLoc SL(N); 11341 SDValue Src = N->getOperand(0); 11342 EVT EltVT = Src.getValueType(); 11343 if (EltVT == MVT::f16) 11344 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 11345 11346 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 11347 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 11348 } 11349 11350 break; 11351 } 11352 case ISD::EXTRACT_VECTOR_ELT: 11353 return performExtractVectorEltCombine(N, DCI); 11354 case ISD::INSERT_VECTOR_ELT: 11355 return performInsertVectorEltCombine(N, DCI); 11356 case ISD::LOAD: { 11357 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 11358 return Widended; 11359 LLVM_FALLTHROUGH; 11360 } 11361 default: { 11362 if (!DCI.isBeforeLegalize()) { 11363 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 11364 return performMemSDNodeCombine(MemNode, DCI); 11365 } 11366 11367 break; 11368 } 11369 } 11370 11371 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 11372 } 11373 11374 /// Helper function for adjustWritemask 11375 static unsigned SubIdx2Lane(unsigned Idx) { 11376 switch (Idx) { 11377 default: return ~0u; 11378 case AMDGPU::sub0: return 0; 11379 case AMDGPU::sub1: return 1; 11380 case AMDGPU::sub2: return 2; 11381 case AMDGPU::sub3: return 3; 11382 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 11383 } 11384 } 11385 11386 /// Adjust the writemask of MIMG instructions 11387 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 11388 SelectionDAG &DAG) const { 11389 unsigned Opcode = Node->getMachineOpcode(); 11390 11391 // Subtract 1 because the vdata output is not a MachineSDNode operand. 11392 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 11393 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 11394 return Node; // not implemented for D16 11395 11396 SDNode *Users[5] = { nullptr }; 11397 unsigned Lane = 0; 11398 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 11399 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 11400 unsigned NewDmask = 0; 11401 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 11402 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 11403 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 11404 Node->getConstantOperandVal(LWEIdx)) 11405 ? true 11406 : false; 11407 unsigned TFCLane = 0; 11408 bool HasChain = Node->getNumValues() > 1; 11409 11410 if (OldDmask == 0) { 11411 // These are folded out, but on the chance it happens don't assert. 11412 return Node; 11413 } 11414 11415 unsigned OldBitsSet = countPopulation(OldDmask); 11416 // Work out which is the TFE/LWE lane if that is enabled. 11417 if (UsesTFC) { 11418 TFCLane = OldBitsSet; 11419 } 11420 11421 // Try to figure out the used register components 11422 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 11423 I != E; ++I) { 11424 11425 // Don't look at users of the chain. 11426 if (I.getUse().getResNo() != 0) 11427 continue; 11428 11429 // Abort if we can't understand the usage 11430 if (!I->isMachineOpcode() || 11431 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 11432 return Node; 11433 11434 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 11435 // Note that subregs are packed, i.e. Lane==0 is the first bit set 11436 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 11437 // set, etc. 11438 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 11439 if (Lane == ~0u) 11440 return Node; 11441 11442 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 11443 if (UsesTFC && Lane == TFCLane) { 11444 Users[Lane] = *I; 11445 } else { 11446 // Set which texture component corresponds to the lane. 11447 unsigned Comp; 11448 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 11449 Comp = countTrailingZeros(Dmask); 11450 Dmask &= ~(1 << Comp); 11451 } 11452 11453 // Abort if we have more than one user per component. 11454 if (Users[Lane]) 11455 return Node; 11456 11457 Users[Lane] = *I; 11458 NewDmask |= 1 << Comp; 11459 } 11460 } 11461 11462 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11463 bool NoChannels = !NewDmask; 11464 if (NoChannels) { 11465 if (!UsesTFC) { 11466 // No uses of the result and not using TFC. Then do nothing. 11467 return Node; 11468 } 11469 // If the original dmask has one channel - then nothing to do 11470 if (OldBitsSet == 1) 11471 return Node; 11472 // Use an arbitrary dmask - required for the instruction to work 11473 NewDmask = 1; 11474 } 11475 // Abort if there's no change 11476 if (NewDmask == OldDmask) 11477 return Node; 11478 11479 unsigned BitsSet = countPopulation(NewDmask); 11480 11481 // Check for TFE or LWE - increase the number of channels by one to account 11482 // for the extra return value 11483 // This will need adjustment for D16 if this is also included in 11484 // adjustWriteMask (this function) but at present D16 are excluded. 11485 unsigned NewChannels = BitsSet + UsesTFC; 11486 11487 int NewOpcode = 11488 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11489 assert(NewOpcode != -1 && 11490 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11491 "failed to find equivalent MIMG op"); 11492 11493 // Adjust the writemask in the node 11494 SmallVector<SDValue, 12> Ops; 11495 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11496 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11497 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11498 11499 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11500 11501 MVT ResultVT = NewChannels == 1 ? 11502 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11503 NewChannels == 5 ? 8 : NewChannels); 11504 SDVTList NewVTList = HasChain ? 11505 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11506 11507 11508 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11509 NewVTList, Ops); 11510 11511 if (HasChain) { 11512 // Update chain. 11513 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11514 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11515 } 11516 11517 if (NewChannels == 1) { 11518 assert(Node->hasNUsesOfValue(1, 0)); 11519 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11520 SDLoc(Node), Users[Lane]->getValueType(0), 11521 SDValue(NewNode, 0)); 11522 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11523 return nullptr; 11524 } 11525 11526 // Update the users of the node with the new indices 11527 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11528 SDNode *User = Users[i]; 11529 if (!User) { 11530 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11531 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11532 if (i || !NoChannels) 11533 continue; 11534 } else { 11535 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11536 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11537 } 11538 11539 switch (Idx) { 11540 default: break; 11541 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11542 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11543 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11544 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11545 } 11546 } 11547 11548 DAG.RemoveDeadNode(Node); 11549 return nullptr; 11550 } 11551 11552 static bool isFrameIndexOp(SDValue Op) { 11553 if (Op.getOpcode() == ISD::AssertZext) 11554 Op = Op.getOperand(0); 11555 11556 return isa<FrameIndexSDNode>(Op); 11557 } 11558 11559 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11560 /// with frame index operands. 11561 /// LLVM assumes that inputs are to these instructions are registers. 11562 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11563 SelectionDAG &DAG) const { 11564 if (Node->getOpcode() == ISD::CopyToReg) { 11565 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11566 SDValue SrcVal = Node->getOperand(2); 11567 11568 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11569 // to try understanding copies to physical registers. 11570 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11571 SDLoc SL(Node); 11572 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11573 SDValue VReg = DAG.getRegister( 11574 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11575 11576 SDNode *Glued = Node->getGluedNode(); 11577 SDValue ToVReg 11578 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11579 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11580 SDValue ToResultReg 11581 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11582 VReg, ToVReg.getValue(1)); 11583 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11584 DAG.RemoveDeadNode(Node); 11585 return ToResultReg.getNode(); 11586 } 11587 } 11588 11589 SmallVector<SDValue, 8> Ops; 11590 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11591 if (!isFrameIndexOp(Node->getOperand(i))) { 11592 Ops.push_back(Node->getOperand(i)); 11593 continue; 11594 } 11595 11596 SDLoc DL(Node); 11597 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11598 Node->getOperand(i).getValueType(), 11599 Node->getOperand(i)), 0)); 11600 } 11601 11602 return DAG.UpdateNodeOperands(Node, Ops); 11603 } 11604 11605 /// Fold the instructions after selecting them. 11606 /// Returns null if users were already updated. 11607 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11608 SelectionDAG &DAG) const { 11609 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11610 unsigned Opcode = Node->getMachineOpcode(); 11611 11612 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11613 !TII->isGather4(Opcode) && 11614 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11615 return adjustWritemask(Node, DAG); 11616 } 11617 11618 if (Opcode == AMDGPU::INSERT_SUBREG || 11619 Opcode == AMDGPU::REG_SEQUENCE) { 11620 legalizeTargetIndependentNode(Node, DAG); 11621 return Node; 11622 } 11623 11624 switch (Opcode) { 11625 case AMDGPU::V_DIV_SCALE_F32_e64: 11626 case AMDGPU::V_DIV_SCALE_F64_e64: { 11627 // Satisfy the operand register constraint when one of the inputs is 11628 // undefined. Ordinarily each undef value will have its own implicit_def of 11629 // a vreg, so force these to use a single register. 11630 SDValue Src0 = Node->getOperand(1); 11631 SDValue Src1 = Node->getOperand(3); 11632 SDValue Src2 = Node->getOperand(5); 11633 11634 if ((Src0.isMachineOpcode() && 11635 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11636 (Src0 == Src1 || Src0 == Src2)) 11637 break; 11638 11639 MVT VT = Src0.getValueType().getSimpleVT(); 11640 const TargetRegisterClass *RC = 11641 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11642 11643 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11644 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11645 11646 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11647 UndefReg, Src0, SDValue()); 11648 11649 // src0 must be the same register as src1 or src2, even if the value is 11650 // undefined, so make sure we don't violate this constraint. 11651 if (Src0.isMachineOpcode() && 11652 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11653 if (Src1.isMachineOpcode() && 11654 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11655 Src0 = Src1; 11656 else if (Src2.isMachineOpcode() && 11657 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11658 Src0 = Src2; 11659 else { 11660 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11661 Src0 = UndefReg; 11662 Src1 = UndefReg; 11663 } 11664 } else 11665 break; 11666 11667 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11668 Ops[1] = Src0; 11669 Ops[3] = Src1; 11670 Ops[5] = Src2; 11671 Ops.push_back(ImpDef.getValue(1)); 11672 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11673 } 11674 default: 11675 break; 11676 } 11677 11678 return Node; 11679 } 11680 11681 // Any MIMG instructions that use tfe or lwe require an initialization of the 11682 // result register that will be written in the case of a memory access failure. 11683 // The required code is also added to tie this init code to the result of the 11684 // img instruction. 11685 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11686 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11687 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11688 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11689 MachineBasicBlock &MBB = *MI.getParent(); 11690 11691 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11692 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11693 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11694 11695 if (!TFE && !LWE) // intersect_ray 11696 return; 11697 11698 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11699 unsigned LWEVal = LWE->getImm(); 11700 unsigned D16Val = D16 ? D16->getImm() : 0; 11701 11702 if (!TFEVal && !LWEVal) 11703 return; 11704 11705 // At least one of TFE or LWE are non-zero 11706 // We have to insert a suitable initialization of the result value and 11707 // tie this to the dest of the image instruction. 11708 11709 const DebugLoc &DL = MI.getDebugLoc(); 11710 11711 int DstIdx = 11712 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11713 11714 // Calculate which dword we have to initialize to 0. 11715 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11716 11717 // check that dmask operand is found. 11718 assert(MO_Dmask && "Expected dmask operand in instruction"); 11719 11720 unsigned dmask = MO_Dmask->getImm(); 11721 // Determine the number of active lanes taking into account the 11722 // Gather4 special case 11723 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11724 11725 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11726 11727 unsigned InitIdx = 11728 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11729 11730 // Abandon attempt if the dst size isn't large enough 11731 // - this is in fact an error but this is picked up elsewhere and 11732 // reported correctly. 11733 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11734 if (DstSize < InitIdx) 11735 return; 11736 11737 // Create a register for the initialization value. 11738 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11739 unsigned NewDst = 0; // Final initialized value will be in here 11740 11741 // If PRTStrictNull feature is enabled (the default) then initialize 11742 // all the result registers to 0, otherwise just the error indication 11743 // register (VGPRn+1) 11744 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11745 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11746 11747 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11748 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11749 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11750 // Initialize dword 11751 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11752 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11753 .addImm(0); 11754 // Insert into the super-reg 11755 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11756 .addReg(PrevDst) 11757 .addReg(SubReg) 11758 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11759 11760 PrevDst = NewDst; 11761 } 11762 11763 // Add as an implicit operand 11764 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11765 11766 // Tie the just added implicit operand to the dst 11767 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11768 } 11769 11770 /// Assign the register class depending on the number of 11771 /// bits set in the writemask 11772 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11773 SDNode *Node) const { 11774 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11775 11776 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11777 11778 if (TII->isVOP3(MI.getOpcode())) { 11779 // Make sure constant bus requirements are respected. 11780 TII->legalizeOperandsVOP3(MRI, MI); 11781 11782 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11783 // This saves a chain-copy of registers and better balance register 11784 // use between vgpr and agpr as agpr tuples tend to be big. 11785 if (MI.getDesc().OpInfo) { 11786 unsigned Opc = MI.getOpcode(); 11787 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11788 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11789 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11790 if (I == -1) 11791 break; 11792 MachineOperand &Op = MI.getOperand(I); 11793 if (!Op.isReg() || !Op.getReg().isVirtual()) 11794 continue; 11795 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11796 if (!TRI->hasAGPRs(RC)) 11797 continue; 11798 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11799 if (!Src || !Src->isCopy() || 11800 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11801 continue; 11802 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11803 // All uses of agpr64 and agpr32 can also accept vgpr except for 11804 // v_accvgpr_read, but we do not produce agpr reads during selection, 11805 // so no use checks are needed. 11806 MRI.setRegClass(Op.getReg(), NewRC); 11807 } 11808 11809 // Resolve the rest of AV operands to AGPRs. 11810 if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) { 11811 if (Src2->isReg() && Src2->getReg().isVirtual()) { 11812 auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg()); 11813 if (TRI->isVectorSuperClass(RC)) { 11814 auto *NewRC = TRI->getEquivalentAGPRClass(RC); 11815 MRI.setRegClass(Src2->getReg(), NewRC); 11816 if (Src2->isTied()) 11817 MRI.setRegClass(MI.getOperand(0).getReg(), NewRC); 11818 } 11819 } 11820 } 11821 } 11822 11823 return; 11824 } 11825 11826 if (TII->isMIMG(MI)) { 11827 if (!MI.mayStore()) 11828 AddIMGInit(MI); 11829 TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::vaddr); 11830 } 11831 } 11832 11833 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11834 uint64_t Val) { 11835 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11836 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11837 } 11838 11839 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11840 const SDLoc &DL, 11841 SDValue Ptr) const { 11842 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11843 11844 // Build the half of the subregister with the constants before building the 11845 // full 128-bit register. If we are building multiple resource descriptors, 11846 // this will allow CSEing of the 2-component register. 11847 const SDValue Ops0[] = { 11848 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11849 buildSMovImm32(DAG, DL, 0), 11850 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11851 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11852 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11853 }; 11854 11855 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11856 MVT::v2i32, Ops0), 0); 11857 11858 // Combine the constants and the pointer. 11859 const SDValue Ops1[] = { 11860 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11861 Ptr, 11862 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11863 SubRegHi, 11864 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11865 }; 11866 11867 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11868 } 11869 11870 /// Return a resource descriptor with the 'Add TID' bit enabled 11871 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11872 /// of the resource descriptor) to create an offset, which is added to 11873 /// the resource pointer. 11874 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11875 SDValue Ptr, uint32_t RsrcDword1, 11876 uint64_t RsrcDword2And3) const { 11877 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11878 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11879 if (RsrcDword1) { 11880 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11881 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11882 0); 11883 } 11884 11885 SDValue DataLo = buildSMovImm32(DAG, DL, 11886 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11887 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11888 11889 const SDValue Ops[] = { 11890 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11891 PtrLo, 11892 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11893 PtrHi, 11894 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11895 DataLo, 11896 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11897 DataHi, 11898 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11899 }; 11900 11901 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11902 } 11903 11904 //===----------------------------------------------------------------------===// 11905 // SI Inline Assembly Support 11906 //===----------------------------------------------------------------------===// 11907 11908 std::pair<unsigned, const TargetRegisterClass *> 11909 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11910 StringRef Constraint, 11911 MVT VT) const { 11912 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11913 11914 const TargetRegisterClass *RC = nullptr; 11915 if (Constraint.size() == 1) { 11916 const unsigned BitWidth = VT.getSizeInBits(); 11917 switch (Constraint[0]) { 11918 default: 11919 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11920 case 's': 11921 case 'r': 11922 switch (BitWidth) { 11923 case 16: 11924 RC = &AMDGPU::SReg_32RegClass; 11925 break; 11926 case 64: 11927 RC = &AMDGPU::SGPR_64RegClass; 11928 break; 11929 default: 11930 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11931 if (!RC) 11932 return std::make_pair(0U, nullptr); 11933 break; 11934 } 11935 break; 11936 case 'v': 11937 switch (BitWidth) { 11938 case 16: 11939 RC = &AMDGPU::VGPR_32RegClass; 11940 break; 11941 default: 11942 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11943 if (!RC) 11944 return std::make_pair(0U, nullptr); 11945 break; 11946 } 11947 break; 11948 case 'a': 11949 if (!Subtarget->hasMAIInsts()) 11950 break; 11951 switch (BitWidth) { 11952 case 16: 11953 RC = &AMDGPU::AGPR_32RegClass; 11954 break; 11955 default: 11956 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11957 if (!RC) 11958 return std::make_pair(0U, nullptr); 11959 break; 11960 } 11961 break; 11962 } 11963 // We actually support i128, i16 and f16 as inline parameters 11964 // even if they are not reported as legal 11965 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11966 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11967 return std::make_pair(0U, RC); 11968 } 11969 11970 if (Constraint.startswith("{") && Constraint.endswith("}")) { 11971 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 11972 if (RegName.consume_front("v")) { 11973 RC = &AMDGPU::VGPR_32RegClass; 11974 } else if (RegName.consume_front("s")) { 11975 RC = &AMDGPU::SGPR_32RegClass; 11976 } else if (RegName.consume_front("a")) { 11977 RC = &AMDGPU::AGPR_32RegClass; 11978 } 11979 11980 if (RC) { 11981 uint32_t Idx; 11982 if (RegName.consume_front("[")) { 11983 uint32_t End; 11984 bool Failed = RegName.consumeInteger(10, Idx); 11985 Failed |= !RegName.consume_front(":"); 11986 Failed |= RegName.consumeInteger(10, End); 11987 Failed |= !RegName.consume_back("]"); 11988 if (!Failed) { 11989 uint32_t Width = (End - Idx + 1) * 32; 11990 MCRegister Reg = RC->getRegister(Idx); 11991 if (SIRegisterInfo::isVGPRClass(RC)) 11992 RC = TRI->getVGPRClassForBitWidth(Width); 11993 else if (SIRegisterInfo::isSGPRClass(RC)) 11994 RC = TRI->getSGPRClassForBitWidth(Width); 11995 else if (SIRegisterInfo::isAGPRClass(RC)) 11996 RC = TRI->getAGPRClassForBitWidth(Width); 11997 if (RC) { 11998 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC); 11999 return std::make_pair(Reg, RC); 12000 } 12001 } 12002 } else { 12003 bool Failed = RegName.getAsInteger(10, Idx); 12004 if (!Failed && Idx < RC->getNumRegs()) 12005 return std::make_pair(RC->getRegister(Idx), RC); 12006 } 12007 } 12008 } 12009 12010 auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 12011 if (Ret.first) 12012 Ret.second = TRI->getPhysRegClass(Ret.first); 12013 12014 return Ret; 12015 } 12016 12017 static bool isImmConstraint(StringRef Constraint) { 12018 if (Constraint.size() == 1) { 12019 switch (Constraint[0]) { 12020 default: break; 12021 case 'I': 12022 case 'J': 12023 case 'A': 12024 case 'B': 12025 case 'C': 12026 return true; 12027 } 12028 } else if (Constraint == "DA" || 12029 Constraint == "DB") { 12030 return true; 12031 } 12032 return false; 12033 } 12034 12035 SITargetLowering::ConstraintType 12036 SITargetLowering::getConstraintType(StringRef Constraint) const { 12037 if (Constraint.size() == 1) { 12038 switch (Constraint[0]) { 12039 default: break; 12040 case 's': 12041 case 'v': 12042 case 'a': 12043 return C_RegisterClass; 12044 } 12045 } 12046 if (isImmConstraint(Constraint)) { 12047 return C_Other; 12048 } 12049 return TargetLowering::getConstraintType(Constraint); 12050 } 12051 12052 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 12053 if (!AMDGPU::isInlinableIntLiteral(Val)) { 12054 Val = Val & maskTrailingOnes<uint64_t>(Size); 12055 } 12056 return Val; 12057 } 12058 12059 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 12060 std::string &Constraint, 12061 std::vector<SDValue> &Ops, 12062 SelectionDAG &DAG) const { 12063 if (isImmConstraint(Constraint)) { 12064 uint64_t Val; 12065 if (getAsmOperandConstVal(Op, Val) && 12066 checkAsmConstraintVal(Op, Constraint, Val)) { 12067 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 12068 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 12069 } 12070 } else { 12071 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12072 } 12073 } 12074 12075 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 12076 unsigned Size = Op.getScalarValueSizeInBits(); 12077 if (Size > 64) 12078 return false; 12079 12080 if (Size == 16 && !Subtarget->has16BitInsts()) 12081 return false; 12082 12083 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12084 Val = C->getSExtValue(); 12085 return true; 12086 } 12087 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 12088 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 12089 return true; 12090 } 12091 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 12092 if (Size != 16 || Op.getNumOperands() != 2) 12093 return false; 12094 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 12095 return false; 12096 if (ConstantSDNode *C = V->getConstantSplatNode()) { 12097 Val = C->getSExtValue(); 12098 return true; 12099 } 12100 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 12101 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 12102 return true; 12103 } 12104 } 12105 12106 return false; 12107 } 12108 12109 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 12110 const std::string &Constraint, 12111 uint64_t Val) const { 12112 if (Constraint.size() == 1) { 12113 switch (Constraint[0]) { 12114 case 'I': 12115 return AMDGPU::isInlinableIntLiteral(Val); 12116 case 'J': 12117 return isInt<16>(Val); 12118 case 'A': 12119 return checkAsmConstraintValA(Op, Val); 12120 case 'B': 12121 return isInt<32>(Val); 12122 case 'C': 12123 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 12124 AMDGPU::isInlinableIntLiteral(Val); 12125 default: 12126 break; 12127 } 12128 } else if (Constraint.size() == 2) { 12129 if (Constraint == "DA") { 12130 int64_t HiBits = static_cast<int32_t>(Val >> 32); 12131 int64_t LoBits = static_cast<int32_t>(Val); 12132 return checkAsmConstraintValA(Op, HiBits, 32) && 12133 checkAsmConstraintValA(Op, LoBits, 32); 12134 } 12135 if (Constraint == "DB") { 12136 return true; 12137 } 12138 } 12139 llvm_unreachable("Invalid asm constraint"); 12140 } 12141 12142 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 12143 uint64_t Val, 12144 unsigned MaxSize) const { 12145 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 12146 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 12147 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 12148 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 12149 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 12150 return true; 12151 } 12152 return false; 12153 } 12154 12155 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 12156 switch (UnalignedClassID) { 12157 case AMDGPU::VReg_64RegClassID: 12158 return AMDGPU::VReg_64_Align2RegClassID; 12159 case AMDGPU::VReg_96RegClassID: 12160 return AMDGPU::VReg_96_Align2RegClassID; 12161 case AMDGPU::VReg_128RegClassID: 12162 return AMDGPU::VReg_128_Align2RegClassID; 12163 case AMDGPU::VReg_160RegClassID: 12164 return AMDGPU::VReg_160_Align2RegClassID; 12165 case AMDGPU::VReg_192RegClassID: 12166 return AMDGPU::VReg_192_Align2RegClassID; 12167 case AMDGPU::VReg_224RegClassID: 12168 return AMDGPU::VReg_224_Align2RegClassID; 12169 case AMDGPU::VReg_256RegClassID: 12170 return AMDGPU::VReg_256_Align2RegClassID; 12171 case AMDGPU::VReg_512RegClassID: 12172 return AMDGPU::VReg_512_Align2RegClassID; 12173 case AMDGPU::VReg_1024RegClassID: 12174 return AMDGPU::VReg_1024_Align2RegClassID; 12175 case AMDGPU::AReg_64RegClassID: 12176 return AMDGPU::AReg_64_Align2RegClassID; 12177 case AMDGPU::AReg_96RegClassID: 12178 return AMDGPU::AReg_96_Align2RegClassID; 12179 case AMDGPU::AReg_128RegClassID: 12180 return AMDGPU::AReg_128_Align2RegClassID; 12181 case AMDGPU::AReg_160RegClassID: 12182 return AMDGPU::AReg_160_Align2RegClassID; 12183 case AMDGPU::AReg_192RegClassID: 12184 return AMDGPU::AReg_192_Align2RegClassID; 12185 case AMDGPU::AReg_256RegClassID: 12186 return AMDGPU::AReg_256_Align2RegClassID; 12187 case AMDGPU::AReg_512RegClassID: 12188 return AMDGPU::AReg_512_Align2RegClassID; 12189 case AMDGPU::AReg_1024RegClassID: 12190 return AMDGPU::AReg_1024_Align2RegClassID; 12191 default: 12192 return -1; 12193 } 12194 } 12195 12196 // Figure out which registers should be reserved for stack access. Only after 12197 // the function is legalized do we know all of the non-spill stack objects or if 12198 // calls are present. 12199 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 12200 MachineRegisterInfo &MRI = MF.getRegInfo(); 12201 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12202 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 12203 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12204 const SIInstrInfo *TII = ST.getInstrInfo(); 12205 12206 if (Info->isEntryFunction()) { 12207 // Callable functions have fixed registers used for stack access. 12208 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 12209 } 12210 12211 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 12212 Info->getStackPtrOffsetReg())); 12213 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 12214 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 12215 12216 // We need to worry about replacing the default register with itself in case 12217 // of MIR testcases missing the MFI. 12218 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 12219 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 12220 12221 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 12222 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 12223 12224 Info->limitOccupancy(MF); 12225 12226 if (ST.isWave32() && !MF.empty()) { 12227 for (auto &MBB : MF) { 12228 for (auto &MI : MBB) { 12229 TII->fixImplicitOperands(MI); 12230 } 12231 } 12232 } 12233 12234 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 12235 // classes if required. Ideally the register class constraints would differ 12236 // per-subtarget, but there's no easy way to achieve that right now. This is 12237 // not a problem for VGPRs because the correctly aligned VGPR class is implied 12238 // from using them as the register class for legal types. 12239 if (ST.needsAlignedVGPRs()) { 12240 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 12241 const Register Reg = Register::index2VirtReg(I); 12242 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 12243 if (!RC) 12244 continue; 12245 int NewClassID = getAlignedAGPRClassID(RC->getID()); 12246 if (NewClassID != -1) 12247 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 12248 } 12249 } 12250 12251 TargetLoweringBase::finalizeLowering(MF); 12252 } 12253 12254 void SITargetLowering::computeKnownBitsForFrameIndex( 12255 const int FI, KnownBits &Known, const MachineFunction &MF) const { 12256 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 12257 12258 // Set the high bits to zero based on the maximum allowed scratch size per 12259 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 12260 // calculation won't overflow, so assume the sign bit is never set. 12261 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 12262 } 12263 12264 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 12265 KnownBits &Known, unsigned Dim) { 12266 unsigned MaxValue = 12267 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 12268 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 12269 } 12270 12271 void SITargetLowering::computeKnownBitsForTargetInstr( 12272 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 12273 const MachineRegisterInfo &MRI, unsigned Depth) const { 12274 const MachineInstr *MI = MRI.getVRegDef(R); 12275 switch (MI->getOpcode()) { 12276 case AMDGPU::G_INTRINSIC: { 12277 switch (MI->getIntrinsicID()) { 12278 case Intrinsic::amdgcn_workitem_id_x: 12279 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 12280 break; 12281 case Intrinsic::amdgcn_workitem_id_y: 12282 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 12283 break; 12284 case Intrinsic::amdgcn_workitem_id_z: 12285 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 12286 break; 12287 case Intrinsic::amdgcn_mbcnt_lo: 12288 case Intrinsic::amdgcn_mbcnt_hi: { 12289 // These return at most the wavefront size - 1. 12290 unsigned Size = MRI.getType(R).getSizeInBits(); 12291 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 12292 break; 12293 } 12294 case Intrinsic::amdgcn_groupstaticsize: { 12295 // We can report everything over the maximum size as 0. We can't report 12296 // based on the actual size because we don't know if it's accurate or not 12297 // at any given point. 12298 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 12299 break; 12300 } 12301 } 12302 break; 12303 } 12304 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 12305 Known.Zero.setHighBits(24); 12306 break; 12307 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 12308 Known.Zero.setHighBits(16); 12309 break; 12310 } 12311 } 12312 12313 Align SITargetLowering::computeKnownAlignForTargetInstr( 12314 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 12315 unsigned Depth) const { 12316 const MachineInstr *MI = MRI.getVRegDef(R); 12317 switch (MI->getOpcode()) { 12318 case AMDGPU::G_INTRINSIC: 12319 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 12320 // FIXME: Can this move to generic code? What about the case where the call 12321 // site specifies a lower alignment? 12322 Intrinsic::ID IID = MI->getIntrinsicID(); 12323 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 12324 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 12325 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 12326 return *RetAlign; 12327 return Align(1); 12328 } 12329 default: 12330 return Align(1); 12331 } 12332 } 12333 12334 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12335 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 12336 const Align CacheLineAlign = Align(64); 12337 12338 // Pre-GFX10 target did not benefit from loop alignment 12339 if (!ML || DisableLoopAlignment || 12340 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 12341 getSubtarget()->hasInstFwdPrefetchBug()) 12342 return PrefAlign; 12343 12344 // On GFX10 I$ is 4 x 64 bytes cache lines. 12345 // By default prefetcher keeps one cache line behind and reads two ahead. 12346 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 12347 // behind and one ahead. 12348 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 12349 // If loop fits 64 bytes it always spans no more than two cache lines and 12350 // does not need an alignment. 12351 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 12352 // Else if loop is less or equal 192 bytes we need two lines behind. 12353 12354 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 12355 const MachineBasicBlock *Header = ML->getHeader(); 12356 if (Header->getAlignment() != PrefAlign) 12357 return Header->getAlignment(); // Already processed. 12358 12359 unsigned LoopSize = 0; 12360 for (const MachineBasicBlock *MBB : ML->blocks()) { 12361 // If inner loop block is aligned assume in average half of the alignment 12362 // size to be added as nops. 12363 if (MBB != Header) 12364 LoopSize += MBB->getAlignment().value() / 2; 12365 12366 for (const MachineInstr &MI : *MBB) { 12367 LoopSize += TII->getInstSizeInBytes(MI); 12368 if (LoopSize > 192) 12369 return PrefAlign; 12370 } 12371 } 12372 12373 if (LoopSize <= 64) 12374 return PrefAlign; 12375 12376 if (LoopSize <= 128) 12377 return CacheLineAlign; 12378 12379 // If any of parent loops is surrounded by prefetch instructions do not 12380 // insert new for inner loop, which would reset parent's settings. 12381 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 12382 if (MachineBasicBlock *Exit = P->getExitBlock()) { 12383 auto I = Exit->getFirstNonDebugInstr(); 12384 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 12385 return CacheLineAlign; 12386 } 12387 } 12388 12389 MachineBasicBlock *Pre = ML->getLoopPreheader(); 12390 MachineBasicBlock *Exit = ML->getExitBlock(); 12391 12392 if (Pre && Exit) { 12393 auto PreTerm = Pre->getFirstTerminator(); 12394 if (PreTerm == Pre->begin() || 12395 std::prev(PreTerm)->getOpcode() != AMDGPU::S_INST_PREFETCH) 12396 BuildMI(*Pre, PreTerm, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH)) 12397 .addImm(1); // prefetch 2 lines behind PC 12398 12399 auto ExitHead = Exit->getFirstNonDebugInstr(); 12400 if (ExitHead == Exit->end() || 12401 ExitHead->getOpcode() != AMDGPU::S_INST_PREFETCH) 12402 BuildMI(*Exit, ExitHead, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH)) 12403 .addImm(2); // prefetch 1 line behind PC 12404 } 12405 12406 return CacheLineAlign; 12407 } 12408 12409 LLVM_ATTRIBUTE_UNUSED 12410 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 12411 assert(N->getOpcode() == ISD::CopyFromReg); 12412 do { 12413 // Follow the chain until we find an INLINEASM node. 12414 N = N->getOperand(0).getNode(); 12415 if (N->getOpcode() == ISD::INLINEASM || 12416 N->getOpcode() == ISD::INLINEASM_BR) 12417 return true; 12418 } while (N->getOpcode() == ISD::CopyFromReg); 12419 return false; 12420 } 12421 12422 bool SITargetLowering::isSDNodeSourceOfDivergence( 12423 const SDNode *N, FunctionLoweringInfo *FLI, 12424 LegacyDivergenceAnalysis *KDA) const { 12425 switch (N->getOpcode()) { 12426 case ISD::CopyFromReg: { 12427 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 12428 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 12429 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12430 Register Reg = R->getReg(); 12431 12432 // FIXME: Why does this need to consider isLiveIn? 12433 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 12434 return !TRI->isSGPRReg(MRI, Reg); 12435 12436 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 12437 return KDA->isDivergent(V); 12438 12439 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 12440 return !TRI->isSGPRReg(MRI, Reg); 12441 } 12442 case ISD::LOAD: { 12443 const LoadSDNode *L = cast<LoadSDNode>(N); 12444 unsigned AS = L->getAddressSpace(); 12445 // A flat load may access private memory. 12446 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 12447 } 12448 case ISD::CALLSEQ_END: 12449 return true; 12450 case ISD::INTRINSIC_WO_CHAIN: 12451 return AMDGPU::isIntrinsicSourceOfDivergence( 12452 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 12453 case ISD::INTRINSIC_W_CHAIN: 12454 return AMDGPU::isIntrinsicSourceOfDivergence( 12455 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 12456 case AMDGPUISD::ATOMIC_CMP_SWAP: 12457 case AMDGPUISD::ATOMIC_INC: 12458 case AMDGPUISD::ATOMIC_DEC: 12459 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12460 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12461 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12462 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12463 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12464 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12465 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12466 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12467 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12468 case AMDGPUISD::BUFFER_ATOMIC_AND: 12469 case AMDGPUISD::BUFFER_ATOMIC_OR: 12470 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12471 case AMDGPUISD::BUFFER_ATOMIC_INC: 12472 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12473 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12474 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12475 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12476 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12477 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12478 // Target-specific read-modify-write atomics are sources of divergence. 12479 return true; 12480 default: 12481 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12482 // Generic read-modify-write atomics are sources of divergence. 12483 return A->readMem() && A->writeMem(); 12484 } 12485 return false; 12486 } 12487 } 12488 12489 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12490 EVT VT) const { 12491 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12492 case MVT::f32: 12493 return hasFP32Denormals(DAG.getMachineFunction()); 12494 case MVT::f64: 12495 case MVT::f16: 12496 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12497 default: 12498 return false; 12499 } 12500 } 12501 12502 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12503 MachineFunction &MF) const { 12504 switch (Ty.getScalarSizeInBits()) { 12505 case 32: 12506 return hasFP32Denormals(MF); 12507 case 64: 12508 case 16: 12509 return hasFP64FP16Denormals(MF); 12510 default: 12511 return false; 12512 } 12513 } 12514 12515 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12516 const SelectionDAG &DAG, 12517 bool SNaN, 12518 unsigned Depth) const { 12519 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12520 const MachineFunction &MF = DAG.getMachineFunction(); 12521 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12522 12523 if (Info->getMode().DX10Clamp) 12524 return true; // Clamped to 0. 12525 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12526 } 12527 12528 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12529 SNaN, Depth); 12530 } 12531 12532 // Global FP atomic instructions have a hardcoded FP mode and do not support 12533 // FP32 denormals, and only support v2f16 denormals. 12534 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12535 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12536 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12537 if (&Flt == &APFloat::IEEEsingle()) 12538 return DenormMode == DenormalMode::getPreserveSign(); 12539 return DenormMode == DenormalMode::getIEEE(); 12540 } 12541 12542 TargetLowering::AtomicExpansionKind 12543 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12544 unsigned AS = RMW->getPointerAddressSpace(); 12545 if (AS == AMDGPUAS::PRIVATE_ADDRESS) 12546 return AtomicExpansionKind::NotAtomic; 12547 12548 auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) { 12549 OptimizationRemarkEmitter ORE(RMW->getFunction()); 12550 LLVMContext &Ctx = RMW->getFunction()->getContext(); 12551 SmallVector<StringRef> SSNs; 12552 Ctx.getSyncScopeNames(SSNs); 12553 auto MemScope = SSNs[RMW->getSyncScopeID()].empty() 12554 ? "system" 12555 : SSNs[RMW->getSyncScopeID()]; 12556 ORE.emit([&]() { 12557 return OptimizationRemark(DEBUG_TYPE, "Passed", RMW) 12558 << "Hardware instruction generated for atomic " 12559 << RMW->getOperationName(RMW->getOperation()) 12560 << " operation at memory scope " << MemScope 12561 << " due to an unsafe request."; 12562 }); 12563 return Kind; 12564 }; 12565 12566 switch (RMW->getOperation()) { 12567 case AtomicRMWInst::FAdd: { 12568 Type *Ty = RMW->getType(); 12569 12570 // We don't have a way to support 16-bit atomics now, so just leave them 12571 // as-is. 12572 if (Ty->isHalfTy()) 12573 return AtomicExpansionKind::None; 12574 12575 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12576 return AtomicExpansionKind::CmpXChg; 12577 12578 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12579 Subtarget->hasAtomicFaddInsts()) { 12580 if (Subtarget->hasGFX940Insts()) 12581 return AtomicExpansionKind::None; 12582 12583 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12584 // floating point atomic instructions. May generate more efficient code, 12585 // but may not respect rounding and denormal modes, and may give incorrect 12586 // results for certain memory destinations. 12587 if (RMW->getFunction() 12588 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12589 .getValueAsString() != "true") 12590 return AtomicExpansionKind::CmpXChg; 12591 12592 if (Subtarget->hasGFX90AInsts()) { 12593 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) 12594 return AtomicExpansionKind::CmpXChg; 12595 12596 auto SSID = RMW->getSyncScopeID(); 12597 if (SSID == SyncScope::System || 12598 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12599 return AtomicExpansionKind::CmpXChg; 12600 12601 return ReportUnsafeHWInst(AtomicExpansionKind::None); 12602 } 12603 12604 if (AS == AMDGPUAS::FLAT_ADDRESS) 12605 return AtomicExpansionKind::CmpXChg; 12606 12607 return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12608 : AtomicExpansionKind::CmpXChg; 12609 } 12610 12611 // DS FP atomics do respect the denormal mode, but the rounding mode is 12612 // fixed to round-to-nearest-even. 12613 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12614 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) { 12615 if (!Ty->isDoubleTy()) 12616 return AtomicExpansionKind::None; 12617 12618 if (fpModeMatchesGlobalFPAtomicMode(RMW)) 12619 return AtomicExpansionKind::None; 12620 12621 return RMW->getFunction() 12622 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12623 .getValueAsString() == "true" 12624 ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12625 : AtomicExpansionKind::CmpXChg; 12626 } 12627 12628 return AtomicExpansionKind::CmpXChg; 12629 } 12630 default: 12631 break; 12632 } 12633 12634 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12635 } 12636 12637 TargetLowering::AtomicExpansionKind 12638 SITargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 12639 return LI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12640 ? AtomicExpansionKind::NotAtomic 12641 : AtomicExpansionKind::None; 12642 } 12643 12644 TargetLowering::AtomicExpansionKind 12645 SITargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 12646 return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12647 ? AtomicExpansionKind::NotAtomic 12648 : AtomicExpansionKind::None; 12649 } 12650 12651 TargetLowering::AtomicExpansionKind 12652 SITargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CmpX) const { 12653 return CmpX->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12654 ? AtomicExpansionKind::NotAtomic 12655 : AtomicExpansionKind::None; 12656 } 12657 12658 const TargetRegisterClass * 12659 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12660 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12661 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12662 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12663 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12664 : &AMDGPU::SReg_32RegClass; 12665 if (!TRI->isSGPRClass(RC) && !isDivergent) 12666 return TRI->getEquivalentSGPRClass(RC); 12667 else if (TRI->isSGPRClass(RC) && isDivergent) 12668 return TRI->getEquivalentVGPRClass(RC); 12669 12670 return RC; 12671 } 12672 12673 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12674 // uniform values (as produced by the mask results of control flow intrinsics) 12675 // used outside of divergent blocks. The phi users need to also be treated as 12676 // always uniform. 12677 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12678 unsigned WaveSize) { 12679 // FIXME: We assume we never cast the mask results of a control flow 12680 // intrinsic. 12681 // Early exit if the type won't be consistent as a compile time hack. 12682 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12683 if (!IT || IT->getBitWidth() != WaveSize) 12684 return false; 12685 12686 if (!isa<Instruction>(V)) 12687 return false; 12688 if (!Visited.insert(V).second) 12689 return false; 12690 bool Result = false; 12691 for (auto U : V->users()) { 12692 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12693 if (V == U->getOperand(1)) { 12694 switch (Intrinsic->getIntrinsicID()) { 12695 default: 12696 Result = false; 12697 break; 12698 case Intrinsic::amdgcn_if_break: 12699 case Intrinsic::amdgcn_if: 12700 case Intrinsic::amdgcn_else: 12701 Result = true; 12702 break; 12703 } 12704 } 12705 if (V == U->getOperand(0)) { 12706 switch (Intrinsic->getIntrinsicID()) { 12707 default: 12708 Result = false; 12709 break; 12710 case Intrinsic::amdgcn_end_cf: 12711 case Intrinsic::amdgcn_loop: 12712 Result = true; 12713 break; 12714 } 12715 } 12716 } else { 12717 Result = hasCFUser(U, Visited, WaveSize); 12718 } 12719 if (Result) 12720 break; 12721 } 12722 return Result; 12723 } 12724 12725 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12726 const Value *V) const { 12727 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12728 if (CI->isInlineAsm()) { 12729 // FIXME: This cannot give a correct answer. This should only trigger in 12730 // the case where inline asm returns mixed SGPR and VGPR results, used 12731 // outside the defining block. We don't have a specific result to 12732 // consider, so this assumes if any value is SGPR, the overall register 12733 // also needs to be SGPR. 12734 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12735 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12736 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12737 for (auto &TC : TargetConstraints) { 12738 if (TC.Type == InlineAsm::isOutput) { 12739 ComputeConstraintToUse(TC, SDValue()); 12740 const TargetRegisterClass *RC = getRegForInlineAsmConstraint( 12741 SIRI, TC.ConstraintCode, TC.ConstraintVT).second; 12742 if (RC && SIRI->isSGPRClass(RC)) 12743 return true; 12744 } 12745 } 12746 } 12747 } 12748 SmallPtrSet<const Value *, 16> Visited; 12749 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12750 } 12751 12752 std::pair<InstructionCost, MVT> 12753 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12754 Type *Ty) const { 12755 std::pair<InstructionCost, MVT> Cost = 12756 TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12757 auto Size = DL.getTypeSizeInBits(Ty); 12758 // Maximum load or store can handle 8 dwords for scalar and 4 for 12759 // vector ALU. Let's assume anything above 8 dwords is expensive 12760 // even if legal. 12761 if (Size <= 256) 12762 return Cost; 12763 12764 Cost.first += (Size + 255) / 256; 12765 return Cost; 12766 } 12767 12768 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const { 12769 SDNode::use_iterator I = N->use_begin(), E = N->use_end(); 12770 for (; I != E; ++I) { 12771 if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) { 12772 if (getBasePtrIndex(M) == I.getOperandNo()) 12773 return true; 12774 } 12775 } 12776 return false; 12777 } 12778 12779 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0, 12780 SDValue N1) const { 12781 if (!N0.hasOneUse()) 12782 return false; 12783 // Take care of the opportunity to keep N0 uniform 12784 if (N0->isDivergent() || !N1->isDivergent()) 12785 return true; 12786 // Check if we have a good chance to form the memory access pattern with the 12787 // base and offset 12788 return (DAG.isBaseWithConstantOffset(N0) && 12789 hasMemSDNodeUser(*N0->use_begin())); 12790 } 12791 12792 MachineMemOperand::Flags 12793 SITargetLowering::getTargetMMOFlags(const Instruction &I) const { 12794 // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load. 12795 if (I.getMetadata("amdgpu.noclobber")) 12796 return MONoClobber; 12797 return MachineMemOperand::MONone; 12798 } 12799