1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// Custom DAG lowering for SI 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "SIISelLowering.h" 15 #include "AMDGPU.h" 16 #include "AMDGPUInstrInfo.h" 17 #include "AMDGPUTargetMachine.h" 18 #include "SIMachineFunctionInfo.h" 19 #include "SIRegisterInfo.h" 20 #include "llvm/ADT/FloatingPointMode.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 23 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 24 #include "llvm/BinaryFormat/ELF.h" 25 #include "llvm/CodeGen/Analysis.h" 26 #include "llvm/CodeGen/FunctionLoweringInfo.h" 27 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 28 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h" 29 #include "llvm/CodeGen/MachineFrameInfo.h" 30 #include "llvm/CodeGen/MachineFunction.h" 31 #include "llvm/CodeGen/MachineLoopInfo.h" 32 #include "llvm/IR/DiagnosticInfo.h" 33 #include "llvm/IR/IntrinsicInst.h" 34 #include "llvm/IR/IntrinsicsAMDGPU.h" 35 #include "llvm/IR/IntrinsicsR600.h" 36 #include "llvm/Support/CommandLine.h" 37 #include "llvm/Support/KnownBits.h" 38 39 using namespace llvm; 40 41 #define DEBUG_TYPE "si-lower" 42 43 STATISTIC(NumTailCalls, "Number of tail calls"); 44 45 static cl::opt<bool> DisableLoopAlignment( 46 "amdgpu-disable-loop-alignment", 47 cl::desc("Do not align and prefetch loops"), 48 cl::init(false)); 49 50 static cl::opt<bool> UseDivergentRegisterIndexing( 51 "amdgpu-use-divergent-register-indexing", 52 cl::Hidden, 53 cl::desc("Use indirect register addressing for divergent indexes"), 54 cl::init(false)); 55 56 static bool hasFP32Denormals(const MachineFunction &MF) { 57 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 58 return Info->getMode().allFP32Denormals(); 59 } 60 61 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 62 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 63 return Info->getMode().allFP64FP16Denormals(); 64 } 65 66 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 67 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 68 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 69 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 70 return AMDGPU::SGPR0 + Reg; 71 } 72 } 73 llvm_unreachable("Cannot allocate sgpr"); 74 } 75 76 SITargetLowering::SITargetLowering(const TargetMachine &TM, 77 const GCNSubtarget &STI) 78 : AMDGPUTargetLowering(TM, STI), 79 Subtarget(&STI) { 80 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 81 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 82 83 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 84 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 85 86 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 87 88 const SIRegisterInfo *TRI = STI.getRegisterInfo(); 89 const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class(); 90 91 addRegisterClass(MVT::f64, V64RegClass); 92 addRegisterClass(MVT::v2f32, V64RegClass); 93 94 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 95 addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96)); 96 97 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 98 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 99 100 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 101 addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128)); 102 103 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 104 addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160)); 105 106 addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass); 107 addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192)); 108 109 addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass); 110 addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192)); 111 112 addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass); 113 addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224)); 114 115 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 116 addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256)); 117 118 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 119 addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256)); 120 121 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 122 addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512)); 123 124 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 125 addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512)); 126 127 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 128 addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024)); 129 130 if (Subtarget->has16BitInsts()) { 131 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 132 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 133 134 // Unless there are also VOP3P operations, not operations are really legal. 135 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 136 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 137 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 138 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 139 addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass); 140 addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass); 141 } 142 143 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 144 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024)); 145 146 computeRegisterProperties(Subtarget->getRegisterInfo()); 147 148 // The boolean content concept here is too inflexible. Compares only ever 149 // really produce a 1-bit result. Any copy/extend from these will turn into a 150 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 151 // it's what most targets use. 152 setBooleanContents(ZeroOrOneBooleanContent); 153 setBooleanVectorContents(ZeroOrOneBooleanContent); 154 155 // We need to custom lower vector stores from local memory 156 setOperationAction(ISD::LOAD, 157 {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32, 158 MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v16i32, MVT::i1, 159 MVT::v32i32}, 160 Custom); 161 162 setOperationAction(ISD::STORE, 163 {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32, 164 MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v16i32, MVT::i1, 165 MVT::v32i32}, 166 Custom); 167 168 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 169 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 170 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 171 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 172 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 173 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 174 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 175 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 176 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 177 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 178 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 179 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 180 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 181 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 182 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 183 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 184 185 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand); 186 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand); 187 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 188 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 189 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 190 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 191 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 192 193 setOperationAction(ISD::GlobalAddress, {MVT::i32, MVT::i64}, Custom); 194 195 setOperationAction(ISD::SELECT, MVT::i1, Promote); 196 setOperationAction(ISD::SELECT, MVT::i64, Custom); 197 setOperationAction(ISD::SELECT, MVT::f64, Promote); 198 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 199 200 setOperationAction(ISD::SELECT_CC, 201 {MVT::f32, MVT::i32, MVT::i64, MVT::f64, MVT::i1}, Expand); 202 203 setOperationAction(ISD::SETCC, MVT::i1, Promote); 204 setOperationAction(ISD::SETCC, {MVT::v2i1, MVT::v4i1}, Expand); 205 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 206 207 setOperationAction(ISD::TRUNCATE, 208 {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32, 209 MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v16i32}, 210 Expand); 211 setOperationAction(ISD::FP_ROUND, 212 {MVT::v2f32, MVT::v3f32, MVT::v4f32, MVT::v5f32, 213 MVT::v6f32, MVT::v7f32, MVT::v8f32, MVT::v16f32}, 214 Expand); 215 216 setOperationAction(ISD::SIGN_EXTEND_INREG, 217 {MVT::v2i1, MVT::v4i1, MVT::v2i8, MVT::v4i8, MVT::v2i16, 218 MVT::v3i16, MVT::v4i16, MVT::Other}, 219 Custom); 220 221 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 222 setOperationAction(ISD::BR_CC, 223 {MVT::i1, MVT::i32, MVT::i64, MVT::f32, MVT::f64}, Expand); 224 225 setOperationAction({ISD::UADDO, ISD::USUBO}, MVT::i32, Legal); 226 227 setOperationAction({ISD::ADDCARRY, ISD::SUBCARRY}, MVT::i32, Legal); 228 229 setOperationAction({ISD::SHL_PARTS, ISD::SRA_PARTS, ISD::SRL_PARTS}, MVT::i64, 230 Expand); 231 232 #if 0 233 setOperationAction({ISD::ADDCARRY, ISD::SUBCARRY}, MVT::i64, Legal); 234 #endif 235 236 // We only support LOAD/STORE and vector manipulation ops for vectors 237 // with > 4 elements. 238 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 239 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 240 MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32, 241 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 242 MVT::v8i16, MVT::v8f16, MVT::v16i64, MVT::v16f64, 243 MVT::v32i32, MVT::v32f32 }) { 244 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 245 switch (Op) { 246 case ISD::LOAD: 247 case ISD::STORE: 248 case ISD::BUILD_VECTOR: 249 case ISD::BITCAST: 250 case ISD::EXTRACT_VECTOR_ELT: 251 case ISD::INSERT_VECTOR_ELT: 252 case ISD::EXTRACT_SUBVECTOR: 253 case ISD::SCALAR_TO_VECTOR: 254 break; 255 case ISD::INSERT_SUBVECTOR: 256 case ISD::CONCAT_VECTORS: 257 setOperationAction(Op, VT, Custom); 258 break; 259 default: 260 setOperationAction(Op, VT, Expand); 261 break; 262 } 263 } 264 } 265 266 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 267 268 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 269 // is expanded to avoid having two separate loops in case the index is a VGPR. 270 271 // Most operations are naturally 32-bit vector operations. We only support 272 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 273 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 274 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 275 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 276 277 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 278 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 279 280 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 281 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 282 283 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 284 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 285 } 286 287 for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) { 288 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 289 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32); 290 291 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 292 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32); 293 294 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 295 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32); 296 297 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 298 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32); 299 } 300 301 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 302 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 303 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 304 305 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 306 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 307 308 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 309 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 310 311 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 312 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 313 } 314 315 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 316 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 317 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 318 319 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 320 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 321 322 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 323 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 324 325 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 326 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 327 } 328 329 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 330 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 331 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 332 333 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 334 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 335 336 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 337 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 338 339 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 340 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 341 } 342 343 setOperationAction(ISD::VECTOR_SHUFFLE, 344 {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32}, 345 Expand); 346 347 setOperationAction(ISD::BUILD_VECTOR, {MVT::v4f16, MVT::v4i16}, Custom); 348 349 // Avoid stack access for these. 350 // TODO: Generalize to more vector types. 351 setOperationAction({ISD::EXTRACT_VECTOR_ELT, ISD::INSERT_VECTOR_ELT}, 352 {MVT::v2i16, MVT::v2f16, MVT::v2i8, MVT::v4i8, MVT::v8i8, 353 MVT::v4i16, MVT::v4f16}, 354 Custom); 355 356 // Deal with vec3 vector operations when widened to vec4. 357 setOperationAction(ISD::INSERT_SUBVECTOR, 358 {MVT::v3i32, MVT::v3f32, MVT::v4i32, MVT::v4f32}, Custom); 359 360 // Deal with vec5/6/7 vector operations when widened to vec8. 361 setOperationAction(ISD::INSERT_SUBVECTOR, 362 {MVT::v5i32, MVT::v5f32, MVT::v6i32, MVT::v6f32, 363 MVT::v7i32, MVT::v7f32, MVT::v8i32, MVT::v8f32}, 364 Custom); 365 366 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 367 // and output demarshalling 368 setOperationAction(ISD::ATOMIC_CMP_SWAP, {MVT::i32, MVT::i64}, Custom); 369 370 // We can't return success/failure, only the old value, 371 // let LLVM add the comparison 372 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, {MVT::i32, MVT::i64}, 373 Expand); 374 375 if (Subtarget->hasFlatAddressSpace()) 376 setOperationAction(ISD::ADDRSPACECAST, {MVT::i32, MVT::i64}, Custom); 377 378 setOperationAction(ISD::BITREVERSE, {MVT::i32, MVT::i64}, Legal); 379 380 // FIXME: This should be narrowed to i32, but that only happens if i64 is 381 // illegal. 382 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 383 setOperationAction(ISD::BSWAP, {MVT::i64, MVT::i32}, Legal); 384 385 // On SI this is s_memtime and s_memrealtime on VI. 386 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 387 setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Custom); 388 389 if (Subtarget->has16BitInsts()) { 390 setOperationAction({ISD::FPOW, ISD::FPOWI}, MVT::f16, Promote); 391 setOperationAction({ISD::FLOG, ISD::FEXP, ISD::FLOG10}, MVT::f16, Custom); 392 } 393 394 if (Subtarget->hasMadMacF32Insts()) 395 setOperationAction(ISD::FMAD, MVT::f32, Legal); 396 397 if (!Subtarget->hasBFI()) 398 // fcopysign can be done in a single instruction with BFI. 399 setOperationAction(ISD::FCOPYSIGN, {MVT::f32, MVT::f64}, Expand); 400 401 if (!Subtarget->hasBCNT(32)) 402 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 403 404 if (!Subtarget->hasBCNT(64)) 405 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 406 407 if (Subtarget->hasFFBH()) 408 setOperationAction({ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF}, MVT::i32, Custom); 409 410 if (Subtarget->hasFFBL()) 411 setOperationAction({ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF}, MVT::i32, Custom); 412 413 // We only really have 32-bit BFE instructions (and 16-bit on VI). 414 // 415 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 416 // effort to match them now. We want this to be false for i64 cases when the 417 // extraction isn't restricted to the upper or lower half. Ideally we would 418 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 419 // span the midpoint are probably relatively rare, so don't worry about them 420 // for now. 421 if (Subtarget->hasBFE()) 422 setHasExtractBitsInsn(true); 423 424 // Clamp modifier on add/sub 425 if (Subtarget->hasIntClamp()) 426 setOperationAction({ISD::UADDSAT, ISD::USUBSAT}, MVT::i32, Legal); 427 428 if (Subtarget->hasAddNoCarry()) 429 setOperationAction({ISD::SADDSAT, ISD::SSUBSAT}, {MVT::i16, MVT::i32}, 430 Legal); 431 432 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, {MVT::f32, MVT::f64}, 433 Custom); 434 435 // These are really only legal for ieee_mode functions. We should be avoiding 436 // them for functions that don't have ieee_mode enabled, so just say they are 437 // legal. 438 setOperationAction({ISD::FMINNUM_IEEE, ISD::FMAXNUM_IEEE}, 439 {MVT::f32, MVT::f64}, Legal); 440 441 if (Subtarget->haveRoundOpsF64()) 442 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FRINT}, MVT::f64, Legal); 443 else 444 setOperationAction({ISD::FCEIL, ISD::FTRUNC, ISD::FRINT, ISD::FFLOOR}, 445 MVT::f64, Custom); 446 447 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 448 449 setOperationAction({ISD::FSIN, ISD::FCOS, ISD::FDIV}, MVT::f32, Custom); 450 setOperationAction(ISD::FDIV, MVT::f64, Custom); 451 452 if (Subtarget->has16BitInsts()) { 453 setOperationAction({ISD::Constant, ISD::SMIN, ISD::SMAX, ISD::UMIN, 454 ISD::UMAX, ISD::UADDSAT, ISD::USUBSAT}, 455 MVT::i16, Legal); 456 457 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 458 459 setOperationAction({ISD::ROTR, ISD::ROTL, ISD::SELECT_CC, ISD::BR_CC}, 460 MVT::i16, Expand); 461 462 setOperationAction({ISD::SIGN_EXTEND, ISD::SDIV, ISD::UDIV, ISD::SREM, 463 ISD::UREM, ISD::BITREVERSE, ISD::CTTZ, 464 ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF, 465 ISD::CTPOP}, 466 MVT::i16, Promote); 467 468 setOperationAction(ISD::LOAD, MVT::i16, Custom); 469 470 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 471 472 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 473 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 474 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 475 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 476 477 setOperationAction({ISD::FP_TO_SINT, ISD::FP_TO_UINT}, MVT::i16, Custom); 478 479 // F16 - Constant Actions. 480 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 481 482 // F16 - Load/Store Actions. 483 setOperationAction(ISD::LOAD, MVT::f16, Promote); 484 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 485 setOperationAction(ISD::STORE, MVT::f16, Promote); 486 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 487 488 // F16 - VOP1 Actions. 489 setOperationAction( 490 {ISD::FP_ROUND, ISD::FCOS, ISD::FSIN, ISD::FROUND, ISD::FPTRUNC_ROUND}, 491 MVT::f16, Custom); 492 493 setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP}, MVT::i16, Custom); 494 495 setOperationAction( 496 {ISD::FP_TO_SINT, ISD::FP_TO_UINT, ISD::SINT_TO_FP, ISD::UINT_TO_FP}, 497 MVT::f16, Promote); 498 499 // F16 - VOP2 Actions. 500 setOperationAction({ISD::BR_CC, ISD::SELECT_CC}, MVT::f16, Expand); 501 502 setOperationAction(ISD::FDIV, MVT::f16, Custom); 503 504 // F16 - VOP3 Actions. 505 setOperationAction(ISD::FMA, MVT::f16, Legal); 506 if (STI.hasMadF16()) 507 setOperationAction(ISD::FMAD, MVT::f16, Legal); 508 509 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16, MVT::v8i16, 510 MVT::v8f16}) { 511 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 512 switch (Op) { 513 case ISD::LOAD: 514 case ISD::STORE: 515 case ISD::BUILD_VECTOR: 516 case ISD::BITCAST: 517 case ISD::EXTRACT_VECTOR_ELT: 518 case ISD::INSERT_VECTOR_ELT: 519 case ISD::INSERT_SUBVECTOR: 520 case ISD::EXTRACT_SUBVECTOR: 521 case ISD::SCALAR_TO_VECTOR: 522 break; 523 case ISD::CONCAT_VECTORS: 524 setOperationAction(Op, VT, Custom); 525 break; 526 default: 527 setOperationAction(Op, VT, Expand); 528 break; 529 } 530 } 531 } 532 533 // v_perm_b32 can handle either of these. 534 setOperationAction(ISD::BSWAP, {MVT::i16, MVT::v2i16}, Legal); 535 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 536 537 // XXX - Do these do anything? Vector constants turn into build_vector. 538 setOperationAction(ISD::Constant, {MVT::v2i16, MVT::v2f16}, Legal); 539 540 setOperationAction(ISD::UNDEF, {MVT::v2i16, MVT::v2f16}, Legal); 541 542 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 543 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 544 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 545 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 546 547 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 548 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 549 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 550 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 551 552 setOperationAction(ISD::AND, MVT::v2i16, Promote); 553 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 554 setOperationAction(ISD::OR, MVT::v2i16, Promote); 555 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 556 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 557 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 558 559 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 560 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 561 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 562 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 563 564 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 565 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 566 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 567 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 568 569 setOperationAction(ISD::LOAD, MVT::v8i16, Promote); 570 AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32); 571 setOperationAction(ISD::LOAD, MVT::v8f16, Promote); 572 AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32); 573 574 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 575 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 576 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 577 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 578 579 setOperationAction(ISD::STORE, MVT::v8i16, Promote); 580 AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32); 581 setOperationAction(ISD::STORE, MVT::v8f16, Promote); 582 AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32); 583 584 setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND}, 585 MVT::v2i32, Expand); 586 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 587 588 setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND}, 589 MVT::v4i32, Expand); 590 591 setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND}, 592 MVT::v8i32, Expand); 593 594 if (!Subtarget->hasVOP3PInsts()) 595 setOperationAction(ISD::BUILD_VECTOR, {MVT::v2i16, MVT::v2f16}, Custom); 596 597 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 598 // This isn't really legal, but this avoids the legalizer unrolling it (and 599 // allows matching fneg (fabs x) patterns) 600 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 601 602 setOperationAction({ISD::FMAXNUM, ISD::FMINNUM}, MVT::f16, Custom); 603 setOperationAction({ISD::FMAXNUM_IEEE, ISD::FMINNUM_IEEE}, MVT::f16, Legal); 604 605 setOperationAction({ISD::FMINNUM_IEEE, ISD::FMAXNUM_IEEE}, 606 {MVT::v4f16, MVT::v8f16}, Custom); 607 608 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, {MVT::v4f16, MVT::v8f16}, 609 Expand); 610 611 for (MVT Vec16 : { MVT::v8i16, MVT::v8f16 }) { 612 setOperationAction( 613 {ISD::BUILD_VECTOR, ISD::EXTRACT_VECTOR_ELT, ISD::SCALAR_TO_VECTOR}, 614 Vec16, Custom); 615 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec16, Expand); 616 } 617 } 618 619 if (Subtarget->hasVOP3PInsts()) { 620 setOperationAction({ISD::ADD, ISD::SUB, ISD::MUL, ISD::SHL, ISD::SRL, 621 ISD::SRA, ISD::SMIN, ISD::UMIN, ISD::SMAX, ISD::UMAX, 622 ISD::UADDSAT, ISD::USUBSAT, ISD::SADDSAT, ISD::SSUBSAT}, 623 MVT::v2i16, Legal); 624 625 setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FMINNUM_IEEE, 626 ISD::FMAXNUM_IEEE, ISD::FCANONICALIZE}, 627 MVT::v2f16, Legal); 628 629 setOperationAction(ISD::EXTRACT_VECTOR_ELT, {MVT::v2i16, MVT::v2f16}, 630 Custom); 631 632 setOperationAction(ISD::VECTOR_SHUFFLE, 633 {MVT::v4f16, MVT::v4i16, MVT::v8f16, MVT::v8i16}, 634 Custom); 635 636 for (MVT VT : {MVT::v4i16, MVT::v8i16}) 637 // Split vector operations. 638 setOperationAction({ISD::SHL, ISD::SRA, ISD::SRL, ISD::ADD, ISD::SUB, 639 ISD::MUL, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, 640 ISD::UADDSAT, ISD::SADDSAT, ISD::USUBSAT, 641 ISD::SSUBSAT}, 642 VT, Custom); 643 644 for (MVT VT : {MVT::v4f16, MVT::v8f16}) 645 // Split vector operations. 646 setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FCANONICALIZE}, 647 VT, Custom); 648 649 setOperationAction({ISD::FMAXNUM, ISD::FMINNUM}, {MVT::v2f16, MVT::v4f16}, 650 Custom); 651 652 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 653 setOperationAction(ISD::SELECT, {MVT::v4i16, MVT::v4f16}, Custom); 654 655 if (Subtarget->hasPackedFP32Ops()) { 656 setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FNEG}, 657 MVT::v2f32, Legal); 658 setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA}, 659 {MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32}, 660 Custom); 661 } 662 } 663 664 setOperationAction({ISD::FNEG, ISD::FABS}, MVT::v4f16, Custom); 665 666 if (Subtarget->has16BitInsts()) { 667 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 668 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 669 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 670 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 671 } else { 672 // Legalization hack. 673 setOperationAction(ISD::SELECT, {MVT::v2i16, MVT::v2f16}, Custom); 674 675 setOperationAction({ISD::FNEG, ISD::FABS}, MVT::v2f16, Custom); 676 } 677 678 setOperationAction(ISD::SELECT, 679 {MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8, 680 MVT::v8i16, MVT::v8f16}, 681 Custom); 682 683 setOperationAction({ISD::SMULO, ISD::UMULO}, MVT::i64, Custom); 684 685 if (Subtarget->hasMad64_32()) 686 setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, MVT::i32, Custom); 687 688 setOperationAction(ISD::INTRINSIC_WO_CHAIN, 689 {MVT::Other, MVT::f32, MVT::v4f32, MVT::i16, MVT::f16, 690 MVT::v2i16, MVT::v2f16}, 691 Custom); 692 693 setOperationAction(ISD::INTRINSIC_W_CHAIN, 694 {MVT::v2f16, MVT::v2i16, MVT::v3f16, MVT::v3i16, 695 MVT::v4f16, MVT::v4i16, MVT::v8f16, MVT::Other, MVT::f16, 696 MVT::i16, MVT::i8}, 697 Custom); 698 699 setOperationAction(ISD::INTRINSIC_VOID, 700 {MVT::Other, MVT::v2i16, MVT::v2f16, MVT::v3i16, 701 MVT::v3f16, MVT::v4f16, MVT::v4i16, MVT::f16, MVT::i16, 702 MVT::i8}, 703 Custom); 704 705 setTargetDAGCombine({ISD::ADD, 706 ISD::ADDCARRY, 707 ISD::SUB, 708 ISD::SUBCARRY, 709 ISD::FADD, 710 ISD::FSUB, 711 ISD::FMINNUM, 712 ISD::FMAXNUM, 713 ISD::FMINNUM_IEEE, 714 ISD::FMAXNUM_IEEE, 715 ISD::FMA, 716 ISD::SMIN, 717 ISD::SMAX, 718 ISD::UMIN, 719 ISD::UMAX, 720 ISD::SETCC, 721 ISD::AND, 722 ISD::OR, 723 ISD::XOR, 724 ISD::SINT_TO_FP, 725 ISD::UINT_TO_FP, 726 ISD::FCANONICALIZE, 727 ISD::SCALAR_TO_VECTOR, 728 ISD::ZERO_EXTEND, 729 ISD::SIGN_EXTEND_INREG, 730 ISD::EXTRACT_VECTOR_ELT, 731 ISD::INSERT_VECTOR_ELT}); 732 733 // All memory operations. Some folding on the pointer operand is done to help 734 // matching the constant offsets in the addressing modes. 735 setTargetDAGCombine({ISD::LOAD, 736 ISD::STORE, 737 ISD::ATOMIC_LOAD, 738 ISD::ATOMIC_STORE, 739 ISD::ATOMIC_CMP_SWAP, 740 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 741 ISD::ATOMIC_SWAP, 742 ISD::ATOMIC_LOAD_ADD, 743 ISD::ATOMIC_LOAD_SUB, 744 ISD::ATOMIC_LOAD_AND, 745 ISD::ATOMIC_LOAD_OR, 746 ISD::ATOMIC_LOAD_XOR, 747 ISD::ATOMIC_LOAD_NAND, 748 ISD::ATOMIC_LOAD_MIN, 749 ISD::ATOMIC_LOAD_MAX, 750 ISD::ATOMIC_LOAD_UMIN, 751 ISD::ATOMIC_LOAD_UMAX, 752 ISD::ATOMIC_LOAD_FADD, 753 ISD::INTRINSIC_VOID, 754 ISD::INTRINSIC_W_CHAIN}); 755 756 // FIXME: In other contexts we pretend this is a per-function property. 757 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 758 759 setSchedulingPreference(Sched::RegPressure); 760 } 761 762 const GCNSubtarget *SITargetLowering::getSubtarget() const { 763 return Subtarget; 764 } 765 766 //===----------------------------------------------------------------------===// 767 // TargetLowering queries 768 //===----------------------------------------------------------------------===// 769 770 // v_mad_mix* support a conversion from f16 to f32. 771 // 772 // There is only one special case when denormals are enabled we don't currently, 773 // where this is OK to use. 774 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 775 EVT DestVT, EVT SrcVT) const { 776 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 777 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 778 DestVT.getScalarType() == MVT::f32 && 779 SrcVT.getScalarType() == MVT::f16 && 780 // TODO: This probably only requires no input flushing? 781 !hasFP32Denormals(DAG.getMachineFunction()); 782 } 783 784 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode, 785 LLT DestTy, LLT SrcTy) const { 786 return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) || 787 (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) && 788 DestTy.getScalarSizeInBits() == 32 && 789 SrcTy.getScalarSizeInBits() == 16 && 790 // TODO: This probably only requires no input flushing? 791 !hasFP32Denormals(*MI.getMF()); 792 } 793 794 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 795 // SI has some legal vector types, but no legal vector operations. Say no 796 // shuffles are legal in order to prefer scalarizing some vector operations. 797 return false; 798 } 799 800 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 801 CallingConv::ID CC, 802 EVT VT) const { 803 if (CC == CallingConv::AMDGPU_KERNEL) 804 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 805 806 if (VT.isVector()) { 807 EVT ScalarVT = VT.getScalarType(); 808 unsigned Size = ScalarVT.getSizeInBits(); 809 if (Size == 16) { 810 if (Subtarget->has16BitInsts()) 811 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 812 return VT.isInteger() ? MVT::i32 : MVT::f32; 813 } 814 815 if (Size < 16) 816 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 817 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 818 } 819 820 if (VT.getSizeInBits() > 32) 821 return MVT::i32; 822 823 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 824 } 825 826 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 827 CallingConv::ID CC, 828 EVT VT) const { 829 if (CC == CallingConv::AMDGPU_KERNEL) 830 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 831 832 if (VT.isVector()) { 833 unsigned NumElts = VT.getVectorNumElements(); 834 EVT ScalarVT = VT.getScalarType(); 835 unsigned Size = ScalarVT.getSizeInBits(); 836 837 // FIXME: Should probably promote 8-bit vectors to i16. 838 if (Size == 16 && Subtarget->has16BitInsts()) 839 return (NumElts + 1) / 2; 840 841 if (Size <= 32) 842 return NumElts; 843 844 if (Size > 32) 845 return NumElts * ((Size + 31) / 32); 846 } else if (VT.getSizeInBits() > 32) 847 return (VT.getSizeInBits() + 31) / 32; 848 849 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 850 } 851 852 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 853 LLVMContext &Context, CallingConv::ID CC, 854 EVT VT, EVT &IntermediateVT, 855 unsigned &NumIntermediates, MVT &RegisterVT) const { 856 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 857 unsigned NumElts = VT.getVectorNumElements(); 858 EVT ScalarVT = VT.getScalarType(); 859 unsigned Size = ScalarVT.getSizeInBits(); 860 // FIXME: We should fix the ABI to be the same on targets without 16-bit 861 // support, but unless we can properly handle 3-vectors, it will be still be 862 // inconsistent. 863 if (Size == 16 && Subtarget->has16BitInsts()) { 864 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 865 IntermediateVT = RegisterVT; 866 NumIntermediates = (NumElts + 1) / 2; 867 return NumIntermediates; 868 } 869 870 if (Size == 32) { 871 RegisterVT = ScalarVT.getSimpleVT(); 872 IntermediateVT = RegisterVT; 873 NumIntermediates = NumElts; 874 return NumIntermediates; 875 } 876 877 if (Size < 16 && Subtarget->has16BitInsts()) { 878 // FIXME: Should probably form v2i16 pieces 879 RegisterVT = MVT::i16; 880 IntermediateVT = ScalarVT; 881 NumIntermediates = NumElts; 882 return NumIntermediates; 883 } 884 885 886 if (Size != 16 && Size <= 32) { 887 RegisterVT = MVT::i32; 888 IntermediateVT = ScalarVT; 889 NumIntermediates = NumElts; 890 return NumIntermediates; 891 } 892 893 if (Size > 32) { 894 RegisterVT = MVT::i32; 895 IntermediateVT = RegisterVT; 896 NumIntermediates = NumElts * ((Size + 31) / 32); 897 return NumIntermediates; 898 } 899 } 900 901 return TargetLowering::getVectorTypeBreakdownForCallingConv( 902 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 903 } 904 905 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 906 assert(DMaskLanes != 0); 907 908 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 909 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 910 return EVT::getVectorVT(Ty->getContext(), 911 EVT::getEVT(VT->getElementType()), 912 NumElts); 913 } 914 915 return EVT::getEVT(Ty); 916 } 917 918 // Peek through TFE struct returns to only use the data size. 919 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 920 auto *ST = dyn_cast<StructType>(Ty); 921 if (!ST) 922 return memVTFromImageData(Ty, DMaskLanes); 923 924 // Some intrinsics return an aggregate type - special case to work out the 925 // correct memVT. 926 // 927 // Only limited forms of aggregate type currently expected. 928 if (ST->getNumContainedTypes() != 2 || 929 !ST->getContainedType(1)->isIntegerTy(32)) 930 return EVT(); 931 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 932 } 933 934 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 935 const CallInst &CI, 936 MachineFunction &MF, 937 unsigned IntrID) const { 938 Info.flags = MachineMemOperand::MONone; 939 if (CI.hasMetadata(LLVMContext::MD_invariant_load)) 940 Info.flags |= MachineMemOperand::MOInvariant; 941 942 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 943 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 944 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 945 (Intrinsic::ID)IntrID); 946 if (Attr.hasFnAttr(Attribute::ReadNone)) 947 return false; 948 949 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 950 951 const GCNTargetMachine &TM = 952 static_cast<const GCNTargetMachine &>(getTargetMachine()); 953 954 if (RsrcIntr->IsImage) { 955 Info.ptrVal = MFI->getImagePSV(TM); 956 Info.align.reset(); 957 } else { 958 Info.ptrVal = MFI->getBufferPSV(TM); 959 } 960 961 Info.flags |= MachineMemOperand::MODereferenceable; 962 if (Attr.hasFnAttr(Attribute::ReadOnly)) { 963 unsigned DMaskLanes = 4; 964 965 if (RsrcIntr->IsImage) { 966 const AMDGPU::ImageDimIntrinsicInfo *Intr 967 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 968 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 969 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 970 971 if (!BaseOpcode->Gather4) { 972 // If this isn't a gather, we may have excess loaded elements in the 973 // IR type. Check the dmask for the real number of elements loaded. 974 unsigned DMask 975 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 976 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 977 } 978 979 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 980 } else 981 Info.memVT = EVT::getEVT(CI.getType()); 982 983 // FIXME: What does alignment mean for an image? 984 Info.opc = ISD::INTRINSIC_W_CHAIN; 985 Info.flags |= MachineMemOperand::MOLoad; 986 } else if (Attr.hasFnAttr(Attribute::WriteOnly)) { 987 Info.opc = ISD::INTRINSIC_VOID; 988 989 Type *DataTy = CI.getArgOperand(0)->getType(); 990 if (RsrcIntr->IsImage) { 991 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 992 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 993 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 994 } else 995 Info.memVT = EVT::getEVT(DataTy); 996 997 Info.flags |= MachineMemOperand::MOStore; 998 } else { 999 // Atomic 1000 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1001 ISD::INTRINSIC_W_CHAIN; 1002 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1003 Info.flags |= MachineMemOperand::MOLoad | 1004 MachineMemOperand::MOStore | 1005 MachineMemOperand::MODereferenceable; 1006 1007 // XXX - Should this be volatile without known ordering? 1008 Info.flags |= MachineMemOperand::MOVolatile; 1009 1010 switch (IntrID) { 1011 default: 1012 break; 1013 case Intrinsic::amdgcn_raw_buffer_load_lds: 1014 case Intrinsic::amdgcn_struct_buffer_load_lds: { 1015 unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue(); 1016 Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8); 1017 return true; 1018 } 1019 } 1020 } 1021 return true; 1022 } 1023 1024 switch (IntrID) { 1025 case Intrinsic::amdgcn_atomic_inc: 1026 case Intrinsic::amdgcn_atomic_dec: 1027 case Intrinsic::amdgcn_ds_ordered_add: 1028 case Intrinsic::amdgcn_ds_ordered_swap: 1029 case Intrinsic::amdgcn_ds_fadd: 1030 case Intrinsic::amdgcn_ds_fmin: 1031 case Intrinsic::amdgcn_ds_fmax: { 1032 Info.opc = ISD::INTRINSIC_W_CHAIN; 1033 Info.memVT = MVT::getVT(CI.getType()); 1034 Info.ptrVal = CI.getOperand(0); 1035 Info.align.reset(); 1036 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1037 1038 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1039 if (!Vol->isZero()) 1040 Info.flags |= MachineMemOperand::MOVolatile; 1041 1042 return true; 1043 } 1044 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1045 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1046 1047 const GCNTargetMachine &TM = 1048 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1049 1050 Info.opc = ISD::INTRINSIC_W_CHAIN; 1051 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1052 Info.ptrVal = MFI->getBufferPSV(TM); 1053 Info.align.reset(); 1054 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1055 1056 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1057 if (!Vol || !Vol->isZero()) 1058 Info.flags |= MachineMemOperand::MOVolatile; 1059 1060 return true; 1061 } 1062 case Intrinsic::amdgcn_ds_append: 1063 case Intrinsic::amdgcn_ds_consume: { 1064 Info.opc = ISD::INTRINSIC_W_CHAIN; 1065 Info.memVT = MVT::getVT(CI.getType()); 1066 Info.ptrVal = CI.getOperand(0); 1067 Info.align.reset(); 1068 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1069 1070 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1071 if (!Vol->isZero()) 1072 Info.flags |= MachineMemOperand::MOVolatile; 1073 1074 return true; 1075 } 1076 case Intrinsic::amdgcn_global_atomic_csub: { 1077 Info.opc = ISD::INTRINSIC_W_CHAIN; 1078 Info.memVT = MVT::getVT(CI.getType()); 1079 Info.ptrVal = CI.getOperand(0); 1080 Info.align.reset(); 1081 Info.flags |= MachineMemOperand::MOLoad | 1082 MachineMemOperand::MOStore | 1083 MachineMemOperand::MOVolatile; 1084 return true; 1085 } 1086 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1087 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1088 Info.opc = ISD::INTRINSIC_W_CHAIN; 1089 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1090 1091 const GCNTargetMachine &TM = 1092 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1093 1094 Info.ptrVal = MFI->getImagePSV(TM); 1095 Info.align.reset(); 1096 Info.flags |= MachineMemOperand::MOLoad | 1097 MachineMemOperand::MODereferenceable; 1098 return true; 1099 } 1100 case Intrinsic::amdgcn_global_atomic_fadd: 1101 case Intrinsic::amdgcn_global_atomic_fmin: 1102 case Intrinsic::amdgcn_global_atomic_fmax: 1103 case Intrinsic::amdgcn_flat_atomic_fadd: 1104 case Intrinsic::amdgcn_flat_atomic_fmin: 1105 case Intrinsic::amdgcn_flat_atomic_fmax: 1106 case Intrinsic::amdgcn_global_atomic_fadd_v2bf16: 1107 case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: { 1108 Info.opc = ISD::INTRINSIC_W_CHAIN; 1109 Info.memVT = MVT::getVT(CI.getType()); 1110 Info.ptrVal = CI.getOperand(0); 1111 Info.align.reset(); 1112 Info.flags |= MachineMemOperand::MOLoad | 1113 MachineMemOperand::MOStore | 1114 MachineMemOperand::MODereferenceable | 1115 MachineMemOperand::MOVolatile; 1116 return true; 1117 } 1118 case Intrinsic::amdgcn_ds_gws_init: 1119 case Intrinsic::amdgcn_ds_gws_barrier: 1120 case Intrinsic::amdgcn_ds_gws_sema_v: 1121 case Intrinsic::amdgcn_ds_gws_sema_br: 1122 case Intrinsic::amdgcn_ds_gws_sema_p: 1123 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1124 Info.opc = ISD::INTRINSIC_VOID; 1125 1126 const GCNTargetMachine &TM = 1127 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1128 1129 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1130 Info.ptrVal = MFI->getGWSPSV(TM); 1131 1132 // This is an abstract access, but we need to specify a type and size. 1133 Info.memVT = MVT::i32; 1134 Info.size = 4; 1135 Info.align = Align(4); 1136 1137 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1138 Info.flags |= MachineMemOperand::MOLoad; 1139 else 1140 Info.flags |= MachineMemOperand::MOStore; 1141 return true; 1142 } 1143 case Intrinsic::amdgcn_global_load_lds: { 1144 Info.opc = ISD::INTRINSIC_VOID; 1145 unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue(); 1146 Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8); 1147 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1148 MachineMemOperand::MOVolatile; 1149 return true; 1150 } 1151 default: 1152 return false; 1153 } 1154 } 1155 1156 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1157 SmallVectorImpl<Value*> &Ops, 1158 Type *&AccessTy) const { 1159 switch (II->getIntrinsicID()) { 1160 case Intrinsic::amdgcn_atomic_inc: 1161 case Intrinsic::amdgcn_atomic_dec: 1162 case Intrinsic::amdgcn_ds_ordered_add: 1163 case Intrinsic::amdgcn_ds_ordered_swap: 1164 case Intrinsic::amdgcn_ds_append: 1165 case Intrinsic::amdgcn_ds_consume: 1166 case Intrinsic::amdgcn_ds_fadd: 1167 case Intrinsic::amdgcn_ds_fmin: 1168 case Intrinsic::amdgcn_ds_fmax: 1169 case Intrinsic::amdgcn_global_atomic_fadd: 1170 case Intrinsic::amdgcn_flat_atomic_fadd: 1171 case Intrinsic::amdgcn_flat_atomic_fmin: 1172 case Intrinsic::amdgcn_flat_atomic_fmax: 1173 case Intrinsic::amdgcn_global_atomic_fadd_v2bf16: 1174 case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: 1175 case Intrinsic::amdgcn_global_atomic_csub: { 1176 Value *Ptr = II->getArgOperand(0); 1177 AccessTy = II->getType(); 1178 Ops.push_back(Ptr); 1179 return true; 1180 } 1181 default: 1182 return false; 1183 } 1184 } 1185 1186 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1187 if (!Subtarget->hasFlatInstOffsets()) { 1188 // Flat instructions do not have offsets, and only have the register 1189 // address. 1190 return AM.BaseOffs == 0 && AM.Scale == 0; 1191 } 1192 1193 return AM.Scale == 0 && 1194 (AM.BaseOffs == 0 || 1195 Subtarget->getInstrInfo()->isLegalFLATOffset( 1196 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT)); 1197 } 1198 1199 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1200 if (Subtarget->hasFlatGlobalInsts()) 1201 return AM.Scale == 0 && 1202 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1203 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1204 SIInstrFlags::FlatGlobal)); 1205 1206 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1207 // Assume the we will use FLAT for all global memory accesses 1208 // on VI. 1209 // FIXME: This assumption is currently wrong. On VI we still use 1210 // MUBUF instructions for the r + i addressing mode. As currently 1211 // implemented, the MUBUF instructions only work on buffer < 4GB. 1212 // It may be possible to support > 4GB buffers with MUBUF instructions, 1213 // by setting the stride value in the resource descriptor which would 1214 // increase the size limit to (stride * 4GB). However, this is risky, 1215 // because it has never been validated. 1216 return isLegalFlatAddressingMode(AM); 1217 } 1218 1219 return isLegalMUBUFAddressingMode(AM); 1220 } 1221 1222 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1223 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1224 // additionally can do r + r + i with addr64. 32-bit has more addressing 1225 // mode options. Depending on the resource constant, it can also do 1226 // (i64 r0) + (i32 r1) * (i14 i). 1227 // 1228 // Private arrays end up using a scratch buffer most of the time, so also 1229 // assume those use MUBUF instructions. Scratch loads / stores are currently 1230 // implemented as mubuf instructions with offen bit set, so slightly 1231 // different than the normal addr64. 1232 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1233 return false; 1234 1235 // FIXME: Since we can split immediate into soffset and immediate offset, 1236 // would it make sense to allow any immediate? 1237 1238 switch (AM.Scale) { 1239 case 0: // r + i or just i, depending on HasBaseReg. 1240 return true; 1241 case 1: 1242 return true; // We have r + r or r + i. 1243 case 2: 1244 if (AM.HasBaseReg) { 1245 // Reject 2 * r + r. 1246 return false; 1247 } 1248 1249 // Allow 2 * r as r + r 1250 // Or 2 * r + i is allowed as r + r + i. 1251 return true; 1252 default: // Don't allow n * r 1253 return false; 1254 } 1255 } 1256 1257 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1258 const AddrMode &AM, Type *Ty, 1259 unsigned AS, Instruction *I) const { 1260 // No global is ever allowed as a base. 1261 if (AM.BaseGV) 1262 return false; 1263 1264 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1265 return isLegalGlobalAddressingMode(AM); 1266 1267 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1268 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1269 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1270 // If the offset isn't a multiple of 4, it probably isn't going to be 1271 // correctly aligned. 1272 // FIXME: Can we get the real alignment here? 1273 if (AM.BaseOffs % 4 != 0) 1274 return isLegalMUBUFAddressingMode(AM); 1275 1276 // There are no SMRD extloads, so if we have to do a small type access we 1277 // will use a MUBUF load. 1278 // FIXME?: We also need to do this if unaligned, but we don't know the 1279 // alignment here. 1280 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1281 return isLegalGlobalAddressingMode(AM); 1282 1283 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1284 // SMRD instructions have an 8-bit, dword offset on SI. 1285 if (!isUInt<8>(AM.BaseOffs / 4)) 1286 return false; 1287 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1288 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1289 // in 8-bits, it can use a smaller encoding. 1290 if (!isUInt<32>(AM.BaseOffs / 4)) 1291 return false; 1292 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1293 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1294 if (!isUInt<20>(AM.BaseOffs)) 1295 return false; 1296 } else 1297 llvm_unreachable("unhandled generation"); 1298 1299 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1300 return true; 1301 1302 if (AM.Scale == 1 && AM.HasBaseReg) 1303 return true; 1304 1305 return false; 1306 1307 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1308 return isLegalMUBUFAddressingMode(AM); 1309 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1310 AS == AMDGPUAS::REGION_ADDRESS) { 1311 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1312 // field. 1313 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1314 // an 8-bit dword offset but we don't know the alignment here. 1315 if (!isUInt<16>(AM.BaseOffs)) 1316 return false; 1317 1318 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1319 return true; 1320 1321 if (AM.Scale == 1 && AM.HasBaseReg) 1322 return true; 1323 1324 return false; 1325 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1326 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1327 // For an unknown address space, this usually means that this is for some 1328 // reason being used for pure arithmetic, and not based on some addressing 1329 // computation. We don't have instructions that compute pointers with any 1330 // addressing modes, so treat them as having no offset like flat 1331 // instructions. 1332 return isLegalFlatAddressingMode(AM); 1333 } 1334 1335 // Assume a user alias of global for unknown address spaces. 1336 return isLegalGlobalAddressingMode(AM); 1337 } 1338 1339 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1340 const MachineFunction &MF) const { 1341 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1342 return (MemVT.getSizeInBits() <= 4 * 32); 1343 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1344 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1345 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1346 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1347 return (MemVT.getSizeInBits() <= 2 * 32); 1348 } 1349 return true; 1350 } 1351 1352 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1353 unsigned Size, unsigned AddrSpace, Align Alignment, 1354 MachineMemOperand::Flags Flags, bool *IsFast) const { 1355 if (IsFast) 1356 *IsFast = false; 1357 1358 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1359 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1360 // Check if alignment requirements for ds_read/write instructions are 1361 // disabled. 1362 if (!Subtarget->hasUnalignedDSAccessEnabled() && Alignment < Align(4)) 1363 return false; 1364 1365 Align RequiredAlignment(PowerOf2Ceil(Size/8)); // Natural alignment. 1366 if (Subtarget->hasLDSMisalignedBug() && Size > 32 && 1367 Alignment < RequiredAlignment) 1368 return false; 1369 1370 // Either, the alignment requirements are "enabled", or there is an 1371 // unaligned LDS access related hardware bug though alignment requirements 1372 // are "disabled". In either case, we need to check for proper alignment 1373 // requirements. 1374 // 1375 switch (Size) { 1376 case 64: 1377 // SI has a hardware bug in the LDS / GDS bounds checking: if the base 1378 // address is negative, then the instruction is incorrectly treated as 1379 // out-of-bounds even if base + offsets is in bounds. Split vectorized 1380 // loads here to avoid emitting ds_read2_b32. We may re-combine the 1381 // load later in the SILoadStoreOptimizer. 1382 if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8)) 1383 return false; 1384 1385 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we 1386 // can do a 4 byte aligned, 8 byte access in a single operation using 1387 // ds_read2/write2_b32 with adjacent offsets. 1388 RequiredAlignment = Align(4); 1389 1390 if (Subtarget->hasUnalignedDSAccessEnabled()) { 1391 // We will either select ds_read_b64/ds_write_b64 or ds_read2_b32/ 1392 // ds_write2_b32 depending on the alignment. In either case with either 1393 // alignment there is no faster way of doing this. 1394 if (IsFast) 1395 *IsFast = true; 1396 return true; 1397 } 1398 1399 break; 1400 case 96: 1401 if (!Subtarget->hasDS96AndDS128()) 1402 return false; 1403 1404 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on 1405 // gfx8 and older. 1406 1407 if (Subtarget->hasUnalignedDSAccessEnabled()) { 1408 // Naturally aligned access is fastest. However, also report it is Fast 1409 // if memory is aligned less than DWORD. A narrow load or store will be 1410 // be equally slow as a single ds_read_b96/ds_write_b96, but there will 1411 // be more of them, so overall we will pay less penalty issuing a single 1412 // instruction. 1413 if (IsFast) 1414 *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4); 1415 return true; 1416 } 1417 1418 break; 1419 case 128: 1420 if (!Subtarget->hasDS96AndDS128() || !Subtarget->useDS128()) 1421 return false; 1422 1423 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on 1424 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a 1425 // single operation using ds_read2/write2_b64. 1426 RequiredAlignment = Align(8); 1427 1428 if (Subtarget->hasUnalignedDSAccessEnabled()) { 1429 // Naturally aligned access is fastest. However, also report it is Fast 1430 // if memory is aligned less than DWORD. A narrow load or store will be 1431 // be equally slow as a single ds_read_b128/ds_write_b128, but there 1432 // will be more of them, so overall we will pay less penalty issuing a 1433 // single instruction. 1434 if (IsFast) 1435 *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4); 1436 return true; 1437 } 1438 1439 break; 1440 default: 1441 if (Size > 32) 1442 return false; 1443 1444 break; 1445 } 1446 1447 if (IsFast) 1448 *IsFast = Alignment >= RequiredAlignment; 1449 1450 return Alignment >= RequiredAlignment || 1451 Subtarget->hasUnalignedDSAccessEnabled(); 1452 } 1453 1454 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1455 bool AlignedBy4 = Alignment >= Align(4); 1456 if (IsFast) 1457 *IsFast = AlignedBy4; 1458 1459 return AlignedBy4 || 1460 Subtarget->enableFlatScratch() || 1461 Subtarget->hasUnalignedScratchAccess(); 1462 } 1463 1464 // FIXME: We have to be conservative here and assume that flat operations 1465 // will access scratch. If we had access to the IR function, then we 1466 // could determine if any private memory was used in the function. 1467 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1468 !Subtarget->hasUnalignedScratchAccess()) { 1469 bool AlignedBy4 = Alignment >= Align(4); 1470 if (IsFast) 1471 *IsFast = AlignedBy4; 1472 1473 return AlignedBy4; 1474 } 1475 1476 if (Subtarget->hasUnalignedBufferAccessEnabled()) { 1477 // If we have a uniform constant load, it still requires using a slow 1478 // buffer instruction if unaligned. 1479 if (IsFast) { 1480 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1481 // 2-byte alignment is worse than 1 unless doing a 2-byte access. 1482 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1483 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1484 Alignment >= Align(4) : Alignment != Align(2); 1485 } 1486 1487 return true; 1488 } 1489 1490 // Smaller than dword value must be aligned. 1491 if (Size < 32) 1492 return false; 1493 1494 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1495 // byte-address are ignored, thus forcing Dword alignment. 1496 // This applies to private, global, and constant memory. 1497 if (IsFast) 1498 *IsFast = true; 1499 1500 return Size >= 32 && Alignment >= Align(4); 1501 } 1502 1503 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1504 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1505 bool *IsFast) const { 1506 bool Allow = allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1507 Alignment, Flags, IsFast); 1508 1509 if (Allow && IsFast && Subtarget->hasUnalignedDSAccessEnabled() && 1510 (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1511 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1512 // Lie it is fast if +unaligned-access-mode is passed so that DS accesses 1513 // get vectorized. We could use ds_read2_b*/ds_write2_b* instructions on a 1514 // misaligned data which is faster than a pair of ds_read_b*/ds_write_b* 1515 // which would be equally misaligned. 1516 // This is only used by the common passes, selection always calls the 1517 // allowsMisalignedMemoryAccessesImpl version. 1518 *IsFast = true; 1519 } 1520 1521 return Allow; 1522 } 1523 1524 EVT SITargetLowering::getOptimalMemOpType( 1525 const MemOp &Op, const AttributeList &FuncAttributes) const { 1526 // FIXME: Should account for address space here. 1527 1528 // The default fallback uses the private pointer size as a guess for a type to 1529 // use. Make sure we switch these to 64-bit accesses. 1530 1531 if (Op.size() >= 16 && 1532 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1533 return MVT::v4i32; 1534 1535 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1536 return MVT::v2i32; 1537 1538 // Use the default. 1539 return MVT::Other; 1540 } 1541 1542 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1543 const MemSDNode *MemNode = cast<MemSDNode>(N); 1544 return MemNode->getMemOperand()->getFlags() & MONoClobber; 1545 } 1546 1547 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1548 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1549 AS == AMDGPUAS::PRIVATE_ADDRESS; 1550 } 1551 1552 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1553 unsigned DestAS) const { 1554 // Flat -> private/local is a simple truncate. 1555 // Flat -> global is no-op 1556 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1557 return true; 1558 1559 const GCNTargetMachine &TM = 1560 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1561 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1562 } 1563 1564 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1565 const MemSDNode *MemNode = cast<MemSDNode>(N); 1566 1567 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1568 } 1569 1570 TargetLoweringBase::LegalizeTypeAction 1571 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1572 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 && 1573 VT.getScalarType().bitsLE(MVT::i16)) 1574 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1575 return TargetLoweringBase::getPreferredVectorAction(VT); 1576 } 1577 1578 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1579 Type *Ty) const { 1580 // FIXME: Could be smarter if called for vector constants. 1581 return true; 1582 } 1583 1584 bool SITargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 1585 unsigned Index) const { 1586 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 1587 return false; 1588 1589 // TODO: Add more cases that are cheap. 1590 return Index == 0; 1591 } 1592 1593 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1594 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1595 switch (Op) { 1596 case ISD::LOAD: 1597 case ISD::STORE: 1598 1599 // These operations are done with 32-bit instructions anyway. 1600 case ISD::AND: 1601 case ISD::OR: 1602 case ISD::XOR: 1603 case ISD::SELECT: 1604 // TODO: Extensions? 1605 return true; 1606 default: 1607 return false; 1608 } 1609 } 1610 1611 // SimplifySetCC uses this function to determine whether or not it should 1612 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1613 if (VT == MVT::i1 && Op == ISD::SETCC) 1614 return false; 1615 1616 return TargetLowering::isTypeDesirableForOp(Op, VT); 1617 } 1618 1619 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1620 const SDLoc &SL, 1621 SDValue Chain, 1622 uint64_t Offset) const { 1623 const DataLayout &DL = DAG.getDataLayout(); 1624 MachineFunction &MF = DAG.getMachineFunction(); 1625 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1626 1627 const ArgDescriptor *InputPtrReg; 1628 const TargetRegisterClass *RC; 1629 LLT ArgTy; 1630 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1631 1632 std::tie(InputPtrReg, RC, ArgTy) = 1633 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1634 1635 // We may not have the kernarg segment argument if we have no kernel 1636 // arguments. 1637 if (!InputPtrReg) 1638 return DAG.getConstant(0, SL, PtrVT); 1639 1640 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1641 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1642 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1643 1644 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1645 } 1646 1647 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1648 const SDLoc &SL) const { 1649 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1650 FIRST_IMPLICIT); 1651 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1652 } 1653 1654 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1655 const SDLoc &SL, SDValue Val, 1656 bool Signed, 1657 const ISD::InputArg *Arg) const { 1658 // First, if it is a widened vector, narrow it. 1659 if (VT.isVector() && 1660 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1661 EVT NarrowedVT = 1662 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1663 VT.getVectorNumElements()); 1664 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1665 DAG.getConstant(0, SL, MVT::i32)); 1666 } 1667 1668 // Then convert the vector elements or scalar value. 1669 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1670 VT.bitsLT(MemVT)) { 1671 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1672 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1673 } 1674 1675 if (MemVT.isFloatingPoint()) 1676 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1677 else if (Signed) 1678 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1679 else 1680 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1681 1682 return Val; 1683 } 1684 1685 SDValue SITargetLowering::lowerKernargMemParameter( 1686 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1687 uint64_t Offset, Align Alignment, bool Signed, 1688 const ISD::InputArg *Arg) const { 1689 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1690 1691 // Try to avoid using an extload by loading earlier than the argument address, 1692 // and extracting the relevant bits. The load should hopefully be merged with 1693 // the previous argument. 1694 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1695 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1696 int64_t AlignDownOffset = alignDown(Offset, 4); 1697 int64_t OffsetDiff = Offset - AlignDownOffset; 1698 1699 EVT IntVT = MemVT.changeTypeToInteger(); 1700 1701 // TODO: If we passed in the base kernel offset we could have a better 1702 // alignment than 4, but we don't really need it. 1703 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1704 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1705 MachineMemOperand::MODereferenceable | 1706 MachineMemOperand::MOInvariant); 1707 1708 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1709 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1710 1711 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1712 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1713 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1714 1715 1716 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1717 } 1718 1719 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1720 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1721 MachineMemOperand::MODereferenceable | 1722 MachineMemOperand::MOInvariant); 1723 1724 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1725 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1726 } 1727 1728 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1729 const SDLoc &SL, SDValue Chain, 1730 const ISD::InputArg &Arg) const { 1731 MachineFunction &MF = DAG.getMachineFunction(); 1732 MachineFrameInfo &MFI = MF.getFrameInfo(); 1733 1734 if (Arg.Flags.isByVal()) { 1735 unsigned Size = Arg.Flags.getByValSize(); 1736 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1737 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1738 } 1739 1740 unsigned ArgOffset = VA.getLocMemOffset(); 1741 unsigned ArgSize = VA.getValVT().getStoreSize(); 1742 1743 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1744 1745 // Create load nodes to retrieve arguments from the stack. 1746 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1747 SDValue ArgValue; 1748 1749 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1750 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1751 MVT MemVT = VA.getValVT(); 1752 1753 switch (VA.getLocInfo()) { 1754 default: 1755 break; 1756 case CCValAssign::BCvt: 1757 MemVT = VA.getLocVT(); 1758 break; 1759 case CCValAssign::SExt: 1760 ExtType = ISD::SEXTLOAD; 1761 break; 1762 case CCValAssign::ZExt: 1763 ExtType = ISD::ZEXTLOAD; 1764 break; 1765 case CCValAssign::AExt: 1766 ExtType = ISD::EXTLOAD; 1767 break; 1768 } 1769 1770 ArgValue = DAG.getExtLoad( 1771 ExtType, SL, VA.getLocVT(), Chain, FIN, 1772 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1773 MemVT); 1774 return ArgValue; 1775 } 1776 1777 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1778 const SIMachineFunctionInfo &MFI, 1779 EVT VT, 1780 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1781 const ArgDescriptor *Reg; 1782 const TargetRegisterClass *RC; 1783 LLT Ty; 1784 1785 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1786 if (!Reg) { 1787 if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) { 1788 // It's possible for a kernarg intrinsic call to appear in a kernel with 1789 // no allocated segment, in which case we do not add the user sgpr 1790 // argument, so just return null. 1791 return DAG.getConstant(0, SDLoc(), VT); 1792 } 1793 1794 // It's undefined behavior if a function marked with the amdgpu-no-* 1795 // attributes uses the corresponding intrinsic. 1796 return DAG.getUNDEF(VT); 1797 } 1798 1799 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1800 } 1801 1802 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1803 CallingConv::ID CallConv, 1804 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1805 FunctionType *FType, 1806 SIMachineFunctionInfo *Info) { 1807 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1808 const ISD::InputArg *Arg = &Ins[I]; 1809 1810 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1811 "vector type argument should have been split"); 1812 1813 // First check if it's a PS input addr. 1814 if (CallConv == CallingConv::AMDGPU_PS && 1815 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1816 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1817 1818 // Inconveniently only the first part of the split is marked as isSplit, 1819 // so skip to the end. We only want to increment PSInputNum once for the 1820 // entire split argument. 1821 if (Arg->Flags.isSplit()) { 1822 while (!Arg->Flags.isSplitEnd()) { 1823 assert((!Arg->VT.isVector() || 1824 Arg->VT.getScalarSizeInBits() == 16) && 1825 "unexpected vector split in ps argument type"); 1826 if (!SkipArg) 1827 Splits.push_back(*Arg); 1828 Arg = &Ins[++I]; 1829 } 1830 } 1831 1832 if (SkipArg) { 1833 // We can safely skip PS inputs. 1834 Skipped.set(Arg->getOrigArgIndex()); 1835 ++PSInputNum; 1836 continue; 1837 } 1838 1839 Info->markPSInputAllocated(PSInputNum); 1840 if (Arg->Used) 1841 Info->markPSInputEnabled(PSInputNum); 1842 1843 ++PSInputNum; 1844 } 1845 1846 Splits.push_back(*Arg); 1847 } 1848 } 1849 1850 // Allocate special inputs passed in VGPRs. 1851 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1852 MachineFunction &MF, 1853 const SIRegisterInfo &TRI, 1854 SIMachineFunctionInfo &Info) const { 1855 const LLT S32 = LLT::scalar(32); 1856 MachineRegisterInfo &MRI = MF.getRegInfo(); 1857 1858 if (Info.hasWorkItemIDX()) { 1859 Register Reg = AMDGPU::VGPR0; 1860 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1861 1862 CCInfo.AllocateReg(Reg); 1863 unsigned Mask = (Subtarget->hasPackedTID() && 1864 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 1865 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1866 } 1867 1868 if (Info.hasWorkItemIDY()) { 1869 assert(Info.hasWorkItemIDX()); 1870 if (Subtarget->hasPackedTID()) { 1871 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1872 0x3ff << 10)); 1873 } else { 1874 unsigned Reg = AMDGPU::VGPR1; 1875 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1876 1877 CCInfo.AllocateReg(Reg); 1878 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1879 } 1880 } 1881 1882 if (Info.hasWorkItemIDZ()) { 1883 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 1884 if (Subtarget->hasPackedTID()) { 1885 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1886 0x3ff << 20)); 1887 } else { 1888 unsigned Reg = AMDGPU::VGPR2; 1889 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1890 1891 CCInfo.AllocateReg(Reg); 1892 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1893 } 1894 } 1895 } 1896 1897 // Try to allocate a VGPR at the end of the argument list, or if no argument 1898 // VGPRs are left allocating a stack slot. 1899 // If \p Mask is is given it indicates bitfield position in the register. 1900 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1901 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1902 ArgDescriptor Arg = ArgDescriptor()) { 1903 if (Arg.isSet()) 1904 return ArgDescriptor::createArg(Arg, Mask); 1905 1906 ArrayRef<MCPhysReg> ArgVGPRs 1907 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1908 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1909 if (RegIdx == ArgVGPRs.size()) { 1910 // Spill to stack required. 1911 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1912 1913 return ArgDescriptor::createStack(Offset, Mask); 1914 } 1915 1916 unsigned Reg = ArgVGPRs[RegIdx]; 1917 Reg = CCInfo.AllocateReg(Reg); 1918 assert(Reg != AMDGPU::NoRegister); 1919 1920 MachineFunction &MF = CCInfo.getMachineFunction(); 1921 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1922 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1923 return ArgDescriptor::createRegister(Reg, Mask); 1924 } 1925 1926 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1927 const TargetRegisterClass *RC, 1928 unsigned NumArgRegs) { 1929 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1930 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1931 if (RegIdx == ArgSGPRs.size()) 1932 report_fatal_error("ran out of SGPRs for arguments"); 1933 1934 unsigned Reg = ArgSGPRs[RegIdx]; 1935 Reg = CCInfo.AllocateReg(Reg); 1936 assert(Reg != AMDGPU::NoRegister); 1937 1938 MachineFunction &MF = CCInfo.getMachineFunction(); 1939 MF.addLiveIn(Reg, RC); 1940 return ArgDescriptor::createRegister(Reg); 1941 } 1942 1943 // If this has a fixed position, we still should allocate the register in the 1944 // CCInfo state. Technically we could get away with this for values passed 1945 // outside of the normal argument range. 1946 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 1947 const TargetRegisterClass *RC, 1948 MCRegister Reg) { 1949 Reg = CCInfo.AllocateReg(Reg); 1950 assert(Reg != AMDGPU::NoRegister); 1951 MachineFunction &MF = CCInfo.getMachineFunction(); 1952 MF.addLiveIn(Reg, RC); 1953 } 1954 1955 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 1956 if (Arg) { 1957 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 1958 Arg.getRegister()); 1959 } else 1960 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1961 } 1962 1963 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 1964 if (Arg) { 1965 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 1966 Arg.getRegister()); 1967 } else 1968 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1969 } 1970 1971 /// Allocate implicit function VGPR arguments at the end of allocated user 1972 /// arguments. 1973 void SITargetLowering::allocateSpecialInputVGPRs( 1974 CCState &CCInfo, MachineFunction &MF, 1975 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1976 const unsigned Mask = 0x3ff; 1977 ArgDescriptor Arg; 1978 1979 if (Info.hasWorkItemIDX()) { 1980 Arg = allocateVGPR32Input(CCInfo, Mask); 1981 Info.setWorkItemIDX(Arg); 1982 } 1983 1984 if (Info.hasWorkItemIDY()) { 1985 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1986 Info.setWorkItemIDY(Arg); 1987 } 1988 1989 if (Info.hasWorkItemIDZ()) 1990 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1991 } 1992 1993 /// Allocate implicit function VGPR arguments in fixed registers. 1994 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1995 CCState &CCInfo, MachineFunction &MF, 1996 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1997 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1998 if (!Reg) 1999 report_fatal_error("failed to allocated VGPR for implicit arguments"); 2000 2001 const unsigned Mask = 0x3ff; 2002 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 2003 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 2004 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 2005 } 2006 2007 void SITargetLowering::allocateSpecialInputSGPRs( 2008 CCState &CCInfo, 2009 MachineFunction &MF, 2010 const SIRegisterInfo &TRI, 2011 SIMachineFunctionInfo &Info) const { 2012 auto &ArgInfo = Info.getArgInfo(); 2013 2014 // TODO: Unify handling with private memory pointers. 2015 if (Info.hasDispatchPtr()) 2016 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 2017 2018 if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) 2019 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 2020 2021 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 2022 // constant offset from the kernarg segment. 2023 if (Info.hasImplicitArgPtr()) 2024 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 2025 2026 if (Info.hasDispatchID()) 2027 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 2028 2029 // flat_scratch_init is not applicable for non-kernel functions. 2030 2031 if (Info.hasWorkGroupIDX()) 2032 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2033 2034 if (Info.hasWorkGroupIDY()) 2035 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2036 2037 if (Info.hasWorkGroupIDZ()) 2038 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2039 } 2040 2041 // Allocate special inputs passed in user SGPRs. 2042 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2043 MachineFunction &MF, 2044 const SIRegisterInfo &TRI, 2045 SIMachineFunctionInfo &Info) const { 2046 if (Info.hasImplicitBufferPtr()) { 2047 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2048 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2049 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2050 } 2051 2052 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2053 if (Info.hasPrivateSegmentBuffer()) { 2054 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2055 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2056 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2057 } 2058 2059 if (Info.hasDispatchPtr()) { 2060 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2061 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2062 CCInfo.AllocateReg(DispatchPtrReg); 2063 } 2064 2065 if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) { 2066 Register QueuePtrReg = Info.addQueuePtr(TRI); 2067 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2068 CCInfo.AllocateReg(QueuePtrReg); 2069 } 2070 2071 if (Info.hasKernargSegmentPtr()) { 2072 MachineRegisterInfo &MRI = MF.getRegInfo(); 2073 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2074 CCInfo.AllocateReg(InputPtrReg); 2075 2076 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2077 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2078 } 2079 2080 if (Info.hasDispatchID()) { 2081 Register DispatchIDReg = Info.addDispatchID(TRI); 2082 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2083 CCInfo.AllocateReg(DispatchIDReg); 2084 } 2085 2086 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2087 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2088 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2089 CCInfo.AllocateReg(FlatScratchInitReg); 2090 } 2091 2092 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2093 // these from the dispatch pointer. 2094 } 2095 2096 // Allocate special input registers that are initialized per-wave. 2097 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2098 MachineFunction &MF, 2099 SIMachineFunctionInfo &Info, 2100 CallingConv::ID CallConv, 2101 bool IsShader) const { 2102 if (Subtarget->hasUserSGPRInit16Bug()) { 2103 // Pad up the used user SGPRs with dead inputs. 2104 unsigned CurrentUserSGPRs = Info.getNumUserSGPRs(); 2105 2106 // Note we do not count the PrivateSegmentWaveByteOffset. We do not want to 2107 // rely on it to reach 16 since if we end up having no stack usage, it will 2108 // not really be added. 2109 unsigned NumRequiredSystemSGPRs = Info.hasWorkGroupIDX() + 2110 Info.hasWorkGroupIDY() + 2111 Info.hasWorkGroupIDZ() + 2112 Info.hasWorkGroupInfo(); 2113 for (unsigned i = NumRequiredSystemSGPRs + CurrentUserSGPRs; i < 16; ++i) { 2114 Register Reg = Info.addReservedUserSGPR(); 2115 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2116 CCInfo.AllocateReg(Reg); 2117 } 2118 } 2119 2120 if (Info.hasWorkGroupIDX()) { 2121 Register Reg = Info.addWorkGroupIDX(); 2122 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2123 CCInfo.AllocateReg(Reg); 2124 } 2125 2126 if (Info.hasWorkGroupIDY()) { 2127 Register Reg = Info.addWorkGroupIDY(); 2128 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2129 CCInfo.AllocateReg(Reg); 2130 } 2131 2132 if (Info.hasWorkGroupIDZ()) { 2133 Register Reg = Info.addWorkGroupIDZ(); 2134 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2135 CCInfo.AllocateReg(Reg); 2136 } 2137 2138 if (Info.hasWorkGroupInfo()) { 2139 Register Reg = Info.addWorkGroupInfo(); 2140 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2141 CCInfo.AllocateReg(Reg); 2142 } 2143 2144 if (Info.hasPrivateSegmentWaveByteOffset()) { 2145 // Scratch wave offset passed in system SGPR. 2146 unsigned PrivateSegmentWaveByteOffsetReg; 2147 2148 if (IsShader) { 2149 PrivateSegmentWaveByteOffsetReg = 2150 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2151 2152 // This is true if the scratch wave byte offset doesn't have a fixed 2153 // location. 2154 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2155 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2156 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2157 } 2158 } else 2159 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2160 2161 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2162 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2163 } 2164 2165 assert(!Subtarget->hasUserSGPRInit16Bug() || Info.getNumPreloadedSGPRs() >= 16); 2166 } 2167 2168 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2169 MachineFunction &MF, 2170 const SIRegisterInfo &TRI, 2171 SIMachineFunctionInfo &Info) { 2172 // Now that we've figured out where the scratch register inputs are, see if 2173 // should reserve the arguments and use them directly. 2174 MachineFrameInfo &MFI = MF.getFrameInfo(); 2175 bool HasStackObjects = MFI.hasStackObjects(); 2176 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2177 2178 // Record that we know we have non-spill stack objects so we don't need to 2179 // check all stack objects later. 2180 if (HasStackObjects) 2181 Info.setHasNonSpillStackObjects(true); 2182 2183 // Everything live out of a block is spilled with fast regalloc, so it's 2184 // almost certain that spilling will be required. 2185 if (TM.getOptLevel() == CodeGenOpt::None) 2186 HasStackObjects = true; 2187 2188 // For now assume stack access is needed in any callee functions, so we need 2189 // the scratch registers to pass in. 2190 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2191 2192 if (!ST.enableFlatScratch()) { 2193 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2194 // If we have stack objects, we unquestionably need the private buffer 2195 // resource. For the Code Object V2 ABI, this will be the first 4 user 2196 // SGPR inputs. We can reserve those and use them directly. 2197 2198 Register PrivateSegmentBufferReg = 2199 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2200 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2201 } else { 2202 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2203 // We tentatively reserve the last registers (skipping the last registers 2204 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2205 // we'll replace these with the ones immediately after those which were 2206 // really allocated. In the prologue copies will be inserted from the 2207 // argument to these reserved registers. 2208 2209 // Without HSA, relocations are used for the scratch pointer and the 2210 // buffer resource setup is always inserted in the prologue. Scratch wave 2211 // offset is still in an input SGPR. 2212 Info.setScratchRSrcReg(ReservedBufferReg); 2213 } 2214 } 2215 2216 MachineRegisterInfo &MRI = MF.getRegInfo(); 2217 2218 // For entry functions we have to set up the stack pointer if we use it, 2219 // whereas non-entry functions get this "for free". This means there is no 2220 // intrinsic advantage to using S32 over S34 in cases where we do not have 2221 // calls but do need a frame pointer (i.e. if we are requested to have one 2222 // because frame pointer elimination is disabled). To keep things simple we 2223 // only ever use S32 as the call ABI stack pointer, and so using it does not 2224 // imply we need a separate frame pointer. 2225 // 2226 // Try to use s32 as the SP, but move it if it would interfere with input 2227 // arguments. This won't work with calls though. 2228 // 2229 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2230 // registers. 2231 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2232 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2233 } else { 2234 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2235 2236 if (MFI.hasCalls()) 2237 report_fatal_error("call in graphics shader with too many input SGPRs"); 2238 2239 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2240 if (!MRI.isLiveIn(Reg)) { 2241 Info.setStackPtrOffsetReg(Reg); 2242 break; 2243 } 2244 } 2245 2246 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2247 report_fatal_error("failed to find register for SP"); 2248 } 2249 2250 // hasFP should be accurate for entry functions even before the frame is 2251 // finalized, because it does not rely on the known stack size, only 2252 // properties like whether variable sized objects are present. 2253 if (ST.getFrameLowering()->hasFP(MF)) { 2254 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2255 } 2256 } 2257 2258 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2259 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2260 return !Info->isEntryFunction(); 2261 } 2262 2263 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2264 2265 } 2266 2267 void SITargetLowering::insertCopiesSplitCSR( 2268 MachineBasicBlock *Entry, 2269 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2270 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2271 2272 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2273 if (!IStart) 2274 return; 2275 2276 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2277 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2278 MachineBasicBlock::iterator MBBI = Entry->begin(); 2279 for (const MCPhysReg *I = IStart; *I; ++I) { 2280 const TargetRegisterClass *RC = nullptr; 2281 if (AMDGPU::SReg_64RegClass.contains(*I)) 2282 RC = &AMDGPU::SGPR_64RegClass; 2283 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2284 RC = &AMDGPU::SGPR_32RegClass; 2285 else 2286 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2287 2288 Register NewVR = MRI->createVirtualRegister(RC); 2289 // Create copy from CSR to a virtual register. 2290 Entry->addLiveIn(*I); 2291 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2292 .addReg(*I); 2293 2294 // Insert the copy-back instructions right before the terminator. 2295 for (auto *Exit : Exits) 2296 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2297 TII->get(TargetOpcode::COPY), *I) 2298 .addReg(NewVR); 2299 } 2300 } 2301 2302 SDValue SITargetLowering::LowerFormalArguments( 2303 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2304 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2305 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2306 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2307 2308 MachineFunction &MF = DAG.getMachineFunction(); 2309 const Function &Fn = MF.getFunction(); 2310 FunctionType *FType = MF.getFunction().getFunctionType(); 2311 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2312 2313 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2314 DiagnosticInfoUnsupported NoGraphicsHSA( 2315 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2316 DAG.getContext()->diagnose(NoGraphicsHSA); 2317 return DAG.getEntryNode(); 2318 } 2319 2320 Info->allocateModuleLDSGlobal(Fn); 2321 2322 SmallVector<ISD::InputArg, 16> Splits; 2323 SmallVector<CCValAssign, 16> ArgLocs; 2324 BitVector Skipped(Ins.size()); 2325 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2326 *DAG.getContext()); 2327 2328 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2329 bool IsKernel = AMDGPU::isKernel(CallConv); 2330 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2331 2332 if (IsGraphics) { 2333 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2334 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2335 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2336 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2337 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2338 !Info->hasWorkItemIDZ()); 2339 } 2340 2341 if (CallConv == CallingConv::AMDGPU_PS) { 2342 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2343 2344 // At least one interpolation mode must be enabled or else the GPU will 2345 // hang. 2346 // 2347 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2348 // set PSInputAddr, the user wants to enable some bits after the compilation 2349 // based on run-time states. Since we can't know what the final PSInputEna 2350 // will look like, so we shouldn't do anything here and the user should take 2351 // responsibility for the correct programming. 2352 // 2353 // Otherwise, the following restrictions apply: 2354 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2355 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2356 // enabled too. 2357 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2358 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2359 CCInfo.AllocateReg(AMDGPU::VGPR0); 2360 CCInfo.AllocateReg(AMDGPU::VGPR1); 2361 Info->markPSInputAllocated(0); 2362 Info->markPSInputEnabled(0); 2363 } 2364 if (Subtarget->isAmdPalOS()) { 2365 // For isAmdPalOS, the user does not enable some bits after compilation 2366 // based on run-time states; the register values being generated here are 2367 // the final ones set in hardware. Therefore we need to apply the 2368 // workaround to PSInputAddr and PSInputEnable together. (The case where 2369 // a bit is set in PSInputAddr but not PSInputEnable is where the 2370 // frontend set up an input arg for a particular interpolation mode, but 2371 // nothing uses that input arg. Really we should have an earlier pass 2372 // that removes such an arg.) 2373 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2374 if ((PsInputBits & 0x7F) == 0 || 2375 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2376 Info->markPSInputEnabled( 2377 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2378 } 2379 } else if (IsKernel) { 2380 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2381 } else { 2382 Splits.append(Ins.begin(), Ins.end()); 2383 } 2384 2385 if (IsEntryFunc) { 2386 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2387 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2388 } else if (!IsGraphics) { 2389 // For the fixed ABI, pass workitem IDs in the last argument register. 2390 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2391 } 2392 2393 if (IsKernel) { 2394 analyzeFormalArgumentsCompute(CCInfo, Ins); 2395 } else { 2396 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2397 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2398 } 2399 2400 SmallVector<SDValue, 16> Chains; 2401 2402 // FIXME: This is the minimum kernel argument alignment. We should improve 2403 // this to the maximum alignment of the arguments. 2404 // 2405 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2406 // kern arg offset. 2407 const Align KernelArgBaseAlign = Align(16); 2408 2409 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2410 const ISD::InputArg &Arg = Ins[i]; 2411 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2412 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2413 continue; 2414 } 2415 2416 CCValAssign &VA = ArgLocs[ArgIdx++]; 2417 MVT VT = VA.getLocVT(); 2418 2419 if (IsEntryFunc && VA.isMemLoc()) { 2420 VT = Ins[i].VT; 2421 EVT MemVT = VA.getLocVT(); 2422 2423 const uint64_t Offset = VA.getLocMemOffset(); 2424 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2425 2426 if (Arg.Flags.isByRef()) { 2427 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2428 2429 const GCNTargetMachine &TM = 2430 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2431 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2432 Arg.Flags.getPointerAddrSpace())) { 2433 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2434 Arg.Flags.getPointerAddrSpace()); 2435 } 2436 2437 InVals.push_back(Ptr); 2438 continue; 2439 } 2440 2441 SDValue Arg = lowerKernargMemParameter( 2442 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2443 Chains.push_back(Arg.getValue(1)); 2444 2445 auto *ParamTy = 2446 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2447 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2448 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2449 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2450 // On SI local pointers are just offsets into LDS, so they are always 2451 // less than 16-bits. On CI and newer they could potentially be 2452 // real pointers, so we can't guarantee their size. 2453 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2454 DAG.getValueType(MVT::i16)); 2455 } 2456 2457 InVals.push_back(Arg); 2458 continue; 2459 } else if (!IsEntryFunc && VA.isMemLoc()) { 2460 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2461 InVals.push_back(Val); 2462 if (!Arg.Flags.isByVal()) 2463 Chains.push_back(Val.getValue(1)); 2464 continue; 2465 } 2466 2467 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2468 2469 Register Reg = VA.getLocReg(); 2470 const TargetRegisterClass *RC = nullptr; 2471 if (AMDGPU::VGPR_32RegClass.contains(Reg)) 2472 RC = &AMDGPU::VGPR_32RegClass; 2473 else if (AMDGPU::SGPR_32RegClass.contains(Reg)) 2474 RC = &AMDGPU::SGPR_32RegClass; 2475 else 2476 llvm_unreachable("Unexpected register class in LowerFormalArguments!"); 2477 EVT ValVT = VA.getValVT(); 2478 2479 Reg = MF.addLiveIn(Reg, RC); 2480 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2481 2482 if (Arg.Flags.isSRet()) { 2483 // The return object should be reasonably addressable. 2484 2485 // FIXME: This helps when the return is a real sret. If it is a 2486 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2487 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2488 unsigned NumBits 2489 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2490 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2491 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2492 } 2493 2494 // If this is an 8 or 16-bit value, it is really passed promoted 2495 // to 32 bits. Insert an assert[sz]ext to capture this, then 2496 // truncate to the right size. 2497 switch (VA.getLocInfo()) { 2498 case CCValAssign::Full: 2499 break; 2500 case CCValAssign::BCvt: 2501 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2502 break; 2503 case CCValAssign::SExt: 2504 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2505 DAG.getValueType(ValVT)); 2506 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2507 break; 2508 case CCValAssign::ZExt: 2509 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2510 DAG.getValueType(ValVT)); 2511 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2512 break; 2513 case CCValAssign::AExt: 2514 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2515 break; 2516 default: 2517 llvm_unreachable("Unknown loc info!"); 2518 } 2519 2520 InVals.push_back(Val); 2521 } 2522 2523 // Start adding system SGPRs. 2524 if (IsEntryFunc) { 2525 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2526 } else { 2527 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2528 if (!IsGraphics) 2529 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2530 } 2531 2532 auto &ArgUsageInfo = 2533 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2534 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2535 2536 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2537 Info->setBytesInStackArgArea(StackArgSize); 2538 2539 return Chains.empty() ? Chain : 2540 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2541 } 2542 2543 // TODO: If return values can't fit in registers, we should return as many as 2544 // possible in registers before passing on stack. 2545 bool SITargetLowering::CanLowerReturn( 2546 CallingConv::ID CallConv, 2547 MachineFunction &MF, bool IsVarArg, 2548 const SmallVectorImpl<ISD::OutputArg> &Outs, 2549 LLVMContext &Context) const { 2550 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2551 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2552 // for shaders. Vector types should be explicitly handled by CC. 2553 if (AMDGPU::isEntryFunctionCC(CallConv)) 2554 return true; 2555 2556 SmallVector<CCValAssign, 16> RVLocs; 2557 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2558 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2559 } 2560 2561 SDValue 2562 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2563 bool isVarArg, 2564 const SmallVectorImpl<ISD::OutputArg> &Outs, 2565 const SmallVectorImpl<SDValue> &OutVals, 2566 const SDLoc &DL, SelectionDAG &DAG) const { 2567 MachineFunction &MF = DAG.getMachineFunction(); 2568 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2569 2570 if (AMDGPU::isKernel(CallConv)) { 2571 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2572 OutVals, DL, DAG); 2573 } 2574 2575 bool IsShader = AMDGPU::isShader(CallConv); 2576 2577 Info->setIfReturnsVoid(Outs.empty()); 2578 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2579 2580 // CCValAssign - represent the assignment of the return value to a location. 2581 SmallVector<CCValAssign, 48> RVLocs; 2582 SmallVector<ISD::OutputArg, 48> Splits; 2583 2584 // CCState - Info about the registers and stack slots. 2585 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2586 *DAG.getContext()); 2587 2588 // Analyze outgoing return values. 2589 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2590 2591 SDValue Flag; 2592 SmallVector<SDValue, 48> RetOps; 2593 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2594 2595 // Copy the result values into the output registers. 2596 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2597 ++I, ++RealRVLocIdx) { 2598 CCValAssign &VA = RVLocs[I]; 2599 assert(VA.isRegLoc() && "Can only return in registers!"); 2600 // TODO: Partially return in registers if return values don't fit. 2601 SDValue Arg = OutVals[RealRVLocIdx]; 2602 2603 // Copied from other backends. 2604 switch (VA.getLocInfo()) { 2605 case CCValAssign::Full: 2606 break; 2607 case CCValAssign::BCvt: 2608 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2609 break; 2610 case CCValAssign::SExt: 2611 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2612 break; 2613 case CCValAssign::ZExt: 2614 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2615 break; 2616 case CCValAssign::AExt: 2617 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2618 break; 2619 default: 2620 llvm_unreachable("Unknown loc info!"); 2621 } 2622 2623 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2624 Flag = Chain.getValue(1); 2625 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2626 } 2627 2628 // FIXME: Does sret work properly? 2629 if (!Info->isEntryFunction()) { 2630 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2631 const MCPhysReg *I = 2632 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2633 if (I) { 2634 for (; *I; ++I) { 2635 if (AMDGPU::SReg_64RegClass.contains(*I)) 2636 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2637 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2638 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2639 else 2640 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2641 } 2642 } 2643 } 2644 2645 // Update chain and glue. 2646 RetOps[0] = Chain; 2647 if (Flag.getNode()) 2648 RetOps.push_back(Flag); 2649 2650 unsigned Opc = AMDGPUISD::ENDPGM; 2651 if (!IsWaveEnd) 2652 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2653 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2654 } 2655 2656 SDValue SITargetLowering::LowerCallResult( 2657 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2658 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2659 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2660 SDValue ThisVal) const { 2661 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2662 2663 // Assign locations to each value returned by this call. 2664 SmallVector<CCValAssign, 16> RVLocs; 2665 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2666 *DAG.getContext()); 2667 CCInfo.AnalyzeCallResult(Ins, RetCC); 2668 2669 // Copy all of the result registers out of their specified physreg. 2670 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2671 CCValAssign VA = RVLocs[i]; 2672 SDValue Val; 2673 2674 if (VA.isRegLoc()) { 2675 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2676 Chain = Val.getValue(1); 2677 InFlag = Val.getValue(2); 2678 } else if (VA.isMemLoc()) { 2679 report_fatal_error("TODO: return values in memory"); 2680 } else 2681 llvm_unreachable("unknown argument location type"); 2682 2683 switch (VA.getLocInfo()) { 2684 case CCValAssign::Full: 2685 break; 2686 case CCValAssign::BCvt: 2687 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2688 break; 2689 case CCValAssign::ZExt: 2690 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2691 DAG.getValueType(VA.getValVT())); 2692 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2693 break; 2694 case CCValAssign::SExt: 2695 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2696 DAG.getValueType(VA.getValVT())); 2697 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2698 break; 2699 case CCValAssign::AExt: 2700 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2701 break; 2702 default: 2703 llvm_unreachable("Unknown loc info!"); 2704 } 2705 2706 InVals.push_back(Val); 2707 } 2708 2709 return Chain; 2710 } 2711 2712 // Add code to pass special inputs required depending on used features separate 2713 // from the explicit user arguments present in the IR. 2714 void SITargetLowering::passSpecialInputs( 2715 CallLoweringInfo &CLI, 2716 CCState &CCInfo, 2717 const SIMachineFunctionInfo &Info, 2718 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2719 SmallVectorImpl<SDValue> &MemOpChains, 2720 SDValue Chain) const { 2721 // If we don't have a call site, this was a call inserted by 2722 // legalization. These can never use special inputs. 2723 if (!CLI.CB) 2724 return; 2725 2726 SelectionDAG &DAG = CLI.DAG; 2727 const SDLoc &DL = CLI.DL; 2728 const Function &F = DAG.getMachineFunction().getFunction(); 2729 2730 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2731 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2732 2733 const AMDGPUFunctionArgInfo *CalleeArgInfo 2734 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2735 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2736 auto &ArgUsageInfo = 2737 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2738 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2739 } 2740 2741 // TODO: Unify with private memory register handling. This is complicated by 2742 // the fact that at least in kernels, the input argument is not necessarily 2743 // in the same location as the input. 2744 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue, 2745 StringLiteral> ImplicitAttrs[] = { 2746 {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"}, 2747 {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" }, 2748 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"}, 2749 {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"}, 2750 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"}, 2751 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"}, 2752 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"} 2753 }; 2754 2755 for (auto Attr : ImplicitAttrs) { 2756 const ArgDescriptor *OutgoingArg; 2757 const TargetRegisterClass *ArgRC; 2758 LLT ArgTy; 2759 2760 AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first; 2761 2762 // If the callee does not use the attribute value, skip copying the value. 2763 if (CLI.CB->hasFnAttr(Attr.second)) 2764 continue; 2765 2766 std::tie(OutgoingArg, ArgRC, ArgTy) = 2767 CalleeArgInfo->getPreloadedValue(InputID); 2768 if (!OutgoingArg) 2769 continue; 2770 2771 const ArgDescriptor *IncomingArg; 2772 const TargetRegisterClass *IncomingArgRC; 2773 LLT Ty; 2774 std::tie(IncomingArg, IncomingArgRC, Ty) = 2775 CallerArgInfo.getPreloadedValue(InputID); 2776 assert(IncomingArgRC == ArgRC); 2777 2778 // All special arguments are ints for now. 2779 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2780 SDValue InputReg; 2781 2782 if (IncomingArg) { 2783 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2784 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) { 2785 // The implicit arg ptr is special because it doesn't have a corresponding 2786 // input for kernels, and is computed from the kernarg segment pointer. 2787 InputReg = getImplicitArgPtr(DAG, DL); 2788 } else { 2789 // We may have proven the input wasn't needed, although the ABI is 2790 // requiring it. We just need to allocate the register appropriately. 2791 InputReg = DAG.getUNDEF(ArgVT); 2792 } 2793 2794 if (OutgoingArg->isRegister()) { 2795 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2796 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2797 report_fatal_error("failed to allocate implicit input argument"); 2798 } else { 2799 unsigned SpecialArgOffset = 2800 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2801 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2802 SpecialArgOffset); 2803 MemOpChains.push_back(ArgStore); 2804 } 2805 } 2806 2807 // Pack workitem IDs into a single register or pass it as is if already 2808 // packed. 2809 const ArgDescriptor *OutgoingArg; 2810 const TargetRegisterClass *ArgRC; 2811 LLT Ty; 2812 2813 std::tie(OutgoingArg, ArgRC, Ty) = 2814 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2815 if (!OutgoingArg) 2816 std::tie(OutgoingArg, ArgRC, Ty) = 2817 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2818 if (!OutgoingArg) 2819 std::tie(OutgoingArg, ArgRC, Ty) = 2820 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2821 if (!OutgoingArg) 2822 return; 2823 2824 const ArgDescriptor *IncomingArgX = std::get<0>( 2825 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2826 const ArgDescriptor *IncomingArgY = std::get<0>( 2827 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2828 const ArgDescriptor *IncomingArgZ = std::get<0>( 2829 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2830 2831 SDValue InputReg; 2832 SDLoc SL; 2833 2834 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x"); 2835 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y"); 2836 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z"); 2837 2838 // If incoming ids are not packed we need to pack them. 2839 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX && 2840 NeedWorkItemIDX) { 2841 if (Subtarget->getMaxWorkitemID(F, 0) != 0) { 2842 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2843 } else { 2844 InputReg = DAG.getConstant(0, DL, MVT::i32); 2845 } 2846 } 2847 2848 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY && 2849 NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) { 2850 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2851 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2852 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2853 InputReg = InputReg.getNode() ? 2854 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2855 } 2856 2857 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ && 2858 NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) { 2859 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2860 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2861 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2862 InputReg = InputReg.getNode() ? 2863 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2864 } 2865 2866 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) { 2867 if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) { 2868 // We're in a situation where the outgoing function requires the workitem 2869 // ID, but the calling function does not have it (e.g a graphics function 2870 // calling a C calling convention function). This is illegal, but we need 2871 // to produce something. 2872 InputReg = DAG.getUNDEF(MVT::i32); 2873 } else { 2874 // Workitem ids are already packed, any of present incoming arguments 2875 // will carry all required fields. 2876 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2877 IncomingArgX ? *IncomingArgX : 2878 IncomingArgY ? *IncomingArgY : 2879 *IncomingArgZ, ~0u); 2880 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2881 } 2882 } 2883 2884 if (OutgoingArg->isRegister()) { 2885 if (InputReg) 2886 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2887 2888 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2889 } else { 2890 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2891 if (InputReg) { 2892 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2893 SpecialArgOffset); 2894 MemOpChains.push_back(ArgStore); 2895 } 2896 } 2897 } 2898 2899 static bool canGuaranteeTCO(CallingConv::ID CC) { 2900 return CC == CallingConv::Fast; 2901 } 2902 2903 /// Return true if we might ever do TCO for calls with this calling convention. 2904 static bool mayTailCallThisCC(CallingConv::ID CC) { 2905 switch (CC) { 2906 case CallingConv::C: 2907 case CallingConv::AMDGPU_Gfx: 2908 return true; 2909 default: 2910 return canGuaranteeTCO(CC); 2911 } 2912 } 2913 2914 bool SITargetLowering::isEligibleForTailCallOptimization( 2915 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2916 const SmallVectorImpl<ISD::OutputArg> &Outs, 2917 const SmallVectorImpl<SDValue> &OutVals, 2918 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2919 if (!mayTailCallThisCC(CalleeCC)) 2920 return false; 2921 2922 // For a divergent call target, we need to do a waterfall loop over the 2923 // possible callees which precludes us from using a simple jump. 2924 if (Callee->isDivergent()) 2925 return false; 2926 2927 MachineFunction &MF = DAG.getMachineFunction(); 2928 const Function &CallerF = MF.getFunction(); 2929 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2930 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2931 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2932 2933 // Kernels aren't callable, and don't have a live in return address so it 2934 // doesn't make sense to do a tail call with entry functions. 2935 if (!CallerPreserved) 2936 return false; 2937 2938 bool CCMatch = CallerCC == CalleeCC; 2939 2940 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2941 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2942 return true; 2943 return false; 2944 } 2945 2946 // TODO: Can we handle var args? 2947 if (IsVarArg) 2948 return false; 2949 2950 for (const Argument &Arg : CallerF.args()) { 2951 if (Arg.hasByValAttr()) 2952 return false; 2953 } 2954 2955 LLVMContext &Ctx = *DAG.getContext(); 2956 2957 // Check that the call results are passed in the same way. 2958 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2959 CCAssignFnForCall(CalleeCC, IsVarArg), 2960 CCAssignFnForCall(CallerCC, IsVarArg))) 2961 return false; 2962 2963 // The callee has to preserve all registers the caller needs to preserve. 2964 if (!CCMatch) { 2965 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2966 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2967 return false; 2968 } 2969 2970 // Nothing more to check if the callee is taking no arguments. 2971 if (Outs.empty()) 2972 return true; 2973 2974 SmallVector<CCValAssign, 16> ArgLocs; 2975 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2976 2977 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2978 2979 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2980 // If the stack arguments for this call do not fit into our own save area then 2981 // the call cannot be made tail. 2982 // TODO: Is this really necessary? 2983 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2984 return false; 2985 2986 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2987 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2988 } 2989 2990 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2991 if (!CI->isTailCall()) 2992 return false; 2993 2994 const Function *ParentFn = CI->getParent()->getParent(); 2995 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2996 return false; 2997 return true; 2998 } 2999 3000 // The wave scratch offset register is used as the global base pointer. 3001 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 3002 SmallVectorImpl<SDValue> &InVals) const { 3003 SelectionDAG &DAG = CLI.DAG; 3004 const SDLoc &DL = CLI.DL; 3005 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 3006 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 3007 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 3008 SDValue Chain = CLI.Chain; 3009 SDValue Callee = CLI.Callee; 3010 bool &IsTailCall = CLI.IsTailCall; 3011 CallingConv::ID CallConv = CLI.CallConv; 3012 bool IsVarArg = CLI.IsVarArg; 3013 bool IsSibCall = false; 3014 bool IsThisReturn = false; 3015 MachineFunction &MF = DAG.getMachineFunction(); 3016 3017 if (Callee.isUndef() || isNullConstant(Callee)) { 3018 if (!CLI.IsTailCall) { 3019 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 3020 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 3021 } 3022 3023 return Chain; 3024 } 3025 3026 if (IsVarArg) { 3027 return lowerUnhandledCall(CLI, InVals, 3028 "unsupported call to variadic function "); 3029 } 3030 3031 if (!CLI.CB) 3032 report_fatal_error("unsupported libcall legalization"); 3033 3034 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 3035 return lowerUnhandledCall(CLI, InVals, 3036 "unsupported required tail call to function "); 3037 } 3038 3039 if (AMDGPU::isShader(CallConv)) { 3040 // Note the issue is with the CC of the called function, not of the call 3041 // itself. 3042 return lowerUnhandledCall(CLI, InVals, 3043 "unsupported call to a shader function "); 3044 } 3045 3046 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 3047 CallConv != CallingConv::AMDGPU_Gfx) { 3048 // Only allow calls with specific calling conventions. 3049 return lowerUnhandledCall(CLI, InVals, 3050 "unsupported calling convention for call from " 3051 "graphics shader of function "); 3052 } 3053 3054 if (IsTailCall) { 3055 IsTailCall = isEligibleForTailCallOptimization( 3056 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3057 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 3058 report_fatal_error("failed to perform tail call elimination on a call " 3059 "site marked musttail"); 3060 } 3061 3062 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3063 3064 // A sibling call is one where we're under the usual C ABI and not planning 3065 // to change that but can still do a tail call: 3066 if (!TailCallOpt && IsTailCall) 3067 IsSibCall = true; 3068 3069 if (IsTailCall) 3070 ++NumTailCalls; 3071 } 3072 3073 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3074 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3075 SmallVector<SDValue, 8> MemOpChains; 3076 3077 // Analyze operands of the call, assigning locations to each operand. 3078 SmallVector<CCValAssign, 16> ArgLocs; 3079 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3080 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3081 3082 if (CallConv != CallingConv::AMDGPU_Gfx) { 3083 // With a fixed ABI, allocate fixed registers before user arguments. 3084 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3085 } 3086 3087 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3088 3089 // Get a count of how many bytes are to be pushed on the stack. 3090 unsigned NumBytes = CCInfo.getNextStackOffset(); 3091 3092 if (IsSibCall) { 3093 // Since we're not changing the ABI to make this a tail call, the memory 3094 // operands are already available in the caller's incoming argument space. 3095 NumBytes = 0; 3096 } 3097 3098 // FPDiff is the byte offset of the call's argument area from the callee's. 3099 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3100 // by this amount for a tail call. In a sibling call it must be 0 because the 3101 // caller will deallocate the entire stack and the callee still expects its 3102 // arguments to begin at SP+0. Completely unused for non-tail calls. 3103 int32_t FPDiff = 0; 3104 MachineFrameInfo &MFI = MF.getFrameInfo(); 3105 3106 // Adjust the stack pointer for the new arguments... 3107 // These operations are automatically eliminated by the prolog/epilog pass 3108 if (!IsSibCall) { 3109 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3110 3111 if (!Subtarget->enableFlatScratch()) { 3112 SmallVector<SDValue, 4> CopyFromChains; 3113 3114 // In the HSA case, this should be an identity copy. 3115 SDValue ScratchRSrcReg 3116 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3117 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3118 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3119 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3120 } 3121 } 3122 3123 MVT PtrVT = MVT::i32; 3124 3125 // Walk the register/memloc assignments, inserting copies/loads. 3126 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3127 CCValAssign &VA = ArgLocs[i]; 3128 SDValue Arg = OutVals[i]; 3129 3130 // Promote the value if needed. 3131 switch (VA.getLocInfo()) { 3132 case CCValAssign::Full: 3133 break; 3134 case CCValAssign::BCvt: 3135 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3136 break; 3137 case CCValAssign::ZExt: 3138 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3139 break; 3140 case CCValAssign::SExt: 3141 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3142 break; 3143 case CCValAssign::AExt: 3144 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3145 break; 3146 case CCValAssign::FPExt: 3147 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3148 break; 3149 default: 3150 llvm_unreachable("Unknown loc info!"); 3151 } 3152 3153 if (VA.isRegLoc()) { 3154 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3155 } else { 3156 assert(VA.isMemLoc()); 3157 3158 SDValue DstAddr; 3159 MachinePointerInfo DstInfo; 3160 3161 unsigned LocMemOffset = VA.getLocMemOffset(); 3162 int32_t Offset = LocMemOffset; 3163 3164 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3165 MaybeAlign Alignment; 3166 3167 if (IsTailCall) { 3168 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3169 unsigned OpSize = Flags.isByVal() ? 3170 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3171 3172 // FIXME: We can have better than the minimum byval required alignment. 3173 Alignment = 3174 Flags.isByVal() 3175 ? Flags.getNonZeroByValAlign() 3176 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3177 3178 Offset = Offset + FPDiff; 3179 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3180 3181 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3182 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3183 3184 // Make sure any stack arguments overlapping with where we're storing 3185 // are loaded before this eventual operation. Otherwise they'll be 3186 // clobbered. 3187 3188 // FIXME: Why is this really necessary? This seems to just result in a 3189 // lot of code to copy the stack and write them back to the same 3190 // locations, which are supposed to be immutable? 3191 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3192 } else { 3193 // Stores to the argument stack area are relative to the stack pointer. 3194 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(), 3195 MVT::i32); 3196 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff); 3197 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3198 Alignment = 3199 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3200 } 3201 3202 if (Outs[i].Flags.isByVal()) { 3203 SDValue SizeNode = 3204 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3205 SDValue Cpy = 3206 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3207 Outs[i].Flags.getNonZeroByValAlign(), 3208 /*isVol = */ false, /*AlwaysInline = */ true, 3209 /*isTailCall = */ false, DstInfo, 3210 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3211 3212 MemOpChains.push_back(Cpy); 3213 } else { 3214 SDValue Store = 3215 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3216 MemOpChains.push_back(Store); 3217 } 3218 } 3219 } 3220 3221 if (!MemOpChains.empty()) 3222 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3223 3224 // Build a sequence of copy-to-reg nodes chained together with token chain 3225 // and flag operands which copy the outgoing args into the appropriate regs. 3226 SDValue InFlag; 3227 for (auto &RegToPass : RegsToPass) { 3228 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3229 RegToPass.second, InFlag); 3230 InFlag = Chain.getValue(1); 3231 } 3232 3233 3234 // We don't usually want to end the call-sequence here because we would tidy 3235 // the frame up *after* the call, however in the ABI-changing tail-call case 3236 // we've carefully laid out the parameters so that when sp is reset they'll be 3237 // in the correct location. 3238 if (IsTailCall && !IsSibCall) { 3239 Chain = DAG.getCALLSEQ_END(Chain, 3240 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3241 DAG.getTargetConstant(0, DL, MVT::i32), 3242 InFlag, DL); 3243 InFlag = Chain.getValue(1); 3244 } 3245 3246 std::vector<SDValue> Ops; 3247 Ops.push_back(Chain); 3248 Ops.push_back(Callee); 3249 // Add a redundant copy of the callee global which will not be legalized, as 3250 // we need direct access to the callee later. 3251 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3252 const GlobalValue *GV = GSD->getGlobal(); 3253 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3254 } else { 3255 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3256 } 3257 3258 if (IsTailCall) { 3259 // Each tail call may have to adjust the stack by a different amount, so 3260 // this information must travel along with the operation for eventual 3261 // consumption by emitEpilogue. 3262 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3263 } 3264 3265 // Add argument registers to the end of the list so that they are known live 3266 // into the call. 3267 for (auto &RegToPass : RegsToPass) { 3268 Ops.push_back(DAG.getRegister(RegToPass.first, 3269 RegToPass.second.getValueType())); 3270 } 3271 3272 // Add a register mask operand representing the call-preserved registers. 3273 3274 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3275 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3276 assert(Mask && "Missing call preserved mask for calling convention"); 3277 Ops.push_back(DAG.getRegisterMask(Mask)); 3278 3279 if (InFlag.getNode()) 3280 Ops.push_back(InFlag); 3281 3282 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3283 3284 // If we're doing a tall call, use a TC_RETURN here rather than an 3285 // actual call instruction. 3286 if (IsTailCall) { 3287 MFI.setHasTailCall(); 3288 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3289 } 3290 3291 // Returns a chain and a flag for retval copy to use. 3292 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3293 Chain = Call.getValue(0); 3294 InFlag = Call.getValue(1); 3295 3296 uint64_t CalleePopBytes = NumBytes; 3297 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3298 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3299 InFlag, DL); 3300 if (!Ins.empty()) 3301 InFlag = Chain.getValue(1); 3302 3303 // Handle result values, copying them out of physregs into vregs that we 3304 // return. 3305 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3306 InVals, IsThisReturn, 3307 IsThisReturn ? OutVals[0] : SDValue()); 3308 } 3309 3310 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3311 // except for applying the wave size scale to the increment amount. 3312 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3313 SDValue Op, SelectionDAG &DAG) const { 3314 const MachineFunction &MF = DAG.getMachineFunction(); 3315 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3316 3317 SDLoc dl(Op); 3318 EVT VT = Op.getValueType(); 3319 SDValue Tmp1 = Op; 3320 SDValue Tmp2 = Op.getValue(1); 3321 SDValue Tmp3 = Op.getOperand(2); 3322 SDValue Chain = Tmp1.getOperand(0); 3323 3324 Register SPReg = Info->getStackPtrOffsetReg(); 3325 3326 // Chain the dynamic stack allocation so that it doesn't modify the stack 3327 // pointer when other instructions are using the stack. 3328 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3329 3330 SDValue Size = Tmp2.getOperand(1); 3331 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3332 Chain = SP.getValue(1); 3333 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3334 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3335 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3336 unsigned Opc = 3337 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3338 ISD::ADD : ISD::SUB; 3339 3340 SDValue ScaledSize = DAG.getNode( 3341 ISD::SHL, dl, VT, Size, 3342 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3343 3344 Align StackAlign = TFL->getStackAlign(); 3345 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3346 if (Alignment && *Alignment > StackAlign) { 3347 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3348 DAG.getConstant(-(uint64_t)Alignment->value() 3349 << ST.getWavefrontSizeLog2(), 3350 dl, VT)); 3351 } 3352 3353 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3354 Tmp2 = DAG.getCALLSEQ_END( 3355 Chain, DAG.getIntPtrConstant(0, dl, true), 3356 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3357 3358 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3359 } 3360 3361 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3362 SelectionDAG &DAG) const { 3363 // We only handle constant sizes here to allow non-entry block, static sized 3364 // allocas. A truly dynamic value is more difficult to support because we 3365 // don't know if the size value is uniform or not. If the size isn't uniform, 3366 // we would need to do a wave reduction to get the maximum size to know how 3367 // much to increment the uniform stack pointer. 3368 SDValue Size = Op.getOperand(1); 3369 if (isa<ConstantSDNode>(Size)) 3370 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3371 3372 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3373 } 3374 3375 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3376 const MachineFunction &MF) const { 3377 Register Reg = StringSwitch<Register>(RegName) 3378 .Case("m0", AMDGPU::M0) 3379 .Case("exec", AMDGPU::EXEC) 3380 .Case("exec_lo", AMDGPU::EXEC_LO) 3381 .Case("exec_hi", AMDGPU::EXEC_HI) 3382 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3383 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3384 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3385 .Default(Register()); 3386 3387 if (Reg == AMDGPU::NoRegister) { 3388 report_fatal_error(Twine("invalid register name \"" 3389 + StringRef(RegName) + "\".")); 3390 3391 } 3392 3393 if (!Subtarget->hasFlatScrRegister() && 3394 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3395 report_fatal_error(Twine("invalid register \"" 3396 + StringRef(RegName) + "\" for subtarget.")); 3397 } 3398 3399 switch (Reg) { 3400 case AMDGPU::M0: 3401 case AMDGPU::EXEC_LO: 3402 case AMDGPU::EXEC_HI: 3403 case AMDGPU::FLAT_SCR_LO: 3404 case AMDGPU::FLAT_SCR_HI: 3405 if (VT.getSizeInBits() == 32) 3406 return Reg; 3407 break; 3408 case AMDGPU::EXEC: 3409 case AMDGPU::FLAT_SCR: 3410 if (VT.getSizeInBits() == 64) 3411 return Reg; 3412 break; 3413 default: 3414 llvm_unreachable("missing register type checking"); 3415 } 3416 3417 report_fatal_error(Twine("invalid type for register \"" 3418 + StringRef(RegName) + "\".")); 3419 } 3420 3421 // If kill is not the last instruction, split the block so kill is always a 3422 // proper terminator. 3423 MachineBasicBlock * 3424 SITargetLowering::splitKillBlock(MachineInstr &MI, 3425 MachineBasicBlock *BB) const { 3426 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3427 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3428 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3429 return SplitBB; 3430 } 3431 3432 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3433 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3434 // be the first instruction in the remainder block. 3435 // 3436 /// \returns { LoopBody, Remainder } 3437 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3438 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3439 MachineFunction *MF = MBB.getParent(); 3440 MachineBasicBlock::iterator I(&MI); 3441 3442 // To insert the loop we need to split the block. Move everything after this 3443 // point to a new block, and insert a new empty block between the two. 3444 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3445 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3446 MachineFunction::iterator MBBI(MBB); 3447 ++MBBI; 3448 3449 MF->insert(MBBI, LoopBB); 3450 MF->insert(MBBI, RemainderBB); 3451 3452 LoopBB->addSuccessor(LoopBB); 3453 LoopBB->addSuccessor(RemainderBB); 3454 3455 // Move the rest of the block into a new block. 3456 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3457 3458 if (InstInLoop) { 3459 auto Next = std::next(I); 3460 3461 // Move instruction to loop body. 3462 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3463 3464 // Move the rest of the block. 3465 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3466 } else { 3467 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3468 } 3469 3470 MBB.addSuccessor(LoopBB); 3471 3472 return std::make_pair(LoopBB, RemainderBB); 3473 } 3474 3475 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3476 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3477 MachineBasicBlock *MBB = MI.getParent(); 3478 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3479 auto I = MI.getIterator(); 3480 auto E = std::next(I); 3481 3482 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3483 .addImm(0); 3484 3485 MIBundleBuilder Bundler(*MBB, I, E); 3486 finalizeBundle(*MBB, Bundler.begin()); 3487 } 3488 3489 MachineBasicBlock * 3490 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3491 MachineBasicBlock *BB) const { 3492 const DebugLoc &DL = MI.getDebugLoc(); 3493 3494 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3495 3496 MachineBasicBlock *LoopBB; 3497 MachineBasicBlock *RemainderBB; 3498 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3499 3500 // Apparently kill flags are only valid if the def is in the same block? 3501 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3502 Src->setIsKill(false); 3503 3504 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3505 3506 MachineBasicBlock::iterator I = LoopBB->end(); 3507 3508 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3509 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3510 3511 // Clear TRAP_STS.MEM_VIOL 3512 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3513 .addImm(0) 3514 .addImm(EncodedReg); 3515 3516 bundleInstWithWaitcnt(MI); 3517 3518 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3519 3520 // Load and check TRAP_STS.MEM_VIOL 3521 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3522 .addImm(EncodedReg); 3523 3524 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3525 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3526 .addReg(Reg, RegState::Kill) 3527 .addImm(0); 3528 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3529 .addMBB(LoopBB); 3530 3531 return RemainderBB; 3532 } 3533 3534 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3535 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3536 // will only do one iteration. In the worst case, this will loop 64 times. 3537 // 3538 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3539 static MachineBasicBlock::iterator 3540 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3541 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3542 const DebugLoc &DL, const MachineOperand &Idx, 3543 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3544 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3545 Register &SGPRIdxReg) { 3546 3547 MachineFunction *MF = OrigBB.getParent(); 3548 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3549 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3550 MachineBasicBlock::iterator I = LoopBB.begin(); 3551 3552 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3553 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3554 Register NewExec = MRI.createVirtualRegister(BoolRC); 3555 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3556 Register CondReg = MRI.createVirtualRegister(BoolRC); 3557 3558 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3559 .addReg(InitReg) 3560 .addMBB(&OrigBB) 3561 .addReg(ResultReg) 3562 .addMBB(&LoopBB); 3563 3564 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3565 .addReg(InitSaveExecReg) 3566 .addMBB(&OrigBB) 3567 .addReg(NewExec) 3568 .addMBB(&LoopBB); 3569 3570 // Read the next variant <- also loop target. 3571 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3572 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3573 3574 // Compare the just read M0 value to all possible Idx values. 3575 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3576 .addReg(CurrentIdxReg) 3577 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3578 3579 // Update EXEC, save the original EXEC value to VCC. 3580 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3581 : AMDGPU::S_AND_SAVEEXEC_B64), 3582 NewExec) 3583 .addReg(CondReg, RegState::Kill); 3584 3585 MRI.setSimpleHint(NewExec, CondReg); 3586 3587 if (UseGPRIdxMode) { 3588 if (Offset == 0) { 3589 SGPRIdxReg = CurrentIdxReg; 3590 } else { 3591 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3592 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3593 .addReg(CurrentIdxReg, RegState::Kill) 3594 .addImm(Offset); 3595 } 3596 } else { 3597 // Move index from VCC into M0 3598 if (Offset == 0) { 3599 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3600 .addReg(CurrentIdxReg, RegState::Kill); 3601 } else { 3602 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3603 .addReg(CurrentIdxReg, RegState::Kill) 3604 .addImm(Offset); 3605 } 3606 } 3607 3608 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3609 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3610 MachineInstr *InsertPt = 3611 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3612 : AMDGPU::S_XOR_B64_term), Exec) 3613 .addReg(Exec) 3614 .addReg(NewExec); 3615 3616 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3617 // s_cbranch_scc0? 3618 3619 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3620 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3621 .addMBB(&LoopBB); 3622 3623 return InsertPt->getIterator(); 3624 } 3625 3626 // This has slightly sub-optimal regalloc when the source vector is killed by 3627 // the read. The register allocator does not understand that the kill is 3628 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3629 // subregister from it, using 1 more VGPR than necessary. This was saved when 3630 // this was expanded after register allocation. 3631 static MachineBasicBlock::iterator 3632 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3633 unsigned InitResultReg, unsigned PhiReg, int Offset, 3634 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3635 MachineFunction *MF = MBB.getParent(); 3636 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3637 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3638 MachineRegisterInfo &MRI = MF->getRegInfo(); 3639 const DebugLoc &DL = MI.getDebugLoc(); 3640 MachineBasicBlock::iterator I(&MI); 3641 3642 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3643 Register DstReg = MI.getOperand(0).getReg(); 3644 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3645 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3646 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3647 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3648 3649 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3650 3651 // Save the EXEC mask 3652 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3653 .addReg(Exec); 3654 3655 MachineBasicBlock *LoopBB; 3656 MachineBasicBlock *RemainderBB; 3657 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3658 3659 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3660 3661 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3662 InitResultReg, DstReg, PhiReg, TmpExec, 3663 Offset, UseGPRIdxMode, SGPRIdxReg); 3664 3665 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3666 MachineFunction::iterator MBBI(LoopBB); 3667 ++MBBI; 3668 MF->insert(MBBI, LandingPad); 3669 LoopBB->removeSuccessor(RemainderBB); 3670 LandingPad->addSuccessor(RemainderBB); 3671 LoopBB->addSuccessor(LandingPad); 3672 MachineBasicBlock::iterator First = LandingPad->begin(); 3673 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3674 .addReg(SaveExec); 3675 3676 return InsPt; 3677 } 3678 3679 // Returns subreg index, offset 3680 static std::pair<unsigned, int> 3681 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3682 const TargetRegisterClass *SuperRC, 3683 unsigned VecReg, 3684 int Offset) { 3685 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3686 3687 // Skip out of bounds offsets, or else we would end up using an undefined 3688 // register. 3689 if (Offset >= NumElts || Offset < 0) 3690 return std::make_pair(AMDGPU::sub0, Offset); 3691 3692 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3693 } 3694 3695 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3696 MachineRegisterInfo &MRI, MachineInstr &MI, 3697 int Offset) { 3698 MachineBasicBlock *MBB = MI.getParent(); 3699 const DebugLoc &DL = MI.getDebugLoc(); 3700 MachineBasicBlock::iterator I(&MI); 3701 3702 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3703 3704 assert(Idx->getReg() != AMDGPU::NoRegister); 3705 3706 if (Offset == 0) { 3707 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3708 } else { 3709 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3710 .add(*Idx) 3711 .addImm(Offset); 3712 } 3713 } 3714 3715 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3716 MachineRegisterInfo &MRI, MachineInstr &MI, 3717 int Offset) { 3718 MachineBasicBlock *MBB = MI.getParent(); 3719 const DebugLoc &DL = MI.getDebugLoc(); 3720 MachineBasicBlock::iterator I(&MI); 3721 3722 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3723 3724 if (Offset == 0) 3725 return Idx->getReg(); 3726 3727 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3728 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3729 .add(*Idx) 3730 .addImm(Offset); 3731 return Tmp; 3732 } 3733 3734 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3735 MachineBasicBlock &MBB, 3736 const GCNSubtarget &ST) { 3737 const SIInstrInfo *TII = ST.getInstrInfo(); 3738 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3739 MachineFunction *MF = MBB.getParent(); 3740 MachineRegisterInfo &MRI = MF->getRegInfo(); 3741 3742 Register Dst = MI.getOperand(0).getReg(); 3743 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3744 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3745 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3746 3747 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3748 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3749 3750 unsigned SubReg; 3751 std::tie(SubReg, Offset) 3752 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3753 3754 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3755 3756 // Check for a SGPR index. 3757 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3758 MachineBasicBlock::iterator I(&MI); 3759 const DebugLoc &DL = MI.getDebugLoc(); 3760 3761 if (UseGPRIdxMode) { 3762 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3763 // to avoid interfering with other uses, so probably requires a new 3764 // optimization pass. 3765 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3766 3767 const MCInstrDesc &GPRIDXDesc = 3768 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3769 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3770 .addReg(SrcReg) 3771 .addReg(Idx) 3772 .addImm(SubReg); 3773 } else { 3774 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3775 3776 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3777 .addReg(SrcReg, 0, SubReg) 3778 .addReg(SrcReg, RegState::Implicit); 3779 } 3780 3781 MI.eraseFromParent(); 3782 3783 return &MBB; 3784 } 3785 3786 // Control flow needs to be inserted if indexing with a VGPR. 3787 const DebugLoc &DL = MI.getDebugLoc(); 3788 MachineBasicBlock::iterator I(&MI); 3789 3790 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3791 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3792 3793 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3794 3795 Register SGPRIdxReg; 3796 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3797 UseGPRIdxMode, SGPRIdxReg); 3798 3799 MachineBasicBlock *LoopBB = InsPt->getParent(); 3800 3801 if (UseGPRIdxMode) { 3802 const MCInstrDesc &GPRIDXDesc = 3803 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3804 3805 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3806 .addReg(SrcReg) 3807 .addReg(SGPRIdxReg) 3808 .addImm(SubReg); 3809 } else { 3810 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3811 .addReg(SrcReg, 0, SubReg) 3812 .addReg(SrcReg, RegState::Implicit); 3813 } 3814 3815 MI.eraseFromParent(); 3816 3817 return LoopBB; 3818 } 3819 3820 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3821 MachineBasicBlock &MBB, 3822 const GCNSubtarget &ST) { 3823 const SIInstrInfo *TII = ST.getInstrInfo(); 3824 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3825 MachineFunction *MF = MBB.getParent(); 3826 MachineRegisterInfo &MRI = MF->getRegInfo(); 3827 3828 Register Dst = MI.getOperand(0).getReg(); 3829 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3830 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3831 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3832 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3833 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3834 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3835 3836 // This can be an immediate, but will be folded later. 3837 assert(Val->getReg()); 3838 3839 unsigned SubReg; 3840 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3841 SrcVec->getReg(), 3842 Offset); 3843 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3844 3845 if (Idx->getReg() == AMDGPU::NoRegister) { 3846 MachineBasicBlock::iterator I(&MI); 3847 const DebugLoc &DL = MI.getDebugLoc(); 3848 3849 assert(Offset == 0); 3850 3851 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3852 .add(*SrcVec) 3853 .add(*Val) 3854 .addImm(SubReg); 3855 3856 MI.eraseFromParent(); 3857 return &MBB; 3858 } 3859 3860 // Check for a SGPR index. 3861 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3862 MachineBasicBlock::iterator I(&MI); 3863 const DebugLoc &DL = MI.getDebugLoc(); 3864 3865 if (UseGPRIdxMode) { 3866 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3867 3868 const MCInstrDesc &GPRIDXDesc = 3869 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3870 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3871 .addReg(SrcVec->getReg()) 3872 .add(*Val) 3873 .addReg(Idx) 3874 .addImm(SubReg); 3875 } else { 3876 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3877 3878 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3879 TRI.getRegSizeInBits(*VecRC), 32, false); 3880 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3881 .addReg(SrcVec->getReg()) 3882 .add(*Val) 3883 .addImm(SubReg); 3884 } 3885 MI.eraseFromParent(); 3886 return &MBB; 3887 } 3888 3889 // Control flow needs to be inserted if indexing with a VGPR. 3890 if (Val->isReg()) 3891 MRI.clearKillFlags(Val->getReg()); 3892 3893 const DebugLoc &DL = MI.getDebugLoc(); 3894 3895 Register PhiReg = MRI.createVirtualRegister(VecRC); 3896 3897 Register SGPRIdxReg; 3898 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3899 UseGPRIdxMode, SGPRIdxReg); 3900 MachineBasicBlock *LoopBB = InsPt->getParent(); 3901 3902 if (UseGPRIdxMode) { 3903 const MCInstrDesc &GPRIDXDesc = 3904 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3905 3906 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3907 .addReg(PhiReg) 3908 .add(*Val) 3909 .addReg(SGPRIdxReg) 3910 .addImm(AMDGPU::sub0); 3911 } else { 3912 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3913 TRI.getRegSizeInBits(*VecRC), 32, false); 3914 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3915 .addReg(PhiReg) 3916 .add(*Val) 3917 .addImm(AMDGPU::sub0); 3918 } 3919 3920 MI.eraseFromParent(); 3921 return LoopBB; 3922 } 3923 3924 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3925 MachineInstr &MI, MachineBasicBlock *BB) const { 3926 3927 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3928 MachineFunction *MF = BB->getParent(); 3929 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3930 3931 switch (MI.getOpcode()) { 3932 case AMDGPU::S_UADDO_PSEUDO: 3933 case AMDGPU::S_USUBO_PSEUDO: { 3934 const DebugLoc &DL = MI.getDebugLoc(); 3935 MachineOperand &Dest0 = MI.getOperand(0); 3936 MachineOperand &Dest1 = MI.getOperand(1); 3937 MachineOperand &Src0 = MI.getOperand(2); 3938 MachineOperand &Src1 = MI.getOperand(3); 3939 3940 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3941 ? AMDGPU::S_ADD_I32 3942 : AMDGPU::S_SUB_I32; 3943 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3944 3945 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3946 .addImm(1) 3947 .addImm(0); 3948 3949 MI.eraseFromParent(); 3950 return BB; 3951 } 3952 case AMDGPU::S_ADD_U64_PSEUDO: 3953 case AMDGPU::S_SUB_U64_PSEUDO: { 3954 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3955 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3956 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3957 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3958 const DebugLoc &DL = MI.getDebugLoc(); 3959 3960 MachineOperand &Dest = MI.getOperand(0); 3961 MachineOperand &Src0 = MI.getOperand(1); 3962 MachineOperand &Src1 = MI.getOperand(2); 3963 3964 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3965 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3966 3967 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3968 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3969 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3970 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3971 3972 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3973 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3974 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3975 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3976 3977 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3978 3979 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3980 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3981 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3982 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3983 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3984 .addReg(DestSub0) 3985 .addImm(AMDGPU::sub0) 3986 .addReg(DestSub1) 3987 .addImm(AMDGPU::sub1); 3988 MI.eraseFromParent(); 3989 return BB; 3990 } 3991 case AMDGPU::V_ADD_U64_PSEUDO: 3992 case AMDGPU::V_SUB_U64_PSEUDO: { 3993 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3994 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3995 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3996 const DebugLoc &DL = MI.getDebugLoc(); 3997 3998 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3999 4000 MachineOperand &Dest = MI.getOperand(0); 4001 MachineOperand &Src0 = MI.getOperand(1); 4002 MachineOperand &Src1 = MI.getOperand(2); 4003 4004 if (IsAdd && ST.hasLshlAddB64()) { 4005 auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64), 4006 Dest.getReg()) 4007 .add(Src0) 4008 .addImm(0) 4009 .add(Src1); 4010 TII->legalizeOperands(*Add); 4011 MI.eraseFromParent(); 4012 return BB; 4013 } 4014 4015 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4016 4017 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4018 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4019 4020 Register CarryReg = MRI.createVirtualRegister(CarryRC); 4021 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 4022 4023 const TargetRegisterClass *Src0RC = Src0.isReg() 4024 ? MRI.getRegClass(Src0.getReg()) 4025 : &AMDGPU::VReg_64RegClass; 4026 const TargetRegisterClass *Src1RC = Src1.isReg() 4027 ? MRI.getRegClass(Src1.getReg()) 4028 : &AMDGPU::VReg_64RegClass; 4029 4030 const TargetRegisterClass *Src0SubRC = 4031 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 4032 const TargetRegisterClass *Src1SubRC = 4033 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 4034 4035 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 4036 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 4037 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 4038 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 4039 4040 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 4041 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 4042 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 4043 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 4044 4045 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 4046 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 4047 .addReg(CarryReg, RegState::Define) 4048 .add(SrcReg0Sub0) 4049 .add(SrcReg1Sub0) 4050 .addImm(0); // clamp bit 4051 4052 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 4053 MachineInstr *HiHalf = 4054 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 4055 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 4056 .add(SrcReg0Sub1) 4057 .add(SrcReg1Sub1) 4058 .addReg(CarryReg, RegState::Kill) 4059 .addImm(0); // clamp bit 4060 4061 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4062 .addReg(DestSub0) 4063 .addImm(AMDGPU::sub0) 4064 .addReg(DestSub1) 4065 .addImm(AMDGPU::sub1); 4066 TII->legalizeOperands(*LoHalf); 4067 TII->legalizeOperands(*HiHalf); 4068 MI.eraseFromParent(); 4069 return BB; 4070 } 4071 case AMDGPU::S_ADD_CO_PSEUDO: 4072 case AMDGPU::S_SUB_CO_PSEUDO: { 4073 // This pseudo has a chance to be selected 4074 // only from uniform add/subcarry node. All the VGPR operands 4075 // therefore assumed to be splat vectors. 4076 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4077 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4078 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4079 MachineBasicBlock::iterator MII = MI; 4080 const DebugLoc &DL = MI.getDebugLoc(); 4081 MachineOperand &Dest = MI.getOperand(0); 4082 MachineOperand &CarryDest = MI.getOperand(1); 4083 MachineOperand &Src0 = MI.getOperand(2); 4084 MachineOperand &Src1 = MI.getOperand(3); 4085 MachineOperand &Src2 = MI.getOperand(4); 4086 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4087 ? AMDGPU::S_ADDC_U32 4088 : AMDGPU::S_SUBB_U32; 4089 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4090 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4091 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4092 .addReg(Src0.getReg()); 4093 Src0.setReg(RegOp0); 4094 } 4095 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4096 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4097 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4098 .addReg(Src1.getReg()); 4099 Src1.setReg(RegOp1); 4100 } 4101 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4102 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4103 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4104 .addReg(Src2.getReg()); 4105 Src2.setReg(RegOp2); 4106 } 4107 4108 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4109 unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC); 4110 assert(WaveSize == 64 || WaveSize == 32); 4111 4112 if (WaveSize == 64) { 4113 if (ST.hasScalarCompareEq64()) { 4114 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4115 .addReg(Src2.getReg()) 4116 .addImm(0); 4117 } else { 4118 const TargetRegisterClass *SubRC = 4119 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4120 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4121 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4122 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4123 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4124 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4125 4126 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4127 .add(Src2Sub0) 4128 .add(Src2Sub1); 4129 4130 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4131 .addReg(Src2_32, RegState::Kill) 4132 .addImm(0); 4133 } 4134 } else { 4135 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4136 .addReg(Src2.getReg()) 4137 .addImm(0); 4138 } 4139 4140 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4141 4142 unsigned SelOpc = 4143 (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32; 4144 4145 BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg()) 4146 .addImm(-1) 4147 .addImm(0); 4148 4149 MI.eraseFromParent(); 4150 return BB; 4151 } 4152 case AMDGPU::SI_INIT_M0: { 4153 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4154 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4155 .add(MI.getOperand(0)); 4156 MI.eraseFromParent(); 4157 return BB; 4158 } 4159 case AMDGPU::GET_GROUPSTATICSIZE: { 4160 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4161 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4162 DebugLoc DL = MI.getDebugLoc(); 4163 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4164 .add(MI.getOperand(0)) 4165 .addImm(MFI->getLDSSize()); 4166 MI.eraseFromParent(); 4167 return BB; 4168 } 4169 case AMDGPU::SI_INDIRECT_SRC_V1: 4170 case AMDGPU::SI_INDIRECT_SRC_V2: 4171 case AMDGPU::SI_INDIRECT_SRC_V4: 4172 case AMDGPU::SI_INDIRECT_SRC_V8: 4173 case AMDGPU::SI_INDIRECT_SRC_V16: 4174 case AMDGPU::SI_INDIRECT_SRC_V32: 4175 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4176 case AMDGPU::SI_INDIRECT_DST_V1: 4177 case AMDGPU::SI_INDIRECT_DST_V2: 4178 case AMDGPU::SI_INDIRECT_DST_V4: 4179 case AMDGPU::SI_INDIRECT_DST_V8: 4180 case AMDGPU::SI_INDIRECT_DST_V16: 4181 case AMDGPU::SI_INDIRECT_DST_V32: 4182 return emitIndirectDst(MI, *BB, *getSubtarget()); 4183 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4184 case AMDGPU::SI_KILL_I1_PSEUDO: 4185 return splitKillBlock(MI, BB); 4186 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4187 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4188 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4189 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4190 4191 Register Dst = MI.getOperand(0).getReg(); 4192 Register Src0 = MI.getOperand(1).getReg(); 4193 Register Src1 = MI.getOperand(2).getReg(); 4194 const DebugLoc &DL = MI.getDebugLoc(); 4195 Register SrcCond = MI.getOperand(3).getReg(); 4196 4197 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4198 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4199 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4200 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4201 4202 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4203 .addReg(SrcCond); 4204 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4205 .addImm(0) 4206 .addReg(Src0, 0, AMDGPU::sub0) 4207 .addImm(0) 4208 .addReg(Src1, 0, AMDGPU::sub0) 4209 .addReg(SrcCondCopy); 4210 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4211 .addImm(0) 4212 .addReg(Src0, 0, AMDGPU::sub1) 4213 .addImm(0) 4214 .addReg(Src1, 0, AMDGPU::sub1) 4215 .addReg(SrcCondCopy); 4216 4217 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4218 .addReg(DstLo) 4219 .addImm(AMDGPU::sub0) 4220 .addReg(DstHi) 4221 .addImm(AMDGPU::sub1); 4222 MI.eraseFromParent(); 4223 return BB; 4224 } 4225 case AMDGPU::SI_BR_UNDEF: { 4226 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4227 const DebugLoc &DL = MI.getDebugLoc(); 4228 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4229 .add(MI.getOperand(0)); 4230 Br->getOperand(1).setIsUndef(true); // read undef SCC 4231 MI.eraseFromParent(); 4232 return BB; 4233 } 4234 case AMDGPU::ADJCALLSTACKUP: 4235 case AMDGPU::ADJCALLSTACKDOWN: { 4236 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4237 MachineInstrBuilder MIB(*MF, &MI); 4238 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4239 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4240 return BB; 4241 } 4242 case AMDGPU::SI_CALL_ISEL: { 4243 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4244 const DebugLoc &DL = MI.getDebugLoc(); 4245 4246 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4247 4248 MachineInstrBuilder MIB; 4249 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4250 4251 for (const MachineOperand &MO : MI.operands()) 4252 MIB.add(MO); 4253 4254 MIB.cloneMemRefs(MI); 4255 MI.eraseFromParent(); 4256 return BB; 4257 } 4258 case AMDGPU::V_ADD_CO_U32_e32: 4259 case AMDGPU::V_SUB_CO_U32_e32: 4260 case AMDGPU::V_SUBREV_CO_U32_e32: { 4261 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4262 const DebugLoc &DL = MI.getDebugLoc(); 4263 unsigned Opc = MI.getOpcode(); 4264 4265 bool NeedClampOperand = false; 4266 if (TII->pseudoToMCOpcode(Opc) == -1) { 4267 Opc = AMDGPU::getVOPe64(Opc); 4268 NeedClampOperand = true; 4269 } 4270 4271 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4272 if (TII->isVOP3(*I)) { 4273 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4274 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4275 I.addReg(TRI->getVCC(), RegState::Define); 4276 } 4277 I.add(MI.getOperand(1)) 4278 .add(MI.getOperand(2)); 4279 if (NeedClampOperand) 4280 I.addImm(0); // clamp bit for e64 encoding 4281 4282 TII->legalizeOperands(*I); 4283 4284 MI.eraseFromParent(); 4285 return BB; 4286 } 4287 case AMDGPU::V_ADDC_U32_e32: 4288 case AMDGPU::V_SUBB_U32_e32: 4289 case AMDGPU::V_SUBBREV_U32_e32: 4290 // These instructions have an implicit use of vcc which counts towards the 4291 // constant bus limit. 4292 TII->legalizeOperands(MI); 4293 return BB; 4294 case AMDGPU::DS_GWS_INIT: 4295 case AMDGPU::DS_GWS_SEMA_BR: 4296 case AMDGPU::DS_GWS_BARRIER: 4297 TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::data0); 4298 LLVM_FALLTHROUGH; 4299 case AMDGPU::DS_GWS_SEMA_V: 4300 case AMDGPU::DS_GWS_SEMA_P: 4301 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4302 // A s_waitcnt 0 is required to be the instruction immediately following. 4303 if (getSubtarget()->hasGWSAutoReplay()) { 4304 bundleInstWithWaitcnt(MI); 4305 return BB; 4306 } 4307 4308 return emitGWSMemViolTestLoop(MI, BB); 4309 case AMDGPU::S_SETREG_B32: { 4310 // Try to optimize cases that only set the denormal mode or rounding mode. 4311 // 4312 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4313 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4314 // instead. 4315 // 4316 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4317 // allow you to have a no side effect instruction in the output of a 4318 // sideeffecting pattern. 4319 unsigned ID, Offset, Width; 4320 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4321 if (ID != AMDGPU::Hwreg::ID_MODE) 4322 return BB; 4323 4324 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4325 const unsigned SetMask = WidthMask << Offset; 4326 4327 if (getSubtarget()->hasDenormModeInst()) { 4328 unsigned SetDenormOp = 0; 4329 unsigned SetRoundOp = 0; 4330 4331 // The dedicated instructions can only set the whole denorm or round mode 4332 // at once, not a subset of bits in either. 4333 if (SetMask == 4334 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4335 // If this fully sets both the round and denorm mode, emit the two 4336 // dedicated instructions for these. 4337 SetRoundOp = AMDGPU::S_ROUND_MODE; 4338 SetDenormOp = AMDGPU::S_DENORM_MODE; 4339 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4340 SetRoundOp = AMDGPU::S_ROUND_MODE; 4341 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4342 SetDenormOp = AMDGPU::S_DENORM_MODE; 4343 } 4344 4345 if (SetRoundOp || SetDenormOp) { 4346 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4347 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4348 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4349 unsigned ImmVal = Def->getOperand(1).getImm(); 4350 if (SetRoundOp) { 4351 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4352 .addImm(ImmVal & 0xf); 4353 4354 // If we also have the denorm mode, get just the denorm mode bits. 4355 ImmVal >>= 4; 4356 } 4357 4358 if (SetDenormOp) { 4359 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4360 .addImm(ImmVal & 0xf); 4361 } 4362 4363 MI.eraseFromParent(); 4364 return BB; 4365 } 4366 } 4367 } 4368 4369 // If only FP bits are touched, used the no side effects pseudo. 4370 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4371 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4372 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4373 4374 return BB; 4375 } 4376 default: 4377 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4378 } 4379 } 4380 4381 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4382 return isTypeLegal(VT.getScalarType()); 4383 } 4384 4385 bool SITargetLowering::hasAtomicFaddRtnForTy(SDValue &Op) const { 4386 switch (Op.getValue(0).getSimpleValueType().SimpleTy) { 4387 case MVT::f32: 4388 return Subtarget->hasAtomicFaddRtnInsts(); 4389 case MVT::v2f16: 4390 case MVT::f64: 4391 return Subtarget->hasGFX90AInsts(); 4392 default: 4393 return false; 4394 } 4395 } 4396 4397 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4398 // This currently forces unfolding various combinations of fsub into fma with 4399 // free fneg'd operands. As long as we have fast FMA (controlled by 4400 // isFMAFasterThanFMulAndFAdd), we should perform these. 4401 4402 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4403 // most of these combines appear to be cycle neutral but save on instruction 4404 // count / code size. 4405 return true; 4406 } 4407 4408 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; } 4409 4410 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4411 EVT VT) const { 4412 if (!VT.isVector()) { 4413 return MVT::i1; 4414 } 4415 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4416 } 4417 4418 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4419 // TODO: Should i16 be used always if legal? For now it would force VALU 4420 // shifts. 4421 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4422 } 4423 4424 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4425 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4426 ? Ty.changeElementSize(16) 4427 : Ty.changeElementSize(32); 4428 } 4429 4430 // Answering this is somewhat tricky and depends on the specific device which 4431 // have different rates for fma or all f64 operations. 4432 // 4433 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4434 // regardless of which device (although the number of cycles differs between 4435 // devices), so it is always profitable for f64. 4436 // 4437 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4438 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4439 // which we can always do even without fused FP ops since it returns the same 4440 // result as the separate operations and since it is always full 4441 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4442 // however does not support denormals, so we do report fma as faster if we have 4443 // a fast fma device and require denormals. 4444 // 4445 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4446 EVT VT) const { 4447 VT = VT.getScalarType(); 4448 4449 switch (VT.getSimpleVT().SimpleTy) { 4450 case MVT::f32: { 4451 // If mad is not available this depends only on if f32 fma is full rate. 4452 if (!Subtarget->hasMadMacF32Insts()) 4453 return Subtarget->hasFastFMAF32(); 4454 4455 // Otherwise f32 mad is always full rate and returns the same result as 4456 // the separate operations so should be preferred over fma. 4457 // However does not support denormals. 4458 if (hasFP32Denormals(MF)) 4459 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4460 4461 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4462 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4463 } 4464 case MVT::f64: 4465 return true; 4466 case MVT::f16: 4467 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4468 default: 4469 break; 4470 } 4471 4472 return false; 4473 } 4474 4475 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4476 LLT Ty) const { 4477 switch (Ty.getScalarSizeInBits()) { 4478 case 16: 4479 return isFMAFasterThanFMulAndFAdd(MF, MVT::f16); 4480 case 32: 4481 return isFMAFasterThanFMulAndFAdd(MF, MVT::f32); 4482 case 64: 4483 return isFMAFasterThanFMulAndFAdd(MF, MVT::f64); 4484 default: 4485 break; 4486 } 4487 4488 return false; 4489 } 4490 4491 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const { 4492 if (!Ty.isScalar()) 4493 return false; 4494 4495 if (Ty.getScalarSizeInBits() == 16) 4496 return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF()); 4497 if (Ty.getScalarSizeInBits() == 32) 4498 return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF()); 4499 4500 return false; 4501 } 4502 4503 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4504 const SDNode *N) const { 4505 // TODO: Check future ftz flag 4506 // v_mad_f32/v_mac_f32 do not support denormals. 4507 EVT VT = N->getValueType(0); 4508 if (VT == MVT::f32) 4509 return Subtarget->hasMadMacF32Insts() && 4510 !hasFP32Denormals(DAG.getMachineFunction()); 4511 if (VT == MVT::f16) { 4512 return Subtarget->hasMadF16() && 4513 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4514 } 4515 4516 return false; 4517 } 4518 4519 //===----------------------------------------------------------------------===// 4520 // Custom DAG Lowering Operations 4521 //===----------------------------------------------------------------------===// 4522 4523 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4524 // wider vector type is legal. 4525 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4526 SelectionDAG &DAG) const { 4527 unsigned Opc = Op.getOpcode(); 4528 EVT VT = Op.getValueType(); 4529 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4530 4531 SDValue Lo, Hi; 4532 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4533 4534 SDLoc SL(Op); 4535 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4536 Op->getFlags()); 4537 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4538 Op->getFlags()); 4539 4540 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4541 } 4542 4543 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4544 // wider vector type is legal. 4545 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4546 SelectionDAG &DAG) const { 4547 unsigned Opc = Op.getOpcode(); 4548 EVT VT = Op.getValueType(); 4549 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4550 VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 || 4551 VT == MVT::v16f32 || VT == MVT::v32f32); 4552 4553 SDValue Lo0, Hi0; 4554 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4555 SDValue Lo1, Hi1; 4556 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4557 4558 SDLoc SL(Op); 4559 4560 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4561 Op->getFlags()); 4562 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4563 Op->getFlags()); 4564 4565 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4566 } 4567 4568 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4569 SelectionDAG &DAG) const { 4570 unsigned Opc = Op.getOpcode(); 4571 EVT VT = Op.getValueType(); 4572 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 || 4573 VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 || 4574 VT == MVT::v16f32 || VT == MVT::v32f32); 4575 4576 SDValue Lo0, Hi0; 4577 SDValue Op0 = Op.getOperand(0); 4578 std::tie(Lo0, Hi0) = Op0.getValueType().isVector() 4579 ? DAG.SplitVectorOperand(Op.getNode(), 0) 4580 : std::make_pair(Op0, Op0); 4581 SDValue Lo1, Hi1; 4582 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4583 SDValue Lo2, Hi2; 4584 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4585 4586 SDLoc SL(Op); 4587 auto ResVT = DAG.GetSplitDestVTs(VT); 4588 4589 SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2, 4590 Op->getFlags()); 4591 SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2, 4592 Op->getFlags()); 4593 4594 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4595 } 4596 4597 4598 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4599 switch (Op.getOpcode()) { 4600 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4601 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4602 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4603 case ISD::LOAD: { 4604 SDValue Result = LowerLOAD(Op, DAG); 4605 assert((!Result.getNode() || 4606 Result.getNode()->getNumValues() == 2) && 4607 "Load should return a value and a chain"); 4608 return Result; 4609 } 4610 4611 case ISD::FSIN: 4612 case ISD::FCOS: 4613 return LowerTrig(Op, DAG); 4614 case ISD::SELECT: return LowerSELECT(Op, DAG); 4615 case ISD::FDIV: return LowerFDIV(Op, DAG); 4616 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4617 case ISD::STORE: return LowerSTORE(Op, DAG); 4618 case ISD::GlobalAddress: { 4619 MachineFunction &MF = DAG.getMachineFunction(); 4620 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4621 return LowerGlobalAddress(MFI, Op, DAG); 4622 } 4623 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4624 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4625 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4626 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4627 case ISD::INSERT_SUBVECTOR: 4628 return lowerINSERT_SUBVECTOR(Op, DAG); 4629 case ISD::INSERT_VECTOR_ELT: 4630 return lowerINSERT_VECTOR_ELT(Op, DAG); 4631 case ISD::EXTRACT_VECTOR_ELT: 4632 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4633 case ISD::VECTOR_SHUFFLE: 4634 return lowerVECTOR_SHUFFLE(Op, DAG); 4635 case ISD::SCALAR_TO_VECTOR: 4636 return lowerSCALAR_TO_VECTOR(Op, DAG); 4637 case ISD::BUILD_VECTOR: 4638 return lowerBUILD_VECTOR(Op, DAG); 4639 case ISD::FP_ROUND: 4640 return lowerFP_ROUND(Op, DAG); 4641 case ISD::FPTRUNC_ROUND: { 4642 unsigned Opc; 4643 SDLoc DL(Op); 4644 4645 if (Op.getOperand(0)->getValueType(0) != MVT::f32) 4646 return SDValue(); 4647 4648 // Get the rounding mode from the last operand 4649 int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4650 if (RoundMode == (int)RoundingMode::TowardPositive) 4651 Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD; 4652 else if (RoundMode == (int)RoundingMode::TowardNegative) 4653 Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD; 4654 else 4655 return SDValue(); 4656 4657 return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0)); 4658 } 4659 case ISD::TRAP: 4660 return lowerTRAP(Op, DAG); 4661 case ISD::DEBUGTRAP: 4662 return lowerDEBUGTRAP(Op, DAG); 4663 case ISD::FABS: 4664 case ISD::FNEG: 4665 case ISD::FCANONICALIZE: 4666 case ISD::BSWAP: 4667 return splitUnaryVectorOp(Op, DAG); 4668 case ISD::FMINNUM: 4669 case ISD::FMAXNUM: 4670 return lowerFMINNUM_FMAXNUM(Op, DAG); 4671 case ISD::FMA: 4672 return splitTernaryVectorOp(Op, DAG); 4673 case ISD::FP_TO_SINT: 4674 case ISD::FP_TO_UINT: 4675 return LowerFP_TO_INT(Op, DAG); 4676 case ISD::SHL: 4677 case ISD::SRA: 4678 case ISD::SRL: 4679 case ISD::ADD: 4680 case ISD::SUB: 4681 case ISD::MUL: 4682 case ISD::SMIN: 4683 case ISD::SMAX: 4684 case ISD::UMIN: 4685 case ISD::UMAX: 4686 case ISD::FADD: 4687 case ISD::FMUL: 4688 case ISD::FMINNUM_IEEE: 4689 case ISD::FMAXNUM_IEEE: 4690 case ISD::UADDSAT: 4691 case ISD::USUBSAT: 4692 case ISD::SADDSAT: 4693 case ISD::SSUBSAT: 4694 return splitBinaryVectorOp(Op, DAG); 4695 case ISD::SMULO: 4696 case ISD::UMULO: 4697 return lowerXMULO(Op, DAG); 4698 case ISD::SMUL_LOHI: 4699 case ISD::UMUL_LOHI: 4700 return lowerXMUL_LOHI(Op, DAG); 4701 case ISD::DYNAMIC_STACKALLOC: 4702 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4703 } 4704 return SDValue(); 4705 } 4706 4707 // Used for D16: Casts the result of an instruction into the right vector, 4708 // packs values if loads return unpacked values. 4709 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4710 const SDLoc &DL, 4711 SelectionDAG &DAG, bool Unpacked) { 4712 if (!LoadVT.isVector()) 4713 return Result; 4714 4715 // Cast back to the original packed type or to a larger type that is a 4716 // multiple of 32 bit for D16. Widening the return type is a required for 4717 // legalization. 4718 EVT FittingLoadVT = LoadVT; 4719 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4720 FittingLoadVT = 4721 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4722 LoadVT.getVectorNumElements() + 1); 4723 } 4724 4725 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4726 // Truncate to v2i16/v4i16. 4727 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4728 4729 // Workaround legalizer not scalarizing truncate after vector op 4730 // legalization but not creating intermediate vector trunc. 4731 SmallVector<SDValue, 4> Elts; 4732 DAG.ExtractVectorElements(Result, Elts); 4733 for (SDValue &Elt : Elts) 4734 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4735 4736 // Pad illegal v1i16/v3fi6 to v4i16 4737 if ((LoadVT.getVectorNumElements() % 2) == 1) 4738 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4739 4740 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4741 4742 // Bitcast to original type (v2f16/v4f16). 4743 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4744 } 4745 4746 // Cast back to the original packed type. 4747 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4748 } 4749 4750 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4751 MemSDNode *M, 4752 SelectionDAG &DAG, 4753 ArrayRef<SDValue> Ops, 4754 bool IsIntrinsic) const { 4755 SDLoc DL(M); 4756 4757 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4758 EVT LoadVT = M->getValueType(0); 4759 4760 EVT EquivLoadVT = LoadVT; 4761 if (LoadVT.isVector()) { 4762 if (Unpacked) { 4763 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4764 LoadVT.getVectorNumElements()); 4765 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4766 // Widen v3f16 to legal type 4767 EquivLoadVT = 4768 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4769 LoadVT.getVectorNumElements() + 1); 4770 } 4771 } 4772 4773 // Change from v4f16/v2f16 to EquivLoadVT. 4774 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4775 4776 SDValue Load 4777 = DAG.getMemIntrinsicNode( 4778 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4779 VTList, Ops, M->getMemoryVT(), 4780 M->getMemOperand()); 4781 4782 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4783 4784 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4785 } 4786 4787 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4788 SelectionDAG &DAG, 4789 ArrayRef<SDValue> Ops) const { 4790 SDLoc DL(M); 4791 EVT LoadVT = M->getValueType(0); 4792 EVT EltType = LoadVT.getScalarType(); 4793 EVT IntVT = LoadVT.changeTypeToInteger(); 4794 4795 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4796 4797 unsigned Opc = 4798 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4799 4800 if (IsD16) { 4801 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4802 } 4803 4804 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4805 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4806 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4807 4808 if (isTypeLegal(LoadVT)) { 4809 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4810 M->getMemOperand(), DAG); 4811 } 4812 4813 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4814 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4815 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4816 M->getMemOperand(), DAG); 4817 return DAG.getMergeValues( 4818 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4819 DL); 4820 } 4821 4822 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4823 SDNode *N, SelectionDAG &DAG) { 4824 EVT VT = N->getValueType(0); 4825 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4826 unsigned CondCode = CD->getZExtValue(); 4827 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4828 return DAG.getUNDEF(VT); 4829 4830 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4831 4832 SDValue LHS = N->getOperand(1); 4833 SDValue RHS = N->getOperand(2); 4834 4835 SDLoc DL(N); 4836 4837 EVT CmpVT = LHS.getValueType(); 4838 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4839 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4840 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4841 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4842 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4843 } 4844 4845 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4846 4847 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4848 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4849 4850 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4851 DAG.getCondCode(CCOpcode)); 4852 if (VT.bitsEq(CCVT)) 4853 return SetCC; 4854 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4855 } 4856 4857 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4858 SDNode *N, SelectionDAG &DAG) { 4859 EVT VT = N->getValueType(0); 4860 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4861 4862 unsigned CondCode = CD->getZExtValue(); 4863 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4864 return DAG.getUNDEF(VT); 4865 4866 SDValue Src0 = N->getOperand(1); 4867 SDValue Src1 = N->getOperand(2); 4868 EVT CmpVT = Src0.getValueType(); 4869 SDLoc SL(N); 4870 4871 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4872 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4873 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4874 } 4875 4876 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4877 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4878 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4879 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4880 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4881 Src1, DAG.getCondCode(CCOpcode)); 4882 if (VT.bitsEq(CCVT)) 4883 return SetCC; 4884 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4885 } 4886 4887 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4888 SelectionDAG &DAG) { 4889 EVT VT = N->getValueType(0); 4890 SDValue Src = N->getOperand(1); 4891 SDLoc SL(N); 4892 4893 if (Src.getOpcode() == ISD::SETCC) { 4894 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4895 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4896 Src.getOperand(1), Src.getOperand(2)); 4897 } 4898 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4899 // (ballot 0) -> 0 4900 if (Arg->isZero()) 4901 return DAG.getConstant(0, SL, VT); 4902 4903 // (ballot 1) -> EXEC/EXEC_LO 4904 if (Arg->isOne()) { 4905 Register Exec; 4906 if (VT.getScalarSizeInBits() == 32) 4907 Exec = AMDGPU::EXEC_LO; 4908 else if (VT.getScalarSizeInBits() == 64) 4909 Exec = AMDGPU::EXEC; 4910 else 4911 return SDValue(); 4912 4913 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4914 } 4915 } 4916 4917 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4918 // ISD::SETNE) 4919 return DAG.getNode( 4920 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4921 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4922 } 4923 4924 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4925 SmallVectorImpl<SDValue> &Results, 4926 SelectionDAG &DAG) const { 4927 switch (N->getOpcode()) { 4928 case ISD::INSERT_VECTOR_ELT: { 4929 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4930 Results.push_back(Res); 4931 return; 4932 } 4933 case ISD::EXTRACT_VECTOR_ELT: { 4934 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4935 Results.push_back(Res); 4936 return; 4937 } 4938 case ISD::INTRINSIC_WO_CHAIN: { 4939 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4940 switch (IID) { 4941 case Intrinsic::amdgcn_cvt_pkrtz: { 4942 SDValue Src0 = N->getOperand(1); 4943 SDValue Src1 = N->getOperand(2); 4944 SDLoc SL(N); 4945 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4946 Src0, Src1); 4947 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4948 return; 4949 } 4950 case Intrinsic::amdgcn_cvt_pknorm_i16: 4951 case Intrinsic::amdgcn_cvt_pknorm_u16: 4952 case Intrinsic::amdgcn_cvt_pk_i16: 4953 case Intrinsic::amdgcn_cvt_pk_u16: { 4954 SDValue Src0 = N->getOperand(1); 4955 SDValue Src1 = N->getOperand(2); 4956 SDLoc SL(N); 4957 unsigned Opcode; 4958 4959 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4960 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4961 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4962 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4963 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4964 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4965 else 4966 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4967 4968 EVT VT = N->getValueType(0); 4969 if (isTypeLegal(VT)) 4970 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4971 else { 4972 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4973 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4974 } 4975 return; 4976 } 4977 } 4978 break; 4979 } 4980 case ISD::INTRINSIC_W_CHAIN: { 4981 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4982 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4983 // FIXME: Hacky 4984 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4985 Results.push_back(Res.getOperand(I)); 4986 } 4987 } else { 4988 Results.push_back(Res); 4989 Results.push_back(Res.getValue(1)); 4990 } 4991 return; 4992 } 4993 4994 break; 4995 } 4996 case ISD::SELECT: { 4997 SDLoc SL(N); 4998 EVT VT = N->getValueType(0); 4999 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 5000 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 5001 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 5002 5003 EVT SelectVT = NewVT; 5004 if (NewVT.bitsLT(MVT::i32)) { 5005 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 5006 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 5007 SelectVT = MVT::i32; 5008 } 5009 5010 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 5011 N->getOperand(0), LHS, RHS); 5012 5013 if (NewVT != SelectVT) 5014 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 5015 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 5016 return; 5017 } 5018 case ISD::FNEG: { 5019 if (N->getValueType(0) != MVT::v2f16) 5020 break; 5021 5022 SDLoc SL(N); 5023 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5024 5025 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 5026 BC, 5027 DAG.getConstant(0x80008000, SL, MVT::i32)); 5028 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5029 return; 5030 } 5031 case ISD::FABS: { 5032 if (N->getValueType(0) != MVT::v2f16) 5033 break; 5034 5035 SDLoc SL(N); 5036 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5037 5038 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 5039 BC, 5040 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 5041 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5042 return; 5043 } 5044 default: 5045 break; 5046 } 5047 } 5048 5049 /// Helper function for LowerBRCOND 5050 static SDNode *findUser(SDValue Value, unsigned Opcode) { 5051 5052 SDNode *Parent = Value.getNode(); 5053 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 5054 I != E; ++I) { 5055 5056 if (I.getUse().get() != Value) 5057 continue; 5058 5059 if (I->getOpcode() == Opcode) 5060 return *I; 5061 } 5062 return nullptr; 5063 } 5064 5065 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 5066 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 5067 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 5068 case Intrinsic::amdgcn_if: 5069 return AMDGPUISD::IF; 5070 case Intrinsic::amdgcn_else: 5071 return AMDGPUISD::ELSE; 5072 case Intrinsic::amdgcn_loop: 5073 return AMDGPUISD::LOOP; 5074 case Intrinsic::amdgcn_end_cf: 5075 llvm_unreachable("should not occur"); 5076 default: 5077 return 0; 5078 } 5079 } 5080 5081 // break, if_break, else_break are all only used as inputs to loop, not 5082 // directly as branch conditions. 5083 return 0; 5084 } 5085 5086 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 5087 const Triple &TT = getTargetMachine().getTargetTriple(); 5088 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5089 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5090 AMDGPU::shouldEmitConstantsToTextSection(TT); 5091 } 5092 5093 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 5094 // FIXME: Either avoid relying on address space here or change the default 5095 // address space for functions to avoid the explicit check. 5096 return (GV->getValueType()->isFunctionTy() || 5097 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 5098 !shouldEmitFixup(GV) && 5099 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 5100 } 5101 5102 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 5103 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 5104 } 5105 5106 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 5107 if (!GV->hasExternalLinkage()) 5108 return true; 5109 5110 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5111 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5112 } 5113 5114 /// This transforms the control flow intrinsics to get the branch destination as 5115 /// last parameter, also switches branch target with BR if the need arise 5116 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5117 SelectionDAG &DAG) const { 5118 SDLoc DL(BRCOND); 5119 5120 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5121 SDValue Target = BRCOND.getOperand(2); 5122 SDNode *BR = nullptr; 5123 SDNode *SetCC = nullptr; 5124 5125 if (Intr->getOpcode() == ISD::SETCC) { 5126 // As long as we negate the condition everything is fine 5127 SetCC = Intr; 5128 Intr = SetCC->getOperand(0).getNode(); 5129 5130 } else { 5131 // Get the target from BR if we don't negate the condition 5132 BR = findUser(BRCOND, ISD::BR); 5133 assert(BR && "brcond missing unconditional branch user"); 5134 Target = BR->getOperand(1); 5135 } 5136 5137 unsigned CFNode = isCFIntrinsic(Intr); 5138 if (CFNode == 0) { 5139 // This is a uniform branch so we don't need to legalize. 5140 return BRCOND; 5141 } 5142 5143 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5144 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5145 5146 assert(!SetCC || 5147 (SetCC->getConstantOperandVal(1) == 1 && 5148 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5149 ISD::SETNE)); 5150 5151 // operands of the new intrinsic call 5152 SmallVector<SDValue, 4> Ops; 5153 if (HaveChain) 5154 Ops.push_back(BRCOND.getOperand(0)); 5155 5156 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5157 Ops.push_back(Target); 5158 5159 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5160 5161 // build the new intrinsic call 5162 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5163 5164 if (!HaveChain) { 5165 SDValue Ops[] = { 5166 SDValue(Result, 0), 5167 BRCOND.getOperand(0) 5168 }; 5169 5170 Result = DAG.getMergeValues(Ops, DL).getNode(); 5171 } 5172 5173 if (BR) { 5174 // Give the branch instruction our target 5175 SDValue Ops[] = { 5176 BR->getOperand(0), 5177 BRCOND.getOperand(2) 5178 }; 5179 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5180 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5181 } 5182 5183 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5184 5185 // Copy the intrinsic results to registers 5186 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5187 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5188 if (!CopyToReg) 5189 continue; 5190 5191 Chain = DAG.getCopyToReg( 5192 Chain, DL, 5193 CopyToReg->getOperand(1), 5194 SDValue(Result, i - 1), 5195 SDValue()); 5196 5197 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5198 } 5199 5200 // Remove the old intrinsic from the chain 5201 DAG.ReplaceAllUsesOfValueWith( 5202 SDValue(Intr, Intr->getNumValues() - 1), 5203 Intr->getOperand(0)); 5204 5205 return Chain; 5206 } 5207 5208 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5209 SelectionDAG &DAG) const { 5210 MVT VT = Op.getSimpleValueType(); 5211 SDLoc DL(Op); 5212 // Checking the depth 5213 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5214 return DAG.getConstant(0, DL, VT); 5215 5216 MachineFunction &MF = DAG.getMachineFunction(); 5217 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5218 // Check for kernel and shader functions 5219 if (Info->isEntryFunction()) 5220 return DAG.getConstant(0, DL, VT); 5221 5222 MachineFrameInfo &MFI = MF.getFrameInfo(); 5223 // There is a call to @llvm.returnaddress in this function 5224 MFI.setReturnAddressIsTaken(true); 5225 5226 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5227 // Get the return address reg and mark it as an implicit live-in 5228 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5229 5230 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5231 } 5232 5233 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5234 SDValue Op, 5235 const SDLoc &DL, 5236 EVT VT) const { 5237 return Op.getValueType().bitsLE(VT) ? 5238 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5239 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5240 DAG.getTargetConstant(0, DL, MVT::i32)); 5241 } 5242 5243 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5244 assert(Op.getValueType() == MVT::f16 && 5245 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5246 5247 SDValue Src = Op.getOperand(0); 5248 EVT SrcVT = Src.getValueType(); 5249 if (SrcVT != MVT::f64) 5250 return Op; 5251 5252 SDLoc DL(Op); 5253 5254 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5255 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5256 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5257 } 5258 5259 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5260 SelectionDAG &DAG) const { 5261 EVT VT = Op.getValueType(); 5262 const MachineFunction &MF = DAG.getMachineFunction(); 5263 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5264 bool IsIEEEMode = Info->getMode().IEEE; 5265 5266 // FIXME: Assert during selection that this is only selected for 5267 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5268 // mode functions, but this happens to be OK since it's only done in cases 5269 // where there is known no sNaN. 5270 if (IsIEEEMode) 5271 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5272 5273 if (VT == MVT::v4f16 || VT == MVT::v8f16) 5274 return splitBinaryVectorOp(Op, DAG); 5275 return Op; 5276 } 5277 5278 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5279 EVT VT = Op.getValueType(); 5280 SDLoc SL(Op); 5281 SDValue LHS = Op.getOperand(0); 5282 SDValue RHS = Op.getOperand(1); 5283 bool isSigned = Op.getOpcode() == ISD::SMULO; 5284 5285 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5286 const APInt &C = RHSC->getAPIntValue(); 5287 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5288 if (C.isPowerOf2()) { 5289 // smulo(x, signed_min) is same as umulo(x, signed_min). 5290 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5291 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5292 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5293 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5294 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5295 SL, VT, Result, ShiftAmt), 5296 LHS, ISD::SETNE); 5297 return DAG.getMergeValues({ Result, Overflow }, SL); 5298 } 5299 } 5300 5301 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5302 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5303 SL, VT, LHS, RHS); 5304 5305 SDValue Sign = isSigned 5306 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5307 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5308 : DAG.getConstant(0, SL, VT); 5309 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5310 5311 return DAG.getMergeValues({ Result, Overflow }, SL); 5312 } 5313 5314 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const { 5315 if (Op->isDivergent()) { 5316 // Select to V_MAD_[IU]64_[IU]32. 5317 return Op; 5318 } 5319 if (Subtarget->hasSMulHi()) { 5320 // Expand to S_MUL_I32 + S_MUL_HI_[IU]32. 5321 return SDValue(); 5322 } 5323 // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to 5324 // calculate the high part, so we might as well do the whole thing with 5325 // V_MAD_[IU]64_[IU]32. 5326 return Op; 5327 } 5328 5329 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5330 if (!Subtarget->isTrapHandlerEnabled() || 5331 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5332 return lowerTrapEndpgm(Op, DAG); 5333 5334 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5335 switch (*HsaAbiVer) { 5336 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5337 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5338 return lowerTrapHsaQueuePtr(Op, DAG); 5339 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5340 case ELF::ELFABIVERSION_AMDGPU_HSA_V5: 5341 return Subtarget->supportsGetDoorbellID() ? 5342 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5343 } 5344 } 5345 5346 llvm_unreachable("Unknown trap handler"); 5347 } 5348 5349 SDValue SITargetLowering::lowerTrapEndpgm( 5350 SDValue Op, SelectionDAG &DAG) const { 5351 SDLoc SL(Op); 5352 SDValue Chain = Op.getOperand(0); 5353 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5354 } 5355 5356 SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT, 5357 const SDLoc &DL, Align Alignment, ImplicitParameter Param) const { 5358 MachineFunction &MF = DAG.getMachineFunction(); 5359 uint64_t Offset = getImplicitParameterOffset(MF, Param); 5360 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset); 5361 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5362 return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment, 5363 MachineMemOperand::MODereferenceable | 5364 MachineMemOperand::MOInvariant); 5365 } 5366 5367 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5368 SDValue Op, SelectionDAG &DAG) const { 5369 SDLoc SL(Op); 5370 SDValue Chain = Op.getOperand(0); 5371 5372 SDValue QueuePtr; 5373 // For code object version 5, QueuePtr is passed through implicit kernarg. 5374 if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) { 5375 QueuePtr = 5376 loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR); 5377 } else { 5378 MachineFunction &MF = DAG.getMachineFunction(); 5379 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5380 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5381 5382 if (UserSGPR == AMDGPU::NoRegister) { 5383 // We probably are in a function incorrectly marked with 5384 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the 5385 // trap, so just use a null pointer. 5386 QueuePtr = DAG.getConstant(0, SL, MVT::i64); 5387 } else { 5388 QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR, 5389 MVT::i64); 5390 } 5391 } 5392 5393 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5394 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5395 QueuePtr, SDValue()); 5396 5397 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5398 SDValue Ops[] = { 5399 ToReg, 5400 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5401 SGPR01, 5402 ToReg.getValue(1) 5403 }; 5404 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5405 } 5406 5407 SDValue SITargetLowering::lowerTrapHsa( 5408 SDValue Op, SelectionDAG &DAG) const { 5409 SDLoc SL(Op); 5410 SDValue Chain = Op.getOperand(0); 5411 5412 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5413 SDValue Ops[] = { 5414 Chain, 5415 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5416 }; 5417 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5418 } 5419 5420 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5421 SDLoc SL(Op); 5422 SDValue Chain = Op.getOperand(0); 5423 MachineFunction &MF = DAG.getMachineFunction(); 5424 5425 if (!Subtarget->isTrapHandlerEnabled() || 5426 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5427 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5428 "debugtrap handler not supported", 5429 Op.getDebugLoc(), 5430 DS_Warning); 5431 LLVMContext &Ctx = MF.getFunction().getContext(); 5432 Ctx.diagnose(NoTrap); 5433 return Chain; 5434 } 5435 5436 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5437 SDValue Ops[] = { 5438 Chain, 5439 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5440 }; 5441 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5442 } 5443 5444 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5445 SelectionDAG &DAG) const { 5446 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5447 if (Subtarget->hasApertureRegs()) { 5448 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5449 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5450 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5451 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5452 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5453 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5454 unsigned Encoding = 5455 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5456 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5457 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5458 5459 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5460 SDValue ApertureReg = SDValue( 5461 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5462 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5463 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5464 } 5465 5466 // For code object version 5, private_base and shared_base are passed through 5467 // implicit kernargs. 5468 if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) { 5469 ImplicitParameter Param = 5470 (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE; 5471 return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param); 5472 } 5473 5474 MachineFunction &MF = DAG.getMachineFunction(); 5475 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5476 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5477 if (UserSGPR == AMDGPU::NoRegister) { 5478 // We probably are in a function incorrectly marked with 5479 // amdgpu-no-queue-ptr. This is undefined. 5480 return DAG.getUNDEF(MVT::i32); 5481 } 5482 5483 SDValue QueuePtr = CreateLiveInRegister( 5484 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5485 5486 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5487 // private_segment_aperture_base_hi. 5488 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5489 5490 SDValue Ptr = 5491 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5492 5493 // TODO: Use custom target PseudoSourceValue. 5494 // TODO: We should use the value from the IR intrinsic call, but it might not 5495 // be available and how do we get it? 5496 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5497 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5498 commonAlignment(Align(64), StructOffset), 5499 MachineMemOperand::MODereferenceable | 5500 MachineMemOperand::MOInvariant); 5501 } 5502 5503 /// Return true if the value is a known valid address, such that a null check is 5504 /// not necessary. 5505 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG, 5506 const AMDGPUTargetMachine &TM, unsigned AddrSpace) { 5507 if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) || 5508 isa<BasicBlockSDNode>(Val)) 5509 return true; 5510 5511 if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val)) 5512 return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace); 5513 5514 // TODO: Search through arithmetic, handle arguments and loads 5515 // marked nonnull. 5516 return false; 5517 } 5518 5519 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5520 SelectionDAG &DAG) const { 5521 SDLoc SL(Op); 5522 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5523 5524 SDValue Src = ASC->getOperand(0); 5525 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5526 unsigned SrcAS = ASC->getSrcAddressSpace(); 5527 5528 const AMDGPUTargetMachine &TM = 5529 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5530 5531 // flat -> local/private 5532 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) { 5533 unsigned DestAS = ASC->getDestAddressSpace(); 5534 5535 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5536 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5537 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5538 5539 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5540 return Ptr; 5541 5542 unsigned NullVal = TM.getNullPointerValue(DestAS); 5543 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5544 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5545 5546 return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr, 5547 SegmentNullPtr); 5548 } 5549 } 5550 5551 // local/private -> flat 5552 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5553 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5554 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5555 5556 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5557 SDValue CvtPtr = 5558 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5559 CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr); 5560 5561 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5562 return CvtPtr; 5563 5564 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5565 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5566 5567 SDValue NonNull 5568 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5569 5570 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr, 5571 FlatNullPtr); 5572 } 5573 } 5574 5575 if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5576 Op.getValueType() == MVT::i64) { 5577 const SIMachineFunctionInfo *Info = 5578 DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>(); 5579 SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32); 5580 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi); 5581 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 5582 } 5583 5584 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5585 Src.getValueType() == MVT::i64) 5586 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5587 5588 // global <-> flat are no-ops and never emitted. 5589 5590 const MachineFunction &MF = DAG.getMachineFunction(); 5591 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5592 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5593 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5594 5595 return DAG.getUNDEF(ASC->getValueType(0)); 5596 } 5597 5598 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5599 // the small vector and inserting them into the big vector. That is better than 5600 // the default expansion of doing it via a stack slot. Even though the use of 5601 // the stack slot would be optimized away afterwards, the stack slot itself 5602 // remains. 5603 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5604 SelectionDAG &DAG) const { 5605 SDValue Vec = Op.getOperand(0); 5606 SDValue Ins = Op.getOperand(1); 5607 SDValue Idx = Op.getOperand(2); 5608 EVT VecVT = Vec.getValueType(); 5609 EVT InsVT = Ins.getValueType(); 5610 EVT EltVT = VecVT.getVectorElementType(); 5611 unsigned InsNumElts = InsVT.getVectorNumElements(); 5612 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5613 SDLoc SL(Op); 5614 5615 for (unsigned I = 0; I != InsNumElts; ++I) { 5616 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5617 DAG.getConstant(I, SL, MVT::i32)); 5618 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5619 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5620 } 5621 return Vec; 5622 } 5623 5624 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5625 SelectionDAG &DAG) const { 5626 SDValue Vec = Op.getOperand(0); 5627 SDValue InsVal = Op.getOperand(1); 5628 SDValue Idx = Op.getOperand(2); 5629 EVT VecVT = Vec.getValueType(); 5630 EVT EltVT = VecVT.getVectorElementType(); 5631 unsigned VecSize = VecVT.getSizeInBits(); 5632 unsigned EltSize = EltVT.getSizeInBits(); 5633 SDLoc SL(Op); 5634 5635 // Specially handle the case of v4i16 with static indexing. 5636 unsigned NumElts = VecVT.getVectorNumElements(); 5637 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5638 if (NumElts == 4 && EltSize == 16 && KIdx) { 5639 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5640 5641 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5642 DAG.getConstant(0, SL, MVT::i32)); 5643 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5644 DAG.getConstant(1, SL, MVT::i32)); 5645 5646 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5647 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5648 5649 unsigned Idx = KIdx->getZExtValue(); 5650 bool InsertLo = Idx < 2; 5651 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5652 InsertLo ? LoVec : HiVec, 5653 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5654 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5655 5656 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5657 5658 SDValue Concat = InsertLo ? 5659 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5660 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5661 5662 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5663 } 5664 5665 // Static indexing does not lower to stack access, and hence there is no need 5666 // for special custom lowering to avoid stack access. 5667 if (isa<ConstantSDNode>(Idx)) 5668 return SDValue(); 5669 5670 // Avoid stack access for dynamic indexing by custom lowering to 5671 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5672 5673 assert(VecSize <= 64 && "Expected target vector size to be <= 64 bits"); 5674 5675 MVT IntVT = MVT::getIntegerVT(VecSize); 5676 5677 // Convert vector index to bit-index and get the required bit mask. 5678 assert(isPowerOf2_32(EltSize)); 5679 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5680 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5681 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5682 DAG.getConstant(0xffff, SL, IntVT), 5683 ScaledIdx); 5684 5685 // 1. Create a congruent vector with the target value in each element. 5686 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5687 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5688 5689 // 2. Mask off all other indicies except the required index within (1). 5690 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5691 5692 // 3. Mask off the required index within the target vector. 5693 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5694 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5695 DAG.getNOT(SL, BFM, IntVT), BCVec); 5696 5697 // 4. Get (2) and (3) ORed into the target vector. 5698 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5699 5700 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5701 } 5702 5703 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5704 SelectionDAG &DAG) const { 5705 SDLoc SL(Op); 5706 5707 EVT ResultVT = Op.getValueType(); 5708 SDValue Vec = Op.getOperand(0); 5709 SDValue Idx = Op.getOperand(1); 5710 EVT VecVT = Vec.getValueType(); 5711 unsigned VecSize = VecVT.getSizeInBits(); 5712 EVT EltVT = VecVT.getVectorElementType(); 5713 5714 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5715 5716 // Make sure we do any optimizations that will make it easier to fold 5717 // source modifiers before obscuring it with bit operations. 5718 5719 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5720 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5721 return Combined; 5722 5723 if (VecSize == 128) { 5724 SDValue Lo, Hi; 5725 EVT LoVT, HiVT; 5726 SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec); 5727 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5728 Lo = 5729 DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5730 V2, DAG.getConstant(0, SL, MVT::i32))); 5731 Hi = 5732 DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5733 V2, DAG.getConstant(1, SL, MVT::i32))); 5734 EVT IdxVT = Idx.getValueType(); 5735 unsigned NElem = VecVT.getVectorNumElements(); 5736 assert(isPowerOf2_32(NElem)); 5737 SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT); 5738 SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask); 5739 SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT); 5740 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx); 5741 } 5742 5743 assert(VecSize <= 64); 5744 5745 MVT IntVT = MVT::getIntegerVT(VecSize); 5746 5747 // If Vec is just a SCALAR_TO_VECTOR, then use the scalar integer directly. 5748 SDValue VecBC = peekThroughBitcasts(Vec); 5749 if (VecBC.getOpcode() == ISD::SCALAR_TO_VECTOR) { 5750 SDValue Src = VecBC.getOperand(0); 5751 Src = DAG.getBitcast(Src.getValueType().changeTypeToInteger(), Src); 5752 Vec = DAG.getAnyExtOrTrunc(Src, SL, IntVT); 5753 } 5754 5755 unsigned EltSize = EltVT.getSizeInBits(); 5756 assert(isPowerOf2_32(EltSize)); 5757 5758 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5759 5760 // Convert vector index to bit-index (* EltSize) 5761 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5762 5763 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5764 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5765 5766 if (ResultVT == MVT::f16) { 5767 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5768 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5769 } 5770 5771 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5772 } 5773 5774 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5775 assert(Elt % 2 == 0); 5776 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5777 } 5778 5779 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5780 SelectionDAG &DAG) const { 5781 SDLoc SL(Op); 5782 EVT ResultVT = Op.getValueType(); 5783 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5784 5785 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5786 EVT EltVT = PackVT.getVectorElementType(); 5787 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5788 5789 // vector_shuffle <0,1,6,7> lhs, rhs 5790 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5791 // 5792 // vector_shuffle <6,7,2,3> lhs, rhs 5793 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5794 // 5795 // vector_shuffle <6,7,0,1> lhs, rhs 5796 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5797 5798 // Avoid scalarizing when both halves are reading from consecutive elements. 5799 SmallVector<SDValue, 4> Pieces; 5800 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5801 if (elementPairIsContiguous(SVN->getMask(), I)) { 5802 const int Idx = SVN->getMaskElt(I); 5803 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5804 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5805 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5806 PackVT, SVN->getOperand(VecIdx), 5807 DAG.getConstant(EltIdx, SL, MVT::i32)); 5808 Pieces.push_back(SubVec); 5809 } else { 5810 const int Idx0 = SVN->getMaskElt(I); 5811 const int Idx1 = SVN->getMaskElt(I + 1); 5812 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5813 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5814 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5815 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5816 5817 SDValue Vec0 = SVN->getOperand(VecIdx0); 5818 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5819 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5820 5821 SDValue Vec1 = SVN->getOperand(VecIdx1); 5822 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5823 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5824 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5825 } 5826 } 5827 5828 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5829 } 5830 5831 SDValue SITargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op, 5832 SelectionDAG &DAG) const { 5833 SDValue SVal = Op.getOperand(0); 5834 EVT ResultVT = Op.getValueType(); 5835 EVT SValVT = SVal.getValueType(); 5836 SDValue UndefVal = DAG.getUNDEF(SValVT); 5837 SDLoc SL(Op); 5838 5839 SmallVector<SDValue, 8> VElts; 5840 VElts.push_back(SVal); 5841 for (int I = 1, E = ResultVT.getVectorNumElements(); I < E; ++I) 5842 VElts.push_back(UndefVal); 5843 5844 return DAG.getBuildVector(ResultVT, SL, VElts); 5845 } 5846 5847 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5848 SelectionDAG &DAG) const { 5849 SDLoc SL(Op); 5850 EVT VT = Op.getValueType(); 5851 5852 if (VT == MVT::v4i16 || VT == MVT::v4f16 || 5853 VT == MVT::v8i16 || VT == MVT::v8f16) { 5854 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 5855 VT.getVectorNumElements() / 2); 5856 MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits()); 5857 5858 // Turn into pair of packed build_vectors. 5859 // TODO: Special case for constants that can be materialized with s_mov_b64. 5860 SmallVector<SDValue, 4> LoOps, HiOps; 5861 for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) { 5862 LoOps.push_back(Op.getOperand(I)); 5863 HiOps.push_back(Op.getOperand(I + E)); 5864 } 5865 SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps); 5866 SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps); 5867 5868 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo); 5869 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi); 5870 5871 SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL, 5872 { CastLo, CastHi }); 5873 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5874 } 5875 5876 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5877 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5878 5879 SDValue Lo = Op.getOperand(0); 5880 SDValue Hi = Op.getOperand(1); 5881 5882 // Avoid adding defined bits with the zero_extend. 5883 if (Hi.isUndef()) { 5884 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5885 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5886 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5887 } 5888 5889 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5890 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5891 5892 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5893 DAG.getConstant(16, SL, MVT::i32)); 5894 if (Lo.isUndef()) 5895 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5896 5897 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5898 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5899 5900 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5901 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5902 } 5903 5904 bool 5905 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5906 // We can fold offsets for anything that doesn't require a GOT relocation. 5907 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5908 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5909 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5910 !shouldEmitGOTReloc(GA->getGlobal()); 5911 } 5912 5913 static SDValue 5914 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5915 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5916 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5917 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5918 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5919 // lowered to the following code sequence: 5920 // 5921 // For constant address space: 5922 // s_getpc_b64 s[0:1] 5923 // s_add_u32 s0, s0, $symbol 5924 // s_addc_u32 s1, s1, 0 5925 // 5926 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5927 // a fixup or relocation is emitted to replace $symbol with a literal 5928 // constant, which is a pc-relative offset from the encoding of the $symbol 5929 // operand to the global variable. 5930 // 5931 // For global address space: 5932 // s_getpc_b64 s[0:1] 5933 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5934 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5935 // 5936 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5937 // fixups or relocations are emitted to replace $symbol@*@lo and 5938 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5939 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5940 // operand to the global variable. 5941 // 5942 // What we want here is an offset from the value returned by s_getpc 5943 // (which is the address of the s_add_u32 instruction) to the global 5944 // variable, but since the encoding of $symbol starts 4 bytes after the start 5945 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5946 // small. This requires us to add 4 to the global variable offset in order to 5947 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5948 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5949 // instruction. 5950 SDValue PtrLo = 5951 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5952 SDValue PtrHi; 5953 if (GAFlags == SIInstrInfo::MO_NONE) { 5954 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5955 } else { 5956 PtrHi = 5957 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5958 } 5959 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5960 } 5961 5962 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5963 SDValue Op, 5964 SelectionDAG &DAG) const { 5965 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5966 SDLoc DL(GSD); 5967 EVT PtrVT = Op.getValueType(); 5968 5969 const GlobalValue *GV = GSD->getGlobal(); 5970 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5971 shouldUseLDSConstAddress(GV)) || 5972 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5973 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5974 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5975 GV->hasExternalLinkage()) { 5976 Type *Ty = GV->getValueType(); 5977 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5978 // zero-sized type in other languages to declare the dynamic shared 5979 // memory which size is not known at the compile time. They will be 5980 // allocated by the runtime and placed directly after the static 5981 // allocated ones. They all share the same offset. 5982 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5983 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5984 // Adjust alignment for that dynamic shared memory array. 5985 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5986 return SDValue( 5987 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5988 } 5989 } 5990 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5991 } 5992 5993 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5994 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5995 SIInstrInfo::MO_ABS32_LO); 5996 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5997 } 5998 5999 if (shouldEmitFixup(GV)) 6000 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 6001 else if (shouldEmitPCReloc(GV)) 6002 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 6003 SIInstrInfo::MO_REL32); 6004 6005 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 6006 SIInstrInfo::MO_GOTPCREL32); 6007 6008 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 6009 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 6010 const DataLayout &DataLayout = DAG.getDataLayout(); 6011 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 6012 MachinePointerInfo PtrInfo 6013 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 6014 6015 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 6016 MachineMemOperand::MODereferenceable | 6017 MachineMemOperand::MOInvariant); 6018 } 6019 6020 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 6021 const SDLoc &DL, SDValue V) const { 6022 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 6023 // the destination register. 6024 // 6025 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 6026 // so we will end up with redundant moves to m0. 6027 // 6028 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 6029 6030 // A Null SDValue creates a glue result. 6031 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 6032 V, Chain); 6033 return SDValue(M0, 0); 6034 } 6035 6036 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 6037 SDValue Op, 6038 MVT VT, 6039 unsigned Offset) const { 6040 SDLoc SL(Op); 6041 SDValue Param = lowerKernargMemParameter( 6042 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 6043 // The local size values will have the hi 16-bits as zero. 6044 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 6045 DAG.getValueType(VT)); 6046 } 6047 6048 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6049 EVT VT) { 6050 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6051 "non-hsa intrinsic with hsa target", 6052 DL.getDebugLoc()); 6053 DAG.getContext()->diagnose(BadIntrin); 6054 return DAG.getUNDEF(VT); 6055 } 6056 6057 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6058 EVT VT) { 6059 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6060 "intrinsic not supported on subtarget", 6061 DL.getDebugLoc()); 6062 DAG.getContext()->diagnose(BadIntrin); 6063 return DAG.getUNDEF(VT); 6064 } 6065 6066 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 6067 ArrayRef<SDValue> Elts) { 6068 assert(!Elts.empty()); 6069 MVT Type; 6070 unsigned NumElts = Elts.size(); 6071 6072 if (NumElts <= 8) { 6073 Type = MVT::getVectorVT(MVT::f32, NumElts); 6074 } else { 6075 assert(Elts.size() <= 16); 6076 Type = MVT::v16f32; 6077 NumElts = 16; 6078 } 6079 6080 SmallVector<SDValue, 16> VecElts(NumElts); 6081 for (unsigned i = 0; i < Elts.size(); ++i) { 6082 SDValue Elt = Elts[i]; 6083 if (Elt.getValueType() != MVT::f32) 6084 Elt = DAG.getBitcast(MVT::f32, Elt); 6085 VecElts[i] = Elt; 6086 } 6087 for (unsigned i = Elts.size(); i < NumElts; ++i) 6088 VecElts[i] = DAG.getUNDEF(MVT::f32); 6089 6090 if (NumElts == 1) 6091 return VecElts[0]; 6092 return DAG.getBuildVector(Type, DL, VecElts); 6093 } 6094 6095 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 6096 SDValue Src, int ExtraElts) { 6097 EVT SrcVT = Src.getValueType(); 6098 6099 SmallVector<SDValue, 8> Elts; 6100 6101 if (SrcVT.isVector()) 6102 DAG.ExtractVectorElements(Src, Elts); 6103 else 6104 Elts.push_back(Src); 6105 6106 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 6107 while (ExtraElts--) 6108 Elts.push_back(Undef); 6109 6110 return DAG.getBuildVector(CastVT, DL, Elts); 6111 } 6112 6113 // Re-construct the required return value for a image load intrinsic. 6114 // This is more complicated due to the optional use TexFailCtrl which means the required 6115 // return type is an aggregate 6116 static SDValue constructRetValue(SelectionDAG &DAG, 6117 MachineSDNode *Result, 6118 ArrayRef<EVT> ResultTypes, 6119 bool IsTexFail, bool Unpacked, bool IsD16, 6120 int DMaskPop, int NumVDataDwords, 6121 const SDLoc &DL) { 6122 // Determine the required return type. This is the same regardless of IsTexFail flag 6123 EVT ReqRetVT = ResultTypes[0]; 6124 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 6125 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6126 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 6127 6128 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6129 DMaskPop : (DMaskPop + 1) / 2; 6130 6131 MVT DataDwordVT = NumDataDwords == 1 ? 6132 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 6133 6134 MVT MaskPopVT = MaskPopDwords == 1 ? 6135 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 6136 6137 SDValue Data(Result, 0); 6138 SDValue TexFail; 6139 6140 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 6141 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 6142 if (MaskPopVT.isVector()) { 6143 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 6144 SDValue(Result, 0), ZeroIdx); 6145 } else { 6146 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 6147 SDValue(Result, 0), ZeroIdx); 6148 } 6149 } 6150 6151 if (DataDwordVT.isVector()) 6152 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 6153 NumDataDwords - MaskPopDwords); 6154 6155 if (IsD16) 6156 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 6157 6158 EVT LegalReqRetVT = ReqRetVT; 6159 if (!ReqRetVT.isVector()) { 6160 if (!Data.getValueType().isInteger()) 6161 Data = DAG.getNode(ISD::BITCAST, DL, 6162 Data.getValueType().changeTypeToInteger(), Data); 6163 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 6164 } else { 6165 // We need to widen the return vector to a legal type 6166 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 6167 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 6168 LegalReqRetVT = 6169 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 6170 ReqRetVT.getVectorNumElements() + 1); 6171 } 6172 } 6173 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 6174 6175 if (IsTexFail) { 6176 TexFail = 6177 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 6178 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 6179 6180 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 6181 } 6182 6183 if (Result->getNumValues() == 1) 6184 return Data; 6185 6186 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 6187 } 6188 6189 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 6190 SDValue *LWE, bool &IsTexFail) { 6191 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 6192 6193 uint64_t Value = TexFailCtrlConst->getZExtValue(); 6194 if (Value) { 6195 IsTexFail = true; 6196 } 6197 6198 SDLoc DL(TexFailCtrlConst); 6199 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 6200 Value &= ~(uint64_t)0x1; 6201 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 6202 Value &= ~(uint64_t)0x2; 6203 6204 return Value == 0; 6205 } 6206 6207 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op, 6208 MVT PackVectorVT, 6209 SmallVectorImpl<SDValue> &PackedAddrs, 6210 unsigned DimIdx, unsigned EndIdx, 6211 unsigned NumGradients) { 6212 SDLoc DL(Op); 6213 for (unsigned I = DimIdx; I < EndIdx; I++) { 6214 SDValue Addr = Op.getOperand(I); 6215 6216 // Gradients are packed with undef for each coordinate. 6217 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 6218 // 1D: undef,dx/dh; undef,dx/dv 6219 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 6220 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 6221 if (((I + 1) >= EndIdx) || 6222 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 6223 I == DimIdx + NumGradients - 1))) { 6224 if (Addr.getValueType() != MVT::i16) 6225 Addr = DAG.getBitcast(MVT::i16, Addr); 6226 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 6227 } else { 6228 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 6229 I++; 6230 } 6231 Addr = DAG.getBitcast(MVT::f32, Addr); 6232 PackedAddrs.push_back(Addr); 6233 } 6234 } 6235 6236 SDValue SITargetLowering::lowerImage(SDValue Op, 6237 const AMDGPU::ImageDimIntrinsicInfo *Intr, 6238 SelectionDAG &DAG, bool WithChain) const { 6239 SDLoc DL(Op); 6240 MachineFunction &MF = DAG.getMachineFunction(); 6241 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 6242 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 6243 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 6244 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 6245 unsigned IntrOpcode = Intr->BaseOpcode; 6246 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6247 bool IsGFX11Plus = AMDGPU::isGFX11Plus(*Subtarget); 6248 6249 SmallVector<EVT, 3> ResultTypes(Op->values()); 6250 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 6251 bool IsD16 = false; 6252 bool IsG16 = false; 6253 bool IsA16 = false; 6254 SDValue VData; 6255 int NumVDataDwords; 6256 bool AdjustRetType = false; 6257 6258 // Offset of intrinsic arguments 6259 const unsigned ArgOffset = WithChain ? 2 : 1; 6260 6261 unsigned DMask; 6262 unsigned DMaskLanes = 0; 6263 6264 if (BaseOpcode->Atomic) { 6265 VData = Op.getOperand(2); 6266 6267 bool Is64Bit = VData.getValueType() == MVT::i64; 6268 if (BaseOpcode->AtomicX2) { 6269 SDValue VData2 = Op.getOperand(3); 6270 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6271 {VData, VData2}); 6272 if (Is64Bit) 6273 VData = DAG.getBitcast(MVT::v4i32, VData); 6274 6275 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6276 DMask = Is64Bit ? 0xf : 0x3; 6277 NumVDataDwords = Is64Bit ? 4 : 2; 6278 } else { 6279 DMask = Is64Bit ? 0x3 : 0x1; 6280 NumVDataDwords = Is64Bit ? 2 : 1; 6281 } 6282 } else { 6283 auto *DMaskConst = 6284 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6285 DMask = DMaskConst->getZExtValue(); 6286 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6287 6288 if (BaseOpcode->Store) { 6289 VData = Op.getOperand(2); 6290 6291 MVT StoreVT = VData.getSimpleValueType(); 6292 if (StoreVT.getScalarType() == MVT::f16) { 6293 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6294 return Op; // D16 is unsupported for this instruction 6295 6296 IsD16 = true; 6297 VData = handleD16VData(VData, DAG, true); 6298 } 6299 6300 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6301 } else { 6302 // Work out the num dwords based on the dmask popcount and underlying type 6303 // and whether packing is supported. 6304 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6305 if (LoadVT.getScalarType() == MVT::f16) { 6306 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6307 return Op; // D16 is unsupported for this instruction 6308 6309 IsD16 = true; 6310 } 6311 6312 // Confirm that the return type is large enough for the dmask specified 6313 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6314 (!LoadVT.isVector() && DMaskLanes > 1)) 6315 return Op; 6316 6317 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6318 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6319 // instructions. 6320 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6321 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6322 NumVDataDwords = (DMaskLanes + 1) / 2; 6323 else 6324 NumVDataDwords = DMaskLanes; 6325 6326 AdjustRetType = true; 6327 } 6328 } 6329 6330 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6331 SmallVector<SDValue, 4> VAddrs; 6332 6333 // Check for 16 bit addresses or derivatives and pack if true. 6334 MVT VAddrVT = 6335 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6336 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6337 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6338 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6339 6340 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6341 VAddrScalarVT = VAddrVT.getScalarType(); 6342 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6343 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6344 6345 // Push back extra arguments. 6346 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) { 6347 if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) { 6348 assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument"); 6349 // Special handling of bias when A16 is on. Bias is of type half but 6350 // occupies full 32-bit. 6351 SDValue Bias = DAG.getBuildVector( 6352 MVT::v2f16, DL, 6353 {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)}); 6354 VAddrs.push_back(Bias); 6355 } else { 6356 assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) && 6357 "Bias needs to be converted to 16 bit in A16 mode"); 6358 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6359 } 6360 } 6361 6362 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) { 6363 // 16 bit gradients are supported, but are tied to the A16 control 6364 // so both gradients and addresses must be 16 bit 6365 LLVM_DEBUG( 6366 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6367 "require 16 bit args for both gradients and addresses"); 6368 return Op; 6369 } 6370 6371 if (IsA16) { 6372 if (!ST->hasA16()) { 6373 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6374 "support 16 bit addresses\n"); 6375 return Op; 6376 } 6377 } 6378 6379 // We've dealt with incorrect input so we know that if IsA16, IsG16 6380 // are set then we have to compress/pack operands (either address, 6381 // gradient or both) 6382 // In the case where a16 and gradients are tied (no G16 support) then we 6383 // have already verified that both IsA16 and IsG16 are true 6384 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) { 6385 // Activate g16 6386 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6387 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6388 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6389 } 6390 6391 // Add gradients (packed or unpacked) 6392 if (IsG16) { 6393 // Pack the gradients 6394 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6395 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs, 6396 ArgOffset + Intr->GradientStart, 6397 ArgOffset + Intr->CoordStart, Intr->NumGradients); 6398 } else { 6399 for (unsigned I = ArgOffset + Intr->GradientStart; 6400 I < ArgOffset + Intr->CoordStart; I++) 6401 VAddrs.push_back(Op.getOperand(I)); 6402 } 6403 6404 // Add addresses (packed or unpacked) 6405 if (IsA16) { 6406 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs, 6407 ArgOffset + Intr->CoordStart, VAddrEnd, 6408 0 /* No gradients */); 6409 } else { 6410 // Add uncompressed address 6411 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6412 VAddrs.push_back(Op.getOperand(I)); 6413 } 6414 6415 // If the register allocator cannot place the address registers contiguously 6416 // without introducing moves, then using the non-sequential address encoding 6417 // is always preferable, since it saves VALU instructions and is usually a 6418 // wash in terms of code size or even better. 6419 // 6420 // However, we currently have no way of hinting to the register allocator that 6421 // MIMG addresses should be placed contiguously when it is possible to do so, 6422 // so force non-NSA for the common 2-address case as a heuristic. 6423 // 6424 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6425 // allocation when possible. 6426 // 6427 // TODO: we can actually allow partial NSA where the final register is a 6428 // contiguous set of the remaining addresses. 6429 // This could help where there are more addresses than supported. 6430 bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) && 6431 VAddrs.size() >= 3 && 6432 VAddrs.size() <= (unsigned)ST->getNSAMaxSize(); 6433 SDValue VAddr; 6434 if (!UseNSA) 6435 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6436 6437 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6438 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6439 SDValue Unorm; 6440 if (!BaseOpcode->Sampler) { 6441 Unorm = True; 6442 } else { 6443 auto UnormConst = 6444 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6445 6446 Unorm = UnormConst->getZExtValue() ? True : False; 6447 } 6448 6449 SDValue TFE; 6450 SDValue LWE; 6451 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6452 bool IsTexFail = false; 6453 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6454 return Op; 6455 6456 if (IsTexFail) { 6457 if (!DMaskLanes) { 6458 // Expecting to get an error flag since TFC is on - and dmask is 0 6459 // Force dmask to be at least 1 otherwise the instruction will fail 6460 DMask = 0x1; 6461 DMaskLanes = 1; 6462 NumVDataDwords = 1; 6463 } 6464 NumVDataDwords += 1; 6465 AdjustRetType = true; 6466 } 6467 6468 // Has something earlier tagged that the return type needs adjusting 6469 // This happens if the instruction is a load or has set TexFailCtrl flags 6470 if (AdjustRetType) { 6471 // NumVDataDwords reflects the true number of dwords required in the return type 6472 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6473 // This is a no-op load. This can be eliminated 6474 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6475 if (isa<MemSDNode>(Op)) 6476 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6477 return Undef; 6478 } 6479 6480 EVT NewVT = NumVDataDwords > 1 ? 6481 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6482 : MVT::i32; 6483 6484 ResultTypes[0] = NewVT; 6485 if (ResultTypes.size() == 3) { 6486 // Original result was aggregate type used for TexFailCtrl results 6487 // The actual instruction returns as a vector type which has now been 6488 // created. Remove the aggregate result. 6489 ResultTypes.erase(&ResultTypes[1]); 6490 } 6491 } 6492 6493 unsigned CPol = cast<ConstantSDNode>( 6494 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6495 if (BaseOpcode->Atomic) 6496 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6497 if (CPol & ~AMDGPU::CPol::ALL) 6498 return Op; 6499 6500 SmallVector<SDValue, 26> Ops; 6501 if (BaseOpcode->Store || BaseOpcode->Atomic) 6502 Ops.push_back(VData); // vdata 6503 if (UseNSA) 6504 append_range(Ops, VAddrs); 6505 else 6506 Ops.push_back(VAddr); 6507 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6508 if (BaseOpcode->Sampler) 6509 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6510 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6511 if (IsGFX10Plus) 6512 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6513 Ops.push_back(Unorm); 6514 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6515 Ops.push_back(IsA16 && // r128, a16 for gfx9 6516 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6517 if (IsGFX10Plus) 6518 Ops.push_back(IsA16 ? True : False); 6519 if (!Subtarget->hasGFX90AInsts()) { 6520 Ops.push_back(TFE); //tfe 6521 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6522 report_fatal_error("TFE is not supported on this GPU"); 6523 } 6524 Ops.push_back(LWE); // lwe 6525 if (!IsGFX10Plus) 6526 Ops.push_back(DimInfo->DA ? True : False); 6527 if (BaseOpcode->HasD16) 6528 Ops.push_back(IsD16 ? True : False); 6529 if (isa<MemSDNode>(Op)) 6530 Ops.push_back(Op.getOperand(0)); // chain 6531 6532 int NumVAddrDwords = 6533 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6534 int Opcode = -1; 6535 6536 if (IsGFX11Plus) { 6537 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6538 UseNSA ? AMDGPU::MIMGEncGfx11NSA 6539 : AMDGPU::MIMGEncGfx11Default, 6540 NumVDataDwords, NumVAddrDwords); 6541 } else if (IsGFX10Plus) { 6542 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6543 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6544 : AMDGPU::MIMGEncGfx10Default, 6545 NumVDataDwords, NumVAddrDwords); 6546 } else { 6547 if (Subtarget->hasGFX90AInsts()) { 6548 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6549 NumVDataDwords, NumVAddrDwords); 6550 if (Opcode == -1) 6551 report_fatal_error( 6552 "requested image instruction is not supported on this GPU"); 6553 } 6554 if (Opcode == -1 && 6555 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6556 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6557 NumVDataDwords, NumVAddrDwords); 6558 if (Opcode == -1) 6559 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6560 NumVDataDwords, NumVAddrDwords); 6561 } 6562 assert(Opcode != -1); 6563 6564 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6565 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6566 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6567 DAG.setNodeMemRefs(NewNode, {MemRef}); 6568 } 6569 6570 if (BaseOpcode->AtomicX2) { 6571 SmallVector<SDValue, 1> Elt; 6572 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6573 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6574 } 6575 if (BaseOpcode->Store) 6576 return SDValue(NewNode, 0); 6577 return constructRetValue(DAG, NewNode, 6578 OrigResultTypes, IsTexFail, 6579 Subtarget->hasUnpackedD16VMem(), IsD16, 6580 DMaskLanes, NumVDataDwords, DL); 6581 } 6582 6583 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6584 SDValue Offset, SDValue CachePolicy, 6585 SelectionDAG &DAG) const { 6586 MachineFunction &MF = DAG.getMachineFunction(); 6587 6588 const DataLayout &DataLayout = DAG.getDataLayout(); 6589 Align Alignment = 6590 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6591 6592 MachineMemOperand *MMO = MF.getMachineMemOperand( 6593 MachinePointerInfo(), 6594 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6595 MachineMemOperand::MOInvariant, 6596 VT.getStoreSize(), Alignment); 6597 6598 if (!Offset->isDivergent()) { 6599 SDValue Ops[] = { 6600 Rsrc, 6601 Offset, // Offset 6602 CachePolicy 6603 }; 6604 6605 // Widen vec3 load to vec4. 6606 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6607 EVT WidenedVT = 6608 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6609 auto WidenedOp = DAG.getMemIntrinsicNode( 6610 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6611 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6612 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6613 DAG.getVectorIdxConstant(0, DL)); 6614 return Subvector; 6615 } 6616 6617 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6618 DAG.getVTList(VT), Ops, VT, MMO); 6619 } 6620 6621 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6622 // assume that the buffer is unswizzled. 6623 SmallVector<SDValue, 4> Loads; 6624 unsigned NumLoads = 1; 6625 MVT LoadVT = VT.getSimpleVT(); 6626 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6627 assert((LoadVT.getScalarType() == MVT::i32 || 6628 LoadVT.getScalarType() == MVT::f32)); 6629 6630 if (NumElts == 8 || NumElts == 16) { 6631 NumLoads = NumElts / 4; 6632 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6633 } 6634 6635 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6636 SDValue Ops[] = { 6637 DAG.getEntryNode(), // Chain 6638 Rsrc, // rsrc 6639 DAG.getConstant(0, DL, MVT::i32), // vindex 6640 {}, // voffset 6641 {}, // soffset 6642 {}, // offset 6643 CachePolicy, // cachepolicy 6644 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6645 }; 6646 6647 // Use the alignment to ensure that the required offsets will fit into the 6648 // immediate offsets. 6649 setBufferOffsets(Offset, DAG, &Ops[3], 6650 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6651 6652 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6653 for (unsigned i = 0; i < NumLoads; ++i) { 6654 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6655 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6656 LoadVT, MMO, DAG)); 6657 } 6658 6659 if (NumElts == 8 || NumElts == 16) 6660 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6661 6662 return Loads[0]; 6663 } 6664 6665 SDValue SITargetLowering::lowerWorkitemID(SelectionDAG &DAG, SDValue Op, 6666 unsigned Dim, 6667 const ArgDescriptor &Arg) const { 6668 SDLoc SL(Op); 6669 MachineFunction &MF = DAG.getMachineFunction(); 6670 unsigned MaxID = Subtarget->getMaxWorkitemID(MF.getFunction(), Dim); 6671 if (MaxID == 0) 6672 return DAG.getConstant(0, SL, MVT::i32); 6673 6674 SDValue Val = loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6675 SDLoc(DAG.getEntryNode()), Arg); 6676 6677 // Don't bother inserting AssertZext for packed IDs since we're emitting the 6678 // masking operations anyway. 6679 // 6680 // TODO: We could assert the top bit is 0 for the source copy. 6681 if (Arg.isMasked()) 6682 return Val; 6683 6684 // Preserve the known bits after expansion to a copy. 6685 EVT SmallVT = 6686 EVT::getIntegerVT(*DAG.getContext(), 32 - countLeadingZeros(MaxID)); 6687 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Val, 6688 DAG.getValueType(SmallVT)); 6689 } 6690 6691 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6692 SelectionDAG &DAG) const { 6693 MachineFunction &MF = DAG.getMachineFunction(); 6694 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6695 6696 EVT VT = Op.getValueType(); 6697 SDLoc DL(Op); 6698 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6699 6700 // TODO: Should this propagate fast-math-flags? 6701 6702 switch (IntrinsicID) { 6703 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6704 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6705 return emitNonHSAIntrinsicError(DAG, DL, VT); 6706 return getPreloadedValue(DAG, *MFI, VT, 6707 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6708 } 6709 case Intrinsic::amdgcn_dispatch_ptr: 6710 case Intrinsic::amdgcn_queue_ptr: { 6711 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6712 DiagnosticInfoUnsupported BadIntrin( 6713 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6714 DL.getDebugLoc()); 6715 DAG.getContext()->diagnose(BadIntrin); 6716 return DAG.getUNDEF(VT); 6717 } 6718 6719 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6720 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6721 return getPreloadedValue(DAG, *MFI, VT, RegID); 6722 } 6723 case Intrinsic::amdgcn_implicitarg_ptr: { 6724 if (MFI->isEntryFunction()) 6725 return getImplicitArgPtr(DAG, DL); 6726 return getPreloadedValue(DAG, *MFI, VT, 6727 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6728 } 6729 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6730 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6731 // This only makes sense to call in a kernel, so just lower to null. 6732 return DAG.getConstant(0, DL, VT); 6733 } 6734 6735 return getPreloadedValue(DAG, *MFI, VT, 6736 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6737 } 6738 case Intrinsic::amdgcn_dispatch_id: { 6739 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6740 } 6741 case Intrinsic::amdgcn_rcp: 6742 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6743 case Intrinsic::amdgcn_rsq: 6744 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6745 case Intrinsic::amdgcn_rsq_legacy: 6746 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6747 return emitRemovedIntrinsicError(DAG, DL, VT); 6748 return SDValue(); 6749 case Intrinsic::amdgcn_rcp_legacy: 6750 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6751 return emitRemovedIntrinsicError(DAG, DL, VT); 6752 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6753 case Intrinsic::amdgcn_rsq_clamp: { 6754 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6755 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6756 6757 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6758 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6759 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6760 6761 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6762 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6763 DAG.getConstantFP(Max, DL, VT)); 6764 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6765 DAG.getConstantFP(Min, DL, VT)); 6766 } 6767 case Intrinsic::r600_read_ngroups_x: 6768 if (Subtarget->isAmdHsaOS()) 6769 return emitNonHSAIntrinsicError(DAG, DL, VT); 6770 6771 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6772 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6773 false); 6774 case Intrinsic::r600_read_ngroups_y: 6775 if (Subtarget->isAmdHsaOS()) 6776 return emitNonHSAIntrinsicError(DAG, DL, VT); 6777 6778 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6779 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6780 false); 6781 case Intrinsic::r600_read_ngroups_z: 6782 if (Subtarget->isAmdHsaOS()) 6783 return emitNonHSAIntrinsicError(DAG, DL, VT); 6784 6785 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6786 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6787 false); 6788 case Intrinsic::r600_read_global_size_x: 6789 if (Subtarget->isAmdHsaOS()) 6790 return emitNonHSAIntrinsicError(DAG, DL, VT); 6791 6792 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6793 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6794 Align(4), false); 6795 case Intrinsic::r600_read_global_size_y: 6796 if (Subtarget->isAmdHsaOS()) 6797 return emitNonHSAIntrinsicError(DAG, DL, VT); 6798 6799 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6800 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6801 Align(4), false); 6802 case Intrinsic::r600_read_global_size_z: 6803 if (Subtarget->isAmdHsaOS()) 6804 return emitNonHSAIntrinsicError(DAG, DL, VT); 6805 6806 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6807 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6808 Align(4), false); 6809 case Intrinsic::r600_read_local_size_x: 6810 if (Subtarget->isAmdHsaOS()) 6811 return emitNonHSAIntrinsicError(DAG, DL, VT); 6812 6813 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6814 SI::KernelInputOffsets::LOCAL_SIZE_X); 6815 case Intrinsic::r600_read_local_size_y: 6816 if (Subtarget->isAmdHsaOS()) 6817 return emitNonHSAIntrinsicError(DAG, DL, VT); 6818 6819 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6820 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6821 case Intrinsic::r600_read_local_size_z: 6822 if (Subtarget->isAmdHsaOS()) 6823 return emitNonHSAIntrinsicError(DAG, DL, VT); 6824 6825 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6826 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6827 case Intrinsic::amdgcn_workgroup_id_x: 6828 return getPreloadedValue(DAG, *MFI, VT, 6829 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6830 case Intrinsic::amdgcn_workgroup_id_y: 6831 return getPreloadedValue(DAG, *MFI, VT, 6832 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6833 case Intrinsic::amdgcn_workgroup_id_z: 6834 return getPreloadedValue(DAG, *MFI, VT, 6835 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6836 case Intrinsic::amdgcn_workitem_id_x: 6837 return lowerWorkitemID(DAG, Op, 0, MFI->getArgInfo().WorkItemIDX); 6838 case Intrinsic::amdgcn_workitem_id_y: 6839 return lowerWorkitemID(DAG, Op, 1, MFI->getArgInfo().WorkItemIDY); 6840 case Intrinsic::amdgcn_workitem_id_z: 6841 return lowerWorkitemID(DAG, Op, 2, MFI->getArgInfo().WorkItemIDZ); 6842 case Intrinsic::amdgcn_wavefrontsize: 6843 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6844 SDLoc(Op), MVT::i32); 6845 case Intrinsic::amdgcn_s_buffer_load: { 6846 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6847 if (CPol & ~AMDGPU::CPol::ALL) 6848 return Op; 6849 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6850 DAG); 6851 } 6852 case Intrinsic::amdgcn_fdiv_fast: 6853 return lowerFDIV_FAST(Op, DAG); 6854 case Intrinsic::amdgcn_sin: 6855 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6856 6857 case Intrinsic::amdgcn_cos: 6858 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6859 6860 case Intrinsic::amdgcn_mul_u24: 6861 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6862 case Intrinsic::amdgcn_mul_i24: 6863 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6864 6865 case Intrinsic::amdgcn_log_clamp: { 6866 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6867 return SDValue(); 6868 6869 return emitRemovedIntrinsicError(DAG, DL, VT); 6870 } 6871 case Intrinsic::amdgcn_ldexp: 6872 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6873 Op.getOperand(1), Op.getOperand(2)); 6874 6875 case Intrinsic::amdgcn_fract: 6876 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6877 6878 case Intrinsic::amdgcn_class: 6879 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6880 Op.getOperand(1), Op.getOperand(2)); 6881 case Intrinsic::amdgcn_div_fmas: 6882 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6883 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6884 Op.getOperand(4)); 6885 6886 case Intrinsic::amdgcn_div_fixup: 6887 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6888 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6889 6890 case Intrinsic::amdgcn_div_scale: { 6891 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6892 6893 // Translate to the operands expected by the machine instruction. The 6894 // first parameter must be the same as the first instruction. 6895 SDValue Numerator = Op.getOperand(1); 6896 SDValue Denominator = Op.getOperand(2); 6897 6898 // Note this order is opposite of the machine instruction's operations, 6899 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6900 // intrinsic has the numerator as the first operand to match a normal 6901 // division operation. 6902 6903 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator; 6904 6905 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6906 Denominator, Numerator); 6907 } 6908 case Intrinsic::amdgcn_icmp: { 6909 // There is a Pat that handles this variant, so return it as-is. 6910 if (Op.getOperand(1).getValueType() == MVT::i1 && 6911 Op.getConstantOperandVal(2) == 0 && 6912 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6913 return Op; 6914 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6915 } 6916 case Intrinsic::amdgcn_fcmp: { 6917 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6918 } 6919 case Intrinsic::amdgcn_ballot: 6920 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6921 case Intrinsic::amdgcn_fmed3: 6922 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6923 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6924 case Intrinsic::amdgcn_fdot2: 6925 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6926 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6927 Op.getOperand(4)); 6928 case Intrinsic::amdgcn_fmul_legacy: 6929 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6930 Op.getOperand(1), Op.getOperand(2)); 6931 case Intrinsic::amdgcn_sffbh: 6932 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6933 case Intrinsic::amdgcn_sbfe: 6934 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6935 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6936 case Intrinsic::amdgcn_ubfe: 6937 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6938 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6939 case Intrinsic::amdgcn_cvt_pkrtz: 6940 case Intrinsic::amdgcn_cvt_pknorm_i16: 6941 case Intrinsic::amdgcn_cvt_pknorm_u16: 6942 case Intrinsic::amdgcn_cvt_pk_i16: 6943 case Intrinsic::amdgcn_cvt_pk_u16: { 6944 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6945 EVT VT = Op.getValueType(); 6946 unsigned Opcode; 6947 6948 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6949 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6950 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6951 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6952 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6953 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6954 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6955 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6956 else 6957 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6958 6959 if (isTypeLegal(VT)) 6960 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6961 6962 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6963 Op.getOperand(1), Op.getOperand(2)); 6964 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6965 } 6966 case Intrinsic::amdgcn_fmad_ftz: 6967 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6968 Op.getOperand(2), Op.getOperand(3)); 6969 6970 case Intrinsic::amdgcn_if_break: 6971 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6972 Op->getOperand(1), Op->getOperand(2)), 0); 6973 6974 case Intrinsic::amdgcn_groupstaticsize: { 6975 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6976 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6977 return Op; 6978 6979 const Module *M = MF.getFunction().getParent(); 6980 const GlobalValue *GV = 6981 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6982 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6983 SIInstrInfo::MO_ABS32_LO); 6984 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6985 } 6986 case Intrinsic::amdgcn_is_shared: 6987 case Intrinsic::amdgcn_is_private: { 6988 SDLoc SL(Op); 6989 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6990 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6991 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6992 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6993 Op.getOperand(1)); 6994 6995 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6996 DAG.getConstant(1, SL, MVT::i32)); 6997 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6998 } 6999 case Intrinsic::amdgcn_perm: 7000 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1), 7001 Op.getOperand(2), Op.getOperand(3)); 7002 case Intrinsic::amdgcn_reloc_constant: { 7003 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 7004 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 7005 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 7006 auto RelocSymbol = cast<GlobalVariable>( 7007 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 7008 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 7009 SIInstrInfo::MO_ABS32_LO); 7010 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 7011 } 7012 default: 7013 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7014 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7015 return lowerImage(Op, ImageDimIntr, DAG, false); 7016 7017 return Op; 7018 } 7019 } 7020 7021 /// Update \p MMO based on the offset inputs to an intrinsic. 7022 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset, 7023 SDValue SOffset, SDValue Offset, 7024 SDValue VIndex = SDValue()) { 7025 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 7026 !isa<ConstantSDNode>(Offset)) { 7027 // The combined offset is not known to be constant, so we cannot represent 7028 // it in the MMO. Give up. 7029 MMO->setValue((Value *)nullptr); 7030 return; 7031 } 7032 7033 if (VIndex && (!isa<ConstantSDNode>(VIndex) || 7034 !cast<ConstantSDNode>(VIndex)->isZero())) { 7035 // The strided index component of the address is not known to be zero, so we 7036 // cannot represent it in the MMO. Give up. 7037 MMO->setValue((Value *)nullptr); 7038 return; 7039 } 7040 7041 MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() + 7042 cast<ConstantSDNode>(SOffset)->getSExtValue() + 7043 cast<ConstantSDNode>(Offset)->getSExtValue()); 7044 } 7045 7046 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 7047 SelectionDAG &DAG, 7048 unsigned NewOpcode) const { 7049 SDLoc DL(Op); 7050 7051 SDValue VData = Op.getOperand(2); 7052 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7053 SDValue Ops[] = { 7054 Op.getOperand(0), // Chain 7055 VData, // vdata 7056 Op.getOperand(3), // rsrc 7057 DAG.getConstant(0, DL, MVT::i32), // vindex 7058 Offsets.first, // voffset 7059 Op.getOperand(5), // soffset 7060 Offsets.second, // offset 7061 Op.getOperand(6), // cachepolicy 7062 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7063 }; 7064 7065 auto *M = cast<MemSDNode>(Op); 7066 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 7067 7068 EVT MemVT = VData.getValueType(); 7069 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7070 M->getMemOperand()); 7071 } 7072 7073 // Return a value to use for the idxen operand by examining the vindex operand. 7074 static unsigned getIdxEn(SDValue VIndex) { 7075 if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex)) 7076 // No need to set idxen if vindex is known to be zero. 7077 return VIndexC->getZExtValue() != 0; 7078 return 1; 7079 } 7080 7081 SDValue 7082 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 7083 unsigned NewOpcode) const { 7084 SDLoc DL(Op); 7085 7086 SDValue VData = Op.getOperand(2); 7087 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7088 SDValue Ops[] = { 7089 Op.getOperand(0), // Chain 7090 VData, // vdata 7091 Op.getOperand(3), // rsrc 7092 Op.getOperand(4), // vindex 7093 Offsets.first, // voffset 7094 Op.getOperand(6), // soffset 7095 Offsets.second, // offset 7096 Op.getOperand(7), // cachepolicy 7097 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7098 }; 7099 7100 auto *M = cast<MemSDNode>(Op); 7101 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7102 7103 EVT MemVT = VData.getValueType(); 7104 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7105 M->getMemOperand()); 7106 } 7107 7108 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 7109 SelectionDAG &DAG) const { 7110 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7111 SDLoc DL(Op); 7112 7113 switch (IntrID) { 7114 case Intrinsic::amdgcn_ds_ordered_add: 7115 case Intrinsic::amdgcn_ds_ordered_swap: { 7116 MemSDNode *M = cast<MemSDNode>(Op); 7117 SDValue Chain = M->getOperand(0); 7118 SDValue M0 = M->getOperand(2); 7119 SDValue Value = M->getOperand(3); 7120 unsigned IndexOperand = M->getConstantOperandVal(7); 7121 unsigned WaveRelease = M->getConstantOperandVal(8); 7122 unsigned WaveDone = M->getConstantOperandVal(9); 7123 7124 unsigned OrderedCountIndex = IndexOperand & 0x3f; 7125 IndexOperand &= ~0x3f; 7126 unsigned CountDw = 0; 7127 7128 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 7129 CountDw = (IndexOperand >> 24) & 0xf; 7130 IndexOperand &= ~(0xf << 24); 7131 7132 if (CountDw < 1 || CountDw > 4) { 7133 report_fatal_error( 7134 "ds_ordered_count: dword count must be between 1 and 4"); 7135 } 7136 } 7137 7138 if (IndexOperand) 7139 report_fatal_error("ds_ordered_count: bad index operand"); 7140 7141 if (WaveDone && !WaveRelease) 7142 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 7143 7144 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 7145 unsigned ShaderType = 7146 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 7147 unsigned Offset0 = OrderedCountIndex << 2; 7148 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (Instruction << 4); 7149 7150 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 7151 Offset1 |= (CountDw - 1) << 6; 7152 7153 if (Subtarget->getGeneration() < AMDGPUSubtarget::GFX11) 7154 Offset1 |= ShaderType << 2; 7155 7156 unsigned Offset = Offset0 | (Offset1 << 8); 7157 7158 SDValue Ops[] = { 7159 Chain, 7160 Value, 7161 DAG.getTargetConstant(Offset, DL, MVT::i16), 7162 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 7163 }; 7164 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 7165 M->getVTList(), Ops, M->getMemoryVT(), 7166 M->getMemOperand()); 7167 } 7168 case Intrinsic::amdgcn_ds_fadd: { 7169 MemSDNode *M = cast<MemSDNode>(Op); 7170 unsigned Opc; 7171 switch (IntrID) { 7172 case Intrinsic::amdgcn_ds_fadd: 7173 Opc = ISD::ATOMIC_LOAD_FADD; 7174 break; 7175 } 7176 7177 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 7178 M->getOperand(0), M->getOperand(2), M->getOperand(3), 7179 M->getMemOperand()); 7180 } 7181 case Intrinsic::amdgcn_atomic_inc: 7182 case Intrinsic::amdgcn_atomic_dec: 7183 case Intrinsic::amdgcn_ds_fmin: 7184 case Intrinsic::amdgcn_ds_fmax: { 7185 MemSDNode *M = cast<MemSDNode>(Op); 7186 unsigned Opc; 7187 switch (IntrID) { 7188 case Intrinsic::amdgcn_atomic_inc: 7189 Opc = AMDGPUISD::ATOMIC_INC; 7190 break; 7191 case Intrinsic::amdgcn_atomic_dec: 7192 Opc = AMDGPUISD::ATOMIC_DEC; 7193 break; 7194 case Intrinsic::amdgcn_ds_fmin: 7195 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 7196 break; 7197 case Intrinsic::amdgcn_ds_fmax: 7198 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 7199 break; 7200 default: 7201 llvm_unreachable("Unknown intrinsic!"); 7202 } 7203 SDValue Ops[] = { 7204 M->getOperand(0), // Chain 7205 M->getOperand(2), // Ptr 7206 M->getOperand(3) // Value 7207 }; 7208 7209 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 7210 M->getMemoryVT(), M->getMemOperand()); 7211 } 7212 case Intrinsic::amdgcn_buffer_load: 7213 case Intrinsic::amdgcn_buffer_load_format: { 7214 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 7215 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7216 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7217 SDValue Ops[] = { 7218 Op.getOperand(0), // Chain 7219 Op.getOperand(2), // rsrc 7220 Op.getOperand(3), // vindex 7221 SDValue(), // voffset -- will be set by setBufferOffsets 7222 SDValue(), // soffset -- will be set by setBufferOffsets 7223 SDValue(), // offset -- will be set by setBufferOffsets 7224 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7225 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7226 }; 7227 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 7228 7229 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 7230 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 7231 7232 EVT VT = Op.getValueType(); 7233 EVT IntVT = VT.changeTypeToInteger(); 7234 auto *M = cast<MemSDNode>(Op); 7235 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7236 EVT LoadVT = Op.getValueType(); 7237 7238 if (LoadVT.getScalarType() == MVT::f16) 7239 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 7240 M, DAG, Ops); 7241 7242 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 7243 if (LoadVT.getScalarType() == MVT::i8 || 7244 LoadVT.getScalarType() == MVT::i16) 7245 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 7246 7247 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 7248 M->getMemOperand(), DAG); 7249 } 7250 case Intrinsic::amdgcn_raw_buffer_load: 7251 case Intrinsic::amdgcn_raw_buffer_load_format: { 7252 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 7253 7254 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7255 SDValue Ops[] = { 7256 Op.getOperand(0), // Chain 7257 Op.getOperand(2), // rsrc 7258 DAG.getConstant(0, DL, MVT::i32), // vindex 7259 Offsets.first, // voffset 7260 Op.getOperand(4), // soffset 7261 Offsets.second, // offset 7262 Op.getOperand(5), // cachepolicy, swizzled buffer 7263 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7264 }; 7265 7266 auto *M = cast<MemSDNode>(Op); 7267 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]); 7268 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 7269 } 7270 case Intrinsic::amdgcn_struct_buffer_load: 7271 case Intrinsic::amdgcn_struct_buffer_load_format: { 7272 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7273 7274 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7275 SDValue Ops[] = { 7276 Op.getOperand(0), // Chain 7277 Op.getOperand(2), // rsrc 7278 Op.getOperand(3), // vindex 7279 Offsets.first, // voffset 7280 Op.getOperand(5), // soffset 7281 Offsets.second, // offset 7282 Op.getOperand(6), // cachepolicy, swizzled buffer 7283 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7284 }; 7285 7286 auto *M = cast<MemSDNode>(Op); 7287 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7288 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7289 } 7290 case Intrinsic::amdgcn_tbuffer_load: { 7291 MemSDNode *M = cast<MemSDNode>(Op); 7292 EVT LoadVT = Op.getValueType(); 7293 7294 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7295 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7296 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7297 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7298 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7299 SDValue Ops[] = { 7300 Op.getOperand(0), // Chain 7301 Op.getOperand(2), // rsrc 7302 Op.getOperand(3), // vindex 7303 Op.getOperand(4), // voffset 7304 Op.getOperand(5), // soffset 7305 Op.getOperand(6), // offset 7306 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7307 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7308 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7309 }; 7310 7311 if (LoadVT.getScalarType() == MVT::f16) 7312 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7313 M, DAG, Ops); 7314 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7315 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7316 DAG); 7317 } 7318 case Intrinsic::amdgcn_raw_tbuffer_load: { 7319 MemSDNode *M = cast<MemSDNode>(Op); 7320 EVT LoadVT = Op.getValueType(); 7321 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7322 7323 SDValue Ops[] = { 7324 Op.getOperand(0), // Chain 7325 Op.getOperand(2), // rsrc 7326 DAG.getConstant(0, DL, MVT::i32), // vindex 7327 Offsets.first, // voffset 7328 Op.getOperand(4), // soffset 7329 Offsets.second, // offset 7330 Op.getOperand(5), // format 7331 Op.getOperand(6), // cachepolicy, swizzled buffer 7332 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7333 }; 7334 7335 if (LoadVT.getScalarType() == MVT::f16) 7336 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7337 M, DAG, Ops); 7338 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7339 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7340 DAG); 7341 } 7342 case Intrinsic::amdgcn_struct_tbuffer_load: { 7343 MemSDNode *M = cast<MemSDNode>(Op); 7344 EVT LoadVT = Op.getValueType(); 7345 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7346 7347 SDValue Ops[] = { 7348 Op.getOperand(0), // Chain 7349 Op.getOperand(2), // rsrc 7350 Op.getOperand(3), // vindex 7351 Offsets.first, // voffset 7352 Op.getOperand(5), // soffset 7353 Offsets.second, // offset 7354 Op.getOperand(6), // format 7355 Op.getOperand(7), // cachepolicy, swizzled buffer 7356 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7357 }; 7358 7359 if (LoadVT.getScalarType() == MVT::f16) 7360 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7361 M, DAG, Ops); 7362 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7363 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7364 DAG); 7365 } 7366 case Intrinsic::amdgcn_buffer_atomic_swap: 7367 case Intrinsic::amdgcn_buffer_atomic_add: 7368 case Intrinsic::amdgcn_buffer_atomic_sub: 7369 case Intrinsic::amdgcn_buffer_atomic_csub: 7370 case Intrinsic::amdgcn_buffer_atomic_smin: 7371 case Intrinsic::amdgcn_buffer_atomic_umin: 7372 case Intrinsic::amdgcn_buffer_atomic_smax: 7373 case Intrinsic::amdgcn_buffer_atomic_umax: 7374 case Intrinsic::amdgcn_buffer_atomic_and: 7375 case Intrinsic::amdgcn_buffer_atomic_or: 7376 case Intrinsic::amdgcn_buffer_atomic_xor: 7377 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7378 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7379 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7380 SDValue Ops[] = { 7381 Op.getOperand(0), // Chain 7382 Op.getOperand(2), // vdata 7383 Op.getOperand(3), // rsrc 7384 Op.getOperand(4), // vindex 7385 SDValue(), // voffset -- will be set by setBufferOffsets 7386 SDValue(), // soffset -- will be set by setBufferOffsets 7387 SDValue(), // offset -- will be set by setBufferOffsets 7388 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7389 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7390 }; 7391 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7392 7393 EVT VT = Op.getValueType(); 7394 7395 auto *M = cast<MemSDNode>(Op); 7396 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7397 unsigned Opcode = 0; 7398 7399 switch (IntrID) { 7400 case Intrinsic::amdgcn_buffer_atomic_swap: 7401 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7402 break; 7403 case Intrinsic::amdgcn_buffer_atomic_add: 7404 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7405 break; 7406 case Intrinsic::amdgcn_buffer_atomic_sub: 7407 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7408 break; 7409 case Intrinsic::amdgcn_buffer_atomic_csub: 7410 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7411 break; 7412 case Intrinsic::amdgcn_buffer_atomic_smin: 7413 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7414 break; 7415 case Intrinsic::amdgcn_buffer_atomic_umin: 7416 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7417 break; 7418 case Intrinsic::amdgcn_buffer_atomic_smax: 7419 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7420 break; 7421 case Intrinsic::amdgcn_buffer_atomic_umax: 7422 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7423 break; 7424 case Intrinsic::amdgcn_buffer_atomic_and: 7425 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7426 break; 7427 case Intrinsic::amdgcn_buffer_atomic_or: 7428 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7429 break; 7430 case Intrinsic::amdgcn_buffer_atomic_xor: 7431 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7432 break; 7433 case Intrinsic::amdgcn_buffer_atomic_fadd: 7434 if (!Op.getValue(0).use_empty() && !hasAtomicFaddRtnForTy(Op)) { 7435 DiagnosticInfoUnsupported 7436 NoFpRet(DAG.getMachineFunction().getFunction(), 7437 "return versions of fp atomics not supported", 7438 DL.getDebugLoc(), DS_Error); 7439 DAG.getContext()->diagnose(NoFpRet); 7440 return SDValue(); 7441 } 7442 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7443 break; 7444 default: 7445 llvm_unreachable("unhandled atomic opcode"); 7446 } 7447 7448 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7449 M->getMemOperand()); 7450 } 7451 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7452 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7453 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7454 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7455 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7456 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7457 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7458 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7459 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7460 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7461 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7462 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7463 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7464 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7465 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7466 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7467 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7468 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7469 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7470 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7471 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7472 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7473 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7474 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7475 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7476 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7477 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7478 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7479 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7480 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7481 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7482 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7483 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7484 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7485 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7486 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7487 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7488 return lowerStructBufferAtomicIntrin(Op, DAG, 7489 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7490 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7491 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7492 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7493 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7494 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7495 return lowerStructBufferAtomicIntrin(Op, DAG, 7496 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7497 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7498 return lowerStructBufferAtomicIntrin(Op, DAG, 7499 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7500 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7501 return lowerStructBufferAtomicIntrin(Op, DAG, 7502 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7503 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7504 return lowerStructBufferAtomicIntrin(Op, DAG, 7505 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7506 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7507 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7508 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7509 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7510 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7511 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7512 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7513 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7514 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7515 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7516 7517 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7518 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7519 unsigned IdxEn = getIdxEn(Op.getOperand(5)); 7520 SDValue Ops[] = { 7521 Op.getOperand(0), // Chain 7522 Op.getOperand(2), // src 7523 Op.getOperand(3), // cmp 7524 Op.getOperand(4), // rsrc 7525 Op.getOperand(5), // vindex 7526 SDValue(), // voffset -- will be set by setBufferOffsets 7527 SDValue(), // soffset -- will be set by setBufferOffsets 7528 SDValue(), // offset -- will be set by setBufferOffsets 7529 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7530 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7531 }; 7532 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7533 7534 EVT VT = Op.getValueType(); 7535 auto *M = cast<MemSDNode>(Op); 7536 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7537 7538 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7539 Op->getVTList(), Ops, VT, M->getMemOperand()); 7540 } 7541 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7542 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7543 SDValue Ops[] = { 7544 Op.getOperand(0), // Chain 7545 Op.getOperand(2), // src 7546 Op.getOperand(3), // cmp 7547 Op.getOperand(4), // rsrc 7548 DAG.getConstant(0, DL, MVT::i32), // vindex 7549 Offsets.first, // voffset 7550 Op.getOperand(6), // soffset 7551 Offsets.second, // offset 7552 Op.getOperand(7), // cachepolicy 7553 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7554 }; 7555 EVT VT = Op.getValueType(); 7556 auto *M = cast<MemSDNode>(Op); 7557 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]); 7558 7559 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7560 Op->getVTList(), Ops, VT, M->getMemOperand()); 7561 } 7562 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7563 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7564 SDValue Ops[] = { 7565 Op.getOperand(0), // Chain 7566 Op.getOperand(2), // src 7567 Op.getOperand(3), // cmp 7568 Op.getOperand(4), // rsrc 7569 Op.getOperand(5), // vindex 7570 Offsets.first, // voffset 7571 Op.getOperand(7), // soffset 7572 Offsets.second, // offset 7573 Op.getOperand(8), // cachepolicy 7574 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7575 }; 7576 EVT VT = Op.getValueType(); 7577 auto *M = cast<MemSDNode>(Op); 7578 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7579 7580 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7581 Op->getVTList(), Ops, VT, M->getMemOperand()); 7582 } 7583 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7584 MemSDNode *M = cast<MemSDNode>(Op); 7585 SDValue NodePtr = M->getOperand(2); 7586 SDValue RayExtent = M->getOperand(3); 7587 SDValue RayOrigin = M->getOperand(4); 7588 SDValue RayDir = M->getOperand(5); 7589 SDValue RayInvDir = M->getOperand(6); 7590 SDValue TDescr = M->getOperand(7); 7591 7592 assert(NodePtr.getValueType() == MVT::i32 || 7593 NodePtr.getValueType() == MVT::i64); 7594 assert(RayDir.getValueType() == MVT::v3f16 || 7595 RayDir.getValueType() == MVT::v3f32); 7596 7597 if (!Subtarget->hasGFX10_AEncoding()) { 7598 emitRemovedIntrinsicError(DAG, DL, Op.getValueType()); 7599 return SDValue(); 7600 } 7601 7602 const bool IsGFX11Plus = AMDGPU::isGFX11Plus(*Subtarget); 7603 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7604 const bool Is64 = NodePtr.getValueType() == MVT::i64; 7605 const unsigned NumVDataDwords = 4; 7606 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11); 7607 const unsigned NumVAddrs = IsGFX11Plus ? (IsA16 ? 4 : 5) : NumVAddrDwords; 7608 const bool UseNSA = 7609 Subtarget->hasNSAEncoding() && NumVAddrs <= Subtarget->getNSAMaxSize(); 7610 const unsigned BaseOpcodes[2][2] = { 7611 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16}, 7612 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY, 7613 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}}; 7614 int Opcode; 7615 if (UseNSA) { 7616 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16], 7617 IsGFX11Plus ? AMDGPU::MIMGEncGfx11NSA 7618 : AMDGPU::MIMGEncGfx10NSA, 7619 NumVDataDwords, NumVAddrDwords); 7620 } else { 7621 Opcode = 7622 AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16], 7623 IsGFX11Plus ? AMDGPU::MIMGEncGfx11Default 7624 : AMDGPU::MIMGEncGfx10Default, 7625 NumVDataDwords, PowerOf2Ceil(NumVAddrDwords)); 7626 } 7627 assert(Opcode != -1); 7628 7629 SmallVector<SDValue, 16> Ops; 7630 7631 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7632 SmallVector<SDValue, 3> Lanes; 7633 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7634 if (Lanes[0].getValueSizeInBits() == 32) { 7635 for (unsigned I = 0; I < 3; ++I) 7636 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7637 } else { 7638 if (IsAligned) { 7639 Ops.push_back( 7640 DAG.getBitcast(MVT::i32, 7641 DAG.getBuildVector(MVT::v2f16, DL, 7642 { Lanes[0], Lanes[1] }))); 7643 Ops.push_back(Lanes[2]); 7644 } else { 7645 SDValue Elt0 = Ops.pop_back_val(); 7646 Ops.push_back( 7647 DAG.getBitcast(MVT::i32, 7648 DAG.getBuildVector(MVT::v2f16, DL, 7649 { Elt0, Lanes[0] }))); 7650 Ops.push_back( 7651 DAG.getBitcast(MVT::i32, 7652 DAG.getBuildVector(MVT::v2f16, DL, 7653 { Lanes[1], Lanes[2] }))); 7654 } 7655 } 7656 }; 7657 7658 if (UseNSA && IsGFX11Plus) { 7659 Ops.push_back(NodePtr); 7660 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7661 Ops.push_back(RayOrigin); 7662 if (IsA16) { 7663 SmallVector<SDValue, 3> DirLanes, InvDirLanes, MergedLanes; 7664 DAG.ExtractVectorElements(RayDir, DirLanes, 0, 3); 7665 DAG.ExtractVectorElements(RayInvDir, InvDirLanes, 0, 3); 7666 for (unsigned I = 0; I < 3; ++I) { 7667 MergedLanes.push_back(DAG.getBitcast( 7668 MVT::i32, DAG.getBuildVector(MVT::v2f16, DL, 7669 {DirLanes[I], InvDirLanes[I]}))); 7670 } 7671 Ops.push_back(DAG.getBuildVector(MVT::v3i32, DL, MergedLanes)); 7672 } else { 7673 Ops.push_back(RayDir); 7674 Ops.push_back(RayInvDir); 7675 } 7676 } else { 7677 if (Is64) 7678 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 7679 2); 7680 else 7681 Ops.push_back(NodePtr); 7682 7683 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7684 packLanes(RayOrigin, true); 7685 packLanes(RayDir, true); 7686 packLanes(RayInvDir, false); 7687 } 7688 7689 if (!UseNSA) { 7690 // Build a single vector containing all the operands so far prepared. 7691 if (NumVAddrDwords > 8) { 7692 SDValue Undef = DAG.getUNDEF(MVT::i32); 7693 Ops.append(16 - Ops.size(), Undef); 7694 } 7695 assert(Ops.size() == 8 || Ops.size() == 16); 7696 SDValue MergedOps = DAG.getBuildVector( 7697 Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops); 7698 Ops.clear(); 7699 Ops.push_back(MergedOps); 7700 } 7701 7702 Ops.push_back(TDescr); 7703 if (IsA16) 7704 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7705 Ops.push_back(M->getChain()); 7706 7707 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7708 MachineMemOperand *MemRef = M->getMemOperand(); 7709 DAG.setNodeMemRefs(NewNode, {MemRef}); 7710 return SDValue(NewNode, 0); 7711 } 7712 case Intrinsic::amdgcn_global_atomic_fadd: 7713 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7714 DiagnosticInfoUnsupported 7715 NoFpRet(DAG.getMachineFunction().getFunction(), 7716 "return versions of fp atomics not supported", 7717 DL.getDebugLoc(), DS_Error); 7718 DAG.getContext()->diagnose(NoFpRet); 7719 return SDValue(); 7720 } 7721 LLVM_FALLTHROUGH; 7722 case Intrinsic::amdgcn_global_atomic_fmin: 7723 case Intrinsic::amdgcn_global_atomic_fmax: 7724 case Intrinsic::amdgcn_flat_atomic_fadd: 7725 case Intrinsic::amdgcn_flat_atomic_fmin: 7726 case Intrinsic::amdgcn_flat_atomic_fmax: { 7727 MemSDNode *M = cast<MemSDNode>(Op); 7728 SDValue Ops[] = { 7729 M->getOperand(0), // Chain 7730 M->getOperand(2), // Ptr 7731 M->getOperand(3) // Value 7732 }; 7733 unsigned Opcode = 0; 7734 switch (IntrID) { 7735 case Intrinsic::amdgcn_global_atomic_fadd: 7736 case Intrinsic::amdgcn_flat_atomic_fadd: { 7737 EVT VT = Op.getOperand(3).getValueType(); 7738 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7739 DAG.getVTList(VT, MVT::Other), Ops, 7740 M->getMemOperand()); 7741 } 7742 case Intrinsic::amdgcn_global_atomic_fmin: 7743 case Intrinsic::amdgcn_flat_atomic_fmin: { 7744 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7745 break; 7746 } 7747 case Intrinsic::amdgcn_global_atomic_fmax: 7748 case Intrinsic::amdgcn_flat_atomic_fmax: { 7749 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7750 break; 7751 } 7752 default: 7753 llvm_unreachable("unhandled atomic opcode"); 7754 } 7755 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7756 M->getVTList(), Ops, M->getMemoryVT(), 7757 M->getMemOperand()); 7758 } 7759 default: 7760 7761 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7762 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7763 return lowerImage(Op, ImageDimIntr, DAG, true); 7764 7765 return SDValue(); 7766 } 7767 } 7768 7769 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7770 // dwordx4 if on SI. 7771 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7772 SDVTList VTList, 7773 ArrayRef<SDValue> Ops, EVT MemVT, 7774 MachineMemOperand *MMO, 7775 SelectionDAG &DAG) const { 7776 EVT VT = VTList.VTs[0]; 7777 EVT WidenedVT = VT; 7778 EVT WidenedMemVT = MemVT; 7779 if (!Subtarget->hasDwordx3LoadStores() && 7780 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7781 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7782 WidenedVT.getVectorElementType(), 4); 7783 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7784 WidenedMemVT.getVectorElementType(), 4); 7785 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7786 } 7787 7788 assert(VTList.NumVTs == 2); 7789 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7790 7791 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7792 WidenedMemVT, MMO); 7793 if (WidenedVT != VT) { 7794 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7795 DAG.getVectorIdxConstant(0, DL)); 7796 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7797 } 7798 return NewOp; 7799 } 7800 7801 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7802 bool ImageStore) const { 7803 EVT StoreVT = VData.getValueType(); 7804 7805 // No change for f16 and legal vector D16 types. 7806 if (!StoreVT.isVector()) 7807 return VData; 7808 7809 SDLoc DL(VData); 7810 unsigned NumElements = StoreVT.getVectorNumElements(); 7811 7812 if (Subtarget->hasUnpackedD16VMem()) { 7813 // We need to unpack the packed data to store. 7814 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7815 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7816 7817 EVT EquivStoreVT = 7818 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7819 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7820 return DAG.UnrollVectorOp(ZExt.getNode()); 7821 } 7822 7823 // The sq block of gfx8.1 does not estimate register use correctly for d16 7824 // image store instructions. The data operand is computed as if it were not a 7825 // d16 image instruction. 7826 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7827 // Bitcast to i16 7828 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7829 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7830 7831 // Decompose into scalars 7832 SmallVector<SDValue, 4> Elts; 7833 DAG.ExtractVectorElements(IntVData, Elts); 7834 7835 // Group pairs of i16 into v2i16 and bitcast to i32 7836 SmallVector<SDValue, 4> PackedElts; 7837 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7838 SDValue Pair = 7839 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7840 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7841 PackedElts.push_back(IntPair); 7842 } 7843 if ((NumElements % 2) == 1) { 7844 // Handle v3i16 7845 unsigned I = Elts.size() / 2; 7846 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7847 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7848 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7849 PackedElts.push_back(IntPair); 7850 } 7851 7852 // Pad using UNDEF 7853 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7854 7855 // Build final vector 7856 EVT VecVT = 7857 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7858 return DAG.getBuildVector(VecVT, DL, PackedElts); 7859 } 7860 7861 if (NumElements == 3) { 7862 EVT IntStoreVT = 7863 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7864 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7865 7866 EVT WidenedStoreVT = EVT::getVectorVT( 7867 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7868 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7869 WidenedStoreVT.getStoreSizeInBits()); 7870 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7871 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7872 } 7873 7874 assert(isTypeLegal(StoreVT)); 7875 return VData; 7876 } 7877 7878 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7879 SelectionDAG &DAG) const { 7880 SDLoc DL(Op); 7881 SDValue Chain = Op.getOperand(0); 7882 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7883 MachineFunction &MF = DAG.getMachineFunction(); 7884 7885 switch (IntrinsicID) { 7886 case Intrinsic::amdgcn_exp_compr: { 7887 if (!Subtarget->hasCompressedExport()) { 7888 DiagnosticInfoUnsupported BadIntrin( 7889 DAG.getMachineFunction().getFunction(), 7890 "intrinsic not supported on subtarget", DL.getDebugLoc()); 7891 DAG.getContext()->diagnose(BadIntrin); 7892 } 7893 SDValue Src0 = Op.getOperand(4); 7894 SDValue Src1 = Op.getOperand(5); 7895 // Hack around illegal type on SI by directly selecting it. 7896 if (isTypeLegal(Src0.getValueType())) 7897 return SDValue(); 7898 7899 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7900 SDValue Undef = DAG.getUNDEF(MVT::f32); 7901 const SDValue Ops[] = { 7902 Op.getOperand(2), // tgt 7903 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7904 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7905 Undef, // src2 7906 Undef, // src3 7907 Op.getOperand(7), // vm 7908 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7909 Op.getOperand(3), // en 7910 Op.getOperand(0) // Chain 7911 }; 7912 7913 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7914 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7915 } 7916 case Intrinsic::amdgcn_s_barrier: { 7917 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7918 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7919 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7920 if (WGSize <= ST.getWavefrontSize()) 7921 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7922 Op.getOperand(0)), 0); 7923 } 7924 return SDValue(); 7925 }; 7926 case Intrinsic::amdgcn_tbuffer_store: { 7927 SDValue VData = Op.getOperand(2); 7928 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7929 if (IsD16) 7930 VData = handleD16VData(VData, DAG); 7931 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7932 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7933 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7934 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7935 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7936 SDValue Ops[] = { 7937 Chain, 7938 VData, // vdata 7939 Op.getOperand(3), // rsrc 7940 Op.getOperand(4), // vindex 7941 Op.getOperand(5), // voffset 7942 Op.getOperand(6), // soffset 7943 Op.getOperand(7), // offset 7944 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7945 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7946 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7947 }; 7948 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7949 AMDGPUISD::TBUFFER_STORE_FORMAT; 7950 MemSDNode *M = cast<MemSDNode>(Op); 7951 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7952 M->getMemoryVT(), M->getMemOperand()); 7953 } 7954 7955 case Intrinsic::amdgcn_struct_tbuffer_store: { 7956 SDValue VData = Op.getOperand(2); 7957 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7958 if (IsD16) 7959 VData = handleD16VData(VData, DAG); 7960 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7961 SDValue Ops[] = { 7962 Chain, 7963 VData, // vdata 7964 Op.getOperand(3), // rsrc 7965 Op.getOperand(4), // vindex 7966 Offsets.first, // voffset 7967 Op.getOperand(6), // soffset 7968 Offsets.second, // offset 7969 Op.getOperand(7), // format 7970 Op.getOperand(8), // cachepolicy, swizzled buffer 7971 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7972 }; 7973 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7974 AMDGPUISD::TBUFFER_STORE_FORMAT; 7975 MemSDNode *M = cast<MemSDNode>(Op); 7976 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7977 M->getMemoryVT(), M->getMemOperand()); 7978 } 7979 7980 case Intrinsic::amdgcn_raw_tbuffer_store: { 7981 SDValue VData = Op.getOperand(2); 7982 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7983 if (IsD16) 7984 VData = handleD16VData(VData, DAG); 7985 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7986 SDValue Ops[] = { 7987 Chain, 7988 VData, // vdata 7989 Op.getOperand(3), // rsrc 7990 DAG.getConstant(0, DL, MVT::i32), // vindex 7991 Offsets.first, // voffset 7992 Op.getOperand(5), // soffset 7993 Offsets.second, // offset 7994 Op.getOperand(6), // format 7995 Op.getOperand(7), // cachepolicy, swizzled buffer 7996 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7997 }; 7998 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7999 AMDGPUISD::TBUFFER_STORE_FORMAT; 8000 MemSDNode *M = cast<MemSDNode>(Op); 8001 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8002 M->getMemoryVT(), M->getMemOperand()); 8003 } 8004 8005 case Intrinsic::amdgcn_buffer_store: 8006 case Intrinsic::amdgcn_buffer_store_format: { 8007 SDValue VData = Op.getOperand(2); 8008 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 8009 if (IsD16) 8010 VData = handleD16VData(VData, DAG); 8011 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 8012 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 8013 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 8014 SDValue Ops[] = { 8015 Chain, 8016 VData, 8017 Op.getOperand(3), // rsrc 8018 Op.getOperand(4), // vindex 8019 SDValue(), // voffset -- will be set by setBufferOffsets 8020 SDValue(), // soffset -- will be set by setBufferOffsets 8021 SDValue(), // offset -- will be set by setBufferOffsets 8022 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 8023 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 8024 }; 8025 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 8026 8027 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 8028 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8029 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8030 MemSDNode *M = cast<MemSDNode>(Op); 8031 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8032 8033 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8034 EVT VDataType = VData.getValueType().getScalarType(); 8035 if (VDataType == MVT::i8 || VDataType == MVT::i16) 8036 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8037 8038 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8039 M->getMemoryVT(), M->getMemOperand()); 8040 } 8041 8042 case Intrinsic::amdgcn_raw_buffer_store: 8043 case Intrinsic::amdgcn_raw_buffer_store_format: { 8044 const bool IsFormat = 8045 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 8046 8047 SDValue VData = Op.getOperand(2); 8048 EVT VDataVT = VData.getValueType(); 8049 EVT EltType = VDataVT.getScalarType(); 8050 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 8051 if (IsD16) { 8052 VData = handleD16VData(VData, DAG); 8053 VDataVT = VData.getValueType(); 8054 } 8055 8056 if (!isTypeLegal(VDataVT)) { 8057 VData = 8058 DAG.getNode(ISD::BITCAST, DL, 8059 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 8060 } 8061 8062 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 8063 SDValue Ops[] = { 8064 Chain, 8065 VData, 8066 Op.getOperand(3), // rsrc 8067 DAG.getConstant(0, DL, MVT::i32), // vindex 8068 Offsets.first, // voffset 8069 Op.getOperand(5), // soffset 8070 Offsets.second, // offset 8071 Op.getOperand(6), // cachepolicy, swizzled buffer 8072 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 8073 }; 8074 unsigned Opc = 8075 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 8076 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8077 MemSDNode *M = cast<MemSDNode>(Op); 8078 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 8079 8080 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8081 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8082 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 8083 8084 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8085 M->getMemoryVT(), M->getMemOperand()); 8086 } 8087 8088 case Intrinsic::amdgcn_struct_buffer_store: 8089 case Intrinsic::amdgcn_struct_buffer_store_format: { 8090 const bool IsFormat = 8091 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 8092 8093 SDValue VData = Op.getOperand(2); 8094 EVT VDataVT = VData.getValueType(); 8095 EVT EltType = VDataVT.getScalarType(); 8096 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 8097 8098 if (IsD16) { 8099 VData = handleD16VData(VData, DAG); 8100 VDataVT = VData.getValueType(); 8101 } 8102 8103 if (!isTypeLegal(VDataVT)) { 8104 VData = 8105 DAG.getNode(ISD::BITCAST, DL, 8106 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 8107 } 8108 8109 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 8110 SDValue Ops[] = { 8111 Chain, 8112 VData, 8113 Op.getOperand(3), // rsrc 8114 Op.getOperand(4), // vindex 8115 Offsets.first, // voffset 8116 Op.getOperand(6), // soffset 8117 Offsets.second, // offset 8118 Op.getOperand(7), // cachepolicy, swizzled buffer 8119 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 8120 }; 8121 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 8122 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8123 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8124 MemSDNode *M = cast<MemSDNode>(Op); 8125 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8126 8127 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8128 EVT VDataType = VData.getValueType().getScalarType(); 8129 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8130 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8131 8132 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8133 M->getMemoryVT(), M->getMemOperand()); 8134 } 8135 case Intrinsic::amdgcn_raw_buffer_load_lds: 8136 case Intrinsic::amdgcn_struct_buffer_load_lds: { 8137 unsigned Opc; 8138 bool HasVIndex = IntrinsicID == Intrinsic::amdgcn_struct_buffer_load_lds; 8139 unsigned OpOffset = HasVIndex ? 1 : 0; 8140 SDValue VOffset = Op.getOperand(5 + OpOffset); 8141 auto CVOffset = dyn_cast<ConstantSDNode>(VOffset); 8142 bool HasVOffset = !CVOffset || !CVOffset->isZero(); 8143 unsigned Size = Op->getConstantOperandVal(4); 8144 8145 switch (Size) { 8146 default: 8147 return SDValue(); 8148 case 1: 8149 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_BOTHEN 8150 : AMDGPU::BUFFER_LOAD_UBYTE_LDS_IDXEN 8151 : HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFEN 8152 : AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFSET; 8153 break; 8154 case 2: 8155 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_BOTHEN 8156 : AMDGPU::BUFFER_LOAD_USHORT_LDS_IDXEN 8157 : HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFEN 8158 : AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFSET; 8159 break; 8160 case 4: 8161 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_BOTHEN 8162 : AMDGPU::BUFFER_LOAD_DWORD_LDS_IDXEN 8163 : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFEN 8164 : AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFSET; 8165 break; 8166 } 8167 8168 SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 8169 8170 SmallVector<SDValue, 8> Ops; 8171 8172 if (HasVIndex && HasVOffset) 8173 Ops.push_back(DAG.getBuildVector(MVT::v2i32, DL, 8174 { Op.getOperand(5), // VIndex 8175 VOffset })); 8176 else if (HasVIndex) 8177 Ops.push_back(Op.getOperand(5)); 8178 else if (HasVOffset) 8179 Ops.push_back(VOffset); 8180 8181 Ops.push_back(Op.getOperand(2)); // rsrc 8182 Ops.push_back(Op.getOperand(6 + OpOffset)); // soffset 8183 Ops.push_back(Op.getOperand(7 + OpOffset)); // imm offset 8184 unsigned Aux = Op.getConstantOperandVal(8 + OpOffset); 8185 Ops.push_back( 8186 DAG.getTargetConstant(Aux & AMDGPU::CPol::ALL, DL, MVT::i8)); // cpol 8187 Ops.push_back( 8188 DAG.getTargetConstant((Aux >> 3) & 1, DL, MVT::i8)); // swz 8189 Ops.push_back(M0Val.getValue(0)); // Chain 8190 Ops.push_back(M0Val.getValue(1)); // Glue 8191 8192 auto *M = cast<MemSDNode>(Op); 8193 MachineMemOperand *LoadMMO = M->getMemOperand(); 8194 MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo(); 8195 LoadPtrI.Offset = Op->getConstantOperandVal(7 + OpOffset); 8196 MachinePointerInfo StorePtrI = LoadPtrI; 8197 StorePtrI.V = nullptr; 8198 StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS; 8199 8200 auto F = LoadMMO->getFlags() & 8201 ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad); 8202 LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad, 8203 Size, LoadMMO->getBaseAlign()); 8204 8205 MachineMemOperand *StoreMMO = 8206 MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore, 8207 sizeof(int32_t), LoadMMO->getBaseAlign()); 8208 8209 auto Load = DAG.getMachineNode(Opc, DL, M->getVTList(), Ops); 8210 DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO}); 8211 8212 return SDValue(Load, 0); 8213 } 8214 case Intrinsic::amdgcn_global_load_lds: { 8215 unsigned Opc; 8216 unsigned Size = Op->getConstantOperandVal(4); 8217 switch (Size) { 8218 default: 8219 return SDValue(); 8220 case 1: 8221 Opc = AMDGPU::GLOBAL_LOAD_LDS_UBYTE; 8222 break; 8223 case 2: 8224 Opc = AMDGPU::GLOBAL_LOAD_LDS_USHORT; 8225 break; 8226 case 4: 8227 Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORD; 8228 break; 8229 } 8230 8231 auto *M = cast<MemSDNode>(Op); 8232 SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 8233 8234 SmallVector<SDValue, 6> Ops; 8235 8236 SDValue Addr = Op.getOperand(2); // Global ptr 8237 SDValue VOffset; 8238 // Try to split SAddr and VOffset. Global and LDS pointers share the same 8239 // immediate offset, so we cannot use a regular SelectGlobalSAddr(). 8240 if (Addr->isDivergent() && Addr.getOpcode() == ISD::ADD) { 8241 SDValue LHS = Addr.getOperand(0); 8242 SDValue RHS = Addr.getOperand(1); 8243 8244 if (LHS->isDivergent()) 8245 std::swap(LHS, RHS); 8246 8247 if (!LHS->isDivergent() && RHS.getOpcode() == ISD::ZERO_EXTEND && 8248 RHS.getOperand(0).getValueType() == MVT::i32) { 8249 // add (i64 sgpr), (zero_extend (i32 vgpr)) 8250 Addr = LHS; 8251 VOffset = RHS.getOperand(0); 8252 } 8253 } 8254 8255 Ops.push_back(Addr); 8256 if (!Addr->isDivergent()) { 8257 Opc = AMDGPU::getGlobalSaddrOp(Opc); 8258 if (!VOffset) 8259 VOffset = SDValue( 8260 DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, DL, MVT::i32, 8261 DAG.getTargetConstant(0, DL, MVT::i32)), 0); 8262 Ops.push_back(VOffset); 8263 } 8264 8265 Ops.push_back(Op.getOperand(5)); // Offset 8266 Ops.push_back(Op.getOperand(6)); // CPol 8267 Ops.push_back(M0Val.getValue(0)); // Chain 8268 Ops.push_back(M0Val.getValue(1)); // Glue 8269 8270 MachineMemOperand *LoadMMO = M->getMemOperand(); 8271 MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo(); 8272 LoadPtrI.Offset = Op->getConstantOperandVal(5); 8273 MachinePointerInfo StorePtrI = LoadPtrI; 8274 LoadPtrI.AddrSpace = AMDGPUAS::GLOBAL_ADDRESS; 8275 StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS; 8276 auto F = LoadMMO->getFlags() & 8277 ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad); 8278 LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad, 8279 Size, LoadMMO->getBaseAlign()); 8280 MachineMemOperand *StoreMMO = 8281 MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore, 8282 sizeof(int32_t), Align(4)); 8283 8284 auto Load = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops); 8285 DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO}); 8286 8287 return SDValue(Load, 0); 8288 } 8289 case Intrinsic::amdgcn_end_cf: 8290 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 8291 Op->getOperand(2), Chain), 0); 8292 8293 default: { 8294 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 8295 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 8296 return lowerImage(Op, ImageDimIntr, DAG, true); 8297 8298 return Op; 8299 } 8300 } 8301 } 8302 8303 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 8304 // offset (the offset that is included in bounds checking and swizzling, to be 8305 // split between the instruction's voffset and immoffset fields) and soffset 8306 // (the offset that is excluded from bounds checking and swizzling, to go in 8307 // the instruction's soffset field). This function takes the first kind of 8308 // offset and figures out how to split it between voffset and immoffset. 8309 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 8310 SDValue Offset, SelectionDAG &DAG) const { 8311 SDLoc DL(Offset); 8312 const unsigned MaxImm = 4095; 8313 SDValue N0 = Offset; 8314 ConstantSDNode *C1 = nullptr; 8315 8316 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 8317 N0 = SDValue(); 8318 else if (DAG.isBaseWithConstantOffset(N0)) { 8319 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 8320 N0 = N0.getOperand(0); 8321 } 8322 8323 if (C1) { 8324 unsigned ImmOffset = C1->getZExtValue(); 8325 // If the immediate value is too big for the immoffset field, put the value 8326 // and -4096 into the immoffset field so that the value that is copied/added 8327 // for the voffset field is a multiple of 4096, and it stands more chance 8328 // of being CSEd with the copy/add for another similar load/store. 8329 // However, do not do that rounding down to a multiple of 4096 if that is a 8330 // negative number, as it appears to be illegal to have a negative offset 8331 // in the vgpr, even if adding the immediate offset makes it positive. 8332 unsigned Overflow = ImmOffset & ~MaxImm; 8333 ImmOffset -= Overflow; 8334 if ((int32_t)Overflow < 0) { 8335 Overflow += ImmOffset; 8336 ImmOffset = 0; 8337 } 8338 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 8339 if (Overflow) { 8340 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 8341 if (!N0) 8342 N0 = OverflowVal; 8343 else { 8344 SDValue Ops[] = { N0, OverflowVal }; 8345 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 8346 } 8347 } 8348 } 8349 if (!N0) 8350 N0 = DAG.getConstant(0, DL, MVT::i32); 8351 if (!C1) 8352 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 8353 return {N0, SDValue(C1, 0)}; 8354 } 8355 8356 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 8357 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 8358 // pointed to by Offsets. 8359 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 8360 SelectionDAG &DAG, SDValue *Offsets, 8361 Align Alignment) const { 8362 SDLoc DL(CombinedOffset); 8363 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 8364 uint32_t Imm = C->getZExtValue(); 8365 uint32_t SOffset, ImmOffset; 8366 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 8367 Alignment)) { 8368 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 8369 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8370 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8371 return; 8372 } 8373 } 8374 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 8375 SDValue N0 = CombinedOffset.getOperand(0); 8376 SDValue N1 = CombinedOffset.getOperand(1); 8377 uint32_t SOffset, ImmOffset; 8378 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 8379 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 8380 Subtarget, Alignment)) { 8381 Offsets[0] = N0; 8382 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8383 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8384 return; 8385 } 8386 } 8387 Offsets[0] = CombinedOffset; 8388 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 8389 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 8390 } 8391 8392 // Handle 8 bit and 16 bit buffer loads 8393 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 8394 EVT LoadVT, SDLoc DL, 8395 ArrayRef<SDValue> Ops, 8396 MemSDNode *M) const { 8397 EVT IntVT = LoadVT.changeTypeToInteger(); 8398 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 8399 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 8400 8401 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 8402 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 8403 Ops, IntVT, 8404 M->getMemOperand()); 8405 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 8406 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 8407 8408 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 8409 } 8410 8411 // Handle 8 bit and 16 bit buffer stores 8412 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 8413 EVT VDataType, SDLoc DL, 8414 SDValue Ops[], 8415 MemSDNode *M) const { 8416 if (VDataType == MVT::f16) 8417 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 8418 8419 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 8420 Ops[1] = BufferStoreExt; 8421 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 8422 AMDGPUISD::BUFFER_STORE_SHORT; 8423 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 8424 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 8425 M->getMemOperand()); 8426 } 8427 8428 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 8429 ISD::LoadExtType ExtType, SDValue Op, 8430 const SDLoc &SL, EVT VT) { 8431 if (VT.bitsLT(Op.getValueType())) 8432 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 8433 8434 switch (ExtType) { 8435 case ISD::SEXTLOAD: 8436 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 8437 case ISD::ZEXTLOAD: 8438 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 8439 case ISD::EXTLOAD: 8440 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 8441 case ISD::NON_EXTLOAD: 8442 return Op; 8443 } 8444 8445 llvm_unreachable("invalid ext type"); 8446 } 8447 8448 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 8449 SelectionDAG &DAG = DCI.DAG; 8450 if (Ld->getAlign() < Align(4) || Ld->isDivergent()) 8451 return SDValue(); 8452 8453 // FIXME: Constant loads should all be marked invariant. 8454 unsigned AS = Ld->getAddressSpace(); 8455 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 8456 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 8457 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 8458 return SDValue(); 8459 8460 // Don't do this early, since it may interfere with adjacent load merging for 8461 // illegal types. We can avoid losing alignment information for exotic types 8462 // pre-legalize. 8463 EVT MemVT = Ld->getMemoryVT(); 8464 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 8465 MemVT.getSizeInBits() >= 32) 8466 return SDValue(); 8467 8468 SDLoc SL(Ld); 8469 8470 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 8471 "unexpected vector extload"); 8472 8473 // TODO: Drop only high part of range. 8474 SDValue Ptr = Ld->getBasePtr(); 8475 SDValue NewLoad = DAG.getLoad( 8476 ISD::UNINDEXED, ISD::NON_EXTLOAD, MVT::i32, SL, Ld->getChain(), Ptr, 8477 Ld->getOffset(), Ld->getPointerInfo(), MVT::i32, Ld->getAlign(), 8478 Ld->getMemOperand()->getFlags(), Ld->getAAInfo(), 8479 nullptr); // Drop ranges 8480 8481 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 8482 if (MemVT.isFloatingPoint()) { 8483 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 8484 "unexpected fp extload"); 8485 TruncVT = MemVT.changeTypeToInteger(); 8486 } 8487 8488 SDValue Cvt = NewLoad; 8489 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 8490 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 8491 DAG.getValueType(TruncVT)); 8492 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 8493 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 8494 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 8495 } else { 8496 assert(Ld->getExtensionType() == ISD::EXTLOAD); 8497 } 8498 8499 EVT VT = Ld->getValueType(0); 8500 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8501 8502 DCI.AddToWorklist(Cvt.getNode()); 8503 8504 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8505 // the appropriate extension from the 32-bit load. 8506 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8507 DCI.AddToWorklist(Cvt.getNode()); 8508 8509 // Handle conversion back to floating point if necessary. 8510 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8511 8512 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8513 } 8514 8515 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8516 SDLoc DL(Op); 8517 LoadSDNode *Load = cast<LoadSDNode>(Op); 8518 ISD::LoadExtType ExtType = Load->getExtensionType(); 8519 EVT MemVT = Load->getMemoryVT(); 8520 8521 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8522 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8523 return SDValue(); 8524 8525 // FIXME: Copied from PPC 8526 // First, load into 32 bits, then truncate to 1 bit. 8527 8528 SDValue Chain = Load->getChain(); 8529 SDValue BasePtr = Load->getBasePtr(); 8530 MachineMemOperand *MMO = Load->getMemOperand(); 8531 8532 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8533 8534 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8535 BasePtr, RealMemVT, MMO); 8536 8537 if (!MemVT.isVector()) { 8538 SDValue Ops[] = { 8539 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8540 NewLD.getValue(1) 8541 }; 8542 8543 return DAG.getMergeValues(Ops, DL); 8544 } 8545 8546 SmallVector<SDValue, 3> Elts; 8547 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8548 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8549 DAG.getConstant(I, DL, MVT::i32)); 8550 8551 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8552 } 8553 8554 SDValue Ops[] = { 8555 DAG.getBuildVector(MemVT, DL, Elts), 8556 NewLD.getValue(1) 8557 }; 8558 8559 return DAG.getMergeValues(Ops, DL); 8560 } 8561 8562 if (!MemVT.isVector()) 8563 return SDValue(); 8564 8565 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8566 "Custom lowering for non-i32 vectors hasn't been implemented."); 8567 8568 Align Alignment = Load->getAlign(); 8569 unsigned AS = Load->getAddressSpace(); 8570 if (Subtarget->hasLDSMisalignedBug() && AS == AMDGPUAS::FLAT_ADDRESS && 8571 Alignment.value() < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8572 return SplitVectorLoad(Op, DAG); 8573 } 8574 8575 MachineFunction &MF = DAG.getMachineFunction(); 8576 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8577 // If there is a possibility that flat instruction access scratch memory 8578 // then we need to use the same legalization rules we use for private. 8579 if (AS == AMDGPUAS::FLAT_ADDRESS && 8580 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8581 AS = MFI->hasFlatScratchInit() ? 8582 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8583 8584 unsigned NumElements = MemVT.getVectorNumElements(); 8585 8586 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8587 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8588 if (!Op->isDivergent() && Alignment >= Align(4) && NumElements < 32) { 8589 if (MemVT.isPow2VectorType()) 8590 return SDValue(); 8591 return WidenOrSplitVectorLoad(Op, DAG); 8592 } 8593 // Non-uniform loads will be selected to MUBUF instructions, so they 8594 // have the same legalization requirements as global and private 8595 // loads. 8596 // 8597 } 8598 8599 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8600 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8601 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8602 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8603 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8604 Alignment >= Align(4) && NumElements < 32) { 8605 if (MemVT.isPow2VectorType()) 8606 return SDValue(); 8607 return WidenOrSplitVectorLoad(Op, DAG); 8608 } 8609 // Non-uniform loads will be selected to MUBUF instructions, so they 8610 // have the same legalization requirements as global and private 8611 // loads. 8612 // 8613 } 8614 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8615 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8616 AS == AMDGPUAS::GLOBAL_ADDRESS || 8617 AS == AMDGPUAS::FLAT_ADDRESS) { 8618 if (NumElements > 4) 8619 return SplitVectorLoad(Op, DAG); 8620 // v3 loads not supported on SI. 8621 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8622 return WidenOrSplitVectorLoad(Op, DAG); 8623 8624 // v3 and v4 loads are supported for private and global memory. 8625 return SDValue(); 8626 } 8627 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8628 // Depending on the setting of the private_element_size field in the 8629 // resource descriptor, we can only make private accesses up to a certain 8630 // size. 8631 switch (Subtarget->getMaxPrivateElementSize()) { 8632 case 4: { 8633 SDValue Ops[2]; 8634 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8635 return DAG.getMergeValues(Ops, DL); 8636 } 8637 case 8: 8638 if (NumElements > 2) 8639 return SplitVectorLoad(Op, DAG); 8640 return SDValue(); 8641 case 16: 8642 // Same as global/flat 8643 if (NumElements > 4) 8644 return SplitVectorLoad(Op, DAG); 8645 // v3 loads not supported on SI. 8646 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8647 return WidenOrSplitVectorLoad(Op, DAG); 8648 8649 return SDValue(); 8650 default: 8651 llvm_unreachable("unsupported private_element_size"); 8652 } 8653 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8654 bool Fast = false; 8655 auto Flags = Load->getMemOperand()->getFlags(); 8656 if (allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8657 Load->getAlign(), Flags, &Fast) && 8658 Fast) 8659 return SDValue(); 8660 8661 if (MemVT.isVector()) 8662 return SplitVectorLoad(Op, DAG); 8663 } 8664 8665 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8666 MemVT, *Load->getMemOperand())) { 8667 SDValue Ops[2]; 8668 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8669 return DAG.getMergeValues(Ops, DL); 8670 } 8671 8672 return SDValue(); 8673 } 8674 8675 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8676 EVT VT = Op.getValueType(); 8677 if (VT.getSizeInBits() == 128) 8678 return splitTernaryVectorOp(Op, DAG); 8679 8680 assert(VT.getSizeInBits() == 64); 8681 8682 SDLoc DL(Op); 8683 SDValue Cond = Op.getOperand(0); 8684 8685 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8686 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8687 8688 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8689 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8690 8691 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8692 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8693 8694 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8695 8696 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8697 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8698 8699 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8700 8701 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8702 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8703 } 8704 8705 // Catch division cases where we can use shortcuts with rcp and rsq 8706 // instructions. 8707 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8708 SelectionDAG &DAG) const { 8709 SDLoc SL(Op); 8710 SDValue LHS = Op.getOperand(0); 8711 SDValue RHS = Op.getOperand(1); 8712 EVT VT = Op.getValueType(); 8713 const SDNodeFlags Flags = Op->getFlags(); 8714 8715 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8716 8717 // Without !fpmath accuracy information, we can't do more because we don't 8718 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8719 if (!AllowInaccurateRcp) 8720 return SDValue(); 8721 8722 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8723 if (CLHS->isExactlyValue(1.0)) { 8724 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8725 // the CI documentation has a worst case error of 1 ulp. 8726 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8727 // use it as long as we aren't trying to use denormals. 8728 // 8729 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8730 8731 // 1.0 / sqrt(x) -> rsq(x) 8732 8733 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8734 // error seems really high at 2^29 ULP. 8735 if (RHS.getOpcode() == ISD::FSQRT) 8736 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8737 8738 // 1.0 / x -> rcp(x) 8739 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8740 } 8741 8742 // Same as for 1.0, but expand the sign out of the constant. 8743 if (CLHS->isExactlyValue(-1.0)) { 8744 // -1.0 / x -> rcp (fneg x) 8745 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8746 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8747 } 8748 } 8749 8750 // Turn into multiply by the reciprocal. 8751 // x / y -> x * (1.0 / y) 8752 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8753 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8754 } 8755 8756 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8757 SelectionDAG &DAG) const { 8758 SDLoc SL(Op); 8759 SDValue X = Op.getOperand(0); 8760 SDValue Y = Op.getOperand(1); 8761 EVT VT = Op.getValueType(); 8762 const SDNodeFlags Flags = Op->getFlags(); 8763 8764 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8765 DAG.getTarget().Options.UnsafeFPMath; 8766 if (!AllowInaccurateDiv) 8767 return SDValue(); 8768 8769 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8770 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8771 8772 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8773 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8774 8775 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8776 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8777 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8778 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8779 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8780 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8781 } 8782 8783 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8784 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8785 SDNodeFlags Flags) { 8786 if (GlueChain->getNumValues() <= 1) { 8787 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8788 } 8789 8790 assert(GlueChain->getNumValues() == 3); 8791 8792 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8793 switch (Opcode) { 8794 default: llvm_unreachable("no chain equivalent for opcode"); 8795 case ISD::FMUL: 8796 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8797 break; 8798 } 8799 8800 return DAG.getNode(Opcode, SL, VTList, 8801 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8802 Flags); 8803 } 8804 8805 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8806 EVT VT, SDValue A, SDValue B, SDValue C, 8807 SDValue GlueChain, SDNodeFlags Flags) { 8808 if (GlueChain->getNumValues() <= 1) { 8809 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8810 } 8811 8812 assert(GlueChain->getNumValues() == 3); 8813 8814 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8815 switch (Opcode) { 8816 default: llvm_unreachable("no chain equivalent for opcode"); 8817 case ISD::FMA: 8818 Opcode = AMDGPUISD::FMA_W_CHAIN; 8819 break; 8820 } 8821 8822 return DAG.getNode(Opcode, SL, VTList, 8823 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8824 Flags); 8825 } 8826 8827 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8828 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8829 return FastLowered; 8830 8831 SDLoc SL(Op); 8832 SDValue Src0 = Op.getOperand(0); 8833 SDValue Src1 = Op.getOperand(1); 8834 8835 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8836 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8837 8838 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8839 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8840 8841 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8842 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8843 8844 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8845 } 8846 8847 // Faster 2.5 ULP division that does not support denormals. 8848 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8849 SDLoc SL(Op); 8850 SDValue LHS = Op.getOperand(1); 8851 SDValue RHS = Op.getOperand(2); 8852 8853 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8854 8855 const APFloat K0Val(BitsToFloat(0x6f800000)); 8856 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8857 8858 const APFloat K1Val(BitsToFloat(0x2f800000)); 8859 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8860 8861 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8862 8863 EVT SetCCVT = 8864 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8865 8866 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8867 8868 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8869 8870 // TODO: Should this propagate fast-math-flags? 8871 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8872 8873 // rcp does not support denormals. 8874 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8875 8876 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8877 8878 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8879 } 8880 8881 // Returns immediate value for setting the F32 denorm mode when using the 8882 // S_DENORM_MODE instruction. 8883 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8884 const SDLoc &SL, const GCNSubtarget *ST) { 8885 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8886 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8887 ? FP_DENORM_FLUSH_NONE 8888 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8889 8890 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8891 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8892 } 8893 8894 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8895 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8896 return FastLowered; 8897 8898 // The selection matcher assumes anything with a chain selecting to a 8899 // mayRaiseFPException machine instruction. Since we're introducing a chain 8900 // here, we need to explicitly report nofpexcept for the regular fdiv 8901 // lowering. 8902 SDNodeFlags Flags = Op->getFlags(); 8903 Flags.setNoFPExcept(true); 8904 8905 SDLoc SL(Op); 8906 SDValue LHS = Op.getOperand(0); 8907 SDValue RHS = Op.getOperand(1); 8908 8909 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8910 8911 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8912 8913 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8914 {RHS, RHS, LHS}, Flags); 8915 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8916 {LHS, RHS, LHS}, Flags); 8917 8918 // Denominator is scaled to not be denormal, so using rcp is ok. 8919 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8920 DenominatorScaled, Flags); 8921 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8922 DenominatorScaled, Flags); 8923 8924 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8925 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8926 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8927 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8928 8929 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8930 8931 if (!HasFP32Denormals) { 8932 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8933 // lowering. The chain dependence is insufficient, and we need glue. We do 8934 // not need the glue variants in a strictfp function. 8935 8936 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8937 8938 SDNode *EnableDenorm; 8939 if (Subtarget->hasDenormModeInst()) { 8940 const SDValue EnableDenormValue = 8941 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8942 8943 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8944 DAG.getEntryNode(), EnableDenormValue).getNode(); 8945 } else { 8946 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8947 SL, MVT::i32); 8948 EnableDenorm = 8949 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8950 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8951 } 8952 8953 SDValue Ops[3] = { 8954 NegDivScale0, 8955 SDValue(EnableDenorm, 0), 8956 SDValue(EnableDenorm, 1) 8957 }; 8958 8959 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8960 } 8961 8962 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8963 ApproxRcp, One, NegDivScale0, Flags); 8964 8965 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8966 ApproxRcp, Fma0, Flags); 8967 8968 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8969 Fma1, Fma1, Flags); 8970 8971 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8972 NumeratorScaled, Mul, Flags); 8973 8974 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8975 Fma2, Fma1, Mul, Fma2, Flags); 8976 8977 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8978 NumeratorScaled, Fma3, Flags); 8979 8980 if (!HasFP32Denormals) { 8981 SDNode *DisableDenorm; 8982 if (Subtarget->hasDenormModeInst()) { 8983 const SDValue DisableDenormValue = 8984 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8985 8986 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8987 Fma4.getValue(1), DisableDenormValue, 8988 Fma4.getValue(2)).getNode(); 8989 } else { 8990 const SDValue DisableDenormValue = 8991 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8992 8993 DisableDenorm = DAG.getMachineNode( 8994 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8995 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8996 } 8997 8998 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8999 SDValue(DisableDenorm, 0), DAG.getRoot()); 9000 DAG.setRoot(OutputChain); 9001 } 9002 9003 SDValue Scale = NumeratorScaled.getValue(1); 9004 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 9005 {Fma4, Fma1, Fma3, Scale}, Flags); 9006 9007 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 9008 } 9009 9010 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 9011 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 9012 return FastLowered; 9013 9014 SDLoc SL(Op); 9015 SDValue X = Op.getOperand(0); 9016 SDValue Y = Op.getOperand(1); 9017 9018 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 9019 9020 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 9021 9022 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 9023 9024 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 9025 9026 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 9027 9028 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 9029 9030 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 9031 9032 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 9033 9034 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 9035 9036 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 9037 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 9038 9039 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 9040 NegDivScale0, Mul, DivScale1); 9041 9042 SDValue Scale; 9043 9044 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 9045 // Workaround a hardware bug on SI where the condition output from div_scale 9046 // is not usable. 9047 9048 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 9049 9050 // Figure out if the scale to use for div_fmas. 9051 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 9052 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 9053 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 9054 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 9055 9056 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 9057 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 9058 9059 SDValue Scale0Hi 9060 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 9061 SDValue Scale1Hi 9062 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 9063 9064 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 9065 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 9066 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 9067 } else { 9068 Scale = DivScale1.getValue(1); 9069 } 9070 9071 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 9072 Fma4, Fma3, Mul, Scale); 9073 9074 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 9075 } 9076 9077 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 9078 EVT VT = Op.getValueType(); 9079 9080 if (VT == MVT::f32) 9081 return LowerFDIV32(Op, DAG); 9082 9083 if (VT == MVT::f64) 9084 return LowerFDIV64(Op, DAG); 9085 9086 if (VT == MVT::f16) 9087 return LowerFDIV16(Op, DAG); 9088 9089 llvm_unreachable("Unexpected type for fdiv"); 9090 } 9091 9092 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 9093 SDLoc DL(Op); 9094 StoreSDNode *Store = cast<StoreSDNode>(Op); 9095 EVT VT = Store->getMemoryVT(); 9096 9097 if (VT == MVT::i1) { 9098 return DAG.getTruncStore(Store->getChain(), DL, 9099 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 9100 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 9101 } 9102 9103 assert(VT.isVector() && 9104 Store->getValue().getValueType().getScalarType() == MVT::i32); 9105 9106 unsigned AS = Store->getAddressSpace(); 9107 if (Subtarget->hasLDSMisalignedBug() && 9108 AS == AMDGPUAS::FLAT_ADDRESS && 9109 Store->getAlign().value() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 9110 return SplitVectorStore(Op, DAG); 9111 } 9112 9113 MachineFunction &MF = DAG.getMachineFunction(); 9114 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 9115 // If there is a possibility that flat instruction access scratch memory 9116 // then we need to use the same legalization rules we use for private. 9117 if (AS == AMDGPUAS::FLAT_ADDRESS && 9118 !Subtarget->hasMultiDwordFlatScratchAddressing()) 9119 AS = MFI->hasFlatScratchInit() ? 9120 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 9121 9122 unsigned NumElements = VT.getVectorNumElements(); 9123 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 9124 AS == AMDGPUAS::FLAT_ADDRESS) { 9125 if (NumElements > 4) 9126 return SplitVectorStore(Op, DAG); 9127 // v3 stores not supported on SI. 9128 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 9129 return SplitVectorStore(Op, DAG); 9130 9131 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 9132 VT, *Store->getMemOperand())) 9133 return expandUnalignedStore(Store, DAG); 9134 9135 return SDValue(); 9136 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 9137 switch (Subtarget->getMaxPrivateElementSize()) { 9138 case 4: 9139 return scalarizeVectorStore(Store, DAG); 9140 case 8: 9141 if (NumElements > 2) 9142 return SplitVectorStore(Op, DAG); 9143 return SDValue(); 9144 case 16: 9145 if (NumElements > 4 || 9146 (NumElements == 3 && !Subtarget->enableFlatScratch())) 9147 return SplitVectorStore(Op, DAG); 9148 return SDValue(); 9149 default: 9150 llvm_unreachable("unsupported private_element_size"); 9151 } 9152 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 9153 bool Fast = false; 9154 auto Flags = Store->getMemOperand()->getFlags(); 9155 if (allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 9156 Store->getAlign(), Flags, &Fast) && 9157 Fast) 9158 return SDValue(); 9159 9160 if (VT.isVector()) 9161 return SplitVectorStore(Op, DAG); 9162 9163 return expandUnalignedStore(Store, DAG); 9164 } 9165 9166 // Probably an invalid store. If so we'll end up emitting a selection error. 9167 return SDValue(); 9168 } 9169 9170 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 9171 SDLoc DL(Op); 9172 EVT VT = Op.getValueType(); 9173 SDValue Arg = Op.getOperand(0); 9174 SDValue TrigVal; 9175 9176 // Propagate fast-math flags so that the multiply we introduce can be folded 9177 // if Arg is already the result of a multiply by constant. 9178 auto Flags = Op->getFlags(); 9179 9180 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 9181 9182 if (Subtarget->hasTrigReducedRange()) { 9183 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9184 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 9185 } else { 9186 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9187 } 9188 9189 switch (Op.getOpcode()) { 9190 case ISD::FCOS: 9191 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 9192 case ISD::FSIN: 9193 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 9194 default: 9195 llvm_unreachable("Wrong trig opcode"); 9196 } 9197 } 9198 9199 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 9200 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 9201 assert(AtomicNode->isCompareAndSwap()); 9202 unsigned AS = AtomicNode->getAddressSpace(); 9203 9204 // No custom lowering required for local address space 9205 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 9206 return Op; 9207 9208 // Non-local address space requires custom lowering for atomic compare 9209 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 9210 SDLoc DL(Op); 9211 SDValue ChainIn = Op.getOperand(0); 9212 SDValue Addr = Op.getOperand(1); 9213 SDValue Old = Op.getOperand(2); 9214 SDValue New = Op.getOperand(3); 9215 EVT VT = Op.getValueType(); 9216 MVT SimpleVT = VT.getSimpleVT(); 9217 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 9218 9219 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 9220 SDValue Ops[] = { ChainIn, Addr, NewOld }; 9221 9222 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 9223 Ops, VT, AtomicNode->getMemOperand()); 9224 } 9225 9226 //===----------------------------------------------------------------------===// 9227 // Custom DAG optimizations 9228 //===----------------------------------------------------------------------===// 9229 9230 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 9231 DAGCombinerInfo &DCI) const { 9232 EVT VT = N->getValueType(0); 9233 EVT ScalarVT = VT.getScalarType(); 9234 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 9235 return SDValue(); 9236 9237 SelectionDAG &DAG = DCI.DAG; 9238 SDLoc DL(N); 9239 9240 SDValue Src = N->getOperand(0); 9241 EVT SrcVT = Src.getValueType(); 9242 9243 // TODO: We could try to match extracting the higher bytes, which would be 9244 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 9245 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 9246 // about in practice. 9247 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 9248 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 9249 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 9250 DCI.AddToWorklist(Cvt.getNode()); 9251 9252 // For the f16 case, fold to a cast to f32 and then cast back to f16. 9253 if (ScalarVT != MVT::f32) { 9254 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 9255 DAG.getTargetConstant(0, DL, MVT::i32)); 9256 } 9257 return Cvt; 9258 } 9259 } 9260 9261 return SDValue(); 9262 } 9263 9264 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 9265 9266 // This is a variant of 9267 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 9268 // 9269 // The normal DAG combiner will do this, but only if the add has one use since 9270 // that would increase the number of instructions. 9271 // 9272 // This prevents us from seeing a constant offset that can be folded into a 9273 // memory instruction's addressing mode. If we know the resulting add offset of 9274 // a pointer can be folded into an addressing offset, we can replace the pointer 9275 // operand with the add of new constant offset. This eliminates one of the uses, 9276 // and may allow the remaining use to also be simplified. 9277 // 9278 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 9279 unsigned AddrSpace, 9280 EVT MemVT, 9281 DAGCombinerInfo &DCI) const { 9282 SDValue N0 = N->getOperand(0); 9283 SDValue N1 = N->getOperand(1); 9284 9285 // We only do this to handle cases where it's profitable when there are 9286 // multiple uses of the add, so defer to the standard combine. 9287 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 9288 N0->hasOneUse()) 9289 return SDValue(); 9290 9291 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 9292 if (!CN1) 9293 return SDValue(); 9294 9295 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 9296 if (!CAdd) 9297 return SDValue(); 9298 9299 // If the resulting offset is too large, we can't fold it into the addressing 9300 // mode offset. 9301 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 9302 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 9303 9304 AddrMode AM; 9305 AM.HasBaseReg = true; 9306 AM.BaseOffs = Offset.getSExtValue(); 9307 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 9308 return SDValue(); 9309 9310 SelectionDAG &DAG = DCI.DAG; 9311 SDLoc SL(N); 9312 EVT VT = N->getValueType(0); 9313 9314 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 9315 SDValue COffset = DAG.getConstant(Offset, SL, VT); 9316 9317 SDNodeFlags Flags; 9318 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 9319 (N0.getOpcode() == ISD::OR || 9320 N0->getFlags().hasNoUnsignedWrap())); 9321 9322 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 9323 } 9324 9325 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 9326 /// by the chain and intrinsic ID. Theoretically we would also need to check the 9327 /// specific intrinsic, but they all place the pointer operand first. 9328 static unsigned getBasePtrIndex(const MemSDNode *N) { 9329 switch (N->getOpcode()) { 9330 case ISD::STORE: 9331 case ISD::INTRINSIC_W_CHAIN: 9332 case ISD::INTRINSIC_VOID: 9333 return 2; 9334 default: 9335 return 1; 9336 } 9337 } 9338 9339 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 9340 DAGCombinerInfo &DCI) const { 9341 SelectionDAG &DAG = DCI.DAG; 9342 SDLoc SL(N); 9343 9344 unsigned PtrIdx = getBasePtrIndex(N); 9345 SDValue Ptr = N->getOperand(PtrIdx); 9346 9347 // TODO: We could also do this for multiplies. 9348 if (Ptr.getOpcode() == ISD::SHL) { 9349 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 9350 N->getMemoryVT(), DCI); 9351 if (NewPtr) { 9352 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 9353 9354 NewOps[PtrIdx] = NewPtr; 9355 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 9356 } 9357 } 9358 9359 return SDValue(); 9360 } 9361 9362 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 9363 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 9364 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 9365 (Opc == ISD::XOR && Val == 0); 9366 } 9367 9368 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 9369 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 9370 // integer combine opportunities since most 64-bit operations are decomposed 9371 // this way. TODO: We won't want this for SALU especially if it is an inline 9372 // immediate. 9373 SDValue SITargetLowering::splitBinaryBitConstantOp( 9374 DAGCombinerInfo &DCI, 9375 const SDLoc &SL, 9376 unsigned Opc, SDValue LHS, 9377 const ConstantSDNode *CRHS) const { 9378 uint64_t Val = CRHS->getZExtValue(); 9379 uint32_t ValLo = Lo_32(Val); 9380 uint32_t ValHi = Hi_32(Val); 9381 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9382 9383 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 9384 bitOpWithConstantIsReducible(Opc, ValHi)) || 9385 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 9386 // If we need to materialize a 64-bit immediate, it will be split up later 9387 // anyway. Avoid creating the harder to understand 64-bit immediate 9388 // materialization. 9389 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 9390 } 9391 9392 return SDValue(); 9393 } 9394 9395 // Returns true if argument is a boolean value which is not serialized into 9396 // memory or argument and does not require v_cndmask_b32 to be deserialized. 9397 static bool isBoolSGPR(SDValue V) { 9398 if (V.getValueType() != MVT::i1) 9399 return false; 9400 switch (V.getOpcode()) { 9401 default: 9402 break; 9403 case ISD::SETCC: 9404 case AMDGPUISD::FP_CLASS: 9405 return true; 9406 case ISD::AND: 9407 case ISD::OR: 9408 case ISD::XOR: 9409 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 9410 } 9411 return false; 9412 } 9413 9414 // If a constant has all zeroes or all ones within each byte return it. 9415 // Otherwise return 0. 9416 static uint32_t getConstantPermuteMask(uint32_t C) { 9417 // 0xff for any zero byte in the mask 9418 uint32_t ZeroByteMask = 0; 9419 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 9420 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 9421 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 9422 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 9423 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 9424 if ((NonZeroByteMask & C) != NonZeroByteMask) 9425 return 0; // Partial bytes selected. 9426 return C; 9427 } 9428 9429 // Check if a node selects whole bytes from its operand 0 starting at a byte 9430 // boundary while masking the rest. Returns select mask as in the v_perm_b32 9431 // or -1 if not succeeded. 9432 // Note byte select encoding: 9433 // value 0-3 selects corresponding source byte; 9434 // value 0xc selects zero; 9435 // value 0xff selects 0xff. 9436 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 9437 assert(V.getValueSizeInBits() == 32); 9438 9439 if (V.getNumOperands() != 2) 9440 return ~0; 9441 9442 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 9443 if (!N1) 9444 return ~0; 9445 9446 uint32_t C = N1->getZExtValue(); 9447 9448 switch (V.getOpcode()) { 9449 default: 9450 break; 9451 case ISD::AND: 9452 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9453 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 9454 } 9455 break; 9456 9457 case ISD::OR: 9458 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9459 return (0x03020100 & ~ConstMask) | ConstMask; 9460 } 9461 break; 9462 9463 case ISD::SHL: 9464 if (C % 8) 9465 return ~0; 9466 9467 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 9468 9469 case ISD::SRL: 9470 if (C % 8) 9471 return ~0; 9472 9473 return uint32_t(0x0c0c0c0c03020100ull >> C); 9474 } 9475 9476 return ~0; 9477 } 9478 9479 SDValue SITargetLowering::performAndCombine(SDNode *N, 9480 DAGCombinerInfo &DCI) const { 9481 if (DCI.isBeforeLegalize()) 9482 return SDValue(); 9483 9484 SelectionDAG &DAG = DCI.DAG; 9485 EVT VT = N->getValueType(0); 9486 SDValue LHS = N->getOperand(0); 9487 SDValue RHS = N->getOperand(1); 9488 9489 9490 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9491 if (VT == MVT::i64 && CRHS) { 9492 if (SDValue Split 9493 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9494 return Split; 9495 } 9496 9497 if (CRHS && VT == MVT::i32) { 9498 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9499 // nb = number of trailing zeroes in mask 9500 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9501 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9502 uint64_t Mask = CRHS->getZExtValue(); 9503 unsigned Bits = countPopulation(Mask); 9504 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9505 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9506 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9507 unsigned Shift = CShift->getZExtValue(); 9508 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9509 unsigned Offset = NB + Shift; 9510 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9511 SDLoc SL(N); 9512 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9513 LHS->getOperand(0), 9514 DAG.getConstant(Offset, SL, MVT::i32), 9515 DAG.getConstant(Bits, SL, MVT::i32)); 9516 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9517 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9518 DAG.getValueType(NarrowVT)); 9519 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9520 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9521 return Shl; 9522 } 9523 } 9524 } 9525 9526 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9527 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9528 isa<ConstantSDNode>(LHS.getOperand(2))) { 9529 uint32_t Sel = getConstantPermuteMask(Mask); 9530 if (!Sel) 9531 return SDValue(); 9532 9533 // Select 0xc for all zero bytes 9534 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9535 SDLoc DL(N); 9536 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9537 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9538 } 9539 } 9540 9541 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9542 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9543 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9544 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9545 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9546 9547 SDValue X = LHS.getOperand(0); 9548 SDValue Y = RHS.getOperand(0); 9549 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9550 return SDValue(); 9551 9552 if (LCC == ISD::SETO) { 9553 if (X != LHS.getOperand(1)) 9554 return SDValue(); 9555 9556 if (RCC == ISD::SETUNE) { 9557 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9558 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9559 return SDValue(); 9560 9561 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9562 SIInstrFlags::N_SUBNORMAL | 9563 SIInstrFlags::N_ZERO | 9564 SIInstrFlags::P_ZERO | 9565 SIInstrFlags::P_SUBNORMAL | 9566 SIInstrFlags::P_NORMAL; 9567 9568 static_assert(((~(SIInstrFlags::S_NAN | 9569 SIInstrFlags::Q_NAN | 9570 SIInstrFlags::N_INFINITY | 9571 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9572 "mask not equal"); 9573 9574 SDLoc DL(N); 9575 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9576 X, DAG.getConstant(Mask, DL, MVT::i32)); 9577 } 9578 } 9579 } 9580 9581 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9582 std::swap(LHS, RHS); 9583 9584 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9585 RHS.hasOneUse()) { 9586 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9587 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9588 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9589 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9590 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9591 (RHS.getOperand(0) == LHS.getOperand(0) && 9592 LHS.getOperand(0) == LHS.getOperand(1))) { 9593 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9594 unsigned NewMask = LCC == ISD::SETO ? 9595 Mask->getZExtValue() & ~OrdMask : 9596 Mask->getZExtValue() & OrdMask; 9597 9598 SDLoc DL(N); 9599 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9600 DAG.getConstant(NewMask, DL, MVT::i32)); 9601 } 9602 } 9603 9604 if (VT == MVT::i32 && 9605 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9606 // and x, (sext cc from i1) => select cc, x, 0 9607 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9608 std::swap(LHS, RHS); 9609 if (isBoolSGPR(RHS.getOperand(0))) 9610 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9611 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9612 } 9613 9614 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9615 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9616 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9617 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9618 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9619 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9620 if (LHSMask != ~0u && RHSMask != ~0u) { 9621 // Canonicalize the expression in an attempt to have fewer unique masks 9622 // and therefore fewer registers used to hold the masks. 9623 if (LHSMask > RHSMask) { 9624 std::swap(LHSMask, RHSMask); 9625 std::swap(LHS, RHS); 9626 } 9627 9628 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9629 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9630 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9631 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9632 9633 // Check of we need to combine values from two sources within a byte. 9634 if (!(LHSUsedLanes & RHSUsedLanes) && 9635 // If we select high and lower word keep it for SDWA. 9636 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9637 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9638 // Each byte in each mask is either selector mask 0-3, or has higher 9639 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9640 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9641 // mask which is not 0xff wins. By anding both masks we have a correct 9642 // result except that 0x0c shall be corrected to give 0x0c only. 9643 uint32_t Mask = LHSMask & RHSMask; 9644 for (unsigned I = 0; I < 32; I += 8) { 9645 uint32_t ByteSel = 0xff << I; 9646 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9647 Mask &= (0x0c << I) & 0xffffffff; 9648 } 9649 9650 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9651 // or 0x0c. 9652 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9653 SDLoc DL(N); 9654 9655 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9656 LHS.getOperand(0), RHS.getOperand(0), 9657 DAG.getConstant(Sel, DL, MVT::i32)); 9658 } 9659 } 9660 } 9661 9662 return SDValue(); 9663 } 9664 9665 SDValue SITargetLowering::performOrCombine(SDNode *N, 9666 DAGCombinerInfo &DCI) const { 9667 SelectionDAG &DAG = DCI.DAG; 9668 SDValue LHS = N->getOperand(0); 9669 SDValue RHS = N->getOperand(1); 9670 9671 EVT VT = N->getValueType(0); 9672 if (VT == MVT::i1) { 9673 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9674 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9675 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9676 SDValue Src = LHS.getOperand(0); 9677 if (Src != RHS.getOperand(0)) 9678 return SDValue(); 9679 9680 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9681 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9682 if (!CLHS || !CRHS) 9683 return SDValue(); 9684 9685 // Only 10 bits are used. 9686 static const uint32_t MaxMask = 0x3ff; 9687 9688 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9689 SDLoc DL(N); 9690 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9691 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9692 } 9693 9694 return SDValue(); 9695 } 9696 9697 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9698 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9699 LHS.getOpcode() == AMDGPUISD::PERM && 9700 isa<ConstantSDNode>(LHS.getOperand(2))) { 9701 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9702 if (!Sel) 9703 return SDValue(); 9704 9705 Sel |= LHS.getConstantOperandVal(2); 9706 SDLoc DL(N); 9707 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9708 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9709 } 9710 9711 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9712 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9713 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9714 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9715 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9716 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9717 if (LHSMask != ~0u && RHSMask != ~0u) { 9718 // Canonicalize the expression in an attempt to have fewer unique masks 9719 // and therefore fewer registers used to hold the masks. 9720 if (LHSMask > RHSMask) { 9721 std::swap(LHSMask, RHSMask); 9722 std::swap(LHS, RHS); 9723 } 9724 9725 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9726 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9727 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9728 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9729 9730 // Check of we need to combine values from two sources within a byte. 9731 if (!(LHSUsedLanes & RHSUsedLanes) && 9732 // If we select high and lower word keep it for SDWA. 9733 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9734 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9735 // Kill zero bytes selected by other mask. Zero value is 0xc. 9736 LHSMask &= ~RHSUsedLanes; 9737 RHSMask &= ~LHSUsedLanes; 9738 // Add 4 to each active LHS lane 9739 LHSMask |= LHSUsedLanes & 0x04040404; 9740 // Combine masks 9741 uint32_t Sel = LHSMask | RHSMask; 9742 SDLoc DL(N); 9743 9744 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9745 LHS.getOperand(0), RHS.getOperand(0), 9746 DAG.getConstant(Sel, DL, MVT::i32)); 9747 } 9748 } 9749 } 9750 9751 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9752 return SDValue(); 9753 9754 // TODO: This could be a generic combine with a predicate for extracting the 9755 // high half of an integer being free. 9756 9757 // (or i64:x, (zero_extend i32:y)) -> 9758 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9759 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9760 RHS.getOpcode() != ISD::ZERO_EXTEND) 9761 std::swap(LHS, RHS); 9762 9763 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9764 SDValue ExtSrc = RHS.getOperand(0); 9765 EVT SrcVT = ExtSrc.getValueType(); 9766 if (SrcVT == MVT::i32) { 9767 SDLoc SL(N); 9768 SDValue LowLHS, HiBits; 9769 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9770 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9771 9772 DCI.AddToWorklist(LowOr.getNode()); 9773 DCI.AddToWorklist(HiBits.getNode()); 9774 9775 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9776 LowOr, HiBits); 9777 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9778 } 9779 } 9780 9781 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9782 if (CRHS) { 9783 if (SDValue Split 9784 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, 9785 N->getOperand(0), CRHS)) 9786 return Split; 9787 } 9788 9789 return SDValue(); 9790 } 9791 9792 SDValue SITargetLowering::performXorCombine(SDNode *N, 9793 DAGCombinerInfo &DCI) const { 9794 if (SDValue RV = reassociateScalarOps(N, DCI.DAG)) 9795 return RV; 9796 9797 EVT VT = N->getValueType(0); 9798 if (VT != MVT::i64) 9799 return SDValue(); 9800 9801 SDValue LHS = N->getOperand(0); 9802 SDValue RHS = N->getOperand(1); 9803 9804 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9805 if (CRHS) { 9806 if (SDValue Split 9807 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9808 return Split; 9809 } 9810 9811 return SDValue(); 9812 } 9813 9814 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9815 DAGCombinerInfo &DCI) const { 9816 if (!Subtarget->has16BitInsts() || 9817 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9818 return SDValue(); 9819 9820 EVT VT = N->getValueType(0); 9821 if (VT != MVT::i32) 9822 return SDValue(); 9823 9824 SDValue Src = N->getOperand(0); 9825 if (Src.getValueType() != MVT::i16) 9826 return SDValue(); 9827 9828 return SDValue(); 9829 } 9830 9831 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9832 DAGCombinerInfo &DCI) 9833 const { 9834 SDValue Src = N->getOperand(0); 9835 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9836 9837 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9838 VTSign->getVT() == MVT::i8) || 9839 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9840 VTSign->getVT() == MVT::i16)) && 9841 Src.hasOneUse()) { 9842 auto *M = cast<MemSDNode>(Src); 9843 SDValue Ops[] = { 9844 Src.getOperand(0), // Chain 9845 Src.getOperand(1), // rsrc 9846 Src.getOperand(2), // vindex 9847 Src.getOperand(3), // voffset 9848 Src.getOperand(4), // soffset 9849 Src.getOperand(5), // offset 9850 Src.getOperand(6), 9851 Src.getOperand(7) 9852 }; 9853 // replace with BUFFER_LOAD_BYTE/SHORT 9854 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9855 Src.getOperand(0).getValueType()); 9856 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9857 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9858 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9859 ResList, 9860 Ops, M->getMemoryVT(), 9861 M->getMemOperand()); 9862 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9863 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9864 } 9865 return SDValue(); 9866 } 9867 9868 SDValue SITargetLowering::performClassCombine(SDNode *N, 9869 DAGCombinerInfo &DCI) const { 9870 SelectionDAG &DAG = DCI.DAG; 9871 SDValue Mask = N->getOperand(1); 9872 9873 // fp_class x, 0 -> false 9874 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9875 if (CMask->isZero()) 9876 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9877 } 9878 9879 if (N->getOperand(0).isUndef()) 9880 return DAG.getUNDEF(MVT::i1); 9881 9882 return SDValue(); 9883 } 9884 9885 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9886 DAGCombinerInfo &DCI) const { 9887 EVT VT = N->getValueType(0); 9888 SDValue N0 = N->getOperand(0); 9889 9890 if (N0.isUndef()) 9891 return N0; 9892 9893 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9894 N0.getOpcode() == ISD::SINT_TO_FP)) { 9895 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9896 N->getFlags()); 9897 } 9898 9899 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9900 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9901 N0.getOperand(0), N->getFlags()); 9902 } 9903 9904 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9905 } 9906 9907 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9908 unsigned MaxDepth) const { 9909 unsigned Opcode = Op.getOpcode(); 9910 if (Opcode == ISD::FCANONICALIZE) 9911 return true; 9912 9913 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9914 auto F = CFP->getValueAPF(); 9915 if (F.isNaN() && F.isSignaling()) 9916 return false; 9917 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9918 } 9919 9920 // If source is a result of another standard FP operation it is already in 9921 // canonical form. 9922 if (MaxDepth == 0) 9923 return false; 9924 9925 switch (Opcode) { 9926 // These will flush denorms if required. 9927 case ISD::FADD: 9928 case ISD::FSUB: 9929 case ISD::FMUL: 9930 case ISD::FCEIL: 9931 case ISD::FFLOOR: 9932 case ISD::FMA: 9933 case ISD::FMAD: 9934 case ISD::FSQRT: 9935 case ISD::FDIV: 9936 case ISD::FREM: 9937 case ISD::FP_ROUND: 9938 case ISD::FP_EXTEND: 9939 case AMDGPUISD::FMUL_LEGACY: 9940 case AMDGPUISD::FMAD_FTZ: 9941 case AMDGPUISD::RCP: 9942 case AMDGPUISD::RSQ: 9943 case AMDGPUISD::RSQ_CLAMP: 9944 case AMDGPUISD::RCP_LEGACY: 9945 case AMDGPUISD::RCP_IFLAG: 9946 case AMDGPUISD::DIV_SCALE: 9947 case AMDGPUISD::DIV_FMAS: 9948 case AMDGPUISD::DIV_FIXUP: 9949 case AMDGPUISD::FRACT: 9950 case AMDGPUISD::LDEXP: 9951 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9952 case AMDGPUISD::CVT_F32_UBYTE0: 9953 case AMDGPUISD::CVT_F32_UBYTE1: 9954 case AMDGPUISD::CVT_F32_UBYTE2: 9955 case AMDGPUISD::CVT_F32_UBYTE3: 9956 return true; 9957 9958 // It can/will be lowered or combined as a bit operation. 9959 // Need to check their input recursively to handle. 9960 case ISD::FNEG: 9961 case ISD::FABS: 9962 case ISD::FCOPYSIGN: 9963 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9964 9965 case ISD::FSIN: 9966 case ISD::FCOS: 9967 case ISD::FSINCOS: 9968 return Op.getValueType().getScalarType() != MVT::f16; 9969 9970 case ISD::FMINNUM: 9971 case ISD::FMAXNUM: 9972 case ISD::FMINNUM_IEEE: 9973 case ISD::FMAXNUM_IEEE: 9974 case AMDGPUISD::CLAMP: 9975 case AMDGPUISD::FMED3: 9976 case AMDGPUISD::FMAX3: 9977 case AMDGPUISD::FMIN3: { 9978 // FIXME: Shouldn't treat the generic operations different based these. 9979 // However, we aren't really required to flush the result from 9980 // minnum/maxnum.. 9981 9982 // snans will be quieted, so we only need to worry about denormals. 9983 if (Subtarget->supportsMinMaxDenormModes() || 9984 denormalsEnabledForType(DAG, Op.getValueType())) 9985 return true; 9986 9987 // Flushing may be required. 9988 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9989 // targets need to check their input recursively. 9990 9991 // FIXME: Does this apply with clamp? It's implemented with max. 9992 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9993 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9994 return false; 9995 } 9996 9997 return true; 9998 } 9999 case ISD::SELECT: { 10000 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 10001 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 10002 } 10003 case ISD::BUILD_VECTOR: { 10004 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 10005 SDValue SrcOp = Op.getOperand(i); 10006 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 10007 return false; 10008 } 10009 10010 return true; 10011 } 10012 case ISD::EXTRACT_VECTOR_ELT: 10013 case ISD::EXTRACT_SUBVECTOR: { 10014 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 10015 } 10016 case ISD::INSERT_VECTOR_ELT: { 10017 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 10018 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 10019 } 10020 case ISD::UNDEF: 10021 // Could be anything. 10022 return false; 10023 10024 case ISD::BITCAST: 10025 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 10026 case ISD::TRUNCATE: { 10027 // Hack round the mess we make when legalizing extract_vector_elt 10028 if (Op.getValueType() == MVT::i16) { 10029 SDValue TruncSrc = Op.getOperand(0); 10030 if (TruncSrc.getValueType() == MVT::i32 && 10031 TruncSrc.getOpcode() == ISD::BITCAST && 10032 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 10033 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 10034 } 10035 } 10036 return false; 10037 } 10038 case ISD::INTRINSIC_WO_CHAIN: { 10039 unsigned IntrinsicID 10040 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10041 // TODO: Handle more intrinsics 10042 switch (IntrinsicID) { 10043 case Intrinsic::amdgcn_cvt_pkrtz: 10044 case Intrinsic::amdgcn_cubeid: 10045 case Intrinsic::amdgcn_frexp_mant: 10046 case Intrinsic::amdgcn_fdot2: 10047 case Intrinsic::amdgcn_rcp: 10048 case Intrinsic::amdgcn_rsq: 10049 case Intrinsic::amdgcn_rsq_clamp: 10050 case Intrinsic::amdgcn_rcp_legacy: 10051 case Intrinsic::amdgcn_rsq_legacy: 10052 case Intrinsic::amdgcn_trig_preop: 10053 return true; 10054 default: 10055 break; 10056 } 10057 10058 LLVM_FALLTHROUGH; 10059 } 10060 default: 10061 return denormalsEnabledForType(DAG, Op.getValueType()) && 10062 DAG.isKnownNeverSNaN(Op); 10063 } 10064 10065 llvm_unreachable("invalid operation"); 10066 } 10067 10068 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 10069 unsigned MaxDepth) const { 10070 MachineRegisterInfo &MRI = MF.getRegInfo(); 10071 MachineInstr *MI = MRI.getVRegDef(Reg); 10072 unsigned Opcode = MI->getOpcode(); 10073 10074 if (Opcode == AMDGPU::G_FCANONICALIZE) 10075 return true; 10076 10077 Optional<FPValueAndVReg> FCR; 10078 // Constant splat (can be padded with undef) or scalar constant. 10079 if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) { 10080 if (FCR->Value.isSignaling()) 10081 return false; 10082 return !FCR->Value.isDenormal() || 10083 denormalsEnabledForType(MRI.getType(FCR->VReg), MF); 10084 } 10085 10086 if (MaxDepth == 0) 10087 return false; 10088 10089 switch (Opcode) { 10090 case AMDGPU::G_FMINNUM_IEEE: 10091 case AMDGPU::G_FMAXNUM_IEEE: { 10092 if (Subtarget->supportsMinMaxDenormModes() || 10093 denormalsEnabledForType(MRI.getType(Reg), MF)) 10094 return true; 10095 for (const MachineOperand &MO : llvm::drop_begin(MI->operands())) 10096 if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1)) 10097 return false; 10098 return true; 10099 } 10100 default: 10101 return denormalsEnabledForType(MRI.getType(Reg), MF) && 10102 isKnownNeverSNaN(Reg, MRI); 10103 } 10104 10105 llvm_unreachable("invalid operation"); 10106 } 10107 10108 // Constant fold canonicalize. 10109 SDValue SITargetLowering::getCanonicalConstantFP( 10110 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 10111 // Flush denormals to 0 if not enabled. 10112 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 10113 return DAG.getConstantFP(0.0, SL, VT); 10114 10115 if (C.isNaN()) { 10116 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 10117 if (C.isSignaling()) { 10118 // Quiet a signaling NaN. 10119 // FIXME: Is this supposed to preserve payload bits? 10120 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 10121 } 10122 10123 // Make sure it is the canonical NaN bitpattern. 10124 // 10125 // TODO: Can we use -1 as the canonical NaN value since it's an inline 10126 // immediate? 10127 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 10128 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 10129 } 10130 10131 // Already canonical. 10132 return DAG.getConstantFP(C, SL, VT); 10133 } 10134 10135 static bool vectorEltWillFoldAway(SDValue Op) { 10136 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 10137 } 10138 10139 SDValue SITargetLowering::performFCanonicalizeCombine( 10140 SDNode *N, 10141 DAGCombinerInfo &DCI) const { 10142 SelectionDAG &DAG = DCI.DAG; 10143 SDValue N0 = N->getOperand(0); 10144 EVT VT = N->getValueType(0); 10145 10146 // fcanonicalize undef -> qnan 10147 if (N0.isUndef()) { 10148 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 10149 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 10150 } 10151 10152 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 10153 EVT VT = N->getValueType(0); 10154 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 10155 } 10156 10157 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 10158 // (fcanonicalize k) 10159 // 10160 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 10161 10162 // TODO: This could be better with wider vectors that will be split to v2f16, 10163 // and to consider uses since there aren't that many packed operations. 10164 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 10165 isTypeLegal(MVT::v2f16)) { 10166 SDLoc SL(N); 10167 SDValue NewElts[2]; 10168 SDValue Lo = N0.getOperand(0); 10169 SDValue Hi = N0.getOperand(1); 10170 EVT EltVT = Lo.getValueType(); 10171 10172 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 10173 for (unsigned I = 0; I != 2; ++I) { 10174 SDValue Op = N0.getOperand(I); 10175 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 10176 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 10177 CFP->getValueAPF()); 10178 } else if (Op.isUndef()) { 10179 // Handled below based on what the other operand is. 10180 NewElts[I] = Op; 10181 } else { 10182 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 10183 } 10184 } 10185 10186 // If one half is undef, and one is constant, prefer a splat vector rather 10187 // than the normal qNaN. If it's a register, prefer 0.0 since that's 10188 // cheaper to use and may be free with a packed operation. 10189 if (NewElts[0].isUndef()) { 10190 if (isa<ConstantFPSDNode>(NewElts[1])) 10191 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 10192 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 10193 } 10194 10195 if (NewElts[1].isUndef()) { 10196 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 10197 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 10198 } 10199 10200 return DAG.getBuildVector(VT, SL, NewElts); 10201 } 10202 } 10203 10204 unsigned SrcOpc = N0.getOpcode(); 10205 10206 // If it's free to do so, push canonicalizes further up the source, which may 10207 // find a canonical source. 10208 // 10209 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 10210 // sNaNs. 10211 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 10212 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 10213 if (CRHS && N0.hasOneUse()) { 10214 SDLoc SL(N); 10215 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 10216 N0.getOperand(0)); 10217 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 10218 DCI.AddToWorklist(Canon0.getNode()); 10219 10220 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 10221 } 10222 } 10223 10224 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 10225 } 10226 10227 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 10228 switch (Opc) { 10229 case ISD::FMAXNUM: 10230 case ISD::FMAXNUM_IEEE: 10231 return AMDGPUISD::FMAX3; 10232 case ISD::SMAX: 10233 return AMDGPUISD::SMAX3; 10234 case ISD::UMAX: 10235 return AMDGPUISD::UMAX3; 10236 case ISD::FMINNUM: 10237 case ISD::FMINNUM_IEEE: 10238 return AMDGPUISD::FMIN3; 10239 case ISD::SMIN: 10240 return AMDGPUISD::SMIN3; 10241 case ISD::UMIN: 10242 return AMDGPUISD::UMIN3; 10243 default: 10244 llvm_unreachable("Not a min/max opcode"); 10245 } 10246 } 10247 10248 SDValue SITargetLowering::performIntMed3ImmCombine( 10249 SelectionDAG &DAG, const SDLoc &SL, 10250 SDValue Op0, SDValue Op1, bool Signed) const { 10251 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 10252 if (!K1) 10253 return SDValue(); 10254 10255 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 10256 if (!K0) 10257 return SDValue(); 10258 10259 if (Signed) { 10260 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 10261 return SDValue(); 10262 } else { 10263 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 10264 return SDValue(); 10265 } 10266 10267 EVT VT = K0->getValueType(0); 10268 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 10269 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 10270 return DAG.getNode(Med3Opc, SL, VT, 10271 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 10272 } 10273 10274 // If there isn't a 16-bit med3 operation, convert to 32-bit. 10275 if (VT == MVT::i16) { 10276 MVT NVT = MVT::i32; 10277 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 10278 10279 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 10280 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 10281 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 10282 10283 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 10284 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 10285 } 10286 10287 return SDValue(); 10288 } 10289 10290 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 10291 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 10292 return C; 10293 10294 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 10295 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 10296 return C; 10297 } 10298 10299 return nullptr; 10300 } 10301 10302 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 10303 const SDLoc &SL, 10304 SDValue Op0, 10305 SDValue Op1) const { 10306 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 10307 if (!K1) 10308 return SDValue(); 10309 10310 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 10311 if (!K0) 10312 return SDValue(); 10313 10314 // Ordered >= (although NaN inputs should have folded away by now). 10315 if (K0->getValueAPF() > K1->getValueAPF()) 10316 return SDValue(); 10317 10318 const MachineFunction &MF = DAG.getMachineFunction(); 10319 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10320 10321 // TODO: Check IEEE bit enabled? 10322 EVT VT = Op0.getValueType(); 10323 if (Info->getMode().DX10Clamp) { 10324 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 10325 // hardware fmed3 behavior converting to a min. 10326 // FIXME: Should this be allowing -0.0? 10327 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 10328 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 10329 } 10330 10331 // med3 for f16 is only available on gfx9+, and not available for v2f16. 10332 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 10333 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 10334 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 10335 // then give the other result, which is different from med3 with a NaN 10336 // input. 10337 SDValue Var = Op0.getOperand(0); 10338 if (!DAG.isKnownNeverSNaN(Var)) 10339 return SDValue(); 10340 10341 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10342 10343 if ((!K0->hasOneUse() || 10344 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 10345 (!K1->hasOneUse() || 10346 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 10347 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 10348 Var, SDValue(K0, 0), SDValue(K1, 0)); 10349 } 10350 } 10351 10352 return SDValue(); 10353 } 10354 10355 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 10356 DAGCombinerInfo &DCI) const { 10357 SelectionDAG &DAG = DCI.DAG; 10358 10359 EVT VT = N->getValueType(0); 10360 unsigned Opc = N->getOpcode(); 10361 SDValue Op0 = N->getOperand(0); 10362 SDValue Op1 = N->getOperand(1); 10363 10364 // Only do this if the inner op has one use since this will just increases 10365 // register pressure for no benefit. 10366 10367 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 10368 !VT.isVector() && 10369 (VT == MVT::i32 || VT == MVT::f32 || 10370 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 10371 // max(max(a, b), c) -> max3(a, b, c) 10372 // min(min(a, b), c) -> min3(a, b, c) 10373 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 10374 SDLoc DL(N); 10375 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10376 DL, 10377 N->getValueType(0), 10378 Op0.getOperand(0), 10379 Op0.getOperand(1), 10380 Op1); 10381 } 10382 10383 // Try commuted. 10384 // max(a, max(b, c)) -> max3(a, b, c) 10385 // min(a, min(b, c)) -> min3(a, b, c) 10386 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 10387 SDLoc DL(N); 10388 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10389 DL, 10390 N->getValueType(0), 10391 Op0, 10392 Op1.getOperand(0), 10393 Op1.getOperand(1)); 10394 } 10395 } 10396 10397 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 10398 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 10399 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 10400 return Med3; 10401 } 10402 10403 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 10404 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 10405 return Med3; 10406 } 10407 10408 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 10409 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 10410 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 10411 (Opc == AMDGPUISD::FMIN_LEGACY && 10412 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 10413 (VT == MVT::f32 || VT == MVT::f64 || 10414 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 10415 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 10416 Op0.hasOneUse()) { 10417 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 10418 return Res; 10419 } 10420 10421 return SDValue(); 10422 } 10423 10424 static bool isClampZeroToOne(SDValue A, SDValue B) { 10425 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 10426 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 10427 // FIXME: Should this be allowing -0.0? 10428 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 10429 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 10430 } 10431 } 10432 10433 return false; 10434 } 10435 10436 // FIXME: Should only worry about snans for version with chain. 10437 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10438 DAGCombinerInfo &DCI) const { 10439 EVT VT = N->getValueType(0); 10440 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10441 // NaNs. With a NaN input, the order of the operands may change the result. 10442 10443 SelectionDAG &DAG = DCI.DAG; 10444 SDLoc SL(N); 10445 10446 SDValue Src0 = N->getOperand(0); 10447 SDValue Src1 = N->getOperand(1); 10448 SDValue Src2 = N->getOperand(2); 10449 10450 if (isClampZeroToOne(Src0, Src1)) { 10451 // const_a, const_b, x -> clamp is safe in all cases including signaling 10452 // nans. 10453 // FIXME: Should this be allowing -0.0? 10454 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10455 } 10456 10457 const MachineFunction &MF = DAG.getMachineFunction(); 10458 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10459 10460 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10461 // handling no dx10-clamp? 10462 if (Info->getMode().DX10Clamp) { 10463 // If NaNs is clamped to 0, we are free to reorder the inputs. 10464 10465 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10466 std::swap(Src0, Src1); 10467 10468 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10469 std::swap(Src1, Src2); 10470 10471 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10472 std::swap(Src0, Src1); 10473 10474 if (isClampZeroToOne(Src1, Src2)) 10475 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10476 } 10477 10478 return SDValue(); 10479 } 10480 10481 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10482 DAGCombinerInfo &DCI) const { 10483 SDValue Src0 = N->getOperand(0); 10484 SDValue Src1 = N->getOperand(1); 10485 if (Src0.isUndef() && Src1.isUndef()) 10486 return DCI.DAG.getUNDEF(N->getValueType(0)); 10487 return SDValue(); 10488 } 10489 10490 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10491 // expanded into a set of cmp/select instructions. 10492 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10493 unsigned NumElem, 10494 bool IsDivergentIdx, 10495 const GCNSubtarget *Subtarget) { 10496 if (UseDivergentRegisterIndexing) 10497 return false; 10498 10499 unsigned VecSize = EltSize * NumElem; 10500 10501 // Sub-dword vectors of size 2 dword or less have better implementation. 10502 if (VecSize <= 64 && EltSize < 32) 10503 return false; 10504 10505 // Always expand the rest of sub-dword instructions, otherwise it will be 10506 // lowered via memory. 10507 if (EltSize < 32) 10508 return true; 10509 10510 // Always do this if var-idx is divergent, otherwise it will become a loop. 10511 if (IsDivergentIdx) 10512 return true; 10513 10514 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10515 unsigned NumInsts = NumElem /* Number of compares */ + 10516 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10517 10518 // On some architectures (GFX9) movrel is not available and it's better 10519 // to expand. 10520 if (!Subtarget->hasMovrel()) 10521 return NumInsts <= 16; 10522 10523 // If movrel is available, use it instead of expanding for vector of 8 10524 // elements. 10525 return NumInsts <= 15; 10526 } 10527 10528 bool SITargetLowering::shouldExpandVectorDynExt(SDNode *N) const { 10529 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10530 if (isa<ConstantSDNode>(Idx)) 10531 return false; 10532 10533 SDValue Vec = N->getOperand(0); 10534 EVT VecVT = Vec.getValueType(); 10535 EVT EltVT = VecVT.getVectorElementType(); 10536 unsigned EltSize = EltVT.getSizeInBits(); 10537 unsigned NumElem = VecVT.getVectorNumElements(); 10538 10539 return SITargetLowering::shouldExpandVectorDynExt( 10540 EltSize, NumElem, Idx->isDivergent(), getSubtarget()); 10541 } 10542 10543 SDValue SITargetLowering::performExtractVectorEltCombine( 10544 SDNode *N, DAGCombinerInfo &DCI) const { 10545 SDValue Vec = N->getOperand(0); 10546 SelectionDAG &DAG = DCI.DAG; 10547 10548 EVT VecVT = Vec.getValueType(); 10549 EVT EltVT = VecVT.getVectorElementType(); 10550 10551 if ((Vec.getOpcode() == ISD::FNEG || 10552 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10553 SDLoc SL(N); 10554 EVT EltVT = N->getValueType(0); 10555 SDValue Idx = N->getOperand(1); 10556 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10557 Vec.getOperand(0), Idx); 10558 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10559 } 10560 10561 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10562 // => 10563 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10564 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10565 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10566 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10567 SDLoc SL(N); 10568 EVT EltVT = N->getValueType(0); 10569 SDValue Idx = N->getOperand(1); 10570 unsigned Opc = Vec.getOpcode(); 10571 10572 switch(Opc) { 10573 default: 10574 break; 10575 // TODO: Support other binary operations. 10576 case ISD::FADD: 10577 case ISD::FSUB: 10578 case ISD::FMUL: 10579 case ISD::ADD: 10580 case ISD::UMIN: 10581 case ISD::UMAX: 10582 case ISD::SMIN: 10583 case ISD::SMAX: 10584 case ISD::FMAXNUM: 10585 case ISD::FMINNUM: 10586 case ISD::FMAXNUM_IEEE: 10587 case ISD::FMINNUM_IEEE: { 10588 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10589 Vec.getOperand(0), Idx); 10590 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10591 Vec.getOperand(1), Idx); 10592 10593 DCI.AddToWorklist(Elt0.getNode()); 10594 DCI.AddToWorklist(Elt1.getNode()); 10595 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10596 } 10597 } 10598 } 10599 10600 unsigned VecSize = VecVT.getSizeInBits(); 10601 unsigned EltSize = EltVT.getSizeInBits(); 10602 10603 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10604 if (shouldExpandVectorDynExt(N)) { 10605 SDLoc SL(N); 10606 SDValue Idx = N->getOperand(1); 10607 SDValue V; 10608 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10609 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10610 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10611 if (I == 0) 10612 V = Elt; 10613 else 10614 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10615 } 10616 return V; 10617 } 10618 10619 if (!DCI.isBeforeLegalize()) 10620 return SDValue(); 10621 10622 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10623 // elements. This exposes more load reduction opportunities by replacing 10624 // multiple small extract_vector_elements with a single 32-bit extract. 10625 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10626 if (isa<MemSDNode>(Vec) && 10627 EltSize <= 16 && 10628 EltVT.isByteSized() && 10629 VecSize > 32 && 10630 VecSize % 32 == 0 && 10631 Idx) { 10632 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10633 10634 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10635 unsigned EltIdx = BitIndex / 32; 10636 unsigned LeftoverBitIdx = BitIndex % 32; 10637 SDLoc SL(N); 10638 10639 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10640 DCI.AddToWorklist(Cast.getNode()); 10641 10642 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10643 DAG.getConstant(EltIdx, SL, MVT::i32)); 10644 DCI.AddToWorklist(Elt.getNode()); 10645 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10646 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10647 DCI.AddToWorklist(Srl.getNode()); 10648 10649 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10650 DCI.AddToWorklist(Trunc.getNode()); 10651 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10652 } 10653 10654 return SDValue(); 10655 } 10656 10657 SDValue 10658 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10659 DAGCombinerInfo &DCI) const { 10660 SDValue Vec = N->getOperand(0); 10661 SDValue Idx = N->getOperand(2); 10662 EVT VecVT = Vec.getValueType(); 10663 EVT EltVT = VecVT.getVectorElementType(); 10664 10665 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10666 // => BUILD_VECTOR n x select (e, const-idx) 10667 if (!shouldExpandVectorDynExt(N)) 10668 return SDValue(); 10669 10670 SelectionDAG &DAG = DCI.DAG; 10671 SDLoc SL(N); 10672 SDValue Ins = N->getOperand(1); 10673 EVT IdxVT = Idx.getValueType(); 10674 10675 SmallVector<SDValue, 16> Ops; 10676 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10677 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10678 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10679 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10680 Ops.push_back(V); 10681 } 10682 10683 return DAG.getBuildVector(VecVT, SL, Ops); 10684 } 10685 10686 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10687 const SDNode *N0, 10688 const SDNode *N1) const { 10689 EVT VT = N0->getValueType(0); 10690 10691 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10692 // support denormals ever. 10693 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10694 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10695 getSubtarget()->hasMadF16())) && 10696 isOperationLegal(ISD::FMAD, VT)) 10697 return ISD::FMAD; 10698 10699 const TargetOptions &Options = DAG.getTarget().Options; 10700 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10701 (N0->getFlags().hasAllowContract() && 10702 N1->getFlags().hasAllowContract())) && 10703 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10704 return ISD::FMA; 10705 } 10706 10707 return 0; 10708 } 10709 10710 // For a reassociatable opcode perform: 10711 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10712 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10713 SelectionDAG &DAG) const { 10714 EVT VT = N->getValueType(0); 10715 if (VT != MVT::i32 && VT != MVT::i64) 10716 return SDValue(); 10717 10718 if (DAG.isBaseWithConstantOffset(SDValue(N, 0))) 10719 return SDValue(); 10720 10721 unsigned Opc = N->getOpcode(); 10722 SDValue Op0 = N->getOperand(0); 10723 SDValue Op1 = N->getOperand(1); 10724 10725 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10726 return SDValue(); 10727 10728 if (Op0->isDivergent()) 10729 std::swap(Op0, Op1); 10730 10731 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10732 return SDValue(); 10733 10734 SDValue Op2 = Op1.getOperand(1); 10735 Op1 = Op1.getOperand(0); 10736 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10737 return SDValue(); 10738 10739 if (Op1->isDivergent()) 10740 std::swap(Op1, Op2); 10741 10742 SDLoc SL(N); 10743 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10744 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10745 } 10746 10747 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10748 EVT VT, 10749 SDValue N0, SDValue N1, SDValue N2, 10750 bool Signed) { 10751 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10752 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10753 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10754 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10755 } 10756 10757 // Fold (add (mul x, y), z) --> (mad_[iu]64_[iu]32 x, y, z) plus high 10758 // multiplies, if any. 10759 // 10760 // Full 64-bit multiplies that feed into an addition are lowered here instead 10761 // of using the generic expansion. The generic expansion ends up with 10762 // a tree of ADD nodes that prevents us from using the "add" part of the 10763 // MAD instruction. The expansion produced here results in a chain of ADDs 10764 // instead of a tree. 10765 SDValue SITargetLowering::tryFoldToMad64_32(SDNode *N, 10766 DAGCombinerInfo &DCI) const { 10767 assert(N->getOpcode() == ISD::ADD); 10768 10769 SelectionDAG &DAG = DCI.DAG; 10770 EVT VT = N->getValueType(0); 10771 SDLoc SL(N); 10772 SDValue LHS = N->getOperand(0); 10773 SDValue RHS = N->getOperand(1); 10774 10775 if (VT.isVector()) 10776 return SDValue(); 10777 10778 // S_MUL_HI_[IU]32 was added in gfx9, which allows us to keep the overall 10779 // result in scalar registers for uniform values. 10780 if (!N->isDivergent() && Subtarget->hasSMulHi()) 10781 return SDValue(); 10782 10783 unsigned NumBits = VT.getScalarSizeInBits(); 10784 if (NumBits <= 32 || NumBits > 64) 10785 return SDValue(); 10786 10787 if (LHS.getOpcode() != ISD::MUL) { 10788 assert(RHS.getOpcode() == ISD::MUL); 10789 std::swap(LHS, RHS); 10790 } 10791 10792 // Avoid the fold if it would unduly increase the number of multiplies due to 10793 // multiple uses, except on hardware with full-rate multiply-add (which is 10794 // part of full-rate 64-bit ops). 10795 if (!Subtarget->hasFullRate64Ops()) { 10796 unsigned NumUsers = 0; 10797 for (SDNode *Use : LHS->uses()) { 10798 // There is a use that does not feed into addition, so the multiply can't 10799 // be removed. We prefer MUL + ADD + ADDC over MAD + MUL. 10800 if (Use->getOpcode() != ISD::ADD) 10801 return SDValue(); 10802 10803 // We prefer 2xMAD over MUL + 2xADD + 2xADDC (code density), and prefer 10804 // MUL + 3xADD + 3xADDC over 3xMAD. 10805 ++NumUsers; 10806 if (NumUsers >= 3) 10807 return SDValue(); 10808 } 10809 } 10810 10811 SDValue MulLHS = LHS.getOperand(0); 10812 SDValue MulRHS = LHS.getOperand(1); 10813 SDValue AddRHS = RHS; 10814 10815 // Always check whether operands are small unsigned values, since that 10816 // knowledge is useful in more cases. Check for small signed values only if 10817 // doing so can unlock a shorter code sequence. 10818 bool MulLHSUnsigned32 = numBitsUnsigned(MulLHS, DAG) <= 32; 10819 bool MulRHSUnsigned32 = numBitsUnsigned(MulRHS, DAG) <= 32; 10820 10821 bool MulSignedLo = false; 10822 if (!MulLHSUnsigned32 || !MulRHSUnsigned32) { 10823 MulSignedLo = numBitsSigned(MulLHS, DAG) <= 32 && 10824 numBitsSigned(MulRHS, DAG) <= 32; 10825 } 10826 10827 // The operands and final result all have the same number of bits. If 10828 // operands need to be extended, they can be extended with garbage. The 10829 // resulting garbage in the high bits of the mad_[iu]64_[iu]32 result is 10830 // truncated away in the end. 10831 if (VT != MVT::i64) { 10832 MulLHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulLHS); 10833 MulRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulRHS); 10834 AddRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, AddRHS); 10835 } 10836 10837 // The basic code generated is conceptually straightforward. Pseudo code: 10838 // 10839 // accum = mad_64_32 lhs.lo, rhs.lo, accum 10840 // accum.hi = add (mul lhs.hi, rhs.lo), accum.hi 10841 // accum.hi = add (mul lhs.lo, rhs.hi), accum.hi 10842 // 10843 // The second and third lines are optional, depending on whether the factors 10844 // are {sign,zero}-extended or not. 10845 // 10846 // The actual DAG is noisier than the pseudo code, but only due to 10847 // instructions that disassemble values into low and high parts, and 10848 // assemble the final result. 10849 SDValue Zero = DAG.getConstant(0, SL, MVT::i32); 10850 SDValue One = DAG.getConstant(1, SL, MVT::i32); 10851 10852 auto MulLHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulLHS); 10853 auto MulRHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulRHS); 10854 SDValue Accum = 10855 getMad64_32(DAG, SL, MVT::i64, MulLHSLo, MulRHSLo, AddRHS, MulSignedLo); 10856 10857 if (!MulSignedLo && (!MulLHSUnsigned32 || !MulRHSUnsigned32)) { 10858 auto AccumLo = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, Zero); 10859 auto AccumHi = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, One); 10860 10861 if (!MulLHSUnsigned32) { 10862 auto MulLHSHi = 10863 DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulLHS, One); 10864 SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSHi, MulRHSLo); 10865 AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi); 10866 } 10867 10868 if (!MulRHSUnsigned32) { 10869 auto MulRHSHi = 10870 DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulRHS, One); 10871 SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSLo, MulRHSHi); 10872 AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi); 10873 } 10874 10875 Accum = DAG.getBuildVector(MVT::v2i32, SL, {AccumLo, AccumHi}); 10876 Accum = DAG.getBitcast(MVT::i64, Accum); 10877 } 10878 10879 if (VT != MVT::i64) 10880 Accum = DAG.getNode(ISD::TRUNCATE, SL, VT, Accum); 10881 return Accum; 10882 } 10883 10884 SDValue SITargetLowering::performAddCombine(SDNode *N, 10885 DAGCombinerInfo &DCI) const { 10886 SelectionDAG &DAG = DCI.DAG; 10887 EVT VT = N->getValueType(0); 10888 SDLoc SL(N); 10889 SDValue LHS = N->getOperand(0); 10890 SDValue RHS = N->getOperand(1); 10891 10892 if (LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) { 10893 if (Subtarget->hasMad64_32()) { 10894 if (SDValue Folded = tryFoldToMad64_32(N, DCI)) 10895 return Folded; 10896 } 10897 10898 return SDValue(); 10899 } 10900 10901 if (SDValue V = reassociateScalarOps(N, DAG)) { 10902 return V; 10903 } 10904 10905 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10906 return SDValue(); 10907 10908 // add x, zext (setcc) => addcarry x, 0, setcc 10909 // add x, sext (setcc) => subcarry x, 0, setcc 10910 unsigned Opc = LHS.getOpcode(); 10911 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10912 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10913 std::swap(RHS, LHS); 10914 10915 Opc = RHS.getOpcode(); 10916 switch (Opc) { 10917 default: break; 10918 case ISD::ZERO_EXTEND: 10919 case ISD::SIGN_EXTEND: 10920 case ISD::ANY_EXTEND: { 10921 auto Cond = RHS.getOperand(0); 10922 // If this won't be a real VOPC output, we would still need to insert an 10923 // extra instruction anyway. 10924 if (!isBoolSGPR(Cond)) 10925 break; 10926 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10927 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10928 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10929 return DAG.getNode(Opc, SL, VTList, Args); 10930 } 10931 case ISD::ADDCARRY: { 10932 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10933 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10934 if (!C || C->getZExtValue() != 0) break; 10935 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10936 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10937 } 10938 } 10939 return SDValue(); 10940 } 10941 10942 SDValue SITargetLowering::performSubCombine(SDNode *N, 10943 DAGCombinerInfo &DCI) const { 10944 SelectionDAG &DAG = DCI.DAG; 10945 EVT VT = N->getValueType(0); 10946 10947 if (VT != MVT::i32) 10948 return SDValue(); 10949 10950 SDLoc SL(N); 10951 SDValue LHS = N->getOperand(0); 10952 SDValue RHS = N->getOperand(1); 10953 10954 // sub x, zext (setcc) => subcarry x, 0, setcc 10955 // sub x, sext (setcc) => addcarry x, 0, setcc 10956 unsigned Opc = RHS.getOpcode(); 10957 switch (Opc) { 10958 default: break; 10959 case ISD::ZERO_EXTEND: 10960 case ISD::SIGN_EXTEND: 10961 case ISD::ANY_EXTEND: { 10962 auto Cond = RHS.getOperand(0); 10963 // If this won't be a real VOPC output, we would still need to insert an 10964 // extra instruction anyway. 10965 if (!isBoolSGPR(Cond)) 10966 break; 10967 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10968 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10969 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10970 return DAG.getNode(Opc, SL, VTList, Args); 10971 } 10972 } 10973 10974 if (LHS.getOpcode() == ISD::SUBCARRY) { 10975 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10976 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10977 if (!C || !C->isZero()) 10978 return SDValue(); 10979 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10980 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10981 } 10982 return SDValue(); 10983 } 10984 10985 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10986 DAGCombinerInfo &DCI) const { 10987 10988 if (N->getValueType(0) != MVT::i32) 10989 return SDValue(); 10990 10991 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10992 if (!C || C->getZExtValue() != 0) 10993 return SDValue(); 10994 10995 SelectionDAG &DAG = DCI.DAG; 10996 SDValue LHS = N->getOperand(0); 10997 10998 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10999 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 11000 unsigned LHSOpc = LHS.getOpcode(); 11001 unsigned Opc = N->getOpcode(); 11002 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 11003 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 11004 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 11005 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 11006 } 11007 return SDValue(); 11008 } 11009 11010 SDValue SITargetLowering::performFAddCombine(SDNode *N, 11011 DAGCombinerInfo &DCI) const { 11012 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 11013 return SDValue(); 11014 11015 SelectionDAG &DAG = DCI.DAG; 11016 EVT VT = N->getValueType(0); 11017 11018 SDLoc SL(N); 11019 SDValue LHS = N->getOperand(0); 11020 SDValue RHS = N->getOperand(1); 11021 11022 // These should really be instruction patterns, but writing patterns with 11023 // source modifiers is a pain. 11024 11025 // fadd (fadd (a, a), b) -> mad 2.0, a, b 11026 if (LHS.getOpcode() == ISD::FADD) { 11027 SDValue A = LHS.getOperand(0); 11028 if (A == LHS.getOperand(1)) { 11029 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 11030 if (FusedOp != 0) { 11031 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 11032 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 11033 } 11034 } 11035 } 11036 11037 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 11038 if (RHS.getOpcode() == ISD::FADD) { 11039 SDValue A = RHS.getOperand(0); 11040 if (A == RHS.getOperand(1)) { 11041 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 11042 if (FusedOp != 0) { 11043 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 11044 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 11045 } 11046 } 11047 } 11048 11049 return SDValue(); 11050 } 11051 11052 SDValue SITargetLowering::performFSubCombine(SDNode *N, 11053 DAGCombinerInfo &DCI) const { 11054 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 11055 return SDValue(); 11056 11057 SelectionDAG &DAG = DCI.DAG; 11058 SDLoc SL(N); 11059 EVT VT = N->getValueType(0); 11060 assert(!VT.isVector()); 11061 11062 // Try to get the fneg to fold into the source modifier. This undoes generic 11063 // DAG combines and folds them into the mad. 11064 // 11065 // Only do this if we are not trying to support denormals. v_mad_f32 does 11066 // not support denormals ever. 11067 SDValue LHS = N->getOperand(0); 11068 SDValue RHS = N->getOperand(1); 11069 if (LHS.getOpcode() == ISD::FADD) { 11070 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 11071 SDValue A = LHS.getOperand(0); 11072 if (A == LHS.getOperand(1)) { 11073 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 11074 if (FusedOp != 0){ 11075 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 11076 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 11077 11078 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 11079 } 11080 } 11081 } 11082 11083 if (RHS.getOpcode() == ISD::FADD) { 11084 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 11085 11086 SDValue A = RHS.getOperand(0); 11087 if (A == RHS.getOperand(1)) { 11088 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 11089 if (FusedOp != 0){ 11090 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 11091 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 11092 } 11093 } 11094 } 11095 11096 return SDValue(); 11097 } 11098 11099 SDValue SITargetLowering::performFMACombine(SDNode *N, 11100 DAGCombinerInfo &DCI) const { 11101 SelectionDAG &DAG = DCI.DAG; 11102 EVT VT = N->getValueType(0); 11103 SDLoc SL(N); 11104 11105 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 11106 return SDValue(); 11107 11108 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 11109 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 11110 SDValue Op1 = N->getOperand(0); 11111 SDValue Op2 = N->getOperand(1); 11112 SDValue FMA = N->getOperand(2); 11113 11114 if (FMA.getOpcode() != ISD::FMA || 11115 Op1.getOpcode() != ISD::FP_EXTEND || 11116 Op2.getOpcode() != ISD::FP_EXTEND) 11117 return SDValue(); 11118 11119 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 11120 // regardless of the denorm mode setting. Therefore, 11121 // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2. 11122 const TargetOptions &Options = DAG.getTarget().Options; 11123 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 11124 (N->getFlags().hasAllowContract() && 11125 FMA->getFlags().hasAllowContract())) { 11126 Op1 = Op1.getOperand(0); 11127 Op2 = Op2.getOperand(0); 11128 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11129 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11130 return SDValue(); 11131 11132 SDValue Vec1 = Op1.getOperand(0); 11133 SDValue Idx1 = Op1.getOperand(1); 11134 SDValue Vec2 = Op2.getOperand(0); 11135 11136 SDValue FMAOp1 = FMA.getOperand(0); 11137 SDValue FMAOp2 = FMA.getOperand(1); 11138 SDValue FMAAcc = FMA.getOperand(2); 11139 11140 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 11141 FMAOp2.getOpcode() != ISD::FP_EXTEND) 11142 return SDValue(); 11143 11144 FMAOp1 = FMAOp1.getOperand(0); 11145 FMAOp2 = FMAOp2.getOperand(0); 11146 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11147 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11148 return SDValue(); 11149 11150 SDValue Vec3 = FMAOp1.getOperand(0); 11151 SDValue Vec4 = FMAOp2.getOperand(0); 11152 SDValue Idx2 = FMAOp1.getOperand(1); 11153 11154 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 11155 // Idx1 and Idx2 cannot be the same. 11156 Idx1 == Idx2) 11157 return SDValue(); 11158 11159 if (Vec1 == Vec2 || Vec3 == Vec4) 11160 return SDValue(); 11161 11162 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 11163 return SDValue(); 11164 11165 if ((Vec1 == Vec3 && Vec2 == Vec4) || 11166 (Vec1 == Vec4 && Vec2 == Vec3)) { 11167 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 11168 DAG.getTargetConstant(0, SL, MVT::i1)); 11169 } 11170 } 11171 return SDValue(); 11172 } 11173 11174 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 11175 DAGCombinerInfo &DCI) const { 11176 SelectionDAG &DAG = DCI.DAG; 11177 SDLoc SL(N); 11178 11179 SDValue LHS = N->getOperand(0); 11180 SDValue RHS = N->getOperand(1); 11181 EVT VT = LHS.getValueType(); 11182 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11183 11184 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 11185 if (!CRHS) { 11186 CRHS = dyn_cast<ConstantSDNode>(LHS); 11187 if (CRHS) { 11188 std::swap(LHS, RHS); 11189 CC = getSetCCSwappedOperands(CC); 11190 } 11191 } 11192 11193 if (CRHS) { 11194 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 11195 isBoolSGPR(LHS.getOperand(0))) { 11196 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 11197 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 11198 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 11199 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 11200 if ((CRHS->isAllOnes() && 11201 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 11202 (CRHS->isZero() && 11203 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 11204 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 11205 DAG.getConstant(-1, SL, MVT::i1)); 11206 if ((CRHS->isAllOnes() && 11207 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 11208 (CRHS->isZero() && 11209 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 11210 return LHS.getOperand(0); 11211 } 11212 11213 const APInt &CRHSVal = CRHS->getAPIntValue(); 11214 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 11215 LHS.getOpcode() == ISD::SELECT && 11216 isa<ConstantSDNode>(LHS.getOperand(1)) && 11217 isa<ConstantSDNode>(LHS.getOperand(2)) && 11218 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 11219 isBoolSGPR(LHS.getOperand(0))) { 11220 // Given CT != FT: 11221 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 11222 // setcc (select cc, CT, CF), CF, ne => cc 11223 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 11224 // setcc (select cc, CT, CF), CT, eq => cc 11225 const APInt &CT = LHS.getConstantOperandAPInt(1); 11226 const APInt &CF = LHS.getConstantOperandAPInt(2); 11227 11228 if ((CF == CRHSVal && CC == ISD::SETEQ) || 11229 (CT == CRHSVal && CC == ISD::SETNE)) 11230 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 11231 DAG.getConstant(-1, SL, MVT::i1)); 11232 if ((CF == CRHSVal && CC == ISD::SETNE) || 11233 (CT == CRHSVal && CC == ISD::SETEQ)) 11234 return LHS.getOperand(0); 11235 } 11236 } 11237 11238 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 11239 VT != MVT::f16)) 11240 return SDValue(); 11241 11242 // Match isinf/isfinite pattern 11243 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 11244 // (fcmp one (fabs x), inf) -> (fp_class x, 11245 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 11246 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 11247 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 11248 if (!CRHS) 11249 return SDValue(); 11250 11251 const APFloat &APF = CRHS->getValueAPF(); 11252 if (APF.isInfinity() && !APF.isNegative()) { 11253 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 11254 SIInstrFlags::N_INFINITY; 11255 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 11256 SIInstrFlags::P_ZERO | 11257 SIInstrFlags::N_NORMAL | 11258 SIInstrFlags::P_NORMAL | 11259 SIInstrFlags::N_SUBNORMAL | 11260 SIInstrFlags::P_SUBNORMAL; 11261 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 11262 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 11263 DAG.getConstant(Mask, SL, MVT::i32)); 11264 } 11265 } 11266 11267 return SDValue(); 11268 } 11269 11270 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 11271 DAGCombinerInfo &DCI) const { 11272 SelectionDAG &DAG = DCI.DAG; 11273 SDLoc SL(N); 11274 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 11275 11276 SDValue Src = N->getOperand(0); 11277 SDValue Shift = N->getOperand(0); 11278 11279 // TODO: Extend type shouldn't matter (assuming legal types). 11280 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 11281 Shift = Shift.getOperand(0); 11282 11283 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 11284 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 11285 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 11286 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 11287 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 11288 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 11289 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 11290 SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0), 11291 SDLoc(Shift.getOperand(0)), MVT::i32); 11292 11293 unsigned ShiftOffset = 8 * Offset; 11294 if (Shift.getOpcode() == ISD::SHL) 11295 ShiftOffset -= C->getZExtValue(); 11296 else 11297 ShiftOffset += C->getZExtValue(); 11298 11299 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 11300 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 11301 MVT::f32, Shifted); 11302 } 11303 } 11304 } 11305 11306 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11307 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 11308 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 11309 // We simplified Src. If this node is not dead, visit it again so it is 11310 // folded properly. 11311 if (N->getOpcode() != ISD::DELETED_NODE) 11312 DCI.AddToWorklist(N); 11313 return SDValue(N, 0); 11314 } 11315 11316 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 11317 if (SDValue DemandedSrc = 11318 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 11319 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 11320 11321 return SDValue(); 11322 } 11323 11324 SDValue SITargetLowering::performClampCombine(SDNode *N, 11325 DAGCombinerInfo &DCI) const { 11326 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 11327 if (!CSrc) 11328 return SDValue(); 11329 11330 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 11331 const APFloat &F = CSrc->getValueAPF(); 11332 APFloat Zero = APFloat::getZero(F.getSemantics()); 11333 if (F < Zero || 11334 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 11335 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 11336 } 11337 11338 APFloat One(F.getSemantics(), "1.0"); 11339 if (F > One) 11340 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 11341 11342 return SDValue(CSrc, 0); 11343 } 11344 11345 11346 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 11347 DAGCombinerInfo &DCI) const { 11348 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 11349 return SDValue(); 11350 switch (N->getOpcode()) { 11351 case ISD::ADD: 11352 return performAddCombine(N, DCI); 11353 case ISD::SUB: 11354 return performSubCombine(N, DCI); 11355 case ISD::ADDCARRY: 11356 case ISD::SUBCARRY: 11357 return performAddCarrySubCarryCombine(N, DCI); 11358 case ISD::FADD: 11359 return performFAddCombine(N, DCI); 11360 case ISD::FSUB: 11361 return performFSubCombine(N, DCI); 11362 case ISD::SETCC: 11363 return performSetCCCombine(N, DCI); 11364 case ISD::FMAXNUM: 11365 case ISD::FMINNUM: 11366 case ISD::FMAXNUM_IEEE: 11367 case ISD::FMINNUM_IEEE: 11368 case ISD::SMAX: 11369 case ISD::SMIN: 11370 case ISD::UMAX: 11371 case ISD::UMIN: 11372 case AMDGPUISD::FMIN_LEGACY: 11373 case AMDGPUISD::FMAX_LEGACY: 11374 return performMinMaxCombine(N, DCI); 11375 case ISD::FMA: 11376 return performFMACombine(N, DCI); 11377 case ISD::AND: 11378 return performAndCombine(N, DCI); 11379 case ISD::OR: 11380 return performOrCombine(N, DCI); 11381 case ISD::XOR: 11382 return performXorCombine(N, DCI); 11383 case ISD::ZERO_EXTEND: 11384 return performZeroExtendCombine(N, DCI); 11385 case ISD::SIGN_EXTEND_INREG: 11386 return performSignExtendInRegCombine(N , DCI); 11387 case AMDGPUISD::FP_CLASS: 11388 return performClassCombine(N, DCI); 11389 case ISD::FCANONICALIZE: 11390 return performFCanonicalizeCombine(N, DCI); 11391 case AMDGPUISD::RCP: 11392 return performRcpCombine(N, DCI); 11393 case AMDGPUISD::FRACT: 11394 case AMDGPUISD::RSQ: 11395 case AMDGPUISD::RCP_LEGACY: 11396 case AMDGPUISD::RCP_IFLAG: 11397 case AMDGPUISD::RSQ_CLAMP: 11398 case AMDGPUISD::LDEXP: { 11399 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 11400 SDValue Src = N->getOperand(0); 11401 if (Src.isUndef()) 11402 return Src; 11403 break; 11404 } 11405 case ISD::SINT_TO_FP: 11406 case ISD::UINT_TO_FP: 11407 return performUCharToFloatCombine(N, DCI); 11408 case AMDGPUISD::CVT_F32_UBYTE0: 11409 case AMDGPUISD::CVT_F32_UBYTE1: 11410 case AMDGPUISD::CVT_F32_UBYTE2: 11411 case AMDGPUISD::CVT_F32_UBYTE3: 11412 return performCvtF32UByteNCombine(N, DCI); 11413 case AMDGPUISD::FMED3: 11414 return performFMed3Combine(N, DCI); 11415 case AMDGPUISD::CVT_PKRTZ_F16_F32: 11416 return performCvtPkRTZCombine(N, DCI); 11417 case AMDGPUISD::CLAMP: 11418 return performClampCombine(N, DCI); 11419 case ISD::SCALAR_TO_VECTOR: { 11420 SelectionDAG &DAG = DCI.DAG; 11421 EVT VT = N->getValueType(0); 11422 11423 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 11424 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 11425 SDLoc SL(N); 11426 SDValue Src = N->getOperand(0); 11427 EVT EltVT = Src.getValueType(); 11428 if (EltVT == MVT::f16) 11429 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 11430 11431 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 11432 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 11433 } 11434 11435 break; 11436 } 11437 case ISD::EXTRACT_VECTOR_ELT: 11438 return performExtractVectorEltCombine(N, DCI); 11439 case ISD::INSERT_VECTOR_ELT: 11440 return performInsertVectorEltCombine(N, DCI); 11441 case ISD::LOAD: { 11442 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 11443 return Widended; 11444 LLVM_FALLTHROUGH; 11445 } 11446 default: { 11447 if (!DCI.isBeforeLegalize()) { 11448 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 11449 return performMemSDNodeCombine(MemNode, DCI); 11450 } 11451 11452 break; 11453 } 11454 } 11455 11456 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 11457 } 11458 11459 /// Helper function for adjustWritemask 11460 static unsigned SubIdx2Lane(unsigned Idx) { 11461 switch (Idx) { 11462 default: return ~0u; 11463 case AMDGPU::sub0: return 0; 11464 case AMDGPU::sub1: return 1; 11465 case AMDGPU::sub2: return 2; 11466 case AMDGPU::sub3: return 3; 11467 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 11468 } 11469 } 11470 11471 /// Adjust the writemask of MIMG instructions 11472 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 11473 SelectionDAG &DAG) const { 11474 unsigned Opcode = Node->getMachineOpcode(); 11475 11476 // Subtract 1 because the vdata output is not a MachineSDNode operand. 11477 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 11478 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 11479 return Node; // not implemented for D16 11480 11481 SDNode *Users[5] = { nullptr }; 11482 unsigned Lane = 0; 11483 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 11484 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 11485 unsigned NewDmask = 0; 11486 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 11487 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 11488 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 11489 Node->getConstantOperandVal(LWEIdx)) 11490 ? true 11491 : false; 11492 unsigned TFCLane = 0; 11493 bool HasChain = Node->getNumValues() > 1; 11494 11495 if (OldDmask == 0) { 11496 // These are folded out, but on the chance it happens don't assert. 11497 return Node; 11498 } 11499 11500 unsigned OldBitsSet = countPopulation(OldDmask); 11501 // Work out which is the TFE/LWE lane if that is enabled. 11502 if (UsesTFC) { 11503 TFCLane = OldBitsSet; 11504 } 11505 11506 // Try to figure out the used register components 11507 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 11508 I != E; ++I) { 11509 11510 // Don't look at users of the chain. 11511 if (I.getUse().getResNo() != 0) 11512 continue; 11513 11514 // Abort if we can't understand the usage 11515 if (!I->isMachineOpcode() || 11516 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 11517 return Node; 11518 11519 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 11520 // Note that subregs are packed, i.e. Lane==0 is the first bit set 11521 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 11522 // set, etc. 11523 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 11524 if (Lane == ~0u) 11525 return Node; 11526 11527 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 11528 if (UsesTFC && Lane == TFCLane) { 11529 Users[Lane] = *I; 11530 } else { 11531 // Set which texture component corresponds to the lane. 11532 unsigned Comp; 11533 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 11534 Comp = countTrailingZeros(Dmask); 11535 Dmask &= ~(1 << Comp); 11536 } 11537 11538 // Abort if we have more than one user per component. 11539 if (Users[Lane]) 11540 return Node; 11541 11542 Users[Lane] = *I; 11543 NewDmask |= 1 << Comp; 11544 } 11545 } 11546 11547 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11548 bool NoChannels = !NewDmask; 11549 if (NoChannels) { 11550 if (!UsesTFC) { 11551 // No uses of the result and not using TFC. Then do nothing. 11552 return Node; 11553 } 11554 // If the original dmask has one channel - then nothing to do 11555 if (OldBitsSet == 1) 11556 return Node; 11557 // Use an arbitrary dmask - required for the instruction to work 11558 NewDmask = 1; 11559 } 11560 // Abort if there's no change 11561 if (NewDmask == OldDmask) 11562 return Node; 11563 11564 unsigned BitsSet = countPopulation(NewDmask); 11565 11566 // Check for TFE or LWE - increase the number of channels by one to account 11567 // for the extra return value 11568 // This will need adjustment for D16 if this is also included in 11569 // adjustWriteMask (this function) but at present D16 are excluded. 11570 unsigned NewChannels = BitsSet + UsesTFC; 11571 11572 int NewOpcode = 11573 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11574 assert(NewOpcode != -1 && 11575 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11576 "failed to find equivalent MIMG op"); 11577 11578 // Adjust the writemask in the node 11579 SmallVector<SDValue, 12> Ops; 11580 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11581 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11582 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11583 11584 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11585 11586 MVT ResultVT = NewChannels == 1 ? 11587 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11588 NewChannels == 5 ? 8 : NewChannels); 11589 SDVTList NewVTList = HasChain ? 11590 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11591 11592 11593 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11594 NewVTList, Ops); 11595 11596 if (HasChain) { 11597 // Update chain. 11598 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11599 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11600 } 11601 11602 if (NewChannels == 1) { 11603 assert(Node->hasNUsesOfValue(1, 0)); 11604 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11605 SDLoc(Node), Users[Lane]->getValueType(0), 11606 SDValue(NewNode, 0)); 11607 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11608 return nullptr; 11609 } 11610 11611 // Update the users of the node with the new indices 11612 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11613 SDNode *User = Users[i]; 11614 if (!User) { 11615 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11616 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11617 if (i || !NoChannels) 11618 continue; 11619 } else { 11620 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11621 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11622 } 11623 11624 switch (Idx) { 11625 default: break; 11626 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11627 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11628 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11629 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11630 } 11631 } 11632 11633 DAG.RemoveDeadNode(Node); 11634 return nullptr; 11635 } 11636 11637 static bool isFrameIndexOp(SDValue Op) { 11638 if (Op.getOpcode() == ISD::AssertZext) 11639 Op = Op.getOperand(0); 11640 11641 return isa<FrameIndexSDNode>(Op); 11642 } 11643 11644 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11645 /// with frame index operands. 11646 /// LLVM assumes that inputs are to these instructions are registers. 11647 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11648 SelectionDAG &DAG) const { 11649 if (Node->getOpcode() == ISD::CopyToReg) { 11650 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11651 SDValue SrcVal = Node->getOperand(2); 11652 11653 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11654 // to try understanding copies to physical registers. 11655 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11656 SDLoc SL(Node); 11657 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11658 SDValue VReg = DAG.getRegister( 11659 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11660 11661 SDNode *Glued = Node->getGluedNode(); 11662 SDValue ToVReg 11663 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11664 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11665 SDValue ToResultReg 11666 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11667 VReg, ToVReg.getValue(1)); 11668 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11669 DAG.RemoveDeadNode(Node); 11670 return ToResultReg.getNode(); 11671 } 11672 } 11673 11674 SmallVector<SDValue, 8> Ops; 11675 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11676 if (!isFrameIndexOp(Node->getOperand(i))) { 11677 Ops.push_back(Node->getOperand(i)); 11678 continue; 11679 } 11680 11681 SDLoc DL(Node); 11682 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11683 Node->getOperand(i).getValueType(), 11684 Node->getOperand(i)), 0)); 11685 } 11686 11687 return DAG.UpdateNodeOperands(Node, Ops); 11688 } 11689 11690 /// Fold the instructions after selecting them. 11691 /// Returns null if users were already updated. 11692 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11693 SelectionDAG &DAG) const { 11694 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11695 unsigned Opcode = Node->getMachineOpcode(); 11696 11697 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11698 !TII->isGather4(Opcode) && 11699 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11700 return adjustWritemask(Node, DAG); 11701 } 11702 11703 if (Opcode == AMDGPU::INSERT_SUBREG || 11704 Opcode == AMDGPU::REG_SEQUENCE) { 11705 legalizeTargetIndependentNode(Node, DAG); 11706 return Node; 11707 } 11708 11709 switch (Opcode) { 11710 case AMDGPU::V_DIV_SCALE_F32_e64: 11711 case AMDGPU::V_DIV_SCALE_F64_e64: { 11712 // Satisfy the operand register constraint when one of the inputs is 11713 // undefined. Ordinarily each undef value will have its own implicit_def of 11714 // a vreg, so force these to use a single register. 11715 SDValue Src0 = Node->getOperand(1); 11716 SDValue Src1 = Node->getOperand(3); 11717 SDValue Src2 = Node->getOperand(5); 11718 11719 if ((Src0.isMachineOpcode() && 11720 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11721 (Src0 == Src1 || Src0 == Src2)) 11722 break; 11723 11724 MVT VT = Src0.getValueType().getSimpleVT(); 11725 const TargetRegisterClass *RC = 11726 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11727 11728 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11729 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11730 11731 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11732 UndefReg, Src0, SDValue()); 11733 11734 // src0 must be the same register as src1 or src2, even if the value is 11735 // undefined, so make sure we don't violate this constraint. 11736 if (Src0.isMachineOpcode() && 11737 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11738 if (Src1.isMachineOpcode() && 11739 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11740 Src0 = Src1; 11741 else if (Src2.isMachineOpcode() && 11742 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11743 Src0 = Src2; 11744 else { 11745 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11746 Src0 = UndefReg; 11747 Src1 = UndefReg; 11748 } 11749 } else 11750 break; 11751 11752 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11753 Ops[1] = Src0; 11754 Ops[3] = Src1; 11755 Ops[5] = Src2; 11756 Ops.push_back(ImpDef.getValue(1)); 11757 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11758 } 11759 default: 11760 break; 11761 } 11762 11763 return Node; 11764 } 11765 11766 // Any MIMG instructions that use tfe or lwe require an initialization of the 11767 // result register that will be written in the case of a memory access failure. 11768 // The required code is also added to tie this init code to the result of the 11769 // img instruction. 11770 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11771 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11772 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11773 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11774 MachineBasicBlock &MBB = *MI.getParent(); 11775 11776 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11777 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11778 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11779 11780 if (!TFE && !LWE) // intersect_ray 11781 return; 11782 11783 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11784 unsigned LWEVal = LWE->getImm(); 11785 unsigned D16Val = D16 ? D16->getImm() : 0; 11786 11787 if (!TFEVal && !LWEVal) 11788 return; 11789 11790 // At least one of TFE or LWE are non-zero 11791 // We have to insert a suitable initialization of the result value and 11792 // tie this to the dest of the image instruction. 11793 11794 const DebugLoc &DL = MI.getDebugLoc(); 11795 11796 int DstIdx = 11797 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11798 11799 // Calculate which dword we have to initialize to 0. 11800 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11801 11802 // check that dmask operand is found. 11803 assert(MO_Dmask && "Expected dmask operand in instruction"); 11804 11805 unsigned dmask = MO_Dmask->getImm(); 11806 // Determine the number of active lanes taking into account the 11807 // Gather4 special case 11808 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11809 11810 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11811 11812 unsigned InitIdx = 11813 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11814 11815 // Abandon attempt if the dst size isn't large enough 11816 // - this is in fact an error but this is picked up elsewhere and 11817 // reported correctly. 11818 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11819 if (DstSize < InitIdx) 11820 return; 11821 11822 // Create a register for the initialization value. 11823 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11824 unsigned NewDst = 0; // Final initialized value will be in here 11825 11826 // If PRTStrictNull feature is enabled (the default) then initialize 11827 // all the result registers to 0, otherwise just the error indication 11828 // register (VGPRn+1) 11829 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11830 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11831 11832 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11833 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11834 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11835 // Initialize dword 11836 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11837 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11838 .addImm(0); 11839 // Insert into the super-reg 11840 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11841 .addReg(PrevDst) 11842 .addReg(SubReg) 11843 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11844 11845 PrevDst = NewDst; 11846 } 11847 11848 // Add as an implicit operand 11849 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11850 11851 // Tie the just added implicit operand to the dst 11852 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11853 } 11854 11855 /// Assign the register class depending on the number of 11856 /// bits set in the writemask 11857 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11858 SDNode *Node) const { 11859 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11860 11861 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11862 11863 if (TII->isVOP3(MI.getOpcode())) { 11864 // Make sure constant bus requirements are respected. 11865 TII->legalizeOperandsVOP3(MRI, MI); 11866 11867 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11868 // This saves a chain-copy of registers and better balance register 11869 // use between vgpr and agpr as agpr tuples tend to be big. 11870 if (MI.getDesc().OpInfo) { 11871 unsigned Opc = MI.getOpcode(); 11872 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11873 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11874 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11875 if (I == -1) 11876 break; 11877 MachineOperand &Op = MI.getOperand(I); 11878 if (!Op.isReg() || !Op.getReg().isVirtual()) 11879 continue; 11880 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11881 if (!TRI->hasAGPRs(RC)) 11882 continue; 11883 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11884 if (!Src || !Src->isCopy() || 11885 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11886 continue; 11887 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11888 // All uses of agpr64 and agpr32 can also accept vgpr except for 11889 // v_accvgpr_read, but we do not produce agpr reads during selection, 11890 // so no use checks are needed. 11891 MRI.setRegClass(Op.getReg(), NewRC); 11892 } 11893 11894 // Resolve the rest of AV operands to AGPRs. 11895 if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) { 11896 if (Src2->isReg() && Src2->getReg().isVirtual()) { 11897 auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg()); 11898 if (TRI->isVectorSuperClass(RC)) { 11899 auto *NewRC = TRI->getEquivalentAGPRClass(RC); 11900 MRI.setRegClass(Src2->getReg(), NewRC); 11901 if (Src2->isTied()) 11902 MRI.setRegClass(MI.getOperand(0).getReg(), NewRC); 11903 } 11904 } 11905 } 11906 } 11907 11908 return; 11909 } 11910 11911 if (TII->isMIMG(MI)) { 11912 if (!MI.mayStore()) 11913 AddIMGInit(MI); 11914 TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::vaddr); 11915 } 11916 } 11917 11918 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11919 uint64_t Val) { 11920 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11921 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11922 } 11923 11924 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11925 const SDLoc &DL, 11926 SDValue Ptr) const { 11927 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11928 11929 // Build the half of the subregister with the constants before building the 11930 // full 128-bit register. If we are building multiple resource descriptors, 11931 // this will allow CSEing of the 2-component register. 11932 const SDValue Ops0[] = { 11933 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11934 buildSMovImm32(DAG, DL, 0), 11935 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11936 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11937 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11938 }; 11939 11940 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11941 MVT::v2i32, Ops0), 0); 11942 11943 // Combine the constants and the pointer. 11944 const SDValue Ops1[] = { 11945 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11946 Ptr, 11947 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11948 SubRegHi, 11949 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11950 }; 11951 11952 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11953 } 11954 11955 /// Return a resource descriptor with the 'Add TID' bit enabled 11956 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11957 /// of the resource descriptor) to create an offset, which is added to 11958 /// the resource pointer. 11959 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11960 SDValue Ptr, uint32_t RsrcDword1, 11961 uint64_t RsrcDword2And3) const { 11962 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11963 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11964 if (RsrcDword1) { 11965 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11966 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11967 0); 11968 } 11969 11970 SDValue DataLo = buildSMovImm32(DAG, DL, 11971 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11972 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11973 11974 const SDValue Ops[] = { 11975 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11976 PtrLo, 11977 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11978 PtrHi, 11979 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11980 DataLo, 11981 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11982 DataHi, 11983 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11984 }; 11985 11986 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11987 } 11988 11989 //===----------------------------------------------------------------------===// 11990 // SI Inline Assembly Support 11991 //===----------------------------------------------------------------------===// 11992 11993 std::pair<unsigned, const TargetRegisterClass *> 11994 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11995 StringRef Constraint, 11996 MVT VT) const { 11997 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11998 11999 const TargetRegisterClass *RC = nullptr; 12000 if (Constraint.size() == 1) { 12001 const unsigned BitWidth = VT.getSizeInBits(); 12002 switch (Constraint[0]) { 12003 default: 12004 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 12005 case 's': 12006 case 'r': 12007 switch (BitWidth) { 12008 case 16: 12009 RC = &AMDGPU::SReg_32RegClass; 12010 break; 12011 case 64: 12012 RC = &AMDGPU::SGPR_64RegClass; 12013 break; 12014 default: 12015 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 12016 if (!RC) 12017 return std::make_pair(0U, nullptr); 12018 break; 12019 } 12020 break; 12021 case 'v': 12022 switch (BitWidth) { 12023 case 16: 12024 RC = &AMDGPU::VGPR_32RegClass; 12025 break; 12026 default: 12027 RC = TRI->getVGPRClassForBitWidth(BitWidth); 12028 if (!RC) 12029 return std::make_pair(0U, nullptr); 12030 break; 12031 } 12032 break; 12033 case 'a': 12034 if (!Subtarget->hasMAIInsts()) 12035 break; 12036 switch (BitWidth) { 12037 case 16: 12038 RC = &AMDGPU::AGPR_32RegClass; 12039 break; 12040 default: 12041 RC = TRI->getAGPRClassForBitWidth(BitWidth); 12042 if (!RC) 12043 return std::make_pair(0U, nullptr); 12044 break; 12045 } 12046 break; 12047 } 12048 // We actually support i128, i16 and f16 as inline parameters 12049 // even if they are not reported as legal 12050 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 12051 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 12052 return std::make_pair(0U, RC); 12053 } 12054 12055 if (Constraint.startswith("{") && Constraint.endswith("}")) { 12056 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 12057 if (RegName.consume_front("v")) { 12058 RC = &AMDGPU::VGPR_32RegClass; 12059 } else if (RegName.consume_front("s")) { 12060 RC = &AMDGPU::SGPR_32RegClass; 12061 } else if (RegName.consume_front("a")) { 12062 RC = &AMDGPU::AGPR_32RegClass; 12063 } 12064 12065 if (RC) { 12066 uint32_t Idx; 12067 if (RegName.consume_front("[")) { 12068 uint32_t End; 12069 bool Failed = RegName.consumeInteger(10, Idx); 12070 Failed |= !RegName.consume_front(":"); 12071 Failed |= RegName.consumeInteger(10, End); 12072 Failed |= !RegName.consume_back("]"); 12073 if (!Failed) { 12074 uint32_t Width = (End - Idx + 1) * 32; 12075 MCRegister Reg = RC->getRegister(Idx); 12076 if (SIRegisterInfo::isVGPRClass(RC)) 12077 RC = TRI->getVGPRClassForBitWidth(Width); 12078 else if (SIRegisterInfo::isSGPRClass(RC)) 12079 RC = TRI->getSGPRClassForBitWidth(Width); 12080 else if (SIRegisterInfo::isAGPRClass(RC)) 12081 RC = TRI->getAGPRClassForBitWidth(Width); 12082 if (RC) { 12083 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC); 12084 return std::make_pair(Reg, RC); 12085 } 12086 } 12087 } else { 12088 bool Failed = RegName.getAsInteger(10, Idx); 12089 if (!Failed && Idx < RC->getNumRegs()) 12090 return std::make_pair(RC->getRegister(Idx), RC); 12091 } 12092 } 12093 } 12094 12095 auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 12096 if (Ret.first) 12097 Ret.second = TRI->getPhysRegClass(Ret.first); 12098 12099 return Ret; 12100 } 12101 12102 static bool isImmConstraint(StringRef Constraint) { 12103 if (Constraint.size() == 1) { 12104 switch (Constraint[0]) { 12105 default: break; 12106 case 'I': 12107 case 'J': 12108 case 'A': 12109 case 'B': 12110 case 'C': 12111 return true; 12112 } 12113 } else if (Constraint == "DA" || 12114 Constraint == "DB") { 12115 return true; 12116 } 12117 return false; 12118 } 12119 12120 SITargetLowering::ConstraintType 12121 SITargetLowering::getConstraintType(StringRef Constraint) const { 12122 if (Constraint.size() == 1) { 12123 switch (Constraint[0]) { 12124 default: break; 12125 case 's': 12126 case 'v': 12127 case 'a': 12128 return C_RegisterClass; 12129 } 12130 } 12131 if (isImmConstraint(Constraint)) { 12132 return C_Other; 12133 } 12134 return TargetLowering::getConstraintType(Constraint); 12135 } 12136 12137 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 12138 if (!AMDGPU::isInlinableIntLiteral(Val)) { 12139 Val = Val & maskTrailingOnes<uint64_t>(Size); 12140 } 12141 return Val; 12142 } 12143 12144 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 12145 std::string &Constraint, 12146 std::vector<SDValue> &Ops, 12147 SelectionDAG &DAG) const { 12148 if (isImmConstraint(Constraint)) { 12149 uint64_t Val; 12150 if (getAsmOperandConstVal(Op, Val) && 12151 checkAsmConstraintVal(Op, Constraint, Val)) { 12152 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 12153 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 12154 } 12155 } else { 12156 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12157 } 12158 } 12159 12160 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 12161 unsigned Size = Op.getScalarValueSizeInBits(); 12162 if (Size > 64) 12163 return false; 12164 12165 if (Size == 16 && !Subtarget->has16BitInsts()) 12166 return false; 12167 12168 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12169 Val = C->getSExtValue(); 12170 return true; 12171 } 12172 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 12173 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 12174 return true; 12175 } 12176 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 12177 if (Size != 16 || Op.getNumOperands() != 2) 12178 return false; 12179 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 12180 return false; 12181 if (ConstantSDNode *C = V->getConstantSplatNode()) { 12182 Val = C->getSExtValue(); 12183 return true; 12184 } 12185 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 12186 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 12187 return true; 12188 } 12189 } 12190 12191 return false; 12192 } 12193 12194 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 12195 const std::string &Constraint, 12196 uint64_t Val) const { 12197 if (Constraint.size() == 1) { 12198 switch (Constraint[0]) { 12199 case 'I': 12200 return AMDGPU::isInlinableIntLiteral(Val); 12201 case 'J': 12202 return isInt<16>(Val); 12203 case 'A': 12204 return checkAsmConstraintValA(Op, Val); 12205 case 'B': 12206 return isInt<32>(Val); 12207 case 'C': 12208 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 12209 AMDGPU::isInlinableIntLiteral(Val); 12210 default: 12211 break; 12212 } 12213 } else if (Constraint.size() == 2) { 12214 if (Constraint == "DA") { 12215 int64_t HiBits = static_cast<int32_t>(Val >> 32); 12216 int64_t LoBits = static_cast<int32_t>(Val); 12217 return checkAsmConstraintValA(Op, HiBits, 32) && 12218 checkAsmConstraintValA(Op, LoBits, 32); 12219 } 12220 if (Constraint == "DB") { 12221 return true; 12222 } 12223 } 12224 llvm_unreachable("Invalid asm constraint"); 12225 } 12226 12227 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 12228 uint64_t Val, 12229 unsigned MaxSize) const { 12230 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 12231 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 12232 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 12233 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 12234 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 12235 return true; 12236 } 12237 return false; 12238 } 12239 12240 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 12241 switch (UnalignedClassID) { 12242 case AMDGPU::VReg_64RegClassID: 12243 return AMDGPU::VReg_64_Align2RegClassID; 12244 case AMDGPU::VReg_96RegClassID: 12245 return AMDGPU::VReg_96_Align2RegClassID; 12246 case AMDGPU::VReg_128RegClassID: 12247 return AMDGPU::VReg_128_Align2RegClassID; 12248 case AMDGPU::VReg_160RegClassID: 12249 return AMDGPU::VReg_160_Align2RegClassID; 12250 case AMDGPU::VReg_192RegClassID: 12251 return AMDGPU::VReg_192_Align2RegClassID; 12252 case AMDGPU::VReg_224RegClassID: 12253 return AMDGPU::VReg_224_Align2RegClassID; 12254 case AMDGPU::VReg_256RegClassID: 12255 return AMDGPU::VReg_256_Align2RegClassID; 12256 case AMDGPU::VReg_512RegClassID: 12257 return AMDGPU::VReg_512_Align2RegClassID; 12258 case AMDGPU::VReg_1024RegClassID: 12259 return AMDGPU::VReg_1024_Align2RegClassID; 12260 case AMDGPU::AReg_64RegClassID: 12261 return AMDGPU::AReg_64_Align2RegClassID; 12262 case AMDGPU::AReg_96RegClassID: 12263 return AMDGPU::AReg_96_Align2RegClassID; 12264 case AMDGPU::AReg_128RegClassID: 12265 return AMDGPU::AReg_128_Align2RegClassID; 12266 case AMDGPU::AReg_160RegClassID: 12267 return AMDGPU::AReg_160_Align2RegClassID; 12268 case AMDGPU::AReg_192RegClassID: 12269 return AMDGPU::AReg_192_Align2RegClassID; 12270 case AMDGPU::AReg_256RegClassID: 12271 return AMDGPU::AReg_256_Align2RegClassID; 12272 case AMDGPU::AReg_512RegClassID: 12273 return AMDGPU::AReg_512_Align2RegClassID; 12274 case AMDGPU::AReg_1024RegClassID: 12275 return AMDGPU::AReg_1024_Align2RegClassID; 12276 default: 12277 return -1; 12278 } 12279 } 12280 12281 // Figure out which registers should be reserved for stack access. Only after 12282 // the function is legalized do we know all of the non-spill stack objects or if 12283 // calls are present. 12284 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 12285 MachineRegisterInfo &MRI = MF.getRegInfo(); 12286 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12287 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 12288 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12289 const SIInstrInfo *TII = ST.getInstrInfo(); 12290 12291 if (Info->isEntryFunction()) { 12292 // Callable functions have fixed registers used for stack access. 12293 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 12294 } 12295 12296 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 12297 Info->getStackPtrOffsetReg())); 12298 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 12299 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 12300 12301 // We need to worry about replacing the default register with itself in case 12302 // of MIR testcases missing the MFI. 12303 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 12304 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 12305 12306 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 12307 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 12308 12309 Info->limitOccupancy(MF); 12310 12311 if (ST.isWave32() && !MF.empty()) { 12312 for (auto &MBB : MF) { 12313 for (auto &MI : MBB) { 12314 TII->fixImplicitOperands(MI); 12315 } 12316 } 12317 } 12318 12319 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 12320 // classes if required. Ideally the register class constraints would differ 12321 // per-subtarget, but there's no easy way to achieve that right now. This is 12322 // not a problem for VGPRs because the correctly aligned VGPR class is implied 12323 // from using them as the register class for legal types. 12324 if (ST.needsAlignedVGPRs()) { 12325 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 12326 const Register Reg = Register::index2VirtReg(I); 12327 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 12328 if (!RC) 12329 continue; 12330 int NewClassID = getAlignedAGPRClassID(RC->getID()); 12331 if (NewClassID != -1) 12332 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 12333 } 12334 } 12335 12336 TargetLoweringBase::finalizeLowering(MF); 12337 } 12338 12339 void SITargetLowering::computeKnownBitsForFrameIndex( 12340 const int FI, KnownBits &Known, const MachineFunction &MF) const { 12341 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 12342 12343 // Set the high bits to zero based on the maximum allowed scratch size per 12344 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 12345 // calculation won't overflow, so assume the sign bit is never set. 12346 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 12347 } 12348 12349 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 12350 KnownBits &Known, unsigned Dim) { 12351 unsigned MaxValue = 12352 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 12353 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 12354 } 12355 12356 void SITargetLowering::computeKnownBitsForTargetInstr( 12357 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 12358 const MachineRegisterInfo &MRI, unsigned Depth) const { 12359 const MachineInstr *MI = MRI.getVRegDef(R); 12360 switch (MI->getOpcode()) { 12361 case AMDGPU::G_INTRINSIC: { 12362 switch (MI->getIntrinsicID()) { 12363 case Intrinsic::amdgcn_workitem_id_x: 12364 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 12365 break; 12366 case Intrinsic::amdgcn_workitem_id_y: 12367 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 12368 break; 12369 case Intrinsic::amdgcn_workitem_id_z: 12370 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 12371 break; 12372 case Intrinsic::amdgcn_mbcnt_lo: 12373 case Intrinsic::amdgcn_mbcnt_hi: { 12374 // These return at most the wavefront size - 1. 12375 unsigned Size = MRI.getType(R).getSizeInBits(); 12376 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 12377 break; 12378 } 12379 case Intrinsic::amdgcn_groupstaticsize: { 12380 // We can report everything over the maximum size as 0. We can't report 12381 // based on the actual size because we don't know if it's accurate or not 12382 // at any given point. 12383 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 12384 break; 12385 } 12386 } 12387 break; 12388 } 12389 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 12390 Known.Zero.setHighBits(24); 12391 break; 12392 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 12393 Known.Zero.setHighBits(16); 12394 break; 12395 } 12396 } 12397 12398 Align SITargetLowering::computeKnownAlignForTargetInstr( 12399 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 12400 unsigned Depth) const { 12401 const MachineInstr *MI = MRI.getVRegDef(R); 12402 switch (MI->getOpcode()) { 12403 case AMDGPU::G_INTRINSIC: 12404 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 12405 // FIXME: Can this move to generic code? What about the case where the call 12406 // site specifies a lower alignment? 12407 Intrinsic::ID IID = MI->getIntrinsicID(); 12408 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 12409 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 12410 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 12411 return *RetAlign; 12412 return Align(1); 12413 } 12414 default: 12415 return Align(1); 12416 } 12417 } 12418 12419 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12420 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 12421 const Align CacheLineAlign = Align(64); 12422 12423 // Pre-GFX10 target did not benefit from loop alignment 12424 if (!ML || DisableLoopAlignment || 12425 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 12426 getSubtarget()->hasInstFwdPrefetchBug()) 12427 return PrefAlign; 12428 12429 // On GFX10 I$ is 4 x 64 bytes cache lines. 12430 // By default prefetcher keeps one cache line behind and reads two ahead. 12431 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 12432 // behind and one ahead. 12433 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 12434 // If loop fits 64 bytes it always spans no more than two cache lines and 12435 // does not need an alignment. 12436 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 12437 // Else if loop is less or equal 192 bytes we need two lines behind. 12438 12439 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 12440 const MachineBasicBlock *Header = ML->getHeader(); 12441 if (Header->getAlignment() != PrefAlign) 12442 return Header->getAlignment(); // Already processed. 12443 12444 unsigned LoopSize = 0; 12445 for (const MachineBasicBlock *MBB : ML->blocks()) { 12446 // If inner loop block is aligned assume in average half of the alignment 12447 // size to be added as nops. 12448 if (MBB != Header) 12449 LoopSize += MBB->getAlignment().value() / 2; 12450 12451 for (const MachineInstr &MI : *MBB) { 12452 LoopSize += TII->getInstSizeInBytes(MI); 12453 if (LoopSize > 192) 12454 return PrefAlign; 12455 } 12456 } 12457 12458 if (LoopSize <= 64) 12459 return PrefAlign; 12460 12461 if (LoopSize <= 128) 12462 return CacheLineAlign; 12463 12464 // If any of parent loops is surrounded by prefetch instructions do not 12465 // insert new for inner loop, which would reset parent's settings. 12466 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 12467 if (MachineBasicBlock *Exit = P->getExitBlock()) { 12468 auto I = Exit->getFirstNonDebugInstr(); 12469 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 12470 return CacheLineAlign; 12471 } 12472 } 12473 12474 MachineBasicBlock *Pre = ML->getLoopPreheader(); 12475 MachineBasicBlock *Exit = ML->getExitBlock(); 12476 12477 if (Pre && Exit) { 12478 auto PreTerm = Pre->getFirstTerminator(); 12479 if (PreTerm == Pre->begin() || 12480 std::prev(PreTerm)->getOpcode() != AMDGPU::S_INST_PREFETCH) 12481 BuildMI(*Pre, PreTerm, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH)) 12482 .addImm(1); // prefetch 2 lines behind PC 12483 12484 auto ExitHead = Exit->getFirstNonDebugInstr(); 12485 if (ExitHead == Exit->end() || 12486 ExitHead->getOpcode() != AMDGPU::S_INST_PREFETCH) 12487 BuildMI(*Exit, ExitHead, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH)) 12488 .addImm(2); // prefetch 1 line behind PC 12489 } 12490 12491 return CacheLineAlign; 12492 } 12493 12494 LLVM_ATTRIBUTE_UNUSED 12495 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 12496 assert(N->getOpcode() == ISD::CopyFromReg); 12497 do { 12498 // Follow the chain until we find an INLINEASM node. 12499 N = N->getOperand(0).getNode(); 12500 if (N->getOpcode() == ISD::INLINEASM || 12501 N->getOpcode() == ISD::INLINEASM_BR) 12502 return true; 12503 } while (N->getOpcode() == ISD::CopyFromReg); 12504 return false; 12505 } 12506 12507 bool SITargetLowering::isSDNodeSourceOfDivergence( 12508 const SDNode *N, FunctionLoweringInfo *FLI, 12509 LegacyDivergenceAnalysis *KDA) const { 12510 switch (N->getOpcode()) { 12511 case ISD::CopyFromReg: { 12512 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 12513 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 12514 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12515 Register Reg = R->getReg(); 12516 12517 // FIXME: Why does this need to consider isLiveIn? 12518 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 12519 return !TRI->isSGPRReg(MRI, Reg); 12520 12521 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 12522 return KDA->isDivergent(V); 12523 12524 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 12525 return !TRI->isSGPRReg(MRI, Reg); 12526 } 12527 case ISD::LOAD: { 12528 const LoadSDNode *L = cast<LoadSDNode>(N); 12529 unsigned AS = L->getAddressSpace(); 12530 // A flat load may access private memory. 12531 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 12532 } 12533 case ISD::CALLSEQ_END: 12534 return true; 12535 case ISD::INTRINSIC_WO_CHAIN: 12536 return AMDGPU::isIntrinsicSourceOfDivergence( 12537 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 12538 case ISD::INTRINSIC_W_CHAIN: 12539 return AMDGPU::isIntrinsicSourceOfDivergence( 12540 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 12541 case AMDGPUISD::ATOMIC_CMP_SWAP: 12542 case AMDGPUISD::ATOMIC_INC: 12543 case AMDGPUISD::ATOMIC_DEC: 12544 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12545 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12546 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12547 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12548 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12549 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12550 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12551 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12552 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12553 case AMDGPUISD::BUFFER_ATOMIC_AND: 12554 case AMDGPUISD::BUFFER_ATOMIC_OR: 12555 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12556 case AMDGPUISD::BUFFER_ATOMIC_INC: 12557 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12558 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12559 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12560 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12561 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12562 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12563 // Target-specific read-modify-write atomics are sources of divergence. 12564 return true; 12565 default: 12566 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12567 // Generic read-modify-write atomics are sources of divergence. 12568 return A->readMem() && A->writeMem(); 12569 } 12570 return false; 12571 } 12572 } 12573 12574 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12575 EVT VT) const { 12576 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12577 case MVT::f32: 12578 return hasFP32Denormals(DAG.getMachineFunction()); 12579 case MVT::f64: 12580 case MVT::f16: 12581 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12582 default: 12583 return false; 12584 } 12585 } 12586 12587 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12588 MachineFunction &MF) const { 12589 switch (Ty.getScalarSizeInBits()) { 12590 case 32: 12591 return hasFP32Denormals(MF); 12592 case 64: 12593 case 16: 12594 return hasFP64FP16Denormals(MF); 12595 default: 12596 return false; 12597 } 12598 } 12599 12600 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12601 const SelectionDAG &DAG, 12602 bool SNaN, 12603 unsigned Depth) const { 12604 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12605 const MachineFunction &MF = DAG.getMachineFunction(); 12606 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12607 12608 if (Info->getMode().DX10Clamp) 12609 return true; // Clamped to 0. 12610 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12611 } 12612 12613 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12614 SNaN, Depth); 12615 } 12616 12617 // Global FP atomic instructions have a hardcoded FP mode and do not support 12618 // FP32 denormals, and only support v2f16 denormals. 12619 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12620 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12621 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12622 if (&Flt == &APFloat::IEEEsingle()) 12623 return DenormMode == DenormalMode::getPreserveSign(); 12624 return DenormMode == DenormalMode::getIEEE(); 12625 } 12626 12627 TargetLowering::AtomicExpansionKind 12628 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12629 unsigned AS = RMW->getPointerAddressSpace(); 12630 if (AS == AMDGPUAS::PRIVATE_ADDRESS) 12631 return AtomicExpansionKind::NotAtomic; 12632 12633 auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) { 12634 OptimizationRemarkEmitter ORE(RMW->getFunction()); 12635 LLVMContext &Ctx = RMW->getFunction()->getContext(); 12636 SmallVector<StringRef> SSNs; 12637 Ctx.getSyncScopeNames(SSNs); 12638 auto MemScope = SSNs[RMW->getSyncScopeID()].empty() 12639 ? "system" 12640 : SSNs[RMW->getSyncScopeID()]; 12641 ORE.emit([&]() { 12642 return OptimizationRemark(DEBUG_TYPE, "Passed", RMW) 12643 << "Hardware instruction generated for atomic " 12644 << RMW->getOperationName(RMW->getOperation()) 12645 << " operation at memory scope " << MemScope 12646 << " due to an unsafe request."; 12647 }); 12648 return Kind; 12649 }; 12650 12651 switch (RMW->getOperation()) { 12652 case AtomicRMWInst::FAdd: { 12653 Type *Ty = RMW->getType(); 12654 12655 // We don't have a way to support 16-bit atomics now, so just leave them 12656 // as-is. 12657 if (Ty->isHalfTy()) 12658 return AtomicExpansionKind::None; 12659 12660 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12661 return AtomicExpansionKind::CmpXChg; 12662 12663 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12664 Subtarget->hasAtomicFaddNoRtnInsts()) { 12665 if (Subtarget->hasGFX940Insts()) 12666 return AtomicExpansionKind::None; 12667 12668 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12669 // floating point atomic instructions. May generate more efficient code, 12670 // but may not respect rounding and denormal modes, and may give incorrect 12671 // results for certain memory destinations. 12672 if (RMW->getFunction() 12673 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12674 .getValueAsString() != "true") 12675 return AtomicExpansionKind::CmpXChg; 12676 12677 if (Subtarget->hasGFX90AInsts()) { 12678 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) 12679 return AtomicExpansionKind::CmpXChg; 12680 12681 auto SSID = RMW->getSyncScopeID(); 12682 if (SSID == SyncScope::System || 12683 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12684 return AtomicExpansionKind::CmpXChg; 12685 12686 return ReportUnsafeHWInst(AtomicExpansionKind::None); 12687 } 12688 12689 if (AS == AMDGPUAS::FLAT_ADDRESS) 12690 return AtomicExpansionKind::CmpXChg; 12691 12692 return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12693 : AtomicExpansionKind::CmpXChg; 12694 } 12695 12696 // DS FP atomics do respect the denormal mode, but the rounding mode is 12697 // fixed to round-to-nearest-even. 12698 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12699 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) { 12700 if (!Ty->isDoubleTy()) 12701 return AtomicExpansionKind::None; 12702 12703 if (fpModeMatchesGlobalFPAtomicMode(RMW)) 12704 return AtomicExpansionKind::None; 12705 12706 return RMW->getFunction() 12707 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12708 .getValueAsString() == "true" 12709 ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12710 : AtomicExpansionKind::CmpXChg; 12711 } 12712 12713 return AtomicExpansionKind::CmpXChg; 12714 } 12715 default: 12716 break; 12717 } 12718 12719 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12720 } 12721 12722 TargetLowering::AtomicExpansionKind 12723 SITargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 12724 return LI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12725 ? AtomicExpansionKind::NotAtomic 12726 : AtomicExpansionKind::None; 12727 } 12728 12729 TargetLowering::AtomicExpansionKind 12730 SITargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 12731 return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12732 ? AtomicExpansionKind::NotAtomic 12733 : AtomicExpansionKind::None; 12734 } 12735 12736 TargetLowering::AtomicExpansionKind 12737 SITargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CmpX) const { 12738 return CmpX->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12739 ? AtomicExpansionKind::NotAtomic 12740 : AtomicExpansionKind::None; 12741 } 12742 12743 const TargetRegisterClass * 12744 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12745 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12746 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12747 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12748 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12749 : &AMDGPU::SReg_32RegClass; 12750 if (!TRI->isSGPRClass(RC) && !isDivergent) 12751 return TRI->getEquivalentSGPRClass(RC); 12752 else if (TRI->isSGPRClass(RC) && isDivergent) 12753 return TRI->getEquivalentVGPRClass(RC); 12754 12755 return RC; 12756 } 12757 12758 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12759 // uniform values (as produced by the mask results of control flow intrinsics) 12760 // used outside of divergent blocks. The phi users need to also be treated as 12761 // always uniform. 12762 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12763 unsigned WaveSize) { 12764 // FIXME: We assume we never cast the mask results of a control flow 12765 // intrinsic. 12766 // Early exit if the type won't be consistent as a compile time hack. 12767 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12768 if (!IT || IT->getBitWidth() != WaveSize) 12769 return false; 12770 12771 if (!isa<Instruction>(V)) 12772 return false; 12773 if (!Visited.insert(V).second) 12774 return false; 12775 bool Result = false; 12776 for (auto U : V->users()) { 12777 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12778 if (V == U->getOperand(1)) { 12779 switch (Intrinsic->getIntrinsicID()) { 12780 default: 12781 Result = false; 12782 break; 12783 case Intrinsic::amdgcn_if_break: 12784 case Intrinsic::amdgcn_if: 12785 case Intrinsic::amdgcn_else: 12786 Result = true; 12787 break; 12788 } 12789 } 12790 if (V == U->getOperand(0)) { 12791 switch (Intrinsic->getIntrinsicID()) { 12792 default: 12793 Result = false; 12794 break; 12795 case Intrinsic::amdgcn_end_cf: 12796 case Intrinsic::amdgcn_loop: 12797 Result = true; 12798 break; 12799 } 12800 } 12801 } else { 12802 Result = hasCFUser(U, Visited, WaveSize); 12803 } 12804 if (Result) 12805 break; 12806 } 12807 return Result; 12808 } 12809 12810 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12811 const Value *V) const { 12812 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12813 if (CI->isInlineAsm()) { 12814 // FIXME: This cannot give a correct answer. This should only trigger in 12815 // the case where inline asm returns mixed SGPR and VGPR results, used 12816 // outside the defining block. We don't have a specific result to 12817 // consider, so this assumes if any value is SGPR, the overall register 12818 // also needs to be SGPR. 12819 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12820 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12821 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12822 for (auto &TC : TargetConstraints) { 12823 if (TC.Type == InlineAsm::isOutput) { 12824 ComputeConstraintToUse(TC, SDValue()); 12825 const TargetRegisterClass *RC = getRegForInlineAsmConstraint( 12826 SIRI, TC.ConstraintCode, TC.ConstraintVT).second; 12827 if (RC && SIRI->isSGPRClass(RC)) 12828 return true; 12829 } 12830 } 12831 } 12832 } 12833 SmallPtrSet<const Value *, 16> Visited; 12834 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12835 } 12836 12837 std::pair<InstructionCost, MVT> 12838 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12839 Type *Ty) const { 12840 std::pair<InstructionCost, MVT> Cost = 12841 TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12842 auto Size = DL.getTypeSizeInBits(Ty); 12843 // Maximum load or store can handle 8 dwords for scalar and 4 for 12844 // vector ALU. Let's assume anything above 8 dwords is expensive 12845 // even if legal. 12846 if (Size <= 256) 12847 return Cost; 12848 12849 Cost.first += (Size + 255) / 256; 12850 return Cost; 12851 } 12852 12853 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const { 12854 SDNode::use_iterator I = N->use_begin(), E = N->use_end(); 12855 for (; I != E; ++I) { 12856 if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) { 12857 if (getBasePtrIndex(M) == I.getOperandNo()) 12858 return true; 12859 } 12860 } 12861 return false; 12862 } 12863 12864 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0, 12865 SDValue N1) const { 12866 if (!N0.hasOneUse()) 12867 return false; 12868 // Take care of the opportunity to keep N0 uniform 12869 if (N0->isDivergent() || !N1->isDivergent()) 12870 return true; 12871 // Check if we have a good chance to form the memory access pattern with the 12872 // base and offset 12873 return (DAG.isBaseWithConstantOffset(N0) && 12874 hasMemSDNodeUser(*N0->use_begin())); 12875 } 12876 12877 MachineMemOperand::Flags 12878 SITargetLowering::getTargetMMOFlags(const Instruction &I) const { 12879 // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load. 12880 if (I.getMetadata("amdgpu.noclobber")) 12881 return MONoClobber; 12882 return MachineMemOperand::MONone; 12883 } 12884