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/Statistic.h" 21 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 22 #include "llvm/BinaryFormat/ELF.h" 23 #include "llvm/CodeGen/Analysis.h" 24 #include "llvm/CodeGen/FunctionLoweringInfo.h" 25 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 26 #include "llvm/CodeGen/MachineLoopInfo.h" 27 #include "llvm/IR/DiagnosticInfo.h" 28 #include "llvm/IR/IntrinsicsAMDGPU.h" 29 #include "llvm/IR/IntrinsicsR600.h" 30 #include "llvm/Support/CommandLine.h" 31 #include "llvm/Support/KnownBits.h" 32 33 using namespace llvm; 34 35 #define DEBUG_TYPE "si-lower" 36 37 STATISTIC(NumTailCalls, "Number of tail calls"); 38 39 static cl::opt<bool> DisableLoopAlignment( 40 "amdgpu-disable-loop-alignment", 41 cl::desc("Do not align and prefetch loops"), 42 cl::init(false)); 43 44 static cl::opt<bool> VGPRReserveforSGPRSpill( 45 "amdgpu-reserve-vgpr-for-sgpr-spill", 46 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 47 48 static cl::opt<bool> UseDivergentRegisterIndexing( 49 "amdgpu-use-divergent-register-indexing", 50 cl::Hidden, 51 cl::desc("Use indirect register addressing for divergent indexes"), 52 cl::init(false)); 53 54 static bool hasFP32Denormals(const MachineFunction &MF) { 55 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 56 return Info->getMode().allFP32Denormals(); 57 } 58 59 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 60 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 61 return Info->getMode().allFP64FP16Denormals(); 62 } 63 64 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 65 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 66 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 67 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 68 return AMDGPU::SGPR0 + Reg; 69 } 70 } 71 llvm_unreachable("Cannot allocate sgpr"); 72 } 73 74 SITargetLowering::SITargetLowering(const TargetMachine &TM, 75 const GCNSubtarget &STI) 76 : AMDGPUTargetLowering(TM, STI), 77 Subtarget(&STI) { 78 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 79 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 80 81 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 82 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 83 84 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 85 86 const SIRegisterInfo *TRI = STI.getRegisterInfo(); 87 const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class(); 88 89 addRegisterClass(MVT::f64, V64RegClass); 90 addRegisterClass(MVT::v2f32, V64RegClass); 91 92 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 93 addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96)); 94 95 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 96 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 97 98 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 99 addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128)); 100 101 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 102 addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160)); 103 104 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 105 addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256)); 106 107 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 108 addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256)); 109 110 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 111 addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512)); 112 113 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 114 addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512)); 115 116 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 117 addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024)); 118 119 if (Subtarget->has16BitInsts()) { 120 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 121 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 122 123 // Unless there are also VOP3P operations, not operations are really legal. 124 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 125 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 126 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 127 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 128 } 129 130 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 131 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024)); 132 133 computeRegisterProperties(Subtarget->getRegisterInfo()); 134 135 // The boolean content concept here is too inflexible. Compares only ever 136 // really produce a 1-bit result. Any copy/extend from these will turn into a 137 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 138 // it's what most targets use. 139 setBooleanContents(ZeroOrOneBooleanContent); 140 setBooleanVectorContents(ZeroOrOneBooleanContent); 141 142 // We need to custom lower vector stores from local memory 143 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 144 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 145 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 146 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 147 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 148 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 149 setOperationAction(ISD::LOAD, MVT::i1, Custom); 150 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 151 152 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 153 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 154 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 155 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 156 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 157 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 158 setOperationAction(ISD::STORE, MVT::i1, Custom); 159 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 160 161 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 162 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 163 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 164 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 165 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 166 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 167 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 168 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 169 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 170 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 171 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 172 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 173 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 174 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 175 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 176 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 177 178 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 179 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 180 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 181 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 182 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 183 184 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 185 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 186 187 setOperationAction(ISD::SELECT, MVT::i1, Promote); 188 setOperationAction(ISD::SELECT, MVT::i64, Custom); 189 setOperationAction(ISD::SELECT, MVT::f64, Promote); 190 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 191 192 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 193 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 194 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 195 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 196 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 197 198 setOperationAction(ISD::SETCC, MVT::i1, Promote); 199 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 200 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 201 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 202 203 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 204 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 205 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 206 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 207 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 208 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 209 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 210 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 211 212 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 213 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 215 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 216 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 217 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 218 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 219 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 220 221 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 222 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 223 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 224 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 225 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 226 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 227 228 setOperationAction(ISD::UADDO, MVT::i32, Legal); 229 setOperationAction(ISD::USUBO, MVT::i32, Legal); 230 231 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 232 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 233 234 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 235 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 236 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 237 238 #if 0 239 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 240 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 241 #endif 242 243 // We only support LOAD/STORE and vector manipulation ops for vectors 244 // with > 4 elements. 245 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 246 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 247 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 248 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 249 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 250 switch (Op) { 251 case ISD::LOAD: 252 case ISD::STORE: 253 case ISD::BUILD_VECTOR: 254 case ISD::BITCAST: 255 case ISD::EXTRACT_VECTOR_ELT: 256 case ISD::INSERT_VECTOR_ELT: 257 case ISD::INSERT_SUBVECTOR: 258 case ISD::EXTRACT_SUBVECTOR: 259 case ISD::SCALAR_TO_VECTOR: 260 break; 261 case ISD::CONCAT_VECTORS: 262 setOperationAction(Op, VT, Custom); 263 break; 264 default: 265 setOperationAction(Op, VT, Expand); 266 break; 267 } 268 } 269 } 270 271 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 272 273 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 274 // is expanded to avoid having two separate loops in case the index is a VGPR. 275 276 // Most operations are naturally 32-bit vector operations. We only support 277 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 278 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 279 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 280 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 281 282 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 283 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 284 285 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 286 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 287 288 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 289 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 290 } 291 292 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 293 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 294 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 295 296 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 297 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 298 299 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 300 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 301 302 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 303 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 304 } 305 306 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 307 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 308 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 309 310 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 311 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 312 313 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 314 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 315 316 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 317 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 318 } 319 320 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 321 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 322 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 323 324 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 325 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 326 327 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 328 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 329 330 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 331 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 332 } 333 334 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 335 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 336 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 337 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 338 339 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 340 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 341 342 // Avoid stack access for these. 343 // TODO: Generalize to more vector types. 344 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 345 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 346 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 347 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 348 349 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 350 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 351 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 352 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 353 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 354 355 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 356 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 357 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 358 359 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 360 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 361 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 362 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 363 364 // Deal with vec3 vector operations when widened to vec4. 365 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 366 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 367 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 368 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 369 370 // Deal with vec5 vector operations when widened to vec8. 371 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 372 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 373 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 374 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 375 376 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 377 // and output demarshalling 378 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 379 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 380 381 // We can't return success/failure, only the old value, 382 // let LLVM add the comparison 383 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 384 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 385 386 if (Subtarget->hasFlatAddressSpace()) { 387 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 388 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 389 } 390 391 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 392 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 393 394 // FIXME: This should be narrowed to i32, but that only happens if i64 is 395 // illegal. 396 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 397 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 398 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 399 400 // On SI this is s_memtime and s_memrealtime on VI. 401 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 402 setOperationAction(ISD::TRAP, MVT::Other, Custom); 403 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 404 405 if (Subtarget->has16BitInsts()) { 406 setOperationAction(ISD::FPOW, MVT::f16, Promote); 407 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 408 setOperationAction(ISD::FLOG, MVT::f16, Custom); 409 setOperationAction(ISD::FEXP, MVT::f16, Custom); 410 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 411 } 412 413 if (Subtarget->hasMadMacF32Insts()) 414 setOperationAction(ISD::FMAD, MVT::f32, Legal); 415 416 if (!Subtarget->hasBFI()) { 417 // fcopysign can be done in a single instruction with BFI. 418 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 419 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 420 } 421 422 if (!Subtarget->hasBCNT(32)) 423 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 424 425 if (!Subtarget->hasBCNT(64)) 426 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 427 428 if (Subtarget->hasFFBH()) 429 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 430 431 if (Subtarget->hasFFBL()) 432 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 433 434 // We only really have 32-bit BFE instructions (and 16-bit on VI). 435 // 436 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 437 // effort to match them now. We want this to be false for i64 cases when the 438 // extraction isn't restricted to the upper or lower half. Ideally we would 439 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 440 // span the midpoint are probably relatively rare, so don't worry about them 441 // for now. 442 if (Subtarget->hasBFE()) 443 setHasExtractBitsInsn(true); 444 445 // Clamp modifier on add/sub 446 if (Subtarget->hasIntClamp()) { 447 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 448 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 449 } 450 451 if (Subtarget->hasAddNoCarry()) { 452 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 453 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 454 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 455 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 456 } 457 458 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 459 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 460 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 461 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 462 463 464 // These are really only legal for ieee_mode functions. We should be avoiding 465 // them for functions that don't have ieee_mode enabled, so just say they are 466 // legal. 467 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 468 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 469 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 470 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 471 472 473 if (Subtarget->haveRoundOpsF64()) { 474 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 475 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 476 setOperationAction(ISD::FRINT, MVT::f64, Legal); 477 } else { 478 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 479 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 480 setOperationAction(ISD::FRINT, MVT::f64, Custom); 481 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 482 } 483 484 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 485 486 setOperationAction(ISD::FSIN, MVT::f32, Custom); 487 setOperationAction(ISD::FCOS, MVT::f32, Custom); 488 setOperationAction(ISD::FDIV, MVT::f32, Custom); 489 setOperationAction(ISD::FDIV, MVT::f64, Custom); 490 491 if (Subtarget->has16BitInsts()) { 492 setOperationAction(ISD::Constant, MVT::i16, Legal); 493 494 setOperationAction(ISD::SMIN, MVT::i16, Legal); 495 setOperationAction(ISD::SMAX, MVT::i16, Legal); 496 497 setOperationAction(ISD::UMIN, MVT::i16, Legal); 498 setOperationAction(ISD::UMAX, MVT::i16, Legal); 499 500 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 501 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 502 503 setOperationAction(ISD::ROTR, MVT::i16, Expand); 504 setOperationAction(ISD::ROTL, MVT::i16, Expand); 505 506 setOperationAction(ISD::SDIV, MVT::i16, Promote); 507 setOperationAction(ISD::UDIV, MVT::i16, Promote); 508 setOperationAction(ISD::SREM, MVT::i16, Promote); 509 setOperationAction(ISD::UREM, MVT::i16, Promote); 510 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 511 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 512 513 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 514 515 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 516 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 517 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 518 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 519 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 520 521 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 522 523 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 524 525 setOperationAction(ISD::LOAD, MVT::i16, Custom); 526 527 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 528 529 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 530 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 531 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 532 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 533 534 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 535 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 536 537 // F16 - Constant Actions. 538 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 539 540 // F16 - Load/Store Actions. 541 setOperationAction(ISD::LOAD, MVT::f16, Promote); 542 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 543 setOperationAction(ISD::STORE, MVT::f16, Promote); 544 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 545 546 // F16 - VOP1 Actions. 547 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 548 setOperationAction(ISD::FCOS, MVT::f16, Custom); 549 setOperationAction(ISD::FSIN, MVT::f16, Custom); 550 551 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 552 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 553 554 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 555 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 556 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 557 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 558 setOperationAction(ISD::FROUND, MVT::f16, Custom); 559 560 // F16 - VOP2 Actions. 561 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 562 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 563 564 setOperationAction(ISD::FDIV, MVT::f16, Custom); 565 566 // F16 - VOP3 Actions. 567 setOperationAction(ISD::FMA, MVT::f16, Legal); 568 if (STI.hasMadF16()) 569 setOperationAction(ISD::FMAD, MVT::f16, Legal); 570 571 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 572 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 573 switch (Op) { 574 case ISD::LOAD: 575 case ISD::STORE: 576 case ISD::BUILD_VECTOR: 577 case ISD::BITCAST: 578 case ISD::EXTRACT_VECTOR_ELT: 579 case ISD::INSERT_VECTOR_ELT: 580 case ISD::INSERT_SUBVECTOR: 581 case ISD::EXTRACT_SUBVECTOR: 582 case ISD::SCALAR_TO_VECTOR: 583 break; 584 case ISD::CONCAT_VECTORS: 585 setOperationAction(Op, VT, Custom); 586 break; 587 default: 588 setOperationAction(Op, VT, Expand); 589 break; 590 } 591 } 592 } 593 594 // v_perm_b32 can handle either of these. 595 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 596 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 597 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 598 599 // XXX - Do these do anything? Vector constants turn into build_vector. 600 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 601 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 602 603 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 604 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 605 606 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 607 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 608 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 609 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 610 611 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 612 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 613 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 614 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 615 616 setOperationAction(ISD::AND, MVT::v2i16, Promote); 617 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 618 setOperationAction(ISD::OR, MVT::v2i16, Promote); 619 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 620 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 621 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 622 623 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 624 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 625 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 626 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 627 628 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 629 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 630 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 631 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 632 633 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 634 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 635 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 636 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 637 638 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 639 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 640 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 641 642 if (!Subtarget->hasVOP3PInsts()) { 643 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 644 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 645 } 646 647 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 648 // This isn't really legal, but this avoids the legalizer unrolling it (and 649 // allows matching fneg (fabs x) patterns) 650 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 651 652 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 653 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 654 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 655 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 656 657 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 658 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 659 660 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 661 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 662 } 663 664 if (Subtarget->hasVOP3PInsts()) { 665 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 666 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 667 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 668 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 669 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 670 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 671 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 672 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 673 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 674 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 675 676 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 677 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 678 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 679 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 680 681 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 682 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 683 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 684 685 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 686 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 687 688 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 689 690 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 691 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 692 693 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 694 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 695 696 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 697 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 698 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 699 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 700 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 701 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 702 703 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 704 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 705 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 706 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 707 708 setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom); 709 setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom); 710 setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom); 711 setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom); 712 713 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 714 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 715 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 716 717 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 718 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 719 720 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 721 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 722 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 723 724 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 725 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 726 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 727 728 if (Subtarget->hasPackedFP32Ops()) { 729 setOperationAction(ISD::FADD, MVT::v2f32, Legal); 730 setOperationAction(ISD::FMUL, MVT::v2f32, Legal); 731 setOperationAction(ISD::FMA, MVT::v2f32, Legal); 732 setOperationAction(ISD::FNEG, MVT::v2f32, Legal); 733 734 for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) { 735 setOperationAction(ISD::FADD, VT, Custom); 736 setOperationAction(ISD::FMUL, VT, Custom); 737 setOperationAction(ISD::FMA, VT, Custom); 738 } 739 } 740 } 741 742 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 743 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 744 745 if (Subtarget->has16BitInsts()) { 746 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 747 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 748 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 749 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 750 } else { 751 // Legalization hack. 752 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 753 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 754 755 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 756 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 757 } 758 759 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 760 setOperationAction(ISD::SELECT, VT, Custom); 761 } 762 763 setOperationAction(ISD::SMULO, MVT::i64, Custom); 764 setOperationAction(ISD::UMULO, MVT::i64, Custom); 765 766 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 767 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 768 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 769 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 770 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 771 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 772 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 773 774 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 775 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 776 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 777 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 778 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 779 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 780 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 781 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 782 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 783 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 784 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 785 786 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 787 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 788 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 789 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 790 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 791 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 792 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 793 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 794 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 795 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 796 797 setTargetDAGCombine(ISD::ADD); 798 setTargetDAGCombine(ISD::ADDCARRY); 799 setTargetDAGCombine(ISD::SUB); 800 setTargetDAGCombine(ISD::SUBCARRY); 801 setTargetDAGCombine(ISD::FADD); 802 setTargetDAGCombine(ISD::FSUB); 803 setTargetDAGCombine(ISD::FMINNUM); 804 setTargetDAGCombine(ISD::FMAXNUM); 805 setTargetDAGCombine(ISD::FMINNUM_IEEE); 806 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 807 setTargetDAGCombine(ISD::FMA); 808 setTargetDAGCombine(ISD::SMIN); 809 setTargetDAGCombine(ISD::SMAX); 810 setTargetDAGCombine(ISD::UMIN); 811 setTargetDAGCombine(ISD::UMAX); 812 setTargetDAGCombine(ISD::SETCC); 813 setTargetDAGCombine(ISD::AND); 814 setTargetDAGCombine(ISD::OR); 815 setTargetDAGCombine(ISD::XOR); 816 setTargetDAGCombine(ISD::SINT_TO_FP); 817 setTargetDAGCombine(ISD::UINT_TO_FP); 818 setTargetDAGCombine(ISD::FCANONICALIZE); 819 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 820 setTargetDAGCombine(ISD::ZERO_EXTEND); 821 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 822 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 823 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 824 825 // All memory operations. Some folding on the pointer operand is done to help 826 // matching the constant offsets in the addressing modes. 827 setTargetDAGCombine(ISD::LOAD); 828 setTargetDAGCombine(ISD::STORE); 829 setTargetDAGCombine(ISD::ATOMIC_LOAD); 830 setTargetDAGCombine(ISD::ATOMIC_STORE); 831 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 832 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 833 setTargetDAGCombine(ISD::ATOMIC_SWAP); 834 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 835 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 836 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 837 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 838 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 839 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 840 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 841 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 842 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 843 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 844 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 845 setTargetDAGCombine(ISD::INTRINSIC_VOID); 846 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 847 848 // FIXME: In other contexts we pretend this is a per-function property. 849 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 850 851 setSchedulingPreference(Sched::RegPressure); 852 } 853 854 const GCNSubtarget *SITargetLowering::getSubtarget() const { 855 return Subtarget; 856 } 857 858 //===----------------------------------------------------------------------===// 859 // TargetLowering queries 860 //===----------------------------------------------------------------------===// 861 862 // v_mad_mix* support a conversion from f16 to f32. 863 // 864 // There is only one special case when denormals are enabled we don't currently, 865 // where this is OK to use. 866 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 867 EVT DestVT, EVT SrcVT) const { 868 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 869 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 870 DestVT.getScalarType() == MVT::f32 && 871 SrcVT.getScalarType() == MVT::f16 && 872 // TODO: This probably only requires no input flushing? 873 !hasFP32Denormals(DAG.getMachineFunction()); 874 } 875 876 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 877 // SI has some legal vector types, but no legal vector operations. Say no 878 // shuffles are legal in order to prefer scalarizing some vector operations. 879 return false; 880 } 881 882 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 883 CallingConv::ID CC, 884 EVT VT) const { 885 if (CC == CallingConv::AMDGPU_KERNEL) 886 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 887 888 if (VT.isVector()) { 889 EVT ScalarVT = VT.getScalarType(); 890 unsigned Size = ScalarVT.getSizeInBits(); 891 if (Size == 16) { 892 if (Subtarget->has16BitInsts()) 893 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 894 return VT.isInteger() ? MVT::i32 : MVT::f32; 895 } 896 897 if (Size < 16) 898 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 899 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 900 } 901 902 if (VT.getSizeInBits() > 32) 903 return MVT::i32; 904 905 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 906 } 907 908 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 909 CallingConv::ID CC, 910 EVT VT) const { 911 if (CC == CallingConv::AMDGPU_KERNEL) 912 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 913 914 if (VT.isVector()) { 915 unsigned NumElts = VT.getVectorNumElements(); 916 EVT ScalarVT = VT.getScalarType(); 917 unsigned Size = ScalarVT.getSizeInBits(); 918 919 // FIXME: Should probably promote 8-bit vectors to i16. 920 if (Size == 16 && Subtarget->has16BitInsts()) 921 return (NumElts + 1) / 2; 922 923 if (Size <= 32) 924 return NumElts; 925 926 if (Size > 32) 927 return NumElts * ((Size + 31) / 32); 928 } else if (VT.getSizeInBits() > 32) 929 return (VT.getSizeInBits() + 31) / 32; 930 931 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 932 } 933 934 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 935 LLVMContext &Context, CallingConv::ID CC, 936 EVT VT, EVT &IntermediateVT, 937 unsigned &NumIntermediates, MVT &RegisterVT) const { 938 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 939 unsigned NumElts = VT.getVectorNumElements(); 940 EVT ScalarVT = VT.getScalarType(); 941 unsigned Size = ScalarVT.getSizeInBits(); 942 // FIXME: We should fix the ABI to be the same on targets without 16-bit 943 // support, but unless we can properly handle 3-vectors, it will be still be 944 // inconsistent. 945 if (Size == 16 && Subtarget->has16BitInsts()) { 946 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 947 IntermediateVT = RegisterVT; 948 NumIntermediates = (NumElts + 1) / 2; 949 return NumIntermediates; 950 } 951 952 if (Size == 32) { 953 RegisterVT = ScalarVT.getSimpleVT(); 954 IntermediateVT = RegisterVT; 955 NumIntermediates = NumElts; 956 return NumIntermediates; 957 } 958 959 if (Size < 16 && Subtarget->has16BitInsts()) { 960 // FIXME: Should probably form v2i16 pieces 961 RegisterVT = MVT::i16; 962 IntermediateVT = ScalarVT; 963 NumIntermediates = NumElts; 964 return NumIntermediates; 965 } 966 967 968 if (Size != 16 && Size <= 32) { 969 RegisterVT = MVT::i32; 970 IntermediateVT = ScalarVT; 971 NumIntermediates = NumElts; 972 return NumIntermediates; 973 } 974 975 if (Size > 32) { 976 RegisterVT = MVT::i32; 977 IntermediateVT = RegisterVT; 978 NumIntermediates = NumElts * ((Size + 31) / 32); 979 return NumIntermediates; 980 } 981 } 982 983 return TargetLowering::getVectorTypeBreakdownForCallingConv( 984 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 985 } 986 987 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 988 assert(DMaskLanes != 0); 989 990 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 991 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 992 return EVT::getVectorVT(Ty->getContext(), 993 EVT::getEVT(VT->getElementType()), 994 NumElts); 995 } 996 997 return EVT::getEVT(Ty); 998 } 999 1000 // Peek through TFE struct returns to only use the data size. 1001 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1002 auto *ST = dyn_cast<StructType>(Ty); 1003 if (!ST) 1004 return memVTFromImageData(Ty, DMaskLanes); 1005 1006 // Some intrinsics return an aggregate type - special case to work out the 1007 // correct memVT. 1008 // 1009 // Only limited forms of aggregate type currently expected. 1010 if (ST->getNumContainedTypes() != 2 || 1011 !ST->getContainedType(1)->isIntegerTy(32)) 1012 return EVT(); 1013 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1014 } 1015 1016 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1017 const CallInst &CI, 1018 MachineFunction &MF, 1019 unsigned IntrID) const { 1020 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1021 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1022 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1023 (Intrinsic::ID)IntrID); 1024 if (Attr.hasFnAttribute(Attribute::ReadNone)) 1025 return false; 1026 1027 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1028 1029 if (RsrcIntr->IsImage) { 1030 Info.ptrVal = 1031 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1032 Info.align.reset(); 1033 } else { 1034 Info.ptrVal = 1035 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1036 } 1037 1038 Info.flags = MachineMemOperand::MODereferenceable; 1039 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 1040 unsigned DMaskLanes = 4; 1041 1042 if (RsrcIntr->IsImage) { 1043 const AMDGPU::ImageDimIntrinsicInfo *Intr 1044 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1045 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1046 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1047 1048 if (!BaseOpcode->Gather4) { 1049 // If this isn't a gather, we may have excess loaded elements in the 1050 // IR type. Check the dmask for the real number of elements loaded. 1051 unsigned DMask 1052 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1053 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1054 } 1055 1056 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1057 } else 1058 Info.memVT = EVT::getEVT(CI.getType()); 1059 1060 // FIXME: What does alignment mean for an image? 1061 Info.opc = ISD::INTRINSIC_W_CHAIN; 1062 Info.flags |= MachineMemOperand::MOLoad; 1063 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1064 Info.opc = ISD::INTRINSIC_VOID; 1065 1066 Type *DataTy = CI.getArgOperand(0)->getType(); 1067 if (RsrcIntr->IsImage) { 1068 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1069 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1070 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1071 } else 1072 Info.memVT = EVT::getEVT(DataTy); 1073 1074 Info.flags |= MachineMemOperand::MOStore; 1075 } else { 1076 // Atomic 1077 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1078 ISD::INTRINSIC_W_CHAIN; 1079 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1080 Info.flags = MachineMemOperand::MOLoad | 1081 MachineMemOperand::MOStore | 1082 MachineMemOperand::MODereferenceable; 1083 1084 // XXX - Should this be volatile without known ordering? 1085 Info.flags |= MachineMemOperand::MOVolatile; 1086 } 1087 return true; 1088 } 1089 1090 switch (IntrID) { 1091 case Intrinsic::amdgcn_atomic_inc: 1092 case Intrinsic::amdgcn_atomic_dec: 1093 case Intrinsic::amdgcn_ds_ordered_add: 1094 case Intrinsic::amdgcn_ds_ordered_swap: 1095 case Intrinsic::amdgcn_ds_fadd: 1096 case Intrinsic::amdgcn_ds_fmin: 1097 case Intrinsic::amdgcn_ds_fmax: { 1098 Info.opc = ISD::INTRINSIC_W_CHAIN; 1099 Info.memVT = MVT::getVT(CI.getType()); 1100 Info.ptrVal = CI.getOperand(0); 1101 Info.align.reset(); 1102 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1103 1104 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1105 if (!Vol->isZero()) 1106 Info.flags |= MachineMemOperand::MOVolatile; 1107 1108 return true; 1109 } 1110 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1111 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1112 1113 Info.opc = ISD::INTRINSIC_W_CHAIN; 1114 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1115 Info.ptrVal = 1116 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1117 Info.align.reset(); 1118 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1119 1120 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1121 if (!Vol || !Vol->isZero()) 1122 Info.flags |= MachineMemOperand::MOVolatile; 1123 1124 return true; 1125 } 1126 case Intrinsic::amdgcn_ds_append: 1127 case Intrinsic::amdgcn_ds_consume: { 1128 Info.opc = ISD::INTRINSIC_W_CHAIN; 1129 Info.memVT = MVT::getVT(CI.getType()); 1130 Info.ptrVal = CI.getOperand(0); 1131 Info.align.reset(); 1132 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1133 1134 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1135 if (!Vol->isZero()) 1136 Info.flags |= MachineMemOperand::MOVolatile; 1137 1138 return true; 1139 } 1140 case Intrinsic::amdgcn_global_atomic_csub: { 1141 Info.opc = ISD::INTRINSIC_W_CHAIN; 1142 Info.memVT = MVT::getVT(CI.getType()); 1143 Info.ptrVal = CI.getOperand(0); 1144 Info.align.reset(); 1145 Info.flags = MachineMemOperand::MOLoad | 1146 MachineMemOperand::MOStore | 1147 MachineMemOperand::MOVolatile; 1148 return true; 1149 } 1150 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1151 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1152 Info.opc = ISD::INTRINSIC_W_CHAIN; 1153 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1154 Info.ptrVal = 1155 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1156 Info.align.reset(); 1157 Info.flags = MachineMemOperand::MOLoad | 1158 MachineMemOperand::MODereferenceable; 1159 return true; 1160 } 1161 case Intrinsic::amdgcn_global_atomic_fadd: 1162 case Intrinsic::amdgcn_global_atomic_fmin: 1163 case Intrinsic::amdgcn_global_atomic_fmax: 1164 case Intrinsic::amdgcn_flat_atomic_fadd: 1165 case Intrinsic::amdgcn_flat_atomic_fmin: 1166 case Intrinsic::amdgcn_flat_atomic_fmax: { 1167 Info.opc = ISD::INTRINSIC_W_CHAIN; 1168 Info.memVT = MVT::getVT(CI.getType()); 1169 Info.ptrVal = CI.getOperand(0); 1170 Info.align.reset(); 1171 Info.flags = MachineMemOperand::MOLoad | 1172 MachineMemOperand::MOStore | 1173 MachineMemOperand::MODereferenceable | 1174 MachineMemOperand::MOVolatile; 1175 return true; 1176 } 1177 case Intrinsic::amdgcn_ds_gws_init: 1178 case Intrinsic::amdgcn_ds_gws_barrier: 1179 case Intrinsic::amdgcn_ds_gws_sema_v: 1180 case Intrinsic::amdgcn_ds_gws_sema_br: 1181 case Intrinsic::amdgcn_ds_gws_sema_p: 1182 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1183 Info.opc = ISD::INTRINSIC_VOID; 1184 1185 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1186 Info.ptrVal = 1187 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1188 1189 // This is an abstract access, but we need to specify a type and size. 1190 Info.memVT = MVT::i32; 1191 Info.size = 4; 1192 Info.align = Align(4); 1193 1194 Info.flags = MachineMemOperand::MOStore; 1195 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1196 Info.flags = MachineMemOperand::MOLoad; 1197 return true; 1198 } 1199 default: 1200 return false; 1201 } 1202 } 1203 1204 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1205 SmallVectorImpl<Value*> &Ops, 1206 Type *&AccessTy) const { 1207 switch (II->getIntrinsicID()) { 1208 case Intrinsic::amdgcn_atomic_inc: 1209 case Intrinsic::amdgcn_atomic_dec: 1210 case Intrinsic::amdgcn_ds_ordered_add: 1211 case Intrinsic::amdgcn_ds_ordered_swap: 1212 case Intrinsic::amdgcn_ds_append: 1213 case Intrinsic::amdgcn_ds_consume: 1214 case Intrinsic::amdgcn_ds_fadd: 1215 case Intrinsic::amdgcn_ds_fmin: 1216 case Intrinsic::amdgcn_ds_fmax: 1217 case Intrinsic::amdgcn_global_atomic_fadd: 1218 case Intrinsic::amdgcn_flat_atomic_fadd: 1219 case Intrinsic::amdgcn_flat_atomic_fmin: 1220 case Intrinsic::amdgcn_flat_atomic_fmax: 1221 case Intrinsic::amdgcn_global_atomic_csub: { 1222 Value *Ptr = II->getArgOperand(0); 1223 AccessTy = II->getType(); 1224 Ops.push_back(Ptr); 1225 return true; 1226 } 1227 default: 1228 return false; 1229 } 1230 } 1231 1232 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1233 if (!Subtarget->hasFlatInstOffsets()) { 1234 // Flat instructions do not have offsets, and only have the register 1235 // address. 1236 return AM.BaseOffs == 0 && AM.Scale == 0; 1237 } 1238 1239 return AM.Scale == 0 && 1240 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1241 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1242 /*Signed=*/false)); 1243 } 1244 1245 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1246 if (Subtarget->hasFlatGlobalInsts()) 1247 return AM.Scale == 0 && 1248 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1249 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1250 /*Signed=*/true)); 1251 1252 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1253 // Assume the we will use FLAT for all global memory accesses 1254 // on VI. 1255 // FIXME: This assumption is currently wrong. On VI we still use 1256 // MUBUF instructions for the r + i addressing mode. As currently 1257 // implemented, the MUBUF instructions only work on buffer < 4GB. 1258 // It may be possible to support > 4GB buffers with MUBUF instructions, 1259 // by setting the stride value in the resource descriptor which would 1260 // increase the size limit to (stride * 4GB). However, this is risky, 1261 // because it has never been validated. 1262 return isLegalFlatAddressingMode(AM); 1263 } 1264 1265 return isLegalMUBUFAddressingMode(AM); 1266 } 1267 1268 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1269 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1270 // additionally can do r + r + i with addr64. 32-bit has more addressing 1271 // mode options. Depending on the resource constant, it can also do 1272 // (i64 r0) + (i32 r1) * (i14 i). 1273 // 1274 // Private arrays end up using a scratch buffer most of the time, so also 1275 // assume those use MUBUF instructions. Scratch loads / stores are currently 1276 // implemented as mubuf instructions with offen bit set, so slightly 1277 // different than the normal addr64. 1278 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1279 return false; 1280 1281 // FIXME: Since we can split immediate into soffset and immediate offset, 1282 // would it make sense to allow any immediate? 1283 1284 switch (AM.Scale) { 1285 case 0: // r + i or just i, depending on HasBaseReg. 1286 return true; 1287 case 1: 1288 return true; // We have r + r or r + i. 1289 case 2: 1290 if (AM.HasBaseReg) { 1291 // Reject 2 * r + r. 1292 return false; 1293 } 1294 1295 // Allow 2 * r as r + r 1296 // Or 2 * r + i is allowed as r + r + i. 1297 return true; 1298 default: // Don't allow n * r 1299 return false; 1300 } 1301 } 1302 1303 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1304 const AddrMode &AM, Type *Ty, 1305 unsigned AS, Instruction *I) const { 1306 // No global is ever allowed as a base. 1307 if (AM.BaseGV) 1308 return false; 1309 1310 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1311 return isLegalGlobalAddressingMode(AM); 1312 1313 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1314 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1315 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1316 // If the offset isn't a multiple of 4, it probably isn't going to be 1317 // correctly aligned. 1318 // FIXME: Can we get the real alignment here? 1319 if (AM.BaseOffs % 4 != 0) 1320 return isLegalMUBUFAddressingMode(AM); 1321 1322 // There are no SMRD extloads, so if we have to do a small type access we 1323 // will use a MUBUF load. 1324 // FIXME?: We also need to do this if unaligned, but we don't know the 1325 // alignment here. 1326 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1327 return isLegalGlobalAddressingMode(AM); 1328 1329 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1330 // SMRD instructions have an 8-bit, dword offset on SI. 1331 if (!isUInt<8>(AM.BaseOffs / 4)) 1332 return false; 1333 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1334 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1335 // in 8-bits, it can use a smaller encoding. 1336 if (!isUInt<32>(AM.BaseOffs / 4)) 1337 return false; 1338 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1339 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1340 if (!isUInt<20>(AM.BaseOffs)) 1341 return false; 1342 } else 1343 llvm_unreachable("unhandled generation"); 1344 1345 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1346 return true; 1347 1348 if (AM.Scale == 1 && AM.HasBaseReg) 1349 return true; 1350 1351 return false; 1352 1353 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1354 return isLegalMUBUFAddressingMode(AM); 1355 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1356 AS == AMDGPUAS::REGION_ADDRESS) { 1357 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1358 // field. 1359 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1360 // an 8-bit dword offset but we don't know the alignment here. 1361 if (!isUInt<16>(AM.BaseOffs)) 1362 return false; 1363 1364 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1365 return true; 1366 1367 if (AM.Scale == 1 && AM.HasBaseReg) 1368 return true; 1369 1370 return false; 1371 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1372 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1373 // For an unknown address space, this usually means that this is for some 1374 // reason being used for pure arithmetic, and not based on some addressing 1375 // computation. We don't have instructions that compute pointers with any 1376 // addressing modes, so treat them as having no offset like flat 1377 // instructions. 1378 return isLegalFlatAddressingMode(AM); 1379 } 1380 1381 // Assume a user alias of global for unknown address spaces. 1382 return isLegalGlobalAddressingMode(AM); 1383 } 1384 1385 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1386 const SelectionDAG &DAG) const { 1387 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1388 return (MemVT.getSizeInBits() <= 4 * 32); 1389 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1390 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1391 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1392 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1393 return (MemVT.getSizeInBits() <= 2 * 32); 1394 } 1395 return true; 1396 } 1397 1398 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1399 unsigned Size, unsigned AddrSpace, Align Alignment, 1400 MachineMemOperand::Flags Flags, bool *IsFast) const { 1401 if (IsFast) 1402 *IsFast = false; 1403 1404 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1405 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1406 // Check if alignment requirements for ds_read/write instructions are 1407 // disabled. 1408 if (Subtarget->hasUnalignedDSAccessEnabled() && 1409 !Subtarget->hasLDSMisalignedBug()) { 1410 if (IsFast) 1411 *IsFast = Alignment != Align(2); 1412 return true; 1413 } 1414 1415 if (Size == 64) { 1416 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1417 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1418 // with adjacent offsets. 1419 bool AlignedBy4 = Alignment >= Align(4); 1420 if (IsFast) 1421 *IsFast = AlignedBy4; 1422 1423 return AlignedBy4; 1424 } 1425 if (Size == 96) { 1426 // ds_read/write_b96 require 16-byte alignment on gfx8 and older. 1427 bool Aligned = Alignment >= Align(16); 1428 if (IsFast) 1429 *IsFast = Aligned; 1430 1431 return Aligned; 1432 } 1433 if (Size == 128) { 1434 // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we 1435 // can do a 8 byte aligned, 16 byte access in a single operation using 1436 // ds_read2/write2_b64. 1437 bool Aligned = Alignment >= Align(8); 1438 if (IsFast) 1439 *IsFast = Aligned; 1440 1441 return Aligned; 1442 } 1443 } 1444 1445 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1446 bool AlignedBy4 = Alignment >= Align(4); 1447 if (IsFast) 1448 *IsFast = AlignedBy4; 1449 1450 return AlignedBy4 || 1451 Subtarget->enableFlatScratch() || 1452 Subtarget->hasUnalignedScratchAccess(); 1453 } 1454 1455 // FIXME: We have to be conservative here and assume that flat operations 1456 // will access scratch. If we had access to the IR function, then we 1457 // could determine if any private memory was used in the function. 1458 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1459 !Subtarget->hasUnalignedScratchAccess()) { 1460 bool AlignedBy4 = Alignment >= Align(4); 1461 if (IsFast) 1462 *IsFast = AlignedBy4; 1463 1464 return AlignedBy4; 1465 } 1466 1467 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1468 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1469 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1470 // If we have an uniform constant load, it still requires using a slow 1471 // buffer instruction if unaligned. 1472 if (IsFast) { 1473 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1474 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1475 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1476 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1477 Alignment >= Align(4) : Alignment != Align(2); 1478 } 1479 1480 return true; 1481 } 1482 1483 // Smaller than dword value must be aligned. 1484 if (Size < 32) 1485 return false; 1486 1487 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1488 // byte-address are ignored, thus forcing Dword alignment. 1489 // This applies to private, global, and constant memory. 1490 if (IsFast) 1491 *IsFast = true; 1492 1493 return Size >= 32 && Alignment >= Align(4); 1494 } 1495 1496 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1497 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1498 bool *IsFast) const { 1499 if (IsFast) 1500 *IsFast = false; 1501 1502 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1503 // which isn't a simple VT. 1504 // Until MVT is extended to handle this, simply check for the size and 1505 // rely on the condition below: allow accesses if the size is a multiple of 4. 1506 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1507 VT.getStoreSize() > 16)) { 1508 return false; 1509 } 1510 1511 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1512 Alignment, Flags, IsFast); 1513 } 1514 1515 EVT SITargetLowering::getOptimalMemOpType( 1516 const MemOp &Op, const AttributeList &FuncAttributes) const { 1517 // FIXME: Should account for address space here. 1518 1519 // The default fallback uses the private pointer size as a guess for a type to 1520 // use. Make sure we switch these to 64-bit accesses. 1521 1522 if (Op.size() >= 16 && 1523 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1524 return MVT::v4i32; 1525 1526 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1527 return MVT::v2i32; 1528 1529 // Use the default. 1530 return MVT::Other; 1531 } 1532 1533 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1534 const MemSDNode *MemNode = cast<MemSDNode>(N); 1535 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1536 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1537 return I && I->getMetadata("amdgpu.noclobber"); 1538 } 1539 1540 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1541 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1542 AS == AMDGPUAS::PRIVATE_ADDRESS; 1543 } 1544 1545 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1546 unsigned DestAS) const { 1547 // Flat -> private/local is a simple truncate. 1548 // Flat -> global is no-op 1549 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1550 return true; 1551 1552 const GCNTargetMachine &TM = 1553 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1554 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1555 } 1556 1557 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1558 const MemSDNode *MemNode = cast<MemSDNode>(N); 1559 1560 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1561 } 1562 1563 TargetLoweringBase::LegalizeTypeAction 1564 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1565 int NumElts = VT.getVectorNumElements(); 1566 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1567 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1568 return TargetLoweringBase::getPreferredVectorAction(VT); 1569 } 1570 1571 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1572 Type *Ty) const { 1573 // FIXME: Could be smarter if called for vector constants. 1574 return true; 1575 } 1576 1577 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1578 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1579 switch (Op) { 1580 case ISD::LOAD: 1581 case ISD::STORE: 1582 1583 // These operations are done with 32-bit instructions anyway. 1584 case ISD::AND: 1585 case ISD::OR: 1586 case ISD::XOR: 1587 case ISD::SELECT: 1588 // TODO: Extensions? 1589 return true; 1590 default: 1591 return false; 1592 } 1593 } 1594 1595 // SimplifySetCC uses this function to determine whether or not it should 1596 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1597 if (VT == MVT::i1 && Op == ISD::SETCC) 1598 return false; 1599 1600 return TargetLowering::isTypeDesirableForOp(Op, VT); 1601 } 1602 1603 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1604 const SDLoc &SL, 1605 SDValue Chain, 1606 uint64_t Offset) const { 1607 const DataLayout &DL = DAG.getDataLayout(); 1608 MachineFunction &MF = DAG.getMachineFunction(); 1609 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1610 1611 const ArgDescriptor *InputPtrReg; 1612 const TargetRegisterClass *RC; 1613 LLT ArgTy; 1614 1615 std::tie(InputPtrReg, RC, ArgTy) = 1616 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1617 1618 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1619 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1620 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1621 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1622 1623 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1624 } 1625 1626 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1627 const SDLoc &SL) const { 1628 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1629 FIRST_IMPLICIT); 1630 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1631 } 1632 1633 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1634 const SDLoc &SL, SDValue Val, 1635 bool Signed, 1636 const ISD::InputArg *Arg) const { 1637 // First, if it is a widened vector, narrow it. 1638 if (VT.isVector() && 1639 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1640 EVT NarrowedVT = 1641 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1642 VT.getVectorNumElements()); 1643 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1644 DAG.getConstant(0, SL, MVT::i32)); 1645 } 1646 1647 // Then convert the vector elements or scalar value. 1648 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1649 VT.bitsLT(MemVT)) { 1650 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1651 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1652 } 1653 1654 if (MemVT.isFloatingPoint()) 1655 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1656 else if (Signed) 1657 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1658 else 1659 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1660 1661 return Val; 1662 } 1663 1664 SDValue SITargetLowering::lowerKernargMemParameter( 1665 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1666 uint64_t Offset, Align Alignment, bool Signed, 1667 const ISD::InputArg *Arg) const { 1668 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1669 1670 // Try to avoid using an extload by loading earlier than the argument address, 1671 // and extracting the relevant bits. The load should hopefully be merged with 1672 // the previous argument. 1673 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1674 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1675 int64_t AlignDownOffset = alignDown(Offset, 4); 1676 int64_t OffsetDiff = Offset - AlignDownOffset; 1677 1678 EVT IntVT = MemVT.changeTypeToInteger(); 1679 1680 // TODO: If we passed in the base kernel offset we could have a better 1681 // alignment than 4, but we don't really need it. 1682 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1683 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1684 MachineMemOperand::MODereferenceable | 1685 MachineMemOperand::MOInvariant); 1686 1687 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1688 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1689 1690 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1691 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1692 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1693 1694 1695 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1696 } 1697 1698 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1699 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1700 MachineMemOperand::MODereferenceable | 1701 MachineMemOperand::MOInvariant); 1702 1703 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1704 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1705 } 1706 1707 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1708 const SDLoc &SL, SDValue Chain, 1709 const ISD::InputArg &Arg) const { 1710 MachineFunction &MF = DAG.getMachineFunction(); 1711 MachineFrameInfo &MFI = MF.getFrameInfo(); 1712 1713 if (Arg.Flags.isByVal()) { 1714 unsigned Size = Arg.Flags.getByValSize(); 1715 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1716 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1717 } 1718 1719 unsigned ArgOffset = VA.getLocMemOffset(); 1720 unsigned ArgSize = VA.getValVT().getStoreSize(); 1721 1722 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1723 1724 // Create load nodes to retrieve arguments from the stack. 1725 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1726 SDValue ArgValue; 1727 1728 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1729 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1730 MVT MemVT = VA.getValVT(); 1731 1732 switch (VA.getLocInfo()) { 1733 default: 1734 break; 1735 case CCValAssign::BCvt: 1736 MemVT = VA.getLocVT(); 1737 break; 1738 case CCValAssign::SExt: 1739 ExtType = ISD::SEXTLOAD; 1740 break; 1741 case CCValAssign::ZExt: 1742 ExtType = ISD::ZEXTLOAD; 1743 break; 1744 case CCValAssign::AExt: 1745 ExtType = ISD::EXTLOAD; 1746 break; 1747 } 1748 1749 ArgValue = DAG.getExtLoad( 1750 ExtType, SL, VA.getLocVT(), Chain, FIN, 1751 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1752 MemVT); 1753 return ArgValue; 1754 } 1755 1756 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1757 const SIMachineFunctionInfo &MFI, 1758 EVT VT, 1759 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1760 const ArgDescriptor *Reg; 1761 const TargetRegisterClass *RC; 1762 LLT Ty; 1763 1764 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1765 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1766 } 1767 1768 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1769 CallingConv::ID CallConv, 1770 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1771 FunctionType *FType, 1772 SIMachineFunctionInfo *Info) { 1773 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1774 const ISD::InputArg *Arg = &Ins[I]; 1775 1776 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1777 "vector type argument should have been split"); 1778 1779 // First check if it's a PS input addr. 1780 if (CallConv == CallingConv::AMDGPU_PS && 1781 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1782 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1783 1784 // Inconveniently only the first part of the split is marked as isSplit, 1785 // so skip to the end. We only want to increment PSInputNum once for the 1786 // entire split argument. 1787 if (Arg->Flags.isSplit()) { 1788 while (!Arg->Flags.isSplitEnd()) { 1789 assert((!Arg->VT.isVector() || 1790 Arg->VT.getScalarSizeInBits() == 16) && 1791 "unexpected vector split in ps argument type"); 1792 if (!SkipArg) 1793 Splits.push_back(*Arg); 1794 Arg = &Ins[++I]; 1795 } 1796 } 1797 1798 if (SkipArg) { 1799 // We can safely skip PS inputs. 1800 Skipped.set(Arg->getOrigArgIndex()); 1801 ++PSInputNum; 1802 continue; 1803 } 1804 1805 Info->markPSInputAllocated(PSInputNum); 1806 if (Arg->Used) 1807 Info->markPSInputEnabled(PSInputNum); 1808 1809 ++PSInputNum; 1810 } 1811 1812 Splits.push_back(*Arg); 1813 } 1814 } 1815 1816 // Allocate special inputs passed in VGPRs. 1817 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1818 MachineFunction &MF, 1819 const SIRegisterInfo &TRI, 1820 SIMachineFunctionInfo &Info) const { 1821 const LLT S32 = LLT::scalar(32); 1822 MachineRegisterInfo &MRI = MF.getRegInfo(); 1823 1824 if (Info.hasWorkItemIDX()) { 1825 Register Reg = AMDGPU::VGPR0; 1826 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1827 1828 CCInfo.AllocateReg(Reg); 1829 unsigned Mask = (Subtarget->hasPackedTID() && 1830 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 1831 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1832 } 1833 1834 if (Info.hasWorkItemIDY()) { 1835 assert(Info.hasWorkItemIDX()); 1836 if (Subtarget->hasPackedTID()) { 1837 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1838 0x3ff << 10)); 1839 } else { 1840 unsigned Reg = AMDGPU::VGPR1; 1841 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1842 1843 CCInfo.AllocateReg(Reg); 1844 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1845 } 1846 } 1847 1848 if (Info.hasWorkItemIDZ()) { 1849 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 1850 if (Subtarget->hasPackedTID()) { 1851 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1852 0x3ff << 20)); 1853 } else { 1854 unsigned Reg = AMDGPU::VGPR2; 1855 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1856 1857 CCInfo.AllocateReg(Reg); 1858 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1859 } 1860 } 1861 } 1862 1863 // Try to allocate a VGPR at the end of the argument list, or if no argument 1864 // VGPRs are left allocating a stack slot. 1865 // If \p Mask is is given it indicates bitfield position in the register. 1866 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1867 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1868 ArgDescriptor Arg = ArgDescriptor()) { 1869 if (Arg.isSet()) 1870 return ArgDescriptor::createArg(Arg, Mask); 1871 1872 ArrayRef<MCPhysReg> ArgVGPRs 1873 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1874 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1875 if (RegIdx == ArgVGPRs.size()) { 1876 // Spill to stack required. 1877 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1878 1879 return ArgDescriptor::createStack(Offset, Mask); 1880 } 1881 1882 unsigned Reg = ArgVGPRs[RegIdx]; 1883 Reg = CCInfo.AllocateReg(Reg); 1884 assert(Reg != AMDGPU::NoRegister); 1885 1886 MachineFunction &MF = CCInfo.getMachineFunction(); 1887 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1888 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1889 return ArgDescriptor::createRegister(Reg, Mask); 1890 } 1891 1892 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1893 const TargetRegisterClass *RC, 1894 unsigned NumArgRegs) { 1895 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1896 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1897 if (RegIdx == ArgSGPRs.size()) 1898 report_fatal_error("ran out of SGPRs for arguments"); 1899 1900 unsigned Reg = ArgSGPRs[RegIdx]; 1901 Reg = CCInfo.AllocateReg(Reg); 1902 assert(Reg != AMDGPU::NoRegister); 1903 1904 MachineFunction &MF = CCInfo.getMachineFunction(); 1905 MF.addLiveIn(Reg, RC); 1906 return ArgDescriptor::createRegister(Reg); 1907 } 1908 1909 // If this has a fixed position, we still should allocate the register in the 1910 // CCInfo state. Technically we could get away with this for values passed 1911 // outside of the normal argument range. 1912 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 1913 const TargetRegisterClass *RC, 1914 MCRegister Reg) { 1915 Reg = CCInfo.AllocateReg(Reg); 1916 assert(Reg != AMDGPU::NoRegister); 1917 MachineFunction &MF = CCInfo.getMachineFunction(); 1918 MF.addLiveIn(Reg, RC); 1919 } 1920 1921 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 1922 if (Arg) { 1923 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 1924 Arg.getRegister()); 1925 } else 1926 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1927 } 1928 1929 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 1930 if (Arg) { 1931 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 1932 Arg.getRegister()); 1933 } else 1934 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1935 } 1936 1937 /// Allocate implicit function VGPR arguments at the end of allocated user 1938 /// arguments. 1939 void SITargetLowering::allocateSpecialInputVGPRs( 1940 CCState &CCInfo, MachineFunction &MF, 1941 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1942 const unsigned Mask = 0x3ff; 1943 ArgDescriptor Arg; 1944 1945 if (Info.hasWorkItemIDX()) { 1946 Arg = allocateVGPR32Input(CCInfo, Mask); 1947 Info.setWorkItemIDX(Arg); 1948 } 1949 1950 if (Info.hasWorkItemIDY()) { 1951 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1952 Info.setWorkItemIDY(Arg); 1953 } 1954 1955 if (Info.hasWorkItemIDZ()) 1956 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1957 } 1958 1959 /// Allocate implicit function VGPR arguments in fixed registers. 1960 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1961 CCState &CCInfo, MachineFunction &MF, 1962 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1963 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1964 if (!Reg) 1965 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1966 1967 const unsigned Mask = 0x3ff; 1968 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1969 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1970 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1971 } 1972 1973 void SITargetLowering::allocateSpecialInputSGPRs( 1974 CCState &CCInfo, 1975 MachineFunction &MF, 1976 const SIRegisterInfo &TRI, 1977 SIMachineFunctionInfo &Info) const { 1978 auto &ArgInfo = Info.getArgInfo(); 1979 1980 // TODO: Unify handling with private memory pointers. 1981 1982 if (Info.hasDispatchPtr()) 1983 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 1984 1985 if (Info.hasQueuePtr()) 1986 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 1987 1988 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1989 // constant offset from the kernarg segment. 1990 if (Info.hasImplicitArgPtr()) 1991 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 1992 1993 if (Info.hasDispatchID()) 1994 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 1995 1996 // flat_scratch_init is not applicable for non-kernel functions. 1997 1998 if (Info.hasWorkGroupIDX()) 1999 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2000 2001 if (Info.hasWorkGroupIDY()) 2002 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2003 2004 if (Info.hasWorkGroupIDZ()) 2005 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2006 } 2007 2008 // Allocate special inputs passed in user SGPRs. 2009 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2010 MachineFunction &MF, 2011 const SIRegisterInfo &TRI, 2012 SIMachineFunctionInfo &Info) const { 2013 if (Info.hasImplicitBufferPtr()) { 2014 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2015 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2016 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2017 } 2018 2019 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2020 if (Info.hasPrivateSegmentBuffer()) { 2021 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2022 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2023 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2024 } 2025 2026 if (Info.hasDispatchPtr()) { 2027 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2028 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2029 CCInfo.AllocateReg(DispatchPtrReg); 2030 } 2031 2032 if (Info.hasQueuePtr()) { 2033 Register QueuePtrReg = Info.addQueuePtr(TRI); 2034 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2035 CCInfo.AllocateReg(QueuePtrReg); 2036 } 2037 2038 if (Info.hasKernargSegmentPtr()) { 2039 MachineRegisterInfo &MRI = MF.getRegInfo(); 2040 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2041 CCInfo.AllocateReg(InputPtrReg); 2042 2043 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2044 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2045 } 2046 2047 if (Info.hasDispatchID()) { 2048 Register DispatchIDReg = Info.addDispatchID(TRI); 2049 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2050 CCInfo.AllocateReg(DispatchIDReg); 2051 } 2052 2053 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2054 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2055 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2056 CCInfo.AllocateReg(FlatScratchInitReg); 2057 } 2058 2059 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2060 // these from the dispatch pointer. 2061 } 2062 2063 // Allocate special input registers that are initialized per-wave. 2064 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2065 MachineFunction &MF, 2066 SIMachineFunctionInfo &Info, 2067 CallingConv::ID CallConv, 2068 bool IsShader) const { 2069 if (Info.hasWorkGroupIDX()) { 2070 Register Reg = Info.addWorkGroupIDX(); 2071 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2072 CCInfo.AllocateReg(Reg); 2073 } 2074 2075 if (Info.hasWorkGroupIDY()) { 2076 Register Reg = Info.addWorkGroupIDY(); 2077 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2078 CCInfo.AllocateReg(Reg); 2079 } 2080 2081 if (Info.hasWorkGroupIDZ()) { 2082 Register Reg = Info.addWorkGroupIDZ(); 2083 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2084 CCInfo.AllocateReg(Reg); 2085 } 2086 2087 if (Info.hasWorkGroupInfo()) { 2088 Register Reg = Info.addWorkGroupInfo(); 2089 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2090 CCInfo.AllocateReg(Reg); 2091 } 2092 2093 if (Info.hasPrivateSegmentWaveByteOffset()) { 2094 // Scratch wave offset passed in system SGPR. 2095 unsigned PrivateSegmentWaveByteOffsetReg; 2096 2097 if (IsShader) { 2098 PrivateSegmentWaveByteOffsetReg = 2099 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2100 2101 // This is true if the scratch wave byte offset doesn't have a fixed 2102 // location. 2103 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2104 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2105 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2106 } 2107 } else 2108 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2109 2110 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2111 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2112 } 2113 } 2114 2115 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2116 MachineFunction &MF, 2117 const SIRegisterInfo &TRI, 2118 SIMachineFunctionInfo &Info) { 2119 // Now that we've figured out where the scratch register inputs are, see if 2120 // should reserve the arguments and use them directly. 2121 MachineFrameInfo &MFI = MF.getFrameInfo(); 2122 bool HasStackObjects = MFI.hasStackObjects(); 2123 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2124 2125 // Record that we know we have non-spill stack objects so we don't need to 2126 // check all stack objects later. 2127 if (HasStackObjects) 2128 Info.setHasNonSpillStackObjects(true); 2129 2130 // Everything live out of a block is spilled with fast regalloc, so it's 2131 // almost certain that spilling will be required. 2132 if (TM.getOptLevel() == CodeGenOpt::None) 2133 HasStackObjects = true; 2134 2135 // For now assume stack access is needed in any callee functions, so we need 2136 // the scratch registers to pass in. 2137 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2138 2139 if (!ST.enableFlatScratch()) { 2140 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2141 // If we have stack objects, we unquestionably need the private buffer 2142 // resource. For the Code Object V2 ABI, this will be the first 4 user 2143 // SGPR inputs. We can reserve those and use them directly. 2144 2145 Register PrivateSegmentBufferReg = 2146 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2147 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2148 } else { 2149 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2150 // We tentatively reserve the last registers (skipping the last registers 2151 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2152 // we'll replace these with the ones immediately after those which were 2153 // really allocated. In the prologue copies will be inserted from the 2154 // argument to these reserved registers. 2155 2156 // Without HSA, relocations are used for the scratch pointer and the 2157 // buffer resource setup is always inserted in the prologue. Scratch wave 2158 // offset is still in an input SGPR. 2159 Info.setScratchRSrcReg(ReservedBufferReg); 2160 } 2161 } 2162 2163 MachineRegisterInfo &MRI = MF.getRegInfo(); 2164 2165 // For entry functions we have to set up the stack pointer if we use it, 2166 // whereas non-entry functions get this "for free". This means there is no 2167 // intrinsic advantage to using S32 over S34 in cases where we do not have 2168 // calls but do need a frame pointer (i.e. if we are requested to have one 2169 // because frame pointer elimination is disabled). To keep things simple we 2170 // only ever use S32 as the call ABI stack pointer, and so using it does not 2171 // imply we need a separate frame pointer. 2172 // 2173 // Try to use s32 as the SP, but move it if it would interfere with input 2174 // arguments. This won't work with calls though. 2175 // 2176 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2177 // registers. 2178 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2179 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2180 } else { 2181 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2182 2183 if (MFI.hasCalls()) 2184 report_fatal_error("call in graphics shader with too many input SGPRs"); 2185 2186 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2187 if (!MRI.isLiveIn(Reg)) { 2188 Info.setStackPtrOffsetReg(Reg); 2189 break; 2190 } 2191 } 2192 2193 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2194 report_fatal_error("failed to find register for SP"); 2195 } 2196 2197 // hasFP should be accurate for entry functions even before the frame is 2198 // finalized, because it does not rely on the known stack size, only 2199 // properties like whether variable sized objects are present. 2200 if (ST.getFrameLowering()->hasFP(MF)) { 2201 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2202 } 2203 } 2204 2205 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2206 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2207 return !Info->isEntryFunction(); 2208 } 2209 2210 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2211 2212 } 2213 2214 void SITargetLowering::insertCopiesSplitCSR( 2215 MachineBasicBlock *Entry, 2216 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2217 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2218 2219 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2220 if (!IStart) 2221 return; 2222 2223 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2224 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2225 MachineBasicBlock::iterator MBBI = Entry->begin(); 2226 for (const MCPhysReg *I = IStart; *I; ++I) { 2227 const TargetRegisterClass *RC = nullptr; 2228 if (AMDGPU::SReg_64RegClass.contains(*I)) 2229 RC = &AMDGPU::SGPR_64RegClass; 2230 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2231 RC = &AMDGPU::SGPR_32RegClass; 2232 else 2233 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2234 2235 Register NewVR = MRI->createVirtualRegister(RC); 2236 // Create copy from CSR to a virtual register. 2237 Entry->addLiveIn(*I); 2238 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2239 .addReg(*I); 2240 2241 // Insert the copy-back instructions right before the terminator. 2242 for (auto *Exit : Exits) 2243 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2244 TII->get(TargetOpcode::COPY), *I) 2245 .addReg(NewVR); 2246 } 2247 } 2248 2249 SDValue SITargetLowering::LowerFormalArguments( 2250 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2251 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2252 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2253 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2254 2255 MachineFunction &MF = DAG.getMachineFunction(); 2256 const Function &Fn = MF.getFunction(); 2257 FunctionType *FType = MF.getFunction().getFunctionType(); 2258 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2259 2260 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2261 DiagnosticInfoUnsupported NoGraphicsHSA( 2262 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2263 DAG.getContext()->diagnose(NoGraphicsHSA); 2264 return DAG.getEntryNode(); 2265 } 2266 2267 Info->allocateModuleLDSGlobal(Fn.getParent()); 2268 2269 SmallVector<ISD::InputArg, 16> Splits; 2270 SmallVector<CCValAssign, 16> ArgLocs; 2271 BitVector Skipped(Ins.size()); 2272 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2273 *DAG.getContext()); 2274 2275 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2276 bool IsKernel = AMDGPU::isKernel(CallConv); 2277 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2278 2279 if (IsGraphics) { 2280 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2281 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2282 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2283 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2284 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2285 !Info->hasWorkItemIDZ()); 2286 } 2287 2288 if (CallConv == CallingConv::AMDGPU_PS) { 2289 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2290 2291 // At least one interpolation mode must be enabled or else the GPU will 2292 // hang. 2293 // 2294 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2295 // set PSInputAddr, the user wants to enable some bits after the compilation 2296 // based on run-time states. Since we can't know what the final PSInputEna 2297 // will look like, so we shouldn't do anything here and the user should take 2298 // responsibility for the correct programming. 2299 // 2300 // Otherwise, the following restrictions apply: 2301 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2302 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2303 // enabled too. 2304 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2305 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2306 CCInfo.AllocateReg(AMDGPU::VGPR0); 2307 CCInfo.AllocateReg(AMDGPU::VGPR1); 2308 Info->markPSInputAllocated(0); 2309 Info->markPSInputEnabled(0); 2310 } 2311 if (Subtarget->isAmdPalOS()) { 2312 // For isAmdPalOS, the user does not enable some bits after compilation 2313 // based on run-time states; the register values being generated here are 2314 // the final ones set in hardware. Therefore we need to apply the 2315 // workaround to PSInputAddr and PSInputEnable together. (The case where 2316 // a bit is set in PSInputAddr but not PSInputEnable is where the 2317 // frontend set up an input arg for a particular interpolation mode, but 2318 // nothing uses that input arg. Really we should have an earlier pass 2319 // that removes such an arg.) 2320 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2321 if ((PsInputBits & 0x7F) == 0 || 2322 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2323 Info->markPSInputEnabled( 2324 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2325 } 2326 } else if (IsKernel) { 2327 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2328 } else { 2329 Splits.append(Ins.begin(), Ins.end()); 2330 } 2331 2332 if (IsEntryFunc) { 2333 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2334 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2335 } else { 2336 // For the fixed ABI, pass workitem IDs in the last argument register. 2337 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2338 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2339 } 2340 2341 if (IsKernel) { 2342 analyzeFormalArgumentsCompute(CCInfo, Ins); 2343 } else { 2344 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2345 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2346 } 2347 2348 SmallVector<SDValue, 16> Chains; 2349 2350 // FIXME: This is the minimum kernel argument alignment. We should improve 2351 // this to the maximum alignment of the arguments. 2352 // 2353 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2354 // kern arg offset. 2355 const Align KernelArgBaseAlign = Align(16); 2356 2357 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2358 const ISD::InputArg &Arg = Ins[i]; 2359 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2360 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2361 continue; 2362 } 2363 2364 CCValAssign &VA = ArgLocs[ArgIdx++]; 2365 MVT VT = VA.getLocVT(); 2366 2367 if (IsEntryFunc && VA.isMemLoc()) { 2368 VT = Ins[i].VT; 2369 EVT MemVT = VA.getLocVT(); 2370 2371 const uint64_t Offset = VA.getLocMemOffset(); 2372 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2373 2374 if (Arg.Flags.isByRef()) { 2375 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2376 2377 const GCNTargetMachine &TM = 2378 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2379 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2380 Arg.Flags.getPointerAddrSpace())) { 2381 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2382 Arg.Flags.getPointerAddrSpace()); 2383 } 2384 2385 InVals.push_back(Ptr); 2386 continue; 2387 } 2388 2389 SDValue Arg = lowerKernargMemParameter( 2390 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2391 Chains.push_back(Arg.getValue(1)); 2392 2393 auto *ParamTy = 2394 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2395 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2396 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2397 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2398 // On SI local pointers are just offsets into LDS, so they are always 2399 // less than 16-bits. On CI and newer they could potentially be 2400 // real pointers, so we can't guarantee their size. 2401 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2402 DAG.getValueType(MVT::i16)); 2403 } 2404 2405 InVals.push_back(Arg); 2406 continue; 2407 } else if (!IsEntryFunc && VA.isMemLoc()) { 2408 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2409 InVals.push_back(Val); 2410 if (!Arg.Flags.isByVal()) 2411 Chains.push_back(Val.getValue(1)); 2412 continue; 2413 } 2414 2415 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2416 2417 Register Reg = VA.getLocReg(); 2418 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2419 EVT ValVT = VA.getValVT(); 2420 2421 Reg = MF.addLiveIn(Reg, RC); 2422 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2423 2424 if (Arg.Flags.isSRet()) { 2425 // The return object should be reasonably addressable. 2426 2427 // FIXME: This helps when the return is a real sret. If it is a 2428 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2429 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2430 unsigned NumBits 2431 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2432 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2433 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2434 } 2435 2436 // If this is an 8 or 16-bit value, it is really passed promoted 2437 // to 32 bits. Insert an assert[sz]ext to capture this, then 2438 // truncate to the right size. 2439 switch (VA.getLocInfo()) { 2440 case CCValAssign::Full: 2441 break; 2442 case CCValAssign::BCvt: 2443 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2444 break; 2445 case CCValAssign::SExt: 2446 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2447 DAG.getValueType(ValVT)); 2448 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2449 break; 2450 case CCValAssign::ZExt: 2451 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2452 DAG.getValueType(ValVT)); 2453 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2454 break; 2455 case CCValAssign::AExt: 2456 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2457 break; 2458 default: 2459 llvm_unreachable("Unknown loc info!"); 2460 } 2461 2462 InVals.push_back(Val); 2463 } 2464 2465 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2466 // Special inputs come after user arguments. 2467 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2468 } 2469 2470 // Start adding system SGPRs. 2471 if (IsEntryFunc) { 2472 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2473 } else { 2474 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2475 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2476 } 2477 2478 auto &ArgUsageInfo = 2479 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2480 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2481 2482 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2483 Info->setBytesInStackArgArea(StackArgSize); 2484 2485 return Chains.empty() ? Chain : 2486 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2487 } 2488 2489 // TODO: If return values can't fit in registers, we should return as many as 2490 // possible in registers before passing on stack. 2491 bool SITargetLowering::CanLowerReturn( 2492 CallingConv::ID CallConv, 2493 MachineFunction &MF, bool IsVarArg, 2494 const SmallVectorImpl<ISD::OutputArg> &Outs, 2495 LLVMContext &Context) const { 2496 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2497 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2498 // for shaders. Vector types should be explicitly handled by CC. 2499 if (AMDGPU::isEntryFunctionCC(CallConv)) 2500 return true; 2501 2502 SmallVector<CCValAssign, 16> RVLocs; 2503 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2504 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2505 } 2506 2507 SDValue 2508 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2509 bool isVarArg, 2510 const SmallVectorImpl<ISD::OutputArg> &Outs, 2511 const SmallVectorImpl<SDValue> &OutVals, 2512 const SDLoc &DL, SelectionDAG &DAG) const { 2513 MachineFunction &MF = DAG.getMachineFunction(); 2514 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2515 2516 if (AMDGPU::isKernel(CallConv)) { 2517 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2518 OutVals, DL, DAG); 2519 } 2520 2521 bool IsShader = AMDGPU::isShader(CallConv); 2522 2523 Info->setIfReturnsVoid(Outs.empty()); 2524 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2525 2526 // CCValAssign - represent the assignment of the return value to a location. 2527 SmallVector<CCValAssign, 48> RVLocs; 2528 SmallVector<ISD::OutputArg, 48> Splits; 2529 2530 // CCState - Info about the registers and stack slots. 2531 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2532 *DAG.getContext()); 2533 2534 // Analyze outgoing return values. 2535 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2536 2537 SDValue Flag; 2538 SmallVector<SDValue, 48> RetOps; 2539 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2540 2541 // Add return address for callable functions. 2542 if (!Info->isEntryFunction()) { 2543 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2544 SDValue ReturnAddrReg = CreateLiveInRegister( 2545 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2546 2547 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2548 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2549 MVT::i64); 2550 Chain = 2551 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2552 Flag = Chain.getValue(1); 2553 RetOps.push_back(ReturnAddrVirtualReg); 2554 } 2555 2556 // Copy the result values into the output registers. 2557 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2558 ++I, ++RealRVLocIdx) { 2559 CCValAssign &VA = RVLocs[I]; 2560 assert(VA.isRegLoc() && "Can only return in registers!"); 2561 // TODO: Partially return in registers if return values don't fit. 2562 SDValue Arg = OutVals[RealRVLocIdx]; 2563 2564 // Copied from other backends. 2565 switch (VA.getLocInfo()) { 2566 case CCValAssign::Full: 2567 break; 2568 case CCValAssign::BCvt: 2569 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2570 break; 2571 case CCValAssign::SExt: 2572 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2573 break; 2574 case CCValAssign::ZExt: 2575 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2576 break; 2577 case CCValAssign::AExt: 2578 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2579 break; 2580 default: 2581 llvm_unreachable("Unknown loc info!"); 2582 } 2583 2584 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2585 Flag = Chain.getValue(1); 2586 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2587 } 2588 2589 // FIXME: Does sret work properly? 2590 if (!Info->isEntryFunction()) { 2591 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2592 const MCPhysReg *I = 2593 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2594 if (I) { 2595 for (; *I; ++I) { 2596 if (AMDGPU::SReg_64RegClass.contains(*I)) 2597 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2598 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2599 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2600 else 2601 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2602 } 2603 } 2604 } 2605 2606 // Update chain and glue. 2607 RetOps[0] = Chain; 2608 if (Flag.getNode()) 2609 RetOps.push_back(Flag); 2610 2611 unsigned Opc = AMDGPUISD::ENDPGM; 2612 if (!IsWaveEnd) 2613 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2614 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2615 } 2616 2617 SDValue SITargetLowering::LowerCallResult( 2618 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2619 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2620 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2621 SDValue ThisVal) const { 2622 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2623 2624 // Assign locations to each value returned by this call. 2625 SmallVector<CCValAssign, 16> RVLocs; 2626 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2627 *DAG.getContext()); 2628 CCInfo.AnalyzeCallResult(Ins, RetCC); 2629 2630 // Copy all of the result registers out of their specified physreg. 2631 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2632 CCValAssign VA = RVLocs[i]; 2633 SDValue Val; 2634 2635 if (VA.isRegLoc()) { 2636 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2637 Chain = Val.getValue(1); 2638 InFlag = Val.getValue(2); 2639 } else if (VA.isMemLoc()) { 2640 report_fatal_error("TODO: return values in memory"); 2641 } else 2642 llvm_unreachable("unknown argument location type"); 2643 2644 switch (VA.getLocInfo()) { 2645 case CCValAssign::Full: 2646 break; 2647 case CCValAssign::BCvt: 2648 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2649 break; 2650 case CCValAssign::ZExt: 2651 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2652 DAG.getValueType(VA.getValVT())); 2653 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2654 break; 2655 case CCValAssign::SExt: 2656 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2657 DAG.getValueType(VA.getValVT())); 2658 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2659 break; 2660 case CCValAssign::AExt: 2661 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2662 break; 2663 default: 2664 llvm_unreachable("Unknown loc info!"); 2665 } 2666 2667 InVals.push_back(Val); 2668 } 2669 2670 return Chain; 2671 } 2672 2673 // Add code to pass special inputs required depending on used features separate 2674 // from the explicit user arguments present in the IR. 2675 void SITargetLowering::passSpecialInputs( 2676 CallLoweringInfo &CLI, 2677 CCState &CCInfo, 2678 const SIMachineFunctionInfo &Info, 2679 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2680 SmallVectorImpl<SDValue> &MemOpChains, 2681 SDValue Chain) const { 2682 // If we don't have a call site, this was a call inserted by 2683 // legalization. These can never use special inputs. 2684 if (!CLI.CB) 2685 return; 2686 2687 SelectionDAG &DAG = CLI.DAG; 2688 const SDLoc &DL = CLI.DL; 2689 2690 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2691 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2692 2693 const AMDGPUFunctionArgInfo *CalleeArgInfo 2694 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2695 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2696 auto &ArgUsageInfo = 2697 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2698 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2699 } 2700 2701 // TODO: Unify with private memory register handling. This is complicated by 2702 // the fact that at least in kernels, the input argument is not necessarily 2703 // in the same location as the input. 2704 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2705 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2706 AMDGPUFunctionArgInfo::QUEUE_PTR, 2707 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2708 AMDGPUFunctionArgInfo::DISPATCH_ID, 2709 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2710 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2711 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2712 }; 2713 2714 for (auto InputID : InputRegs) { 2715 const ArgDescriptor *OutgoingArg; 2716 const TargetRegisterClass *ArgRC; 2717 LLT ArgTy; 2718 2719 std::tie(OutgoingArg, ArgRC, ArgTy) = 2720 CalleeArgInfo->getPreloadedValue(InputID); 2721 if (!OutgoingArg) 2722 continue; 2723 2724 const ArgDescriptor *IncomingArg; 2725 const TargetRegisterClass *IncomingArgRC; 2726 LLT Ty; 2727 std::tie(IncomingArg, IncomingArgRC, Ty) = 2728 CallerArgInfo.getPreloadedValue(InputID); 2729 assert(IncomingArgRC == ArgRC); 2730 2731 // All special arguments are ints for now. 2732 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2733 SDValue InputReg; 2734 2735 if (IncomingArg) { 2736 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2737 } else { 2738 // The implicit arg ptr is special because it doesn't have a corresponding 2739 // input for kernels, and is computed from the kernarg segment pointer. 2740 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2741 InputReg = getImplicitArgPtr(DAG, DL); 2742 } 2743 2744 if (OutgoingArg->isRegister()) { 2745 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2746 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2747 report_fatal_error("failed to allocate implicit input argument"); 2748 } else { 2749 unsigned SpecialArgOffset = 2750 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2751 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2752 SpecialArgOffset); 2753 MemOpChains.push_back(ArgStore); 2754 } 2755 } 2756 2757 // Pack workitem IDs into a single register or pass it as is if already 2758 // packed. 2759 const ArgDescriptor *OutgoingArg; 2760 const TargetRegisterClass *ArgRC; 2761 LLT Ty; 2762 2763 std::tie(OutgoingArg, ArgRC, Ty) = 2764 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2765 if (!OutgoingArg) 2766 std::tie(OutgoingArg, ArgRC, Ty) = 2767 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2768 if (!OutgoingArg) 2769 std::tie(OutgoingArg, ArgRC, Ty) = 2770 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2771 if (!OutgoingArg) 2772 return; 2773 2774 const ArgDescriptor *IncomingArgX = std::get<0>( 2775 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2776 const ArgDescriptor *IncomingArgY = std::get<0>( 2777 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2778 const ArgDescriptor *IncomingArgZ = std::get<0>( 2779 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2780 2781 SDValue InputReg; 2782 SDLoc SL; 2783 2784 // If incoming ids are not packed we need to pack them. 2785 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2786 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2787 2788 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2789 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2790 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2791 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2792 InputReg = InputReg.getNode() ? 2793 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2794 } 2795 2796 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2797 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2798 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2799 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2800 InputReg = InputReg.getNode() ? 2801 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2802 } 2803 2804 if (!InputReg.getNode()) { 2805 // Workitem ids are already packed, any of present incoming arguments 2806 // will carry all required fields. 2807 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2808 IncomingArgX ? *IncomingArgX : 2809 IncomingArgY ? *IncomingArgY : 2810 *IncomingArgZ, ~0u); 2811 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2812 } 2813 2814 if (OutgoingArg->isRegister()) { 2815 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2816 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2817 } else { 2818 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2819 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2820 SpecialArgOffset); 2821 MemOpChains.push_back(ArgStore); 2822 } 2823 } 2824 2825 static bool canGuaranteeTCO(CallingConv::ID CC) { 2826 return CC == CallingConv::Fast; 2827 } 2828 2829 /// Return true if we might ever do TCO for calls with this calling convention. 2830 static bool mayTailCallThisCC(CallingConv::ID CC) { 2831 switch (CC) { 2832 case CallingConv::C: 2833 case CallingConv::AMDGPU_Gfx: 2834 return true; 2835 default: 2836 return canGuaranteeTCO(CC); 2837 } 2838 } 2839 2840 bool SITargetLowering::isEligibleForTailCallOptimization( 2841 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2842 const SmallVectorImpl<ISD::OutputArg> &Outs, 2843 const SmallVectorImpl<SDValue> &OutVals, 2844 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2845 if (!mayTailCallThisCC(CalleeCC)) 2846 return false; 2847 2848 MachineFunction &MF = DAG.getMachineFunction(); 2849 const Function &CallerF = MF.getFunction(); 2850 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2851 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2852 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2853 2854 // Kernels aren't callable, and don't have a live in return address so it 2855 // doesn't make sense to do a tail call with entry functions. 2856 if (!CallerPreserved) 2857 return false; 2858 2859 bool CCMatch = CallerCC == CalleeCC; 2860 2861 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2862 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2863 return true; 2864 return false; 2865 } 2866 2867 // TODO: Can we handle var args? 2868 if (IsVarArg) 2869 return false; 2870 2871 for (const Argument &Arg : CallerF.args()) { 2872 if (Arg.hasByValAttr()) 2873 return false; 2874 } 2875 2876 LLVMContext &Ctx = *DAG.getContext(); 2877 2878 // Check that the call results are passed in the same way. 2879 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2880 CCAssignFnForCall(CalleeCC, IsVarArg), 2881 CCAssignFnForCall(CallerCC, IsVarArg))) 2882 return false; 2883 2884 // The callee has to preserve all registers the caller needs to preserve. 2885 if (!CCMatch) { 2886 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2887 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2888 return false; 2889 } 2890 2891 // Nothing more to check if the callee is taking no arguments. 2892 if (Outs.empty()) 2893 return true; 2894 2895 SmallVector<CCValAssign, 16> ArgLocs; 2896 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2897 2898 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2899 2900 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2901 // If the stack arguments for this call do not fit into our own save area then 2902 // the call cannot be made tail. 2903 // TODO: Is this really necessary? 2904 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2905 return false; 2906 2907 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2908 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2909 } 2910 2911 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2912 if (!CI->isTailCall()) 2913 return false; 2914 2915 const Function *ParentFn = CI->getParent()->getParent(); 2916 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2917 return false; 2918 return true; 2919 } 2920 2921 // The wave scratch offset register is used as the global base pointer. 2922 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2923 SmallVectorImpl<SDValue> &InVals) const { 2924 SelectionDAG &DAG = CLI.DAG; 2925 const SDLoc &DL = CLI.DL; 2926 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2927 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2928 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2929 SDValue Chain = CLI.Chain; 2930 SDValue Callee = CLI.Callee; 2931 bool &IsTailCall = CLI.IsTailCall; 2932 CallingConv::ID CallConv = CLI.CallConv; 2933 bool IsVarArg = CLI.IsVarArg; 2934 bool IsSibCall = false; 2935 bool IsThisReturn = false; 2936 MachineFunction &MF = DAG.getMachineFunction(); 2937 2938 if (Callee.isUndef() || isNullConstant(Callee)) { 2939 if (!CLI.IsTailCall) { 2940 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2941 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2942 } 2943 2944 return Chain; 2945 } 2946 2947 if (IsVarArg) { 2948 return lowerUnhandledCall(CLI, InVals, 2949 "unsupported call to variadic function "); 2950 } 2951 2952 if (!CLI.CB) 2953 report_fatal_error("unsupported libcall legalization"); 2954 2955 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2956 !CLI.CB->getCalledFunction() && CallConv != CallingConv::AMDGPU_Gfx) { 2957 return lowerUnhandledCall(CLI, InVals, 2958 "unsupported indirect call to function "); 2959 } 2960 2961 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2962 return lowerUnhandledCall(CLI, InVals, 2963 "unsupported required tail call to function "); 2964 } 2965 2966 if (AMDGPU::isShader(CallConv)) { 2967 // Note the issue is with the CC of the called function, not of the call 2968 // itself. 2969 return lowerUnhandledCall(CLI, InVals, 2970 "unsupported call to a shader function "); 2971 } 2972 2973 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 2974 CallConv != CallingConv::AMDGPU_Gfx) { 2975 // Only allow calls with specific calling conventions. 2976 return lowerUnhandledCall(CLI, InVals, 2977 "unsupported calling convention for call from " 2978 "graphics shader of function "); 2979 } 2980 2981 if (IsTailCall) { 2982 IsTailCall = isEligibleForTailCallOptimization( 2983 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2984 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2985 report_fatal_error("failed to perform tail call elimination on a call " 2986 "site marked musttail"); 2987 } 2988 2989 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2990 2991 // A sibling call is one where we're under the usual C ABI and not planning 2992 // to change that but can still do a tail call: 2993 if (!TailCallOpt && IsTailCall) 2994 IsSibCall = true; 2995 2996 if (IsTailCall) 2997 ++NumTailCalls; 2998 } 2999 3000 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3001 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3002 SmallVector<SDValue, 8> MemOpChains; 3003 3004 // Analyze operands of the call, assigning locations to each operand. 3005 SmallVector<CCValAssign, 16> ArgLocs; 3006 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3007 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3008 3009 if (AMDGPUTargetMachine::EnableFixedFunctionABI && 3010 CallConv != CallingConv::AMDGPU_Gfx) { 3011 // With a fixed ABI, allocate fixed registers before user arguments. 3012 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3013 } 3014 3015 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3016 3017 // Get a count of how many bytes are to be pushed on the stack. 3018 unsigned NumBytes = CCInfo.getNextStackOffset(); 3019 3020 if (IsSibCall) { 3021 // Since we're not changing the ABI to make this a tail call, the memory 3022 // operands are already available in the caller's incoming argument space. 3023 NumBytes = 0; 3024 } 3025 3026 // FPDiff is the byte offset of the call's argument area from the callee's. 3027 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3028 // by this amount for a tail call. In a sibling call it must be 0 because the 3029 // caller will deallocate the entire stack and the callee still expects its 3030 // arguments to begin at SP+0. Completely unused for non-tail calls. 3031 int32_t FPDiff = 0; 3032 MachineFrameInfo &MFI = MF.getFrameInfo(); 3033 3034 // Adjust the stack pointer for the new arguments... 3035 // These operations are automatically eliminated by the prolog/epilog pass 3036 if (!IsSibCall) { 3037 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3038 3039 if (!Subtarget->enableFlatScratch()) { 3040 SmallVector<SDValue, 4> CopyFromChains; 3041 3042 // In the HSA case, this should be an identity copy. 3043 SDValue ScratchRSrcReg 3044 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3045 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3046 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3047 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3048 } 3049 } 3050 3051 MVT PtrVT = MVT::i32; 3052 3053 // Walk the register/memloc assignments, inserting copies/loads. 3054 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3055 CCValAssign &VA = ArgLocs[i]; 3056 SDValue Arg = OutVals[i]; 3057 3058 // Promote the value if needed. 3059 switch (VA.getLocInfo()) { 3060 case CCValAssign::Full: 3061 break; 3062 case CCValAssign::BCvt: 3063 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3064 break; 3065 case CCValAssign::ZExt: 3066 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3067 break; 3068 case CCValAssign::SExt: 3069 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3070 break; 3071 case CCValAssign::AExt: 3072 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3073 break; 3074 case CCValAssign::FPExt: 3075 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3076 break; 3077 default: 3078 llvm_unreachable("Unknown loc info!"); 3079 } 3080 3081 if (VA.isRegLoc()) { 3082 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3083 } else { 3084 assert(VA.isMemLoc()); 3085 3086 SDValue DstAddr; 3087 MachinePointerInfo DstInfo; 3088 3089 unsigned LocMemOffset = VA.getLocMemOffset(); 3090 int32_t Offset = LocMemOffset; 3091 3092 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3093 MaybeAlign Alignment; 3094 3095 if (IsTailCall) { 3096 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3097 unsigned OpSize = Flags.isByVal() ? 3098 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3099 3100 // FIXME: We can have better than the minimum byval required alignment. 3101 Alignment = 3102 Flags.isByVal() 3103 ? Flags.getNonZeroByValAlign() 3104 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3105 3106 Offset = Offset + FPDiff; 3107 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3108 3109 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3110 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3111 3112 // Make sure any stack arguments overlapping with where we're storing 3113 // are loaded before this eventual operation. Otherwise they'll be 3114 // clobbered. 3115 3116 // FIXME: Why is this really necessary? This seems to just result in a 3117 // lot of code to copy the stack and write them back to the same 3118 // locations, which are supposed to be immutable? 3119 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3120 } else { 3121 DstAddr = PtrOff; 3122 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3123 Alignment = 3124 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3125 } 3126 3127 if (Outs[i].Flags.isByVal()) { 3128 SDValue SizeNode = 3129 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3130 SDValue Cpy = 3131 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3132 Outs[i].Flags.getNonZeroByValAlign(), 3133 /*isVol = */ false, /*AlwaysInline = */ true, 3134 /*isTailCall = */ false, DstInfo, 3135 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3136 3137 MemOpChains.push_back(Cpy); 3138 } else { 3139 SDValue Store = 3140 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3141 MemOpChains.push_back(Store); 3142 } 3143 } 3144 } 3145 3146 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 3147 CallConv != CallingConv::AMDGPU_Gfx) { 3148 // Copy special input registers after user input arguments. 3149 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3150 } 3151 3152 if (!MemOpChains.empty()) 3153 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3154 3155 // Build a sequence of copy-to-reg nodes chained together with token chain 3156 // and flag operands which copy the outgoing args into the appropriate regs. 3157 SDValue InFlag; 3158 for (auto &RegToPass : RegsToPass) { 3159 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3160 RegToPass.second, InFlag); 3161 InFlag = Chain.getValue(1); 3162 } 3163 3164 3165 SDValue PhysReturnAddrReg; 3166 if (IsTailCall) { 3167 // Since the return is being combined with the call, we need to pass on the 3168 // return address. 3169 3170 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3171 SDValue ReturnAddrReg = CreateLiveInRegister( 3172 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3173 3174 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3175 MVT::i64); 3176 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3177 InFlag = Chain.getValue(1); 3178 } 3179 3180 // We don't usually want to end the call-sequence here because we would tidy 3181 // the frame up *after* the call, however in the ABI-changing tail-call case 3182 // we've carefully laid out the parameters so that when sp is reset they'll be 3183 // in the correct location. 3184 if (IsTailCall && !IsSibCall) { 3185 Chain = DAG.getCALLSEQ_END(Chain, 3186 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3187 DAG.getTargetConstant(0, DL, MVT::i32), 3188 InFlag, DL); 3189 InFlag = Chain.getValue(1); 3190 } 3191 3192 std::vector<SDValue> Ops; 3193 Ops.push_back(Chain); 3194 Ops.push_back(Callee); 3195 // Add a redundant copy of the callee global which will not be legalized, as 3196 // we need direct access to the callee later. 3197 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3198 const GlobalValue *GV = GSD->getGlobal(); 3199 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3200 } else { 3201 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3202 } 3203 3204 if (IsTailCall) { 3205 // Each tail call may have to adjust the stack by a different amount, so 3206 // this information must travel along with the operation for eventual 3207 // consumption by emitEpilogue. 3208 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3209 3210 Ops.push_back(PhysReturnAddrReg); 3211 } 3212 3213 // Add argument registers to the end of the list so that they are known live 3214 // into the call. 3215 for (auto &RegToPass : RegsToPass) { 3216 Ops.push_back(DAG.getRegister(RegToPass.first, 3217 RegToPass.second.getValueType())); 3218 } 3219 3220 // Add a register mask operand representing the call-preserved registers. 3221 3222 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3223 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3224 assert(Mask && "Missing call preserved mask for calling convention"); 3225 Ops.push_back(DAG.getRegisterMask(Mask)); 3226 3227 if (InFlag.getNode()) 3228 Ops.push_back(InFlag); 3229 3230 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3231 3232 // If we're doing a tall call, use a TC_RETURN here rather than an 3233 // actual call instruction. 3234 if (IsTailCall) { 3235 MFI.setHasTailCall(); 3236 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3237 } 3238 3239 // Returns a chain and a flag for retval copy to use. 3240 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3241 Chain = Call.getValue(0); 3242 InFlag = Call.getValue(1); 3243 3244 uint64_t CalleePopBytes = NumBytes; 3245 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3246 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3247 InFlag, DL); 3248 if (!Ins.empty()) 3249 InFlag = Chain.getValue(1); 3250 3251 // Handle result values, copying them out of physregs into vregs that we 3252 // return. 3253 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3254 InVals, IsThisReturn, 3255 IsThisReturn ? OutVals[0] : SDValue()); 3256 } 3257 3258 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3259 // except for applying the wave size scale to the increment amount. 3260 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3261 SDValue Op, SelectionDAG &DAG) const { 3262 const MachineFunction &MF = DAG.getMachineFunction(); 3263 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3264 3265 SDLoc dl(Op); 3266 EVT VT = Op.getValueType(); 3267 SDValue Tmp1 = Op; 3268 SDValue Tmp2 = Op.getValue(1); 3269 SDValue Tmp3 = Op.getOperand(2); 3270 SDValue Chain = Tmp1.getOperand(0); 3271 3272 Register SPReg = Info->getStackPtrOffsetReg(); 3273 3274 // Chain the dynamic stack allocation so that it doesn't modify the stack 3275 // pointer when other instructions are using the stack. 3276 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3277 3278 SDValue Size = Tmp2.getOperand(1); 3279 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3280 Chain = SP.getValue(1); 3281 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3282 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3283 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3284 unsigned Opc = 3285 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3286 ISD::ADD : ISD::SUB; 3287 3288 SDValue ScaledSize = DAG.getNode( 3289 ISD::SHL, dl, VT, Size, 3290 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3291 3292 Align StackAlign = TFL->getStackAlign(); 3293 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3294 if (Alignment && *Alignment > StackAlign) { 3295 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3296 DAG.getConstant(-(uint64_t)Alignment->value() 3297 << ST.getWavefrontSizeLog2(), 3298 dl, VT)); 3299 } 3300 3301 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3302 Tmp2 = DAG.getCALLSEQ_END( 3303 Chain, DAG.getIntPtrConstant(0, dl, true), 3304 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3305 3306 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3307 } 3308 3309 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3310 SelectionDAG &DAG) const { 3311 // We only handle constant sizes here to allow non-entry block, static sized 3312 // allocas. A truly dynamic value is more difficult to support because we 3313 // don't know if the size value is uniform or not. If the size isn't uniform, 3314 // we would need to do a wave reduction to get the maximum size to know how 3315 // much to increment the uniform stack pointer. 3316 SDValue Size = Op.getOperand(1); 3317 if (isa<ConstantSDNode>(Size)) 3318 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3319 3320 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3321 } 3322 3323 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3324 const MachineFunction &MF) const { 3325 Register Reg = StringSwitch<Register>(RegName) 3326 .Case("m0", AMDGPU::M0) 3327 .Case("exec", AMDGPU::EXEC) 3328 .Case("exec_lo", AMDGPU::EXEC_LO) 3329 .Case("exec_hi", AMDGPU::EXEC_HI) 3330 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3331 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3332 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3333 .Default(Register()); 3334 3335 if (Reg == AMDGPU::NoRegister) { 3336 report_fatal_error(Twine("invalid register name \"" 3337 + StringRef(RegName) + "\".")); 3338 3339 } 3340 3341 if (!Subtarget->hasFlatScrRegister() && 3342 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3343 report_fatal_error(Twine("invalid register \"" 3344 + StringRef(RegName) + "\" for subtarget.")); 3345 } 3346 3347 switch (Reg) { 3348 case AMDGPU::M0: 3349 case AMDGPU::EXEC_LO: 3350 case AMDGPU::EXEC_HI: 3351 case AMDGPU::FLAT_SCR_LO: 3352 case AMDGPU::FLAT_SCR_HI: 3353 if (VT.getSizeInBits() == 32) 3354 return Reg; 3355 break; 3356 case AMDGPU::EXEC: 3357 case AMDGPU::FLAT_SCR: 3358 if (VT.getSizeInBits() == 64) 3359 return Reg; 3360 break; 3361 default: 3362 llvm_unreachable("missing register type checking"); 3363 } 3364 3365 report_fatal_error(Twine("invalid type for register \"" 3366 + StringRef(RegName) + "\".")); 3367 } 3368 3369 // If kill is not the last instruction, split the block so kill is always a 3370 // proper terminator. 3371 MachineBasicBlock * 3372 SITargetLowering::splitKillBlock(MachineInstr &MI, 3373 MachineBasicBlock *BB) const { 3374 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3375 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3376 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3377 return SplitBB; 3378 } 3379 3380 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3381 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3382 // be the first instruction in the remainder block. 3383 // 3384 /// \returns { LoopBody, Remainder } 3385 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3386 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3387 MachineFunction *MF = MBB.getParent(); 3388 MachineBasicBlock::iterator I(&MI); 3389 3390 // To insert the loop we need to split the block. Move everything after this 3391 // point to a new block, and insert a new empty block between the two. 3392 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3393 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3394 MachineFunction::iterator MBBI(MBB); 3395 ++MBBI; 3396 3397 MF->insert(MBBI, LoopBB); 3398 MF->insert(MBBI, RemainderBB); 3399 3400 LoopBB->addSuccessor(LoopBB); 3401 LoopBB->addSuccessor(RemainderBB); 3402 3403 // Move the rest of the block into a new block. 3404 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3405 3406 if (InstInLoop) { 3407 auto Next = std::next(I); 3408 3409 // Move instruction to loop body. 3410 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3411 3412 // Move the rest of the block. 3413 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3414 } else { 3415 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3416 } 3417 3418 MBB.addSuccessor(LoopBB); 3419 3420 return std::make_pair(LoopBB, RemainderBB); 3421 } 3422 3423 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3424 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3425 MachineBasicBlock *MBB = MI.getParent(); 3426 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3427 auto I = MI.getIterator(); 3428 auto E = std::next(I); 3429 3430 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3431 .addImm(0); 3432 3433 MIBundleBuilder Bundler(*MBB, I, E); 3434 finalizeBundle(*MBB, Bundler.begin()); 3435 } 3436 3437 MachineBasicBlock * 3438 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3439 MachineBasicBlock *BB) const { 3440 const DebugLoc &DL = MI.getDebugLoc(); 3441 3442 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3443 3444 MachineBasicBlock *LoopBB; 3445 MachineBasicBlock *RemainderBB; 3446 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3447 3448 // Apparently kill flags are only valid if the def is in the same block? 3449 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3450 Src->setIsKill(false); 3451 3452 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3453 3454 MachineBasicBlock::iterator I = LoopBB->end(); 3455 3456 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3457 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3458 3459 // Clear TRAP_STS.MEM_VIOL 3460 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3461 .addImm(0) 3462 .addImm(EncodedReg); 3463 3464 bundleInstWithWaitcnt(MI); 3465 3466 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3467 3468 // Load and check TRAP_STS.MEM_VIOL 3469 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3470 .addImm(EncodedReg); 3471 3472 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3473 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3474 .addReg(Reg, RegState::Kill) 3475 .addImm(0); 3476 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3477 .addMBB(LoopBB); 3478 3479 return RemainderBB; 3480 } 3481 3482 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3483 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3484 // will only do one iteration. In the worst case, this will loop 64 times. 3485 // 3486 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3487 static MachineBasicBlock::iterator 3488 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3489 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3490 const DebugLoc &DL, const MachineOperand &Idx, 3491 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3492 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3493 Register &SGPRIdxReg) { 3494 3495 MachineFunction *MF = OrigBB.getParent(); 3496 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3497 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3498 MachineBasicBlock::iterator I = LoopBB.begin(); 3499 3500 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3501 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3502 Register NewExec = MRI.createVirtualRegister(BoolRC); 3503 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3504 Register CondReg = MRI.createVirtualRegister(BoolRC); 3505 3506 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3507 .addReg(InitReg) 3508 .addMBB(&OrigBB) 3509 .addReg(ResultReg) 3510 .addMBB(&LoopBB); 3511 3512 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3513 .addReg(InitSaveExecReg) 3514 .addMBB(&OrigBB) 3515 .addReg(NewExec) 3516 .addMBB(&LoopBB); 3517 3518 // Read the next variant <- also loop target. 3519 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3520 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3521 3522 // Compare the just read M0 value to all possible Idx values. 3523 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3524 .addReg(CurrentIdxReg) 3525 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3526 3527 // Update EXEC, save the original EXEC value to VCC. 3528 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3529 : AMDGPU::S_AND_SAVEEXEC_B64), 3530 NewExec) 3531 .addReg(CondReg, RegState::Kill); 3532 3533 MRI.setSimpleHint(NewExec, CondReg); 3534 3535 if (UseGPRIdxMode) { 3536 if (Offset == 0) { 3537 SGPRIdxReg = CurrentIdxReg; 3538 } else { 3539 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3540 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3541 .addReg(CurrentIdxReg, RegState::Kill) 3542 .addImm(Offset); 3543 } 3544 } else { 3545 // Move index from VCC into M0 3546 if (Offset == 0) { 3547 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3548 .addReg(CurrentIdxReg, RegState::Kill); 3549 } else { 3550 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3551 .addReg(CurrentIdxReg, RegState::Kill) 3552 .addImm(Offset); 3553 } 3554 } 3555 3556 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3557 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3558 MachineInstr *InsertPt = 3559 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3560 : AMDGPU::S_XOR_B64_term), Exec) 3561 .addReg(Exec) 3562 .addReg(NewExec); 3563 3564 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3565 // s_cbranch_scc0? 3566 3567 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3568 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3569 .addMBB(&LoopBB); 3570 3571 return InsertPt->getIterator(); 3572 } 3573 3574 // This has slightly sub-optimal regalloc when the source vector is killed by 3575 // the read. The register allocator does not understand that the kill is 3576 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3577 // subregister from it, using 1 more VGPR than necessary. This was saved when 3578 // this was expanded after register allocation. 3579 static MachineBasicBlock::iterator 3580 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3581 unsigned InitResultReg, unsigned PhiReg, int Offset, 3582 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3583 MachineFunction *MF = MBB.getParent(); 3584 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3585 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3586 MachineRegisterInfo &MRI = MF->getRegInfo(); 3587 const DebugLoc &DL = MI.getDebugLoc(); 3588 MachineBasicBlock::iterator I(&MI); 3589 3590 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3591 Register DstReg = MI.getOperand(0).getReg(); 3592 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3593 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3594 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3595 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3596 3597 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3598 3599 // Save the EXEC mask 3600 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3601 .addReg(Exec); 3602 3603 MachineBasicBlock *LoopBB; 3604 MachineBasicBlock *RemainderBB; 3605 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3606 3607 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3608 3609 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3610 InitResultReg, DstReg, PhiReg, TmpExec, 3611 Offset, UseGPRIdxMode, SGPRIdxReg); 3612 3613 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3614 MachineFunction::iterator MBBI(LoopBB); 3615 ++MBBI; 3616 MF->insert(MBBI, LandingPad); 3617 LoopBB->removeSuccessor(RemainderBB); 3618 LandingPad->addSuccessor(RemainderBB); 3619 LoopBB->addSuccessor(LandingPad); 3620 MachineBasicBlock::iterator First = LandingPad->begin(); 3621 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3622 .addReg(SaveExec); 3623 3624 return InsPt; 3625 } 3626 3627 // Returns subreg index, offset 3628 static std::pair<unsigned, int> 3629 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3630 const TargetRegisterClass *SuperRC, 3631 unsigned VecReg, 3632 int Offset) { 3633 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3634 3635 // Skip out of bounds offsets, or else we would end up using an undefined 3636 // register. 3637 if (Offset >= NumElts || Offset < 0) 3638 return std::make_pair(AMDGPU::sub0, Offset); 3639 3640 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3641 } 3642 3643 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3644 MachineRegisterInfo &MRI, MachineInstr &MI, 3645 int Offset) { 3646 MachineBasicBlock *MBB = MI.getParent(); 3647 const DebugLoc &DL = MI.getDebugLoc(); 3648 MachineBasicBlock::iterator I(&MI); 3649 3650 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3651 3652 assert(Idx->getReg() != AMDGPU::NoRegister); 3653 3654 if (Offset == 0) { 3655 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3656 } else { 3657 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3658 .add(*Idx) 3659 .addImm(Offset); 3660 } 3661 } 3662 3663 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3664 MachineRegisterInfo &MRI, MachineInstr &MI, 3665 int Offset) { 3666 MachineBasicBlock *MBB = MI.getParent(); 3667 const DebugLoc &DL = MI.getDebugLoc(); 3668 MachineBasicBlock::iterator I(&MI); 3669 3670 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3671 3672 if (Offset == 0) 3673 return Idx->getReg(); 3674 3675 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3676 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3677 .add(*Idx) 3678 .addImm(Offset); 3679 return Tmp; 3680 } 3681 3682 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3683 MachineBasicBlock &MBB, 3684 const GCNSubtarget &ST) { 3685 const SIInstrInfo *TII = ST.getInstrInfo(); 3686 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3687 MachineFunction *MF = MBB.getParent(); 3688 MachineRegisterInfo &MRI = MF->getRegInfo(); 3689 3690 Register Dst = MI.getOperand(0).getReg(); 3691 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3692 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3693 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3694 3695 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3696 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3697 3698 unsigned SubReg; 3699 std::tie(SubReg, Offset) 3700 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3701 3702 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3703 3704 // Check for a SGPR index. 3705 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3706 MachineBasicBlock::iterator I(&MI); 3707 const DebugLoc &DL = MI.getDebugLoc(); 3708 3709 if (UseGPRIdxMode) { 3710 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3711 // to avoid interfering with other uses, so probably requires a new 3712 // optimization pass. 3713 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3714 3715 const MCInstrDesc &GPRIDXDesc = 3716 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3717 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3718 .addReg(SrcReg) 3719 .addReg(Idx) 3720 .addImm(SubReg); 3721 } else { 3722 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3723 3724 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3725 .addReg(SrcReg, 0, SubReg) 3726 .addReg(SrcReg, RegState::Implicit); 3727 } 3728 3729 MI.eraseFromParent(); 3730 3731 return &MBB; 3732 } 3733 3734 // Control flow needs to be inserted if indexing with a VGPR. 3735 const DebugLoc &DL = MI.getDebugLoc(); 3736 MachineBasicBlock::iterator I(&MI); 3737 3738 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3739 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3740 3741 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3742 3743 Register SGPRIdxReg; 3744 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3745 UseGPRIdxMode, SGPRIdxReg); 3746 3747 MachineBasicBlock *LoopBB = InsPt->getParent(); 3748 3749 if (UseGPRIdxMode) { 3750 const MCInstrDesc &GPRIDXDesc = 3751 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3752 3753 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3754 .addReg(SrcReg) 3755 .addReg(SGPRIdxReg) 3756 .addImm(SubReg); 3757 } else { 3758 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3759 .addReg(SrcReg, 0, SubReg) 3760 .addReg(SrcReg, RegState::Implicit); 3761 } 3762 3763 MI.eraseFromParent(); 3764 3765 return LoopBB; 3766 } 3767 3768 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3769 MachineBasicBlock &MBB, 3770 const GCNSubtarget &ST) { 3771 const SIInstrInfo *TII = ST.getInstrInfo(); 3772 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3773 MachineFunction *MF = MBB.getParent(); 3774 MachineRegisterInfo &MRI = MF->getRegInfo(); 3775 3776 Register Dst = MI.getOperand(0).getReg(); 3777 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3778 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3779 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3780 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3781 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3782 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3783 3784 // This can be an immediate, but will be folded later. 3785 assert(Val->getReg()); 3786 3787 unsigned SubReg; 3788 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3789 SrcVec->getReg(), 3790 Offset); 3791 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3792 3793 if (Idx->getReg() == AMDGPU::NoRegister) { 3794 MachineBasicBlock::iterator I(&MI); 3795 const DebugLoc &DL = MI.getDebugLoc(); 3796 3797 assert(Offset == 0); 3798 3799 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3800 .add(*SrcVec) 3801 .add(*Val) 3802 .addImm(SubReg); 3803 3804 MI.eraseFromParent(); 3805 return &MBB; 3806 } 3807 3808 // Check for a SGPR index. 3809 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3810 MachineBasicBlock::iterator I(&MI); 3811 const DebugLoc &DL = MI.getDebugLoc(); 3812 3813 if (UseGPRIdxMode) { 3814 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3815 3816 const MCInstrDesc &GPRIDXDesc = 3817 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3818 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3819 .addReg(SrcVec->getReg()) 3820 .add(*Val) 3821 .addReg(Idx) 3822 .addImm(SubReg); 3823 } else { 3824 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3825 3826 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3827 TRI.getRegSizeInBits(*VecRC), 32, false); 3828 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3829 .addReg(SrcVec->getReg()) 3830 .add(*Val) 3831 .addImm(SubReg); 3832 } 3833 MI.eraseFromParent(); 3834 return &MBB; 3835 } 3836 3837 // Control flow needs to be inserted if indexing with a VGPR. 3838 if (Val->isReg()) 3839 MRI.clearKillFlags(Val->getReg()); 3840 3841 const DebugLoc &DL = MI.getDebugLoc(); 3842 3843 Register PhiReg = MRI.createVirtualRegister(VecRC); 3844 3845 Register SGPRIdxReg; 3846 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3847 UseGPRIdxMode, SGPRIdxReg); 3848 MachineBasicBlock *LoopBB = InsPt->getParent(); 3849 3850 if (UseGPRIdxMode) { 3851 const MCInstrDesc &GPRIDXDesc = 3852 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3853 3854 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3855 .addReg(PhiReg) 3856 .add(*Val) 3857 .addReg(SGPRIdxReg) 3858 .addImm(AMDGPU::sub0); 3859 } else { 3860 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3861 TRI.getRegSizeInBits(*VecRC), 32, false); 3862 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3863 .addReg(PhiReg) 3864 .add(*Val) 3865 .addImm(AMDGPU::sub0); 3866 } 3867 3868 MI.eraseFromParent(); 3869 return LoopBB; 3870 } 3871 3872 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3873 MachineInstr &MI, MachineBasicBlock *BB) const { 3874 3875 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3876 MachineFunction *MF = BB->getParent(); 3877 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3878 3879 switch (MI.getOpcode()) { 3880 case AMDGPU::S_UADDO_PSEUDO: 3881 case AMDGPU::S_USUBO_PSEUDO: { 3882 const DebugLoc &DL = MI.getDebugLoc(); 3883 MachineOperand &Dest0 = MI.getOperand(0); 3884 MachineOperand &Dest1 = MI.getOperand(1); 3885 MachineOperand &Src0 = MI.getOperand(2); 3886 MachineOperand &Src1 = MI.getOperand(3); 3887 3888 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3889 ? AMDGPU::S_ADD_I32 3890 : AMDGPU::S_SUB_I32; 3891 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3892 3893 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3894 .addImm(1) 3895 .addImm(0); 3896 3897 MI.eraseFromParent(); 3898 return BB; 3899 } 3900 case AMDGPU::S_ADD_U64_PSEUDO: 3901 case AMDGPU::S_SUB_U64_PSEUDO: { 3902 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3903 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3904 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3905 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3906 const DebugLoc &DL = MI.getDebugLoc(); 3907 3908 MachineOperand &Dest = MI.getOperand(0); 3909 MachineOperand &Src0 = MI.getOperand(1); 3910 MachineOperand &Src1 = MI.getOperand(2); 3911 3912 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3913 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3914 3915 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3916 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3917 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3918 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3919 3920 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3921 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3922 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3923 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3924 3925 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3926 3927 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3928 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3929 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3930 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3931 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3932 .addReg(DestSub0) 3933 .addImm(AMDGPU::sub0) 3934 .addReg(DestSub1) 3935 .addImm(AMDGPU::sub1); 3936 MI.eraseFromParent(); 3937 return BB; 3938 } 3939 case AMDGPU::V_ADD_U64_PSEUDO: 3940 case AMDGPU::V_SUB_U64_PSEUDO: { 3941 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3942 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3943 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3944 const DebugLoc &DL = MI.getDebugLoc(); 3945 3946 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3947 3948 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3949 3950 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3951 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3952 3953 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3954 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3955 3956 MachineOperand &Dest = MI.getOperand(0); 3957 MachineOperand &Src0 = MI.getOperand(1); 3958 MachineOperand &Src1 = MI.getOperand(2); 3959 3960 const TargetRegisterClass *Src0RC = Src0.isReg() 3961 ? MRI.getRegClass(Src0.getReg()) 3962 : &AMDGPU::VReg_64RegClass; 3963 const TargetRegisterClass *Src1RC = Src1.isReg() 3964 ? MRI.getRegClass(Src1.getReg()) 3965 : &AMDGPU::VReg_64RegClass; 3966 3967 const TargetRegisterClass *Src0SubRC = 3968 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3969 const TargetRegisterClass *Src1SubRC = 3970 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3971 3972 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3973 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3974 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3975 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3976 3977 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3978 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3979 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3980 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3981 3982 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 3983 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3984 .addReg(CarryReg, RegState::Define) 3985 .add(SrcReg0Sub0) 3986 .add(SrcReg1Sub0) 3987 .addImm(0); // clamp bit 3988 3989 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3990 MachineInstr *HiHalf = 3991 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3992 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3993 .add(SrcReg0Sub1) 3994 .add(SrcReg1Sub1) 3995 .addReg(CarryReg, RegState::Kill) 3996 .addImm(0); // clamp bit 3997 3998 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3999 .addReg(DestSub0) 4000 .addImm(AMDGPU::sub0) 4001 .addReg(DestSub1) 4002 .addImm(AMDGPU::sub1); 4003 TII->legalizeOperands(*LoHalf); 4004 TII->legalizeOperands(*HiHalf); 4005 MI.eraseFromParent(); 4006 return BB; 4007 } 4008 case AMDGPU::S_ADD_CO_PSEUDO: 4009 case AMDGPU::S_SUB_CO_PSEUDO: { 4010 // This pseudo has a chance to be selected 4011 // only from uniform add/subcarry node. All the VGPR operands 4012 // therefore assumed to be splat vectors. 4013 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4014 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4015 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4016 MachineBasicBlock::iterator MII = MI; 4017 const DebugLoc &DL = MI.getDebugLoc(); 4018 MachineOperand &Dest = MI.getOperand(0); 4019 MachineOperand &CarryDest = MI.getOperand(1); 4020 MachineOperand &Src0 = MI.getOperand(2); 4021 MachineOperand &Src1 = MI.getOperand(3); 4022 MachineOperand &Src2 = MI.getOperand(4); 4023 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4024 ? AMDGPU::S_ADDC_U32 4025 : AMDGPU::S_SUBB_U32; 4026 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4027 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4028 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4029 .addReg(Src0.getReg()); 4030 Src0.setReg(RegOp0); 4031 } 4032 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4033 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4034 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4035 .addReg(Src1.getReg()); 4036 Src1.setReg(RegOp1); 4037 } 4038 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4039 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4040 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4041 .addReg(Src2.getReg()); 4042 Src2.setReg(RegOp2); 4043 } 4044 4045 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4046 if (TRI->getRegSizeInBits(*Src2RC) == 64) { 4047 if (ST.hasScalarCompareEq64()) { 4048 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4049 .addReg(Src2.getReg()) 4050 .addImm(0); 4051 } else { 4052 const TargetRegisterClass *SubRC = 4053 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4054 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4055 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4056 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4057 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4058 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4059 4060 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4061 .add(Src2Sub0) 4062 .add(Src2Sub1); 4063 4064 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4065 .addReg(Src2_32, RegState::Kill) 4066 .addImm(0); 4067 } 4068 } else { 4069 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4070 .addReg(Src2.getReg()) 4071 .addImm(0); 4072 } 4073 4074 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4075 4076 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 4077 .addReg(AMDGPU::SCC); 4078 MI.eraseFromParent(); 4079 return BB; 4080 } 4081 case AMDGPU::SI_INIT_M0: { 4082 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4083 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4084 .add(MI.getOperand(0)); 4085 MI.eraseFromParent(); 4086 return BB; 4087 } 4088 case AMDGPU::GET_GROUPSTATICSIZE: { 4089 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4090 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4091 DebugLoc DL = MI.getDebugLoc(); 4092 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4093 .add(MI.getOperand(0)) 4094 .addImm(MFI->getLDSSize()); 4095 MI.eraseFromParent(); 4096 return BB; 4097 } 4098 case AMDGPU::SI_INDIRECT_SRC_V1: 4099 case AMDGPU::SI_INDIRECT_SRC_V2: 4100 case AMDGPU::SI_INDIRECT_SRC_V4: 4101 case AMDGPU::SI_INDIRECT_SRC_V8: 4102 case AMDGPU::SI_INDIRECT_SRC_V16: 4103 case AMDGPU::SI_INDIRECT_SRC_V32: 4104 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4105 case AMDGPU::SI_INDIRECT_DST_V1: 4106 case AMDGPU::SI_INDIRECT_DST_V2: 4107 case AMDGPU::SI_INDIRECT_DST_V4: 4108 case AMDGPU::SI_INDIRECT_DST_V8: 4109 case AMDGPU::SI_INDIRECT_DST_V16: 4110 case AMDGPU::SI_INDIRECT_DST_V32: 4111 return emitIndirectDst(MI, *BB, *getSubtarget()); 4112 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4113 case AMDGPU::SI_KILL_I1_PSEUDO: 4114 return splitKillBlock(MI, BB); 4115 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4116 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4117 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4118 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4119 4120 Register Dst = MI.getOperand(0).getReg(); 4121 Register Src0 = MI.getOperand(1).getReg(); 4122 Register Src1 = MI.getOperand(2).getReg(); 4123 const DebugLoc &DL = MI.getDebugLoc(); 4124 Register SrcCond = MI.getOperand(3).getReg(); 4125 4126 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4127 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4128 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4129 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4130 4131 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4132 .addReg(SrcCond); 4133 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4134 .addImm(0) 4135 .addReg(Src0, 0, AMDGPU::sub0) 4136 .addImm(0) 4137 .addReg(Src1, 0, AMDGPU::sub0) 4138 .addReg(SrcCondCopy); 4139 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4140 .addImm(0) 4141 .addReg(Src0, 0, AMDGPU::sub1) 4142 .addImm(0) 4143 .addReg(Src1, 0, AMDGPU::sub1) 4144 .addReg(SrcCondCopy); 4145 4146 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4147 .addReg(DstLo) 4148 .addImm(AMDGPU::sub0) 4149 .addReg(DstHi) 4150 .addImm(AMDGPU::sub1); 4151 MI.eraseFromParent(); 4152 return BB; 4153 } 4154 case AMDGPU::SI_BR_UNDEF: { 4155 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4156 const DebugLoc &DL = MI.getDebugLoc(); 4157 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4158 .add(MI.getOperand(0)); 4159 Br->getOperand(1).setIsUndef(true); // read undef SCC 4160 MI.eraseFromParent(); 4161 return BB; 4162 } 4163 case AMDGPU::ADJCALLSTACKUP: 4164 case AMDGPU::ADJCALLSTACKDOWN: { 4165 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4166 MachineInstrBuilder MIB(*MF, &MI); 4167 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4168 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4169 return BB; 4170 } 4171 case AMDGPU::SI_CALL_ISEL: { 4172 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4173 const DebugLoc &DL = MI.getDebugLoc(); 4174 4175 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4176 4177 MachineInstrBuilder MIB; 4178 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4179 4180 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4181 MIB.add(MI.getOperand(I)); 4182 4183 MIB.cloneMemRefs(MI); 4184 MI.eraseFromParent(); 4185 return BB; 4186 } 4187 case AMDGPU::V_ADD_CO_U32_e32: 4188 case AMDGPU::V_SUB_CO_U32_e32: 4189 case AMDGPU::V_SUBREV_CO_U32_e32: { 4190 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4191 const DebugLoc &DL = MI.getDebugLoc(); 4192 unsigned Opc = MI.getOpcode(); 4193 4194 bool NeedClampOperand = false; 4195 if (TII->pseudoToMCOpcode(Opc) == -1) { 4196 Opc = AMDGPU::getVOPe64(Opc); 4197 NeedClampOperand = true; 4198 } 4199 4200 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4201 if (TII->isVOP3(*I)) { 4202 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4203 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4204 I.addReg(TRI->getVCC(), RegState::Define); 4205 } 4206 I.add(MI.getOperand(1)) 4207 .add(MI.getOperand(2)); 4208 if (NeedClampOperand) 4209 I.addImm(0); // clamp bit for e64 encoding 4210 4211 TII->legalizeOperands(*I); 4212 4213 MI.eraseFromParent(); 4214 return BB; 4215 } 4216 case AMDGPU::DS_GWS_INIT: 4217 case AMDGPU::DS_GWS_SEMA_V: 4218 case AMDGPU::DS_GWS_SEMA_BR: 4219 case AMDGPU::DS_GWS_SEMA_P: 4220 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4221 case AMDGPU::DS_GWS_BARRIER: 4222 // A s_waitcnt 0 is required to be the instruction immediately following. 4223 if (getSubtarget()->hasGWSAutoReplay()) { 4224 bundleInstWithWaitcnt(MI); 4225 return BB; 4226 } 4227 4228 return emitGWSMemViolTestLoop(MI, BB); 4229 case AMDGPU::S_SETREG_B32: { 4230 // Try to optimize cases that only set the denormal mode or rounding mode. 4231 // 4232 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4233 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4234 // instead. 4235 // 4236 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4237 // allow you to have a no side effect instruction in the output of a 4238 // sideeffecting pattern. 4239 unsigned ID, Offset, Width; 4240 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4241 if (ID != AMDGPU::Hwreg::ID_MODE) 4242 return BB; 4243 4244 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4245 const unsigned SetMask = WidthMask << Offset; 4246 4247 if (getSubtarget()->hasDenormModeInst()) { 4248 unsigned SetDenormOp = 0; 4249 unsigned SetRoundOp = 0; 4250 4251 // The dedicated instructions can only set the whole denorm or round mode 4252 // at once, not a subset of bits in either. 4253 if (SetMask == 4254 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4255 // If this fully sets both the round and denorm mode, emit the two 4256 // dedicated instructions for these. 4257 SetRoundOp = AMDGPU::S_ROUND_MODE; 4258 SetDenormOp = AMDGPU::S_DENORM_MODE; 4259 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4260 SetRoundOp = AMDGPU::S_ROUND_MODE; 4261 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4262 SetDenormOp = AMDGPU::S_DENORM_MODE; 4263 } 4264 4265 if (SetRoundOp || SetDenormOp) { 4266 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4267 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4268 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4269 unsigned ImmVal = Def->getOperand(1).getImm(); 4270 if (SetRoundOp) { 4271 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4272 .addImm(ImmVal & 0xf); 4273 4274 // If we also have the denorm mode, get just the denorm mode bits. 4275 ImmVal >>= 4; 4276 } 4277 4278 if (SetDenormOp) { 4279 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4280 .addImm(ImmVal & 0xf); 4281 } 4282 4283 MI.eraseFromParent(); 4284 return BB; 4285 } 4286 } 4287 } 4288 4289 // If only FP bits are touched, used the no side effects pseudo. 4290 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4291 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4292 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4293 4294 return BB; 4295 } 4296 default: 4297 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4298 } 4299 } 4300 4301 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4302 return isTypeLegal(VT.getScalarType()); 4303 } 4304 4305 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4306 // This currently forces unfolding various combinations of fsub into fma with 4307 // free fneg'd operands. As long as we have fast FMA (controlled by 4308 // isFMAFasterThanFMulAndFAdd), we should perform these. 4309 4310 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4311 // most of these combines appear to be cycle neutral but save on instruction 4312 // count / code size. 4313 return true; 4314 } 4315 4316 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4317 EVT VT) const { 4318 if (!VT.isVector()) { 4319 return MVT::i1; 4320 } 4321 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4322 } 4323 4324 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4325 // TODO: Should i16 be used always if legal? For now it would force VALU 4326 // shifts. 4327 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4328 } 4329 4330 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4331 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4332 ? Ty.changeElementSize(16) 4333 : Ty.changeElementSize(32); 4334 } 4335 4336 // Answering this is somewhat tricky and depends on the specific device which 4337 // have different rates for fma or all f64 operations. 4338 // 4339 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4340 // regardless of which device (although the number of cycles differs between 4341 // devices), so it is always profitable for f64. 4342 // 4343 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4344 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4345 // which we can always do even without fused FP ops since it returns the same 4346 // result as the separate operations and since it is always full 4347 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4348 // however does not support denormals, so we do report fma as faster if we have 4349 // a fast fma device and require denormals. 4350 // 4351 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4352 EVT VT) const { 4353 VT = VT.getScalarType(); 4354 4355 switch (VT.getSimpleVT().SimpleTy) { 4356 case MVT::f32: { 4357 // If mad is not available this depends only on if f32 fma is full rate. 4358 if (!Subtarget->hasMadMacF32Insts()) 4359 return Subtarget->hasFastFMAF32(); 4360 4361 // Otherwise f32 mad is always full rate and returns the same result as 4362 // the separate operations so should be preferred over fma. 4363 // However does not support denomals. 4364 if (hasFP32Denormals(MF)) 4365 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4366 4367 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4368 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4369 } 4370 case MVT::f64: 4371 return true; 4372 case MVT::f16: 4373 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4374 default: 4375 break; 4376 } 4377 4378 return false; 4379 } 4380 4381 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4382 const SDNode *N) const { 4383 // TODO: Check future ftz flag 4384 // v_mad_f32/v_mac_f32 do not support denormals. 4385 EVT VT = N->getValueType(0); 4386 if (VT == MVT::f32) 4387 return Subtarget->hasMadMacF32Insts() && 4388 !hasFP32Denormals(DAG.getMachineFunction()); 4389 if (VT == MVT::f16) { 4390 return Subtarget->hasMadF16() && 4391 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4392 } 4393 4394 return false; 4395 } 4396 4397 //===----------------------------------------------------------------------===// 4398 // Custom DAG Lowering Operations 4399 //===----------------------------------------------------------------------===// 4400 4401 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4402 // wider vector type is legal. 4403 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4404 SelectionDAG &DAG) const { 4405 unsigned Opc = Op.getOpcode(); 4406 EVT VT = Op.getValueType(); 4407 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4408 4409 SDValue Lo, Hi; 4410 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4411 4412 SDLoc SL(Op); 4413 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4414 Op->getFlags()); 4415 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4416 Op->getFlags()); 4417 4418 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4419 } 4420 4421 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4422 // wider vector type is legal. 4423 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4424 SelectionDAG &DAG) const { 4425 unsigned Opc = Op.getOpcode(); 4426 EVT VT = Op.getValueType(); 4427 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4428 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4429 4430 SDValue Lo0, Hi0; 4431 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4432 SDValue Lo1, Hi1; 4433 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4434 4435 SDLoc SL(Op); 4436 4437 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4438 Op->getFlags()); 4439 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4440 Op->getFlags()); 4441 4442 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4443 } 4444 4445 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4446 SelectionDAG &DAG) const { 4447 unsigned Opc = Op.getOpcode(); 4448 EVT VT = Op.getValueType(); 4449 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4450 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4451 4452 SDValue Lo0, Hi0; 4453 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4454 SDValue Lo1, Hi1; 4455 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4456 SDValue Lo2, Hi2; 4457 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4458 4459 SDLoc SL(Op); 4460 4461 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4462 Op->getFlags()); 4463 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4464 Op->getFlags()); 4465 4466 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4467 } 4468 4469 4470 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4471 switch (Op.getOpcode()) { 4472 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4473 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4474 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4475 case ISD::LOAD: { 4476 SDValue Result = LowerLOAD(Op, DAG); 4477 assert((!Result.getNode() || 4478 Result.getNode()->getNumValues() == 2) && 4479 "Load should return a value and a chain"); 4480 return Result; 4481 } 4482 4483 case ISD::FSIN: 4484 case ISD::FCOS: 4485 return LowerTrig(Op, DAG); 4486 case ISD::SELECT: return LowerSELECT(Op, DAG); 4487 case ISD::FDIV: return LowerFDIV(Op, DAG); 4488 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4489 case ISD::STORE: return LowerSTORE(Op, DAG); 4490 case ISD::GlobalAddress: { 4491 MachineFunction &MF = DAG.getMachineFunction(); 4492 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4493 return LowerGlobalAddress(MFI, Op, DAG); 4494 } 4495 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4496 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4497 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4498 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4499 case ISD::INSERT_SUBVECTOR: 4500 return lowerINSERT_SUBVECTOR(Op, DAG); 4501 case ISD::INSERT_VECTOR_ELT: 4502 return lowerINSERT_VECTOR_ELT(Op, DAG); 4503 case ISD::EXTRACT_VECTOR_ELT: 4504 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4505 case ISD::VECTOR_SHUFFLE: 4506 return lowerVECTOR_SHUFFLE(Op, DAG); 4507 case ISD::BUILD_VECTOR: 4508 return lowerBUILD_VECTOR(Op, DAG); 4509 case ISD::FP_ROUND: 4510 return lowerFP_ROUND(Op, DAG); 4511 case ISD::TRAP: 4512 return lowerTRAP(Op, DAG); 4513 case ISD::DEBUGTRAP: 4514 return lowerDEBUGTRAP(Op, DAG); 4515 case ISD::FABS: 4516 case ISD::FNEG: 4517 case ISD::FCANONICALIZE: 4518 case ISD::BSWAP: 4519 return splitUnaryVectorOp(Op, DAG); 4520 case ISD::FMINNUM: 4521 case ISD::FMAXNUM: 4522 return lowerFMINNUM_FMAXNUM(Op, DAG); 4523 case ISD::FMA: 4524 return splitTernaryVectorOp(Op, DAG); 4525 case ISD::SHL: 4526 case ISD::SRA: 4527 case ISD::SRL: 4528 case ISD::ADD: 4529 case ISD::SUB: 4530 case ISD::MUL: 4531 case ISD::SMIN: 4532 case ISD::SMAX: 4533 case ISD::UMIN: 4534 case ISD::UMAX: 4535 case ISD::FADD: 4536 case ISD::FMUL: 4537 case ISD::FMINNUM_IEEE: 4538 case ISD::FMAXNUM_IEEE: 4539 case ISD::UADDSAT: 4540 case ISD::USUBSAT: 4541 case ISD::SADDSAT: 4542 case ISD::SSUBSAT: 4543 return splitBinaryVectorOp(Op, DAG); 4544 case ISD::SMULO: 4545 case ISD::UMULO: 4546 return lowerXMULO(Op, DAG); 4547 case ISD::DYNAMIC_STACKALLOC: 4548 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4549 } 4550 return SDValue(); 4551 } 4552 4553 // Used for D16: Casts the result of an instruction into the right vector, 4554 // packs values if loads return unpacked values. 4555 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4556 const SDLoc &DL, 4557 SelectionDAG &DAG, bool Unpacked) { 4558 if (!LoadVT.isVector()) 4559 return Result; 4560 4561 // Cast back to the original packed type or to a larger type that is a 4562 // multiple of 32 bit for D16. Widening the return type is a required for 4563 // legalization. 4564 EVT FittingLoadVT = LoadVT; 4565 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4566 FittingLoadVT = 4567 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4568 LoadVT.getVectorNumElements() + 1); 4569 } 4570 4571 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4572 // Truncate to v2i16/v4i16. 4573 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4574 4575 // Workaround legalizer not scalarizing truncate after vector op 4576 // legalization but not creating intermediate vector trunc. 4577 SmallVector<SDValue, 4> Elts; 4578 DAG.ExtractVectorElements(Result, Elts); 4579 for (SDValue &Elt : Elts) 4580 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4581 4582 // Pad illegal v1i16/v3fi6 to v4i16 4583 if ((LoadVT.getVectorNumElements() % 2) == 1) 4584 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4585 4586 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4587 4588 // Bitcast to original type (v2f16/v4f16). 4589 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4590 } 4591 4592 // Cast back to the original packed type. 4593 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4594 } 4595 4596 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4597 MemSDNode *M, 4598 SelectionDAG &DAG, 4599 ArrayRef<SDValue> Ops, 4600 bool IsIntrinsic) const { 4601 SDLoc DL(M); 4602 4603 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4604 EVT LoadVT = M->getValueType(0); 4605 4606 EVT EquivLoadVT = LoadVT; 4607 if (LoadVT.isVector()) { 4608 if (Unpacked) { 4609 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4610 LoadVT.getVectorNumElements()); 4611 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4612 // Widen v3f16 to legal type 4613 EquivLoadVT = 4614 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4615 LoadVT.getVectorNumElements() + 1); 4616 } 4617 } 4618 4619 // Change from v4f16/v2f16 to EquivLoadVT. 4620 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4621 4622 SDValue Load 4623 = DAG.getMemIntrinsicNode( 4624 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4625 VTList, Ops, M->getMemoryVT(), 4626 M->getMemOperand()); 4627 4628 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4629 4630 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4631 } 4632 4633 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4634 SelectionDAG &DAG, 4635 ArrayRef<SDValue> Ops) const { 4636 SDLoc DL(M); 4637 EVT LoadVT = M->getValueType(0); 4638 EVT EltType = LoadVT.getScalarType(); 4639 EVT IntVT = LoadVT.changeTypeToInteger(); 4640 4641 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4642 4643 unsigned Opc = 4644 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4645 4646 if (IsD16) { 4647 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4648 } 4649 4650 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4651 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4652 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4653 4654 if (isTypeLegal(LoadVT)) { 4655 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4656 M->getMemOperand(), DAG); 4657 } 4658 4659 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4660 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4661 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4662 M->getMemOperand(), DAG); 4663 return DAG.getMergeValues( 4664 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4665 DL); 4666 } 4667 4668 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4669 SDNode *N, SelectionDAG &DAG) { 4670 EVT VT = N->getValueType(0); 4671 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4672 unsigned CondCode = CD->getZExtValue(); 4673 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4674 return DAG.getUNDEF(VT); 4675 4676 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4677 4678 SDValue LHS = N->getOperand(1); 4679 SDValue RHS = N->getOperand(2); 4680 4681 SDLoc DL(N); 4682 4683 EVT CmpVT = LHS.getValueType(); 4684 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4685 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4686 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4687 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4688 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4689 } 4690 4691 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4692 4693 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4694 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4695 4696 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4697 DAG.getCondCode(CCOpcode)); 4698 if (VT.bitsEq(CCVT)) 4699 return SetCC; 4700 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4701 } 4702 4703 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4704 SDNode *N, SelectionDAG &DAG) { 4705 EVT VT = N->getValueType(0); 4706 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4707 4708 unsigned CondCode = CD->getZExtValue(); 4709 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4710 return DAG.getUNDEF(VT); 4711 4712 SDValue Src0 = N->getOperand(1); 4713 SDValue Src1 = N->getOperand(2); 4714 EVT CmpVT = Src0.getValueType(); 4715 SDLoc SL(N); 4716 4717 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4718 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4719 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4720 } 4721 4722 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4723 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4724 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4725 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4726 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4727 Src1, DAG.getCondCode(CCOpcode)); 4728 if (VT.bitsEq(CCVT)) 4729 return SetCC; 4730 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4731 } 4732 4733 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4734 SelectionDAG &DAG) { 4735 EVT VT = N->getValueType(0); 4736 SDValue Src = N->getOperand(1); 4737 SDLoc SL(N); 4738 4739 if (Src.getOpcode() == ISD::SETCC) { 4740 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4741 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4742 Src.getOperand(1), Src.getOperand(2)); 4743 } 4744 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4745 // (ballot 0) -> 0 4746 if (Arg->isNullValue()) 4747 return DAG.getConstant(0, SL, VT); 4748 4749 // (ballot 1) -> EXEC/EXEC_LO 4750 if (Arg->isOne()) { 4751 Register Exec; 4752 if (VT.getScalarSizeInBits() == 32) 4753 Exec = AMDGPU::EXEC_LO; 4754 else if (VT.getScalarSizeInBits() == 64) 4755 Exec = AMDGPU::EXEC; 4756 else 4757 return SDValue(); 4758 4759 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4760 } 4761 } 4762 4763 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4764 // ISD::SETNE) 4765 return DAG.getNode( 4766 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4767 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4768 } 4769 4770 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4771 SmallVectorImpl<SDValue> &Results, 4772 SelectionDAG &DAG) const { 4773 switch (N->getOpcode()) { 4774 case ISD::INSERT_VECTOR_ELT: { 4775 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4776 Results.push_back(Res); 4777 return; 4778 } 4779 case ISD::EXTRACT_VECTOR_ELT: { 4780 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4781 Results.push_back(Res); 4782 return; 4783 } 4784 case ISD::INTRINSIC_WO_CHAIN: { 4785 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4786 switch (IID) { 4787 case Intrinsic::amdgcn_cvt_pkrtz: { 4788 SDValue Src0 = N->getOperand(1); 4789 SDValue Src1 = N->getOperand(2); 4790 SDLoc SL(N); 4791 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4792 Src0, Src1); 4793 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4794 return; 4795 } 4796 case Intrinsic::amdgcn_cvt_pknorm_i16: 4797 case Intrinsic::amdgcn_cvt_pknorm_u16: 4798 case Intrinsic::amdgcn_cvt_pk_i16: 4799 case Intrinsic::amdgcn_cvt_pk_u16: { 4800 SDValue Src0 = N->getOperand(1); 4801 SDValue Src1 = N->getOperand(2); 4802 SDLoc SL(N); 4803 unsigned Opcode; 4804 4805 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4806 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4807 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4808 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4809 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4810 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4811 else 4812 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4813 4814 EVT VT = N->getValueType(0); 4815 if (isTypeLegal(VT)) 4816 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4817 else { 4818 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4819 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4820 } 4821 return; 4822 } 4823 } 4824 break; 4825 } 4826 case ISD::INTRINSIC_W_CHAIN: { 4827 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4828 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4829 // FIXME: Hacky 4830 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4831 Results.push_back(Res.getOperand(I)); 4832 } 4833 } else { 4834 Results.push_back(Res); 4835 Results.push_back(Res.getValue(1)); 4836 } 4837 return; 4838 } 4839 4840 break; 4841 } 4842 case ISD::SELECT: { 4843 SDLoc SL(N); 4844 EVT VT = N->getValueType(0); 4845 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4846 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4847 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4848 4849 EVT SelectVT = NewVT; 4850 if (NewVT.bitsLT(MVT::i32)) { 4851 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4852 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4853 SelectVT = MVT::i32; 4854 } 4855 4856 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4857 N->getOperand(0), LHS, RHS); 4858 4859 if (NewVT != SelectVT) 4860 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4861 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4862 return; 4863 } 4864 case ISD::FNEG: { 4865 if (N->getValueType(0) != MVT::v2f16) 4866 break; 4867 4868 SDLoc SL(N); 4869 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4870 4871 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4872 BC, 4873 DAG.getConstant(0x80008000, SL, MVT::i32)); 4874 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4875 return; 4876 } 4877 case ISD::FABS: { 4878 if (N->getValueType(0) != MVT::v2f16) 4879 break; 4880 4881 SDLoc SL(N); 4882 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4883 4884 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4885 BC, 4886 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4887 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4888 return; 4889 } 4890 default: 4891 break; 4892 } 4893 } 4894 4895 /// Helper function for LowerBRCOND 4896 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4897 4898 SDNode *Parent = Value.getNode(); 4899 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4900 I != E; ++I) { 4901 4902 if (I.getUse().get() != Value) 4903 continue; 4904 4905 if (I->getOpcode() == Opcode) 4906 return *I; 4907 } 4908 return nullptr; 4909 } 4910 4911 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4912 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4913 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4914 case Intrinsic::amdgcn_if: 4915 return AMDGPUISD::IF; 4916 case Intrinsic::amdgcn_else: 4917 return AMDGPUISD::ELSE; 4918 case Intrinsic::amdgcn_loop: 4919 return AMDGPUISD::LOOP; 4920 case Intrinsic::amdgcn_end_cf: 4921 llvm_unreachable("should not occur"); 4922 default: 4923 return 0; 4924 } 4925 } 4926 4927 // break, if_break, else_break are all only used as inputs to loop, not 4928 // directly as branch conditions. 4929 return 0; 4930 } 4931 4932 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4933 const Triple &TT = getTargetMachine().getTargetTriple(); 4934 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4935 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4936 AMDGPU::shouldEmitConstantsToTextSection(TT); 4937 } 4938 4939 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4940 // FIXME: Either avoid relying on address space here or change the default 4941 // address space for functions to avoid the explicit check. 4942 return (GV->getValueType()->isFunctionTy() || 4943 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4944 !shouldEmitFixup(GV) && 4945 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4946 } 4947 4948 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4949 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4950 } 4951 4952 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4953 if (!GV->hasExternalLinkage()) 4954 return true; 4955 4956 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4957 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4958 } 4959 4960 /// This transforms the control flow intrinsics to get the branch destination as 4961 /// last parameter, also switches branch target with BR if the need arise 4962 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4963 SelectionDAG &DAG) const { 4964 SDLoc DL(BRCOND); 4965 4966 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4967 SDValue Target = BRCOND.getOperand(2); 4968 SDNode *BR = nullptr; 4969 SDNode *SetCC = nullptr; 4970 4971 if (Intr->getOpcode() == ISD::SETCC) { 4972 // As long as we negate the condition everything is fine 4973 SetCC = Intr; 4974 Intr = SetCC->getOperand(0).getNode(); 4975 4976 } else { 4977 // Get the target from BR if we don't negate the condition 4978 BR = findUser(BRCOND, ISD::BR); 4979 assert(BR && "brcond missing unconditional branch user"); 4980 Target = BR->getOperand(1); 4981 } 4982 4983 unsigned CFNode = isCFIntrinsic(Intr); 4984 if (CFNode == 0) { 4985 // This is a uniform branch so we don't need to legalize. 4986 return BRCOND; 4987 } 4988 4989 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4990 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4991 4992 assert(!SetCC || 4993 (SetCC->getConstantOperandVal(1) == 1 && 4994 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4995 ISD::SETNE)); 4996 4997 // operands of the new intrinsic call 4998 SmallVector<SDValue, 4> Ops; 4999 if (HaveChain) 5000 Ops.push_back(BRCOND.getOperand(0)); 5001 5002 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5003 Ops.push_back(Target); 5004 5005 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5006 5007 // build the new intrinsic call 5008 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5009 5010 if (!HaveChain) { 5011 SDValue Ops[] = { 5012 SDValue(Result, 0), 5013 BRCOND.getOperand(0) 5014 }; 5015 5016 Result = DAG.getMergeValues(Ops, DL).getNode(); 5017 } 5018 5019 if (BR) { 5020 // Give the branch instruction our target 5021 SDValue Ops[] = { 5022 BR->getOperand(0), 5023 BRCOND.getOperand(2) 5024 }; 5025 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5026 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5027 } 5028 5029 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5030 5031 // Copy the intrinsic results to registers 5032 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5033 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5034 if (!CopyToReg) 5035 continue; 5036 5037 Chain = DAG.getCopyToReg( 5038 Chain, DL, 5039 CopyToReg->getOperand(1), 5040 SDValue(Result, i - 1), 5041 SDValue()); 5042 5043 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5044 } 5045 5046 // Remove the old intrinsic from the chain 5047 DAG.ReplaceAllUsesOfValueWith( 5048 SDValue(Intr, Intr->getNumValues() - 1), 5049 Intr->getOperand(0)); 5050 5051 return Chain; 5052 } 5053 5054 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5055 SelectionDAG &DAG) const { 5056 MVT VT = Op.getSimpleValueType(); 5057 SDLoc DL(Op); 5058 // Checking the depth 5059 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5060 return DAG.getConstant(0, DL, VT); 5061 5062 MachineFunction &MF = DAG.getMachineFunction(); 5063 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5064 // Check for kernel and shader functions 5065 if (Info->isEntryFunction()) 5066 return DAG.getConstant(0, DL, VT); 5067 5068 MachineFrameInfo &MFI = MF.getFrameInfo(); 5069 // There is a call to @llvm.returnaddress in this function 5070 MFI.setReturnAddressIsTaken(true); 5071 5072 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5073 // Get the return address reg and mark it as an implicit live-in 5074 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5075 5076 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5077 } 5078 5079 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5080 SDValue Op, 5081 const SDLoc &DL, 5082 EVT VT) const { 5083 return Op.getValueType().bitsLE(VT) ? 5084 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5085 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5086 DAG.getTargetConstant(0, DL, MVT::i32)); 5087 } 5088 5089 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5090 assert(Op.getValueType() == MVT::f16 && 5091 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5092 5093 SDValue Src = Op.getOperand(0); 5094 EVT SrcVT = Src.getValueType(); 5095 if (SrcVT != MVT::f64) 5096 return Op; 5097 5098 SDLoc DL(Op); 5099 5100 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5101 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5102 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5103 } 5104 5105 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5106 SelectionDAG &DAG) const { 5107 EVT VT = Op.getValueType(); 5108 const MachineFunction &MF = DAG.getMachineFunction(); 5109 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5110 bool IsIEEEMode = Info->getMode().IEEE; 5111 5112 // FIXME: Assert during selection that this is only selected for 5113 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5114 // mode functions, but this happens to be OK since it's only done in cases 5115 // where there is known no sNaN. 5116 if (IsIEEEMode) 5117 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5118 5119 if (VT == MVT::v4f16) 5120 return splitBinaryVectorOp(Op, DAG); 5121 return Op; 5122 } 5123 5124 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5125 EVT VT = Op.getValueType(); 5126 SDLoc SL(Op); 5127 SDValue LHS = Op.getOperand(0); 5128 SDValue RHS = Op.getOperand(1); 5129 bool isSigned = Op.getOpcode() == ISD::SMULO; 5130 5131 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5132 const APInt &C = RHSC->getAPIntValue(); 5133 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5134 if (C.isPowerOf2()) { 5135 // smulo(x, signed_min) is same as umulo(x, signed_min). 5136 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5137 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5138 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5139 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5140 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5141 SL, VT, Result, ShiftAmt), 5142 LHS, ISD::SETNE); 5143 return DAG.getMergeValues({ Result, Overflow }, SL); 5144 } 5145 } 5146 5147 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5148 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5149 SL, VT, LHS, RHS); 5150 5151 SDValue Sign = isSigned 5152 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5153 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5154 : DAG.getConstant(0, SL, VT); 5155 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5156 5157 return DAG.getMergeValues({ Result, Overflow }, SL); 5158 } 5159 5160 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5161 if (!Subtarget->isTrapHandlerEnabled() || 5162 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5163 return lowerTrapEndpgm(Op, DAG); 5164 5165 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5166 switch (*HsaAbiVer) { 5167 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5168 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5169 return lowerTrapHsaQueuePtr(Op, DAG); 5170 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5171 return Subtarget->supportsGetDoorbellID() ? 5172 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5173 } 5174 } 5175 5176 llvm_unreachable("Unknown trap handler"); 5177 } 5178 5179 SDValue SITargetLowering::lowerTrapEndpgm( 5180 SDValue Op, SelectionDAG &DAG) const { 5181 SDLoc SL(Op); 5182 SDValue Chain = Op.getOperand(0); 5183 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5184 } 5185 5186 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5187 SDValue Op, SelectionDAG &DAG) const { 5188 SDLoc SL(Op); 5189 SDValue Chain = Op.getOperand(0); 5190 5191 MachineFunction &MF = DAG.getMachineFunction(); 5192 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5193 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5194 assert(UserSGPR != AMDGPU::NoRegister); 5195 SDValue QueuePtr = CreateLiveInRegister( 5196 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5197 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5198 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5199 QueuePtr, SDValue()); 5200 5201 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5202 SDValue Ops[] = { 5203 ToReg, 5204 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5205 SGPR01, 5206 ToReg.getValue(1) 5207 }; 5208 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5209 } 5210 5211 SDValue SITargetLowering::lowerTrapHsa( 5212 SDValue Op, SelectionDAG &DAG) const { 5213 SDLoc SL(Op); 5214 SDValue Chain = Op.getOperand(0); 5215 5216 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5217 SDValue Ops[] = { 5218 Chain, 5219 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5220 }; 5221 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5222 } 5223 5224 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5225 SDLoc SL(Op); 5226 SDValue Chain = Op.getOperand(0); 5227 MachineFunction &MF = DAG.getMachineFunction(); 5228 5229 if (!Subtarget->isTrapHandlerEnabled() || 5230 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5231 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5232 "debugtrap handler not supported", 5233 Op.getDebugLoc(), 5234 DS_Warning); 5235 LLVMContext &Ctx = MF.getFunction().getContext(); 5236 Ctx.diagnose(NoTrap); 5237 return Chain; 5238 } 5239 5240 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5241 SDValue Ops[] = { 5242 Chain, 5243 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5244 }; 5245 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5246 } 5247 5248 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5249 SelectionDAG &DAG) const { 5250 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5251 if (Subtarget->hasApertureRegs()) { 5252 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5253 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5254 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5255 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5256 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5257 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5258 unsigned Encoding = 5259 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5260 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5261 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5262 5263 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5264 SDValue ApertureReg = SDValue( 5265 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5266 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5267 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5268 } 5269 5270 MachineFunction &MF = DAG.getMachineFunction(); 5271 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5272 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5273 assert(UserSGPR != AMDGPU::NoRegister); 5274 5275 SDValue QueuePtr = CreateLiveInRegister( 5276 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5277 5278 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5279 // private_segment_aperture_base_hi. 5280 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5281 5282 SDValue Ptr = 5283 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5284 5285 // TODO: Use custom target PseudoSourceValue. 5286 // TODO: We should use the value from the IR intrinsic call, but it might not 5287 // be available and how do we get it? 5288 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5289 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5290 commonAlignment(Align(64), StructOffset), 5291 MachineMemOperand::MODereferenceable | 5292 MachineMemOperand::MOInvariant); 5293 } 5294 5295 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5296 SelectionDAG &DAG) const { 5297 SDLoc SL(Op); 5298 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5299 5300 SDValue Src = ASC->getOperand(0); 5301 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5302 5303 const AMDGPUTargetMachine &TM = 5304 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5305 5306 // flat -> local/private 5307 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5308 unsigned DestAS = ASC->getDestAddressSpace(); 5309 5310 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5311 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5312 unsigned NullVal = TM.getNullPointerValue(DestAS); 5313 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5314 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5315 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5316 5317 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5318 NonNull, Ptr, SegmentNullPtr); 5319 } 5320 } 5321 5322 // local/private -> flat 5323 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5324 unsigned SrcAS = ASC->getSrcAddressSpace(); 5325 5326 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5327 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5328 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5329 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5330 5331 SDValue NonNull 5332 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5333 5334 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5335 SDValue CvtPtr 5336 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5337 5338 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5339 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5340 FlatNullPtr); 5341 } 5342 } 5343 5344 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5345 Src.getValueType() == MVT::i64) 5346 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5347 5348 // global <-> flat are no-ops and never emitted. 5349 5350 const MachineFunction &MF = DAG.getMachineFunction(); 5351 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5352 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5353 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5354 5355 return DAG.getUNDEF(ASC->getValueType(0)); 5356 } 5357 5358 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5359 // the small vector and inserting them into the big vector. That is better than 5360 // the default expansion of doing it via a stack slot. Even though the use of 5361 // the stack slot would be optimized away afterwards, the stack slot itself 5362 // remains. 5363 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5364 SelectionDAG &DAG) const { 5365 SDValue Vec = Op.getOperand(0); 5366 SDValue Ins = Op.getOperand(1); 5367 SDValue Idx = Op.getOperand(2); 5368 EVT VecVT = Vec.getValueType(); 5369 EVT InsVT = Ins.getValueType(); 5370 EVT EltVT = VecVT.getVectorElementType(); 5371 unsigned InsNumElts = InsVT.getVectorNumElements(); 5372 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5373 SDLoc SL(Op); 5374 5375 for (unsigned I = 0; I != InsNumElts; ++I) { 5376 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5377 DAG.getConstant(I, SL, MVT::i32)); 5378 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5379 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5380 } 5381 return Vec; 5382 } 5383 5384 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5385 SelectionDAG &DAG) const { 5386 SDValue Vec = Op.getOperand(0); 5387 SDValue InsVal = Op.getOperand(1); 5388 SDValue Idx = Op.getOperand(2); 5389 EVT VecVT = Vec.getValueType(); 5390 EVT EltVT = VecVT.getVectorElementType(); 5391 unsigned VecSize = VecVT.getSizeInBits(); 5392 unsigned EltSize = EltVT.getSizeInBits(); 5393 5394 5395 assert(VecSize <= 64); 5396 5397 unsigned NumElts = VecVT.getVectorNumElements(); 5398 SDLoc SL(Op); 5399 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5400 5401 if (NumElts == 4 && EltSize == 16 && KIdx) { 5402 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5403 5404 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5405 DAG.getConstant(0, SL, MVT::i32)); 5406 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5407 DAG.getConstant(1, SL, MVT::i32)); 5408 5409 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5410 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5411 5412 unsigned Idx = KIdx->getZExtValue(); 5413 bool InsertLo = Idx < 2; 5414 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5415 InsertLo ? LoVec : HiVec, 5416 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5417 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5418 5419 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5420 5421 SDValue Concat = InsertLo ? 5422 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5423 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5424 5425 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5426 } 5427 5428 if (isa<ConstantSDNode>(Idx)) 5429 return SDValue(); 5430 5431 MVT IntVT = MVT::getIntegerVT(VecSize); 5432 5433 // Avoid stack access for dynamic indexing. 5434 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5435 5436 // Create a congruent vector with the target value in each element so that 5437 // the required element can be masked and ORed into the target vector. 5438 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5439 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5440 5441 assert(isPowerOf2_32(EltSize)); 5442 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5443 5444 // Convert vector index to bit-index. 5445 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5446 5447 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5448 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5449 DAG.getConstant(0xffff, SL, IntVT), 5450 ScaledIdx); 5451 5452 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5453 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5454 DAG.getNOT(SL, BFM, IntVT), BCVec); 5455 5456 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5457 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5458 } 5459 5460 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5461 SelectionDAG &DAG) const { 5462 SDLoc SL(Op); 5463 5464 EVT ResultVT = Op.getValueType(); 5465 SDValue Vec = Op.getOperand(0); 5466 SDValue Idx = Op.getOperand(1); 5467 EVT VecVT = Vec.getValueType(); 5468 unsigned VecSize = VecVT.getSizeInBits(); 5469 EVT EltVT = VecVT.getVectorElementType(); 5470 assert(VecSize <= 64); 5471 5472 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5473 5474 // Make sure we do any optimizations that will make it easier to fold 5475 // source modifiers before obscuring it with bit operations. 5476 5477 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5478 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5479 return Combined; 5480 5481 unsigned EltSize = EltVT.getSizeInBits(); 5482 assert(isPowerOf2_32(EltSize)); 5483 5484 MVT IntVT = MVT::getIntegerVT(VecSize); 5485 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5486 5487 // Convert vector index to bit-index (* EltSize) 5488 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5489 5490 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5491 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5492 5493 if (ResultVT == MVT::f16) { 5494 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5495 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5496 } 5497 5498 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5499 } 5500 5501 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5502 assert(Elt % 2 == 0); 5503 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5504 } 5505 5506 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5507 SelectionDAG &DAG) const { 5508 SDLoc SL(Op); 5509 EVT ResultVT = Op.getValueType(); 5510 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5511 5512 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5513 EVT EltVT = PackVT.getVectorElementType(); 5514 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5515 5516 // vector_shuffle <0,1,6,7> lhs, rhs 5517 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5518 // 5519 // vector_shuffle <6,7,2,3> lhs, rhs 5520 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5521 // 5522 // vector_shuffle <6,7,0,1> lhs, rhs 5523 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5524 5525 // Avoid scalarizing when both halves are reading from consecutive elements. 5526 SmallVector<SDValue, 4> Pieces; 5527 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5528 if (elementPairIsContiguous(SVN->getMask(), I)) { 5529 const int Idx = SVN->getMaskElt(I); 5530 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5531 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5532 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5533 PackVT, SVN->getOperand(VecIdx), 5534 DAG.getConstant(EltIdx, SL, MVT::i32)); 5535 Pieces.push_back(SubVec); 5536 } else { 5537 const int Idx0 = SVN->getMaskElt(I); 5538 const int Idx1 = SVN->getMaskElt(I + 1); 5539 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5540 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5541 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5542 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5543 5544 SDValue Vec0 = SVN->getOperand(VecIdx0); 5545 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5546 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5547 5548 SDValue Vec1 = SVN->getOperand(VecIdx1); 5549 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5550 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5551 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5552 } 5553 } 5554 5555 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5556 } 5557 5558 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5559 SelectionDAG &DAG) const { 5560 SDLoc SL(Op); 5561 EVT VT = Op.getValueType(); 5562 5563 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5564 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5565 5566 // Turn into pair of packed build_vectors. 5567 // TODO: Special case for constants that can be materialized with s_mov_b64. 5568 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5569 { Op.getOperand(0), Op.getOperand(1) }); 5570 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5571 { Op.getOperand(2), Op.getOperand(3) }); 5572 5573 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5574 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5575 5576 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5577 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5578 } 5579 5580 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5581 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5582 5583 SDValue Lo = Op.getOperand(0); 5584 SDValue Hi = Op.getOperand(1); 5585 5586 // Avoid adding defined bits with the zero_extend. 5587 if (Hi.isUndef()) { 5588 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5589 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5590 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5591 } 5592 5593 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5594 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5595 5596 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5597 DAG.getConstant(16, SL, MVT::i32)); 5598 if (Lo.isUndef()) 5599 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5600 5601 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5602 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5603 5604 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5605 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5606 } 5607 5608 bool 5609 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5610 // We can fold offsets for anything that doesn't require a GOT relocation. 5611 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5612 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5613 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5614 !shouldEmitGOTReloc(GA->getGlobal()); 5615 } 5616 5617 static SDValue 5618 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5619 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5620 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5621 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5622 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5623 // lowered to the following code sequence: 5624 // 5625 // For constant address space: 5626 // s_getpc_b64 s[0:1] 5627 // s_add_u32 s0, s0, $symbol 5628 // s_addc_u32 s1, s1, 0 5629 // 5630 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5631 // a fixup or relocation is emitted to replace $symbol with a literal 5632 // constant, which is a pc-relative offset from the encoding of the $symbol 5633 // operand to the global variable. 5634 // 5635 // For global address space: 5636 // s_getpc_b64 s[0:1] 5637 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5638 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5639 // 5640 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5641 // fixups or relocations are emitted to replace $symbol@*@lo and 5642 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5643 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5644 // operand to the global variable. 5645 // 5646 // What we want here is an offset from the value returned by s_getpc 5647 // (which is the address of the s_add_u32 instruction) to the global 5648 // variable, but since the encoding of $symbol starts 4 bytes after the start 5649 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5650 // small. This requires us to add 4 to the global variable offset in order to 5651 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5652 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5653 // instruction. 5654 SDValue PtrLo = 5655 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5656 SDValue PtrHi; 5657 if (GAFlags == SIInstrInfo::MO_NONE) { 5658 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5659 } else { 5660 PtrHi = 5661 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5662 } 5663 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5664 } 5665 5666 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5667 SDValue Op, 5668 SelectionDAG &DAG) const { 5669 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5670 SDLoc DL(GSD); 5671 EVT PtrVT = Op.getValueType(); 5672 5673 const GlobalValue *GV = GSD->getGlobal(); 5674 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5675 shouldUseLDSConstAddress(GV)) || 5676 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5677 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5678 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5679 GV->hasExternalLinkage()) { 5680 Type *Ty = GV->getValueType(); 5681 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5682 // zero-sized type in other languages to declare the dynamic shared 5683 // memory which size is not known at the compile time. They will be 5684 // allocated by the runtime and placed directly after the static 5685 // allocated ones. They all share the same offset. 5686 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5687 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5688 // Adjust alignment for that dynamic shared memory array. 5689 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5690 return SDValue( 5691 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5692 } 5693 } 5694 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5695 } 5696 5697 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5698 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5699 SIInstrInfo::MO_ABS32_LO); 5700 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5701 } 5702 5703 if (shouldEmitFixup(GV)) 5704 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5705 else if (shouldEmitPCReloc(GV)) 5706 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5707 SIInstrInfo::MO_REL32); 5708 5709 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5710 SIInstrInfo::MO_GOTPCREL32); 5711 5712 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5713 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5714 const DataLayout &DataLayout = DAG.getDataLayout(); 5715 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5716 MachinePointerInfo PtrInfo 5717 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5718 5719 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5720 MachineMemOperand::MODereferenceable | 5721 MachineMemOperand::MOInvariant); 5722 } 5723 5724 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5725 const SDLoc &DL, SDValue V) const { 5726 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5727 // the destination register. 5728 // 5729 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5730 // so we will end up with redundant moves to m0. 5731 // 5732 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5733 5734 // A Null SDValue creates a glue result. 5735 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5736 V, Chain); 5737 return SDValue(M0, 0); 5738 } 5739 5740 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5741 SDValue Op, 5742 MVT VT, 5743 unsigned Offset) const { 5744 SDLoc SL(Op); 5745 SDValue Param = lowerKernargMemParameter( 5746 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5747 // The local size values will have the hi 16-bits as zero. 5748 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5749 DAG.getValueType(VT)); 5750 } 5751 5752 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5753 EVT VT) { 5754 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5755 "non-hsa intrinsic with hsa target", 5756 DL.getDebugLoc()); 5757 DAG.getContext()->diagnose(BadIntrin); 5758 return DAG.getUNDEF(VT); 5759 } 5760 5761 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5762 EVT VT) { 5763 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5764 "intrinsic not supported on subtarget", 5765 DL.getDebugLoc()); 5766 DAG.getContext()->diagnose(BadIntrin); 5767 return DAG.getUNDEF(VT); 5768 } 5769 5770 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5771 ArrayRef<SDValue> Elts) { 5772 assert(!Elts.empty()); 5773 MVT Type; 5774 unsigned NumElts; 5775 5776 if (Elts.size() == 1) { 5777 Type = MVT::f32; 5778 NumElts = 1; 5779 } else if (Elts.size() == 2) { 5780 Type = MVT::v2f32; 5781 NumElts = 2; 5782 } else if (Elts.size() == 3) { 5783 Type = MVT::v3f32; 5784 NumElts = 3; 5785 } else if (Elts.size() <= 4) { 5786 Type = MVT::v4f32; 5787 NumElts = 4; 5788 } else if (Elts.size() <= 8) { 5789 Type = MVT::v8f32; 5790 NumElts = 8; 5791 } else { 5792 assert(Elts.size() <= 16); 5793 Type = MVT::v16f32; 5794 NumElts = 16; 5795 } 5796 5797 SmallVector<SDValue, 16> VecElts(NumElts); 5798 for (unsigned i = 0; i < Elts.size(); ++i) { 5799 SDValue Elt = Elts[i]; 5800 if (Elt.getValueType() != MVT::f32) 5801 Elt = DAG.getBitcast(MVT::f32, Elt); 5802 VecElts[i] = Elt; 5803 } 5804 for (unsigned i = Elts.size(); i < NumElts; ++i) 5805 VecElts[i] = DAG.getUNDEF(MVT::f32); 5806 5807 if (NumElts == 1) 5808 return VecElts[0]; 5809 return DAG.getBuildVector(Type, DL, VecElts); 5810 } 5811 5812 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5813 SDValue Src, int ExtraElts) { 5814 EVT SrcVT = Src.getValueType(); 5815 5816 SmallVector<SDValue, 8> Elts; 5817 5818 if (SrcVT.isVector()) 5819 DAG.ExtractVectorElements(Src, Elts); 5820 else 5821 Elts.push_back(Src); 5822 5823 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5824 while (ExtraElts--) 5825 Elts.push_back(Undef); 5826 5827 return DAG.getBuildVector(CastVT, DL, Elts); 5828 } 5829 5830 // Re-construct the required return value for a image load intrinsic. 5831 // This is more complicated due to the optional use TexFailCtrl which means the required 5832 // return type is an aggregate 5833 static SDValue constructRetValue(SelectionDAG &DAG, 5834 MachineSDNode *Result, 5835 ArrayRef<EVT> ResultTypes, 5836 bool IsTexFail, bool Unpacked, bool IsD16, 5837 int DMaskPop, int NumVDataDwords, 5838 const SDLoc &DL, LLVMContext &Context) { 5839 // Determine the required return type. This is the same regardless of IsTexFail flag 5840 EVT ReqRetVT = ResultTypes[0]; 5841 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5842 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5843 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5844 5845 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5846 DMaskPop : (DMaskPop + 1) / 2; 5847 5848 MVT DataDwordVT = NumDataDwords == 1 ? 5849 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5850 5851 MVT MaskPopVT = MaskPopDwords == 1 ? 5852 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5853 5854 SDValue Data(Result, 0); 5855 SDValue TexFail; 5856 5857 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 5858 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5859 if (MaskPopVT.isVector()) { 5860 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5861 SDValue(Result, 0), ZeroIdx); 5862 } else { 5863 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5864 SDValue(Result, 0), ZeroIdx); 5865 } 5866 } 5867 5868 if (DataDwordVT.isVector()) 5869 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5870 NumDataDwords - MaskPopDwords); 5871 5872 if (IsD16) 5873 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5874 5875 EVT LegalReqRetVT = ReqRetVT; 5876 if (!ReqRetVT.isVector()) { 5877 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5878 } else { 5879 // We need to widen the return vector to a legal type 5880 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 5881 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 5882 LegalReqRetVT = 5883 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 5884 ReqRetVT.getVectorNumElements() + 1); 5885 } 5886 } 5887 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 5888 5889 if (IsTexFail) { 5890 TexFail = 5891 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 5892 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5893 5894 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5895 } 5896 5897 if (Result->getNumValues() == 1) 5898 return Data; 5899 5900 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5901 } 5902 5903 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5904 SDValue *LWE, bool &IsTexFail) { 5905 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5906 5907 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5908 if (Value) { 5909 IsTexFail = true; 5910 } 5911 5912 SDLoc DL(TexFailCtrlConst); 5913 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5914 Value &= ~(uint64_t)0x1; 5915 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5916 Value &= ~(uint64_t)0x2; 5917 5918 return Value == 0; 5919 } 5920 5921 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5922 MVT PackVectorVT, 5923 SmallVectorImpl<SDValue> &PackedAddrs, 5924 unsigned DimIdx, unsigned EndIdx, 5925 unsigned NumGradients) { 5926 SDLoc DL(Op); 5927 for (unsigned I = DimIdx; I < EndIdx; I++) { 5928 SDValue Addr = Op.getOperand(I); 5929 5930 // Gradients are packed with undef for each coordinate. 5931 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5932 // 1D: undef,dx/dh; undef,dx/dv 5933 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5934 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5935 if (((I + 1) >= EndIdx) || 5936 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5937 I == DimIdx + NumGradients - 1))) { 5938 if (Addr.getValueType() != MVT::i16) 5939 Addr = DAG.getBitcast(MVT::i16, Addr); 5940 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5941 } else { 5942 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5943 I++; 5944 } 5945 Addr = DAG.getBitcast(MVT::f32, Addr); 5946 PackedAddrs.push_back(Addr); 5947 } 5948 } 5949 5950 SDValue SITargetLowering::lowerImage(SDValue Op, 5951 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5952 SelectionDAG &DAG, bool WithChain) const { 5953 SDLoc DL(Op); 5954 MachineFunction &MF = DAG.getMachineFunction(); 5955 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5956 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5957 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5958 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5959 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5960 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5961 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5962 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5963 unsigned IntrOpcode = Intr->BaseOpcode; 5964 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 5965 5966 SmallVector<EVT, 3> ResultTypes(Op->values()); 5967 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 5968 bool IsD16 = false; 5969 bool IsG16 = false; 5970 bool IsA16 = false; 5971 SDValue VData; 5972 int NumVDataDwords; 5973 bool AdjustRetType = false; 5974 5975 // Offset of intrinsic arguments 5976 const unsigned ArgOffset = WithChain ? 2 : 1; 5977 5978 unsigned DMask; 5979 unsigned DMaskLanes = 0; 5980 5981 if (BaseOpcode->Atomic) { 5982 VData = Op.getOperand(2); 5983 5984 bool Is64Bit = VData.getValueType() == MVT::i64; 5985 if (BaseOpcode->AtomicX2) { 5986 SDValue VData2 = Op.getOperand(3); 5987 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5988 {VData, VData2}); 5989 if (Is64Bit) 5990 VData = DAG.getBitcast(MVT::v4i32, VData); 5991 5992 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5993 DMask = Is64Bit ? 0xf : 0x3; 5994 NumVDataDwords = Is64Bit ? 4 : 2; 5995 } else { 5996 DMask = Is64Bit ? 0x3 : 0x1; 5997 NumVDataDwords = Is64Bit ? 2 : 1; 5998 } 5999 } else { 6000 auto *DMaskConst = 6001 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6002 DMask = DMaskConst->getZExtValue(); 6003 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6004 6005 if (BaseOpcode->Store) { 6006 VData = Op.getOperand(2); 6007 6008 MVT StoreVT = VData.getSimpleValueType(); 6009 if (StoreVT.getScalarType() == MVT::f16) { 6010 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6011 return Op; // D16 is unsupported for this instruction 6012 6013 IsD16 = true; 6014 VData = handleD16VData(VData, DAG, true); 6015 } 6016 6017 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6018 } else { 6019 // Work out the num dwords based on the dmask popcount and underlying type 6020 // and whether packing is supported. 6021 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6022 if (LoadVT.getScalarType() == MVT::f16) { 6023 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6024 return Op; // D16 is unsupported for this instruction 6025 6026 IsD16 = true; 6027 } 6028 6029 // Confirm that the return type is large enough for the dmask specified 6030 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6031 (!LoadVT.isVector() && DMaskLanes > 1)) 6032 return Op; 6033 6034 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6035 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6036 // instructions. 6037 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6038 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6039 NumVDataDwords = (DMaskLanes + 1) / 2; 6040 else 6041 NumVDataDwords = DMaskLanes; 6042 6043 AdjustRetType = true; 6044 } 6045 } 6046 6047 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6048 SmallVector<SDValue, 4> VAddrs; 6049 6050 // Optimize _L to _LZ when _L is zero 6051 if (LZMappingInfo) { 6052 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6053 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6054 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6055 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6056 VAddrEnd--; // remove 'lod' 6057 } 6058 } 6059 } 6060 6061 // Optimize _mip away, when 'lod' is zero 6062 if (MIPMappingInfo) { 6063 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6064 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6065 if (ConstantLod->isNullValue()) { 6066 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6067 VAddrEnd--; // remove 'mip' 6068 } 6069 } 6070 } 6071 6072 // Push back extra arguments. 6073 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) 6074 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6075 6076 // Check for 16 bit addresses or derivatives and pack if true. 6077 MVT VAddrVT = 6078 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6079 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6080 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6081 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6082 6083 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6084 VAddrScalarVT = VAddrVT.getScalarType(); 6085 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6086 if (IsA16 || IsG16) { 6087 if (IsA16) { 6088 if (!ST->hasA16()) { 6089 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6090 "support 16 bit addresses\n"); 6091 return Op; 6092 } 6093 if (!IsG16) { 6094 LLVM_DEBUG( 6095 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6096 "need 16 bit derivatives but got 32 bit derivatives\n"); 6097 return Op; 6098 } 6099 } else if (!ST->hasG16()) { 6100 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6101 "support 16 bit derivatives\n"); 6102 return Op; 6103 } 6104 6105 if (BaseOpcode->Gradients && !IsA16) { 6106 if (!ST->hasG16()) { 6107 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6108 "support 16 bit derivatives\n"); 6109 return Op; 6110 } 6111 // Activate g16 6112 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6113 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6114 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6115 } 6116 6117 // Don't compress addresses for G16 6118 const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6119 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, 6120 ArgOffset + Intr->GradientStart, PackEndIdx, 6121 Intr->NumGradients); 6122 6123 if (!IsA16) { 6124 // Add uncompressed address 6125 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6126 VAddrs.push_back(Op.getOperand(I)); 6127 } 6128 } else { 6129 for (unsigned I = ArgOffset + Intr->GradientStart; I < VAddrEnd; I++) 6130 VAddrs.push_back(Op.getOperand(I)); 6131 } 6132 6133 // If the register allocator cannot place the address registers contiguously 6134 // without introducing moves, then using the non-sequential address encoding 6135 // is always preferable, since it saves VALU instructions and is usually a 6136 // wash in terms of code size or even better. 6137 // 6138 // However, we currently have no way of hinting to the register allocator that 6139 // MIMG addresses should be placed contiguously when it is possible to do so, 6140 // so force non-NSA for the common 2-address case as a heuristic. 6141 // 6142 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6143 // allocation when possible. 6144 bool UseNSA = 6145 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 6146 SDValue VAddr; 6147 if (!UseNSA) 6148 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6149 6150 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6151 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6152 SDValue Unorm; 6153 if (!BaseOpcode->Sampler) { 6154 Unorm = True; 6155 } else { 6156 auto UnormConst = 6157 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6158 6159 Unorm = UnormConst->getZExtValue() ? True : False; 6160 } 6161 6162 SDValue TFE; 6163 SDValue LWE; 6164 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6165 bool IsTexFail = false; 6166 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6167 return Op; 6168 6169 if (IsTexFail) { 6170 if (!DMaskLanes) { 6171 // Expecting to get an error flag since TFC is on - and dmask is 0 6172 // Force dmask to be at least 1 otherwise the instruction will fail 6173 DMask = 0x1; 6174 DMaskLanes = 1; 6175 NumVDataDwords = 1; 6176 } 6177 NumVDataDwords += 1; 6178 AdjustRetType = true; 6179 } 6180 6181 // Has something earlier tagged that the return type needs adjusting 6182 // This happens if the instruction is a load or has set TexFailCtrl flags 6183 if (AdjustRetType) { 6184 // NumVDataDwords reflects the true number of dwords required in the return type 6185 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6186 // This is a no-op load. This can be eliminated 6187 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6188 if (isa<MemSDNode>(Op)) 6189 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6190 return Undef; 6191 } 6192 6193 EVT NewVT = NumVDataDwords > 1 ? 6194 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6195 : MVT::i32; 6196 6197 ResultTypes[0] = NewVT; 6198 if (ResultTypes.size() == 3) { 6199 // Original result was aggregate type used for TexFailCtrl results 6200 // The actual instruction returns as a vector type which has now been 6201 // created. Remove the aggregate result. 6202 ResultTypes.erase(&ResultTypes[1]); 6203 } 6204 } 6205 6206 unsigned CPol = cast<ConstantSDNode>( 6207 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6208 if (BaseOpcode->Atomic) 6209 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6210 if (CPol & ~AMDGPU::CPol::ALL) 6211 return Op; 6212 6213 SmallVector<SDValue, 26> Ops; 6214 if (BaseOpcode->Store || BaseOpcode->Atomic) 6215 Ops.push_back(VData); // vdata 6216 if (UseNSA) 6217 append_range(Ops, VAddrs); 6218 else 6219 Ops.push_back(VAddr); 6220 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6221 if (BaseOpcode->Sampler) 6222 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6223 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6224 if (IsGFX10Plus) 6225 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6226 Ops.push_back(Unorm); 6227 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6228 Ops.push_back(IsA16 && // r128, a16 for gfx9 6229 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6230 if (IsGFX10Plus) 6231 Ops.push_back(IsA16 ? True : False); 6232 if (!Subtarget->hasGFX90AInsts()) { 6233 Ops.push_back(TFE); //tfe 6234 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6235 report_fatal_error("TFE is not supported on this GPU"); 6236 } 6237 Ops.push_back(LWE); // lwe 6238 if (!IsGFX10Plus) 6239 Ops.push_back(DimInfo->DA ? True : False); 6240 if (BaseOpcode->HasD16) 6241 Ops.push_back(IsD16 ? True : False); 6242 if (isa<MemSDNode>(Op)) 6243 Ops.push_back(Op.getOperand(0)); // chain 6244 6245 int NumVAddrDwords = 6246 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6247 int Opcode = -1; 6248 6249 if (IsGFX10Plus) { 6250 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6251 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6252 : AMDGPU::MIMGEncGfx10Default, 6253 NumVDataDwords, NumVAddrDwords); 6254 } else { 6255 if (Subtarget->hasGFX90AInsts()) { 6256 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6257 NumVDataDwords, NumVAddrDwords); 6258 if (Opcode == -1) 6259 report_fatal_error( 6260 "requested image instruction is not supported on this GPU"); 6261 } 6262 if (Opcode == -1 && 6263 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6264 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6265 NumVDataDwords, NumVAddrDwords); 6266 if (Opcode == -1) 6267 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6268 NumVDataDwords, NumVAddrDwords); 6269 } 6270 assert(Opcode != -1); 6271 6272 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6273 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6274 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6275 DAG.setNodeMemRefs(NewNode, {MemRef}); 6276 } 6277 6278 if (BaseOpcode->AtomicX2) { 6279 SmallVector<SDValue, 1> Elt; 6280 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6281 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6282 } else if (!BaseOpcode->Store) { 6283 return constructRetValue(DAG, NewNode, 6284 OrigResultTypes, IsTexFail, 6285 Subtarget->hasUnpackedD16VMem(), IsD16, 6286 DMaskLanes, NumVDataDwords, DL, 6287 *DAG.getContext()); 6288 } 6289 6290 return SDValue(NewNode, 0); 6291 } 6292 6293 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6294 SDValue Offset, SDValue CachePolicy, 6295 SelectionDAG &DAG) const { 6296 MachineFunction &MF = DAG.getMachineFunction(); 6297 6298 const DataLayout &DataLayout = DAG.getDataLayout(); 6299 Align Alignment = 6300 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6301 6302 MachineMemOperand *MMO = MF.getMachineMemOperand( 6303 MachinePointerInfo(), 6304 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6305 MachineMemOperand::MOInvariant, 6306 VT.getStoreSize(), Alignment); 6307 6308 if (!Offset->isDivergent()) { 6309 SDValue Ops[] = { 6310 Rsrc, 6311 Offset, // Offset 6312 CachePolicy 6313 }; 6314 6315 // Widen vec3 load to vec4. 6316 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6317 EVT WidenedVT = 6318 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6319 auto WidenedOp = DAG.getMemIntrinsicNode( 6320 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6321 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6322 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6323 DAG.getVectorIdxConstant(0, DL)); 6324 return Subvector; 6325 } 6326 6327 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6328 DAG.getVTList(VT), Ops, VT, MMO); 6329 } 6330 6331 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6332 // assume that the buffer is unswizzled. 6333 SmallVector<SDValue, 4> Loads; 6334 unsigned NumLoads = 1; 6335 MVT LoadVT = VT.getSimpleVT(); 6336 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6337 assert((LoadVT.getScalarType() == MVT::i32 || 6338 LoadVT.getScalarType() == MVT::f32)); 6339 6340 if (NumElts == 8 || NumElts == 16) { 6341 NumLoads = NumElts / 4; 6342 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6343 } 6344 6345 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6346 SDValue Ops[] = { 6347 DAG.getEntryNode(), // Chain 6348 Rsrc, // rsrc 6349 DAG.getConstant(0, DL, MVT::i32), // vindex 6350 {}, // voffset 6351 {}, // soffset 6352 {}, // offset 6353 CachePolicy, // cachepolicy 6354 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6355 }; 6356 6357 // Use the alignment to ensure that the required offsets will fit into the 6358 // immediate offsets. 6359 setBufferOffsets(Offset, DAG, &Ops[3], 6360 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6361 6362 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6363 for (unsigned i = 0; i < NumLoads; ++i) { 6364 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6365 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6366 LoadVT, MMO, DAG)); 6367 } 6368 6369 if (NumElts == 8 || NumElts == 16) 6370 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6371 6372 return Loads[0]; 6373 } 6374 6375 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6376 SelectionDAG &DAG) const { 6377 MachineFunction &MF = DAG.getMachineFunction(); 6378 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6379 6380 EVT VT = Op.getValueType(); 6381 SDLoc DL(Op); 6382 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6383 6384 // TODO: Should this propagate fast-math-flags? 6385 6386 switch (IntrinsicID) { 6387 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6388 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6389 return emitNonHSAIntrinsicError(DAG, DL, VT); 6390 return getPreloadedValue(DAG, *MFI, VT, 6391 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6392 } 6393 case Intrinsic::amdgcn_dispatch_ptr: 6394 case Intrinsic::amdgcn_queue_ptr: { 6395 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6396 DiagnosticInfoUnsupported BadIntrin( 6397 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6398 DL.getDebugLoc()); 6399 DAG.getContext()->diagnose(BadIntrin); 6400 return DAG.getUNDEF(VT); 6401 } 6402 6403 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6404 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6405 return getPreloadedValue(DAG, *MFI, VT, RegID); 6406 } 6407 case Intrinsic::amdgcn_implicitarg_ptr: { 6408 if (MFI->isEntryFunction()) 6409 return getImplicitArgPtr(DAG, DL); 6410 return getPreloadedValue(DAG, *MFI, VT, 6411 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6412 } 6413 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6414 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6415 // This only makes sense to call in a kernel, so just lower to null. 6416 return DAG.getConstant(0, DL, VT); 6417 } 6418 6419 return getPreloadedValue(DAG, *MFI, VT, 6420 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6421 } 6422 case Intrinsic::amdgcn_dispatch_id: { 6423 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6424 } 6425 case Intrinsic::amdgcn_rcp: 6426 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6427 case Intrinsic::amdgcn_rsq: 6428 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6429 case Intrinsic::amdgcn_rsq_legacy: 6430 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6431 return emitRemovedIntrinsicError(DAG, DL, VT); 6432 return SDValue(); 6433 case Intrinsic::amdgcn_rcp_legacy: 6434 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6435 return emitRemovedIntrinsicError(DAG, DL, VT); 6436 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6437 case Intrinsic::amdgcn_rsq_clamp: { 6438 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6439 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6440 6441 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6442 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6443 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6444 6445 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6446 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6447 DAG.getConstantFP(Max, DL, VT)); 6448 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6449 DAG.getConstantFP(Min, DL, VT)); 6450 } 6451 case Intrinsic::r600_read_ngroups_x: 6452 if (Subtarget->isAmdHsaOS()) 6453 return emitNonHSAIntrinsicError(DAG, DL, VT); 6454 6455 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6456 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6457 false); 6458 case Intrinsic::r600_read_ngroups_y: 6459 if (Subtarget->isAmdHsaOS()) 6460 return emitNonHSAIntrinsicError(DAG, DL, VT); 6461 6462 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6463 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6464 false); 6465 case Intrinsic::r600_read_ngroups_z: 6466 if (Subtarget->isAmdHsaOS()) 6467 return emitNonHSAIntrinsicError(DAG, DL, VT); 6468 6469 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6470 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6471 false); 6472 case Intrinsic::r600_read_global_size_x: 6473 if (Subtarget->isAmdHsaOS()) 6474 return emitNonHSAIntrinsicError(DAG, DL, VT); 6475 6476 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6477 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6478 Align(4), false); 6479 case Intrinsic::r600_read_global_size_y: 6480 if (Subtarget->isAmdHsaOS()) 6481 return emitNonHSAIntrinsicError(DAG, DL, VT); 6482 6483 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6484 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6485 Align(4), false); 6486 case Intrinsic::r600_read_global_size_z: 6487 if (Subtarget->isAmdHsaOS()) 6488 return emitNonHSAIntrinsicError(DAG, DL, VT); 6489 6490 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6491 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6492 Align(4), false); 6493 case Intrinsic::r600_read_local_size_x: 6494 if (Subtarget->isAmdHsaOS()) 6495 return emitNonHSAIntrinsicError(DAG, DL, VT); 6496 6497 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6498 SI::KernelInputOffsets::LOCAL_SIZE_X); 6499 case Intrinsic::r600_read_local_size_y: 6500 if (Subtarget->isAmdHsaOS()) 6501 return emitNonHSAIntrinsicError(DAG, DL, VT); 6502 6503 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6504 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6505 case Intrinsic::r600_read_local_size_z: 6506 if (Subtarget->isAmdHsaOS()) 6507 return emitNonHSAIntrinsicError(DAG, DL, VT); 6508 6509 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6510 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6511 case Intrinsic::amdgcn_workgroup_id_x: 6512 return getPreloadedValue(DAG, *MFI, VT, 6513 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6514 case Intrinsic::amdgcn_workgroup_id_y: 6515 return getPreloadedValue(DAG, *MFI, VT, 6516 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6517 case Intrinsic::amdgcn_workgroup_id_z: 6518 return getPreloadedValue(DAG, *MFI, VT, 6519 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6520 case Intrinsic::amdgcn_workitem_id_x: 6521 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6522 SDLoc(DAG.getEntryNode()), 6523 MFI->getArgInfo().WorkItemIDX); 6524 case Intrinsic::amdgcn_workitem_id_y: 6525 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6526 SDLoc(DAG.getEntryNode()), 6527 MFI->getArgInfo().WorkItemIDY); 6528 case Intrinsic::amdgcn_workitem_id_z: 6529 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6530 SDLoc(DAG.getEntryNode()), 6531 MFI->getArgInfo().WorkItemIDZ); 6532 case Intrinsic::amdgcn_wavefrontsize: 6533 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6534 SDLoc(Op), MVT::i32); 6535 case Intrinsic::amdgcn_s_buffer_load: { 6536 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6537 if (CPol & ~AMDGPU::CPol::ALL) 6538 return Op; 6539 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6540 DAG); 6541 } 6542 case Intrinsic::amdgcn_fdiv_fast: 6543 return lowerFDIV_FAST(Op, DAG); 6544 case Intrinsic::amdgcn_sin: 6545 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6546 6547 case Intrinsic::amdgcn_cos: 6548 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6549 6550 case Intrinsic::amdgcn_mul_u24: 6551 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6552 case Intrinsic::amdgcn_mul_i24: 6553 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6554 6555 case Intrinsic::amdgcn_log_clamp: { 6556 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6557 return SDValue(); 6558 6559 return emitRemovedIntrinsicError(DAG, DL, VT); 6560 } 6561 case Intrinsic::amdgcn_ldexp: 6562 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6563 Op.getOperand(1), Op.getOperand(2)); 6564 6565 case Intrinsic::amdgcn_fract: 6566 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6567 6568 case Intrinsic::amdgcn_class: 6569 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6570 Op.getOperand(1), Op.getOperand(2)); 6571 case Intrinsic::amdgcn_div_fmas: 6572 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6573 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6574 Op.getOperand(4)); 6575 6576 case Intrinsic::amdgcn_div_fixup: 6577 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6578 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6579 6580 case Intrinsic::amdgcn_div_scale: { 6581 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6582 6583 // Translate to the operands expected by the machine instruction. The 6584 // first parameter must be the same as the first instruction. 6585 SDValue Numerator = Op.getOperand(1); 6586 SDValue Denominator = Op.getOperand(2); 6587 6588 // Note this order is opposite of the machine instruction's operations, 6589 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6590 // intrinsic has the numerator as the first operand to match a normal 6591 // division operation. 6592 6593 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6594 6595 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6596 Denominator, Numerator); 6597 } 6598 case Intrinsic::amdgcn_icmp: { 6599 // There is a Pat that handles this variant, so return it as-is. 6600 if (Op.getOperand(1).getValueType() == MVT::i1 && 6601 Op.getConstantOperandVal(2) == 0 && 6602 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6603 return Op; 6604 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6605 } 6606 case Intrinsic::amdgcn_fcmp: { 6607 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6608 } 6609 case Intrinsic::amdgcn_ballot: 6610 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6611 case Intrinsic::amdgcn_fmed3: 6612 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6613 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6614 case Intrinsic::amdgcn_fdot2: 6615 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6616 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6617 Op.getOperand(4)); 6618 case Intrinsic::amdgcn_fmul_legacy: 6619 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6620 Op.getOperand(1), Op.getOperand(2)); 6621 case Intrinsic::amdgcn_sffbh: 6622 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6623 case Intrinsic::amdgcn_sbfe: 6624 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6625 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6626 case Intrinsic::amdgcn_ubfe: 6627 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6628 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6629 case Intrinsic::amdgcn_cvt_pkrtz: 6630 case Intrinsic::amdgcn_cvt_pknorm_i16: 6631 case Intrinsic::amdgcn_cvt_pknorm_u16: 6632 case Intrinsic::amdgcn_cvt_pk_i16: 6633 case Intrinsic::amdgcn_cvt_pk_u16: { 6634 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6635 EVT VT = Op.getValueType(); 6636 unsigned Opcode; 6637 6638 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6639 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6640 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6641 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6642 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6643 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6644 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6645 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6646 else 6647 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6648 6649 if (isTypeLegal(VT)) 6650 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6651 6652 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6653 Op.getOperand(1), Op.getOperand(2)); 6654 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6655 } 6656 case Intrinsic::amdgcn_fmad_ftz: 6657 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6658 Op.getOperand(2), Op.getOperand(3)); 6659 6660 case Intrinsic::amdgcn_if_break: 6661 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6662 Op->getOperand(1), Op->getOperand(2)), 0); 6663 6664 case Intrinsic::amdgcn_groupstaticsize: { 6665 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6666 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6667 return Op; 6668 6669 const Module *M = MF.getFunction().getParent(); 6670 const GlobalValue *GV = 6671 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6672 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6673 SIInstrInfo::MO_ABS32_LO); 6674 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6675 } 6676 case Intrinsic::amdgcn_is_shared: 6677 case Intrinsic::amdgcn_is_private: { 6678 SDLoc SL(Op); 6679 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6680 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6681 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6682 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6683 Op.getOperand(1)); 6684 6685 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6686 DAG.getConstant(1, SL, MVT::i32)); 6687 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6688 } 6689 case Intrinsic::amdgcn_alignbit: 6690 return DAG.getNode(ISD::FSHR, DL, VT, 6691 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6692 case Intrinsic::amdgcn_reloc_constant: { 6693 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6694 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6695 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6696 auto RelocSymbol = cast<GlobalVariable>( 6697 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6698 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6699 SIInstrInfo::MO_ABS32_LO); 6700 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6701 } 6702 default: 6703 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6704 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6705 return lowerImage(Op, ImageDimIntr, DAG, false); 6706 6707 return Op; 6708 } 6709 } 6710 6711 // This function computes an appropriate offset to pass to 6712 // MachineMemOperand::setOffset() based on the offset inputs to 6713 // an intrinsic. If any of the offsets are non-contstant or 6714 // if VIndex is non-zero then this function returns 0. Otherwise, 6715 // it returns the sum of VOffset, SOffset, and Offset. 6716 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6717 SDValue SOffset, 6718 SDValue Offset, 6719 SDValue VIndex = SDValue()) { 6720 6721 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6722 !isa<ConstantSDNode>(Offset)) 6723 return 0; 6724 6725 if (VIndex) { 6726 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6727 return 0; 6728 } 6729 6730 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6731 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6732 cast<ConstantSDNode>(Offset)->getSExtValue(); 6733 } 6734 6735 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6736 SelectionDAG &DAG, 6737 unsigned NewOpcode) const { 6738 SDLoc DL(Op); 6739 6740 SDValue VData = Op.getOperand(2); 6741 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6742 SDValue Ops[] = { 6743 Op.getOperand(0), // Chain 6744 VData, // vdata 6745 Op.getOperand(3), // rsrc 6746 DAG.getConstant(0, DL, MVT::i32), // vindex 6747 Offsets.first, // voffset 6748 Op.getOperand(5), // soffset 6749 Offsets.second, // offset 6750 Op.getOperand(6), // cachepolicy 6751 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6752 }; 6753 6754 auto *M = cast<MemSDNode>(Op); 6755 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6756 6757 EVT MemVT = VData.getValueType(); 6758 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6759 M->getMemOperand()); 6760 } 6761 6762 SDValue 6763 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6764 unsigned NewOpcode) const { 6765 SDLoc DL(Op); 6766 6767 SDValue VData = Op.getOperand(2); 6768 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6769 SDValue Ops[] = { 6770 Op.getOperand(0), // Chain 6771 VData, // vdata 6772 Op.getOperand(3), // rsrc 6773 Op.getOperand(4), // vindex 6774 Offsets.first, // voffset 6775 Op.getOperand(6), // soffset 6776 Offsets.second, // offset 6777 Op.getOperand(7), // cachepolicy 6778 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6779 }; 6780 6781 auto *M = cast<MemSDNode>(Op); 6782 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6783 Ops[3])); 6784 6785 EVT MemVT = VData.getValueType(); 6786 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6787 M->getMemOperand()); 6788 } 6789 6790 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6791 SelectionDAG &DAG) const { 6792 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6793 SDLoc DL(Op); 6794 6795 switch (IntrID) { 6796 case Intrinsic::amdgcn_ds_ordered_add: 6797 case Intrinsic::amdgcn_ds_ordered_swap: { 6798 MemSDNode *M = cast<MemSDNode>(Op); 6799 SDValue Chain = M->getOperand(0); 6800 SDValue M0 = M->getOperand(2); 6801 SDValue Value = M->getOperand(3); 6802 unsigned IndexOperand = M->getConstantOperandVal(7); 6803 unsigned WaveRelease = M->getConstantOperandVal(8); 6804 unsigned WaveDone = M->getConstantOperandVal(9); 6805 6806 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6807 IndexOperand &= ~0x3f; 6808 unsigned CountDw = 0; 6809 6810 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6811 CountDw = (IndexOperand >> 24) & 0xf; 6812 IndexOperand &= ~(0xf << 24); 6813 6814 if (CountDw < 1 || CountDw > 4) { 6815 report_fatal_error( 6816 "ds_ordered_count: dword count must be between 1 and 4"); 6817 } 6818 } 6819 6820 if (IndexOperand) 6821 report_fatal_error("ds_ordered_count: bad index operand"); 6822 6823 if (WaveDone && !WaveRelease) 6824 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6825 6826 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6827 unsigned ShaderType = 6828 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6829 unsigned Offset0 = OrderedCountIndex << 2; 6830 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6831 (Instruction << 4); 6832 6833 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6834 Offset1 |= (CountDw - 1) << 6; 6835 6836 unsigned Offset = Offset0 | (Offset1 << 8); 6837 6838 SDValue Ops[] = { 6839 Chain, 6840 Value, 6841 DAG.getTargetConstant(Offset, DL, MVT::i16), 6842 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6843 }; 6844 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6845 M->getVTList(), Ops, M->getMemoryVT(), 6846 M->getMemOperand()); 6847 } 6848 case Intrinsic::amdgcn_ds_fadd: { 6849 MemSDNode *M = cast<MemSDNode>(Op); 6850 unsigned Opc; 6851 switch (IntrID) { 6852 case Intrinsic::amdgcn_ds_fadd: 6853 Opc = ISD::ATOMIC_LOAD_FADD; 6854 break; 6855 } 6856 6857 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6858 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6859 M->getMemOperand()); 6860 } 6861 case Intrinsic::amdgcn_atomic_inc: 6862 case Intrinsic::amdgcn_atomic_dec: 6863 case Intrinsic::amdgcn_ds_fmin: 6864 case Intrinsic::amdgcn_ds_fmax: { 6865 MemSDNode *M = cast<MemSDNode>(Op); 6866 unsigned Opc; 6867 switch (IntrID) { 6868 case Intrinsic::amdgcn_atomic_inc: 6869 Opc = AMDGPUISD::ATOMIC_INC; 6870 break; 6871 case Intrinsic::amdgcn_atomic_dec: 6872 Opc = AMDGPUISD::ATOMIC_DEC; 6873 break; 6874 case Intrinsic::amdgcn_ds_fmin: 6875 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6876 break; 6877 case Intrinsic::amdgcn_ds_fmax: 6878 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6879 break; 6880 default: 6881 llvm_unreachable("Unknown intrinsic!"); 6882 } 6883 SDValue Ops[] = { 6884 M->getOperand(0), // Chain 6885 M->getOperand(2), // Ptr 6886 M->getOperand(3) // Value 6887 }; 6888 6889 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6890 M->getMemoryVT(), M->getMemOperand()); 6891 } 6892 case Intrinsic::amdgcn_buffer_load: 6893 case Intrinsic::amdgcn_buffer_load_format: { 6894 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6895 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6896 unsigned IdxEn = 1; 6897 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6898 IdxEn = Idx->getZExtValue() != 0; 6899 SDValue Ops[] = { 6900 Op.getOperand(0), // Chain 6901 Op.getOperand(2), // rsrc 6902 Op.getOperand(3), // vindex 6903 SDValue(), // voffset -- will be set by setBufferOffsets 6904 SDValue(), // soffset -- will be set by setBufferOffsets 6905 SDValue(), // offset -- will be set by setBufferOffsets 6906 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6907 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6908 }; 6909 6910 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6911 // We don't know the offset if vindex is non-zero, so clear it. 6912 if (IdxEn) 6913 Offset = 0; 6914 6915 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6916 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6917 6918 EVT VT = Op.getValueType(); 6919 EVT IntVT = VT.changeTypeToInteger(); 6920 auto *M = cast<MemSDNode>(Op); 6921 M->getMemOperand()->setOffset(Offset); 6922 EVT LoadVT = Op.getValueType(); 6923 6924 if (LoadVT.getScalarType() == MVT::f16) 6925 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6926 M, DAG, Ops); 6927 6928 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6929 if (LoadVT.getScalarType() == MVT::i8 || 6930 LoadVT.getScalarType() == MVT::i16) 6931 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6932 6933 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6934 M->getMemOperand(), DAG); 6935 } 6936 case Intrinsic::amdgcn_raw_buffer_load: 6937 case Intrinsic::amdgcn_raw_buffer_load_format: { 6938 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6939 6940 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6941 SDValue Ops[] = { 6942 Op.getOperand(0), // Chain 6943 Op.getOperand(2), // rsrc 6944 DAG.getConstant(0, DL, MVT::i32), // vindex 6945 Offsets.first, // voffset 6946 Op.getOperand(4), // soffset 6947 Offsets.second, // offset 6948 Op.getOperand(5), // cachepolicy, swizzled buffer 6949 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6950 }; 6951 6952 auto *M = cast<MemSDNode>(Op); 6953 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6954 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6955 } 6956 case Intrinsic::amdgcn_struct_buffer_load: 6957 case Intrinsic::amdgcn_struct_buffer_load_format: { 6958 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6959 6960 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6961 SDValue Ops[] = { 6962 Op.getOperand(0), // Chain 6963 Op.getOperand(2), // rsrc 6964 Op.getOperand(3), // vindex 6965 Offsets.first, // voffset 6966 Op.getOperand(5), // soffset 6967 Offsets.second, // offset 6968 Op.getOperand(6), // cachepolicy, swizzled buffer 6969 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6970 }; 6971 6972 auto *M = cast<MemSDNode>(Op); 6973 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6974 Ops[2])); 6975 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6976 } 6977 case Intrinsic::amdgcn_tbuffer_load: { 6978 MemSDNode *M = cast<MemSDNode>(Op); 6979 EVT LoadVT = Op.getValueType(); 6980 6981 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6982 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6983 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6984 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6985 unsigned IdxEn = 1; 6986 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6987 IdxEn = Idx->getZExtValue() != 0; 6988 SDValue Ops[] = { 6989 Op.getOperand(0), // Chain 6990 Op.getOperand(2), // rsrc 6991 Op.getOperand(3), // vindex 6992 Op.getOperand(4), // voffset 6993 Op.getOperand(5), // soffset 6994 Op.getOperand(6), // offset 6995 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6996 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6997 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6998 }; 6999 7000 if (LoadVT.getScalarType() == MVT::f16) 7001 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7002 M, DAG, Ops); 7003 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7004 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7005 DAG); 7006 } 7007 case Intrinsic::amdgcn_raw_tbuffer_load: { 7008 MemSDNode *M = cast<MemSDNode>(Op); 7009 EVT LoadVT = Op.getValueType(); 7010 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7011 7012 SDValue Ops[] = { 7013 Op.getOperand(0), // Chain 7014 Op.getOperand(2), // rsrc 7015 DAG.getConstant(0, DL, MVT::i32), // vindex 7016 Offsets.first, // voffset 7017 Op.getOperand(4), // soffset 7018 Offsets.second, // offset 7019 Op.getOperand(5), // format 7020 Op.getOperand(6), // cachepolicy, swizzled buffer 7021 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7022 }; 7023 7024 if (LoadVT.getScalarType() == MVT::f16) 7025 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7026 M, DAG, Ops); 7027 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7028 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7029 DAG); 7030 } 7031 case Intrinsic::amdgcn_struct_tbuffer_load: { 7032 MemSDNode *M = cast<MemSDNode>(Op); 7033 EVT LoadVT = Op.getValueType(); 7034 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7035 7036 SDValue Ops[] = { 7037 Op.getOperand(0), // Chain 7038 Op.getOperand(2), // rsrc 7039 Op.getOperand(3), // vindex 7040 Offsets.first, // voffset 7041 Op.getOperand(5), // soffset 7042 Offsets.second, // offset 7043 Op.getOperand(6), // format 7044 Op.getOperand(7), // cachepolicy, swizzled buffer 7045 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7046 }; 7047 7048 if (LoadVT.getScalarType() == MVT::f16) 7049 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7050 M, DAG, Ops); 7051 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7052 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7053 DAG); 7054 } 7055 case Intrinsic::amdgcn_buffer_atomic_swap: 7056 case Intrinsic::amdgcn_buffer_atomic_add: 7057 case Intrinsic::amdgcn_buffer_atomic_sub: 7058 case Intrinsic::amdgcn_buffer_atomic_csub: 7059 case Intrinsic::amdgcn_buffer_atomic_smin: 7060 case Intrinsic::amdgcn_buffer_atomic_umin: 7061 case Intrinsic::amdgcn_buffer_atomic_smax: 7062 case Intrinsic::amdgcn_buffer_atomic_umax: 7063 case Intrinsic::amdgcn_buffer_atomic_and: 7064 case Intrinsic::amdgcn_buffer_atomic_or: 7065 case Intrinsic::amdgcn_buffer_atomic_xor: 7066 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7067 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7068 unsigned IdxEn = 1; 7069 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7070 IdxEn = Idx->getZExtValue() != 0; 7071 SDValue Ops[] = { 7072 Op.getOperand(0), // Chain 7073 Op.getOperand(2), // vdata 7074 Op.getOperand(3), // rsrc 7075 Op.getOperand(4), // vindex 7076 SDValue(), // voffset -- will be set by setBufferOffsets 7077 SDValue(), // soffset -- will be set by setBufferOffsets 7078 SDValue(), // offset -- will be set by setBufferOffsets 7079 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7080 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7081 }; 7082 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7083 // We don't know the offset if vindex is non-zero, so clear it. 7084 if (IdxEn) 7085 Offset = 0; 7086 EVT VT = Op.getValueType(); 7087 7088 auto *M = cast<MemSDNode>(Op); 7089 M->getMemOperand()->setOffset(Offset); 7090 unsigned Opcode = 0; 7091 7092 switch (IntrID) { 7093 case Intrinsic::amdgcn_buffer_atomic_swap: 7094 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7095 break; 7096 case Intrinsic::amdgcn_buffer_atomic_add: 7097 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7098 break; 7099 case Intrinsic::amdgcn_buffer_atomic_sub: 7100 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7101 break; 7102 case Intrinsic::amdgcn_buffer_atomic_csub: 7103 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7104 break; 7105 case Intrinsic::amdgcn_buffer_atomic_smin: 7106 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7107 break; 7108 case Intrinsic::amdgcn_buffer_atomic_umin: 7109 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7110 break; 7111 case Intrinsic::amdgcn_buffer_atomic_smax: 7112 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7113 break; 7114 case Intrinsic::amdgcn_buffer_atomic_umax: 7115 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7116 break; 7117 case Intrinsic::amdgcn_buffer_atomic_and: 7118 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7119 break; 7120 case Intrinsic::amdgcn_buffer_atomic_or: 7121 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7122 break; 7123 case Intrinsic::amdgcn_buffer_atomic_xor: 7124 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7125 break; 7126 case Intrinsic::amdgcn_buffer_atomic_fadd: 7127 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7128 DiagnosticInfoUnsupported 7129 NoFpRet(DAG.getMachineFunction().getFunction(), 7130 "return versions of fp atomics not supported", 7131 DL.getDebugLoc(), DS_Error); 7132 DAG.getContext()->diagnose(NoFpRet); 7133 return SDValue(); 7134 } 7135 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7136 break; 7137 default: 7138 llvm_unreachable("unhandled atomic opcode"); 7139 } 7140 7141 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7142 M->getMemOperand()); 7143 } 7144 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7145 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7146 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7147 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7148 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7149 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7150 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7151 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7152 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7153 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7154 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7155 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7156 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7157 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7158 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7159 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7160 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7161 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7162 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7163 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7164 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7165 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7166 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7167 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7168 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7169 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7170 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7171 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7172 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7173 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7174 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7175 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7176 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7177 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7178 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7179 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7180 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7181 return lowerStructBufferAtomicIntrin(Op, DAG, 7182 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7183 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7184 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7185 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7186 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7187 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7188 return lowerStructBufferAtomicIntrin(Op, DAG, 7189 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7190 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7191 return lowerStructBufferAtomicIntrin(Op, DAG, 7192 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7193 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7194 return lowerStructBufferAtomicIntrin(Op, DAG, 7195 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7196 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7197 return lowerStructBufferAtomicIntrin(Op, DAG, 7198 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7199 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7200 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7201 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7202 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7203 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7204 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7205 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7206 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7207 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7208 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7209 7210 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7211 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7212 unsigned IdxEn = 1; 7213 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7214 IdxEn = Idx->getZExtValue() != 0; 7215 SDValue Ops[] = { 7216 Op.getOperand(0), // Chain 7217 Op.getOperand(2), // src 7218 Op.getOperand(3), // cmp 7219 Op.getOperand(4), // rsrc 7220 Op.getOperand(5), // 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(Slc << 1, DL, MVT::i32), // cachepolicy 7225 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7226 }; 7227 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7228 // We don't know the offset if vindex is non-zero, so clear it. 7229 if (IdxEn) 7230 Offset = 0; 7231 EVT VT = Op.getValueType(); 7232 auto *M = cast<MemSDNode>(Op); 7233 M->getMemOperand()->setOffset(Offset); 7234 7235 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7236 Op->getVTList(), Ops, VT, M->getMemOperand()); 7237 } 7238 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7239 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7240 SDValue Ops[] = { 7241 Op.getOperand(0), // Chain 7242 Op.getOperand(2), // src 7243 Op.getOperand(3), // cmp 7244 Op.getOperand(4), // rsrc 7245 DAG.getConstant(0, DL, MVT::i32), // vindex 7246 Offsets.first, // voffset 7247 Op.getOperand(6), // soffset 7248 Offsets.second, // offset 7249 Op.getOperand(7), // cachepolicy 7250 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7251 }; 7252 EVT VT = Op.getValueType(); 7253 auto *M = cast<MemSDNode>(Op); 7254 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7255 7256 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7257 Op->getVTList(), Ops, VT, M->getMemOperand()); 7258 } 7259 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7260 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7261 SDValue Ops[] = { 7262 Op.getOperand(0), // Chain 7263 Op.getOperand(2), // src 7264 Op.getOperand(3), // cmp 7265 Op.getOperand(4), // rsrc 7266 Op.getOperand(5), // vindex 7267 Offsets.first, // voffset 7268 Op.getOperand(7), // soffset 7269 Offsets.second, // offset 7270 Op.getOperand(8), // cachepolicy 7271 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7272 }; 7273 EVT VT = Op.getValueType(); 7274 auto *M = cast<MemSDNode>(Op); 7275 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7276 Ops[4])); 7277 7278 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7279 Op->getVTList(), Ops, VT, M->getMemOperand()); 7280 } 7281 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7282 SDLoc DL(Op); 7283 MemSDNode *M = cast<MemSDNode>(Op); 7284 SDValue NodePtr = M->getOperand(2); 7285 SDValue RayExtent = M->getOperand(3); 7286 SDValue RayOrigin = M->getOperand(4); 7287 SDValue RayDir = M->getOperand(5); 7288 SDValue RayInvDir = M->getOperand(6); 7289 SDValue TDescr = M->getOperand(7); 7290 7291 assert(NodePtr.getValueType() == MVT::i32 || 7292 NodePtr.getValueType() == MVT::i64); 7293 assert(RayDir.getValueType() == MVT::v4f16 || 7294 RayDir.getValueType() == MVT::v4f32); 7295 7296 bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7297 bool Is64 = NodePtr.getValueType() == MVT::i64; 7298 unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa 7299 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa 7300 : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa 7301 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa; 7302 7303 SmallVector<SDValue, 16> Ops; 7304 7305 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7306 SmallVector<SDValue, 3> Lanes; 7307 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7308 if (Lanes[0].getValueSizeInBits() == 32) { 7309 for (unsigned I = 0; I < 3; ++I) 7310 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7311 } else { 7312 if (IsAligned) { 7313 Ops.push_back( 7314 DAG.getBitcast(MVT::i32, 7315 DAG.getBuildVector(MVT::v2f16, DL, 7316 { Lanes[0], Lanes[1] }))); 7317 Ops.push_back(Lanes[2]); 7318 } else { 7319 SDValue Elt0 = Ops.pop_back_val(); 7320 Ops.push_back( 7321 DAG.getBitcast(MVT::i32, 7322 DAG.getBuildVector(MVT::v2f16, DL, 7323 { Elt0, Lanes[0] }))); 7324 Ops.push_back( 7325 DAG.getBitcast(MVT::i32, 7326 DAG.getBuildVector(MVT::v2f16, DL, 7327 { Lanes[1], Lanes[2] }))); 7328 } 7329 } 7330 }; 7331 7332 if (Is64) 7333 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7334 else 7335 Ops.push_back(NodePtr); 7336 7337 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7338 packLanes(RayOrigin, true); 7339 packLanes(RayDir, true); 7340 packLanes(RayInvDir, false); 7341 Ops.push_back(TDescr); 7342 if (IsA16) 7343 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7344 Ops.push_back(M->getChain()); 7345 7346 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7347 MachineMemOperand *MemRef = M->getMemOperand(); 7348 DAG.setNodeMemRefs(NewNode, {MemRef}); 7349 return SDValue(NewNode, 0); 7350 } 7351 case Intrinsic::amdgcn_global_atomic_fadd: 7352 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7353 DiagnosticInfoUnsupported 7354 NoFpRet(DAG.getMachineFunction().getFunction(), 7355 "return versions of fp atomics not supported", 7356 DL.getDebugLoc(), DS_Error); 7357 DAG.getContext()->diagnose(NoFpRet); 7358 return SDValue(); 7359 } 7360 LLVM_FALLTHROUGH; 7361 case Intrinsic::amdgcn_global_atomic_fmin: 7362 case Intrinsic::amdgcn_global_atomic_fmax: 7363 case Intrinsic::amdgcn_flat_atomic_fadd: 7364 case Intrinsic::amdgcn_flat_atomic_fmin: 7365 case Intrinsic::amdgcn_flat_atomic_fmax: { 7366 MemSDNode *M = cast<MemSDNode>(Op); 7367 SDValue Ops[] = { 7368 M->getOperand(0), // Chain 7369 M->getOperand(2), // Ptr 7370 M->getOperand(3) // Value 7371 }; 7372 unsigned Opcode = 0; 7373 switch (IntrID) { 7374 case Intrinsic::amdgcn_global_atomic_fadd: 7375 case Intrinsic::amdgcn_flat_atomic_fadd: { 7376 EVT VT = Op.getOperand(3).getValueType(); 7377 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7378 DAG.getVTList(VT, MVT::Other), Ops, 7379 M->getMemOperand()); 7380 } 7381 case Intrinsic::amdgcn_global_atomic_fmin: 7382 case Intrinsic::amdgcn_flat_atomic_fmin: { 7383 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7384 break; 7385 } 7386 case Intrinsic::amdgcn_global_atomic_fmax: 7387 case Intrinsic::amdgcn_flat_atomic_fmax: { 7388 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7389 break; 7390 } 7391 default: 7392 llvm_unreachable("unhandled atomic opcode"); 7393 } 7394 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7395 M->getVTList(), Ops, M->getMemoryVT(), 7396 M->getMemOperand()); 7397 } 7398 default: 7399 7400 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7401 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7402 return lowerImage(Op, ImageDimIntr, DAG, true); 7403 7404 return SDValue(); 7405 } 7406 } 7407 7408 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7409 // dwordx4 if on SI. 7410 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7411 SDVTList VTList, 7412 ArrayRef<SDValue> Ops, EVT MemVT, 7413 MachineMemOperand *MMO, 7414 SelectionDAG &DAG) const { 7415 EVT VT = VTList.VTs[0]; 7416 EVT WidenedVT = VT; 7417 EVT WidenedMemVT = MemVT; 7418 if (!Subtarget->hasDwordx3LoadStores() && 7419 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7420 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7421 WidenedVT.getVectorElementType(), 4); 7422 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7423 WidenedMemVT.getVectorElementType(), 4); 7424 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7425 } 7426 7427 assert(VTList.NumVTs == 2); 7428 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7429 7430 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7431 WidenedMemVT, MMO); 7432 if (WidenedVT != VT) { 7433 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7434 DAG.getVectorIdxConstant(0, DL)); 7435 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7436 } 7437 return NewOp; 7438 } 7439 7440 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7441 bool ImageStore) const { 7442 EVT StoreVT = VData.getValueType(); 7443 7444 // No change for f16 and legal vector D16 types. 7445 if (!StoreVT.isVector()) 7446 return VData; 7447 7448 SDLoc DL(VData); 7449 unsigned NumElements = StoreVT.getVectorNumElements(); 7450 7451 if (Subtarget->hasUnpackedD16VMem()) { 7452 // We need to unpack the packed data to store. 7453 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7454 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7455 7456 EVT EquivStoreVT = 7457 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7458 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7459 return DAG.UnrollVectorOp(ZExt.getNode()); 7460 } 7461 7462 // The sq block of gfx8.1 does not estimate register use correctly for d16 7463 // image store instructions. The data operand is computed as if it were not a 7464 // d16 image instruction. 7465 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7466 // Bitcast to i16 7467 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7468 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7469 7470 // Decompose into scalars 7471 SmallVector<SDValue, 4> Elts; 7472 DAG.ExtractVectorElements(IntVData, Elts); 7473 7474 // Group pairs of i16 into v2i16 and bitcast to i32 7475 SmallVector<SDValue, 4> PackedElts; 7476 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7477 SDValue Pair = 7478 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7479 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7480 PackedElts.push_back(IntPair); 7481 } 7482 if ((NumElements % 2) == 1) { 7483 // Handle v3i16 7484 unsigned I = Elts.size() / 2; 7485 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7486 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7487 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7488 PackedElts.push_back(IntPair); 7489 } 7490 7491 // Pad using UNDEF 7492 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7493 7494 // Build final vector 7495 EVT VecVT = 7496 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7497 return DAG.getBuildVector(VecVT, DL, PackedElts); 7498 } 7499 7500 if (NumElements == 3) { 7501 EVT IntStoreVT = 7502 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7503 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7504 7505 EVT WidenedStoreVT = EVT::getVectorVT( 7506 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7507 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7508 WidenedStoreVT.getStoreSizeInBits()); 7509 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7510 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7511 } 7512 7513 assert(isTypeLegal(StoreVT)); 7514 return VData; 7515 } 7516 7517 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7518 SelectionDAG &DAG) const { 7519 SDLoc DL(Op); 7520 SDValue Chain = Op.getOperand(0); 7521 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7522 MachineFunction &MF = DAG.getMachineFunction(); 7523 7524 switch (IntrinsicID) { 7525 case Intrinsic::amdgcn_exp_compr: { 7526 SDValue Src0 = Op.getOperand(4); 7527 SDValue Src1 = Op.getOperand(5); 7528 // Hack around illegal type on SI by directly selecting it. 7529 if (isTypeLegal(Src0.getValueType())) 7530 return SDValue(); 7531 7532 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7533 SDValue Undef = DAG.getUNDEF(MVT::f32); 7534 const SDValue Ops[] = { 7535 Op.getOperand(2), // tgt 7536 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7537 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7538 Undef, // src2 7539 Undef, // src3 7540 Op.getOperand(7), // vm 7541 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7542 Op.getOperand(3), // en 7543 Op.getOperand(0) // Chain 7544 }; 7545 7546 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7547 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7548 } 7549 case Intrinsic::amdgcn_s_barrier: { 7550 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7551 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7552 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7553 if (WGSize <= ST.getWavefrontSize()) 7554 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7555 Op.getOperand(0)), 0); 7556 } 7557 return SDValue(); 7558 }; 7559 case Intrinsic::amdgcn_tbuffer_store: { 7560 SDValue VData = Op.getOperand(2); 7561 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7562 if (IsD16) 7563 VData = handleD16VData(VData, DAG); 7564 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7565 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7566 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7567 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7568 unsigned IdxEn = 1; 7569 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7570 IdxEn = Idx->getZExtValue() != 0; 7571 SDValue Ops[] = { 7572 Chain, 7573 VData, // vdata 7574 Op.getOperand(3), // rsrc 7575 Op.getOperand(4), // vindex 7576 Op.getOperand(5), // voffset 7577 Op.getOperand(6), // soffset 7578 Op.getOperand(7), // offset 7579 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7580 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7581 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7582 }; 7583 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7584 AMDGPUISD::TBUFFER_STORE_FORMAT; 7585 MemSDNode *M = cast<MemSDNode>(Op); 7586 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7587 M->getMemoryVT(), M->getMemOperand()); 7588 } 7589 7590 case Intrinsic::amdgcn_struct_tbuffer_store: { 7591 SDValue VData = Op.getOperand(2); 7592 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7593 if (IsD16) 7594 VData = handleD16VData(VData, DAG); 7595 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7596 SDValue Ops[] = { 7597 Chain, 7598 VData, // vdata 7599 Op.getOperand(3), // rsrc 7600 Op.getOperand(4), // vindex 7601 Offsets.first, // voffset 7602 Op.getOperand(6), // soffset 7603 Offsets.second, // offset 7604 Op.getOperand(7), // format 7605 Op.getOperand(8), // cachepolicy, swizzled buffer 7606 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7607 }; 7608 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7609 AMDGPUISD::TBUFFER_STORE_FORMAT; 7610 MemSDNode *M = cast<MemSDNode>(Op); 7611 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7612 M->getMemoryVT(), M->getMemOperand()); 7613 } 7614 7615 case Intrinsic::amdgcn_raw_tbuffer_store: { 7616 SDValue VData = Op.getOperand(2); 7617 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7618 if (IsD16) 7619 VData = handleD16VData(VData, DAG); 7620 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7621 SDValue Ops[] = { 7622 Chain, 7623 VData, // vdata 7624 Op.getOperand(3), // rsrc 7625 DAG.getConstant(0, DL, MVT::i32), // vindex 7626 Offsets.first, // voffset 7627 Op.getOperand(5), // soffset 7628 Offsets.second, // offset 7629 Op.getOperand(6), // format 7630 Op.getOperand(7), // cachepolicy, swizzled buffer 7631 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7632 }; 7633 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7634 AMDGPUISD::TBUFFER_STORE_FORMAT; 7635 MemSDNode *M = cast<MemSDNode>(Op); 7636 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7637 M->getMemoryVT(), M->getMemOperand()); 7638 } 7639 7640 case Intrinsic::amdgcn_buffer_store: 7641 case Intrinsic::amdgcn_buffer_store_format: { 7642 SDValue VData = Op.getOperand(2); 7643 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7644 if (IsD16) 7645 VData = handleD16VData(VData, DAG); 7646 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7647 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7648 unsigned IdxEn = 1; 7649 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7650 IdxEn = Idx->getZExtValue() != 0; 7651 SDValue Ops[] = { 7652 Chain, 7653 VData, 7654 Op.getOperand(3), // rsrc 7655 Op.getOperand(4), // vindex 7656 SDValue(), // voffset -- will be set by setBufferOffsets 7657 SDValue(), // soffset -- will be set by setBufferOffsets 7658 SDValue(), // offset -- will be set by setBufferOffsets 7659 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7660 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7661 }; 7662 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7663 // We don't know the offset if vindex is non-zero, so clear it. 7664 if (IdxEn) 7665 Offset = 0; 7666 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7667 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7668 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7669 MemSDNode *M = cast<MemSDNode>(Op); 7670 M->getMemOperand()->setOffset(Offset); 7671 7672 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7673 EVT VDataType = VData.getValueType().getScalarType(); 7674 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7675 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7676 7677 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7678 M->getMemoryVT(), M->getMemOperand()); 7679 } 7680 7681 case Intrinsic::amdgcn_raw_buffer_store: 7682 case Intrinsic::amdgcn_raw_buffer_store_format: { 7683 const bool IsFormat = 7684 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7685 7686 SDValue VData = Op.getOperand(2); 7687 EVT VDataVT = VData.getValueType(); 7688 EVT EltType = VDataVT.getScalarType(); 7689 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7690 if (IsD16) { 7691 VData = handleD16VData(VData, DAG); 7692 VDataVT = VData.getValueType(); 7693 } 7694 7695 if (!isTypeLegal(VDataVT)) { 7696 VData = 7697 DAG.getNode(ISD::BITCAST, DL, 7698 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7699 } 7700 7701 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7702 SDValue Ops[] = { 7703 Chain, 7704 VData, 7705 Op.getOperand(3), // rsrc 7706 DAG.getConstant(0, DL, MVT::i32), // vindex 7707 Offsets.first, // voffset 7708 Op.getOperand(5), // soffset 7709 Offsets.second, // offset 7710 Op.getOperand(6), // cachepolicy, swizzled buffer 7711 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7712 }; 7713 unsigned Opc = 7714 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7715 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7716 MemSDNode *M = cast<MemSDNode>(Op); 7717 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7718 7719 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7720 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7721 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7722 7723 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7724 M->getMemoryVT(), M->getMemOperand()); 7725 } 7726 7727 case Intrinsic::amdgcn_struct_buffer_store: 7728 case Intrinsic::amdgcn_struct_buffer_store_format: { 7729 const bool IsFormat = 7730 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7731 7732 SDValue VData = Op.getOperand(2); 7733 EVT VDataVT = VData.getValueType(); 7734 EVT EltType = VDataVT.getScalarType(); 7735 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7736 7737 if (IsD16) { 7738 VData = handleD16VData(VData, DAG); 7739 VDataVT = VData.getValueType(); 7740 } 7741 7742 if (!isTypeLegal(VDataVT)) { 7743 VData = 7744 DAG.getNode(ISD::BITCAST, DL, 7745 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7746 } 7747 7748 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7749 SDValue Ops[] = { 7750 Chain, 7751 VData, 7752 Op.getOperand(3), // rsrc 7753 Op.getOperand(4), // vindex 7754 Offsets.first, // voffset 7755 Op.getOperand(6), // soffset 7756 Offsets.second, // offset 7757 Op.getOperand(7), // cachepolicy, swizzled buffer 7758 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7759 }; 7760 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7761 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7762 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7763 MemSDNode *M = cast<MemSDNode>(Op); 7764 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7765 Ops[3])); 7766 7767 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7768 EVT VDataType = VData.getValueType().getScalarType(); 7769 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7770 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7771 7772 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7773 M->getMemoryVT(), M->getMemOperand()); 7774 } 7775 case Intrinsic::amdgcn_end_cf: 7776 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7777 Op->getOperand(2), Chain), 0); 7778 7779 default: { 7780 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7781 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7782 return lowerImage(Op, ImageDimIntr, DAG, true); 7783 7784 return Op; 7785 } 7786 } 7787 } 7788 7789 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7790 // offset (the offset that is included in bounds checking and swizzling, to be 7791 // split between the instruction's voffset and immoffset fields) and soffset 7792 // (the offset that is excluded from bounds checking and swizzling, to go in 7793 // the instruction's soffset field). This function takes the first kind of 7794 // offset and figures out how to split it between voffset and immoffset. 7795 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7796 SDValue Offset, SelectionDAG &DAG) const { 7797 SDLoc DL(Offset); 7798 const unsigned MaxImm = 4095; 7799 SDValue N0 = Offset; 7800 ConstantSDNode *C1 = nullptr; 7801 7802 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7803 N0 = SDValue(); 7804 else if (DAG.isBaseWithConstantOffset(N0)) { 7805 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7806 N0 = N0.getOperand(0); 7807 } 7808 7809 if (C1) { 7810 unsigned ImmOffset = C1->getZExtValue(); 7811 // If the immediate value is too big for the immoffset field, put the value 7812 // and -4096 into the immoffset field so that the value that is copied/added 7813 // for the voffset field is a multiple of 4096, and it stands more chance 7814 // of being CSEd with the copy/add for another similar load/store. 7815 // However, do not do that rounding down to a multiple of 4096 if that is a 7816 // negative number, as it appears to be illegal to have a negative offset 7817 // in the vgpr, even if adding the immediate offset makes it positive. 7818 unsigned Overflow = ImmOffset & ~MaxImm; 7819 ImmOffset -= Overflow; 7820 if ((int32_t)Overflow < 0) { 7821 Overflow += ImmOffset; 7822 ImmOffset = 0; 7823 } 7824 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7825 if (Overflow) { 7826 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7827 if (!N0) 7828 N0 = OverflowVal; 7829 else { 7830 SDValue Ops[] = { N0, OverflowVal }; 7831 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7832 } 7833 } 7834 } 7835 if (!N0) 7836 N0 = DAG.getConstant(0, DL, MVT::i32); 7837 if (!C1) 7838 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7839 return {N0, SDValue(C1, 0)}; 7840 } 7841 7842 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7843 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7844 // pointed to by Offsets. 7845 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7846 SelectionDAG &DAG, SDValue *Offsets, 7847 Align Alignment) const { 7848 SDLoc DL(CombinedOffset); 7849 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7850 uint32_t Imm = C->getZExtValue(); 7851 uint32_t SOffset, ImmOffset; 7852 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7853 Alignment)) { 7854 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7855 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7856 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7857 return SOffset + ImmOffset; 7858 } 7859 } 7860 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7861 SDValue N0 = CombinedOffset.getOperand(0); 7862 SDValue N1 = CombinedOffset.getOperand(1); 7863 uint32_t SOffset, ImmOffset; 7864 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7865 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7866 Subtarget, Alignment)) { 7867 Offsets[0] = N0; 7868 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7869 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7870 return 0; 7871 } 7872 } 7873 Offsets[0] = CombinedOffset; 7874 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7875 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7876 return 0; 7877 } 7878 7879 // Handle 8 bit and 16 bit buffer loads 7880 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7881 EVT LoadVT, SDLoc DL, 7882 ArrayRef<SDValue> Ops, 7883 MemSDNode *M) const { 7884 EVT IntVT = LoadVT.changeTypeToInteger(); 7885 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7886 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7887 7888 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7889 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7890 Ops, IntVT, 7891 M->getMemOperand()); 7892 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7893 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7894 7895 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7896 } 7897 7898 // Handle 8 bit and 16 bit buffer stores 7899 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7900 EVT VDataType, SDLoc DL, 7901 SDValue Ops[], 7902 MemSDNode *M) const { 7903 if (VDataType == MVT::f16) 7904 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7905 7906 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7907 Ops[1] = BufferStoreExt; 7908 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7909 AMDGPUISD::BUFFER_STORE_SHORT; 7910 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7911 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7912 M->getMemOperand()); 7913 } 7914 7915 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7916 ISD::LoadExtType ExtType, SDValue Op, 7917 const SDLoc &SL, EVT VT) { 7918 if (VT.bitsLT(Op.getValueType())) 7919 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7920 7921 switch (ExtType) { 7922 case ISD::SEXTLOAD: 7923 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7924 case ISD::ZEXTLOAD: 7925 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7926 case ISD::EXTLOAD: 7927 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7928 case ISD::NON_EXTLOAD: 7929 return Op; 7930 } 7931 7932 llvm_unreachable("invalid ext type"); 7933 } 7934 7935 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7936 SelectionDAG &DAG = DCI.DAG; 7937 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7938 return SDValue(); 7939 7940 // FIXME: Constant loads should all be marked invariant. 7941 unsigned AS = Ld->getAddressSpace(); 7942 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7943 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7944 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7945 return SDValue(); 7946 7947 // Don't do this early, since it may interfere with adjacent load merging for 7948 // illegal types. We can avoid losing alignment information for exotic types 7949 // pre-legalize. 7950 EVT MemVT = Ld->getMemoryVT(); 7951 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7952 MemVT.getSizeInBits() >= 32) 7953 return SDValue(); 7954 7955 SDLoc SL(Ld); 7956 7957 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7958 "unexpected vector extload"); 7959 7960 // TODO: Drop only high part of range. 7961 SDValue Ptr = Ld->getBasePtr(); 7962 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7963 MVT::i32, SL, Ld->getChain(), Ptr, 7964 Ld->getOffset(), 7965 Ld->getPointerInfo(), MVT::i32, 7966 Ld->getAlignment(), 7967 Ld->getMemOperand()->getFlags(), 7968 Ld->getAAInfo(), 7969 nullptr); // Drop ranges 7970 7971 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7972 if (MemVT.isFloatingPoint()) { 7973 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7974 "unexpected fp extload"); 7975 TruncVT = MemVT.changeTypeToInteger(); 7976 } 7977 7978 SDValue Cvt = NewLoad; 7979 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7980 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7981 DAG.getValueType(TruncVT)); 7982 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7983 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7984 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7985 } else { 7986 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7987 } 7988 7989 EVT VT = Ld->getValueType(0); 7990 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7991 7992 DCI.AddToWorklist(Cvt.getNode()); 7993 7994 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7995 // the appropriate extension from the 32-bit load. 7996 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7997 DCI.AddToWorklist(Cvt.getNode()); 7998 7999 // Handle conversion back to floating point if necessary. 8000 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8001 8002 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8003 } 8004 8005 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8006 SDLoc DL(Op); 8007 LoadSDNode *Load = cast<LoadSDNode>(Op); 8008 ISD::LoadExtType ExtType = Load->getExtensionType(); 8009 EVT MemVT = Load->getMemoryVT(); 8010 8011 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8012 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8013 return SDValue(); 8014 8015 // FIXME: Copied from PPC 8016 // First, load into 32 bits, then truncate to 1 bit. 8017 8018 SDValue Chain = Load->getChain(); 8019 SDValue BasePtr = Load->getBasePtr(); 8020 MachineMemOperand *MMO = Load->getMemOperand(); 8021 8022 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8023 8024 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8025 BasePtr, RealMemVT, MMO); 8026 8027 if (!MemVT.isVector()) { 8028 SDValue Ops[] = { 8029 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8030 NewLD.getValue(1) 8031 }; 8032 8033 return DAG.getMergeValues(Ops, DL); 8034 } 8035 8036 SmallVector<SDValue, 3> Elts; 8037 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8038 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8039 DAG.getConstant(I, DL, MVT::i32)); 8040 8041 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8042 } 8043 8044 SDValue Ops[] = { 8045 DAG.getBuildVector(MemVT, DL, Elts), 8046 NewLD.getValue(1) 8047 }; 8048 8049 return DAG.getMergeValues(Ops, DL); 8050 } 8051 8052 if (!MemVT.isVector()) 8053 return SDValue(); 8054 8055 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8056 "Custom lowering for non-i32 vectors hasn't been implemented."); 8057 8058 unsigned Alignment = Load->getAlignment(); 8059 unsigned AS = Load->getAddressSpace(); 8060 if (Subtarget->hasLDSMisalignedBug() && 8061 AS == AMDGPUAS::FLAT_ADDRESS && 8062 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8063 return SplitVectorLoad(Op, DAG); 8064 } 8065 8066 MachineFunction &MF = DAG.getMachineFunction(); 8067 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8068 // If there is a possibilty that flat instruction access scratch memory 8069 // then we need to use the same legalization rules we use for private. 8070 if (AS == AMDGPUAS::FLAT_ADDRESS && 8071 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8072 AS = MFI->hasFlatScratchInit() ? 8073 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8074 8075 unsigned NumElements = MemVT.getVectorNumElements(); 8076 8077 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8078 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8079 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8080 if (MemVT.isPow2VectorType()) 8081 return SDValue(); 8082 return WidenOrSplitVectorLoad(Op, DAG); 8083 } 8084 // Non-uniform loads will be selected to MUBUF instructions, so they 8085 // have the same legalization requirements as global and private 8086 // loads. 8087 // 8088 } 8089 8090 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8091 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8092 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8093 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8094 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8095 Alignment >= 4 && NumElements < 32) { 8096 if (MemVT.isPow2VectorType()) 8097 return SDValue(); 8098 return WidenOrSplitVectorLoad(Op, DAG); 8099 } 8100 // Non-uniform loads will be selected to MUBUF instructions, so they 8101 // have the same legalization requirements as global and private 8102 // loads. 8103 // 8104 } 8105 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8106 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8107 AS == AMDGPUAS::GLOBAL_ADDRESS || 8108 AS == AMDGPUAS::FLAT_ADDRESS) { 8109 if (NumElements > 4) 8110 return SplitVectorLoad(Op, DAG); 8111 // v3 loads not supported on SI. 8112 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8113 return WidenOrSplitVectorLoad(Op, DAG); 8114 8115 // v3 and v4 loads are supported for private and global memory. 8116 return SDValue(); 8117 } 8118 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8119 // Depending on the setting of the private_element_size field in the 8120 // resource descriptor, we can only make private accesses up to a certain 8121 // size. 8122 switch (Subtarget->getMaxPrivateElementSize()) { 8123 case 4: { 8124 SDValue Ops[2]; 8125 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8126 return DAG.getMergeValues(Ops, DL); 8127 } 8128 case 8: 8129 if (NumElements > 2) 8130 return SplitVectorLoad(Op, DAG); 8131 return SDValue(); 8132 case 16: 8133 // Same as global/flat 8134 if (NumElements > 4) 8135 return SplitVectorLoad(Op, DAG); 8136 // v3 loads not supported on SI. 8137 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8138 return WidenOrSplitVectorLoad(Op, DAG); 8139 8140 return SDValue(); 8141 default: 8142 llvm_unreachable("unsupported private_element_size"); 8143 } 8144 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8145 // Use ds_read_b128 or ds_read_b96 when possible. 8146 if (Subtarget->hasDS96AndDS128() && 8147 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8148 MemVT.getStoreSize() == 12) && 8149 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8150 Load->getAlign())) 8151 return SDValue(); 8152 8153 if (NumElements > 2) 8154 return SplitVectorLoad(Op, DAG); 8155 8156 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8157 // address is negative, then the instruction is incorrectly treated as 8158 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8159 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8160 // load later in the SILoadStoreOptimizer. 8161 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8162 NumElements == 2 && MemVT.getStoreSize() == 8 && 8163 Load->getAlignment() < 8) { 8164 return SplitVectorLoad(Op, DAG); 8165 } 8166 } 8167 8168 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8169 MemVT, *Load->getMemOperand())) { 8170 SDValue Ops[2]; 8171 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8172 return DAG.getMergeValues(Ops, DL); 8173 } 8174 8175 return SDValue(); 8176 } 8177 8178 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8179 EVT VT = Op.getValueType(); 8180 assert(VT.getSizeInBits() == 64); 8181 8182 SDLoc DL(Op); 8183 SDValue Cond = Op.getOperand(0); 8184 8185 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8186 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8187 8188 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8189 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8190 8191 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8192 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8193 8194 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8195 8196 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8197 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8198 8199 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8200 8201 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8202 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8203 } 8204 8205 // Catch division cases where we can use shortcuts with rcp and rsq 8206 // instructions. 8207 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8208 SelectionDAG &DAG) const { 8209 SDLoc SL(Op); 8210 SDValue LHS = Op.getOperand(0); 8211 SDValue RHS = Op.getOperand(1); 8212 EVT VT = Op.getValueType(); 8213 const SDNodeFlags Flags = Op->getFlags(); 8214 8215 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8216 8217 // Without !fpmath accuracy information, we can't do more because we don't 8218 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8219 if (!AllowInaccurateRcp) 8220 return SDValue(); 8221 8222 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8223 if (CLHS->isExactlyValue(1.0)) { 8224 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8225 // the CI documentation has a worst case error of 1 ulp. 8226 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8227 // use it as long as we aren't trying to use denormals. 8228 // 8229 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8230 8231 // 1.0 / sqrt(x) -> rsq(x) 8232 8233 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8234 // error seems really high at 2^29 ULP. 8235 if (RHS.getOpcode() == ISD::FSQRT) 8236 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8237 8238 // 1.0 / x -> rcp(x) 8239 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8240 } 8241 8242 // Same as for 1.0, but expand the sign out of the constant. 8243 if (CLHS->isExactlyValue(-1.0)) { 8244 // -1.0 / x -> rcp (fneg x) 8245 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8246 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8247 } 8248 } 8249 8250 // Turn into multiply by the reciprocal. 8251 // x / y -> x * (1.0 / y) 8252 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8253 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8254 } 8255 8256 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8257 SelectionDAG &DAG) const { 8258 SDLoc SL(Op); 8259 SDValue X = Op.getOperand(0); 8260 SDValue Y = Op.getOperand(1); 8261 EVT VT = Op.getValueType(); 8262 const SDNodeFlags Flags = Op->getFlags(); 8263 8264 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8265 DAG.getTarget().Options.UnsafeFPMath; 8266 if (!AllowInaccurateDiv) 8267 return SDValue(); 8268 8269 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8270 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8271 8272 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8273 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8274 8275 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8276 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8277 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8278 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8279 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8280 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8281 } 8282 8283 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8284 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8285 SDNodeFlags Flags) { 8286 if (GlueChain->getNumValues() <= 1) { 8287 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8288 } 8289 8290 assert(GlueChain->getNumValues() == 3); 8291 8292 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8293 switch (Opcode) { 8294 default: llvm_unreachable("no chain equivalent for opcode"); 8295 case ISD::FMUL: 8296 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8297 break; 8298 } 8299 8300 return DAG.getNode(Opcode, SL, VTList, 8301 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8302 Flags); 8303 } 8304 8305 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8306 EVT VT, SDValue A, SDValue B, SDValue C, 8307 SDValue GlueChain, SDNodeFlags Flags) { 8308 if (GlueChain->getNumValues() <= 1) { 8309 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8310 } 8311 8312 assert(GlueChain->getNumValues() == 3); 8313 8314 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8315 switch (Opcode) { 8316 default: llvm_unreachable("no chain equivalent for opcode"); 8317 case ISD::FMA: 8318 Opcode = AMDGPUISD::FMA_W_CHAIN; 8319 break; 8320 } 8321 8322 return DAG.getNode(Opcode, SL, VTList, 8323 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8324 Flags); 8325 } 8326 8327 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8328 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8329 return FastLowered; 8330 8331 SDLoc SL(Op); 8332 SDValue Src0 = Op.getOperand(0); 8333 SDValue Src1 = Op.getOperand(1); 8334 8335 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8336 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8337 8338 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8339 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8340 8341 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8342 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8343 8344 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8345 } 8346 8347 // Faster 2.5 ULP division that does not support denormals. 8348 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8349 SDLoc SL(Op); 8350 SDValue LHS = Op.getOperand(1); 8351 SDValue RHS = Op.getOperand(2); 8352 8353 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8354 8355 const APFloat K0Val(BitsToFloat(0x6f800000)); 8356 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8357 8358 const APFloat K1Val(BitsToFloat(0x2f800000)); 8359 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8360 8361 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8362 8363 EVT SetCCVT = 8364 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8365 8366 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8367 8368 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8369 8370 // TODO: Should this propagate fast-math-flags? 8371 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8372 8373 // rcp does not support denormals. 8374 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8375 8376 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8377 8378 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8379 } 8380 8381 // Returns immediate value for setting the F32 denorm mode when using the 8382 // S_DENORM_MODE instruction. 8383 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8384 const SDLoc &SL, const GCNSubtarget *ST) { 8385 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8386 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8387 ? FP_DENORM_FLUSH_NONE 8388 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8389 8390 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8391 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8392 } 8393 8394 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8395 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8396 return FastLowered; 8397 8398 // The selection matcher assumes anything with a chain selecting to a 8399 // mayRaiseFPException machine instruction. Since we're introducing a chain 8400 // here, we need to explicitly report nofpexcept for the regular fdiv 8401 // lowering. 8402 SDNodeFlags Flags = Op->getFlags(); 8403 Flags.setNoFPExcept(true); 8404 8405 SDLoc SL(Op); 8406 SDValue LHS = Op.getOperand(0); 8407 SDValue RHS = Op.getOperand(1); 8408 8409 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8410 8411 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8412 8413 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8414 {RHS, RHS, LHS}, Flags); 8415 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8416 {LHS, RHS, LHS}, Flags); 8417 8418 // Denominator is scaled to not be denormal, so using rcp is ok. 8419 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8420 DenominatorScaled, Flags); 8421 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8422 DenominatorScaled, Flags); 8423 8424 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8425 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8426 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8427 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8428 8429 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8430 8431 if (!HasFP32Denormals) { 8432 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8433 // lowering. The chain dependence is insufficient, and we need glue. We do 8434 // not need the glue variants in a strictfp function. 8435 8436 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8437 8438 SDNode *EnableDenorm; 8439 if (Subtarget->hasDenormModeInst()) { 8440 const SDValue EnableDenormValue = 8441 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8442 8443 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8444 DAG.getEntryNode(), EnableDenormValue).getNode(); 8445 } else { 8446 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8447 SL, MVT::i32); 8448 EnableDenorm = 8449 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8450 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8451 } 8452 8453 SDValue Ops[3] = { 8454 NegDivScale0, 8455 SDValue(EnableDenorm, 0), 8456 SDValue(EnableDenorm, 1) 8457 }; 8458 8459 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8460 } 8461 8462 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8463 ApproxRcp, One, NegDivScale0, Flags); 8464 8465 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8466 ApproxRcp, Fma0, Flags); 8467 8468 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8469 Fma1, Fma1, Flags); 8470 8471 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8472 NumeratorScaled, Mul, Flags); 8473 8474 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8475 Fma2, Fma1, Mul, Fma2, Flags); 8476 8477 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8478 NumeratorScaled, Fma3, Flags); 8479 8480 if (!HasFP32Denormals) { 8481 SDNode *DisableDenorm; 8482 if (Subtarget->hasDenormModeInst()) { 8483 const SDValue DisableDenormValue = 8484 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8485 8486 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8487 Fma4.getValue(1), DisableDenormValue, 8488 Fma4.getValue(2)).getNode(); 8489 } else { 8490 const SDValue DisableDenormValue = 8491 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8492 8493 DisableDenorm = DAG.getMachineNode( 8494 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8495 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8496 } 8497 8498 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8499 SDValue(DisableDenorm, 0), DAG.getRoot()); 8500 DAG.setRoot(OutputChain); 8501 } 8502 8503 SDValue Scale = NumeratorScaled.getValue(1); 8504 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8505 {Fma4, Fma1, Fma3, Scale}, Flags); 8506 8507 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8508 } 8509 8510 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8511 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8512 return FastLowered; 8513 8514 SDLoc SL(Op); 8515 SDValue X = Op.getOperand(0); 8516 SDValue Y = Op.getOperand(1); 8517 8518 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8519 8520 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8521 8522 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8523 8524 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8525 8526 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8527 8528 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8529 8530 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8531 8532 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8533 8534 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8535 8536 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8537 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8538 8539 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8540 NegDivScale0, Mul, DivScale1); 8541 8542 SDValue Scale; 8543 8544 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8545 // Workaround a hardware bug on SI where the condition output from div_scale 8546 // is not usable. 8547 8548 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8549 8550 // Figure out if the scale to use for div_fmas. 8551 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8552 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8553 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8554 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8555 8556 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8557 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8558 8559 SDValue Scale0Hi 8560 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8561 SDValue Scale1Hi 8562 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8563 8564 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8565 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8566 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8567 } else { 8568 Scale = DivScale1.getValue(1); 8569 } 8570 8571 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8572 Fma4, Fma3, Mul, Scale); 8573 8574 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8575 } 8576 8577 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8578 EVT VT = Op.getValueType(); 8579 8580 if (VT == MVT::f32) 8581 return LowerFDIV32(Op, DAG); 8582 8583 if (VT == MVT::f64) 8584 return LowerFDIV64(Op, DAG); 8585 8586 if (VT == MVT::f16) 8587 return LowerFDIV16(Op, DAG); 8588 8589 llvm_unreachable("Unexpected type for fdiv"); 8590 } 8591 8592 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8593 SDLoc DL(Op); 8594 StoreSDNode *Store = cast<StoreSDNode>(Op); 8595 EVT VT = Store->getMemoryVT(); 8596 8597 if (VT == MVT::i1) { 8598 return DAG.getTruncStore(Store->getChain(), DL, 8599 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8600 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8601 } 8602 8603 assert(VT.isVector() && 8604 Store->getValue().getValueType().getScalarType() == MVT::i32); 8605 8606 unsigned AS = Store->getAddressSpace(); 8607 if (Subtarget->hasLDSMisalignedBug() && 8608 AS == AMDGPUAS::FLAT_ADDRESS && 8609 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8610 return SplitVectorStore(Op, DAG); 8611 } 8612 8613 MachineFunction &MF = DAG.getMachineFunction(); 8614 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8615 // If there is a possibilty that flat instruction access scratch memory 8616 // then we need to use the same legalization rules we use for private. 8617 if (AS == AMDGPUAS::FLAT_ADDRESS && 8618 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8619 AS = MFI->hasFlatScratchInit() ? 8620 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8621 8622 unsigned NumElements = VT.getVectorNumElements(); 8623 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8624 AS == AMDGPUAS::FLAT_ADDRESS) { 8625 if (NumElements > 4) 8626 return SplitVectorStore(Op, DAG); 8627 // v3 stores not supported on SI. 8628 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8629 return SplitVectorStore(Op, DAG); 8630 8631 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8632 VT, *Store->getMemOperand())) 8633 return expandUnalignedStore(Store, DAG); 8634 8635 return SDValue(); 8636 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8637 switch (Subtarget->getMaxPrivateElementSize()) { 8638 case 4: 8639 return scalarizeVectorStore(Store, DAG); 8640 case 8: 8641 if (NumElements > 2) 8642 return SplitVectorStore(Op, DAG); 8643 return SDValue(); 8644 case 16: 8645 if (NumElements > 4 || 8646 (NumElements == 3 && !Subtarget->enableFlatScratch())) 8647 return SplitVectorStore(Op, DAG); 8648 return SDValue(); 8649 default: 8650 llvm_unreachable("unsupported private_element_size"); 8651 } 8652 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8653 // Use ds_write_b128 or ds_write_b96 when possible. 8654 if (Subtarget->hasDS96AndDS128() && 8655 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8656 (VT.getStoreSize() == 12)) && 8657 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8658 Store->getAlign())) 8659 return SDValue(); 8660 8661 if (NumElements > 2) 8662 return SplitVectorStore(Op, DAG); 8663 8664 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8665 // address is negative, then the instruction is incorrectly treated as 8666 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8667 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8668 // store later in the SILoadStoreOptimizer. 8669 if (!Subtarget->hasUsableDSOffset() && 8670 NumElements == 2 && VT.getStoreSize() == 8 && 8671 Store->getAlignment() < 8) { 8672 return SplitVectorStore(Op, DAG); 8673 } 8674 8675 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8676 VT, *Store->getMemOperand())) { 8677 if (VT.isVector()) 8678 return SplitVectorStore(Op, DAG); 8679 return expandUnalignedStore(Store, DAG); 8680 } 8681 8682 return SDValue(); 8683 } else { 8684 llvm_unreachable("unhandled address space"); 8685 } 8686 } 8687 8688 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8689 SDLoc DL(Op); 8690 EVT VT = Op.getValueType(); 8691 SDValue Arg = Op.getOperand(0); 8692 SDValue TrigVal; 8693 8694 // Propagate fast-math flags so that the multiply we introduce can be folded 8695 // if Arg is already the result of a multiply by constant. 8696 auto Flags = Op->getFlags(); 8697 8698 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8699 8700 if (Subtarget->hasTrigReducedRange()) { 8701 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8702 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8703 } else { 8704 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8705 } 8706 8707 switch (Op.getOpcode()) { 8708 case ISD::FCOS: 8709 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8710 case ISD::FSIN: 8711 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8712 default: 8713 llvm_unreachable("Wrong trig opcode"); 8714 } 8715 } 8716 8717 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8718 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8719 assert(AtomicNode->isCompareAndSwap()); 8720 unsigned AS = AtomicNode->getAddressSpace(); 8721 8722 // No custom lowering required for local address space 8723 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8724 return Op; 8725 8726 // Non-local address space requires custom lowering for atomic compare 8727 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8728 SDLoc DL(Op); 8729 SDValue ChainIn = Op.getOperand(0); 8730 SDValue Addr = Op.getOperand(1); 8731 SDValue Old = Op.getOperand(2); 8732 SDValue New = Op.getOperand(3); 8733 EVT VT = Op.getValueType(); 8734 MVT SimpleVT = VT.getSimpleVT(); 8735 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8736 8737 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8738 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8739 8740 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8741 Ops, VT, AtomicNode->getMemOperand()); 8742 } 8743 8744 //===----------------------------------------------------------------------===// 8745 // Custom DAG optimizations 8746 //===----------------------------------------------------------------------===// 8747 8748 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8749 DAGCombinerInfo &DCI) const { 8750 EVT VT = N->getValueType(0); 8751 EVT ScalarVT = VT.getScalarType(); 8752 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8753 return SDValue(); 8754 8755 SelectionDAG &DAG = DCI.DAG; 8756 SDLoc DL(N); 8757 8758 SDValue Src = N->getOperand(0); 8759 EVT SrcVT = Src.getValueType(); 8760 8761 // TODO: We could try to match extracting the higher bytes, which would be 8762 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8763 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8764 // about in practice. 8765 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8766 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8767 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8768 DCI.AddToWorklist(Cvt.getNode()); 8769 8770 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8771 if (ScalarVT != MVT::f32) { 8772 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8773 DAG.getTargetConstant(0, DL, MVT::i32)); 8774 } 8775 return Cvt; 8776 } 8777 } 8778 8779 return SDValue(); 8780 } 8781 8782 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8783 8784 // This is a variant of 8785 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8786 // 8787 // The normal DAG combiner will do this, but only if the add has one use since 8788 // that would increase the number of instructions. 8789 // 8790 // This prevents us from seeing a constant offset that can be folded into a 8791 // memory instruction's addressing mode. If we know the resulting add offset of 8792 // a pointer can be folded into an addressing offset, we can replace the pointer 8793 // operand with the add of new constant offset. This eliminates one of the uses, 8794 // and may allow the remaining use to also be simplified. 8795 // 8796 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8797 unsigned AddrSpace, 8798 EVT MemVT, 8799 DAGCombinerInfo &DCI) const { 8800 SDValue N0 = N->getOperand(0); 8801 SDValue N1 = N->getOperand(1); 8802 8803 // We only do this to handle cases where it's profitable when there are 8804 // multiple uses of the add, so defer to the standard combine. 8805 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8806 N0->hasOneUse()) 8807 return SDValue(); 8808 8809 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8810 if (!CN1) 8811 return SDValue(); 8812 8813 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8814 if (!CAdd) 8815 return SDValue(); 8816 8817 // If the resulting offset is too large, we can't fold it into the addressing 8818 // mode offset. 8819 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8820 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8821 8822 AddrMode AM; 8823 AM.HasBaseReg = true; 8824 AM.BaseOffs = Offset.getSExtValue(); 8825 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8826 return SDValue(); 8827 8828 SelectionDAG &DAG = DCI.DAG; 8829 SDLoc SL(N); 8830 EVT VT = N->getValueType(0); 8831 8832 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8833 SDValue COffset = DAG.getConstant(Offset, SL, VT); 8834 8835 SDNodeFlags Flags; 8836 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8837 (N0.getOpcode() == ISD::OR || 8838 N0->getFlags().hasNoUnsignedWrap())); 8839 8840 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8841 } 8842 8843 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 8844 /// by the chain and intrinsic ID. Theoretically we would also need to check the 8845 /// specific intrinsic, but they all place the pointer operand first. 8846 static unsigned getBasePtrIndex(const MemSDNode *N) { 8847 switch (N->getOpcode()) { 8848 case ISD::STORE: 8849 case ISD::INTRINSIC_W_CHAIN: 8850 case ISD::INTRINSIC_VOID: 8851 return 2; 8852 default: 8853 return 1; 8854 } 8855 } 8856 8857 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8858 DAGCombinerInfo &DCI) const { 8859 SelectionDAG &DAG = DCI.DAG; 8860 SDLoc SL(N); 8861 8862 unsigned PtrIdx = getBasePtrIndex(N); 8863 SDValue Ptr = N->getOperand(PtrIdx); 8864 8865 // TODO: We could also do this for multiplies. 8866 if (Ptr.getOpcode() == ISD::SHL) { 8867 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8868 N->getMemoryVT(), DCI); 8869 if (NewPtr) { 8870 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8871 8872 NewOps[PtrIdx] = NewPtr; 8873 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8874 } 8875 } 8876 8877 return SDValue(); 8878 } 8879 8880 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8881 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8882 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8883 (Opc == ISD::XOR && Val == 0); 8884 } 8885 8886 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8887 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8888 // integer combine opportunities since most 64-bit operations are decomposed 8889 // this way. TODO: We won't want this for SALU especially if it is an inline 8890 // immediate. 8891 SDValue SITargetLowering::splitBinaryBitConstantOp( 8892 DAGCombinerInfo &DCI, 8893 const SDLoc &SL, 8894 unsigned Opc, SDValue LHS, 8895 const ConstantSDNode *CRHS) const { 8896 uint64_t Val = CRHS->getZExtValue(); 8897 uint32_t ValLo = Lo_32(Val); 8898 uint32_t ValHi = Hi_32(Val); 8899 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8900 8901 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8902 bitOpWithConstantIsReducible(Opc, ValHi)) || 8903 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8904 // If we need to materialize a 64-bit immediate, it will be split up later 8905 // anyway. Avoid creating the harder to understand 64-bit immediate 8906 // materialization. 8907 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8908 } 8909 8910 return SDValue(); 8911 } 8912 8913 // Returns true if argument is a boolean value which is not serialized into 8914 // memory or argument and does not require v_cndmask_b32 to be deserialized. 8915 static bool isBoolSGPR(SDValue V) { 8916 if (V.getValueType() != MVT::i1) 8917 return false; 8918 switch (V.getOpcode()) { 8919 default: 8920 break; 8921 case ISD::SETCC: 8922 case AMDGPUISD::FP_CLASS: 8923 return true; 8924 case ISD::AND: 8925 case ISD::OR: 8926 case ISD::XOR: 8927 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 8928 } 8929 return false; 8930 } 8931 8932 // If a constant has all zeroes or all ones within each byte return it. 8933 // Otherwise return 0. 8934 static uint32_t getConstantPermuteMask(uint32_t C) { 8935 // 0xff for any zero byte in the mask 8936 uint32_t ZeroByteMask = 0; 8937 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8938 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8939 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8940 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8941 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8942 if ((NonZeroByteMask & C) != NonZeroByteMask) 8943 return 0; // Partial bytes selected. 8944 return C; 8945 } 8946 8947 // Check if a node selects whole bytes from its operand 0 starting at a byte 8948 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8949 // or -1 if not succeeded. 8950 // Note byte select encoding: 8951 // value 0-3 selects corresponding source byte; 8952 // value 0xc selects zero; 8953 // value 0xff selects 0xff. 8954 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8955 assert(V.getValueSizeInBits() == 32); 8956 8957 if (V.getNumOperands() != 2) 8958 return ~0; 8959 8960 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8961 if (!N1) 8962 return ~0; 8963 8964 uint32_t C = N1->getZExtValue(); 8965 8966 switch (V.getOpcode()) { 8967 default: 8968 break; 8969 case ISD::AND: 8970 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8971 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8972 } 8973 break; 8974 8975 case ISD::OR: 8976 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8977 return (0x03020100 & ~ConstMask) | ConstMask; 8978 } 8979 break; 8980 8981 case ISD::SHL: 8982 if (C % 8) 8983 return ~0; 8984 8985 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8986 8987 case ISD::SRL: 8988 if (C % 8) 8989 return ~0; 8990 8991 return uint32_t(0x0c0c0c0c03020100ull >> C); 8992 } 8993 8994 return ~0; 8995 } 8996 8997 SDValue SITargetLowering::performAndCombine(SDNode *N, 8998 DAGCombinerInfo &DCI) const { 8999 if (DCI.isBeforeLegalize()) 9000 return SDValue(); 9001 9002 SelectionDAG &DAG = DCI.DAG; 9003 EVT VT = N->getValueType(0); 9004 SDValue LHS = N->getOperand(0); 9005 SDValue RHS = N->getOperand(1); 9006 9007 9008 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9009 if (VT == MVT::i64 && CRHS) { 9010 if (SDValue Split 9011 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9012 return Split; 9013 } 9014 9015 if (CRHS && VT == MVT::i32) { 9016 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9017 // nb = number of trailing zeroes in mask 9018 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9019 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9020 uint64_t Mask = CRHS->getZExtValue(); 9021 unsigned Bits = countPopulation(Mask); 9022 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9023 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9024 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9025 unsigned Shift = CShift->getZExtValue(); 9026 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9027 unsigned Offset = NB + Shift; 9028 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9029 SDLoc SL(N); 9030 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9031 LHS->getOperand(0), 9032 DAG.getConstant(Offset, SL, MVT::i32), 9033 DAG.getConstant(Bits, SL, MVT::i32)); 9034 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9035 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9036 DAG.getValueType(NarrowVT)); 9037 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9038 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9039 return Shl; 9040 } 9041 } 9042 } 9043 9044 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9045 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9046 isa<ConstantSDNode>(LHS.getOperand(2))) { 9047 uint32_t Sel = getConstantPermuteMask(Mask); 9048 if (!Sel) 9049 return SDValue(); 9050 9051 // Select 0xc for all zero bytes 9052 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9053 SDLoc DL(N); 9054 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9055 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9056 } 9057 } 9058 9059 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9060 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9061 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9062 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9063 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9064 9065 SDValue X = LHS.getOperand(0); 9066 SDValue Y = RHS.getOperand(0); 9067 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9068 return SDValue(); 9069 9070 if (LCC == ISD::SETO) { 9071 if (X != LHS.getOperand(1)) 9072 return SDValue(); 9073 9074 if (RCC == ISD::SETUNE) { 9075 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9076 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9077 return SDValue(); 9078 9079 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9080 SIInstrFlags::N_SUBNORMAL | 9081 SIInstrFlags::N_ZERO | 9082 SIInstrFlags::P_ZERO | 9083 SIInstrFlags::P_SUBNORMAL | 9084 SIInstrFlags::P_NORMAL; 9085 9086 static_assert(((~(SIInstrFlags::S_NAN | 9087 SIInstrFlags::Q_NAN | 9088 SIInstrFlags::N_INFINITY | 9089 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9090 "mask not equal"); 9091 9092 SDLoc DL(N); 9093 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9094 X, DAG.getConstant(Mask, DL, MVT::i32)); 9095 } 9096 } 9097 } 9098 9099 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9100 std::swap(LHS, RHS); 9101 9102 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9103 RHS.hasOneUse()) { 9104 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9105 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9106 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9107 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9108 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9109 (RHS.getOperand(0) == LHS.getOperand(0) && 9110 LHS.getOperand(0) == LHS.getOperand(1))) { 9111 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9112 unsigned NewMask = LCC == ISD::SETO ? 9113 Mask->getZExtValue() & ~OrdMask : 9114 Mask->getZExtValue() & OrdMask; 9115 9116 SDLoc DL(N); 9117 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9118 DAG.getConstant(NewMask, DL, MVT::i32)); 9119 } 9120 } 9121 9122 if (VT == MVT::i32 && 9123 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9124 // and x, (sext cc from i1) => select cc, x, 0 9125 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9126 std::swap(LHS, RHS); 9127 if (isBoolSGPR(RHS.getOperand(0))) 9128 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9129 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9130 } 9131 9132 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9133 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9134 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9135 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9136 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9137 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9138 if (LHSMask != ~0u && RHSMask != ~0u) { 9139 // Canonicalize the expression in an attempt to have fewer unique masks 9140 // and therefore fewer registers used to hold the masks. 9141 if (LHSMask > RHSMask) { 9142 std::swap(LHSMask, RHSMask); 9143 std::swap(LHS, RHS); 9144 } 9145 9146 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9147 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9148 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9149 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9150 9151 // Check of we need to combine values from two sources within a byte. 9152 if (!(LHSUsedLanes & RHSUsedLanes) && 9153 // If we select high and lower word keep it for SDWA. 9154 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9155 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9156 // Each byte in each mask is either selector mask 0-3, or has higher 9157 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9158 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9159 // mask which is not 0xff wins. By anding both masks we have a correct 9160 // result except that 0x0c shall be corrected to give 0x0c only. 9161 uint32_t Mask = LHSMask & RHSMask; 9162 for (unsigned I = 0; I < 32; I += 8) { 9163 uint32_t ByteSel = 0xff << I; 9164 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9165 Mask &= (0x0c << I) & 0xffffffff; 9166 } 9167 9168 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9169 // or 0x0c. 9170 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9171 SDLoc DL(N); 9172 9173 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9174 LHS.getOperand(0), RHS.getOperand(0), 9175 DAG.getConstant(Sel, DL, MVT::i32)); 9176 } 9177 } 9178 } 9179 9180 return SDValue(); 9181 } 9182 9183 SDValue SITargetLowering::performOrCombine(SDNode *N, 9184 DAGCombinerInfo &DCI) const { 9185 SelectionDAG &DAG = DCI.DAG; 9186 SDValue LHS = N->getOperand(0); 9187 SDValue RHS = N->getOperand(1); 9188 9189 EVT VT = N->getValueType(0); 9190 if (VT == MVT::i1) { 9191 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9192 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9193 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9194 SDValue Src = LHS.getOperand(0); 9195 if (Src != RHS.getOperand(0)) 9196 return SDValue(); 9197 9198 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9199 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9200 if (!CLHS || !CRHS) 9201 return SDValue(); 9202 9203 // Only 10 bits are used. 9204 static const uint32_t MaxMask = 0x3ff; 9205 9206 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9207 SDLoc DL(N); 9208 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9209 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9210 } 9211 9212 return SDValue(); 9213 } 9214 9215 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9216 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9217 LHS.getOpcode() == AMDGPUISD::PERM && 9218 isa<ConstantSDNode>(LHS.getOperand(2))) { 9219 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9220 if (!Sel) 9221 return SDValue(); 9222 9223 Sel |= LHS.getConstantOperandVal(2); 9224 SDLoc DL(N); 9225 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9226 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9227 } 9228 9229 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9230 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9231 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9232 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9233 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9234 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9235 if (LHSMask != ~0u && RHSMask != ~0u) { 9236 // Canonicalize the expression in an attempt to have fewer unique masks 9237 // and therefore fewer registers used to hold the masks. 9238 if (LHSMask > RHSMask) { 9239 std::swap(LHSMask, RHSMask); 9240 std::swap(LHS, RHS); 9241 } 9242 9243 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9244 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9245 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9246 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9247 9248 // Check of we need to combine values from two sources within a byte. 9249 if (!(LHSUsedLanes & RHSUsedLanes) && 9250 // If we select high and lower word keep it for SDWA. 9251 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9252 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9253 // Kill zero bytes selected by other mask. Zero value is 0xc. 9254 LHSMask &= ~RHSUsedLanes; 9255 RHSMask &= ~LHSUsedLanes; 9256 // Add 4 to each active LHS lane 9257 LHSMask |= LHSUsedLanes & 0x04040404; 9258 // Combine masks 9259 uint32_t Sel = LHSMask | RHSMask; 9260 SDLoc DL(N); 9261 9262 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9263 LHS.getOperand(0), RHS.getOperand(0), 9264 DAG.getConstant(Sel, DL, MVT::i32)); 9265 } 9266 } 9267 } 9268 9269 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9270 return SDValue(); 9271 9272 // TODO: This could be a generic combine with a predicate for extracting the 9273 // high half of an integer being free. 9274 9275 // (or i64:x, (zero_extend i32:y)) -> 9276 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9277 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9278 RHS.getOpcode() != ISD::ZERO_EXTEND) 9279 std::swap(LHS, RHS); 9280 9281 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9282 SDValue ExtSrc = RHS.getOperand(0); 9283 EVT SrcVT = ExtSrc.getValueType(); 9284 if (SrcVT == MVT::i32) { 9285 SDLoc SL(N); 9286 SDValue LowLHS, HiBits; 9287 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9288 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9289 9290 DCI.AddToWorklist(LowOr.getNode()); 9291 DCI.AddToWorklist(HiBits.getNode()); 9292 9293 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9294 LowOr, HiBits); 9295 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9296 } 9297 } 9298 9299 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9300 if (CRHS) { 9301 if (SDValue Split 9302 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9303 return Split; 9304 } 9305 9306 return SDValue(); 9307 } 9308 9309 SDValue SITargetLowering::performXorCombine(SDNode *N, 9310 DAGCombinerInfo &DCI) const { 9311 EVT VT = N->getValueType(0); 9312 if (VT != MVT::i64) 9313 return SDValue(); 9314 9315 SDValue LHS = N->getOperand(0); 9316 SDValue RHS = N->getOperand(1); 9317 9318 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9319 if (CRHS) { 9320 if (SDValue Split 9321 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9322 return Split; 9323 } 9324 9325 return SDValue(); 9326 } 9327 9328 // Instructions that will be lowered with a final instruction that zeros the 9329 // high result bits. 9330 // XXX - probably only need to list legal operations. 9331 static bool fp16SrcZerosHighBits(unsigned Opc) { 9332 switch (Opc) { 9333 case ISD::FADD: 9334 case ISD::FSUB: 9335 case ISD::FMUL: 9336 case ISD::FDIV: 9337 case ISD::FREM: 9338 case ISD::FMA: 9339 case ISD::FMAD: 9340 case ISD::FCANONICALIZE: 9341 case ISD::FP_ROUND: 9342 case ISD::UINT_TO_FP: 9343 case ISD::SINT_TO_FP: 9344 case ISD::FABS: 9345 // Fabs is lowered to a bit operation, but it's an and which will clear the 9346 // high bits anyway. 9347 case ISD::FSQRT: 9348 case ISD::FSIN: 9349 case ISD::FCOS: 9350 case ISD::FPOWI: 9351 case ISD::FPOW: 9352 case ISD::FLOG: 9353 case ISD::FLOG2: 9354 case ISD::FLOG10: 9355 case ISD::FEXP: 9356 case ISD::FEXP2: 9357 case ISD::FCEIL: 9358 case ISD::FTRUNC: 9359 case ISD::FRINT: 9360 case ISD::FNEARBYINT: 9361 case ISD::FROUND: 9362 case ISD::FFLOOR: 9363 case ISD::FMINNUM: 9364 case ISD::FMAXNUM: 9365 case AMDGPUISD::FRACT: 9366 case AMDGPUISD::CLAMP: 9367 case AMDGPUISD::COS_HW: 9368 case AMDGPUISD::SIN_HW: 9369 case AMDGPUISD::FMIN3: 9370 case AMDGPUISD::FMAX3: 9371 case AMDGPUISD::FMED3: 9372 case AMDGPUISD::FMAD_FTZ: 9373 case AMDGPUISD::RCP: 9374 case AMDGPUISD::RSQ: 9375 case AMDGPUISD::RCP_IFLAG: 9376 case AMDGPUISD::LDEXP: 9377 return true; 9378 default: 9379 // fcopysign, select and others may be lowered to 32-bit bit operations 9380 // which don't zero the high bits. 9381 return false; 9382 } 9383 } 9384 9385 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9386 DAGCombinerInfo &DCI) const { 9387 if (!Subtarget->has16BitInsts() || 9388 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9389 return SDValue(); 9390 9391 EVT VT = N->getValueType(0); 9392 if (VT != MVT::i32) 9393 return SDValue(); 9394 9395 SDValue Src = N->getOperand(0); 9396 if (Src.getValueType() != MVT::i16) 9397 return SDValue(); 9398 9399 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9400 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9401 if (Src.getOpcode() == ISD::BITCAST) { 9402 SDValue BCSrc = Src.getOperand(0); 9403 if (BCSrc.getValueType() == MVT::f16 && 9404 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9405 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9406 } 9407 9408 return SDValue(); 9409 } 9410 9411 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9412 DAGCombinerInfo &DCI) 9413 const { 9414 SDValue Src = N->getOperand(0); 9415 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9416 9417 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9418 VTSign->getVT() == MVT::i8) || 9419 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9420 VTSign->getVT() == MVT::i16)) && 9421 Src.hasOneUse()) { 9422 auto *M = cast<MemSDNode>(Src); 9423 SDValue Ops[] = { 9424 Src.getOperand(0), // Chain 9425 Src.getOperand(1), // rsrc 9426 Src.getOperand(2), // vindex 9427 Src.getOperand(3), // voffset 9428 Src.getOperand(4), // soffset 9429 Src.getOperand(5), // offset 9430 Src.getOperand(6), 9431 Src.getOperand(7) 9432 }; 9433 // replace with BUFFER_LOAD_BYTE/SHORT 9434 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9435 Src.getOperand(0).getValueType()); 9436 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9437 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9438 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9439 ResList, 9440 Ops, M->getMemoryVT(), 9441 M->getMemOperand()); 9442 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9443 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9444 } 9445 return SDValue(); 9446 } 9447 9448 SDValue SITargetLowering::performClassCombine(SDNode *N, 9449 DAGCombinerInfo &DCI) const { 9450 SelectionDAG &DAG = DCI.DAG; 9451 SDValue Mask = N->getOperand(1); 9452 9453 // fp_class x, 0 -> false 9454 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9455 if (CMask->isNullValue()) 9456 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9457 } 9458 9459 if (N->getOperand(0).isUndef()) 9460 return DAG.getUNDEF(MVT::i1); 9461 9462 return SDValue(); 9463 } 9464 9465 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9466 DAGCombinerInfo &DCI) const { 9467 EVT VT = N->getValueType(0); 9468 SDValue N0 = N->getOperand(0); 9469 9470 if (N0.isUndef()) 9471 return N0; 9472 9473 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9474 N0.getOpcode() == ISD::SINT_TO_FP)) { 9475 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9476 N->getFlags()); 9477 } 9478 9479 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9480 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9481 N0.getOperand(0), N->getFlags()); 9482 } 9483 9484 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9485 } 9486 9487 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9488 unsigned MaxDepth) const { 9489 unsigned Opcode = Op.getOpcode(); 9490 if (Opcode == ISD::FCANONICALIZE) 9491 return true; 9492 9493 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9494 auto F = CFP->getValueAPF(); 9495 if (F.isNaN() && F.isSignaling()) 9496 return false; 9497 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9498 } 9499 9500 // If source is a result of another standard FP operation it is already in 9501 // canonical form. 9502 if (MaxDepth == 0) 9503 return false; 9504 9505 switch (Opcode) { 9506 // These will flush denorms if required. 9507 case ISD::FADD: 9508 case ISD::FSUB: 9509 case ISD::FMUL: 9510 case ISD::FCEIL: 9511 case ISD::FFLOOR: 9512 case ISD::FMA: 9513 case ISD::FMAD: 9514 case ISD::FSQRT: 9515 case ISD::FDIV: 9516 case ISD::FREM: 9517 case ISD::FP_ROUND: 9518 case ISD::FP_EXTEND: 9519 case AMDGPUISD::FMUL_LEGACY: 9520 case AMDGPUISD::FMAD_FTZ: 9521 case AMDGPUISD::RCP: 9522 case AMDGPUISD::RSQ: 9523 case AMDGPUISD::RSQ_CLAMP: 9524 case AMDGPUISD::RCP_LEGACY: 9525 case AMDGPUISD::RCP_IFLAG: 9526 case AMDGPUISD::DIV_SCALE: 9527 case AMDGPUISD::DIV_FMAS: 9528 case AMDGPUISD::DIV_FIXUP: 9529 case AMDGPUISD::FRACT: 9530 case AMDGPUISD::LDEXP: 9531 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9532 case AMDGPUISD::CVT_F32_UBYTE0: 9533 case AMDGPUISD::CVT_F32_UBYTE1: 9534 case AMDGPUISD::CVT_F32_UBYTE2: 9535 case AMDGPUISD::CVT_F32_UBYTE3: 9536 return true; 9537 9538 // It can/will be lowered or combined as a bit operation. 9539 // Need to check their input recursively to handle. 9540 case ISD::FNEG: 9541 case ISD::FABS: 9542 case ISD::FCOPYSIGN: 9543 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9544 9545 case ISD::FSIN: 9546 case ISD::FCOS: 9547 case ISD::FSINCOS: 9548 return Op.getValueType().getScalarType() != MVT::f16; 9549 9550 case ISD::FMINNUM: 9551 case ISD::FMAXNUM: 9552 case ISD::FMINNUM_IEEE: 9553 case ISD::FMAXNUM_IEEE: 9554 case AMDGPUISD::CLAMP: 9555 case AMDGPUISD::FMED3: 9556 case AMDGPUISD::FMAX3: 9557 case AMDGPUISD::FMIN3: { 9558 // FIXME: Shouldn't treat the generic operations different based these. 9559 // However, we aren't really required to flush the result from 9560 // minnum/maxnum.. 9561 9562 // snans will be quieted, so we only need to worry about denormals. 9563 if (Subtarget->supportsMinMaxDenormModes() || 9564 denormalsEnabledForType(DAG, Op.getValueType())) 9565 return true; 9566 9567 // Flushing may be required. 9568 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9569 // targets need to check their input recursively. 9570 9571 // FIXME: Does this apply with clamp? It's implemented with max. 9572 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9573 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9574 return false; 9575 } 9576 9577 return true; 9578 } 9579 case ISD::SELECT: { 9580 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9581 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9582 } 9583 case ISD::BUILD_VECTOR: { 9584 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9585 SDValue SrcOp = Op.getOperand(i); 9586 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9587 return false; 9588 } 9589 9590 return true; 9591 } 9592 case ISD::EXTRACT_VECTOR_ELT: 9593 case ISD::EXTRACT_SUBVECTOR: { 9594 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9595 } 9596 case ISD::INSERT_VECTOR_ELT: { 9597 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9598 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9599 } 9600 case ISD::UNDEF: 9601 // Could be anything. 9602 return false; 9603 9604 case ISD::BITCAST: { 9605 // Hack round the mess we make when legalizing extract_vector_elt 9606 SDValue Src = Op.getOperand(0); 9607 if (Src.getValueType() == MVT::i16 && 9608 Src.getOpcode() == ISD::TRUNCATE) { 9609 SDValue TruncSrc = Src.getOperand(0); 9610 if (TruncSrc.getValueType() == MVT::i32 && 9611 TruncSrc.getOpcode() == ISD::BITCAST && 9612 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9613 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9614 } 9615 } 9616 9617 return false; 9618 } 9619 case ISD::INTRINSIC_WO_CHAIN: { 9620 unsigned IntrinsicID 9621 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9622 // TODO: Handle more intrinsics 9623 switch (IntrinsicID) { 9624 case Intrinsic::amdgcn_cvt_pkrtz: 9625 case Intrinsic::amdgcn_cubeid: 9626 case Intrinsic::amdgcn_frexp_mant: 9627 case Intrinsic::amdgcn_fdot2: 9628 case Intrinsic::amdgcn_rcp: 9629 case Intrinsic::amdgcn_rsq: 9630 case Intrinsic::amdgcn_rsq_clamp: 9631 case Intrinsic::amdgcn_rcp_legacy: 9632 case Intrinsic::amdgcn_rsq_legacy: 9633 case Intrinsic::amdgcn_trig_preop: 9634 return true; 9635 default: 9636 break; 9637 } 9638 9639 LLVM_FALLTHROUGH; 9640 } 9641 default: 9642 return denormalsEnabledForType(DAG, Op.getValueType()) && 9643 DAG.isKnownNeverSNaN(Op); 9644 } 9645 9646 llvm_unreachable("invalid operation"); 9647 } 9648 9649 // Constant fold canonicalize. 9650 SDValue SITargetLowering::getCanonicalConstantFP( 9651 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9652 // Flush denormals to 0 if not enabled. 9653 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9654 return DAG.getConstantFP(0.0, SL, VT); 9655 9656 if (C.isNaN()) { 9657 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9658 if (C.isSignaling()) { 9659 // Quiet a signaling NaN. 9660 // FIXME: Is this supposed to preserve payload bits? 9661 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9662 } 9663 9664 // Make sure it is the canonical NaN bitpattern. 9665 // 9666 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9667 // immediate? 9668 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9669 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9670 } 9671 9672 // Already canonical. 9673 return DAG.getConstantFP(C, SL, VT); 9674 } 9675 9676 static bool vectorEltWillFoldAway(SDValue Op) { 9677 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9678 } 9679 9680 SDValue SITargetLowering::performFCanonicalizeCombine( 9681 SDNode *N, 9682 DAGCombinerInfo &DCI) const { 9683 SelectionDAG &DAG = DCI.DAG; 9684 SDValue N0 = N->getOperand(0); 9685 EVT VT = N->getValueType(0); 9686 9687 // fcanonicalize undef -> qnan 9688 if (N0.isUndef()) { 9689 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9690 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9691 } 9692 9693 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9694 EVT VT = N->getValueType(0); 9695 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9696 } 9697 9698 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9699 // (fcanonicalize k) 9700 // 9701 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9702 9703 // TODO: This could be better with wider vectors that will be split to v2f16, 9704 // and to consider uses since there aren't that many packed operations. 9705 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9706 isTypeLegal(MVT::v2f16)) { 9707 SDLoc SL(N); 9708 SDValue NewElts[2]; 9709 SDValue Lo = N0.getOperand(0); 9710 SDValue Hi = N0.getOperand(1); 9711 EVT EltVT = Lo.getValueType(); 9712 9713 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9714 for (unsigned I = 0; I != 2; ++I) { 9715 SDValue Op = N0.getOperand(I); 9716 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9717 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9718 CFP->getValueAPF()); 9719 } else if (Op.isUndef()) { 9720 // Handled below based on what the other operand is. 9721 NewElts[I] = Op; 9722 } else { 9723 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9724 } 9725 } 9726 9727 // If one half is undef, and one is constant, perfer a splat vector rather 9728 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9729 // cheaper to use and may be free with a packed operation. 9730 if (NewElts[0].isUndef()) { 9731 if (isa<ConstantFPSDNode>(NewElts[1])) 9732 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9733 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9734 } 9735 9736 if (NewElts[1].isUndef()) { 9737 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9738 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9739 } 9740 9741 return DAG.getBuildVector(VT, SL, NewElts); 9742 } 9743 } 9744 9745 unsigned SrcOpc = N0.getOpcode(); 9746 9747 // If it's free to do so, push canonicalizes further up the source, which may 9748 // find a canonical source. 9749 // 9750 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9751 // sNaNs. 9752 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9753 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9754 if (CRHS && N0.hasOneUse()) { 9755 SDLoc SL(N); 9756 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9757 N0.getOperand(0)); 9758 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9759 DCI.AddToWorklist(Canon0.getNode()); 9760 9761 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9762 } 9763 } 9764 9765 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9766 } 9767 9768 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9769 switch (Opc) { 9770 case ISD::FMAXNUM: 9771 case ISD::FMAXNUM_IEEE: 9772 return AMDGPUISD::FMAX3; 9773 case ISD::SMAX: 9774 return AMDGPUISD::SMAX3; 9775 case ISD::UMAX: 9776 return AMDGPUISD::UMAX3; 9777 case ISD::FMINNUM: 9778 case ISD::FMINNUM_IEEE: 9779 return AMDGPUISD::FMIN3; 9780 case ISD::SMIN: 9781 return AMDGPUISD::SMIN3; 9782 case ISD::UMIN: 9783 return AMDGPUISD::UMIN3; 9784 default: 9785 llvm_unreachable("Not a min/max opcode"); 9786 } 9787 } 9788 9789 SDValue SITargetLowering::performIntMed3ImmCombine( 9790 SelectionDAG &DAG, const SDLoc &SL, 9791 SDValue Op0, SDValue Op1, bool Signed) const { 9792 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9793 if (!K1) 9794 return SDValue(); 9795 9796 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9797 if (!K0) 9798 return SDValue(); 9799 9800 if (Signed) { 9801 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9802 return SDValue(); 9803 } else { 9804 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9805 return SDValue(); 9806 } 9807 9808 EVT VT = K0->getValueType(0); 9809 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9810 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9811 return DAG.getNode(Med3Opc, SL, VT, 9812 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9813 } 9814 9815 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9816 if (VT == MVT::i16) { 9817 MVT NVT = MVT::i32; 9818 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9819 9820 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9821 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9822 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9823 9824 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9825 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9826 } 9827 9828 return SDValue(); 9829 } 9830 9831 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9832 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9833 return C; 9834 9835 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9836 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9837 return C; 9838 } 9839 9840 return nullptr; 9841 } 9842 9843 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9844 const SDLoc &SL, 9845 SDValue Op0, 9846 SDValue Op1) const { 9847 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9848 if (!K1) 9849 return SDValue(); 9850 9851 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9852 if (!K0) 9853 return SDValue(); 9854 9855 // Ordered >= (although NaN inputs should have folded away by now). 9856 if (K0->getValueAPF() > K1->getValueAPF()) 9857 return SDValue(); 9858 9859 const MachineFunction &MF = DAG.getMachineFunction(); 9860 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9861 9862 // TODO: Check IEEE bit enabled? 9863 EVT VT = Op0.getValueType(); 9864 if (Info->getMode().DX10Clamp) { 9865 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9866 // hardware fmed3 behavior converting to a min. 9867 // FIXME: Should this be allowing -0.0? 9868 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9869 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9870 } 9871 9872 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9873 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9874 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9875 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9876 // then give the other result, which is different from med3 with a NaN 9877 // input. 9878 SDValue Var = Op0.getOperand(0); 9879 if (!DAG.isKnownNeverSNaN(Var)) 9880 return SDValue(); 9881 9882 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9883 9884 if ((!K0->hasOneUse() || 9885 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9886 (!K1->hasOneUse() || 9887 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9888 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9889 Var, SDValue(K0, 0), SDValue(K1, 0)); 9890 } 9891 } 9892 9893 return SDValue(); 9894 } 9895 9896 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9897 DAGCombinerInfo &DCI) const { 9898 SelectionDAG &DAG = DCI.DAG; 9899 9900 EVT VT = N->getValueType(0); 9901 unsigned Opc = N->getOpcode(); 9902 SDValue Op0 = N->getOperand(0); 9903 SDValue Op1 = N->getOperand(1); 9904 9905 // Only do this if the inner op has one use since this will just increases 9906 // register pressure for no benefit. 9907 9908 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9909 !VT.isVector() && 9910 (VT == MVT::i32 || VT == MVT::f32 || 9911 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9912 // max(max(a, b), c) -> max3(a, b, c) 9913 // min(min(a, b), c) -> min3(a, b, c) 9914 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9915 SDLoc DL(N); 9916 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9917 DL, 9918 N->getValueType(0), 9919 Op0.getOperand(0), 9920 Op0.getOperand(1), 9921 Op1); 9922 } 9923 9924 // Try commuted. 9925 // max(a, max(b, c)) -> max3(a, b, c) 9926 // min(a, min(b, c)) -> min3(a, b, c) 9927 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9928 SDLoc DL(N); 9929 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9930 DL, 9931 N->getValueType(0), 9932 Op0, 9933 Op1.getOperand(0), 9934 Op1.getOperand(1)); 9935 } 9936 } 9937 9938 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9939 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9940 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9941 return Med3; 9942 } 9943 9944 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9945 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9946 return Med3; 9947 } 9948 9949 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9950 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9951 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9952 (Opc == AMDGPUISD::FMIN_LEGACY && 9953 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9954 (VT == MVT::f32 || VT == MVT::f64 || 9955 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9956 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9957 Op0.hasOneUse()) { 9958 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9959 return Res; 9960 } 9961 9962 return SDValue(); 9963 } 9964 9965 static bool isClampZeroToOne(SDValue A, SDValue B) { 9966 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9967 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9968 // FIXME: Should this be allowing -0.0? 9969 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9970 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9971 } 9972 } 9973 9974 return false; 9975 } 9976 9977 // FIXME: Should only worry about snans for version with chain. 9978 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9979 DAGCombinerInfo &DCI) const { 9980 EVT VT = N->getValueType(0); 9981 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9982 // NaNs. With a NaN input, the order of the operands may change the result. 9983 9984 SelectionDAG &DAG = DCI.DAG; 9985 SDLoc SL(N); 9986 9987 SDValue Src0 = N->getOperand(0); 9988 SDValue Src1 = N->getOperand(1); 9989 SDValue Src2 = N->getOperand(2); 9990 9991 if (isClampZeroToOne(Src0, Src1)) { 9992 // const_a, const_b, x -> clamp is safe in all cases including signaling 9993 // nans. 9994 // FIXME: Should this be allowing -0.0? 9995 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9996 } 9997 9998 const MachineFunction &MF = DAG.getMachineFunction(); 9999 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10000 10001 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10002 // handling no dx10-clamp? 10003 if (Info->getMode().DX10Clamp) { 10004 // If NaNs is clamped to 0, we are free to reorder the inputs. 10005 10006 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10007 std::swap(Src0, Src1); 10008 10009 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10010 std::swap(Src1, Src2); 10011 10012 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10013 std::swap(Src0, Src1); 10014 10015 if (isClampZeroToOne(Src1, Src2)) 10016 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10017 } 10018 10019 return SDValue(); 10020 } 10021 10022 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10023 DAGCombinerInfo &DCI) const { 10024 SDValue Src0 = N->getOperand(0); 10025 SDValue Src1 = N->getOperand(1); 10026 if (Src0.isUndef() && Src1.isUndef()) 10027 return DCI.DAG.getUNDEF(N->getValueType(0)); 10028 return SDValue(); 10029 } 10030 10031 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10032 // expanded into a set of cmp/select instructions. 10033 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10034 unsigned NumElem, 10035 bool IsDivergentIdx) { 10036 if (UseDivergentRegisterIndexing) 10037 return false; 10038 10039 unsigned VecSize = EltSize * NumElem; 10040 10041 // Sub-dword vectors of size 2 dword or less have better implementation. 10042 if (VecSize <= 64 && EltSize < 32) 10043 return false; 10044 10045 // Always expand the rest of sub-dword instructions, otherwise it will be 10046 // lowered via memory. 10047 if (EltSize < 32) 10048 return true; 10049 10050 // Always do this if var-idx is divergent, otherwise it will become a loop. 10051 if (IsDivergentIdx) 10052 return true; 10053 10054 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10055 unsigned NumInsts = NumElem /* Number of compares */ + 10056 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10057 return NumInsts <= 16; 10058 } 10059 10060 static bool shouldExpandVectorDynExt(SDNode *N) { 10061 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10062 if (isa<ConstantSDNode>(Idx)) 10063 return false; 10064 10065 SDValue Vec = N->getOperand(0); 10066 EVT VecVT = Vec.getValueType(); 10067 EVT EltVT = VecVT.getVectorElementType(); 10068 unsigned EltSize = EltVT.getSizeInBits(); 10069 unsigned NumElem = VecVT.getVectorNumElements(); 10070 10071 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10072 Idx->isDivergent()); 10073 } 10074 10075 SDValue SITargetLowering::performExtractVectorEltCombine( 10076 SDNode *N, DAGCombinerInfo &DCI) const { 10077 SDValue Vec = N->getOperand(0); 10078 SelectionDAG &DAG = DCI.DAG; 10079 10080 EVT VecVT = Vec.getValueType(); 10081 EVT EltVT = VecVT.getVectorElementType(); 10082 10083 if ((Vec.getOpcode() == ISD::FNEG || 10084 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10085 SDLoc SL(N); 10086 EVT EltVT = N->getValueType(0); 10087 SDValue Idx = N->getOperand(1); 10088 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10089 Vec.getOperand(0), Idx); 10090 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10091 } 10092 10093 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10094 // => 10095 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10096 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10097 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10098 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10099 SDLoc SL(N); 10100 EVT EltVT = N->getValueType(0); 10101 SDValue Idx = N->getOperand(1); 10102 unsigned Opc = Vec.getOpcode(); 10103 10104 switch(Opc) { 10105 default: 10106 break; 10107 // TODO: Support other binary operations. 10108 case ISD::FADD: 10109 case ISD::FSUB: 10110 case ISD::FMUL: 10111 case ISD::ADD: 10112 case ISD::UMIN: 10113 case ISD::UMAX: 10114 case ISD::SMIN: 10115 case ISD::SMAX: 10116 case ISD::FMAXNUM: 10117 case ISD::FMINNUM: 10118 case ISD::FMAXNUM_IEEE: 10119 case ISD::FMINNUM_IEEE: { 10120 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10121 Vec.getOperand(0), Idx); 10122 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10123 Vec.getOperand(1), Idx); 10124 10125 DCI.AddToWorklist(Elt0.getNode()); 10126 DCI.AddToWorklist(Elt1.getNode()); 10127 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10128 } 10129 } 10130 } 10131 10132 unsigned VecSize = VecVT.getSizeInBits(); 10133 unsigned EltSize = EltVT.getSizeInBits(); 10134 10135 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10136 if (::shouldExpandVectorDynExt(N)) { 10137 SDLoc SL(N); 10138 SDValue Idx = N->getOperand(1); 10139 SDValue V; 10140 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10141 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10142 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10143 if (I == 0) 10144 V = Elt; 10145 else 10146 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10147 } 10148 return V; 10149 } 10150 10151 if (!DCI.isBeforeLegalize()) 10152 return SDValue(); 10153 10154 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10155 // elements. This exposes more load reduction opportunities by replacing 10156 // multiple small extract_vector_elements with a single 32-bit extract. 10157 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10158 if (isa<MemSDNode>(Vec) && 10159 EltSize <= 16 && 10160 EltVT.isByteSized() && 10161 VecSize > 32 && 10162 VecSize % 32 == 0 && 10163 Idx) { 10164 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10165 10166 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10167 unsigned EltIdx = BitIndex / 32; 10168 unsigned LeftoverBitIdx = BitIndex % 32; 10169 SDLoc SL(N); 10170 10171 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10172 DCI.AddToWorklist(Cast.getNode()); 10173 10174 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10175 DAG.getConstant(EltIdx, SL, MVT::i32)); 10176 DCI.AddToWorklist(Elt.getNode()); 10177 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10178 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10179 DCI.AddToWorklist(Srl.getNode()); 10180 10181 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10182 DCI.AddToWorklist(Trunc.getNode()); 10183 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10184 } 10185 10186 return SDValue(); 10187 } 10188 10189 SDValue 10190 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10191 DAGCombinerInfo &DCI) const { 10192 SDValue Vec = N->getOperand(0); 10193 SDValue Idx = N->getOperand(2); 10194 EVT VecVT = Vec.getValueType(); 10195 EVT EltVT = VecVT.getVectorElementType(); 10196 10197 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10198 // => BUILD_VECTOR n x select (e, const-idx) 10199 if (!::shouldExpandVectorDynExt(N)) 10200 return SDValue(); 10201 10202 SelectionDAG &DAG = DCI.DAG; 10203 SDLoc SL(N); 10204 SDValue Ins = N->getOperand(1); 10205 EVT IdxVT = Idx.getValueType(); 10206 10207 SmallVector<SDValue, 16> Ops; 10208 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10209 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10210 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10211 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10212 Ops.push_back(V); 10213 } 10214 10215 return DAG.getBuildVector(VecVT, SL, Ops); 10216 } 10217 10218 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10219 const SDNode *N0, 10220 const SDNode *N1) const { 10221 EVT VT = N0->getValueType(0); 10222 10223 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10224 // support denormals ever. 10225 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10226 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10227 getSubtarget()->hasMadF16())) && 10228 isOperationLegal(ISD::FMAD, VT)) 10229 return ISD::FMAD; 10230 10231 const TargetOptions &Options = DAG.getTarget().Options; 10232 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10233 (N0->getFlags().hasAllowContract() && 10234 N1->getFlags().hasAllowContract())) && 10235 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10236 return ISD::FMA; 10237 } 10238 10239 return 0; 10240 } 10241 10242 // For a reassociatable opcode perform: 10243 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10244 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10245 SelectionDAG &DAG) const { 10246 EVT VT = N->getValueType(0); 10247 if (VT != MVT::i32 && VT != MVT::i64) 10248 return SDValue(); 10249 10250 unsigned Opc = N->getOpcode(); 10251 SDValue Op0 = N->getOperand(0); 10252 SDValue Op1 = N->getOperand(1); 10253 10254 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10255 return SDValue(); 10256 10257 if (Op0->isDivergent()) 10258 std::swap(Op0, Op1); 10259 10260 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10261 return SDValue(); 10262 10263 SDValue Op2 = Op1.getOperand(1); 10264 Op1 = Op1.getOperand(0); 10265 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10266 return SDValue(); 10267 10268 if (Op1->isDivergent()) 10269 std::swap(Op1, Op2); 10270 10271 // If either operand is constant this will conflict with 10272 // DAGCombiner::ReassociateOps(). 10273 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10274 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10275 return SDValue(); 10276 10277 SDLoc SL(N); 10278 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10279 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10280 } 10281 10282 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10283 EVT VT, 10284 SDValue N0, SDValue N1, SDValue N2, 10285 bool Signed) { 10286 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10287 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10288 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10289 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10290 } 10291 10292 SDValue SITargetLowering::performAddCombine(SDNode *N, 10293 DAGCombinerInfo &DCI) const { 10294 SelectionDAG &DAG = DCI.DAG; 10295 EVT VT = N->getValueType(0); 10296 SDLoc SL(N); 10297 SDValue LHS = N->getOperand(0); 10298 SDValue RHS = N->getOperand(1); 10299 10300 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10301 && Subtarget->hasMad64_32() && 10302 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10303 VT.getScalarSizeInBits() <= 64) { 10304 if (LHS.getOpcode() != ISD::MUL) 10305 std::swap(LHS, RHS); 10306 10307 SDValue MulLHS = LHS.getOperand(0); 10308 SDValue MulRHS = LHS.getOperand(1); 10309 SDValue AddRHS = RHS; 10310 10311 // TODO: Maybe restrict if SGPR inputs. 10312 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10313 numBitsUnsigned(MulRHS, DAG) <= 32) { 10314 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10315 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10316 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10317 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10318 } 10319 10320 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10321 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10322 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10323 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10324 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10325 } 10326 10327 return SDValue(); 10328 } 10329 10330 if (SDValue V = reassociateScalarOps(N, DAG)) { 10331 return V; 10332 } 10333 10334 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10335 return SDValue(); 10336 10337 // add x, zext (setcc) => addcarry x, 0, setcc 10338 // add x, sext (setcc) => subcarry x, 0, setcc 10339 unsigned Opc = LHS.getOpcode(); 10340 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10341 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10342 std::swap(RHS, LHS); 10343 10344 Opc = RHS.getOpcode(); 10345 switch (Opc) { 10346 default: break; 10347 case ISD::ZERO_EXTEND: 10348 case ISD::SIGN_EXTEND: 10349 case ISD::ANY_EXTEND: { 10350 auto Cond = RHS.getOperand(0); 10351 // If this won't be a real VOPC output, we would still need to insert an 10352 // extra instruction anyway. 10353 if (!isBoolSGPR(Cond)) 10354 break; 10355 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10356 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10357 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10358 return DAG.getNode(Opc, SL, VTList, Args); 10359 } 10360 case ISD::ADDCARRY: { 10361 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10362 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10363 if (!C || C->getZExtValue() != 0) break; 10364 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10365 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10366 } 10367 } 10368 return SDValue(); 10369 } 10370 10371 SDValue SITargetLowering::performSubCombine(SDNode *N, 10372 DAGCombinerInfo &DCI) const { 10373 SelectionDAG &DAG = DCI.DAG; 10374 EVT VT = N->getValueType(0); 10375 10376 if (VT != MVT::i32) 10377 return SDValue(); 10378 10379 SDLoc SL(N); 10380 SDValue LHS = N->getOperand(0); 10381 SDValue RHS = N->getOperand(1); 10382 10383 // sub x, zext (setcc) => subcarry x, 0, setcc 10384 // sub x, sext (setcc) => addcarry x, 0, setcc 10385 unsigned Opc = RHS.getOpcode(); 10386 switch (Opc) { 10387 default: break; 10388 case ISD::ZERO_EXTEND: 10389 case ISD::SIGN_EXTEND: 10390 case ISD::ANY_EXTEND: { 10391 auto Cond = RHS.getOperand(0); 10392 // If this won't be a real VOPC output, we would still need to insert an 10393 // extra instruction anyway. 10394 if (!isBoolSGPR(Cond)) 10395 break; 10396 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10397 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10398 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10399 return DAG.getNode(Opc, SL, VTList, Args); 10400 } 10401 } 10402 10403 if (LHS.getOpcode() == ISD::SUBCARRY) { 10404 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10405 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10406 if (!C || !C->isNullValue()) 10407 return SDValue(); 10408 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10409 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10410 } 10411 return SDValue(); 10412 } 10413 10414 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10415 DAGCombinerInfo &DCI) const { 10416 10417 if (N->getValueType(0) != MVT::i32) 10418 return SDValue(); 10419 10420 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10421 if (!C || C->getZExtValue() != 0) 10422 return SDValue(); 10423 10424 SelectionDAG &DAG = DCI.DAG; 10425 SDValue LHS = N->getOperand(0); 10426 10427 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10428 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10429 unsigned LHSOpc = LHS.getOpcode(); 10430 unsigned Opc = N->getOpcode(); 10431 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10432 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10433 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10434 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10435 } 10436 return SDValue(); 10437 } 10438 10439 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10440 DAGCombinerInfo &DCI) const { 10441 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10442 return SDValue(); 10443 10444 SelectionDAG &DAG = DCI.DAG; 10445 EVT VT = N->getValueType(0); 10446 10447 SDLoc SL(N); 10448 SDValue LHS = N->getOperand(0); 10449 SDValue RHS = N->getOperand(1); 10450 10451 // These should really be instruction patterns, but writing patterns with 10452 // source modiifiers is a pain. 10453 10454 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10455 if (LHS.getOpcode() == ISD::FADD) { 10456 SDValue A = LHS.getOperand(0); 10457 if (A == LHS.getOperand(1)) { 10458 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10459 if (FusedOp != 0) { 10460 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10461 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10462 } 10463 } 10464 } 10465 10466 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10467 if (RHS.getOpcode() == ISD::FADD) { 10468 SDValue A = RHS.getOperand(0); 10469 if (A == RHS.getOperand(1)) { 10470 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10471 if (FusedOp != 0) { 10472 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10473 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10474 } 10475 } 10476 } 10477 10478 return SDValue(); 10479 } 10480 10481 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10482 DAGCombinerInfo &DCI) const { 10483 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10484 return SDValue(); 10485 10486 SelectionDAG &DAG = DCI.DAG; 10487 SDLoc SL(N); 10488 EVT VT = N->getValueType(0); 10489 assert(!VT.isVector()); 10490 10491 // Try to get the fneg to fold into the source modifier. This undoes generic 10492 // DAG combines and folds them into the mad. 10493 // 10494 // Only do this if we are not trying to support denormals. v_mad_f32 does 10495 // not support denormals ever. 10496 SDValue LHS = N->getOperand(0); 10497 SDValue RHS = N->getOperand(1); 10498 if (LHS.getOpcode() == ISD::FADD) { 10499 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10500 SDValue A = LHS.getOperand(0); 10501 if (A == LHS.getOperand(1)) { 10502 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10503 if (FusedOp != 0){ 10504 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10505 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10506 10507 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10508 } 10509 } 10510 } 10511 10512 if (RHS.getOpcode() == ISD::FADD) { 10513 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10514 10515 SDValue A = RHS.getOperand(0); 10516 if (A == RHS.getOperand(1)) { 10517 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10518 if (FusedOp != 0){ 10519 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10520 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10521 } 10522 } 10523 } 10524 10525 return SDValue(); 10526 } 10527 10528 SDValue SITargetLowering::performFMACombine(SDNode *N, 10529 DAGCombinerInfo &DCI) const { 10530 SelectionDAG &DAG = DCI.DAG; 10531 EVT VT = N->getValueType(0); 10532 SDLoc SL(N); 10533 10534 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 10535 return SDValue(); 10536 10537 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10538 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10539 SDValue Op1 = N->getOperand(0); 10540 SDValue Op2 = N->getOperand(1); 10541 SDValue FMA = N->getOperand(2); 10542 10543 if (FMA.getOpcode() != ISD::FMA || 10544 Op1.getOpcode() != ISD::FP_EXTEND || 10545 Op2.getOpcode() != ISD::FP_EXTEND) 10546 return SDValue(); 10547 10548 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10549 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10550 // is sufficient to allow generaing fdot2. 10551 const TargetOptions &Options = DAG.getTarget().Options; 10552 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10553 (N->getFlags().hasAllowContract() && 10554 FMA->getFlags().hasAllowContract())) { 10555 Op1 = Op1.getOperand(0); 10556 Op2 = Op2.getOperand(0); 10557 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10558 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10559 return SDValue(); 10560 10561 SDValue Vec1 = Op1.getOperand(0); 10562 SDValue Idx1 = Op1.getOperand(1); 10563 SDValue Vec2 = Op2.getOperand(0); 10564 10565 SDValue FMAOp1 = FMA.getOperand(0); 10566 SDValue FMAOp2 = FMA.getOperand(1); 10567 SDValue FMAAcc = FMA.getOperand(2); 10568 10569 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10570 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10571 return SDValue(); 10572 10573 FMAOp1 = FMAOp1.getOperand(0); 10574 FMAOp2 = FMAOp2.getOperand(0); 10575 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10576 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10577 return SDValue(); 10578 10579 SDValue Vec3 = FMAOp1.getOperand(0); 10580 SDValue Vec4 = FMAOp2.getOperand(0); 10581 SDValue Idx2 = FMAOp1.getOperand(1); 10582 10583 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10584 // Idx1 and Idx2 cannot be the same. 10585 Idx1 == Idx2) 10586 return SDValue(); 10587 10588 if (Vec1 == Vec2 || Vec3 == Vec4) 10589 return SDValue(); 10590 10591 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10592 return SDValue(); 10593 10594 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10595 (Vec1 == Vec4 && Vec2 == Vec3)) { 10596 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10597 DAG.getTargetConstant(0, SL, MVT::i1)); 10598 } 10599 } 10600 return SDValue(); 10601 } 10602 10603 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10604 DAGCombinerInfo &DCI) const { 10605 SelectionDAG &DAG = DCI.DAG; 10606 SDLoc SL(N); 10607 10608 SDValue LHS = N->getOperand(0); 10609 SDValue RHS = N->getOperand(1); 10610 EVT VT = LHS.getValueType(); 10611 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10612 10613 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10614 if (!CRHS) { 10615 CRHS = dyn_cast<ConstantSDNode>(LHS); 10616 if (CRHS) { 10617 std::swap(LHS, RHS); 10618 CC = getSetCCSwappedOperands(CC); 10619 } 10620 } 10621 10622 if (CRHS) { 10623 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10624 isBoolSGPR(LHS.getOperand(0))) { 10625 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10626 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10627 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10628 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10629 if ((CRHS->isAllOnesValue() && 10630 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10631 (CRHS->isNullValue() && 10632 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10633 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10634 DAG.getConstant(-1, SL, MVT::i1)); 10635 if ((CRHS->isAllOnesValue() && 10636 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10637 (CRHS->isNullValue() && 10638 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10639 return LHS.getOperand(0); 10640 } 10641 10642 uint64_t CRHSVal = CRHS->getZExtValue(); 10643 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10644 LHS.getOpcode() == ISD::SELECT && 10645 isa<ConstantSDNode>(LHS.getOperand(1)) && 10646 isa<ConstantSDNode>(LHS.getOperand(2)) && 10647 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10648 isBoolSGPR(LHS.getOperand(0))) { 10649 // Given CT != FT: 10650 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10651 // setcc (select cc, CT, CF), CF, ne => cc 10652 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10653 // setcc (select cc, CT, CF), CT, eq => cc 10654 uint64_t CT = LHS.getConstantOperandVal(1); 10655 uint64_t CF = LHS.getConstantOperandVal(2); 10656 10657 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10658 (CT == CRHSVal && CC == ISD::SETNE)) 10659 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10660 DAG.getConstant(-1, SL, MVT::i1)); 10661 if ((CF == CRHSVal && CC == ISD::SETNE) || 10662 (CT == CRHSVal && CC == ISD::SETEQ)) 10663 return LHS.getOperand(0); 10664 } 10665 } 10666 10667 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10668 VT != MVT::f16)) 10669 return SDValue(); 10670 10671 // Match isinf/isfinite pattern 10672 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10673 // (fcmp one (fabs x), inf) -> (fp_class x, 10674 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10675 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10676 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10677 if (!CRHS) 10678 return SDValue(); 10679 10680 const APFloat &APF = CRHS->getValueAPF(); 10681 if (APF.isInfinity() && !APF.isNegative()) { 10682 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10683 SIInstrFlags::N_INFINITY; 10684 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10685 SIInstrFlags::P_ZERO | 10686 SIInstrFlags::N_NORMAL | 10687 SIInstrFlags::P_NORMAL | 10688 SIInstrFlags::N_SUBNORMAL | 10689 SIInstrFlags::P_SUBNORMAL; 10690 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10691 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10692 DAG.getConstant(Mask, SL, MVT::i32)); 10693 } 10694 } 10695 10696 return SDValue(); 10697 } 10698 10699 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10700 DAGCombinerInfo &DCI) const { 10701 SelectionDAG &DAG = DCI.DAG; 10702 SDLoc SL(N); 10703 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10704 10705 SDValue Src = N->getOperand(0); 10706 SDValue Shift = N->getOperand(0); 10707 10708 // TODO: Extend type shouldn't matter (assuming legal types). 10709 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10710 Shift = Shift.getOperand(0); 10711 10712 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10713 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10714 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10715 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10716 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10717 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10718 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10719 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10720 SDLoc(Shift.getOperand(0)), MVT::i32); 10721 10722 unsigned ShiftOffset = 8 * Offset; 10723 if (Shift.getOpcode() == ISD::SHL) 10724 ShiftOffset -= C->getZExtValue(); 10725 else 10726 ShiftOffset += C->getZExtValue(); 10727 10728 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10729 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10730 MVT::f32, Shift); 10731 } 10732 } 10733 } 10734 10735 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10736 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10737 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10738 // We simplified Src. If this node is not dead, visit it again so it is 10739 // folded properly. 10740 if (N->getOpcode() != ISD::DELETED_NODE) 10741 DCI.AddToWorklist(N); 10742 return SDValue(N, 0); 10743 } 10744 10745 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10746 if (SDValue DemandedSrc = 10747 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10748 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10749 10750 return SDValue(); 10751 } 10752 10753 SDValue SITargetLowering::performClampCombine(SDNode *N, 10754 DAGCombinerInfo &DCI) const { 10755 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10756 if (!CSrc) 10757 return SDValue(); 10758 10759 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10760 const APFloat &F = CSrc->getValueAPF(); 10761 APFloat Zero = APFloat::getZero(F.getSemantics()); 10762 if (F < Zero || 10763 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10764 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10765 } 10766 10767 APFloat One(F.getSemantics(), "1.0"); 10768 if (F > One) 10769 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10770 10771 return SDValue(CSrc, 0); 10772 } 10773 10774 10775 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10776 DAGCombinerInfo &DCI) const { 10777 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10778 return SDValue(); 10779 switch (N->getOpcode()) { 10780 case ISD::ADD: 10781 return performAddCombine(N, DCI); 10782 case ISD::SUB: 10783 return performSubCombine(N, DCI); 10784 case ISD::ADDCARRY: 10785 case ISD::SUBCARRY: 10786 return performAddCarrySubCarryCombine(N, DCI); 10787 case ISD::FADD: 10788 return performFAddCombine(N, DCI); 10789 case ISD::FSUB: 10790 return performFSubCombine(N, DCI); 10791 case ISD::SETCC: 10792 return performSetCCCombine(N, DCI); 10793 case ISD::FMAXNUM: 10794 case ISD::FMINNUM: 10795 case ISD::FMAXNUM_IEEE: 10796 case ISD::FMINNUM_IEEE: 10797 case ISD::SMAX: 10798 case ISD::SMIN: 10799 case ISD::UMAX: 10800 case ISD::UMIN: 10801 case AMDGPUISD::FMIN_LEGACY: 10802 case AMDGPUISD::FMAX_LEGACY: 10803 return performMinMaxCombine(N, DCI); 10804 case ISD::FMA: 10805 return performFMACombine(N, DCI); 10806 case ISD::AND: 10807 return performAndCombine(N, DCI); 10808 case ISD::OR: 10809 return performOrCombine(N, DCI); 10810 case ISD::XOR: 10811 return performXorCombine(N, DCI); 10812 case ISD::ZERO_EXTEND: 10813 return performZeroExtendCombine(N, DCI); 10814 case ISD::SIGN_EXTEND_INREG: 10815 return performSignExtendInRegCombine(N , DCI); 10816 case AMDGPUISD::FP_CLASS: 10817 return performClassCombine(N, DCI); 10818 case ISD::FCANONICALIZE: 10819 return performFCanonicalizeCombine(N, DCI); 10820 case AMDGPUISD::RCP: 10821 return performRcpCombine(N, DCI); 10822 case AMDGPUISD::FRACT: 10823 case AMDGPUISD::RSQ: 10824 case AMDGPUISD::RCP_LEGACY: 10825 case AMDGPUISD::RCP_IFLAG: 10826 case AMDGPUISD::RSQ_CLAMP: 10827 case AMDGPUISD::LDEXP: { 10828 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10829 SDValue Src = N->getOperand(0); 10830 if (Src.isUndef()) 10831 return Src; 10832 break; 10833 } 10834 case ISD::SINT_TO_FP: 10835 case ISD::UINT_TO_FP: 10836 return performUCharToFloatCombine(N, DCI); 10837 case AMDGPUISD::CVT_F32_UBYTE0: 10838 case AMDGPUISD::CVT_F32_UBYTE1: 10839 case AMDGPUISD::CVT_F32_UBYTE2: 10840 case AMDGPUISD::CVT_F32_UBYTE3: 10841 return performCvtF32UByteNCombine(N, DCI); 10842 case AMDGPUISD::FMED3: 10843 return performFMed3Combine(N, DCI); 10844 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10845 return performCvtPkRTZCombine(N, DCI); 10846 case AMDGPUISD::CLAMP: 10847 return performClampCombine(N, DCI); 10848 case ISD::SCALAR_TO_VECTOR: { 10849 SelectionDAG &DAG = DCI.DAG; 10850 EVT VT = N->getValueType(0); 10851 10852 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10853 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10854 SDLoc SL(N); 10855 SDValue Src = N->getOperand(0); 10856 EVT EltVT = Src.getValueType(); 10857 if (EltVT == MVT::f16) 10858 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10859 10860 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10861 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10862 } 10863 10864 break; 10865 } 10866 case ISD::EXTRACT_VECTOR_ELT: 10867 return performExtractVectorEltCombine(N, DCI); 10868 case ISD::INSERT_VECTOR_ELT: 10869 return performInsertVectorEltCombine(N, DCI); 10870 case ISD::LOAD: { 10871 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10872 return Widended; 10873 LLVM_FALLTHROUGH; 10874 } 10875 default: { 10876 if (!DCI.isBeforeLegalize()) { 10877 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 10878 return performMemSDNodeCombine(MemNode, DCI); 10879 } 10880 10881 break; 10882 } 10883 } 10884 10885 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10886 } 10887 10888 /// Helper function for adjustWritemask 10889 static unsigned SubIdx2Lane(unsigned Idx) { 10890 switch (Idx) { 10891 default: return ~0u; 10892 case AMDGPU::sub0: return 0; 10893 case AMDGPU::sub1: return 1; 10894 case AMDGPU::sub2: return 2; 10895 case AMDGPU::sub3: return 3; 10896 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10897 } 10898 } 10899 10900 /// Adjust the writemask of MIMG instructions 10901 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10902 SelectionDAG &DAG) const { 10903 unsigned Opcode = Node->getMachineOpcode(); 10904 10905 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10906 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10907 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10908 return Node; // not implemented for D16 10909 10910 SDNode *Users[5] = { nullptr }; 10911 unsigned Lane = 0; 10912 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10913 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10914 unsigned NewDmask = 0; 10915 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10916 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10917 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 10918 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10919 unsigned TFCLane = 0; 10920 bool HasChain = Node->getNumValues() > 1; 10921 10922 if (OldDmask == 0) { 10923 // These are folded out, but on the chance it happens don't assert. 10924 return Node; 10925 } 10926 10927 unsigned OldBitsSet = countPopulation(OldDmask); 10928 // Work out which is the TFE/LWE lane if that is enabled. 10929 if (UsesTFC) { 10930 TFCLane = OldBitsSet; 10931 } 10932 10933 // Try to figure out the used register components 10934 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10935 I != E; ++I) { 10936 10937 // Don't look at users of the chain. 10938 if (I.getUse().getResNo() != 0) 10939 continue; 10940 10941 // Abort if we can't understand the usage 10942 if (!I->isMachineOpcode() || 10943 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10944 return Node; 10945 10946 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10947 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10948 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10949 // set, etc. 10950 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10951 if (Lane == ~0u) 10952 return Node; 10953 10954 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10955 if (UsesTFC && Lane == TFCLane) { 10956 Users[Lane] = *I; 10957 } else { 10958 // Set which texture component corresponds to the lane. 10959 unsigned Comp; 10960 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10961 Comp = countTrailingZeros(Dmask); 10962 Dmask &= ~(1 << Comp); 10963 } 10964 10965 // Abort if we have more than one user per component. 10966 if (Users[Lane]) 10967 return Node; 10968 10969 Users[Lane] = *I; 10970 NewDmask |= 1 << Comp; 10971 } 10972 } 10973 10974 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10975 bool NoChannels = !NewDmask; 10976 if (NoChannels) { 10977 if (!UsesTFC) { 10978 // No uses of the result and not using TFC. Then do nothing. 10979 return Node; 10980 } 10981 // If the original dmask has one channel - then nothing to do 10982 if (OldBitsSet == 1) 10983 return Node; 10984 // Use an arbitrary dmask - required for the instruction to work 10985 NewDmask = 1; 10986 } 10987 // Abort if there's no change 10988 if (NewDmask == OldDmask) 10989 return Node; 10990 10991 unsigned BitsSet = countPopulation(NewDmask); 10992 10993 // Check for TFE or LWE - increase the number of channels by one to account 10994 // for the extra return value 10995 // This will need adjustment for D16 if this is also included in 10996 // adjustWriteMask (this function) but at present D16 are excluded. 10997 unsigned NewChannels = BitsSet + UsesTFC; 10998 10999 int NewOpcode = 11000 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11001 assert(NewOpcode != -1 && 11002 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11003 "failed to find equivalent MIMG op"); 11004 11005 // Adjust the writemask in the node 11006 SmallVector<SDValue, 12> Ops; 11007 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11008 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11009 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11010 11011 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11012 11013 MVT ResultVT = NewChannels == 1 ? 11014 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11015 NewChannels == 5 ? 8 : NewChannels); 11016 SDVTList NewVTList = HasChain ? 11017 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11018 11019 11020 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11021 NewVTList, Ops); 11022 11023 if (HasChain) { 11024 // Update chain. 11025 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11026 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11027 } 11028 11029 if (NewChannels == 1) { 11030 assert(Node->hasNUsesOfValue(1, 0)); 11031 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11032 SDLoc(Node), Users[Lane]->getValueType(0), 11033 SDValue(NewNode, 0)); 11034 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11035 return nullptr; 11036 } 11037 11038 // Update the users of the node with the new indices 11039 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11040 SDNode *User = Users[i]; 11041 if (!User) { 11042 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11043 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11044 if (i || !NoChannels) 11045 continue; 11046 } else { 11047 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11048 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11049 } 11050 11051 switch (Idx) { 11052 default: break; 11053 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11054 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11055 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11056 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11057 } 11058 } 11059 11060 DAG.RemoveDeadNode(Node); 11061 return nullptr; 11062 } 11063 11064 static bool isFrameIndexOp(SDValue Op) { 11065 if (Op.getOpcode() == ISD::AssertZext) 11066 Op = Op.getOperand(0); 11067 11068 return isa<FrameIndexSDNode>(Op); 11069 } 11070 11071 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11072 /// with frame index operands. 11073 /// LLVM assumes that inputs are to these instructions are registers. 11074 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11075 SelectionDAG &DAG) const { 11076 if (Node->getOpcode() == ISD::CopyToReg) { 11077 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11078 SDValue SrcVal = Node->getOperand(2); 11079 11080 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11081 // to try understanding copies to physical registers. 11082 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11083 SDLoc SL(Node); 11084 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11085 SDValue VReg = DAG.getRegister( 11086 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11087 11088 SDNode *Glued = Node->getGluedNode(); 11089 SDValue ToVReg 11090 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11091 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11092 SDValue ToResultReg 11093 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11094 VReg, ToVReg.getValue(1)); 11095 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11096 DAG.RemoveDeadNode(Node); 11097 return ToResultReg.getNode(); 11098 } 11099 } 11100 11101 SmallVector<SDValue, 8> Ops; 11102 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11103 if (!isFrameIndexOp(Node->getOperand(i))) { 11104 Ops.push_back(Node->getOperand(i)); 11105 continue; 11106 } 11107 11108 SDLoc DL(Node); 11109 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11110 Node->getOperand(i).getValueType(), 11111 Node->getOperand(i)), 0)); 11112 } 11113 11114 return DAG.UpdateNodeOperands(Node, Ops); 11115 } 11116 11117 /// Fold the instructions after selecting them. 11118 /// Returns null if users were already updated. 11119 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11120 SelectionDAG &DAG) const { 11121 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11122 unsigned Opcode = Node->getMachineOpcode(); 11123 11124 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11125 !TII->isGather4(Opcode) && 11126 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11127 return adjustWritemask(Node, DAG); 11128 } 11129 11130 if (Opcode == AMDGPU::INSERT_SUBREG || 11131 Opcode == AMDGPU::REG_SEQUENCE) { 11132 legalizeTargetIndependentNode(Node, DAG); 11133 return Node; 11134 } 11135 11136 switch (Opcode) { 11137 case AMDGPU::V_DIV_SCALE_F32_e64: 11138 case AMDGPU::V_DIV_SCALE_F64_e64: { 11139 // Satisfy the operand register constraint when one of the inputs is 11140 // undefined. Ordinarily each undef value will have its own implicit_def of 11141 // a vreg, so force these to use a single register. 11142 SDValue Src0 = Node->getOperand(1); 11143 SDValue Src1 = Node->getOperand(3); 11144 SDValue Src2 = Node->getOperand(5); 11145 11146 if ((Src0.isMachineOpcode() && 11147 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11148 (Src0 == Src1 || Src0 == Src2)) 11149 break; 11150 11151 MVT VT = Src0.getValueType().getSimpleVT(); 11152 const TargetRegisterClass *RC = 11153 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11154 11155 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11156 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11157 11158 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11159 UndefReg, Src0, SDValue()); 11160 11161 // src0 must be the same register as src1 or src2, even if the value is 11162 // undefined, so make sure we don't violate this constraint. 11163 if (Src0.isMachineOpcode() && 11164 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11165 if (Src1.isMachineOpcode() && 11166 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11167 Src0 = Src1; 11168 else if (Src2.isMachineOpcode() && 11169 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11170 Src0 = Src2; 11171 else { 11172 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11173 Src0 = UndefReg; 11174 Src1 = UndefReg; 11175 } 11176 } else 11177 break; 11178 11179 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11180 Ops[1] = Src0; 11181 Ops[3] = Src1; 11182 Ops[5] = Src2; 11183 Ops.push_back(ImpDef.getValue(1)); 11184 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11185 } 11186 default: 11187 break; 11188 } 11189 11190 return Node; 11191 } 11192 11193 /// Assign the register class depending on the number of 11194 /// bits set in the writemask 11195 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11196 SDNode *Node) const { 11197 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11198 11199 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11200 11201 if (TII->isVOP3(MI.getOpcode())) { 11202 // Make sure constant bus requirements are respected. 11203 TII->legalizeOperandsVOP3(MRI, MI); 11204 11205 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11206 // This saves a chain-copy of registers and better ballance register 11207 // use between vgpr and agpr as agpr tuples tend to be big. 11208 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 11209 unsigned Opc = MI.getOpcode(); 11210 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11211 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11212 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11213 if (I == -1) 11214 break; 11215 MachineOperand &Op = MI.getOperand(I); 11216 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 11217 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 11218 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 11219 continue; 11220 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11221 if (!Src || !Src->isCopy() || 11222 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11223 continue; 11224 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11225 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11226 // All uses of agpr64 and agpr32 can also accept vgpr except for 11227 // v_accvgpr_read, but we do not produce agpr reads during selection, 11228 // so no use checks are needed. 11229 MRI.setRegClass(Op.getReg(), NewRC); 11230 } 11231 } 11232 11233 return; 11234 } 11235 11236 // Replace unused atomics with the no return version. 11237 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11238 if (NoRetAtomicOp != -1) { 11239 if (!Node->hasAnyUseOfValue(0)) { 11240 int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11241 AMDGPU::OpName::cpol); 11242 if (CPolIdx != -1) { 11243 MachineOperand &CPol = MI.getOperand(CPolIdx); 11244 CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC); 11245 } 11246 MI.RemoveOperand(0); 11247 MI.setDesc(TII->get(NoRetAtomicOp)); 11248 return; 11249 } 11250 11251 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11252 // instruction, because the return type of these instructions is a vec2 of 11253 // the memory type, so it can be tied to the input operand. 11254 // This means these instructions always have a use, so we need to add a 11255 // special case to check if the atomic has only one extract_subreg use, 11256 // which itself has no uses. 11257 if ((Node->hasNUsesOfValue(1, 0) && 11258 Node->use_begin()->isMachineOpcode() && 11259 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11260 !Node->use_begin()->hasAnyUseOfValue(0))) { 11261 Register Def = MI.getOperand(0).getReg(); 11262 11263 // Change this into a noret atomic. 11264 MI.setDesc(TII->get(NoRetAtomicOp)); 11265 MI.RemoveOperand(0); 11266 11267 // If we only remove the def operand from the atomic instruction, the 11268 // extract_subreg will be left with a use of a vreg without a def. 11269 // So we need to insert an implicit_def to avoid machine verifier 11270 // errors. 11271 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11272 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11273 } 11274 return; 11275 } 11276 } 11277 11278 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11279 uint64_t Val) { 11280 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11281 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11282 } 11283 11284 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11285 const SDLoc &DL, 11286 SDValue Ptr) const { 11287 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11288 11289 // Build the half of the subregister with the constants before building the 11290 // full 128-bit register. If we are building multiple resource descriptors, 11291 // this will allow CSEing of the 2-component register. 11292 const SDValue Ops0[] = { 11293 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11294 buildSMovImm32(DAG, DL, 0), 11295 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11296 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11297 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11298 }; 11299 11300 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11301 MVT::v2i32, Ops0), 0); 11302 11303 // Combine the constants and the pointer. 11304 const SDValue Ops1[] = { 11305 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11306 Ptr, 11307 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11308 SubRegHi, 11309 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11310 }; 11311 11312 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11313 } 11314 11315 /// Return a resource descriptor with the 'Add TID' bit enabled 11316 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11317 /// of the resource descriptor) to create an offset, which is added to 11318 /// the resource pointer. 11319 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11320 SDValue Ptr, uint32_t RsrcDword1, 11321 uint64_t RsrcDword2And3) const { 11322 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11323 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11324 if (RsrcDword1) { 11325 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11326 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11327 0); 11328 } 11329 11330 SDValue DataLo = buildSMovImm32(DAG, DL, 11331 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11332 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11333 11334 const SDValue Ops[] = { 11335 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11336 PtrLo, 11337 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11338 PtrHi, 11339 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11340 DataLo, 11341 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11342 DataHi, 11343 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11344 }; 11345 11346 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11347 } 11348 11349 //===----------------------------------------------------------------------===// 11350 // SI Inline Assembly Support 11351 //===----------------------------------------------------------------------===// 11352 11353 std::pair<unsigned, const TargetRegisterClass *> 11354 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11355 StringRef Constraint, 11356 MVT VT) const { 11357 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11358 11359 const TargetRegisterClass *RC = nullptr; 11360 if (Constraint.size() == 1) { 11361 const unsigned BitWidth = VT.getSizeInBits(); 11362 switch (Constraint[0]) { 11363 default: 11364 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11365 case 's': 11366 case 'r': 11367 switch (BitWidth) { 11368 case 16: 11369 RC = &AMDGPU::SReg_32RegClass; 11370 break; 11371 case 64: 11372 RC = &AMDGPU::SGPR_64RegClass; 11373 break; 11374 default: 11375 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11376 if (!RC) 11377 return std::make_pair(0U, nullptr); 11378 break; 11379 } 11380 break; 11381 case 'v': 11382 switch (BitWidth) { 11383 case 16: 11384 RC = &AMDGPU::VGPR_32RegClass; 11385 break; 11386 default: 11387 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11388 if (!RC) 11389 return std::make_pair(0U, nullptr); 11390 break; 11391 } 11392 break; 11393 case 'a': 11394 if (!Subtarget->hasMAIInsts()) 11395 break; 11396 switch (BitWidth) { 11397 case 16: 11398 RC = &AMDGPU::AGPR_32RegClass; 11399 break; 11400 default: 11401 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11402 if (!RC) 11403 return std::make_pair(0U, nullptr); 11404 break; 11405 } 11406 break; 11407 } 11408 // We actually support i128, i16 and f16 as inline parameters 11409 // even if they are not reported as legal 11410 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11411 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11412 return std::make_pair(0U, RC); 11413 } 11414 11415 if (Constraint.size() > 1) { 11416 if (Constraint[1] == 'v') { 11417 RC = &AMDGPU::VGPR_32RegClass; 11418 } else if (Constraint[1] == 's') { 11419 RC = &AMDGPU::SGPR_32RegClass; 11420 } else if (Constraint[1] == 'a') { 11421 RC = &AMDGPU::AGPR_32RegClass; 11422 } 11423 11424 if (RC) { 11425 uint32_t Idx; 11426 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11427 if (!Failed && Idx < RC->getNumRegs()) 11428 return std::make_pair(RC->getRegister(Idx), RC); 11429 } 11430 } 11431 11432 // FIXME: Returns VS_32 for physical SGPR constraints 11433 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11434 } 11435 11436 static bool isImmConstraint(StringRef Constraint) { 11437 if (Constraint.size() == 1) { 11438 switch (Constraint[0]) { 11439 default: break; 11440 case 'I': 11441 case 'J': 11442 case 'A': 11443 case 'B': 11444 case 'C': 11445 return true; 11446 } 11447 } else if (Constraint == "DA" || 11448 Constraint == "DB") { 11449 return true; 11450 } 11451 return false; 11452 } 11453 11454 SITargetLowering::ConstraintType 11455 SITargetLowering::getConstraintType(StringRef Constraint) const { 11456 if (Constraint.size() == 1) { 11457 switch (Constraint[0]) { 11458 default: break; 11459 case 's': 11460 case 'v': 11461 case 'a': 11462 return C_RegisterClass; 11463 } 11464 } 11465 if (isImmConstraint(Constraint)) { 11466 return C_Other; 11467 } 11468 return TargetLowering::getConstraintType(Constraint); 11469 } 11470 11471 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11472 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11473 Val = Val & maskTrailingOnes<uint64_t>(Size); 11474 } 11475 return Val; 11476 } 11477 11478 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11479 std::string &Constraint, 11480 std::vector<SDValue> &Ops, 11481 SelectionDAG &DAG) const { 11482 if (isImmConstraint(Constraint)) { 11483 uint64_t Val; 11484 if (getAsmOperandConstVal(Op, Val) && 11485 checkAsmConstraintVal(Op, Constraint, Val)) { 11486 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11487 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11488 } 11489 } else { 11490 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11491 } 11492 } 11493 11494 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11495 unsigned Size = Op.getScalarValueSizeInBits(); 11496 if (Size > 64) 11497 return false; 11498 11499 if (Size == 16 && !Subtarget->has16BitInsts()) 11500 return false; 11501 11502 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11503 Val = C->getSExtValue(); 11504 return true; 11505 } 11506 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11507 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11508 return true; 11509 } 11510 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11511 if (Size != 16 || Op.getNumOperands() != 2) 11512 return false; 11513 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11514 return false; 11515 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11516 Val = C->getSExtValue(); 11517 return true; 11518 } 11519 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11520 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11521 return true; 11522 } 11523 } 11524 11525 return false; 11526 } 11527 11528 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11529 const std::string &Constraint, 11530 uint64_t Val) const { 11531 if (Constraint.size() == 1) { 11532 switch (Constraint[0]) { 11533 case 'I': 11534 return AMDGPU::isInlinableIntLiteral(Val); 11535 case 'J': 11536 return isInt<16>(Val); 11537 case 'A': 11538 return checkAsmConstraintValA(Op, Val); 11539 case 'B': 11540 return isInt<32>(Val); 11541 case 'C': 11542 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11543 AMDGPU::isInlinableIntLiteral(Val); 11544 default: 11545 break; 11546 } 11547 } else if (Constraint.size() == 2) { 11548 if (Constraint == "DA") { 11549 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11550 int64_t LoBits = static_cast<int32_t>(Val); 11551 return checkAsmConstraintValA(Op, HiBits, 32) && 11552 checkAsmConstraintValA(Op, LoBits, 32); 11553 } 11554 if (Constraint == "DB") { 11555 return true; 11556 } 11557 } 11558 llvm_unreachable("Invalid asm constraint"); 11559 } 11560 11561 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11562 uint64_t Val, 11563 unsigned MaxSize) const { 11564 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11565 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11566 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11567 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11568 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11569 return true; 11570 } 11571 return false; 11572 } 11573 11574 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 11575 switch (UnalignedClassID) { 11576 case AMDGPU::VReg_64RegClassID: 11577 return AMDGPU::VReg_64_Align2RegClassID; 11578 case AMDGPU::VReg_96RegClassID: 11579 return AMDGPU::VReg_96_Align2RegClassID; 11580 case AMDGPU::VReg_128RegClassID: 11581 return AMDGPU::VReg_128_Align2RegClassID; 11582 case AMDGPU::VReg_160RegClassID: 11583 return AMDGPU::VReg_160_Align2RegClassID; 11584 case AMDGPU::VReg_192RegClassID: 11585 return AMDGPU::VReg_192_Align2RegClassID; 11586 case AMDGPU::VReg_256RegClassID: 11587 return AMDGPU::VReg_256_Align2RegClassID; 11588 case AMDGPU::VReg_512RegClassID: 11589 return AMDGPU::VReg_512_Align2RegClassID; 11590 case AMDGPU::VReg_1024RegClassID: 11591 return AMDGPU::VReg_1024_Align2RegClassID; 11592 case AMDGPU::AReg_64RegClassID: 11593 return AMDGPU::AReg_64_Align2RegClassID; 11594 case AMDGPU::AReg_96RegClassID: 11595 return AMDGPU::AReg_96_Align2RegClassID; 11596 case AMDGPU::AReg_128RegClassID: 11597 return AMDGPU::AReg_128_Align2RegClassID; 11598 case AMDGPU::AReg_160RegClassID: 11599 return AMDGPU::AReg_160_Align2RegClassID; 11600 case AMDGPU::AReg_192RegClassID: 11601 return AMDGPU::AReg_192_Align2RegClassID; 11602 case AMDGPU::AReg_256RegClassID: 11603 return AMDGPU::AReg_256_Align2RegClassID; 11604 case AMDGPU::AReg_512RegClassID: 11605 return AMDGPU::AReg_512_Align2RegClassID; 11606 case AMDGPU::AReg_1024RegClassID: 11607 return AMDGPU::AReg_1024_Align2RegClassID; 11608 default: 11609 return -1; 11610 } 11611 } 11612 11613 // Figure out which registers should be reserved for stack access. Only after 11614 // the function is legalized do we know all of the non-spill stack objects or if 11615 // calls are present. 11616 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11617 MachineRegisterInfo &MRI = MF.getRegInfo(); 11618 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11619 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11620 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11621 const SIInstrInfo *TII = ST.getInstrInfo(); 11622 11623 if (Info->isEntryFunction()) { 11624 // Callable functions have fixed registers used for stack access. 11625 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11626 } 11627 11628 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11629 Info->getStackPtrOffsetReg())); 11630 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11631 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11632 11633 // We need to worry about replacing the default register with itself in case 11634 // of MIR testcases missing the MFI. 11635 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11636 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11637 11638 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11639 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11640 11641 Info->limitOccupancy(MF); 11642 11643 if (ST.isWave32() && !MF.empty()) { 11644 for (auto &MBB : MF) { 11645 for (auto &MI : MBB) { 11646 TII->fixImplicitOperands(MI); 11647 } 11648 } 11649 } 11650 11651 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 11652 // classes if required. Ideally the register class constraints would differ 11653 // per-subtarget, but there's no easy way to achieve that right now. This is 11654 // not a problem for VGPRs because the correctly aligned VGPR class is implied 11655 // from using them as the register class for legal types. 11656 if (ST.needsAlignedVGPRs()) { 11657 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 11658 const Register Reg = Register::index2VirtReg(I); 11659 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 11660 if (!RC) 11661 continue; 11662 int NewClassID = getAlignedAGPRClassID(RC->getID()); 11663 if (NewClassID != -1) 11664 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 11665 } 11666 } 11667 11668 TargetLoweringBase::finalizeLowering(MF); 11669 11670 // Allocate a VGPR for future SGPR Spill if 11671 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11672 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11673 if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() && 11674 !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction()) 11675 Info->reserveVGPRforSGPRSpills(MF); 11676 } 11677 11678 void SITargetLowering::computeKnownBitsForFrameIndex( 11679 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11680 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11681 11682 // Set the high bits to zero based on the maximum allowed scratch size per 11683 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11684 // calculation won't overflow, so assume the sign bit is never set. 11685 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11686 } 11687 11688 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11689 KnownBits &Known, unsigned Dim) { 11690 unsigned MaxValue = 11691 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11692 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11693 } 11694 11695 void SITargetLowering::computeKnownBitsForTargetInstr( 11696 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11697 const MachineRegisterInfo &MRI, unsigned Depth) const { 11698 const MachineInstr *MI = MRI.getVRegDef(R); 11699 switch (MI->getOpcode()) { 11700 case AMDGPU::G_INTRINSIC: { 11701 switch (MI->getIntrinsicID()) { 11702 case Intrinsic::amdgcn_workitem_id_x: 11703 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11704 break; 11705 case Intrinsic::amdgcn_workitem_id_y: 11706 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11707 break; 11708 case Intrinsic::amdgcn_workitem_id_z: 11709 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11710 break; 11711 case Intrinsic::amdgcn_mbcnt_lo: 11712 case Intrinsic::amdgcn_mbcnt_hi: { 11713 // These return at most the wavefront size - 1. 11714 unsigned Size = MRI.getType(R).getSizeInBits(); 11715 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11716 break; 11717 } 11718 case Intrinsic::amdgcn_groupstaticsize: { 11719 // We can report everything over the maximum size as 0. We can't report 11720 // based on the actual size because we don't know if it's accurate or not 11721 // at any given point. 11722 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11723 break; 11724 } 11725 } 11726 break; 11727 } 11728 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 11729 Known.Zero.setHighBits(24); 11730 break; 11731 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 11732 Known.Zero.setHighBits(16); 11733 break; 11734 } 11735 } 11736 11737 Align SITargetLowering::computeKnownAlignForTargetInstr( 11738 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11739 unsigned Depth) const { 11740 const MachineInstr *MI = MRI.getVRegDef(R); 11741 switch (MI->getOpcode()) { 11742 case AMDGPU::G_INTRINSIC: 11743 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11744 // FIXME: Can this move to generic code? What about the case where the call 11745 // site specifies a lower alignment? 11746 Intrinsic::ID IID = MI->getIntrinsicID(); 11747 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11748 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11749 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11750 return *RetAlign; 11751 return Align(1); 11752 } 11753 default: 11754 return Align(1); 11755 } 11756 } 11757 11758 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11759 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11760 const Align CacheLineAlign = Align(64); 11761 11762 // Pre-GFX10 target did not benefit from loop alignment 11763 if (!ML || DisableLoopAlignment || 11764 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11765 getSubtarget()->hasInstFwdPrefetchBug()) 11766 return PrefAlign; 11767 11768 // On GFX10 I$ is 4 x 64 bytes cache lines. 11769 // By default prefetcher keeps one cache line behind and reads two ahead. 11770 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11771 // behind and one ahead. 11772 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11773 // If loop fits 64 bytes it always spans no more than two cache lines and 11774 // does not need an alignment. 11775 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11776 // Else if loop is less or equal 192 bytes we need two lines behind. 11777 11778 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11779 const MachineBasicBlock *Header = ML->getHeader(); 11780 if (Header->getAlignment() != PrefAlign) 11781 return Header->getAlignment(); // Already processed. 11782 11783 unsigned LoopSize = 0; 11784 for (const MachineBasicBlock *MBB : ML->blocks()) { 11785 // If inner loop block is aligned assume in average half of the alignment 11786 // size to be added as nops. 11787 if (MBB != Header) 11788 LoopSize += MBB->getAlignment().value() / 2; 11789 11790 for (const MachineInstr &MI : *MBB) { 11791 LoopSize += TII->getInstSizeInBytes(MI); 11792 if (LoopSize > 192) 11793 return PrefAlign; 11794 } 11795 } 11796 11797 if (LoopSize <= 64) 11798 return PrefAlign; 11799 11800 if (LoopSize <= 128) 11801 return CacheLineAlign; 11802 11803 // If any of parent loops is surrounded by prefetch instructions do not 11804 // insert new for inner loop, which would reset parent's settings. 11805 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11806 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11807 auto I = Exit->getFirstNonDebugInstr(); 11808 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11809 return CacheLineAlign; 11810 } 11811 } 11812 11813 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11814 MachineBasicBlock *Exit = ML->getExitBlock(); 11815 11816 if (Pre && Exit) { 11817 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11818 TII->get(AMDGPU::S_INST_PREFETCH)) 11819 .addImm(1); // prefetch 2 lines behind PC 11820 11821 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11822 TII->get(AMDGPU::S_INST_PREFETCH)) 11823 .addImm(2); // prefetch 1 line behind PC 11824 } 11825 11826 return CacheLineAlign; 11827 } 11828 11829 LLVM_ATTRIBUTE_UNUSED 11830 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11831 assert(N->getOpcode() == ISD::CopyFromReg); 11832 do { 11833 // Follow the chain until we find an INLINEASM node. 11834 N = N->getOperand(0).getNode(); 11835 if (N->getOpcode() == ISD::INLINEASM || 11836 N->getOpcode() == ISD::INLINEASM_BR) 11837 return true; 11838 } while (N->getOpcode() == ISD::CopyFromReg); 11839 return false; 11840 } 11841 11842 bool SITargetLowering::isSDNodeSourceOfDivergence( 11843 const SDNode *N, FunctionLoweringInfo *FLI, 11844 LegacyDivergenceAnalysis *KDA) const { 11845 switch (N->getOpcode()) { 11846 case ISD::CopyFromReg: { 11847 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11848 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11849 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11850 Register Reg = R->getReg(); 11851 11852 // FIXME: Why does this need to consider isLiveIn? 11853 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11854 return !TRI->isSGPRReg(MRI, Reg); 11855 11856 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11857 return KDA->isDivergent(V); 11858 11859 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11860 return !TRI->isSGPRReg(MRI, Reg); 11861 } 11862 case ISD::LOAD: { 11863 const LoadSDNode *L = cast<LoadSDNode>(N); 11864 unsigned AS = L->getAddressSpace(); 11865 // A flat load may access private memory. 11866 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11867 } 11868 case ISD::CALLSEQ_END: 11869 return true; 11870 case ISD::INTRINSIC_WO_CHAIN: 11871 return AMDGPU::isIntrinsicSourceOfDivergence( 11872 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11873 case ISD::INTRINSIC_W_CHAIN: 11874 return AMDGPU::isIntrinsicSourceOfDivergence( 11875 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11876 case AMDGPUISD::ATOMIC_CMP_SWAP: 11877 case AMDGPUISD::ATOMIC_INC: 11878 case AMDGPUISD::ATOMIC_DEC: 11879 case AMDGPUISD::ATOMIC_LOAD_FMIN: 11880 case AMDGPUISD::ATOMIC_LOAD_FMAX: 11881 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 11882 case AMDGPUISD::BUFFER_ATOMIC_ADD: 11883 case AMDGPUISD::BUFFER_ATOMIC_SUB: 11884 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 11885 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 11886 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 11887 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 11888 case AMDGPUISD::BUFFER_ATOMIC_AND: 11889 case AMDGPUISD::BUFFER_ATOMIC_OR: 11890 case AMDGPUISD::BUFFER_ATOMIC_XOR: 11891 case AMDGPUISD::BUFFER_ATOMIC_INC: 11892 case AMDGPUISD::BUFFER_ATOMIC_DEC: 11893 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 11894 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 11895 case AMDGPUISD::BUFFER_ATOMIC_FADD: 11896 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 11897 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 11898 // Target-specific read-modify-write atomics are sources of divergence. 11899 return true; 11900 default: 11901 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 11902 // Generic read-modify-write atomics are sources of divergence. 11903 return A->readMem() && A->writeMem(); 11904 } 11905 return false; 11906 } 11907 } 11908 11909 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11910 EVT VT) const { 11911 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11912 case MVT::f32: 11913 return hasFP32Denormals(DAG.getMachineFunction()); 11914 case MVT::f64: 11915 case MVT::f16: 11916 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11917 default: 11918 return false; 11919 } 11920 } 11921 11922 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11923 const SelectionDAG &DAG, 11924 bool SNaN, 11925 unsigned Depth) const { 11926 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11927 const MachineFunction &MF = DAG.getMachineFunction(); 11928 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11929 11930 if (Info->getMode().DX10Clamp) 11931 return true; // Clamped to 0. 11932 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11933 } 11934 11935 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11936 SNaN, Depth); 11937 } 11938 11939 // Global FP atomic instructions have a hardcoded FP mode and do not support 11940 // FP32 denormals, and only support v2f16 denormals. 11941 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 11942 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 11943 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 11944 if (&Flt == &APFloat::IEEEsingle()) 11945 return DenormMode == DenormalMode::getPreserveSign(); 11946 return DenormMode == DenormalMode::getIEEE(); 11947 } 11948 11949 TargetLowering::AtomicExpansionKind 11950 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11951 switch (RMW->getOperation()) { 11952 case AtomicRMWInst::FAdd: { 11953 Type *Ty = RMW->getType(); 11954 11955 // We don't have a way to support 16-bit atomics now, so just leave them 11956 // as-is. 11957 if (Ty->isHalfTy()) 11958 return AtomicExpansionKind::None; 11959 11960 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 11961 return AtomicExpansionKind::CmpXChg; 11962 11963 // TODO: Do have these for flat. Older targets also had them for buffers. 11964 unsigned AS = RMW->getPointerAddressSpace(); 11965 11966 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 11967 Subtarget->hasAtomicFaddInsts()) { 11968 if (!fpModeMatchesGlobalFPAtomicMode(RMW) || 11969 RMW->getFunction()->getFnAttribute("amdgpu-unsafe-fp-atomics") 11970 .getValueAsString() != "true") 11971 return AtomicExpansionKind::CmpXChg; 11972 11973 if (Subtarget->hasGFX90AInsts()) { 11974 auto SSID = RMW->getSyncScopeID(); 11975 if (SSID == SyncScope::System || 11976 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 11977 return AtomicExpansionKind::CmpXChg; 11978 11979 return (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) ? 11980 AtomicExpansionKind::CmpXChg : AtomicExpansionKind::None; 11981 } 11982 11983 if (!Subtarget->hasGFX90AInsts() && AS != AMDGPUAS::GLOBAL_ADDRESS) 11984 return AtomicExpansionKind::CmpXChg; 11985 11986 return RMW->use_empty() ? AtomicExpansionKind::None : 11987 AtomicExpansionKind::CmpXChg; 11988 } 11989 11990 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 11991 // to round-to-nearest-even. 11992 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 11993 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) { 11994 return (Ty->isDoubleTy() && !fpModeMatchesGlobalFPAtomicMode(RMW)) ? 11995 AtomicExpansionKind::CmpXChg : AtomicExpansionKind::None; 11996 } 11997 11998 return AtomicExpansionKind::CmpXChg; 11999 } 12000 default: 12001 break; 12002 } 12003 12004 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12005 } 12006 12007 const TargetRegisterClass * 12008 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12009 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12010 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12011 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12012 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12013 : &AMDGPU::SReg_32RegClass; 12014 if (!TRI->isSGPRClass(RC) && !isDivergent) 12015 return TRI->getEquivalentSGPRClass(RC); 12016 else if (TRI->isSGPRClass(RC) && isDivergent) 12017 return TRI->getEquivalentVGPRClass(RC); 12018 12019 return RC; 12020 } 12021 12022 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12023 // uniform values (as produced by the mask results of control flow intrinsics) 12024 // used outside of divergent blocks. The phi users need to also be treated as 12025 // always uniform. 12026 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12027 unsigned WaveSize) { 12028 // FIXME: We asssume we never cast the mask results of a control flow 12029 // intrinsic. 12030 // Early exit if the type won't be consistent as a compile time hack. 12031 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12032 if (!IT || IT->getBitWidth() != WaveSize) 12033 return false; 12034 12035 if (!isa<Instruction>(V)) 12036 return false; 12037 if (!Visited.insert(V).second) 12038 return false; 12039 bool Result = false; 12040 for (auto U : V->users()) { 12041 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12042 if (V == U->getOperand(1)) { 12043 switch (Intrinsic->getIntrinsicID()) { 12044 default: 12045 Result = false; 12046 break; 12047 case Intrinsic::amdgcn_if_break: 12048 case Intrinsic::amdgcn_if: 12049 case Intrinsic::amdgcn_else: 12050 Result = true; 12051 break; 12052 } 12053 } 12054 if (V == U->getOperand(0)) { 12055 switch (Intrinsic->getIntrinsicID()) { 12056 default: 12057 Result = false; 12058 break; 12059 case Intrinsic::amdgcn_end_cf: 12060 case Intrinsic::amdgcn_loop: 12061 Result = true; 12062 break; 12063 } 12064 } 12065 } else { 12066 Result = hasCFUser(U, Visited, WaveSize); 12067 } 12068 if (Result) 12069 break; 12070 } 12071 return Result; 12072 } 12073 12074 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12075 const Value *V) const { 12076 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12077 if (CI->isInlineAsm()) { 12078 // FIXME: This cannot give a correct answer. This should only trigger in 12079 // the case where inline asm returns mixed SGPR and VGPR results, used 12080 // outside the defining block. We don't have a specific result to 12081 // consider, so this assumes if any value is SGPR, the overall register 12082 // also needs to be SGPR. 12083 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12084 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12085 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12086 for (auto &TC : TargetConstraints) { 12087 if (TC.Type == InlineAsm::isOutput) { 12088 ComputeConstraintToUse(TC, SDValue()); 12089 unsigned AssignedReg; 12090 const TargetRegisterClass *RC; 12091 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 12092 SIRI, TC.ConstraintCode, TC.ConstraintVT); 12093 if (RC) { 12094 MachineRegisterInfo &MRI = MF.getRegInfo(); 12095 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 12096 return true; 12097 else if (SIRI->isSGPRClass(RC)) 12098 return true; 12099 } 12100 } 12101 } 12102 } 12103 } 12104 SmallPtrSet<const Value *, 16> Visited; 12105 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12106 } 12107 12108 std::pair<int, MVT> 12109 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12110 Type *Ty) const { 12111 auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12112 auto Size = DL.getTypeSizeInBits(Ty); 12113 // Maximum load or store can handle 8 dwords for scalar and 4 for 12114 // vector ALU. Let's assume anything above 8 dwords is expensive 12115 // even if legal. 12116 if (Size <= 256) 12117 return Cost; 12118 12119 Cost.first = (Size + 255) / 256; 12120 return Cost; 12121 } 12122