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 || 1241 Subtarget->getInstrInfo()->isLegalFLATOffset( 1242 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT)); 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 SIInstrFlags::FlatGlobal)); 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 // Either, the alignment requirements are "enabled", or there is an 1416 // unaligned LDS access related hardware bug though alignment requirements 1417 // are "disabled". In either case, we need to check for proper alignment 1418 // requirements. 1419 // 1420 if (Size == 64) { 1421 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we 1422 // can do a 4 byte aligned, 8 byte access in a single operation using 1423 // ds_read2/write2_b32 with adjacent offsets. 1424 bool AlignedBy4 = Alignment >= Align(4); 1425 if (IsFast) 1426 *IsFast = AlignedBy4; 1427 1428 return AlignedBy4; 1429 } 1430 if (Size == 96) { 1431 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on 1432 // gfx8 and older. 1433 bool AlignedBy16 = Alignment >= Align(16); 1434 if (IsFast) 1435 *IsFast = AlignedBy16; 1436 1437 return AlignedBy16; 1438 } 1439 if (Size == 128) { 1440 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on 1441 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a 1442 // single operation using ds_read2/write2_b64. 1443 bool AlignedBy8 = Alignment >= Align(8); 1444 if (IsFast) 1445 *IsFast = AlignedBy8; 1446 1447 return AlignedBy8; 1448 } 1449 } 1450 1451 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1452 bool AlignedBy4 = Alignment >= Align(4); 1453 if (IsFast) 1454 *IsFast = AlignedBy4; 1455 1456 return AlignedBy4 || 1457 Subtarget->enableFlatScratch() || 1458 Subtarget->hasUnalignedScratchAccess(); 1459 } 1460 1461 // FIXME: We have to be conservative here and assume that flat operations 1462 // will access scratch. If we had access to the IR function, then we 1463 // could determine if any private memory was used in the function. 1464 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1465 !Subtarget->hasUnalignedScratchAccess()) { 1466 bool AlignedBy4 = Alignment >= Align(4); 1467 if (IsFast) 1468 *IsFast = AlignedBy4; 1469 1470 return AlignedBy4; 1471 } 1472 1473 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1474 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1475 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1476 // If we have an uniform constant load, it still requires using a slow 1477 // buffer instruction if unaligned. 1478 if (IsFast) { 1479 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1480 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1481 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1482 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1483 Alignment >= Align(4) : Alignment != Align(2); 1484 } 1485 1486 return true; 1487 } 1488 1489 // Smaller than dword value must be aligned. 1490 if (Size < 32) 1491 return false; 1492 1493 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1494 // byte-address are ignored, thus forcing Dword alignment. 1495 // This applies to private, global, and constant memory. 1496 if (IsFast) 1497 *IsFast = true; 1498 1499 return Size >= 32 && Alignment >= Align(4); 1500 } 1501 1502 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1503 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1504 bool *IsFast) const { 1505 if (IsFast) 1506 *IsFast = false; 1507 1508 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1509 // which isn't a simple VT. 1510 // Until MVT is extended to handle this, simply check for the size and 1511 // rely on the condition below: allow accesses if the size is a multiple of 4. 1512 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1513 VT.getStoreSize() > 16)) { 1514 return false; 1515 } 1516 1517 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1518 Alignment, Flags, IsFast); 1519 } 1520 1521 EVT SITargetLowering::getOptimalMemOpType( 1522 const MemOp &Op, const AttributeList &FuncAttributes) const { 1523 // FIXME: Should account for address space here. 1524 1525 // The default fallback uses the private pointer size as a guess for a type to 1526 // use. Make sure we switch these to 64-bit accesses. 1527 1528 if (Op.size() >= 16 && 1529 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1530 return MVT::v4i32; 1531 1532 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1533 return MVT::v2i32; 1534 1535 // Use the default. 1536 return MVT::Other; 1537 } 1538 1539 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1540 const MemSDNode *MemNode = cast<MemSDNode>(N); 1541 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1542 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1543 return I && I->getMetadata("amdgpu.noclobber"); 1544 } 1545 1546 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1547 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1548 AS == AMDGPUAS::PRIVATE_ADDRESS; 1549 } 1550 1551 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1552 unsigned DestAS) const { 1553 // Flat -> private/local is a simple truncate. 1554 // Flat -> global is no-op 1555 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1556 return true; 1557 1558 const GCNTargetMachine &TM = 1559 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1560 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1561 } 1562 1563 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1564 const MemSDNode *MemNode = cast<MemSDNode>(N); 1565 1566 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1567 } 1568 1569 TargetLoweringBase::LegalizeTypeAction 1570 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1571 int NumElts = VT.getVectorNumElements(); 1572 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1573 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1574 return TargetLoweringBase::getPreferredVectorAction(VT); 1575 } 1576 1577 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1578 Type *Ty) const { 1579 // FIXME: Could be smarter if called for vector constants. 1580 return true; 1581 } 1582 1583 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1584 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1585 switch (Op) { 1586 case ISD::LOAD: 1587 case ISD::STORE: 1588 1589 // These operations are done with 32-bit instructions anyway. 1590 case ISD::AND: 1591 case ISD::OR: 1592 case ISD::XOR: 1593 case ISD::SELECT: 1594 // TODO: Extensions? 1595 return true; 1596 default: 1597 return false; 1598 } 1599 } 1600 1601 // SimplifySetCC uses this function to determine whether or not it should 1602 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1603 if (VT == MVT::i1 && Op == ISD::SETCC) 1604 return false; 1605 1606 return TargetLowering::isTypeDesirableForOp(Op, VT); 1607 } 1608 1609 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1610 const SDLoc &SL, 1611 SDValue Chain, 1612 uint64_t Offset) const { 1613 const DataLayout &DL = DAG.getDataLayout(); 1614 MachineFunction &MF = DAG.getMachineFunction(); 1615 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1616 1617 const ArgDescriptor *InputPtrReg; 1618 const TargetRegisterClass *RC; 1619 LLT ArgTy; 1620 1621 std::tie(InputPtrReg, RC, ArgTy) = 1622 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1623 1624 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1625 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1626 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1627 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1628 1629 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1630 } 1631 1632 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1633 const SDLoc &SL) const { 1634 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1635 FIRST_IMPLICIT); 1636 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1637 } 1638 1639 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1640 const SDLoc &SL, SDValue Val, 1641 bool Signed, 1642 const ISD::InputArg *Arg) const { 1643 // First, if it is a widened vector, narrow it. 1644 if (VT.isVector() && 1645 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1646 EVT NarrowedVT = 1647 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1648 VT.getVectorNumElements()); 1649 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1650 DAG.getConstant(0, SL, MVT::i32)); 1651 } 1652 1653 // Then convert the vector elements or scalar value. 1654 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1655 VT.bitsLT(MemVT)) { 1656 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1657 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1658 } 1659 1660 if (MemVT.isFloatingPoint()) 1661 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1662 else if (Signed) 1663 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1664 else 1665 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1666 1667 return Val; 1668 } 1669 1670 SDValue SITargetLowering::lowerKernargMemParameter( 1671 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1672 uint64_t Offset, Align Alignment, bool Signed, 1673 const ISD::InputArg *Arg) const { 1674 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1675 1676 // Try to avoid using an extload by loading earlier than the argument address, 1677 // and extracting the relevant bits. The load should hopefully be merged with 1678 // the previous argument. 1679 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1680 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1681 int64_t AlignDownOffset = alignDown(Offset, 4); 1682 int64_t OffsetDiff = Offset - AlignDownOffset; 1683 1684 EVT IntVT = MemVT.changeTypeToInteger(); 1685 1686 // TODO: If we passed in the base kernel offset we could have a better 1687 // alignment than 4, but we don't really need it. 1688 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1689 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1690 MachineMemOperand::MODereferenceable | 1691 MachineMemOperand::MOInvariant); 1692 1693 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1694 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1695 1696 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1697 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1698 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1699 1700 1701 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1702 } 1703 1704 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1705 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1706 MachineMemOperand::MODereferenceable | 1707 MachineMemOperand::MOInvariant); 1708 1709 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1710 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1711 } 1712 1713 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1714 const SDLoc &SL, SDValue Chain, 1715 const ISD::InputArg &Arg) const { 1716 MachineFunction &MF = DAG.getMachineFunction(); 1717 MachineFrameInfo &MFI = MF.getFrameInfo(); 1718 1719 if (Arg.Flags.isByVal()) { 1720 unsigned Size = Arg.Flags.getByValSize(); 1721 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1722 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1723 } 1724 1725 unsigned ArgOffset = VA.getLocMemOffset(); 1726 unsigned ArgSize = VA.getValVT().getStoreSize(); 1727 1728 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1729 1730 // Create load nodes to retrieve arguments from the stack. 1731 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1732 SDValue ArgValue; 1733 1734 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1735 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1736 MVT MemVT = VA.getValVT(); 1737 1738 switch (VA.getLocInfo()) { 1739 default: 1740 break; 1741 case CCValAssign::BCvt: 1742 MemVT = VA.getLocVT(); 1743 break; 1744 case CCValAssign::SExt: 1745 ExtType = ISD::SEXTLOAD; 1746 break; 1747 case CCValAssign::ZExt: 1748 ExtType = ISD::ZEXTLOAD; 1749 break; 1750 case CCValAssign::AExt: 1751 ExtType = ISD::EXTLOAD; 1752 break; 1753 } 1754 1755 ArgValue = DAG.getExtLoad( 1756 ExtType, SL, VA.getLocVT(), Chain, FIN, 1757 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1758 MemVT); 1759 return ArgValue; 1760 } 1761 1762 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1763 const SIMachineFunctionInfo &MFI, 1764 EVT VT, 1765 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1766 const ArgDescriptor *Reg; 1767 const TargetRegisterClass *RC; 1768 LLT Ty; 1769 1770 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1771 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1772 } 1773 1774 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1775 CallingConv::ID CallConv, 1776 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1777 FunctionType *FType, 1778 SIMachineFunctionInfo *Info) { 1779 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1780 const ISD::InputArg *Arg = &Ins[I]; 1781 1782 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1783 "vector type argument should have been split"); 1784 1785 // First check if it's a PS input addr. 1786 if (CallConv == CallingConv::AMDGPU_PS && 1787 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1788 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1789 1790 // Inconveniently only the first part of the split is marked as isSplit, 1791 // so skip to the end. We only want to increment PSInputNum once for the 1792 // entire split argument. 1793 if (Arg->Flags.isSplit()) { 1794 while (!Arg->Flags.isSplitEnd()) { 1795 assert((!Arg->VT.isVector() || 1796 Arg->VT.getScalarSizeInBits() == 16) && 1797 "unexpected vector split in ps argument type"); 1798 if (!SkipArg) 1799 Splits.push_back(*Arg); 1800 Arg = &Ins[++I]; 1801 } 1802 } 1803 1804 if (SkipArg) { 1805 // We can safely skip PS inputs. 1806 Skipped.set(Arg->getOrigArgIndex()); 1807 ++PSInputNum; 1808 continue; 1809 } 1810 1811 Info->markPSInputAllocated(PSInputNum); 1812 if (Arg->Used) 1813 Info->markPSInputEnabled(PSInputNum); 1814 1815 ++PSInputNum; 1816 } 1817 1818 Splits.push_back(*Arg); 1819 } 1820 } 1821 1822 // Allocate special inputs passed in VGPRs. 1823 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1824 MachineFunction &MF, 1825 const SIRegisterInfo &TRI, 1826 SIMachineFunctionInfo &Info) const { 1827 const LLT S32 = LLT::scalar(32); 1828 MachineRegisterInfo &MRI = MF.getRegInfo(); 1829 1830 if (Info.hasWorkItemIDX()) { 1831 Register Reg = AMDGPU::VGPR0; 1832 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1833 1834 CCInfo.AllocateReg(Reg); 1835 unsigned Mask = (Subtarget->hasPackedTID() && 1836 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 1837 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1838 } 1839 1840 if (Info.hasWorkItemIDY()) { 1841 assert(Info.hasWorkItemIDX()); 1842 if (Subtarget->hasPackedTID()) { 1843 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1844 0x3ff << 10)); 1845 } else { 1846 unsigned Reg = AMDGPU::VGPR1; 1847 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1848 1849 CCInfo.AllocateReg(Reg); 1850 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1851 } 1852 } 1853 1854 if (Info.hasWorkItemIDZ()) { 1855 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 1856 if (Subtarget->hasPackedTID()) { 1857 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1858 0x3ff << 20)); 1859 } else { 1860 unsigned Reg = AMDGPU::VGPR2; 1861 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1862 1863 CCInfo.AllocateReg(Reg); 1864 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1865 } 1866 } 1867 } 1868 1869 // Try to allocate a VGPR at the end of the argument list, or if no argument 1870 // VGPRs are left allocating a stack slot. 1871 // If \p Mask is is given it indicates bitfield position in the register. 1872 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1873 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1874 ArgDescriptor Arg = ArgDescriptor()) { 1875 if (Arg.isSet()) 1876 return ArgDescriptor::createArg(Arg, Mask); 1877 1878 ArrayRef<MCPhysReg> ArgVGPRs 1879 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1880 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1881 if (RegIdx == ArgVGPRs.size()) { 1882 // Spill to stack required. 1883 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1884 1885 return ArgDescriptor::createStack(Offset, Mask); 1886 } 1887 1888 unsigned Reg = ArgVGPRs[RegIdx]; 1889 Reg = CCInfo.AllocateReg(Reg); 1890 assert(Reg != AMDGPU::NoRegister); 1891 1892 MachineFunction &MF = CCInfo.getMachineFunction(); 1893 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1894 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1895 return ArgDescriptor::createRegister(Reg, Mask); 1896 } 1897 1898 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1899 const TargetRegisterClass *RC, 1900 unsigned NumArgRegs) { 1901 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1902 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1903 if (RegIdx == ArgSGPRs.size()) 1904 report_fatal_error("ran out of SGPRs for arguments"); 1905 1906 unsigned Reg = ArgSGPRs[RegIdx]; 1907 Reg = CCInfo.AllocateReg(Reg); 1908 assert(Reg != AMDGPU::NoRegister); 1909 1910 MachineFunction &MF = CCInfo.getMachineFunction(); 1911 MF.addLiveIn(Reg, RC); 1912 return ArgDescriptor::createRegister(Reg); 1913 } 1914 1915 // If this has a fixed position, we still should allocate the register in the 1916 // CCInfo state. Technically we could get away with this for values passed 1917 // outside of the normal argument range. 1918 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 1919 const TargetRegisterClass *RC, 1920 MCRegister Reg) { 1921 Reg = CCInfo.AllocateReg(Reg); 1922 assert(Reg != AMDGPU::NoRegister); 1923 MachineFunction &MF = CCInfo.getMachineFunction(); 1924 MF.addLiveIn(Reg, RC); 1925 } 1926 1927 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 1928 if (Arg) { 1929 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 1930 Arg.getRegister()); 1931 } else 1932 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1933 } 1934 1935 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 1936 if (Arg) { 1937 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 1938 Arg.getRegister()); 1939 } else 1940 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1941 } 1942 1943 /// Allocate implicit function VGPR arguments at the end of allocated user 1944 /// arguments. 1945 void SITargetLowering::allocateSpecialInputVGPRs( 1946 CCState &CCInfo, MachineFunction &MF, 1947 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1948 const unsigned Mask = 0x3ff; 1949 ArgDescriptor Arg; 1950 1951 if (Info.hasWorkItemIDX()) { 1952 Arg = allocateVGPR32Input(CCInfo, Mask); 1953 Info.setWorkItemIDX(Arg); 1954 } 1955 1956 if (Info.hasWorkItemIDY()) { 1957 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1958 Info.setWorkItemIDY(Arg); 1959 } 1960 1961 if (Info.hasWorkItemIDZ()) 1962 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1963 } 1964 1965 /// Allocate implicit function VGPR arguments in fixed registers. 1966 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1967 CCState &CCInfo, MachineFunction &MF, 1968 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1969 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1970 if (!Reg) 1971 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1972 1973 const unsigned Mask = 0x3ff; 1974 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1975 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1976 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1977 } 1978 1979 void SITargetLowering::allocateSpecialInputSGPRs( 1980 CCState &CCInfo, 1981 MachineFunction &MF, 1982 const SIRegisterInfo &TRI, 1983 SIMachineFunctionInfo &Info) const { 1984 auto &ArgInfo = Info.getArgInfo(); 1985 1986 // TODO: Unify handling with private memory pointers. 1987 1988 if (Info.hasDispatchPtr()) 1989 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 1990 1991 if (Info.hasQueuePtr()) 1992 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 1993 1994 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1995 // constant offset from the kernarg segment. 1996 if (Info.hasImplicitArgPtr()) 1997 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 1998 1999 if (Info.hasDispatchID()) 2000 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 2001 2002 // flat_scratch_init is not applicable for non-kernel functions. 2003 2004 if (Info.hasWorkGroupIDX()) 2005 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2006 2007 if (Info.hasWorkGroupIDY()) 2008 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2009 2010 if (Info.hasWorkGroupIDZ()) 2011 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2012 } 2013 2014 // Allocate special inputs passed in user SGPRs. 2015 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2016 MachineFunction &MF, 2017 const SIRegisterInfo &TRI, 2018 SIMachineFunctionInfo &Info) const { 2019 if (Info.hasImplicitBufferPtr()) { 2020 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2021 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2022 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2023 } 2024 2025 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2026 if (Info.hasPrivateSegmentBuffer()) { 2027 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2028 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2029 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2030 } 2031 2032 if (Info.hasDispatchPtr()) { 2033 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2034 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2035 CCInfo.AllocateReg(DispatchPtrReg); 2036 } 2037 2038 if (Info.hasQueuePtr()) { 2039 Register QueuePtrReg = Info.addQueuePtr(TRI); 2040 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2041 CCInfo.AllocateReg(QueuePtrReg); 2042 } 2043 2044 if (Info.hasKernargSegmentPtr()) { 2045 MachineRegisterInfo &MRI = MF.getRegInfo(); 2046 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2047 CCInfo.AllocateReg(InputPtrReg); 2048 2049 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2050 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2051 } 2052 2053 if (Info.hasDispatchID()) { 2054 Register DispatchIDReg = Info.addDispatchID(TRI); 2055 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2056 CCInfo.AllocateReg(DispatchIDReg); 2057 } 2058 2059 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2060 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2061 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2062 CCInfo.AllocateReg(FlatScratchInitReg); 2063 } 2064 2065 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2066 // these from the dispatch pointer. 2067 } 2068 2069 // Allocate special input registers that are initialized per-wave. 2070 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2071 MachineFunction &MF, 2072 SIMachineFunctionInfo &Info, 2073 CallingConv::ID CallConv, 2074 bool IsShader) const { 2075 if (Info.hasWorkGroupIDX()) { 2076 Register Reg = Info.addWorkGroupIDX(); 2077 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2078 CCInfo.AllocateReg(Reg); 2079 } 2080 2081 if (Info.hasWorkGroupIDY()) { 2082 Register Reg = Info.addWorkGroupIDY(); 2083 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2084 CCInfo.AllocateReg(Reg); 2085 } 2086 2087 if (Info.hasWorkGroupIDZ()) { 2088 Register Reg = Info.addWorkGroupIDZ(); 2089 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2090 CCInfo.AllocateReg(Reg); 2091 } 2092 2093 if (Info.hasWorkGroupInfo()) { 2094 Register Reg = Info.addWorkGroupInfo(); 2095 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2096 CCInfo.AllocateReg(Reg); 2097 } 2098 2099 if (Info.hasPrivateSegmentWaveByteOffset()) { 2100 // Scratch wave offset passed in system SGPR. 2101 unsigned PrivateSegmentWaveByteOffsetReg; 2102 2103 if (IsShader) { 2104 PrivateSegmentWaveByteOffsetReg = 2105 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2106 2107 // This is true if the scratch wave byte offset doesn't have a fixed 2108 // location. 2109 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2110 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2111 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2112 } 2113 } else 2114 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2115 2116 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2117 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2118 } 2119 } 2120 2121 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2122 MachineFunction &MF, 2123 const SIRegisterInfo &TRI, 2124 SIMachineFunctionInfo &Info) { 2125 // Now that we've figured out where the scratch register inputs are, see if 2126 // should reserve the arguments and use them directly. 2127 MachineFrameInfo &MFI = MF.getFrameInfo(); 2128 bool HasStackObjects = MFI.hasStackObjects(); 2129 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2130 2131 // Record that we know we have non-spill stack objects so we don't need to 2132 // check all stack objects later. 2133 if (HasStackObjects) 2134 Info.setHasNonSpillStackObjects(true); 2135 2136 // Everything live out of a block is spilled with fast regalloc, so it's 2137 // almost certain that spilling will be required. 2138 if (TM.getOptLevel() == CodeGenOpt::None) 2139 HasStackObjects = true; 2140 2141 // For now assume stack access is needed in any callee functions, so we need 2142 // the scratch registers to pass in. 2143 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2144 2145 if (!ST.enableFlatScratch()) { 2146 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2147 // If we have stack objects, we unquestionably need the private buffer 2148 // resource. For the Code Object V2 ABI, this will be the first 4 user 2149 // SGPR inputs. We can reserve those and use them directly. 2150 2151 Register PrivateSegmentBufferReg = 2152 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2153 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2154 } else { 2155 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2156 // We tentatively reserve the last registers (skipping the last registers 2157 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2158 // we'll replace these with the ones immediately after those which were 2159 // really allocated. In the prologue copies will be inserted from the 2160 // argument to these reserved registers. 2161 2162 // Without HSA, relocations are used for the scratch pointer and the 2163 // buffer resource setup is always inserted in the prologue. Scratch wave 2164 // offset is still in an input SGPR. 2165 Info.setScratchRSrcReg(ReservedBufferReg); 2166 } 2167 } 2168 2169 MachineRegisterInfo &MRI = MF.getRegInfo(); 2170 2171 // For entry functions we have to set up the stack pointer if we use it, 2172 // whereas non-entry functions get this "for free". This means there is no 2173 // intrinsic advantage to using S32 over S34 in cases where we do not have 2174 // calls but do need a frame pointer (i.e. if we are requested to have one 2175 // because frame pointer elimination is disabled). To keep things simple we 2176 // only ever use S32 as the call ABI stack pointer, and so using it does not 2177 // imply we need a separate frame pointer. 2178 // 2179 // Try to use s32 as the SP, but move it if it would interfere with input 2180 // arguments. This won't work with calls though. 2181 // 2182 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2183 // registers. 2184 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2185 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2186 } else { 2187 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2188 2189 if (MFI.hasCalls()) 2190 report_fatal_error("call in graphics shader with too many input SGPRs"); 2191 2192 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2193 if (!MRI.isLiveIn(Reg)) { 2194 Info.setStackPtrOffsetReg(Reg); 2195 break; 2196 } 2197 } 2198 2199 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2200 report_fatal_error("failed to find register for SP"); 2201 } 2202 2203 // hasFP should be accurate for entry functions even before the frame is 2204 // finalized, because it does not rely on the known stack size, only 2205 // properties like whether variable sized objects are present. 2206 if (ST.getFrameLowering()->hasFP(MF)) { 2207 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2208 } 2209 } 2210 2211 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2212 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2213 return !Info->isEntryFunction(); 2214 } 2215 2216 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2217 2218 } 2219 2220 void SITargetLowering::insertCopiesSplitCSR( 2221 MachineBasicBlock *Entry, 2222 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2223 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2224 2225 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2226 if (!IStart) 2227 return; 2228 2229 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2230 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2231 MachineBasicBlock::iterator MBBI = Entry->begin(); 2232 for (const MCPhysReg *I = IStart; *I; ++I) { 2233 const TargetRegisterClass *RC = nullptr; 2234 if (AMDGPU::SReg_64RegClass.contains(*I)) 2235 RC = &AMDGPU::SGPR_64RegClass; 2236 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2237 RC = &AMDGPU::SGPR_32RegClass; 2238 else 2239 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2240 2241 Register NewVR = MRI->createVirtualRegister(RC); 2242 // Create copy from CSR to a virtual register. 2243 Entry->addLiveIn(*I); 2244 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2245 .addReg(*I); 2246 2247 // Insert the copy-back instructions right before the terminator. 2248 for (auto *Exit : Exits) 2249 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2250 TII->get(TargetOpcode::COPY), *I) 2251 .addReg(NewVR); 2252 } 2253 } 2254 2255 SDValue SITargetLowering::LowerFormalArguments( 2256 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2257 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2258 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2259 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2260 2261 MachineFunction &MF = DAG.getMachineFunction(); 2262 const Function &Fn = MF.getFunction(); 2263 FunctionType *FType = MF.getFunction().getFunctionType(); 2264 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2265 2266 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2267 DiagnosticInfoUnsupported NoGraphicsHSA( 2268 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2269 DAG.getContext()->diagnose(NoGraphicsHSA); 2270 return DAG.getEntryNode(); 2271 } 2272 2273 Info->allocateModuleLDSGlobal(Fn.getParent()); 2274 2275 SmallVector<ISD::InputArg, 16> Splits; 2276 SmallVector<CCValAssign, 16> ArgLocs; 2277 BitVector Skipped(Ins.size()); 2278 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2279 *DAG.getContext()); 2280 2281 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2282 bool IsKernel = AMDGPU::isKernel(CallConv); 2283 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2284 2285 if (IsGraphics) { 2286 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2287 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2288 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2289 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2290 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2291 !Info->hasWorkItemIDZ()); 2292 } 2293 2294 if (CallConv == CallingConv::AMDGPU_PS) { 2295 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2296 2297 // At least one interpolation mode must be enabled or else the GPU will 2298 // hang. 2299 // 2300 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2301 // set PSInputAddr, the user wants to enable some bits after the compilation 2302 // based on run-time states. Since we can't know what the final PSInputEna 2303 // will look like, so we shouldn't do anything here and the user should take 2304 // responsibility for the correct programming. 2305 // 2306 // Otherwise, the following restrictions apply: 2307 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2308 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2309 // enabled too. 2310 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2311 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2312 CCInfo.AllocateReg(AMDGPU::VGPR0); 2313 CCInfo.AllocateReg(AMDGPU::VGPR1); 2314 Info->markPSInputAllocated(0); 2315 Info->markPSInputEnabled(0); 2316 } 2317 if (Subtarget->isAmdPalOS()) { 2318 // For isAmdPalOS, the user does not enable some bits after compilation 2319 // based on run-time states; the register values being generated here are 2320 // the final ones set in hardware. Therefore we need to apply the 2321 // workaround to PSInputAddr and PSInputEnable together. (The case where 2322 // a bit is set in PSInputAddr but not PSInputEnable is where the 2323 // frontend set up an input arg for a particular interpolation mode, but 2324 // nothing uses that input arg. Really we should have an earlier pass 2325 // that removes such an arg.) 2326 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2327 if ((PsInputBits & 0x7F) == 0 || 2328 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2329 Info->markPSInputEnabled( 2330 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2331 } 2332 } else if (IsKernel) { 2333 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2334 } else { 2335 Splits.append(Ins.begin(), Ins.end()); 2336 } 2337 2338 if (IsEntryFunc) { 2339 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2340 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2341 } else { 2342 // For the fixed ABI, pass workitem IDs in the last argument register. 2343 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2344 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2345 } 2346 2347 if (IsKernel) { 2348 analyzeFormalArgumentsCompute(CCInfo, Ins); 2349 } else { 2350 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2351 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2352 } 2353 2354 SmallVector<SDValue, 16> Chains; 2355 2356 // FIXME: This is the minimum kernel argument alignment. We should improve 2357 // this to the maximum alignment of the arguments. 2358 // 2359 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2360 // kern arg offset. 2361 const Align KernelArgBaseAlign = Align(16); 2362 2363 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2364 const ISD::InputArg &Arg = Ins[i]; 2365 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2366 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2367 continue; 2368 } 2369 2370 CCValAssign &VA = ArgLocs[ArgIdx++]; 2371 MVT VT = VA.getLocVT(); 2372 2373 if (IsEntryFunc && VA.isMemLoc()) { 2374 VT = Ins[i].VT; 2375 EVT MemVT = VA.getLocVT(); 2376 2377 const uint64_t Offset = VA.getLocMemOffset(); 2378 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2379 2380 if (Arg.Flags.isByRef()) { 2381 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2382 2383 const GCNTargetMachine &TM = 2384 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2385 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2386 Arg.Flags.getPointerAddrSpace())) { 2387 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2388 Arg.Flags.getPointerAddrSpace()); 2389 } 2390 2391 InVals.push_back(Ptr); 2392 continue; 2393 } 2394 2395 SDValue Arg = lowerKernargMemParameter( 2396 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2397 Chains.push_back(Arg.getValue(1)); 2398 2399 auto *ParamTy = 2400 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2401 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2402 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2403 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2404 // On SI local pointers are just offsets into LDS, so they are always 2405 // less than 16-bits. On CI and newer they could potentially be 2406 // real pointers, so we can't guarantee their size. 2407 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2408 DAG.getValueType(MVT::i16)); 2409 } 2410 2411 InVals.push_back(Arg); 2412 continue; 2413 } else if (!IsEntryFunc && VA.isMemLoc()) { 2414 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2415 InVals.push_back(Val); 2416 if (!Arg.Flags.isByVal()) 2417 Chains.push_back(Val.getValue(1)); 2418 continue; 2419 } 2420 2421 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2422 2423 Register Reg = VA.getLocReg(); 2424 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2425 EVT ValVT = VA.getValVT(); 2426 2427 Reg = MF.addLiveIn(Reg, RC); 2428 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2429 2430 if (Arg.Flags.isSRet()) { 2431 // The return object should be reasonably addressable. 2432 2433 // FIXME: This helps when the return is a real sret. If it is a 2434 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2435 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2436 unsigned NumBits 2437 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2438 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2439 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2440 } 2441 2442 // If this is an 8 or 16-bit value, it is really passed promoted 2443 // to 32 bits. Insert an assert[sz]ext to capture this, then 2444 // truncate to the right size. 2445 switch (VA.getLocInfo()) { 2446 case CCValAssign::Full: 2447 break; 2448 case CCValAssign::BCvt: 2449 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2450 break; 2451 case CCValAssign::SExt: 2452 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2453 DAG.getValueType(ValVT)); 2454 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2455 break; 2456 case CCValAssign::ZExt: 2457 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2458 DAG.getValueType(ValVT)); 2459 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2460 break; 2461 case CCValAssign::AExt: 2462 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2463 break; 2464 default: 2465 llvm_unreachable("Unknown loc info!"); 2466 } 2467 2468 InVals.push_back(Val); 2469 } 2470 2471 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2472 // Special inputs come after user arguments. 2473 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2474 } 2475 2476 // Start adding system SGPRs. 2477 if (IsEntryFunc) { 2478 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2479 } else { 2480 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2481 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2482 } 2483 2484 auto &ArgUsageInfo = 2485 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2486 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2487 2488 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2489 Info->setBytesInStackArgArea(StackArgSize); 2490 2491 return Chains.empty() ? Chain : 2492 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2493 } 2494 2495 // TODO: If return values can't fit in registers, we should return as many as 2496 // possible in registers before passing on stack. 2497 bool SITargetLowering::CanLowerReturn( 2498 CallingConv::ID CallConv, 2499 MachineFunction &MF, bool IsVarArg, 2500 const SmallVectorImpl<ISD::OutputArg> &Outs, 2501 LLVMContext &Context) const { 2502 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2503 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2504 // for shaders. Vector types should be explicitly handled by CC. 2505 if (AMDGPU::isEntryFunctionCC(CallConv)) 2506 return true; 2507 2508 SmallVector<CCValAssign, 16> RVLocs; 2509 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2510 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2511 } 2512 2513 SDValue 2514 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2515 bool isVarArg, 2516 const SmallVectorImpl<ISD::OutputArg> &Outs, 2517 const SmallVectorImpl<SDValue> &OutVals, 2518 const SDLoc &DL, SelectionDAG &DAG) const { 2519 MachineFunction &MF = DAG.getMachineFunction(); 2520 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2521 2522 if (AMDGPU::isKernel(CallConv)) { 2523 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2524 OutVals, DL, DAG); 2525 } 2526 2527 bool IsShader = AMDGPU::isShader(CallConv); 2528 2529 Info->setIfReturnsVoid(Outs.empty()); 2530 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2531 2532 // CCValAssign - represent the assignment of the return value to a location. 2533 SmallVector<CCValAssign, 48> RVLocs; 2534 SmallVector<ISD::OutputArg, 48> Splits; 2535 2536 // CCState - Info about the registers and stack slots. 2537 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2538 *DAG.getContext()); 2539 2540 // Analyze outgoing return values. 2541 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2542 2543 SDValue Flag; 2544 SmallVector<SDValue, 48> RetOps; 2545 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2546 2547 // Add return address for callable functions. 2548 if (!Info->isEntryFunction()) { 2549 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2550 SDValue ReturnAddrReg = CreateLiveInRegister( 2551 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2552 2553 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2554 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2555 MVT::i64); 2556 Chain = 2557 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2558 Flag = Chain.getValue(1); 2559 RetOps.push_back(ReturnAddrVirtualReg); 2560 } 2561 2562 // Copy the result values into the output registers. 2563 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2564 ++I, ++RealRVLocIdx) { 2565 CCValAssign &VA = RVLocs[I]; 2566 assert(VA.isRegLoc() && "Can only return in registers!"); 2567 // TODO: Partially return in registers if return values don't fit. 2568 SDValue Arg = OutVals[RealRVLocIdx]; 2569 2570 // Copied from other backends. 2571 switch (VA.getLocInfo()) { 2572 case CCValAssign::Full: 2573 break; 2574 case CCValAssign::BCvt: 2575 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2576 break; 2577 case CCValAssign::SExt: 2578 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2579 break; 2580 case CCValAssign::ZExt: 2581 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2582 break; 2583 case CCValAssign::AExt: 2584 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2585 break; 2586 default: 2587 llvm_unreachable("Unknown loc info!"); 2588 } 2589 2590 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2591 Flag = Chain.getValue(1); 2592 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2593 } 2594 2595 // FIXME: Does sret work properly? 2596 if (!Info->isEntryFunction()) { 2597 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2598 const MCPhysReg *I = 2599 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2600 if (I) { 2601 for (; *I; ++I) { 2602 if (AMDGPU::SReg_64RegClass.contains(*I)) 2603 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2604 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2605 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2606 else 2607 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2608 } 2609 } 2610 } 2611 2612 // Update chain and glue. 2613 RetOps[0] = Chain; 2614 if (Flag.getNode()) 2615 RetOps.push_back(Flag); 2616 2617 unsigned Opc = AMDGPUISD::ENDPGM; 2618 if (!IsWaveEnd) 2619 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2620 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2621 } 2622 2623 SDValue SITargetLowering::LowerCallResult( 2624 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2625 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2626 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2627 SDValue ThisVal) const { 2628 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2629 2630 // Assign locations to each value returned by this call. 2631 SmallVector<CCValAssign, 16> RVLocs; 2632 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2633 *DAG.getContext()); 2634 CCInfo.AnalyzeCallResult(Ins, RetCC); 2635 2636 // Copy all of the result registers out of their specified physreg. 2637 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2638 CCValAssign VA = RVLocs[i]; 2639 SDValue Val; 2640 2641 if (VA.isRegLoc()) { 2642 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2643 Chain = Val.getValue(1); 2644 InFlag = Val.getValue(2); 2645 } else if (VA.isMemLoc()) { 2646 report_fatal_error("TODO: return values in memory"); 2647 } else 2648 llvm_unreachable("unknown argument location type"); 2649 2650 switch (VA.getLocInfo()) { 2651 case CCValAssign::Full: 2652 break; 2653 case CCValAssign::BCvt: 2654 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2655 break; 2656 case CCValAssign::ZExt: 2657 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2658 DAG.getValueType(VA.getValVT())); 2659 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2660 break; 2661 case CCValAssign::SExt: 2662 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2663 DAG.getValueType(VA.getValVT())); 2664 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2665 break; 2666 case CCValAssign::AExt: 2667 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2668 break; 2669 default: 2670 llvm_unreachable("Unknown loc info!"); 2671 } 2672 2673 InVals.push_back(Val); 2674 } 2675 2676 return Chain; 2677 } 2678 2679 // Add code to pass special inputs required depending on used features separate 2680 // from the explicit user arguments present in the IR. 2681 void SITargetLowering::passSpecialInputs( 2682 CallLoweringInfo &CLI, 2683 CCState &CCInfo, 2684 const SIMachineFunctionInfo &Info, 2685 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2686 SmallVectorImpl<SDValue> &MemOpChains, 2687 SDValue Chain) const { 2688 // If we don't have a call site, this was a call inserted by 2689 // legalization. These can never use special inputs. 2690 if (!CLI.CB) 2691 return; 2692 2693 SelectionDAG &DAG = CLI.DAG; 2694 const SDLoc &DL = CLI.DL; 2695 2696 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2697 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2698 2699 const AMDGPUFunctionArgInfo *CalleeArgInfo 2700 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2701 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2702 auto &ArgUsageInfo = 2703 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2704 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2705 } 2706 2707 // TODO: Unify with private memory register handling. This is complicated by 2708 // the fact that at least in kernels, the input argument is not necessarily 2709 // in the same location as the input. 2710 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2711 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2712 AMDGPUFunctionArgInfo::QUEUE_PTR, 2713 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2714 AMDGPUFunctionArgInfo::DISPATCH_ID, 2715 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2716 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2717 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2718 }; 2719 2720 for (auto InputID : InputRegs) { 2721 const ArgDescriptor *OutgoingArg; 2722 const TargetRegisterClass *ArgRC; 2723 LLT ArgTy; 2724 2725 std::tie(OutgoingArg, ArgRC, ArgTy) = 2726 CalleeArgInfo->getPreloadedValue(InputID); 2727 if (!OutgoingArg) 2728 continue; 2729 2730 const ArgDescriptor *IncomingArg; 2731 const TargetRegisterClass *IncomingArgRC; 2732 LLT Ty; 2733 std::tie(IncomingArg, IncomingArgRC, Ty) = 2734 CallerArgInfo.getPreloadedValue(InputID); 2735 assert(IncomingArgRC == ArgRC); 2736 2737 // All special arguments are ints for now. 2738 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2739 SDValue InputReg; 2740 2741 if (IncomingArg) { 2742 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2743 } else { 2744 // The implicit arg ptr is special because it doesn't have a corresponding 2745 // input for kernels, and is computed from the kernarg segment pointer. 2746 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2747 InputReg = getImplicitArgPtr(DAG, DL); 2748 } 2749 2750 if (OutgoingArg->isRegister()) { 2751 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2752 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2753 report_fatal_error("failed to allocate implicit input argument"); 2754 } else { 2755 unsigned SpecialArgOffset = 2756 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2757 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2758 SpecialArgOffset); 2759 MemOpChains.push_back(ArgStore); 2760 } 2761 } 2762 2763 // Pack workitem IDs into a single register or pass it as is if already 2764 // packed. 2765 const ArgDescriptor *OutgoingArg; 2766 const TargetRegisterClass *ArgRC; 2767 LLT Ty; 2768 2769 std::tie(OutgoingArg, ArgRC, Ty) = 2770 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2771 if (!OutgoingArg) 2772 std::tie(OutgoingArg, ArgRC, Ty) = 2773 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2774 if (!OutgoingArg) 2775 std::tie(OutgoingArg, ArgRC, Ty) = 2776 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2777 if (!OutgoingArg) 2778 return; 2779 2780 const ArgDescriptor *IncomingArgX = std::get<0>( 2781 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2782 const ArgDescriptor *IncomingArgY = std::get<0>( 2783 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2784 const ArgDescriptor *IncomingArgZ = std::get<0>( 2785 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2786 2787 SDValue InputReg; 2788 SDLoc SL; 2789 2790 // If incoming ids are not packed we need to pack them. 2791 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2792 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2793 2794 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2795 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2796 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2797 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2798 InputReg = InputReg.getNode() ? 2799 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2800 } 2801 2802 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2803 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2804 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2805 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2806 InputReg = InputReg.getNode() ? 2807 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2808 } 2809 2810 if (!InputReg.getNode()) { 2811 // Workitem ids are already packed, any of present incoming arguments 2812 // will carry all required fields. 2813 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2814 IncomingArgX ? *IncomingArgX : 2815 IncomingArgY ? *IncomingArgY : 2816 *IncomingArgZ, ~0u); 2817 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2818 } 2819 2820 if (OutgoingArg->isRegister()) { 2821 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2822 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2823 } else { 2824 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2825 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2826 SpecialArgOffset); 2827 MemOpChains.push_back(ArgStore); 2828 } 2829 } 2830 2831 static bool canGuaranteeTCO(CallingConv::ID CC) { 2832 return CC == CallingConv::Fast; 2833 } 2834 2835 /// Return true if we might ever do TCO for calls with this calling convention. 2836 static bool mayTailCallThisCC(CallingConv::ID CC) { 2837 switch (CC) { 2838 case CallingConv::C: 2839 case CallingConv::AMDGPU_Gfx: 2840 return true; 2841 default: 2842 return canGuaranteeTCO(CC); 2843 } 2844 } 2845 2846 bool SITargetLowering::isEligibleForTailCallOptimization( 2847 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2848 const SmallVectorImpl<ISD::OutputArg> &Outs, 2849 const SmallVectorImpl<SDValue> &OutVals, 2850 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2851 if (!mayTailCallThisCC(CalleeCC)) 2852 return false; 2853 2854 // For a divergent call target, we need to do a waterfall loop over the 2855 // possible callees which precludes us from using a simple jump. 2856 if (Callee->isDivergent()) 2857 return false; 2858 2859 MachineFunction &MF = DAG.getMachineFunction(); 2860 const Function &CallerF = MF.getFunction(); 2861 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2862 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2863 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2864 2865 // Kernels aren't callable, and don't have a live in return address so it 2866 // doesn't make sense to do a tail call with entry functions. 2867 if (!CallerPreserved) 2868 return false; 2869 2870 bool CCMatch = CallerCC == CalleeCC; 2871 2872 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2873 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2874 return true; 2875 return false; 2876 } 2877 2878 // TODO: Can we handle var args? 2879 if (IsVarArg) 2880 return false; 2881 2882 for (const Argument &Arg : CallerF.args()) { 2883 if (Arg.hasByValAttr()) 2884 return false; 2885 } 2886 2887 LLVMContext &Ctx = *DAG.getContext(); 2888 2889 // Check that the call results are passed in the same way. 2890 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2891 CCAssignFnForCall(CalleeCC, IsVarArg), 2892 CCAssignFnForCall(CallerCC, IsVarArg))) 2893 return false; 2894 2895 // The callee has to preserve all registers the caller needs to preserve. 2896 if (!CCMatch) { 2897 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2898 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2899 return false; 2900 } 2901 2902 // Nothing more to check if the callee is taking no arguments. 2903 if (Outs.empty()) 2904 return true; 2905 2906 SmallVector<CCValAssign, 16> ArgLocs; 2907 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2908 2909 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2910 2911 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2912 // If the stack arguments for this call do not fit into our own save area then 2913 // the call cannot be made tail. 2914 // TODO: Is this really necessary? 2915 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2916 return false; 2917 2918 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2919 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2920 } 2921 2922 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2923 if (!CI->isTailCall()) 2924 return false; 2925 2926 const Function *ParentFn = CI->getParent()->getParent(); 2927 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2928 return false; 2929 return true; 2930 } 2931 2932 // The wave scratch offset register is used as the global base pointer. 2933 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2934 SmallVectorImpl<SDValue> &InVals) const { 2935 SelectionDAG &DAG = CLI.DAG; 2936 const SDLoc &DL = CLI.DL; 2937 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2938 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2939 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2940 SDValue Chain = CLI.Chain; 2941 SDValue Callee = CLI.Callee; 2942 bool &IsTailCall = CLI.IsTailCall; 2943 CallingConv::ID CallConv = CLI.CallConv; 2944 bool IsVarArg = CLI.IsVarArg; 2945 bool IsSibCall = false; 2946 bool IsThisReturn = false; 2947 MachineFunction &MF = DAG.getMachineFunction(); 2948 2949 if (Callee.isUndef() || isNullConstant(Callee)) { 2950 if (!CLI.IsTailCall) { 2951 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2952 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2953 } 2954 2955 return Chain; 2956 } 2957 2958 if (IsVarArg) { 2959 return lowerUnhandledCall(CLI, InVals, 2960 "unsupported call to variadic function "); 2961 } 2962 2963 if (!CLI.CB) 2964 report_fatal_error("unsupported libcall legalization"); 2965 2966 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2967 return lowerUnhandledCall(CLI, InVals, 2968 "unsupported required tail call to function "); 2969 } 2970 2971 if (AMDGPU::isShader(CallConv)) { 2972 // Note the issue is with the CC of the called function, not of the call 2973 // itself. 2974 return lowerUnhandledCall(CLI, InVals, 2975 "unsupported call to a shader function "); 2976 } 2977 2978 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 2979 CallConv != CallingConv::AMDGPU_Gfx) { 2980 // Only allow calls with specific calling conventions. 2981 return lowerUnhandledCall(CLI, InVals, 2982 "unsupported calling convention for call from " 2983 "graphics shader of function "); 2984 } 2985 2986 if (IsTailCall) { 2987 IsTailCall = isEligibleForTailCallOptimization( 2988 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2989 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2990 report_fatal_error("failed to perform tail call elimination on a call " 2991 "site marked musttail"); 2992 } 2993 2994 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2995 2996 // A sibling call is one where we're under the usual C ABI and not planning 2997 // to change that but can still do a tail call: 2998 if (!TailCallOpt && IsTailCall) 2999 IsSibCall = true; 3000 3001 if (IsTailCall) 3002 ++NumTailCalls; 3003 } 3004 3005 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3006 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3007 SmallVector<SDValue, 8> MemOpChains; 3008 3009 // Analyze operands of the call, assigning locations to each operand. 3010 SmallVector<CCValAssign, 16> ArgLocs; 3011 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3012 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3013 3014 if (AMDGPUTargetMachine::EnableFixedFunctionABI && 3015 CallConv != CallingConv::AMDGPU_Gfx) { 3016 // With a fixed ABI, allocate fixed registers before user arguments. 3017 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3018 } 3019 3020 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3021 3022 // Get a count of how many bytes are to be pushed on the stack. 3023 unsigned NumBytes = CCInfo.getNextStackOffset(); 3024 3025 if (IsSibCall) { 3026 // Since we're not changing the ABI to make this a tail call, the memory 3027 // operands are already available in the caller's incoming argument space. 3028 NumBytes = 0; 3029 } 3030 3031 // FPDiff is the byte offset of the call's argument area from the callee's. 3032 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3033 // by this amount for a tail call. In a sibling call it must be 0 because the 3034 // caller will deallocate the entire stack and the callee still expects its 3035 // arguments to begin at SP+0. Completely unused for non-tail calls. 3036 int32_t FPDiff = 0; 3037 MachineFrameInfo &MFI = MF.getFrameInfo(); 3038 3039 // Adjust the stack pointer for the new arguments... 3040 // These operations are automatically eliminated by the prolog/epilog pass 3041 if (!IsSibCall) { 3042 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3043 3044 if (!Subtarget->enableFlatScratch()) { 3045 SmallVector<SDValue, 4> CopyFromChains; 3046 3047 // In the HSA case, this should be an identity copy. 3048 SDValue ScratchRSrcReg 3049 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3050 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3051 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3052 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3053 } 3054 } 3055 3056 MVT PtrVT = MVT::i32; 3057 3058 // Walk the register/memloc assignments, inserting copies/loads. 3059 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3060 CCValAssign &VA = ArgLocs[i]; 3061 SDValue Arg = OutVals[i]; 3062 3063 // Promote the value if needed. 3064 switch (VA.getLocInfo()) { 3065 case CCValAssign::Full: 3066 break; 3067 case CCValAssign::BCvt: 3068 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3069 break; 3070 case CCValAssign::ZExt: 3071 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3072 break; 3073 case CCValAssign::SExt: 3074 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3075 break; 3076 case CCValAssign::AExt: 3077 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3078 break; 3079 case CCValAssign::FPExt: 3080 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3081 break; 3082 default: 3083 llvm_unreachable("Unknown loc info!"); 3084 } 3085 3086 if (VA.isRegLoc()) { 3087 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3088 } else { 3089 assert(VA.isMemLoc()); 3090 3091 SDValue DstAddr; 3092 MachinePointerInfo DstInfo; 3093 3094 unsigned LocMemOffset = VA.getLocMemOffset(); 3095 int32_t Offset = LocMemOffset; 3096 3097 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3098 MaybeAlign Alignment; 3099 3100 if (IsTailCall) { 3101 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3102 unsigned OpSize = Flags.isByVal() ? 3103 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3104 3105 // FIXME: We can have better than the minimum byval required alignment. 3106 Alignment = 3107 Flags.isByVal() 3108 ? Flags.getNonZeroByValAlign() 3109 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3110 3111 Offset = Offset + FPDiff; 3112 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3113 3114 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3115 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3116 3117 // Make sure any stack arguments overlapping with where we're storing 3118 // are loaded before this eventual operation. Otherwise they'll be 3119 // clobbered. 3120 3121 // FIXME: Why is this really necessary? This seems to just result in a 3122 // lot of code to copy the stack and write them back to the same 3123 // locations, which are supposed to be immutable? 3124 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3125 } else { 3126 DstAddr = PtrOff; 3127 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3128 Alignment = 3129 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3130 } 3131 3132 if (Outs[i].Flags.isByVal()) { 3133 SDValue SizeNode = 3134 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3135 SDValue Cpy = 3136 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3137 Outs[i].Flags.getNonZeroByValAlign(), 3138 /*isVol = */ false, /*AlwaysInline = */ true, 3139 /*isTailCall = */ false, DstInfo, 3140 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3141 3142 MemOpChains.push_back(Cpy); 3143 } else { 3144 SDValue Store = 3145 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3146 MemOpChains.push_back(Store); 3147 } 3148 } 3149 } 3150 3151 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 3152 CallConv != CallingConv::AMDGPU_Gfx) { 3153 // Copy special input registers after user input arguments. 3154 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3155 } 3156 3157 if (!MemOpChains.empty()) 3158 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3159 3160 // Build a sequence of copy-to-reg nodes chained together with token chain 3161 // and flag operands which copy the outgoing args into the appropriate regs. 3162 SDValue InFlag; 3163 for (auto &RegToPass : RegsToPass) { 3164 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3165 RegToPass.second, InFlag); 3166 InFlag = Chain.getValue(1); 3167 } 3168 3169 3170 SDValue PhysReturnAddrReg; 3171 if (IsTailCall) { 3172 // Since the return is being combined with the call, we need to pass on the 3173 // return address. 3174 3175 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3176 SDValue ReturnAddrReg = CreateLiveInRegister( 3177 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3178 3179 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3180 MVT::i64); 3181 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3182 InFlag = Chain.getValue(1); 3183 } 3184 3185 // We don't usually want to end the call-sequence here because we would tidy 3186 // the frame up *after* the call, however in the ABI-changing tail-call case 3187 // we've carefully laid out the parameters so that when sp is reset they'll be 3188 // in the correct location. 3189 if (IsTailCall && !IsSibCall) { 3190 Chain = DAG.getCALLSEQ_END(Chain, 3191 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3192 DAG.getTargetConstant(0, DL, MVT::i32), 3193 InFlag, DL); 3194 InFlag = Chain.getValue(1); 3195 } 3196 3197 std::vector<SDValue> Ops; 3198 Ops.push_back(Chain); 3199 Ops.push_back(Callee); 3200 // Add a redundant copy of the callee global which will not be legalized, as 3201 // we need direct access to the callee later. 3202 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3203 const GlobalValue *GV = GSD->getGlobal(); 3204 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3205 } else { 3206 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3207 } 3208 3209 if (IsTailCall) { 3210 // Each tail call may have to adjust the stack by a different amount, so 3211 // this information must travel along with the operation for eventual 3212 // consumption by emitEpilogue. 3213 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3214 3215 Ops.push_back(PhysReturnAddrReg); 3216 } 3217 3218 // Add argument registers to the end of the list so that they are known live 3219 // into the call. 3220 for (auto &RegToPass : RegsToPass) { 3221 Ops.push_back(DAG.getRegister(RegToPass.first, 3222 RegToPass.second.getValueType())); 3223 } 3224 3225 // Add a register mask operand representing the call-preserved registers. 3226 3227 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3228 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3229 assert(Mask && "Missing call preserved mask for calling convention"); 3230 Ops.push_back(DAG.getRegisterMask(Mask)); 3231 3232 if (InFlag.getNode()) 3233 Ops.push_back(InFlag); 3234 3235 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3236 3237 // If we're doing a tall call, use a TC_RETURN here rather than an 3238 // actual call instruction. 3239 if (IsTailCall) { 3240 MFI.setHasTailCall(); 3241 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3242 } 3243 3244 // Returns a chain and a flag for retval copy to use. 3245 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3246 Chain = Call.getValue(0); 3247 InFlag = Call.getValue(1); 3248 3249 uint64_t CalleePopBytes = NumBytes; 3250 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3251 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3252 InFlag, DL); 3253 if (!Ins.empty()) 3254 InFlag = Chain.getValue(1); 3255 3256 // Handle result values, copying them out of physregs into vregs that we 3257 // return. 3258 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3259 InVals, IsThisReturn, 3260 IsThisReturn ? OutVals[0] : SDValue()); 3261 } 3262 3263 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3264 // except for applying the wave size scale to the increment amount. 3265 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3266 SDValue Op, SelectionDAG &DAG) const { 3267 const MachineFunction &MF = DAG.getMachineFunction(); 3268 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3269 3270 SDLoc dl(Op); 3271 EVT VT = Op.getValueType(); 3272 SDValue Tmp1 = Op; 3273 SDValue Tmp2 = Op.getValue(1); 3274 SDValue Tmp3 = Op.getOperand(2); 3275 SDValue Chain = Tmp1.getOperand(0); 3276 3277 Register SPReg = Info->getStackPtrOffsetReg(); 3278 3279 // Chain the dynamic stack allocation so that it doesn't modify the stack 3280 // pointer when other instructions are using the stack. 3281 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3282 3283 SDValue Size = Tmp2.getOperand(1); 3284 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3285 Chain = SP.getValue(1); 3286 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3287 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3288 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3289 unsigned Opc = 3290 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3291 ISD::ADD : ISD::SUB; 3292 3293 SDValue ScaledSize = DAG.getNode( 3294 ISD::SHL, dl, VT, Size, 3295 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3296 3297 Align StackAlign = TFL->getStackAlign(); 3298 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3299 if (Alignment && *Alignment > StackAlign) { 3300 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3301 DAG.getConstant(-(uint64_t)Alignment->value() 3302 << ST.getWavefrontSizeLog2(), 3303 dl, VT)); 3304 } 3305 3306 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3307 Tmp2 = DAG.getCALLSEQ_END( 3308 Chain, DAG.getIntPtrConstant(0, dl, true), 3309 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3310 3311 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3312 } 3313 3314 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3315 SelectionDAG &DAG) const { 3316 // We only handle constant sizes here to allow non-entry block, static sized 3317 // allocas. A truly dynamic value is more difficult to support because we 3318 // don't know if the size value is uniform or not. If the size isn't uniform, 3319 // we would need to do a wave reduction to get the maximum size to know how 3320 // much to increment the uniform stack pointer. 3321 SDValue Size = Op.getOperand(1); 3322 if (isa<ConstantSDNode>(Size)) 3323 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3324 3325 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3326 } 3327 3328 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3329 const MachineFunction &MF) const { 3330 Register Reg = StringSwitch<Register>(RegName) 3331 .Case("m0", AMDGPU::M0) 3332 .Case("exec", AMDGPU::EXEC) 3333 .Case("exec_lo", AMDGPU::EXEC_LO) 3334 .Case("exec_hi", AMDGPU::EXEC_HI) 3335 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3336 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3337 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3338 .Default(Register()); 3339 3340 if (Reg == AMDGPU::NoRegister) { 3341 report_fatal_error(Twine("invalid register name \"" 3342 + StringRef(RegName) + "\".")); 3343 3344 } 3345 3346 if (!Subtarget->hasFlatScrRegister() && 3347 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3348 report_fatal_error(Twine("invalid register \"" 3349 + StringRef(RegName) + "\" for subtarget.")); 3350 } 3351 3352 switch (Reg) { 3353 case AMDGPU::M0: 3354 case AMDGPU::EXEC_LO: 3355 case AMDGPU::EXEC_HI: 3356 case AMDGPU::FLAT_SCR_LO: 3357 case AMDGPU::FLAT_SCR_HI: 3358 if (VT.getSizeInBits() == 32) 3359 return Reg; 3360 break; 3361 case AMDGPU::EXEC: 3362 case AMDGPU::FLAT_SCR: 3363 if (VT.getSizeInBits() == 64) 3364 return Reg; 3365 break; 3366 default: 3367 llvm_unreachable("missing register type checking"); 3368 } 3369 3370 report_fatal_error(Twine("invalid type for register \"" 3371 + StringRef(RegName) + "\".")); 3372 } 3373 3374 // If kill is not the last instruction, split the block so kill is always a 3375 // proper terminator. 3376 MachineBasicBlock * 3377 SITargetLowering::splitKillBlock(MachineInstr &MI, 3378 MachineBasicBlock *BB) const { 3379 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3380 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3381 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3382 return SplitBB; 3383 } 3384 3385 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3386 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3387 // be the first instruction in the remainder block. 3388 // 3389 /// \returns { LoopBody, Remainder } 3390 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3391 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3392 MachineFunction *MF = MBB.getParent(); 3393 MachineBasicBlock::iterator I(&MI); 3394 3395 // To insert the loop we need to split the block. Move everything after this 3396 // point to a new block, and insert a new empty block between the two. 3397 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3398 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3399 MachineFunction::iterator MBBI(MBB); 3400 ++MBBI; 3401 3402 MF->insert(MBBI, LoopBB); 3403 MF->insert(MBBI, RemainderBB); 3404 3405 LoopBB->addSuccessor(LoopBB); 3406 LoopBB->addSuccessor(RemainderBB); 3407 3408 // Move the rest of the block into a new block. 3409 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3410 3411 if (InstInLoop) { 3412 auto Next = std::next(I); 3413 3414 // Move instruction to loop body. 3415 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3416 3417 // Move the rest of the block. 3418 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3419 } else { 3420 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3421 } 3422 3423 MBB.addSuccessor(LoopBB); 3424 3425 return std::make_pair(LoopBB, RemainderBB); 3426 } 3427 3428 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3429 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3430 MachineBasicBlock *MBB = MI.getParent(); 3431 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3432 auto I = MI.getIterator(); 3433 auto E = std::next(I); 3434 3435 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3436 .addImm(0); 3437 3438 MIBundleBuilder Bundler(*MBB, I, E); 3439 finalizeBundle(*MBB, Bundler.begin()); 3440 } 3441 3442 MachineBasicBlock * 3443 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3444 MachineBasicBlock *BB) const { 3445 const DebugLoc &DL = MI.getDebugLoc(); 3446 3447 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3448 3449 MachineBasicBlock *LoopBB; 3450 MachineBasicBlock *RemainderBB; 3451 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3452 3453 // Apparently kill flags are only valid if the def is in the same block? 3454 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3455 Src->setIsKill(false); 3456 3457 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3458 3459 MachineBasicBlock::iterator I = LoopBB->end(); 3460 3461 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3462 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3463 3464 // Clear TRAP_STS.MEM_VIOL 3465 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3466 .addImm(0) 3467 .addImm(EncodedReg); 3468 3469 bundleInstWithWaitcnt(MI); 3470 3471 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3472 3473 // Load and check TRAP_STS.MEM_VIOL 3474 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3475 .addImm(EncodedReg); 3476 3477 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3478 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3479 .addReg(Reg, RegState::Kill) 3480 .addImm(0); 3481 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3482 .addMBB(LoopBB); 3483 3484 return RemainderBB; 3485 } 3486 3487 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3488 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3489 // will only do one iteration. In the worst case, this will loop 64 times. 3490 // 3491 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3492 static MachineBasicBlock::iterator 3493 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3494 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3495 const DebugLoc &DL, const MachineOperand &Idx, 3496 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3497 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3498 Register &SGPRIdxReg) { 3499 3500 MachineFunction *MF = OrigBB.getParent(); 3501 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3502 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3503 MachineBasicBlock::iterator I = LoopBB.begin(); 3504 3505 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3506 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3507 Register NewExec = MRI.createVirtualRegister(BoolRC); 3508 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3509 Register CondReg = MRI.createVirtualRegister(BoolRC); 3510 3511 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3512 .addReg(InitReg) 3513 .addMBB(&OrigBB) 3514 .addReg(ResultReg) 3515 .addMBB(&LoopBB); 3516 3517 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3518 .addReg(InitSaveExecReg) 3519 .addMBB(&OrigBB) 3520 .addReg(NewExec) 3521 .addMBB(&LoopBB); 3522 3523 // Read the next variant <- also loop target. 3524 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3525 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3526 3527 // Compare the just read M0 value to all possible Idx values. 3528 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3529 .addReg(CurrentIdxReg) 3530 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3531 3532 // Update EXEC, save the original EXEC value to VCC. 3533 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3534 : AMDGPU::S_AND_SAVEEXEC_B64), 3535 NewExec) 3536 .addReg(CondReg, RegState::Kill); 3537 3538 MRI.setSimpleHint(NewExec, CondReg); 3539 3540 if (UseGPRIdxMode) { 3541 if (Offset == 0) { 3542 SGPRIdxReg = CurrentIdxReg; 3543 } else { 3544 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3545 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3546 .addReg(CurrentIdxReg, RegState::Kill) 3547 .addImm(Offset); 3548 } 3549 } else { 3550 // Move index from VCC into M0 3551 if (Offset == 0) { 3552 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3553 .addReg(CurrentIdxReg, RegState::Kill); 3554 } else { 3555 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3556 .addReg(CurrentIdxReg, RegState::Kill) 3557 .addImm(Offset); 3558 } 3559 } 3560 3561 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3562 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3563 MachineInstr *InsertPt = 3564 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3565 : AMDGPU::S_XOR_B64_term), Exec) 3566 .addReg(Exec) 3567 .addReg(NewExec); 3568 3569 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3570 // s_cbranch_scc0? 3571 3572 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3573 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3574 .addMBB(&LoopBB); 3575 3576 return InsertPt->getIterator(); 3577 } 3578 3579 // This has slightly sub-optimal regalloc when the source vector is killed by 3580 // the read. The register allocator does not understand that the kill is 3581 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3582 // subregister from it, using 1 more VGPR than necessary. This was saved when 3583 // this was expanded after register allocation. 3584 static MachineBasicBlock::iterator 3585 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3586 unsigned InitResultReg, unsigned PhiReg, int Offset, 3587 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3588 MachineFunction *MF = MBB.getParent(); 3589 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3590 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3591 MachineRegisterInfo &MRI = MF->getRegInfo(); 3592 const DebugLoc &DL = MI.getDebugLoc(); 3593 MachineBasicBlock::iterator I(&MI); 3594 3595 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3596 Register DstReg = MI.getOperand(0).getReg(); 3597 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3598 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3599 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3600 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3601 3602 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3603 3604 // Save the EXEC mask 3605 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3606 .addReg(Exec); 3607 3608 MachineBasicBlock *LoopBB; 3609 MachineBasicBlock *RemainderBB; 3610 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3611 3612 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3613 3614 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3615 InitResultReg, DstReg, PhiReg, TmpExec, 3616 Offset, UseGPRIdxMode, SGPRIdxReg); 3617 3618 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3619 MachineFunction::iterator MBBI(LoopBB); 3620 ++MBBI; 3621 MF->insert(MBBI, LandingPad); 3622 LoopBB->removeSuccessor(RemainderBB); 3623 LandingPad->addSuccessor(RemainderBB); 3624 LoopBB->addSuccessor(LandingPad); 3625 MachineBasicBlock::iterator First = LandingPad->begin(); 3626 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3627 .addReg(SaveExec); 3628 3629 return InsPt; 3630 } 3631 3632 // Returns subreg index, offset 3633 static std::pair<unsigned, int> 3634 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3635 const TargetRegisterClass *SuperRC, 3636 unsigned VecReg, 3637 int Offset) { 3638 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3639 3640 // Skip out of bounds offsets, or else we would end up using an undefined 3641 // register. 3642 if (Offset >= NumElts || Offset < 0) 3643 return std::make_pair(AMDGPU::sub0, Offset); 3644 3645 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3646 } 3647 3648 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3649 MachineRegisterInfo &MRI, MachineInstr &MI, 3650 int Offset) { 3651 MachineBasicBlock *MBB = MI.getParent(); 3652 const DebugLoc &DL = MI.getDebugLoc(); 3653 MachineBasicBlock::iterator I(&MI); 3654 3655 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3656 3657 assert(Idx->getReg() != AMDGPU::NoRegister); 3658 3659 if (Offset == 0) { 3660 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3661 } else { 3662 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3663 .add(*Idx) 3664 .addImm(Offset); 3665 } 3666 } 3667 3668 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3669 MachineRegisterInfo &MRI, MachineInstr &MI, 3670 int Offset) { 3671 MachineBasicBlock *MBB = MI.getParent(); 3672 const DebugLoc &DL = MI.getDebugLoc(); 3673 MachineBasicBlock::iterator I(&MI); 3674 3675 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3676 3677 if (Offset == 0) 3678 return Idx->getReg(); 3679 3680 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3681 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3682 .add(*Idx) 3683 .addImm(Offset); 3684 return Tmp; 3685 } 3686 3687 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3688 MachineBasicBlock &MBB, 3689 const GCNSubtarget &ST) { 3690 const SIInstrInfo *TII = ST.getInstrInfo(); 3691 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3692 MachineFunction *MF = MBB.getParent(); 3693 MachineRegisterInfo &MRI = MF->getRegInfo(); 3694 3695 Register Dst = MI.getOperand(0).getReg(); 3696 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3697 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3698 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3699 3700 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3701 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3702 3703 unsigned SubReg; 3704 std::tie(SubReg, Offset) 3705 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3706 3707 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3708 3709 // Check for a SGPR index. 3710 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3711 MachineBasicBlock::iterator I(&MI); 3712 const DebugLoc &DL = MI.getDebugLoc(); 3713 3714 if (UseGPRIdxMode) { 3715 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3716 // to avoid interfering with other uses, so probably requires a new 3717 // optimization pass. 3718 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3719 3720 const MCInstrDesc &GPRIDXDesc = 3721 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3722 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3723 .addReg(SrcReg) 3724 .addReg(Idx) 3725 .addImm(SubReg); 3726 } else { 3727 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3728 3729 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3730 .addReg(SrcReg, 0, SubReg) 3731 .addReg(SrcReg, RegState::Implicit); 3732 } 3733 3734 MI.eraseFromParent(); 3735 3736 return &MBB; 3737 } 3738 3739 // Control flow needs to be inserted if indexing with a VGPR. 3740 const DebugLoc &DL = MI.getDebugLoc(); 3741 MachineBasicBlock::iterator I(&MI); 3742 3743 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3744 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3745 3746 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3747 3748 Register SGPRIdxReg; 3749 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3750 UseGPRIdxMode, SGPRIdxReg); 3751 3752 MachineBasicBlock *LoopBB = InsPt->getParent(); 3753 3754 if (UseGPRIdxMode) { 3755 const MCInstrDesc &GPRIDXDesc = 3756 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3757 3758 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3759 .addReg(SrcReg) 3760 .addReg(SGPRIdxReg) 3761 .addImm(SubReg); 3762 } else { 3763 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3764 .addReg(SrcReg, 0, SubReg) 3765 .addReg(SrcReg, RegState::Implicit); 3766 } 3767 3768 MI.eraseFromParent(); 3769 3770 return LoopBB; 3771 } 3772 3773 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3774 MachineBasicBlock &MBB, 3775 const GCNSubtarget &ST) { 3776 const SIInstrInfo *TII = ST.getInstrInfo(); 3777 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3778 MachineFunction *MF = MBB.getParent(); 3779 MachineRegisterInfo &MRI = MF->getRegInfo(); 3780 3781 Register Dst = MI.getOperand(0).getReg(); 3782 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3783 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3784 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3785 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3786 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3787 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3788 3789 // This can be an immediate, but will be folded later. 3790 assert(Val->getReg()); 3791 3792 unsigned SubReg; 3793 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3794 SrcVec->getReg(), 3795 Offset); 3796 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3797 3798 if (Idx->getReg() == AMDGPU::NoRegister) { 3799 MachineBasicBlock::iterator I(&MI); 3800 const DebugLoc &DL = MI.getDebugLoc(); 3801 3802 assert(Offset == 0); 3803 3804 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3805 .add(*SrcVec) 3806 .add(*Val) 3807 .addImm(SubReg); 3808 3809 MI.eraseFromParent(); 3810 return &MBB; 3811 } 3812 3813 // Check for a SGPR index. 3814 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3815 MachineBasicBlock::iterator I(&MI); 3816 const DebugLoc &DL = MI.getDebugLoc(); 3817 3818 if (UseGPRIdxMode) { 3819 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3820 3821 const MCInstrDesc &GPRIDXDesc = 3822 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3823 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3824 .addReg(SrcVec->getReg()) 3825 .add(*Val) 3826 .addReg(Idx) 3827 .addImm(SubReg); 3828 } else { 3829 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3830 3831 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3832 TRI.getRegSizeInBits(*VecRC), 32, false); 3833 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3834 .addReg(SrcVec->getReg()) 3835 .add(*Val) 3836 .addImm(SubReg); 3837 } 3838 MI.eraseFromParent(); 3839 return &MBB; 3840 } 3841 3842 // Control flow needs to be inserted if indexing with a VGPR. 3843 if (Val->isReg()) 3844 MRI.clearKillFlags(Val->getReg()); 3845 3846 const DebugLoc &DL = MI.getDebugLoc(); 3847 3848 Register PhiReg = MRI.createVirtualRegister(VecRC); 3849 3850 Register SGPRIdxReg; 3851 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3852 UseGPRIdxMode, SGPRIdxReg); 3853 MachineBasicBlock *LoopBB = InsPt->getParent(); 3854 3855 if (UseGPRIdxMode) { 3856 const MCInstrDesc &GPRIDXDesc = 3857 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3858 3859 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3860 .addReg(PhiReg) 3861 .add(*Val) 3862 .addReg(SGPRIdxReg) 3863 .addImm(AMDGPU::sub0); 3864 } else { 3865 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3866 TRI.getRegSizeInBits(*VecRC), 32, false); 3867 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3868 .addReg(PhiReg) 3869 .add(*Val) 3870 .addImm(AMDGPU::sub0); 3871 } 3872 3873 MI.eraseFromParent(); 3874 return LoopBB; 3875 } 3876 3877 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3878 MachineInstr &MI, MachineBasicBlock *BB) const { 3879 3880 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3881 MachineFunction *MF = BB->getParent(); 3882 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3883 3884 switch (MI.getOpcode()) { 3885 case AMDGPU::S_UADDO_PSEUDO: 3886 case AMDGPU::S_USUBO_PSEUDO: { 3887 const DebugLoc &DL = MI.getDebugLoc(); 3888 MachineOperand &Dest0 = MI.getOperand(0); 3889 MachineOperand &Dest1 = MI.getOperand(1); 3890 MachineOperand &Src0 = MI.getOperand(2); 3891 MachineOperand &Src1 = MI.getOperand(3); 3892 3893 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3894 ? AMDGPU::S_ADD_I32 3895 : AMDGPU::S_SUB_I32; 3896 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3897 3898 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3899 .addImm(1) 3900 .addImm(0); 3901 3902 MI.eraseFromParent(); 3903 return BB; 3904 } 3905 case AMDGPU::S_ADD_U64_PSEUDO: 3906 case AMDGPU::S_SUB_U64_PSEUDO: { 3907 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3908 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3909 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3910 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3911 const DebugLoc &DL = MI.getDebugLoc(); 3912 3913 MachineOperand &Dest = MI.getOperand(0); 3914 MachineOperand &Src0 = MI.getOperand(1); 3915 MachineOperand &Src1 = MI.getOperand(2); 3916 3917 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3918 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3919 3920 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3921 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3922 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3923 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3924 3925 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3926 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3927 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3928 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3929 3930 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3931 3932 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3933 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3934 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3935 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3936 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3937 .addReg(DestSub0) 3938 .addImm(AMDGPU::sub0) 3939 .addReg(DestSub1) 3940 .addImm(AMDGPU::sub1); 3941 MI.eraseFromParent(); 3942 return BB; 3943 } 3944 case AMDGPU::V_ADD_U64_PSEUDO: 3945 case AMDGPU::V_SUB_U64_PSEUDO: { 3946 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3947 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3948 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3949 const DebugLoc &DL = MI.getDebugLoc(); 3950 3951 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3952 3953 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3954 3955 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3956 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3957 3958 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3959 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3960 3961 MachineOperand &Dest = MI.getOperand(0); 3962 MachineOperand &Src0 = MI.getOperand(1); 3963 MachineOperand &Src1 = MI.getOperand(2); 3964 3965 const TargetRegisterClass *Src0RC = Src0.isReg() 3966 ? MRI.getRegClass(Src0.getReg()) 3967 : &AMDGPU::VReg_64RegClass; 3968 const TargetRegisterClass *Src1RC = Src1.isReg() 3969 ? MRI.getRegClass(Src1.getReg()) 3970 : &AMDGPU::VReg_64RegClass; 3971 3972 const TargetRegisterClass *Src0SubRC = 3973 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3974 const TargetRegisterClass *Src1SubRC = 3975 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3976 3977 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3978 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3979 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3980 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3981 3982 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3983 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3984 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3985 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3986 3987 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 3988 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3989 .addReg(CarryReg, RegState::Define) 3990 .add(SrcReg0Sub0) 3991 .add(SrcReg1Sub0) 3992 .addImm(0); // clamp bit 3993 3994 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3995 MachineInstr *HiHalf = 3996 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3997 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3998 .add(SrcReg0Sub1) 3999 .add(SrcReg1Sub1) 4000 .addReg(CarryReg, RegState::Kill) 4001 .addImm(0); // clamp bit 4002 4003 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4004 .addReg(DestSub0) 4005 .addImm(AMDGPU::sub0) 4006 .addReg(DestSub1) 4007 .addImm(AMDGPU::sub1); 4008 TII->legalizeOperands(*LoHalf); 4009 TII->legalizeOperands(*HiHalf); 4010 MI.eraseFromParent(); 4011 return BB; 4012 } 4013 case AMDGPU::S_ADD_CO_PSEUDO: 4014 case AMDGPU::S_SUB_CO_PSEUDO: { 4015 // This pseudo has a chance to be selected 4016 // only from uniform add/subcarry node. All the VGPR operands 4017 // therefore assumed to be splat vectors. 4018 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4019 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4020 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4021 MachineBasicBlock::iterator MII = MI; 4022 const DebugLoc &DL = MI.getDebugLoc(); 4023 MachineOperand &Dest = MI.getOperand(0); 4024 MachineOperand &CarryDest = MI.getOperand(1); 4025 MachineOperand &Src0 = MI.getOperand(2); 4026 MachineOperand &Src1 = MI.getOperand(3); 4027 MachineOperand &Src2 = MI.getOperand(4); 4028 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4029 ? AMDGPU::S_ADDC_U32 4030 : AMDGPU::S_SUBB_U32; 4031 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4032 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4033 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4034 .addReg(Src0.getReg()); 4035 Src0.setReg(RegOp0); 4036 } 4037 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4038 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4039 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4040 .addReg(Src1.getReg()); 4041 Src1.setReg(RegOp1); 4042 } 4043 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4044 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4045 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4046 .addReg(Src2.getReg()); 4047 Src2.setReg(RegOp2); 4048 } 4049 4050 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4051 if (TRI->getRegSizeInBits(*Src2RC) == 64) { 4052 if (ST.hasScalarCompareEq64()) { 4053 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4054 .addReg(Src2.getReg()) 4055 .addImm(0); 4056 } else { 4057 const TargetRegisterClass *SubRC = 4058 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4059 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4060 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4061 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4062 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4063 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4064 4065 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4066 .add(Src2Sub0) 4067 .add(Src2Sub1); 4068 4069 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4070 .addReg(Src2_32, RegState::Kill) 4071 .addImm(0); 4072 } 4073 } else { 4074 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4075 .addReg(Src2.getReg()) 4076 .addImm(0); 4077 } 4078 4079 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4080 4081 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 4082 .addReg(AMDGPU::SCC); 4083 MI.eraseFromParent(); 4084 return BB; 4085 } 4086 case AMDGPU::SI_INIT_M0: { 4087 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4088 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4089 .add(MI.getOperand(0)); 4090 MI.eraseFromParent(); 4091 return BB; 4092 } 4093 case AMDGPU::GET_GROUPSTATICSIZE: { 4094 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4095 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4096 DebugLoc DL = MI.getDebugLoc(); 4097 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4098 .add(MI.getOperand(0)) 4099 .addImm(MFI->getLDSSize()); 4100 MI.eraseFromParent(); 4101 return BB; 4102 } 4103 case AMDGPU::SI_INDIRECT_SRC_V1: 4104 case AMDGPU::SI_INDIRECT_SRC_V2: 4105 case AMDGPU::SI_INDIRECT_SRC_V4: 4106 case AMDGPU::SI_INDIRECT_SRC_V8: 4107 case AMDGPU::SI_INDIRECT_SRC_V16: 4108 case AMDGPU::SI_INDIRECT_SRC_V32: 4109 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4110 case AMDGPU::SI_INDIRECT_DST_V1: 4111 case AMDGPU::SI_INDIRECT_DST_V2: 4112 case AMDGPU::SI_INDIRECT_DST_V4: 4113 case AMDGPU::SI_INDIRECT_DST_V8: 4114 case AMDGPU::SI_INDIRECT_DST_V16: 4115 case AMDGPU::SI_INDIRECT_DST_V32: 4116 return emitIndirectDst(MI, *BB, *getSubtarget()); 4117 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4118 case AMDGPU::SI_KILL_I1_PSEUDO: 4119 return splitKillBlock(MI, BB); 4120 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4121 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4122 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4123 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4124 4125 Register Dst = MI.getOperand(0).getReg(); 4126 Register Src0 = MI.getOperand(1).getReg(); 4127 Register Src1 = MI.getOperand(2).getReg(); 4128 const DebugLoc &DL = MI.getDebugLoc(); 4129 Register SrcCond = MI.getOperand(3).getReg(); 4130 4131 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4132 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4133 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4134 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4135 4136 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4137 .addReg(SrcCond); 4138 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4139 .addImm(0) 4140 .addReg(Src0, 0, AMDGPU::sub0) 4141 .addImm(0) 4142 .addReg(Src1, 0, AMDGPU::sub0) 4143 .addReg(SrcCondCopy); 4144 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4145 .addImm(0) 4146 .addReg(Src0, 0, AMDGPU::sub1) 4147 .addImm(0) 4148 .addReg(Src1, 0, AMDGPU::sub1) 4149 .addReg(SrcCondCopy); 4150 4151 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4152 .addReg(DstLo) 4153 .addImm(AMDGPU::sub0) 4154 .addReg(DstHi) 4155 .addImm(AMDGPU::sub1); 4156 MI.eraseFromParent(); 4157 return BB; 4158 } 4159 case AMDGPU::SI_BR_UNDEF: { 4160 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4161 const DebugLoc &DL = MI.getDebugLoc(); 4162 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4163 .add(MI.getOperand(0)); 4164 Br->getOperand(1).setIsUndef(true); // read undef SCC 4165 MI.eraseFromParent(); 4166 return BB; 4167 } 4168 case AMDGPU::ADJCALLSTACKUP: 4169 case AMDGPU::ADJCALLSTACKDOWN: { 4170 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4171 MachineInstrBuilder MIB(*MF, &MI); 4172 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4173 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4174 return BB; 4175 } 4176 case AMDGPU::SI_CALL_ISEL: { 4177 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4178 const DebugLoc &DL = MI.getDebugLoc(); 4179 4180 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4181 4182 MachineInstrBuilder MIB; 4183 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4184 4185 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4186 MIB.add(MI.getOperand(I)); 4187 4188 MIB.cloneMemRefs(MI); 4189 MI.eraseFromParent(); 4190 return BB; 4191 } 4192 case AMDGPU::V_ADD_CO_U32_e32: 4193 case AMDGPU::V_SUB_CO_U32_e32: 4194 case AMDGPU::V_SUBREV_CO_U32_e32: { 4195 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4196 const DebugLoc &DL = MI.getDebugLoc(); 4197 unsigned Opc = MI.getOpcode(); 4198 4199 bool NeedClampOperand = false; 4200 if (TII->pseudoToMCOpcode(Opc) == -1) { 4201 Opc = AMDGPU::getVOPe64(Opc); 4202 NeedClampOperand = true; 4203 } 4204 4205 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4206 if (TII->isVOP3(*I)) { 4207 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4208 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4209 I.addReg(TRI->getVCC(), RegState::Define); 4210 } 4211 I.add(MI.getOperand(1)) 4212 .add(MI.getOperand(2)); 4213 if (NeedClampOperand) 4214 I.addImm(0); // clamp bit for e64 encoding 4215 4216 TII->legalizeOperands(*I); 4217 4218 MI.eraseFromParent(); 4219 return BB; 4220 } 4221 case AMDGPU::DS_GWS_INIT: 4222 case AMDGPU::DS_GWS_SEMA_V: 4223 case AMDGPU::DS_GWS_SEMA_BR: 4224 case AMDGPU::DS_GWS_SEMA_P: 4225 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4226 case AMDGPU::DS_GWS_BARRIER: 4227 // A s_waitcnt 0 is required to be the instruction immediately following. 4228 if (getSubtarget()->hasGWSAutoReplay()) { 4229 bundleInstWithWaitcnt(MI); 4230 return BB; 4231 } 4232 4233 return emitGWSMemViolTestLoop(MI, BB); 4234 case AMDGPU::S_SETREG_B32: { 4235 // Try to optimize cases that only set the denormal mode or rounding mode. 4236 // 4237 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4238 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4239 // instead. 4240 // 4241 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4242 // allow you to have a no side effect instruction in the output of a 4243 // sideeffecting pattern. 4244 unsigned ID, Offset, Width; 4245 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4246 if (ID != AMDGPU::Hwreg::ID_MODE) 4247 return BB; 4248 4249 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4250 const unsigned SetMask = WidthMask << Offset; 4251 4252 if (getSubtarget()->hasDenormModeInst()) { 4253 unsigned SetDenormOp = 0; 4254 unsigned SetRoundOp = 0; 4255 4256 // The dedicated instructions can only set the whole denorm or round mode 4257 // at once, not a subset of bits in either. 4258 if (SetMask == 4259 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4260 // If this fully sets both the round and denorm mode, emit the two 4261 // dedicated instructions for these. 4262 SetRoundOp = AMDGPU::S_ROUND_MODE; 4263 SetDenormOp = AMDGPU::S_DENORM_MODE; 4264 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4265 SetRoundOp = AMDGPU::S_ROUND_MODE; 4266 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4267 SetDenormOp = AMDGPU::S_DENORM_MODE; 4268 } 4269 4270 if (SetRoundOp || SetDenormOp) { 4271 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4272 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4273 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4274 unsigned ImmVal = Def->getOperand(1).getImm(); 4275 if (SetRoundOp) { 4276 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4277 .addImm(ImmVal & 0xf); 4278 4279 // If we also have the denorm mode, get just the denorm mode bits. 4280 ImmVal >>= 4; 4281 } 4282 4283 if (SetDenormOp) { 4284 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4285 .addImm(ImmVal & 0xf); 4286 } 4287 4288 MI.eraseFromParent(); 4289 return BB; 4290 } 4291 } 4292 } 4293 4294 // If only FP bits are touched, used the no side effects pseudo. 4295 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4296 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4297 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4298 4299 return BB; 4300 } 4301 default: 4302 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4303 } 4304 } 4305 4306 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4307 return isTypeLegal(VT.getScalarType()); 4308 } 4309 4310 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4311 // This currently forces unfolding various combinations of fsub into fma with 4312 // free fneg'd operands. As long as we have fast FMA (controlled by 4313 // isFMAFasterThanFMulAndFAdd), we should perform these. 4314 4315 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4316 // most of these combines appear to be cycle neutral but save on instruction 4317 // count / code size. 4318 return true; 4319 } 4320 4321 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4322 EVT VT) const { 4323 if (!VT.isVector()) { 4324 return MVT::i1; 4325 } 4326 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4327 } 4328 4329 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4330 // TODO: Should i16 be used always if legal? For now it would force VALU 4331 // shifts. 4332 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4333 } 4334 4335 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4336 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4337 ? Ty.changeElementSize(16) 4338 : Ty.changeElementSize(32); 4339 } 4340 4341 // Answering this is somewhat tricky and depends on the specific device which 4342 // have different rates for fma or all f64 operations. 4343 // 4344 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4345 // regardless of which device (although the number of cycles differs between 4346 // devices), so it is always profitable for f64. 4347 // 4348 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4349 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4350 // which we can always do even without fused FP ops since it returns the same 4351 // result as the separate operations and since it is always full 4352 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4353 // however does not support denormals, so we do report fma as faster if we have 4354 // a fast fma device and require denormals. 4355 // 4356 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4357 EVT VT) const { 4358 VT = VT.getScalarType(); 4359 4360 switch (VT.getSimpleVT().SimpleTy) { 4361 case MVT::f32: { 4362 // If mad is not available this depends only on if f32 fma is full rate. 4363 if (!Subtarget->hasMadMacF32Insts()) 4364 return Subtarget->hasFastFMAF32(); 4365 4366 // Otherwise f32 mad is always full rate and returns the same result as 4367 // the separate operations so should be preferred over fma. 4368 // However does not support denomals. 4369 if (hasFP32Denormals(MF)) 4370 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4371 4372 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4373 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4374 } 4375 case MVT::f64: 4376 return true; 4377 case MVT::f16: 4378 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4379 default: 4380 break; 4381 } 4382 4383 return false; 4384 } 4385 4386 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4387 const SDNode *N) const { 4388 // TODO: Check future ftz flag 4389 // v_mad_f32/v_mac_f32 do not support denormals. 4390 EVT VT = N->getValueType(0); 4391 if (VT == MVT::f32) 4392 return Subtarget->hasMadMacF32Insts() && 4393 !hasFP32Denormals(DAG.getMachineFunction()); 4394 if (VT == MVT::f16) { 4395 return Subtarget->hasMadF16() && 4396 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4397 } 4398 4399 return false; 4400 } 4401 4402 //===----------------------------------------------------------------------===// 4403 // Custom DAG Lowering Operations 4404 //===----------------------------------------------------------------------===// 4405 4406 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4407 // wider vector type is legal. 4408 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4409 SelectionDAG &DAG) const { 4410 unsigned Opc = Op.getOpcode(); 4411 EVT VT = Op.getValueType(); 4412 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4413 4414 SDValue Lo, Hi; 4415 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4416 4417 SDLoc SL(Op); 4418 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4419 Op->getFlags()); 4420 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4421 Op->getFlags()); 4422 4423 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4424 } 4425 4426 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4427 // wider vector type is legal. 4428 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4429 SelectionDAG &DAG) const { 4430 unsigned Opc = Op.getOpcode(); 4431 EVT VT = Op.getValueType(); 4432 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4433 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4434 4435 SDValue Lo0, Hi0; 4436 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4437 SDValue Lo1, Hi1; 4438 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4439 4440 SDLoc SL(Op); 4441 4442 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4443 Op->getFlags()); 4444 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4445 Op->getFlags()); 4446 4447 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4448 } 4449 4450 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4451 SelectionDAG &DAG) const { 4452 unsigned Opc = Op.getOpcode(); 4453 EVT VT = Op.getValueType(); 4454 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4455 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4456 4457 SDValue Lo0, Hi0; 4458 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4459 SDValue Lo1, Hi1; 4460 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4461 SDValue Lo2, Hi2; 4462 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4463 4464 SDLoc SL(Op); 4465 4466 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4467 Op->getFlags()); 4468 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4469 Op->getFlags()); 4470 4471 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4472 } 4473 4474 4475 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4476 switch (Op.getOpcode()) { 4477 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4478 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4479 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4480 case ISD::LOAD: { 4481 SDValue Result = LowerLOAD(Op, DAG); 4482 assert((!Result.getNode() || 4483 Result.getNode()->getNumValues() == 2) && 4484 "Load should return a value and a chain"); 4485 return Result; 4486 } 4487 4488 case ISD::FSIN: 4489 case ISD::FCOS: 4490 return LowerTrig(Op, DAG); 4491 case ISD::SELECT: return LowerSELECT(Op, DAG); 4492 case ISD::FDIV: return LowerFDIV(Op, DAG); 4493 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4494 case ISD::STORE: return LowerSTORE(Op, DAG); 4495 case ISD::GlobalAddress: { 4496 MachineFunction &MF = DAG.getMachineFunction(); 4497 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4498 return LowerGlobalAddress(MFI, Op, DAG); 4499 } 4500 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4501 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4502 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4503 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4504 case ISD::INSERT_SUBVECTOR: 4505 return lowerINSERT_SUBVECTOR(Op, DAG); 4506 case ISD::INSERT_VECTOR_ELT: 4507 return lowerINSERT_VECTOR_ELT(Op, DAG); 4508 case ISD::EXTRACT_VECTOR_ELT: 4509 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4510 case ISD::VECTOR_SHUFFLE: 4511 return lowerVECTOR_SHUFFLE(Op, DAG); 4512 case ISD::BUILD_VECTOR: 4513 return lowerBUILD_VECTOR(Op, DAG); 4514 case ISD::FP_ROUND: 4515 return lowerFP_ROUND(Op, DAG); 4516 case ISD::TRAP: 4517 return lowerTRAP(Op, DAG); 4518 case ISD::DEBUGTRAP: 4519 return lowerDEBUGTRAP(Op, DAG); 4520 case ISD::FABS: 4521 case ISD::FNEG: 4522 case ISD::FCANONICALIZE: 4523 case ISD::BSWAP: 4524 return splitUnaryVectorOp(Op, DAG); 4525 case ISD::FMINNUM: 4526 case ISD::FMAXNUM: 4527 return lowerFMINNUM_FMAXNUM(Op, DAG); 4528 case ISD::FMA: 4529 return splitTernaryVectorOp(Op, DAG); 4530 case ISD::SHL: 4531 case ISD::SRA: 4532 case ISD::SRL: 4533 case ISD::ADD: 4534 case ISD::SUB: 4535 case ISD::MUL: 4536 case ISD::SMIN: 4537 case ISD::SMAX: 4538 case ISD::UMIN: 4539 case ISD::UMAX: 4540 case ISD::FADD: 4541 case ISD::FMUL: 4542 case ISD::FMINNUM_IEEE: 4543 case ISD::FMAXNUM_IEEE: 4544 case ISD::UADDSAT: 4545 case ISD::USUBSAT: 4546 case ISD::SADDSAT: 4547 case ISD::SSUBSAT: 4548 return splitBinaryVectorOp(Op, DAG); 4549 case ISD::SMULO: 4550 case ISD::UMULO: 4551 return lowerXMULO(Op, DAG); 4552 case ISD::DYNAMIC_STACKALLOC: 4553 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4554 } 4555 return SDValue(); 4556 } 4557 4558 // Used for D16: Casts the result of an instruction into the right vector, 4559 // packs values if loads return unpacked values. 4560 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4561 const SDLoc &DL, 4562 SelectionDAG &DAG, bool Unpacked) { 4563 if (!LoadVT.isVector()) 4564 return Result; 4565 4566 // Cast back to the original packed type or to a larger type that is a 4567 // multiple of 32 bit for D16. Widening the return type is a required for 4568 // legalization. 4569 EVT FittingLoadVT = LoadVT; 4570 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4571 FittingLoadVT = 4572 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4573 LoadVT.getVectorNumElements() + 1); 4574 } 4575 4576 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4577 // Truncate to v2i16/v4i16. 4578 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4579 4580 // Workaround legalizer not scalarizing truncate after vector op 4581 // legalization but not creating intermediate vector trunc. 4582 SmallVector<SDValue, 4> Elts; 4583 DAG.ExtractVectorElements(Result, Elts); 4584 for (SDValue &Elt : Elts) 4585 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4586 4587 // Pad illegal v1i16/v3fi6 to v4i16 4588 if ((LoadVT.getVectorNumElements() % 2) == 1) 4589 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4590 4591 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4592 4593 // Bitcast to original type (v2f16/v4f16). 4594 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4595 } 4596 4597 // Cast back to the original packed type. 4598 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4599 } 4600 4601 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4602 MemSDNode *M, 4603 SelectionDAG &DAG, 4604 ArrayRef<SDValue> Ops, 4605 bool IsIntrinsic) const { 4606 SDLoc DL(M); 4607 4608 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4609 EVT LoadVT = M->getValueType(0); 4610 4611 EVT EquivLoadVT = LoadVT; 4612 if (LoadVT.isVector()) { 4613 if (Unpacked) { 4614 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4615 LoadVT.getVectorNumElements()); 4616 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4617 // Widen v3f16 to legal type 4618 EquivLoadVT = 4619 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4620 LoadVT.getVectorNumElements() + 1); 4621 } 4622 } 4623 4624 // Change from v4f16/v2f16 to EquivLoadVT. 4625 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4626 4627 SDValue Load 4628 = DAG.getMemIntrinsicNode( 4629 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4630 VTList, Ops, M->getMemoryVT(), 4631 M->getMemOperand()); 4632 4633 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4634 4635 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4636 } 4637 4638 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4639 SelectionDAG &DAG, 4640 ArrayRef<SDValue> Ops) const { 4641 SDLoc DL(M); 4642 EVT LoadVT = M->getValueType(0); 4643 EVT EltType = LoadVT.getScalarType(); 4644 EVT IntVT = LoadVT.changeTypeToInteger(); 4645 4646 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4647 4648 unsigned Opc = 4649 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4650 4651 if (IsD16) { 4652 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4653 } 4654 4655 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4656 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4657 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4658 4659 if (isTypeLegal(LoadVT)) { 4660 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4661 M->getMemOperand(), DAG); 4662 } 4663 4664 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4665 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4666 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4667 M->getMemOperand(), DAG); 4668 return DAG.getMergeValues( 4669 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4670 DL); 4671 } 4672 4673 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4674 SDNode *N, SelectionDAG &DAG) { 4675 EVT VT = N->getValueType(0); 4676 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4677 unsigned CondCode = CD->getZExtValue(); 4678 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4679 return DAG.getUNDEF(VT); 4680 4681 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4682 4683 SDValue LHS = N->getOperand(1); 4684 SDValue RHS = N->getOperand(2); 4685 4686 SDLoc DL(N); 4687 4688 EVT CmpVT = LHS.getValueType(); 4689 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4690 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4691 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4692 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4693 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4694 } 4695 4696 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4697 4698 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4699 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4700 4701 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4702 DAG.getCondCode(CCOpcode)); 4703 if (VT.bitsEq(CCVT)) 4704 return SetCC; 4705 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4706 } 4707 4708 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4709 SDNode *N, SelectionDAG &DAG) { 4710 EVT VT = N->getValueType(0); 4711 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4712 4713 unsigned CondCode = CD->getZExtValue(); 4714 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4715 return DAG.getUNDEF(VT); 4716 4717 SDValue Src0 = N->getOperand(1); 4718 SDValue Src1 = N->getOperand(2); 4719 EVT CmpVT = Src0.getValueType(); 4720 SDLoc SL(N); 4721 4722 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4723 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4724 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4725 } 4726 4727 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4728 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4729 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4730 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4731 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4732 Src1, DAG.getCondCode(CCOpcode)); 4733 if (VT.bitsEq(CCVT)) 4734 return SetCC; 4735 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4736 } 4737 4738 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4739 SelectionDAG &DAG) { 4740 EVT VT = N->getValueType(0); 4741 SDValue Src = N->getOperand(1); 4742 SDLoc SL(N); 4743 4744 if (Src.getOpcode() == ISD::SETCC) { 4745 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4746 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4747 Src.getOperand(1), Src.getOperand(2)); 4748 } 4749 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4750 // (ballot 0) -> 0 4751 if (Arg->isNullValue()) 4752 return DAG.getConstant(0, SL, VT); 4753 4754 // (ballot 1) -> EXEC/EXEC_LO 4755 if (Arg->isOne()) { 4756 Register Exec; 4757 if (VT.getScalarSizeInBits() == 32) 4758 Exec = AMDGPU::EXEC_LO; 4759 else if (VT.getScalarSizeInBits() == 64) 4760 Exec = AMDGPU::EXEC; 4761 else 4762 return SDValue(); 4763 4764 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4765 } 4766 } 4767 4768 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4769 // ISD::SETNE) 4770 return DAG.getNode( 4771 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4772 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4773 } 4774 4775 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4776 SmallVectorImpl<SDValue> &Results, 4777 SelectionDAG &DAG) const { 4778 switch (N->getOpcode()) { 4779 case ISD::INSERT_VECTOR_ELT: { 4780 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4781 Results.push_back(Res); 4782 return; 4783 } 4784 case ISD::EXTRACT_VECTOR_ELT: { 4785 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4786 Results.push_back(Res); 4787 return; 4788 } 4789 case ISD::INTRINSIC_WO_CHAIN: { 4790 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4791 switch (IID) { 4792 case Intrinsic::amdgcn_cvt_pkrtz: { 4793 SDValue Src0 = N->getOperand(1); 4794 SDValue Src1 = N->getOperand(2); 4795 SDLoc SL(N); 4796 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4797 Src0, Src1); 4798 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4799 return; 4800 } 4801 case Intrinsic::amdgcn_cvt_pknorm_i16: 4802 case Intrinsic::amdgcn_cvt_pknorm_u16: 4803 case Intrinsic::amdgcn_cvt_pk_i16: 4804 case Intrinsic::amdgcn_cvt_pk_u16: { 4805 SDValue Src0 = N->getOperand(1); 4806 SDValue Src1 = N->getOperand(2); 4807 SDLoc SL(N); 4808 unsigned Opcode; 4809 4810 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4811 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4812 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4813 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4814 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4815 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4816 else 4817 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4818 4819 EVT VT = N->getValueType(0); 4820 if (isTypeLegal(VT)) 4821 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4822 else { 4823 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4824 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4825 } 4826 return; 4827 } 4828 } 4829 break; 4830 } 4831 case ISD::INTRINSIC_W_CHAIN: { 4832 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4833 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4834 // FIXME: Hacky 4835 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4836 Results.push_back(Res.getOperand(I)); 4837 } 4838 } else { 4839 Results.push_back(Res); 4840 Results.push_back(Res.getValue(1)); 4841 } 4842 return; 4843 } 4844 4845 break; 4846 } 4847 case ISD::SELECT: { 4848 SDLoc SL(N); 4849 EVT VT = N->getValueType(0); 4850 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4851 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4852 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4853 4854 EVT SelectVT = NewVT; 4855 if (NewVT.bitsLT(MVT::i32)) { 4856 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4857 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4858 SelectVT = MVT::i32; 4859 } 4860 4861 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4862 N->getOperand(0), LHS, RHS); 4863 4864 if (NewVT != SelectVT) 4865 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4866 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4867 return; 4868 } 4869 case ISD::FNEG: { 4870 if (N->getValueType(0) != MVT::v2f16) 4871 break; 4872 4873 SDLoc SL(N); 4874 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4875 4876 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4877 BC, 4878 DAG.getConstant(0x80008000, SL, MVT::i32)); 4879 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4880 return; 4881 } 4882 case ISD::FABS: { 4883 if (N->getValueType(0) != MVT::v2f16) 4884 break; 4885 4886 SDLoc SL(N); 4887 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4888 4889 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4890 BC, 4891 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4892 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4893 return; 4894 } 4895 default: 4896 break; 4897 } 4898 } 4899 4900 /// Helper function for LowerBRCOND 4901 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4902 4903 SDNode *Parent = Value.getNode(); 4904 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4905 I != E; ++I) { 4906 4907 if (I.getUse().get() != Value) 4908 continue; 4909 4910 if (I->getOpcode() == Opcode) 4911 return *I; 4912 } 4913 return nullptr; 4914 } 4915 4916 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4917 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4918 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4919 case Intrinsic::amdgcn_if: 4920 return AMDGPUISD::IF; 4921 case Intrinsic::amdgcn_else: 4922 return AMDGPUISD::ELSE; 4923 case Intrinsic::amdgcn_loop: 4924 return AMDGPUISD::LOOP; 4925 case Intrinsic::amdgcn_end_cf: 4926 llvm_unreachable("should not occur"); 4927 default: 4928 return 0; 4929 } 4930 } 4931 4932 // break, if_break, else_break are all only used as inputs to loop, not 4933 // directly as branch conditions. 4934 return 0; 4935 } 4936 4937 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4938 const Triple &TT = getTargetMachine().getTargetTriple(); 4939 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4940 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4941 AMDGPU::shouldEmitConstantsToTextSection(TT); 4942 } 4943 4944 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4945 // FIXME: Either avoid relying on address space here or change the default 4946 // address space for functions to avoid the explicit check. 4947 return (GV->getValueType()->isFunctionTy() || 4948 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4949 !shouldEmitFixup(GV) && 4950 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4951 } 4952 4953 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4954 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4955 } 4956 4957 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4958 if (!GV->hasExternalLinkage()) 4959 return true; 4960 4961 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4962 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4963 } 4964 4965 /// This transforms the control flow intrinsics to get the branch destination as 4966 /// last parameter, also switches branch target with BR if the need arise 4967 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4968 SelectionDAG &DAG) const { 4969 SDLoc DL(BRCOND); 4970 4971 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4972 SDValue Target = BRCOND.getOperand(2); 4973 SDNode *BR = nullptr; 4974 SDNode *SetCC = nullptr; 4975 4976 if (Intr->getOpcode() == ISD::SETCC) { 4977 // As long as we negate the condition everything is fine 4978 SetCC = Intr; 4979 Intr = SetCC->getOperand(0).getNode(); 4980 4981 } else { 4982 // Get the target from BR if we don't negate the condition 4983 BR = findUser(BRCOND, ISD::BR); 4984 assert(BR && "brcond missing unconditional branch user"); 4985 Target = BR->getOperand(1); 4986 } 4987 4988 unsigned CFNode = isCFIntrinsic(Intr); 4989 if (CFNode == 0) { 4990 // This is a uniform branch so we don't need to legalize. 4991 return BRCOND; 4992 } 4993 4994 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4995 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4996 4997 assert(!SetCC || 4998 (SetCC->getConstantOperandVal(1) == 1 && 4999 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5000 ISD::SETNE)); 5001 5002 // operands of the new intrinsic call 5003 SmallVector<SDValue, 4> Ops; 5004 if (HaveChain) 5005 Ops.push_back(BRCOND.getOperand(0)); 5006 5007 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5008 Ops.push_back(Target); 5009 5010 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5011 5012 // build the new intrinsic call 5013 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5014 5015 if (!HaveChain) { 5016 SDValue Ops[] = { 5017 SDValue(Result, 0), 5018 BRCOND.getOperand(0) 5019 }; 5020 5021 Result = DAG.getMergeValues(Ops, DL).getNode(); 5022 } 5023 5024 if (BR) { 5025 // Give the branch instruction our target 5026 SDValue Ops[] = { 5027 BR->getOperand(0), 5028 BRCOND.getOperand(2) 5029 }; 5030 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5031 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5032 } 5033 5034 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5035 5036 // Copy the intrinsic results to registers 5037 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5038 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5039 if (!CopyToReg) 5040 continue; 5041 5042 Chain = DAG.getCopyToReg( 5043 Chain, DL, 5044 CopyToReg->getOperand(1), 5045 SDValue(Result, i - 1), 5046 SDValue()); 5047 5048 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5049 } 5050 5051 // Remove the old intrinsic from the chain 5052 DAG.ReplaceAllUsesOfValueWith( 5053 SDValue(Intr, Intr->getNumValues() - 1), 5054 Intr->getOperand(0)); 5055 5056 return Chain; 5057 } 5058 5059 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5060 SelectionDAG &DAG) const { 5061 MVT VT = Op.getSimpleValueType(); 5062 SDLoc DL(Op); 5063 // Checking the depth 5064 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5065 return DAG.getConstant(0, DL, VT); 5066 5067 MachineFunction &MF = DAG.getMachineFunction(); 5068 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5069 // Check for kernel and shader functions 5070 if (Info->isEntryFunction()) 5071 return DAG.getConstant(0, DL, VT); 5072 5073 MachineFrameInfo &MFI = MF.getFrameInfo(); 5074 // There is a call to @llvm.returnaddress in this function 5075 MFI.setReturnAddressIsTaken(true); 5076 5077 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5078 // Get the return address reg and mark it as an implicit live-in 5079 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5080 5081 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5082 } 5083 5084 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5085 SDValue Op, 5086 const SDLoc &DL, 5087 EVT VT) const { 5088 return Op.getValueType().bitsLE(VT) ? 5089 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5090 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5091 DAG.getTargetConstant(0, DL, MVT::i32)); 5092 } 5093 5094 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5095 assert(Op.getValueType() == MVT::f16 && 5096 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5097 5098 SDValue Src = Op.getOperand(0); 5099 EVT SrcVT = Src.getValueType(); 5100 if (SrcVT != MVT::f64) 5101 return Op; 5102 5103 SDLoc DL(Op); 5104 5105 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5106 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5107 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5108 } 5109 5110 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5111 SelectionDAG &DAG) const { 5112 EVT VT = Op.getValueType(); 5113 const MachineFunction &MF = DAG.getMachineFunction(); 5114 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5115 bool IsIEEEMode = Info->getMode().IEEE; 5116 5117 // FIXME: Assert during selection that this is only selected for 5118 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5119 // mode functions, but this happens to be OK since it's only done in cases 5120 // where there is known no sNaN. 5121 if (IsIEEEMode) 5122 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5123 5124 if (VT == MVT::v4f16) 5125 return splitBinaryVectorOp(Op, DAG); 5126 return Op; 5127 } 5128 5129 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5130 EVT VT = Op.getValueType(); 5131 SDLoc SL(Op); 5132 SDValue LHS = Op.getOperand(0); 5133 SDValue RHS = Op.getOperand(1); 5134 bool isSigned = Op.getOpcode() == ISD::SMULO; 5135 5136 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5137 const APInt &C = RHSC->getAPIntValue(); 5138 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5139 if (C.isPowerOf2()) { 5140 // smulo(x, signed_min) is same as umulo(x, signed_min). 5141 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5142 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5143 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5144 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5145 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5146 SL, VT, Result, ShiftAmt), 5147 LHS, ISD::SETNE); 5148 return DAG.getMergeValues({ Result, Overflow }, SL); 5149 } 5150 } 5151 5152 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5153 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5154 SL, VT, LHS, RHS); 5155 5156 SDValue Sign = isSigned 5157 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5158 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5159 : DAG.getConstant(0, SL, VT); 5160 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5161 5162 return DAG.getMergeValues({ Result, Overflow }, SL); 5163 } 5164 5165 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5166 if (!Subtarget->isTrapHandlerEnabled() || 5167 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5168 return lowerTrapEndpgm(Op, DAG); 5169 5170 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5171 switch (*HsaAbiVer) { 5172 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5173 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5174 return lowerTrapHsaQueuePtr(Op, DAG); 5175 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5176 return Subtarget->supportsGetDoorbellID() ? 5177 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5178 } 5179 } 5180 5181 llvm_unreachable("Unknown trap handler"); 5182 } 5183 5184 SDValue SITargetLowering::lowerTrapEndpgm( 5185 SDValue Op, SelectionDAG &DAG) const { 5186 SDLoc SL(Op); 5187 SDValue Chain = Op.getOperand(0); 5188 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5189 } 5190 5191 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5192 SDValue Op, SelectionDAG &DAG) const { 5193 SDLoc SL(Op); 5194 SDValue Chain = Op.getOperand(0); 5195 5196 MachineFunction &MF = DAG.getMachineFunction(); 5197 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5198 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5199 assert(UserSGPR != AMDGPU::NoRegister); 5200 SDValue QueuePtr = CreateLiveInRegister( 5201 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5202 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5203 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5204 QueuePtr, SDValue()); 5205 5206 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5207 SDValue Ops[] = { 5208 ToReg, 5209 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5210 SGPR01, 5211 ToReg.getValue(1) 5212 }; 5213 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5214 } 5215 5216 SDValue SITargetLowering::lowerTrapHsa( 5217 SDValue Op, SelectionDAG &DAG) const { 5218 SDLoc SL(Op); 5219 SDValue Chain = Op.getOperand(0); 5220 5221 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5222 SDValue Ops[] = { 5223 Chain, 5224 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5225 }; 5226 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5227 } 5228 5229 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5230 SDLoc SL(Op); 5231 SDValue Chain = Op.getOperand(0); 5232 MachineFunction &MF = DAG.getMachineFunction(); 5233 5234 if (!Subtarget->isTrapHandlerEnabled() || 5235 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5236 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5237 "debugtrap handler not supported", 5238 Op.getDebugLoc(), 5239 DS_Warning); 5240 LLVMContext &Ctx = MF.getFunction().getContext(); 5241 Ctx.diagnose(NoTrap); 5242 return Chain; 5243 } 5244 5245 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5246 SDValue Ops[] = { 5247 Chain, 5248 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5249 }; 5250 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5251 } 5252 5253 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5254 SelectionDAG &DAG) const { 5255 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5256 if (Subtarget->hasApertureRegs()) { 5257 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5258 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5259 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5260 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5261 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5262 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5263 unsigned Encoding = 5264 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5265 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5266 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5267 5268 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5269 SDValue ApertureReg = SDValue( 5270 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5271 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5272 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5273 } 5274 5275 MachineFunction &MF = DAG.getMachineFunction(); 5276 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5277 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5278 assert(UserSGPR != AMDGPU::NoRegister); 5279 5280 SDValue QueuePtr = CreateLiveInRegister( 5281 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5282 5283 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5284 // private_segment_aperture_base_hi. 5285 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5286 5287 SDValue Ptr = 5288 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5289 5290 // TODO: Use custom target PseudoSourceValue. 5291 // TODO: We should use the value from the IR intrinsic call, but it might not 5292 // be available and how do we get it? 5293 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5294 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5295 commonAlignment(Align(64), StructOffset), 5296 MachineMemOperand::MODereferenceable | 5297 MachineMemOperand::MOInvariant); 5298 } 5299 5300 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5301 SelectionDAG &DAG) const { 5302 SDLoc SL(Op); 5303 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5304 5305 SDValue Src = ASC->getOperand(0); 5306 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5307 5308 const AMDGPUTargetMachine &TM = 5309 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5310 5311 // flat -> local/private 5312 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5313 unsigned DestAS = ASC->getDestAddressSpace(); 5314 5315 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5316 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5317 unsigned NullVal = TM.getNullPointerValue(DestAS); 5318 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5319 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5320 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5321 5322 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5323 NonNull, Ptr, SegmentNullPtr); 5324 } 5325 } 5326 5327 // local/private -> flat 5328 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5329 unsigned SrcAS = ASC->getSrcAddressSpace(); 5330 5331 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5332 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5333 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5334 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5335 5336 SDValue NonNull 5337 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5338 5339 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5340 SDValue CvtPtr 5341 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5342 5343 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5344 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5345 FlatNullPtr); 5346 } 5347 } 5348 5349 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5350 Src.getValueType() == MVT::i64) 5351 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5352 5353 // global <-> flat are no-ops and never emitted. 5354 5355 const MachineFunction &MF = DAG.getMachineFunction(); 5356 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5357 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5358 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5359 5360 return DAG.getUNDEF(ASC->getValueType(0)); 5361 } 5362 5363 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5364 // the small vector and inserting them into the big vector. That is better than 5365 // the default expansion of doing it via a stack slot. Even though the use of 5366 // the stack slot would be optimized away afterwards, the stack slot itself 5367 // remains. 5368 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5369 SelectionDAG &DAG) const { 5370 SDValue Vec = Op.getOperand(0); 5371 SDValue Ins = Op.getOperand(1); 5372 SDValue Idx = Op.getOperand(2); 5373 EVT VecVT = Vec.getValueType(); 5374 EVT InsVT = Ins.getValueType(); 5375 EVT EltVT = VecVT.getVectorElementType(); 5376 unsigned InsNumElts = InsVT.getVectorNumElements(); 5377 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5378 SDLoc SL(Op); 5379 5380 for (unsigned I = 0; I != InsNumElts; ++I) { 5381 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5382 DAG.getConstant(I, SL, MVT::i32)); 5383 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5384 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5385 } 5386 return Vec; 5387 } 5388 5389 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5390 SelectionDAG &DAG) const { 5391 SDValue Vec = Op.getOperand(0); 5392 SDValue InsVal = Op.getOperand(1); 5393 SDValue Idx = Op.getOperand(2); 5394 EVT VecVT = Vec.getValueType(); 5395 EVT EltVT = VecVT.getVectorElementType(); 5396 unsigned VecSize = VecVT.getSizeInBits(); 5397 unsigned EltSize = EltVT.getSizeInBits(); 5398 5399 5400 assert(VecSize <= 64); 5401 5402 unsigned NumElts = VecVT.getVectorNumElements(); 5403 SDLoc SL(Op); 5404 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5405 5406 if (NumElts == 4 && EltSize == 16 && KIdx) { 5407 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5408 5409 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5410 DAG.getConstant(0, SL, MVT::i32)); 5411 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5412 DAG.getConstant(1, SL, MVT::i32)); 5413 5414 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5415 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5416 5417 unsigned Idx = KIdx->getZExtValue(); 5418 bool InsertLo = Idx < 2; 5419 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5420 InsertLo ? LoVec : HiVec, 5421 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5422 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5423 5424 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5425 5426 SDValue Concat = InsertLo ? 5427 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5428 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5429 5430 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5431 } 5432 5433 if (isa<ConstantSDNode>(Idx)) 5434 return SDValue(); 5435 5436 MVT IntVT = MVT::getIntegerVT(VecSize); 5437 5438 // Avoid stack access for dynamic indexing. 5439 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5440 5441 // Create a congruent vector with the target value in each element so that 5442 // the required element can be masked and ORed into the target vector. 5443 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5444 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5445 5446 assert(isPowerOf2_32(EltSize)); 5447 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5448 5449 // Convert vector index to bit-index. 5450 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5451 5452 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5453 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5454 DAG.getConstant(0xffff, SL, IntVT), 5455 ScaledIdx); 5456 5457 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5458 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5459 DAG.getNOT(SL, BFM, IntVT), BCVec); 5460 5461 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5462 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5463 } 5464 5465 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5466 SelectionDAG &DAG) const { 5467 SDLoc SL(Op); 5468 5469 EVT ResultVT = Op.getValueType(); 5470 SDValue Vec = Op.getOperand(0); 5471 SDValue Idx = Op.getOperand(1); 5472 EVT VecVT = Vec.getValueType(); 5473 unsigned VecSize = VecVT.getSizeInBits(); 5474 EVT EltVT = VecVT.getVectorElementType(); 5475 assert(VecSize <= 64); 5476 5477 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5478 5479 // Make sure we do any optimizations that will make it easier to fold 5480 // source modifiers before obscuring it with bit operations. 5481 5482 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5483 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5484 return Combined; 5485 5486 unsigned EltSize = EltVT.getSizeInBits(); 5487 assert(isPowerOf2_32(EltSize)); 5488 5489 MVT IntVT = MVT::getIntegerVT(VecSize); 5490 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5491 5492 // Convert vector index to bit-index (* EltSize) 5493 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5494 5495 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5496 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5497 5498 if (ResultVT == MVT::f16) { 5499 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5500 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5501 } 5502 5503 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5504 } 5505 5506 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5507 assert(Elt % 2 == 0); 5508 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5509 } 5510 5511 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5512 SelectionDAG &DAG) const { 5513 SDLoc SL(Op); 5514 EVT ResultVT = Op.getValueType(); 5515 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5516 5517 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5518 EVT EltVT = PackVT.getVectorElementType(); 5519 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5520 5521 // vector_shuffle <0,1,6,7> lhs, rhs 5522 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5523 // 5524 // vector_shuffle <6,7,2,3> lhs, rhs 5525 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5526 // 5527 // vector_shuffle <6,7,0,1> lhs, rhs 5528 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5529 5530 // Avoid scalarizing when both halves are reading from consecutive elements. 5531 SmallVector<SDValue, 4> Pieces; 5532 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5533 if (elementPairIsContiguous(SVN->getMask(), I)) { 5534 const int Idx = SVN->getMaskElt(I); 5535 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5536 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5537 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5538 PackVT, SVN->getOperand(VecIdx), 5539 DAG.getConstant(EltIdx, SL, MVT::i32)); 5540 Pieces.push_back(SubVec); 5541 } else { 5542 const int Idx0 = SVN->getMaskElt(I); 5543 const int Idx1 = SVN->getMaskElt(I + 1); 5544 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5545 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5546 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5547 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5548 5549 SDValue Vec0 = SVN->getOperand(VecIdx0); 5550 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5551 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5552 5553 SDValue Vec1 = SVN->getOperand(VecIdx1); 5554 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5555 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5556 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5557 } 5558 } 5559 5560 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5561 } 5562 5563 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5564 SelectionDAG &DAG) const { 5565 SDLoc SL(Op); 5566 EVT VT = Op.getValueType(); 5567 5568 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5569 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5570 5571 // Turn into pair of packed build_vectors. 5572 // TODO: Special case for constants that can be materialized with s_mov_b64. 5573 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5574 { Op.getOperand(0), Op.getOperand(1) }); 5575 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5576 { Op.getOperand(2), Op.getOperand(3) }); 5577 5578 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5579 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5580 5581 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5582 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5583 } 5584 5585 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5586 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5587 5588 SDValue Lo = Op.getOperand(0); 5589 SDValue Hi = Op.getOperand(1); 5590 5591 // Avoid adding defined bits with the zero_extend. 5592 if (Hi.isUndef()) { 5593 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5594 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5595 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5596 } 5597 5598 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5599 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5600 5601 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5602 DAG.getConstant(16, SL, MVT::i32)); 5603 if (Lo.isUndef()) 5604 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5605 5606 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5607 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5608 5609 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5610 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5611 } 5612 5613 bool 5614 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5615 // We can fold offsets for anything that doesn't require a GOT relocation. 5616 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5617 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5618 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5619 !shouldEmitGOTReloc(GA->getGlobal()); 5620 } 5621 5622 static SDValue 5623 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5624 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5625 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5626 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5627 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5628 // lowered to the following code sequence: 5629 // 5630 // For constant address space: 5631 // s_getpc_b64 s[0:1] 5632 // s_add_u32 s0, s0, $symbol 5633 // s_addc_u32 s1, s1, 0 5634 // 5635 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5636 // a fixup or relocation is emitted to replace $symbol with a literal 5637 // constant, which is a pc-relative offset from the encoding of the $symbol 5638 // operand to the global variable. 5639 // 5640 // For global address space: 5641 // s_getpc_b64 s[0:1] 5642 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5643 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5644 // 5645 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5646 // fixups or relocations are emitted to replace $symbol@*@lo and 5647 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5648 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5649 // operand to the global variable. 5650 // 5651 // What we want here is an offset from the value returned by s_getpc 5652 // (which is the address of the s_add_u32 instruction) to the global 5653 // variable, but since the encoding of $symbol starts 4 bytes after the start 5654 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5655 // small. This requires us to add 4 to the global variable offset in order to 5656 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5657 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5658 // instruction. 5659 SDValue PtrLo = 5660 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5661 SDValue PtrHi; 5662 if (GAFlags == SIInstrInfo::MO_NONE) { 5663 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5664 } else { 5665 PtrHi = 5666 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5667 } 5668 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5669 } 5670 5671 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5672 SDValue Op, 5673 SelectionDAG &DAG) const { 5674 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5675 SDLoc DL(GSD); 5676 EVT PtrVT = Op.getValueType(); 5677 5678 const GlobalValue *GV = GSD->getGlobal(); 5679 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5680 shouldUseLDSConstAddress(GV)) || 5681 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5682 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5683 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5684 GV->hasExternalLinkage()) { 5685 Type *Ty = GV->getValueType(); 5686 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5687 // zero-sized type in other languages to declare the dynamic shared 5688 // memory which size is not known at the compile time. They will be 5689 // allocated by the runtime and placed directly after the static 5690 // allocated ones. They all share the same offset. 5691 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5692 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5693 // Adjust alignment for that dynamic shared memory array. 5694 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5695 return SDValue( 5696 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5697 } 5698 } 5699 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5700 } 5701 5702 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5703 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5704 SIInstrInfo::MO_ABS32_LO); 5705 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5706 } 5707 5708 if (shouldEmitFixup(GV)) 5709 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5710 else if (shouldEmitPCReloc(GV)) 5711 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5712 SIInstrInfo::MO_REL32); 5713 5714 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5715 SIInstrInfo::MO_GOTPCREL32); 5716 5717 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5718 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5719 const DataLayout &DataLayout = DAG.getDataLayout(); 5720 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5721 MachinePointerInfo PtrInfo 5722 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5723 5724 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5725 MachineMemOperand::MODereferenceable | 5726 MachineMemOperand::MOInvariant); 5727 } 5728 5729 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5730 const SDLoc &DL, SDValue V) const { 5731 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5732 // the destination register. 5733 // 5734 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5735 // so we will end up with redundant moves to m0. 5736 // 5737 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5738 5739 // A Null SDValue creates a glue result. 5740 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5741 V, Chain); 5742 return SDValue(M0, 0); 5743 } 5744 5745 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5746 SDValue Op, 5747 MVT VT, 5748 unsigned Offset) const { 5749 SDLoc SL(Op); 5750 SDValue Param = lowerKernargMemParameter( 5751 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5752 // The local size values will have the hi 16-bits as zero. 5753 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5754 DAG.getValueType(VT)); 5755 } 5756 5757 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5758 EVT VT) { 5759 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5760 "non-hsa intrinsic with hsa target", 5761 DL.getDebugLoc()); 5762 DAG.getContext()->diagnose(BadIntrin); 5763 return DAG.getUNDEF(VT); 5764 } 5765 5766 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5767 EVT VT) { 5768 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5769 "intrinsic not supported on subtarget", 5770 DL.getDebugLoc()); 5771 DAG.getContext()->diagnose(BadIntrin); 5772 return DAG.getUNDEF(VT); 5773 } 5774 5775 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5776 ArrayRef<SDValue> Elts) { 5777 assert(!Elts.empty()); 5778 MVT Type; 5779 unsigned NumElts; 5780 5781 if (Elts.size() == 1) { 5782 Type = MVT::f32; 5783 NumElts = 1; 5784 } else if (Elts.size() == 2) { 5785 Type = MVT::v2f32; 5786 NumElts = 2; 5787 } else if (Elts.size() == 3) { 5788 Type = MVT::v3f32; 5789 NumElts = 3; 5790 } else if (Elts.size() <= 4) { 5791 Type = MVT::v4f32; 5792 NumElts = 4; 5793 } else if (Elts.size() <= 8) { 5794 Type = MVT::v8f32; 5795 NumElts = 8; 5796 } else { 5797 assert(Elts.size() <= 16); 5798 Type = MVT::v16f32; 5799 NumElts = 16; 5800 } 5801 5802 SmallVector<SDValue, 16> VecElts(NumElts); 5803 for (unsigned i = 0; i < Elts.size(); ++i) { 5804 SDValue Elt = Elts[i]; 5805 if (Elt.getValueType() != MVT::f32) 5806 Elt = DAG.getBitcast(MVT::f32, Elt); 5807 VecElts[i] = Elt; 5808 } 5809 for (unsigned i = Elts.size(); i < NumElts; ++i) 5810 VecElts[i] = DAG.getUNDEF(MVT::f32); 5811 5812 if (NumElts == 1) 5813 return VecElts[0]; 5814 return DAG.getBuildVector(Type, DL, VecElts); 5815 } 5816 5817 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5818 SDValue Src, int ExtraElts) { 5819 EVT SrcVT = Src.getValueType(); 5820 5821 SmallVector<SDValue, 8> Elts; 5822 5823 if (SrcVT.isVector()) 5824 DAG.ExtractVectorElements(Src, Elts); 5825 else 5826 Elts.push_back(Src); 5827 5828 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5829 while (ExtraElts--) 5830 Elts.push_back(Undef); 5831 5832 return DAG.getBuildVector(CastVT, DL, Elts); 5833 } 5834 5835 // Re-construct the required return value for a image load intrinsic. 5836 // This is more complicated due to the optional use TexFailCtrl which means the required 5837 // return type is an aggregate 5838 static SDValue constructRetValue(SelectionDAG &DAG, 5839 MachineSDNode *Result, 5840 ArrayRef<EVT> ResultTypes, 5841 bool IsTexFail, bool Unpacked, bool IsD16, 5842 int DMaskPop, int NumVDataDwords, 5843 const SDLoc &DL) { 5844 // Determine the required return type. This is the same regardless of IsTexFail flag 5845 EVT ReqRetVT = ResultTypes[0]; 5846 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5847 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5848 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5849 5850 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5851 DMaskPop : (DMaskPop + 1) / 2; 5852 5853 MVT DataDwordVT = NumDataDwords == 1 ? 5854 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5855 5856 MVT MaskPopVT = MaskPopDwords == 1 ? 5857 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5858 5859 SDValue Data(Result, 0); 5860 SDValue TexFail; 5861 5862 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 5863 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5864 if (MaskPopVT.isVector()) { 5865 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5866 SDValue(Result, 0), ZeroIdx); 5867 } else { 5868 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5869 SDValue(Result, 0), ZeroIdx); 5870 } 5871 } 5872 5873 if (DataDwordVT.isVector()) 5874 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5875 NumDataDwords - MaskPopDwords); 5876 5877 if (IsD16) 5878 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5879 5880 EVT LegalReqRetVT = ReqRetVT; 5881 if (!ReqRetVT.isVector()) { 5882 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5883 } else { 5884 // We need to widen the return vector to a legal type 5885 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 5886 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 5887 LegalReqRetVT = 5888 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 5889 ReqRetVT.getVectorNumElements() + 1); 5890 } 5891 } 5892 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 5893 5894 if (IsTexFail) { 5895 TexFail = 5896 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 5897 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5898 5899 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5900 } 5901 5902 if (Result->getNumValues() == 1) 5903 return Data; 5904 5905 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5906 } 5907 5908 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5909 SDValue *LWE, bool &IsTexFail) { 5910 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5911 5912 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5913 if (Value) { 5914 IsTexFail = true; 5915 } 5916 5917 SDLoc DL(TexFailCtrlConst); 5918 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5919 Value &= ~(uint64_t)0x1; 5920 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5921 Value &= ~(uint64_t)0x2; 5922 5923 return Value == 0; 5924 } 5925 5926 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5927 MVT PackVectorVT, 5928 SmallVectorImpl<SDValue> &PackedAddrs, 5929 unsigned DimIdx, unsigned EndIdx, 5930 unsigned NumGradients) { 5931 SDLoc DL(Op); 5932 for (unsigned I = DimIdx; I < EndIdx; I++) { 5933 SDValue Addr = Op.getOperand(I); 5934 5935 // Gradients are packed with undef for each coordinate. 5936 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5937 // 1D: undef,dx/dh; undef,dx/dv 5938 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5939 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5940 if (((I + 1) >= EndIdx) || 5941 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5942 I == DimIdx + NumGradients - 1))) { 5943 if (Addr.getValueType() != MVT::i16) 5944 Addr = DAG.getBitcast(MVT::i16, Addr); 5945 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5946 } else { 5947 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5948 I++; 5949 } 5950 Addr = DAG.getBitcast(MVT::f32, Addr); 5951 PackedAddrs.push_back(Addr); 5952 } 5953 } 5954 5955 SDValue SITargetLowering::lowerImage(SDValue Op, 5956 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5957 SelectionDAG &DAG, bool WithChain) const { 5958 SDLoc DL(Op); 5959 MachineFunction &MF = DAG.getMachineFunction(); 5960 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5961 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5962 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5963 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5964 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5965 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5966 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5967 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5968 unsigned IntrOpcode = Intr->BaseOpcode; 5969 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 5970 5971 SmallVector<EVT, 3> ResultTypes(Op->values()); 5972 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 5973 bool IsD16 = false; 5974 bool IsG16 = false; 5975 bool IsA16 = false; 5976 SDValue VData; 5977 int NumVDataDwords; 5978 bool AdjustRetType = false; 5979 5980 // Offset of intrinsic arguments 5981 const unsigned ArgOffset = WithChain ? 2 : 1; 5982 5983 unsigned DMask; 5984 unsigned DMaskLanes = 0; 5985 5986 if (BaseOpcode->Atomic) { 5987 VData = Op.getOperand(2); 5988 5989 bool Is64Bit = VData.getValueType() == MVT::i64; 5990 if (BaseOpcode->AtomicX2) { 5991 SDValue VData2 = Op.getOperand(3); 5992 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5993 {VData, VData2}); 5994 if (Is64Bit) 5995 VData = DAG.getBitcast(MVT::v4i32, VData); 5996 5997 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5998 DMask = Is64Bit ? 0xf : 0x3; 5999 NumVDataDwords = Is64Bit ? 4 : 2; 6000 } else { 6001 DMask = Is64Bit ? 0x3 : 0x1; 6002 NumVDataDwords = Is64Bit ? 2 : 1; 6003 } 6004 } else { 6005 auto *DMaskConst = 6006 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6007 DMask = DMaskConst->getZExtValue(); 6008 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6009 6010 if (BaseOpcode->Store) { 6011 VData = Op.getOperand(2); 6012 6013 MVT StoreVT = VData.getSimpleValueType(); 6014 if (StoreVT.getScalarType() == MVT::f16) { 6015 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6016 return Op; // D16 is unsupported for this instruction 6017 6018 IsD16 = true; 6019 VData = handleD16VData(VData, DAG, true); 6020 } 6021 6022 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6023 } else { 6024 // Work out the num dwords based on the dmask popcount and underlying type 6025 // and whether packing is supported. 6026 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6027 if (LoadVT.getScalarType() == MVT::f16) { 6028 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6029 return Op; // D16 is unsupported for this instruction 6030 6031 IsD16 = true; 6032 } 6033 6034 // Confirm that the return type is large enough for the dmask specified 6035 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6036 (!LoadVT.isVector() && DMaskLanes > 1)) 6037 return Op; 6038 6039 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6040 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6041 // instructions. 6042 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6043 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6044 NumVDataDwords = (DMaskLanes + 1) / 2; 6045 else 6046 NumVDataDwords = DMaskLanes; 6047 6048 AdjustRetType = true; 6049 } 6050 } 6051 6052 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6053 SmallVector<SDValue, 4> VAddrs; 6054 6055 // Optimize _L to _LZ when _L is zero 6056 if (LZMappingInfo) { 6057 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6058 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6059 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6060 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6061 VAddrEnd--; // remove 'lod' 6062 } 6063 } 6064 } 6065 6066 // Optimize _mip away, when 'lod' is zero 6067 if (MIPMappingInfo) { 6068 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6069 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6070 if (ConstantLod->isNullValue()) { 6071 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6072 VAddrEnd--; // remove 'mip' 6073 } 6074 } 6075 } 6076 6077 // Push back extra arguments. 6078 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) 6079 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6080 6081 // Check for 16 bit addresses or derivatives and pack if true. 6082 MVT VAddrVT = 6083 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6084 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6085 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6086 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6087 6088 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6089 VAddrScalarVT = VAddrVT.getScalarType(); 6090 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6091 if (IsA16 || IsG16) { 6092 if (IsA16) { 6093 if (!ST->hasA16()) { 6094 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6095 "support 16 bit addresses\n"); 6096 return Op; 6097 } 6098 if (!IsG16) { 6099 LLVM_DEBUG( 6100 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6101 "need 16 bit derivatives but got 32 bit derivatives\n"); 6102 return Op; 6103 } 6104 } else if (!ST->hasG16()) { 6105 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6106 "support 16 bit derivatives\n"); 6107 return Op; 6108 } 6109 6110 if (BaseOpcode->Gradients && !IsA16) { 6111 if (!ST->hasG16()) { 6112 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6113 "support 16 bit derivatives\n"); 6114 return Op; 6115 } 6116 // Activate g16 6117 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6118 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6119 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6120 } 6121 6122 // Don't compress addresses for G16 6123 const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6124 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, 6125 ArgOffset + Intr->GradientStart, PackEndIdx, 6126 Intr->NumGradients); 6127 6128 if (!IsA16) { 6129 // Add uncompressed address 6130 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6131 VAddrs.push_back(Op.getOperand(I)); 6132 } 6133 } else { 6134 for (unsigned I = ArgOffset + Intr->GradientStart; I < VAddrEnd; I++) 6135 VAddrs.push_back(Op.getOperand(I)); 6136 } 6137 6138 // If the register allocator cannot place the address registers contiguously 6139 // without introducing moves, then using the non-sequential address encoding 6140 // is always preferable, since it saves VALU instructions and is usually a 6141 // wash in terms of code size or even better. 6142 // 6143 // However, we currently have no way of hinting to the register allocator that 6144 // MIMG addresses should be placed contiguously when it is possible to do so, 6145 // so force non-NSA for the common 2-address case as a heuristic. 6146 // 6147 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6148 // allocation when possible. 6149 bool UseNSA = 6150 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 6151 SDValue VAddr; 6152 if (!UseNSA) 6153 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6154 6155 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6156 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6157 SDValue Unorm; 6158 if (!BaseOpcode->Sampler) { 6159 Unorm = True; 6160 } else { 6161 auto UnormConst = 6162 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6163 6164 Unorm = UnormConst->getZExtValue() ? True : False; 6165 } 6166 6167 SDValue TFE; 6168 SDValue LWE; 6169 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6170 bool IsTexFail = false; 6171 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6172 return Op; 6173 6174 if (IsTexFail) { 6175 if (!DMaskLanes) { 6176 // Expecting to get an error flag since TFC is on - and dmask is 0 6177 // Force dmask to be at least 1 otherwise the instruction will fail 6178 DMask = 0x1; 6179 DMaskLanes = 1; 6180 NumVDataDwords = 1; 6181 } 6182 NumVDataDwords += 1; 6183 AdjustRetType = true; 6184 } 6185 6186 // Has something earlier tagged that the return type needs adjusting 6187 // This happens if the instruction is a load or has set TexFailCtrl flags 6188 if (AdjustRetType) { 6189 // NumVDataDwords reflects the true number of dwords required in the return type 6190 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6191 // This is a no-op load. This can be eliminated 6192 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6193 if (isa<MemSDNode>(Op)) 6194 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6195 return Undef; 6196 } 6197 6198 EVT NewVT = NumVDataDwords > 1 ? 6199 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6200 : MVT::i32; 6201 6202 ResultTypes[0] = NewVT; 6203 if (ResultTypes.size() == 3) { 6204 // Original result was aggregate type used for TexFailCtrl results 6205 // The actual instruction returns as a vector type which has now been 6206 // created. Remove the aggregate result. 6207 ResultTypes.erase(&ResultTypes[1]); 6208 } 6209 } 6210 6211 unsigned CPol = cast<ConstantSDNode>( 6212 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6213 if (BaseOpcode->Atomic) 6214 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6215 if (CPol & ~AMDGPU::CPol::ALL) 6216 return Op; 6217 6218 SmallVector<SDValue, 26> Ops; 6219 if (BaseOpcode->Store || BaseOpcode->Atomic) 6220 Ops.push_back(VData); // vdata 6221 if (UseNSA) 6222 append_range(Ops, VAddrs); 6223 else 6224 Ops.push_back(VAddr); 6225 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6226 if (BaseOpcode->Sampler) 6227 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6228 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6229 if (IsGFX10Plus) 6230 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6231 Ops.push_back(Unorm); 6232 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6233 Ops.push_back(IsA16 && // r128, a16 for gfx9 6234 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6235 if (IsGFX10Plus) 6236 Ops.push_back(IsA16 ? True : False); 6237 if (!Subtarget->hasGFX90AInsts()) { 6238 Ops.push_back(TFE); //tfe 6239 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6240 report_fatal_error("TFE is not supported on this GPU"); 6241 } 6242 Ops.push_back(LWE); // lwe 6243 if (!IsGFX10Plus) 6244 Ops.push_back(DimInfo->DA ? True : False); 6245 if (BaseOpcode->HasD16) 6246 Ops.push_back(IsD16 ? True : False); 6247 if (isa<MemSDNode>(Op)) 6248 Ops.push_back(Op.getOperand(0)); // chain 6249 6250 int NumVAddrDwords = 6251 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6252 int Opcode = -1; 6253 6254 if (IsGFX10Plus) { 6255 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6256 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6257 : AMDGPU::MIMGEncGfx10Default, 6258 NumVDataDwords, NumVAddrDwords); 6259 } else { 6260 if (Subtarget->hasGFX90AInsts()) { 6261 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6262 NumVDataDwords, NumVAddrDwords); 6263 if (Opcode == -1) 6264 report_fatal_error( 6265 "requested image instruction is not supported on this GPU"); 6266 } 6267 if (Opcode == -1 && 6268 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6269 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6270 NumVDataDwords, NumVAddrDwords); 6271 if (Opcode == -1) 6272 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6273 NumVDataDwords, NumVAddrDwords); 6274 } 6275 assert(Opcode != -1); 6276 6277 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6278 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6279 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6280 DAG.setNodeMemRefs(NewNode, {MemRef}); 6281 } 6282 6283 if (BaseOpcode->AtomicX2) { 6284 SmallVector<SDValue, 1> Elt; 6285 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6286 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6287 } 6288 if (BaseOpcode->Store) 6289 return SDValue(NewNode, 0); 6290 return constructRetValue(DAG, NewNode, 6291 OrigResultTypes, IsTexFail, 6292 Subtarget->hasUnpackedD16VMem(), IsD16, 6293 DMaskLanes, NumVDataDwords, DL); 6294 } 6295 6296 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6297 SDValue Offset, SDValue CachePolicy, 6298 SelectionDAG &DAG) const { 6299 MachineFunction &MF = DAG.getMachineFunction(); 6300 6301 const DataLayout &DataLayout = DAG.getDataLayout(); 6302 Align Alignment = 6303 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6304 6305 MachineMemOperand *MMO = MF.getMachineMemOperand( 6306 MachinePointerInfo(), 6307 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6308 MachineMemOperand::MOInvariant, 6309 VT.getStoreSize(), Alignment); 6310 6311 if (!Offset->isDivergent()) { 6312 SDValue Ops[] = { 6313 Rsrc, 6314 Offset, // Offset 6315 CachePolicy 6316 }; 6317 6318 // Widen vec3 load to vec4. 6319 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6320 EVT WidenedVT = 6321 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6322 auto WidenedOp = DAG.getMemIntrinsicNode( 6323 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6324 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6325 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6326 DAG.getVectorIdxConstant(0, DL)); 6327 return Subvector; 6328 } 6329 6330 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6331 DAG.getVTList(VT), Ops, VT, MMO); 6332 } 6333 6334 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6335 // assume that the buffer is unswizzled. 6336 SmallVector<SDValue, 4> Loads; 6337 unsigned NumLoads = 1; 6338 MVT LoadVT = VT.getSimpleVT(); 6339 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6340 assert((LoadVT.getScalarType() == MVT::i32 || 6341 LoadVT.getScalarType() == MVT::f32)); 6342 6343 if (NumElts == 8 || NumElts == 16) { 6344 NumLoads = NumElts / 4; 6345 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6346 } 6347 6348 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6349 SDValue Ops[] = { 6350 DAG.getEntryNode(), // Chain 6351 Rsrc, // rsrc 6352 DAG.getConstant(0, DL, MVT::i32), // vindex 6353 {}, // voffset 6354 {}, // soffset 6355 {}, // offset 6356 CachePolicy, // cachepolicy 6357 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6358 }; 6359 6360 // Use the alignment to ensure that the required offsets will fit into the 6361 // immediate offsets. 6362 setBufferOffsets(Offset, DAG, &Ops[3], 6363 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6364 6365 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6366 for (unsigned i = 0; i < NumLoads; ++i) { 6367 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6368 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6369 LoadVT, MMO, DAG)); 6370 } 6371 6372 if (NumElts == 8 || NumElts == 16) 6373 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6374 6375 return Loads[0]; 6376 } 6377 6378 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6379 SelectionDAG &DAG) const { 6380 MachineFunction &MF = DAG.getMachineFunction(); 6381 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6382 6383 EVT VT = Op.getValueType(); 6384 SDLoc DL(Op); 6385 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6386 6387 // TODO: Should this propagate fast-math-flags? 6388 6389 switch (IntrinsicID) { 6390 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6391 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6392 return emitNonHSAIntrinsicError(DAG, DL, VT); 6393 return getPreloadedValue(DAG, *MFI, VT, 6394 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6395 } 6396 case Intrinsic::amdgcn_dispatch_ptr: 6397 case Intrinsic::amdgcn_queue_ptr: { 6398 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6399 DiagnosticInfoUnsupported BadIntrin( 6400 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6401 DL.getDebugLoc()); 6402 DAG.getContext()->diagnose(BadIntrin); 6403 return DAG.getUNDEF(VT); 6404 } 6405 6406 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6407 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6408 return getPreloadedValue(DAG, *MFI, VT, RegID); 6409 } 6410 case Intrinsic::amdgcn_implicitarg_ptr: { 6411 if (MFI->isEntryFunction()) 6412 return getImplicitArgPtr(DAG, DL); 6413 return getPreloadedValue(DAG, *MFI, VT, 6414 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6415 } 6416 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6417 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6418 // This only makes sense to call in a kernel, so just lower to null. 6419 return DAG.getConstant(0, DL, VT); 6420 } 6421 6422 return getPreloadedValue(DAG, *MFI, VT, 6423 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6424 } 6425 case Intrinsic::amdgcn_dispatch_id: { 6426 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6427 } 6428 case Intrinsic::amdgcn_rcp: 6429 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6430 case Intrinsic::amdgcn_rsq: 6431 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6432 case Intrinsic::amdgcn_rsq_legacy: 6433 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6434 return emitRemovedIntrinsicError(DAG, DL, VT); 6435 return SDValue(); 6436 case Intrinsic::amdgcn_rcp_legacy: 6437 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6438 return emitRemovedIntrinsicError(DAG, DL, VT); 6439 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6440 case Intrinsic::amdgcn_rsq_clamp: { 6441 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6442 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6443 6444 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6445 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6446 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6447 6448 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6449 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6450 DAG.getConstantFP(Max, DL, VT)); 6451 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6452 DAG.getConstantFP(Min, DL, VT)); 6453 } 6454 case Intrinsic::r600_read_ngroups_x: 6455 if (Subtarget->isAmdHsaOS()) 6456 return emitNonHSAIntrinsicError(DAG, DL, VT); 6457 6458 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6459 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6460 false); 6461 case Intrinsic::r600_read_ngroups_y: 6462 if (Subtarget->isAmdHsaOS()) 6463 return emitNonHSAIntrinsicError(DAG, DL, VT); 6464 6465 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6466 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6467 false); 6468 case Intrinsic::r600_read_ngroups_z: 6469 if (Subtarget->isAmdHsaOS()) 6470 return emitNonHSAIntrinsicError(DAG, DL, VT); 6471 6472 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6473 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6474 false); 6475 case Intrinsic::r600_read_global_size_x: 6476 if (Subtarget->isAmdHsaOS()) 6477 return emitNonHSAIntrinsicError(DAG, DL, VT); 6478 6479 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6480 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6481 Align(4), false); 6482 case Intrinsic::r600_read_global_size_y: 6483 if (Subtarget->isAmdHsaOS()) 6484 return emitNonHSAIntrinsicError(DAG, DL, VT); 6485 6486 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6487 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6488 Align(4), false); 6489 case Intrinsic::r600_read_global_size_z: 6490 if (Subtarget->isAmdHsaOS()) 6491 return emitNonHSAIntrinsicError(DAG, DL, VT); 6492 6493 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6494 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6495 Align(4), false); 6496 case Intrinsic::r600_read_local_size_x: 6497 if (Subtarget->isAmdHsaOS()) 6498 return emitNonHSAIntrinsicError(DAG, DL, VT); 6499 6500 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6501 SI::KernelInputOffsets::LOCAL_SIZE_X); 6502 case Intrinsic::r600_read_local_size_y: 6503 if (Subtarget->isAmdHsaOS()) 6504 return emitNonHSAIntrinsicError(DAG, DL, VT); 6505 6506 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6507 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6508 case Intrinsic::r600_read_local_size_z: 6509 if (Subtarget->isAmdHsaOS()) 6510 return emitNonHSAIntrinsicError(DAG, DL, VT); 6511 6512 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6513 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6514 case Intrinsic::amdgcn_workgroup_id_x: 6515 return getPreloadedValue(DAG, *MFI, VT, 6516 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6517 case Intrinsic::amdgcn_workgroup_id_y: 6518 return getPreloadedValue(DAG, *MFI, VT, 6519 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6520 case Intrinsic::amdgcn_workgroup_id_z: 6521 return getPreloadedValue(DAG, *MFI, VT, 6522 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6523 case Intrinsic::amdgcn_workitem_id_x: 6524 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6525 SDLoc(DAG.getEntryNode()), 6526 MFI->getArgInfo().WorkItemIDX); 6527 case Intrinsic::amdgcn_workitem_id_y: 6528 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6529 SDLoc(DAG.getEntryNode()), 6530 MFI->getArgInfo().WorkItemIDY); 6531 case Intrinsic::amdgcn_workitem_id_z: 6532 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6533 SDLoc(DAG.getEntryNode()), 6534 MFI->getArgInfo().WorkItemIDZ); 6535 case Intrinsic::amdgcn_wavefrontsize: 6536 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6537 SDLoc(Op), MVT::i32); 6538 case Intrinsic::amdgcn_s_buffer_load: { 6539 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6540 if (CPol & ~AMDGPU::CPol::ALL) 6541 return Op; 6542 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6543 DAG); 6544 } 6545 case Intrinsic::amdgcn_fdiv_fast: 6546 return lowerFDIV_FAST(Op, DAG); 6547 case Intrinsic::amdgcn_sin: 6548 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6549 6550 case Intrinsic::amdgcn_cos: 6551 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6552 6553 case Intrinsic::amdgcn_mul_u24: 6554 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6555 case Intrinsic::amdgcn_mul_i24: 6556 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6557 6558 case Intrinsic::amdgcn_log_clamp: { 6559 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6560 return SDValue(); 6561 6562 return emitRemovedIntrinsicError(DAG, DL, VT); 6563 } 6564 case Intrinsic::amdgcn_ldexp: 6565 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6566 Op.getOperand(1), Op.getOperand(2)); 6567 6568 case Intrinsic::amdgcn_fract: 6569 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6570 6571 case Intrinsic::amdgcn_class: 6572 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6573 Op.getOperand(1), Op.getOperand(2)); 6574 case Intrinsic::amdgcn_div_fmas: 6575 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6576 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6577 Op.getOperand(4)); 6578 6579 case Intrinsic::amdgcn_div_fixup: 6580 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6581 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6582 6583 case Intrinsic::amdgcn_div_scale: { 6584 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6585 6586 // Translate to the operands expected by the machine instruction. The 6587 // first parameter must be the same as the first instruction. 6588 SDValue Numerator = Op.getOperand(1); 6589 SDValue Denominator = Op.getOperand(2); 6590 6591 // Note this order is opposite of the machine instruction's operations, 6592 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6593 // intrinsic has the numerator as the first operand to match a normal 6594 // division operation. 6595 6596 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6597 6598 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6599 Denominator, Numerator); 6600 } 6601 case Intrinsic::amdgcn_icmp: { 6602 // There is a Pat that handles this variant, so return it as-is. 6603 if (Op.getOperand(1).getValueType() == MVT::i1 && 6604 Op.getConstantOperandVal(2) == 0 && 6605 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6606 return Op; 6607 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6608 } 6609 case Intrinsic::amdgcn_fcmp: { 6610 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6611 } 6612 case Intrinsic::amdgcn_ballot: 6613 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6614 case Intrinsic::amdgcn_fmed3: 6615 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6616 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6617 case Intrinsic::amdgcn_fdot2: 6618 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6619 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6620 Op.getOperand(4)); 6621 case Intrinsic::amdgcn_fmul_legacy: 6622 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6623 Op.getOperand(1), Op.getOperand(2)); 6624 case Intrinsic::amdgcn_sffbh: 6625 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6626 case Intrinsic::amdgcn_sbfe: 6627 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6628 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6629 case Intrinsic::amdgcn_ubfe: 6630 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6631 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6632 case Intrinsic::amdgcn_cvt_pkrtz: 6633 case Intrinsic::amdgcn_cvt_pknorm_i16: 6634 case Intrinsic::amdgcn_cvt_pknorm_u16: 6635 case Intrinsic::amdgcn_cvt_pk_i16: 6636 case Intrinsic::amdgcn_cvt_pk_u16: { 6637 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6638 EVT VT = Op.getValueType(); 6639 unsigned Opcode; 6640 6641 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6642 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6643 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6644 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6645 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6646 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6647 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6648 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6649 else 6650 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6651 6652 if (isTypeLegal(VT)) 6653 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6654 6655 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6656 Op.getOperand(1), Op.getOperand(2)); 6657 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6658 } 6659 case Intrinsic::amdgcn_fmad_ftz: 6660 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6661 Op.getOperand(2), Op.getOperand(3)); 6662 6663 case Intrinsic::amdgcn_if_break: 6664 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6665 Op->getOperand(1), Op->getOperand(2)), 0); 6666 6667 case Intrinsic::amdgcn_groupstaticsize: { 6668 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6669 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6670 return Op; 6671 6672 const Module *M = MF.getFunction().getParent(); 6673 const GlobalValue *GV = 6674 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6675 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6676 SIInstrInfo::MO_ABS32_LO); 6677 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6678 } 6679 case Intrinsic::amdgcn_is_shared: 6680 case Intrinsic::amdgcn_is_private: { 6681 SDLoc SL(Op); 6682 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6683 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6684 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6685 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6686 Op.getOperand(1)); 6687 6688 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6689 DAG.getConstant(1, SL, MVT::i32)); 6690 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6691 } 6692 case Intrinsic::amdgcn_alignbit: 6693 return DAG.getNode(ISD::FSHR, DL, VT, 6694 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6695 case Intrinsic::amdgcn_reloc_constant: { 6696 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6697 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6698 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6699 auto RelocSymbol = cast<GlobalVariable>( 6700 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6701 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6702 SIInstrInfo::MO_ABS32_LO); 6703 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6704 } 6705 default: 6706 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6707 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6708 return lowerImage(Op, ImageDimIntr, DAG, false); 6709 6710 return Op; 6711 } 6712 } 6713 6714 // This function computes an appropriate offset to pass to 6715 // MachineMemOperand::setOffset() based on the offset inputs to 6716 // an intrinsic. If any of the offsets are non-contstant or 6717 // if VIndex is non-zero then this function returns 0. Otherwise, 6718 // it returns the sum of VOffset, SOffset, and Offset. 6719 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6720 SDValue SOffset, 6721 SDValue Offset, 6722 SDValue VIndex = SDValue()) { 6723 6724 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6725 !isa<ConstantSDNode>(Offset)) 6726 return 0; 6727 6728 if (VIndex) { 6729 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6730 return 0; 6731 } 6732 6733 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6734 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6735 cast<ConstantSDNode>(Offset)->getSExtValue(); 6736 } 6737 6738 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6739 SelectionDAG &DAG, 6740 unsigned NewOpcode) const { 6741 SDLoc DL(Op); 6742 6743 SDValue VData = Op.getOperand(2); 6744 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6745 SDValue Ops[] = { 6746 Op.getOperand(0), // Chain 6747 VData, // vdata 6748 Op.getOperand(3), // rsrc 6749 DAG.getConstant(0, DL, MVT::i32), // vindex 6750 Offsets.first, // voffset 6751 Op.getOperand(5), // soffset 6752 Offsets.second, // offset 6753 Op.getOperand(6), // cachepolicy 6754 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6755 }; 6756 6757 auto *M = cast<MemSDNode>(Op); 6758 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6759 6760 EVT MemVT = VData.getValueType(); 6761 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6762 M->getMemOperand()); 6763 } 6764 6765 SDValue 6766 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6767 unsigned NewOpcode) const { 6768 SDLoc DL(Op); 6769 6770 SDValue VData = Op.getOperand(2); 6771 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6772 SDValue Ops[] = { 6773 Op.getOperand(0), // Chain 6774 VData, // vdata 6775 Op.getOperand(3), // rsrc 6776 Op.getOperand(4), // vindex 6777 Offsets.first, // voffset 6778 Op.getOperand(6), // soffset 6779 Offsets.second, // offset 6780 Op.getOperand(7), // cachepolicy 6781 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6782 }; 6783 6784 auto *M = cast<MemSDNode>(Op); 6785 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6786 Ops[3])); 6787 6788 EVT MemVT = VData.getValueType(); 6789 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6790 M->getMemOperand()); 6791 } 6792 6793 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6794 SelectionDAG &DAG) const { 6795 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6796 SDLoc DL(Op); 6797 6798 switch (IntrID) { 6799 case Intrinsic::amdgcn_ds_ordered_add: 6800 case Intrinsic::amdgcn_ds_ordered_swap: { 6801 MemSDNode *M = cast<MemSDNode>(Op); 6802 SDValue Chain = M->getOperand(0); 6803 SDValue M0 = M->getOperand(2); 6804 SDValue Value = M->getOperand(3); 6805 unsigned IndexOperand = M->getConstantOperandVal(7); 6806 unsigned WaveRelease = M->getConstantOperandVal(8); 6807 unsigned WaveDone = M->getConstantOperandVal(9); 6808 6809 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6810 IndexOperand &= ~0x3f; 6811 unsigned CountDw = 0; 6812 6813 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6814 CountDw = (IndexOperand >> 24) & 0xf; 6815 IndexOperand &= ~(0xf << 24); 6816 6817 if (CountDw < 1 || CountDw > 4) { 6818 report_fatal_error( 6819 "ds_ordered_count: dword count must be between 1 and 4"); 6820 } 6821 } 6822 6823 if (IndexOperand) 6824 report_fatal_error("ds_ordered_count: bad index operand"); 6825 6826 if (WaveDone && !WaveRelease) 6827 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6828 6829 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6830 unsigned ShaderType = 6831 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6832 unsigned Offset0 = OrderedCountIndex << 2; 6833 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6834 (Instruction << 4); 6835 6836 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6837 Offset1 |= (CountDw - 1) << 6; 6838 6839 unsigned Offset = Offset0 | (Offset1 << 8); 6840 6841 SDValue Ops[] = { 6842 Chain, 6843 Value, 6844 DAG.getTargetConstant(Offset, DL, MVT::i16), 6845 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6846 }; 6847 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6848 M->getVTList(), Ops, M->getMemoryVT(), 6849 M->getMemOperand()); 6850 } 6851 case Intrinsic::amdgcn_ds_fadd: { 6852 MemSDNode *M = cast<MemSDNode>(Op); 6853 unsigned Opc; 6854 switch (IntrID) { 6855 case Intrinsic::amdgcn_ds_fadd: 6856 Opc = ISD::ATOMIC_LOAD_FADD; 6857 break; 6858 } 6859 6860 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6861 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6862 M->getMemOperand()); 6863 } 6864 case Intrinsic::amdgcn_atomic_inc: 6865 case Intrinsic::amdgcn_atomic_dec: 6866 case Intrinsic::amdgcn_ds_fmin: 6867 case Intrinsic::amdgcn_ds_fmax: { 6868 MemSDNode *M = cast<MemSDNode>(Op); 6869 unsigned Opc; 6870 switch (IntrID) { 6871 case Intrinsic::amdgcn_atomic_inc: 6872 Opc = AMDGPUISD::ATOMIC_INC; 6873 break; 6874 case Intrinsic::amdgcn_atomic_dec: 6875 Opc = AMDGPUISD::ATOMIC_DEC; 6876 break; 6877 case Intrinsic::amdgcn_ds_fmin: 6878 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6879 break; 6880 case Intrinsic::amdgcn_ds_fmax: 6881 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6882 break; 6883 default: 6884 llvm_unreachable("Unknown intrinsic!"); 6885 } 6886 SDValue Ops[] = { 6887 M->getOperand(0), // Chain 6888 M->getOperand(2), // Ptr 6889 M->getOperand(3) // Value 6890 }; 6891 6892 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6893 M->getMemoryVT(), M->getMemOperand()); 6894 } 6895 case Intrinsic::amdgcn_buffer_load: 6896 case Intrinsic::amdgcn_buffer_load_format: { 6897 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6898 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6899 unsigned IdxEn = 1; 6900 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6901 IdxEn = Idx->getZExtValue() != 0; 6902 SDValue Ops[] = { 6903 Op.getOperand(0), // Chain 6904 Op.getOperand(2), // rsrc 6905 Op.getOperand(3), // vindex 6906 SDValue(), // voffset -- will be set by setBufferOffsets 6907 SDValue(), // soffset -- will be set by setBufferOffsets 6908 SDValue(), // offset -- will be set by setBufferOffsets 6909 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6910 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6911 }; 6912 6913 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6914 // We don't know the offset if vindex is non-zero, so clear it. 6915 if (IdxEn) 6916 Offset = 0; 6917 6918 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6919 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6920 6921 EVT VT = Op.getValueType(); 6922 EVT IntVT = VT.changeTypeToInteger(); 6923 auto *M = cast<MemSDNode>(Op); 6924 M->getMemOperand()->setOffset(Offset); 6925 EVT LoadVT = Op.getValueType(); 6926 6927 if (LoadVT.getScalarType() == MVT::f16) 6928 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6929 M, DAG, Ops); 6930 6931 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6932 if (LoadVT.getScalarType() == MVT::i8 || 6933 LoadVT.getScalarType() == MVT::i16) 6934 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6935 6936 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6937 M->getMemOperand(), DAG); 6938 } 6939 case Intrinsic::amdgcn_raw_buffer_load: 6940 case Intrinsic::amdgcn_raw_buffer_load_format: { 6941 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6942 6943 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6944 SDValue Ops[] = { 6945 Op.getOperand(0), // Chain 6946 Op.getOperand(2), // rsrc 6947 DAG.getConstant(0, DL, MVT::i32), // vindex 6948 Offsets.first, // voffset 6949 Op.getOperand(4), // soffset 6950 Offsets.second, // offset 6951 Op.getOperand(5), // cachepolicy, swizzled buffer 6952 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6953 }; 6954 6955 auto *M = cast<MemSDNode>(Op); 6956 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6957 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6958 } 6959 case Intrinsic::amdgcn_struct_buffer_load: 6960 case Intrinsic::amdgcn_struct_buffer_load_format: { 6961 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6962 6963 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6964 SDValue Ops[] = { 6965 Op.getOperand(0), // Chain 6966 Op.getOperand(2), // rsrc 6967 Op.getOperand(3), // vindex 6968 Offsets.first, // voffset 6969 Op.getOperand(5), // soffset 6970 Offsets.second, // offset 6971 Op.getOperand(6), // cachepolicy, swizzled buffer 6972 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6973 }; 6974 6975 auto *M = cast<MemSDNode>(Op); 6976 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6977 Ops[2])); 6978 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6979 } 6980 case Intrinsic::amdgcn_tbuffer_load: { 6981 MemSDNode *M = cast<MemSDNode>(Op); 6982 EVT LoadVT = Op.getValueType(); 6983 6984 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6985 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6986 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6987 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6988 unsigned IdxEn = 1; 6989 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6990 IdxEn = Idx->getZExtValue() != 0; 6991 SDValue Ops[] = { 6992 Op.getOperand(0), // Chain 6993 Op.getOperand(2), // rsrc 6994 Op.getOperand(3), // vindex 6995 Op.getOperand(4), // voffset 6996 Op.getOperand(5), // soffset 6997 Op.getOperand(6), // offset 6998 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6999 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7000 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7001 }; 7002 7003 if (LoadVT.getScalarType() == MVT::f16) 7004 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7005 M, DAG, Ops); 7006 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7007 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7008 DAG); 7009 } 7010 case Intrinsic::amdgcn_raw_tbuffer_load: { 7011 MemSDNode *M = cast<MemSDNode>(Op); 7012 EVT LoadVT = Op.getValueType(); 7013 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7014 7015 SDValue Ops[] = { 7016 Op.getOperand(0), // Chain 7017 Op.getOperand(2), // rsrc 7018 DAG.getConstant(0, DL, MVT::i32), // vindex 7019 Offsets.first, // voffset 7020 Op.getOperand(4), // soffset 7021 Offsets.second, // offset 7022 Op.getOperand(5), // format 7023 Op.getOperand(6), // cachepolicy, swizzled buffer 7024 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7025 }; 7026 7027 if (LoadVT.getScalarType() == MVT::f16) 7028 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7029 M, DAG, Ops); 7030 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7031 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7032 DAG); 7033 } 7034 case Intrinsic::amdgcn_struct_tbuffer_load: { 7035 MemSDNode *M = cast<MemSDNode>(Op); 7036 EVT LoadVT = Op.getValueType(); 7037 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7038 7039 SDValue Ops[] = { 7040 Op.getOperand(0), // Chain 7041 Op.getOperand(2), // rsrc 7042 Op.getOperand(3), // vindex 7043 Offsets.first, // voffset 7044 Op.getOperand(5), // soffset 7045 Offsets.second, // offset 7046 Op.getOperand(6), // format 7047 Op.getOperand(7), // cachepolicy, swizzled buffer 7048 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7049 }; 7050 7051 if (LoadVT.getScalarType() == MVT::f16) 7052 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7053 M, DAG, Ops); 7054 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7055 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7056 DAG); 7057 } 7058 case Intrinsic::amdgcn_buffer_atomic_swap: 7059 case Intrinsic::amdgcn_buffer_atomic_add: 7060 case Intrinsic::amdgcn_buffer_atomic_sub: 7061 case Intrinsic::amdgcn_buffer_atomic_csub: 7062 case Intrinsic::amdgcn_buffer_atomic_smin: 7063 case Intrinsic::amdgcn_buffer_atomic_umin: 7064 case Intrinsic::amdgcn_buffer_atomic_smax: 7065 case Intrinsic::amdgcn_buffer_atomic_umax: 7066 case Intrinsic::amdgcn_buffer_atomic_and: 7067 case Intrinsic::amdgcn_buffer_atomic_or: 7068 case Intrinsic::amdgcn_buffer_atomic_xor: 7069 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7070 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7071 unsigned IdxEn = 1; 7072 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7073 IdxEn = Idx->getZExtValue() != 0; 7074 SDValue Ops[] = { 7075 Op.getOperand(0), // Chain 7076 Op.getOperand(2), // vdata 7077 Op.getOperand(3), // rsrc 7078 Op.getOperand(4), // vindex 7079 SDValue(), // voffset -- will be set by setBufferOffsets 7080 SDValue(), // soffset -- will be set by setBufferOffsets 7081 SDValue(), // offset -- will be set by setBufferOffsets 7082 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7083 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7084 }; 7085 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7086 // We don't know the offset if vindex is non-zero, so clear it. 7087 if (IdxEn) 7088 Offset = 0; 7089 EVT VT = Op.getValueType(); 7090 7091 auto *M = cast<MemSDNode>(Op); 7092 M->getMemOperand()->setOffset(Offset); 7093 unsigned Opcode = 0; 7094 7095 switch (IntrID) { 7096 case Intrinsic::amdgcn_buffer_atomic_swap: 7097 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7098 break; 7099 case Intrinsic::amdgcn_buffer_atomic_add: 7100 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7101 break; 7102 case Intrinsic::amdgcn_buffer_atomic_sub: 7103 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7104 break; 7105 case Intrinsic::amdgcn_buffer_atomic_csub: 7106 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7107 break; 7108 case Intrinsic::amdgcn_buffer_atomic_smin: 7109 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7110 break; 7111 case Intrinsic::amdgcn_buffer_atomic_umin: 7112 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7113 break; 7114 case Intrinsic::amdgcn_buffer_atomic_smax: 7115 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7116 break; 7117 case Intrinsic::amdgcn_buffer_atomic_umax: 7118 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7119 break; 7120 case Intrinsic::amdgcn_buffer_atomic_and: 7121 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7122 break; 7123 case Intrinsic::amdgcn_buffer_atomic_or: 7124 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7125 break; 7126 case Intrinsic::amdgcn_buffer_atomic_xor: 7127 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7128 break; 7129 case Intrinsic::amdgcn_buffer_atomic_fadd: 7130 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7131 DiagnosticInfoUnsupported 7132 NoFpRet(DAG.getMachineFunction().getFunction(), 7133 "return versions of fp atomics not supported", 7134 DL.getDebugLoc(), DS_Error); 7135 DAG.getContext()->diagnose(NoFpRet); 7136 return SDValue(); 7137 } 7138 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7139 break; 7140 default: 7141 llvm_unreachable("unhandled atomic opcode"); 7142 } 7143 7144 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7145 M->getMemOperand()); 7146 } 7147 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7148 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7149 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7150 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7151 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7152 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7153 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7154 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7155 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7156 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7157 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7158 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7159 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7160 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7161 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7162 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7163 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7164 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7165 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7166 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7167 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7168 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7169 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7170 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7171 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7172 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7173 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7174 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7175 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7176 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7177 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7178 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7179 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7180 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7181 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7182 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7183 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7184 return lowerStructBufferAtomicIntrin(Op, DAG, 7185 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7186 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7187 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7188 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7189 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7190 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7191 return lowerStructBufferAtomicIntrin(Op, DAG, 7192 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7193 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7194 return lowerStructBufferAtomicIntrin(Op, DAG, 7195 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7196 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7197 return lowerStructBufferAtomicIntrin(Op, DAG, 7198 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7199 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7200 return lowerStructBufferAtomicIntrin(Op, DAG, 7201 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7202 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7203 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7204 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7205 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7206 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7207 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7208 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7209 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7210 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7211 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7212 7213 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7214 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7215 unsigned IdxEn = 1; 7216 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7217 IdxEn = Idx->getZExtValue() != 0; 7218 SDValue Ops[] = { 7219 Op.getOperand(0), // Chain 7220 Op.getOperand(2), // src 7221 Op.getOperand(3), // cmp 7222 Op.getOperand(4), // rsrc 7223 Op.getOperand(5), // vindex 7224 SDValue(), // voffset -- will be set by setBufferOffsets 7225 SDValue(), // soffset -- will be set by setBufferOffsets 7226 SDValue(), // offset -- will be set by setBufferOffsets 7227 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7228 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7229 }; 7230 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7231 // We don't know the offset if vindex is non-zero, so clear it. 7232 if (IdxEn) 7233 Offset = 0; 7234 EVT VT = Op.getValueType(); 7235 auto *M = cast<MemSDNode>(Op); 7236 M->getMemOperand()->setOffset(Offset); 7237 7238 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7239 Op->getVTList(), Ops, VT, M->getMemOperand()); 7240 } 7241 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7242 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7243 SDValue Ops[] = { 7244 Op.getOperand(0), // Chain 7245 Op.getOperand(2), // src 7246 Op.getOperand(3), // cmp 7247 Op.getOperand(4), // rsrc 7248 DAG.getConstant(0, DL, MVT::i32), // vindex 7249 Offsets.first, // voffset 7250 Op.getOperand(6), // soffset 7251 Offsets.second, // offset 7252 Op.getOperand(7), // cachepolicy 7253 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7254 }; 7255 EVT VT = Op.getValueType(); 7256 auto *M = cast<MemSDNode>(Op); 7257 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7258 7259 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7260 Op->getVTList(), Ops, VT, M->getMemOperand()); 7261 } 7262 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7263 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7264 SDValue Ops[] = { 7265 Op.getOperand(0), // Chain 7266 Op.getOperand(2), // src 7267 Op.getOperand(3), // cmp 7268 Op.getOperand(4), // rsrc 7269 Op.getOperand(5), // vindex 7270 Offsets.first, // voffset 7271 Op.getOperand(7), // soffset 7272 Offsets.second, // offset 7273 Op.getOperand(8), // cachepolicy 7274 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7275 }; 7276 EVT VT = Op.getValueType(); 7277 auto *M = cast<MemSDNode>(Op); 7278 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7279 Ops[4])); 7280 7281 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7282 Op->getVTList(), Ops, VT, M->getMemOperand()); 7283 } 7284 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7285 SDLoc DL(Op); 7286 MemSDNode *M = cast<MemSDNode>(Op); 7287 SDValue NodePtr = M->getOperand(2); 7288 SDValue RayExtent = M->getOperand(3); 7289 SDValue RayOrigin = M->getOperand(4); 7290 SDValue RayDir = M->getOperand(5); 7291 SDValue RayInvDir = M->getOperand(6); 7292 SDValue TDescr = M->getOperand(7); 7293 7294 assert(NodePtr.getValueType() == MVT::i32 || 7295 NodePtr.getValueType() == MVT::i64); 7296 assert(RayDir.getValueType() == MVT::v4f16 || 7297 RayDir.getValueType() == MVT::v4f32); 7298 7299 bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7300 bool Is64 = NodePtr.getValueType() == MVT::i64; 7301 unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa 7302 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa 7303 : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa 7304 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa; 7305 7306 SmallVector<SDValue, 16> Ops; 7307 7308 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7309 SmallVector<SDValue, 3> Lanes; 7310 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7311 if (Lanes[0].getValueSizeInBits() == 32) { 7312 for (unsigned I = 0; I < 3; ++I) 7313 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7314 } else { 7315 if (IsAligned) { 7316 Ops.push_back( 7317 DAG.getBitcast(MVT::i32, 7318 DAG.getBuildVector(MVT::v2f16, DL, 7319 { Lanes[0], Lanes[1] }))); 7320 Ops.push_back(Lanes[2]); 7321 } else { 7322 SDValue Elt0 = Ops.pop_back_val(); 7323 Ops.push_back( 7324 DAG.getBitcast(MVT::i32, 7325 DAG.getBuildVector(MVT::v2f16, DL, 7326 { Elt0, Lanes[0] }))); 7327 Ops.push_back( 7328 DAG.getBitcast(MVT::i32, 7329 DAG.getBuildVector(MVT::v2f16, DL, 7330 { Lanes[1], Lanes[2] }))); 7331 } 7332 } 7333 }; 7334 7335 if (Is64) 7336 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7337 else 7338 Ops.push_back(NodePtr); 7339 7340 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7341 packLanes(RayOrigin, true); 7342 packLanes(RayDir, true); 7343 packLanes(RayInvDir, false); 7344 Ops.push_back(TDescr); 7345 if (IsA16) 7346 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7347 Ops.push_back(M->getChain()); 7348 7349 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7350 MachineMemOperand *MemRef = M->getMemOperand(); 7351 DAG.setNodeMemRefs(NewNode, {MemRef}); 7352 return SDValue(NewNode, 0); 7353 } 7354 case Intrinsic::amdgcn_global_atomic_fadd: 7355 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7356 DiagnosticInfoUnsupported 7357 NoFpRet(DAG.getMachineFunction().getFunction(), 7358 "return versions of fp atomics not supported", 7359 DL.getDebugLoc(), DS_Error); 7360 DAG.getContext()->diagnose(NoFpRet); 7361 return SDValue(); 7362 } 7363 LLVM_FALLTHROUGH; 7364 case Intrinsic::amdgcn_global_atomic_fmin: 7365 case Intrinsic::amdgcn_global_atomic_fmax: 7366 case Intrinsic::amdgcn_flat_atomic_fadd: 7367 case Intrinsic::amdgcn_flat_atomic_fmin: 7368 case Intrinsic::amdgcn_flat_atomic_fmax: { 7369 MemSDNode *M = cast<MemSDNode>(Op); 7370 SDValue Ops[] = { 7371 M->getOperand(0), // Chain 7372 M->getOperand(2), // Ptr 7373 M->getOperand(3) // Value 7374 }; 7375 unsigned Opcode = 0; 7376 switch (IntrID) { 7377 case Intrinsic::amdgcn_global_atomic_fadd: 7378 case Intrinsic::amdgcn_flat_atomic_fadd: { 7379 EVT VT = Op.getOperand(3).getValueType(); 7380 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7381 DAG.getVTList(VT, MVT::Other), Ops, 7382 M->getMemOperand()); 7383 } 7384 case Intrinsic::amdgcn_global_atomic_fmin: 7385 case Intrinsic::amdgcn_flat_atomic_fmin: { 7386 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7387 break; 7388 } 7389 case Intrinsic::amdgcn_global_atomic_fmax: 7390 case Intrinsic::amdgcn_flat_atomic_fmax: { 7391 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7392 break; 7393 } 7394 default: 7395 llvm_unreachable("unhandled atomic opcode"); 7396 } 7397 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7398 M->getVTList(), Ops, M->getMemoryVT(), 7399 M->getMemOperand()); 7400 } 7401 default: 7402 7403 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7404 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7405 return lowerImage(Op, ImageDimIntr, DAG, true); 7406 7407 return SDValue(); 7408 } 7409 } 7410 7411 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7412 // dwordx4 if on SI. 7413 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7414 SDVTList VTList, 7415 ArrayRef<SDValue> Ops, EVT MemVT, 7416 MachineMemOperand *MMO, 7417 SelectionDAG &DAG) const { 7418 EVT VT = VTList.VTs[0]; 7419 EVT WidenedVT = VT; 7420 EVT WidenedMemVT = MemVT; 7421 if (!Subtarget->hasDwordx3LoadStores() && 7422 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7423 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7424 WidenedVT.getVectorElementType(), 4); 7425 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7426 WidenedMemVT.getVectorElementType(), 4); 7427 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7428 } 7429 7430 assert(VTList.NumVTs == 2); 7431 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7432 7433 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7434 WidenedMemVT, MMO); 7435 if (WidenedVT != VT) { 7436 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7437 DAG.getVectorIdxConstant(0, DL)); 7438 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7439 } 7440 return NewOp; 7441 } 7442 7443 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7444 bool ImageStore) const { 7445 EVT StoreVT = VData.getValueType(); 7446 7447 // No change for f16 and legal vector D16 types. 7448 if (!StoreVT.isVector()) 7449 return VData; 7450 7451 SDLoc DL(VData); 7452 unsigned NumElements = StoreVT.getVectorNumElements(); 7453 7454 if (Subtarget->hasUnpackedD16VMem()) { 7455 // We need to unpack the packed data to store. 7456 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7457 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7458 7459 EVT EquivStoreVT = 7460 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7461 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7462 return DAG.UnrollVectorOp(ZExt.getNode()); 7463 } 7464 7465 // The sq block of gfx8.1 does not estimate register use correctly for d16 7466 // image store instructions. The data operand is computed as if it were not a 7467 // d16 image instruction. 7468 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7469 // Bitcast to i16 7470 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7471 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7472 7473 // Decompose into scalars 7474 SmallVector<SDValue, 4> Elts; 7475 DAG.ExtractVectorElements(IntVData, Elts); 7476 7477 // Group pairs of i16 into v2i16 and bitcast to i32 7478 SmallVector<SDValue, 4> PackedElts; 7479 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7480 SDValue Pair = 7481 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7482 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7483 PackedElts.push_back(IntPair); 7484 } 7485 if ((NumElements % 2) == 1) { 7486 // Handle v3i16 7487 unsigned I = Elts.size() / 2; 7488 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7489 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7490 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7491 PackedElts.push_back(IntPair); 7492 } 7493 7494 // Pad using UNDEF 7495 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7496 7497 // Build final vector 7498 EVT VecVT = 7499 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7500 return DAG.getBuildVector(VecVT, DL, PackedElts); 7501 } 7502 7503 if (NumElements == 3) { 7504 EVT IntStoreVT = 7505 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7506 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7507 7508 EVT WidenedStoreVT = EVT::getVectorVT( 7509 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7510 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7511 WidenedStoreVT.getStoreSizeInBits()); 7512 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7513 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7514 } 7515 7516 assert(isTypeLegal(StoreVT)); 7517 return VData; 7518 } 7519 7520 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7521 SelectionDAG &DAG) const { 7522 SDLoc DL(Op); 7523 SDValue Chain = Op.getOperand(0); 7524 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7525 MachineFunction &MF = DAG.getMachineFunction(); 7526 7527 switch (IntrinsicID) { 7528 case Intrinsic::amdgcn_exp_compr: { 7529 SDValue Src0 = Op.getOperand(4); 7530 SDValue Src1 = Op.getOperand(5); 7531 // Hack around illegal type on SI by directly selecting it. 7532 if (isTypeLegal(Src0.getValueType())) 7533 return SDValue(); 7534 7535 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7536 SDValue Undef = DAG.getUNDEF(MVT::f32); 7537 const SDValue Ops[] = { 7538 Op.getOperand(2), // tgt 7539 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7540 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7541 Undef, // src2 7542 Undef, // src3 7543 Op.getOperand(7), // vm 7544 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7545 Op.getOperand(3), // en 7546 Op.getOperand(0) // Chain 7547 }; 7548 7549 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7550 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7551 } 7552 case Intrinsic::amdgcn_s_barrier: { 7553 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7554 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7555 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7556 if (WGSize <= ST.getWavefrontSize()) 7557 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7558 Op.getOperand(0)), 0); 7559 } 7560 return SDValue(); 7561 }; 7562 case Intrinsic::amdgcn_tbuffer_store: { 7563 SDValue VData = Op.getOperand(2); 7564 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7565 if (IsD16) 7566 VData = handleD16VData(VData, DAG); 7567 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7568 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7569 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7570 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7571 unsigned IdxEn = 1; 7572 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7573 IdxEn = Idx->getZExtValue() != 0; 7574 SDValue Ops[] = { 7575 Chain, 7576 VData, // vdata 7577 Op.getOperand(3), // rsrc 7578 Op.getOperand(4), // vindex 7579 Op.getOperand(5), // voffset 7580 Op.getOperand(6), // soffset 7581 Op.getOperand(7), // offset 7582 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7583 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7584 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7585 }; 7586 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7587 AMDGPUISD::TBUFFER_STORE_FORMAT; 7588 MemSDNode *M = cast<MemSDNode>(Op); 7589 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7590 M->getMemoryVT(), M->getMemOperand()); 7591 } 7592 7593 case Intrinsic::amdgcn_struct_tbuffer_store: { 7594 SDValue VData = Op.getOperand(2); 7595 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7596 if (IsD16) 7597 VData = handleD16VData(VData, DAG); 7598 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7599 SDValue Ops[] = { 7600 Chain, 7601 VData, // vdata 7602 Op.getOperand(3), // rsrc 7603 Op.getOperand(4), // vindex 7604 Offsets.first, // voffset 7605 Op.getOperand(6), // soffset 7606 Offsets.second, // offset 7607 Op.getOperand(7), // format 7608 Op.getOperand(8), // cachepolicy, swizzled buffer 7609 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7610 }; 7611 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7612 AMDGPUISD::TBUFFER_STORE_FORMAT; 7613 MemSDNode *M = cast<MemSDNode>(Op); 7614 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7615 M->getMemoryVT(), M->getMemOperand()); 7616 } 7617 7618 case Intrinsic::amdgcn_raw_tbuffer_store: { 7619 SDValue VData = Op.getOperand(2); 7620 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7621 if (IsD16) 7622 VData = handleD16VData(VData, DAG); 7623 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7624 SDValue Ops[] = { 7625 Chain, 7626 VData, // vdata 7627 Op.getOperand(3), // rsrc 7628 DAG.getConstant(0, DL, MVT::i32), // vindex 7629 Offsets.first, // voffset 7630 Op.getOperand(5), // soffset 7631 Offsets.second, // offset 7632 Op.getOperand(6), // format 7633 Op.getOperand(7), // cachepolicy, swizzled buffer 7634 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7635 }; 7636 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7637 AMDGPUISD::TBUFFER_STORE_FORMAT; 7638 MemSDNode *M = cast<MemSDNode>(Op); 7639 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7640 M->getMemoryVT(), M->getMemOperand()); 7641 } 7642 7643 case Intrinsic::amdgcn_buffer_store: 7644 case Intrinsic::amdgcn_buffer_store_format: { 7645 SDValue VData = Op.getOperand(2); 7646 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7647 if (IsD16) 7648 VData = handleD16VData(VData, DAG); 7649 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7650 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7651 unsigned IdxEn = 1; 7652 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7653 IdxEn = Idx->getZExtValue() != 0; 7654 SDValue Ops[] = { 7655 Chain, 7656 VData, 7657 Op.getOperand(3), // rsrc 7658 Op.getOperand(4), // vindex 7659 SDValue(), // voffset -- will be set by setBufferOffsets 7660 SDValue(), // soffset -- will be set by setBufferOffsets 7661 SDValue(), // offset -- will be set by setBufferOffsets 7662 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7663 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7664 }; 7665 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7666 // We don't know the offset if vindex is non-zero, so clear it. 7667 if (IdxEn) 7668 Offset = 0; 7669 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7670 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7671 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7672 MemSDNode *M = cast<MemSDNode>(Op); 7673 M->getMemOperand()->setOffset(Offset); 7674 7675 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7676 EVT VDataType = VData.getValueType().getScalarType(); 7677 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7678 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7679 7680 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7681 M->getMemoryVT(), M->getMemOperand()); 7682 } 7683 7684 case Intrinsic::amdgcn_raw_buffer_store: 7685 case Intrinsic::amdgcn_raw_buffer_store_format: { 7686 const bool IsFormat = 7687 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7688 7689 SDValue VData = Op.getOperand(2); 7690 EVT VDataVT = VData.getValueType(); 7691 EVT EltType = VDataVT.getScalarType(); 7692 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7693 if (IsD16) { 7694 VData = handleD16VData(VData, DAG); 7695 VDataVT = VData.getValueType(); 7696 } 7697 7698 if (!isTypeLegal(VDataVT)) { 7699 VData = 7700 DAG.getNode(ISD::BITCAST, DL, 7701 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7702 } 7703 7704 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7705 SDValue Ops[] = { 7706 Chain, 7707 VData, 7708 Op.getOperand(3), // rsrc 7709 DAG.getConstant(0, DL, MVT::i32), // vindex 7710 Offsets.first, // voffset 7711 Op.getOperand(5), // soffset 7712 Offsets.second, // offset 7713 Op.getOperand(6), // cachepolicy, swizzled buffer 7714 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7715 }; 7716 unsigned Opc = 7717 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7718 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7719 MemSDNode *M = cast<MemSDNode>(Op); 7720 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7721 7722 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7723 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7724 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7725 7726 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7727 M->getMemoryVT(), M->getMemOperand()); 7728 } 7729 7730 case Intrinsic::amdgcn_struct_buffer_store: 7731 case Intrinsic::amdgcn_struct_buffer_store_format: { 7732 const bool IsFormat = 7733 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7734 7735 SDValue VData = Op.getOperand(2); 7736 EVT VDataVT = VData.getValueType(); 7737 EVT EltType = VDataVT.getScalarType(); 7738 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7739 7740 if (IsD16) { 7741 VData = handleD16VData(VData, DAG); 7742 VDataVT = VData.getValueType(); 7743 } 7744 7745 if (!isTypeLegal(VDataVT)) { 7746 VData = 7747 DAG.getNode(ISD::BITCAST, DL, 7748 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7749 } 7750 7751 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7752 SDValue Ops[] = { 7753 Chain, 7754 VData, 7755 Op.getOperand(3), // rsrc 7756 Op.getOperand(4), // vindex 7757 Offsets.first, // voffset 7758 Op.getOperand(6), // soffset 7759 Offsets.second, // offset 7760 Op.getOperand(7), // cachepolicy, swizzled buffer 7761 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7762 }; 7763 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7764 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7765 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7766 MemSDNode *M = cast<MemSDNode>(Op); 7767 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7768 Ops[3])); 7769 7770 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7771 EVT VDataType = VData.getValueType().getScalarType(); 7772 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7773 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7774 7775 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7776 M->getMemoryVT(), M->getMemOperand()); 7777 } 7778 case Intrinsic::amdgcn_end_cf: 7779 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7780 Op->getOperand(2), Chain), 0); 7781 7782 default: { 7783 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7784 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7785 return lowerImage(Op, ImageDimIntr, DAG, true); 7786 7787 return Op; 7788 } 7789 } 7790 } 7791 7792 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7793 // offset (the offset that is included in bounds checking and swizzling, to be 7794 // split between the instruction's voffset and immoffset fields) and soffset 7795 // (the offset that is excluded from bounds checking and swizzling, to go in 7796 // the instruction's soffset field). This function takes the first kind of 7797 // offset and figures out how to split it between voffset and immoffset. 7798 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7799 SDValue Offset, SelectionDAG &DAG) const { 7800 SDLoc DL(Offset); 7801 const unsigned MaxImm = 4095; 7802 SDValue N0 = Offset; 7803 ConstantSDNode *C1 = nullptr; 7804 7805 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7806 N0 = SDValue(); 7807 else if (DAG.isBaseWithConstantOffset(N0)) { 7808 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7809 N0 = N0.getOperand(0); 7810 } 7811 7812 if (C1) { 7813 unsigned ImmOffset = C1->getZExtValue(); 7814 // If the immediate value is too big for the immoffset field, put the value 7815 // and -4096 into the immoffset field so that the value that is copied/added 7816 // for the voffset field is a multiple of 4096, and it stands more chance 7817 // of being CSEd with the copy/add for another similar load/store. 7818 // However, do not do that rounding down to a multiple of 4096 if that is a 7819 // negative number, as it appears to be illegal to have a negative offset 7820 // in the vgpr, even if adding the immediate offset makes it positive. 7821 unsigned Overflow = ImmOffset & ~MaxImm; 7822 ImmOffset -= Overflow; 7823 if ((int32_t)Overflow < 0) { 7824 Overflow += ImmOffset; 7825 ImmOffset = 0; 7826 } 7827 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7828 if (Overflow) { 7829 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7830 if (!N0) 7831 N0 = OverflowVal; 7832 else { 7833 SDValue Ops[] = { N0, OverflowVal }; 7834 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7835 } 7836 } 7837 } 7838 if (!N0) 7839 N0 = DAG.getConstant(0, DL, MVT::i32); 7840 if (!C1) 7841 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7842 return {N0, SDValue(C1, 0)}; 7843 } 7844 7845 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7846 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7847 // pointed to by Offsets. 7848 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7849 SelectionDAG &DAG, SDValue *Offsets, 7850 Align Alignment) const { 7851 SDLoc DL(CombinedOffset); 7852 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7853 uint32_t Imm = C->getZExtValue(); 7854 uint32_t SOffset, ImmOffset; 7855 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7856 Alignment)) { 7857 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7858 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7859 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7860 return SOffset + ImmOffset; 7861 } 7862 } 7863 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7864 SDValue N0 = CombinedOffset.getOperand(0); 7865 SDValue N1 = CombinedOffset.getOperand(1); 7866 uint32_t SOffset, ImmOffset; 7867 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7868 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7869 Subtarget, Alignment)) { 7870 Offsets[0] = N0; 7871 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7872 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7873 return 0; 7874 } 7875 } 7876 Offsets[0] = CombinedOffset; 7877 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7878 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7879 return 0; 7880 } 7881 7882 // Handle 8 bit and 16 bit buffer loads 7883 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7884 EVT LoadVT, SDLoc DL, 7885 ArrayRef<SDValue> Ops, 7886 MemSDNode *M) const { 7887 EVT IntVT = LoadVT.changeTypeToInteger(); 7888 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7889 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7890 7891 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7892 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7893 Ops, IntVT, 7894 M->getMemOperand()); 7895 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7896 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7897 7898 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7899 } 7900 7901 // Handle 8 bit and 16 bit buffer stores 7902 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7903 EVT VDataType, SDLoc DL, 7904 SDValue Ops[], 7905 MemSDNode *M) const { 7906 if (VDataType == MVT::f16) 7907 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7908 7909 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7910 Ops[1] = BufferStoreExt; 7911 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7912 AMDGPUISD::BUFFER_STORE_SHORT; 7913 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7914 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7915 M->getMemOperand()); 7916 } 7917 7918 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7919 ISD::LoadExtType ExtType, SDValue Op, 7920 const SDLoc &SL, EVT VT) { 7921 if (VT.bitsLT(Op.getValueType())) 7922 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7923 7924 switch (ExtType) { 7925 case ISD::SEXTLOAD: 7926 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7927 case ISD::ZEXTLOAD: 7928 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7929 case ISD::EXTLOAD: 7930 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7931 case ISD::NON_EXTLOAD: 7932 return Op; 7933 } 7934 7935 llvm_unreachable("invalid ext type"); 7936 } 7937 7938 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7939 SelectionDAG &DAG = DCI.DAG; 7940 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7941 return SDValue(); 7942 7943 // FIXME: Constant loads should all be marked invariant. 7944 unsigned AS = Ld->getAddressSpace(); 7945 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7946 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7947 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7948 return SDValue(); 7949 7950 // Don't do this early, since it may interfere with adjacent load merging for 7951 // illegal types. We can avoid losing alignment information for exotic types 7952 // pre-legalize. 7953 EVT MemVT = Ld->getMemoryVT(); 7954 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7955 MemVT.getSizeInBits() >= 32) 7956 return SDValue(); 7957 7958 SDLoc SL(Ld); 7959 7960 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7961 "unexpected vector extload"); 7962 7963 // TODO: Drop only high part of range. 7964 SDValue Ptr = Ld->getBasePtr(); 7965 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7966 MVT::i32, SL, Ld->getChain(), Ptr, 7967 Ld->getOffset(), 7968 Ld->getPointerInfo(), MVT::i32, 7969 Ld->getAlignment(), 7970 Ld->getMemOperand()->getFlags(), 7971 Ld->getAAInfo(), 7972 nullptr); // Drop ranges 7973 7974 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7975 if (MemVT.isFloatingPoint()) { 7976 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7977 "unexpected fp extload"); 7978 TruncVT = MemVT.changeTypeToInteger(); 7979 } 7980 7981 SDValue Cvt = NewLoad; 7982 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7983 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7984 DAG.getValueType(TruncVT)); 7985 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7986 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7987 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7988 } else { 7989 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7990 } 7991 7992 EVT VT = Ld->getValueType(0); 7993 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7994 7995 DCI.AddToWorklist(Cvt.getNode()); 7996 7997 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7998 // the appropriate extension from the 32-bit load. 7999 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8000 DCI.AddToWorklist(Cvt.getNode()); 8001 8002 // Handle conversion back to floating point if necessary. 8003 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8004 8005 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8006 } 8007 8008 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8009 SDLoc DL(Op); 8010 LoadSDNode *Load = cast<LoadSDNode>(Op); 8011 ISD::LoadExtType ExtType = Load->getExtensionType(); 8012 EVT MemVT = Load->getMemoryVT(); 8013 8014 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8015 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8016 return SDValue(); 8017 8018 // FIXME: Copied from PPC 8019 // First, load into 32 bits, then truncate to 1 bit. 8020 8021 SDValue Chain = Load->getChain(); 8022 SDValue BasePtr = Load->getBasePtr(); 8023 MachineMemOperand *MMO = Load->getMemOperand(); 8024 8025 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8026 8027 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8028 BasePtr, RealMemVT, MMO); 8029 8030 if (!MemVT.isVector()) { 8031 SDValue Ops[] = { 8032 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8033 NewLD.getValue(1) 8034 }; 8035 8036 return DAG.getMergeValues(Ops, DL); 8037 } 8038 8039 SmallVector<SDValue, 3> Elts; 8040 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8041 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8042 DAG.getConstant(I, DL, MVT::i32)); 8043 8044 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8045 } 8046 8047 SDValue Ops[] = { 8048 DAG.getBuildVector(MemVT, DL, Elts), 8049 NewLD.getValue(1) 8050 }; 8051 8052 return DAG.getMergeValues(Ops, DL); 8053 } 8054 8055 if (!MemVT.isVector()) 8056 return SDValue(); 8057 8058 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8059 "Custom lowering for non-i32 vectors hasn't been implemented."); 8060 8061 unsigned Alignment = Load->getAlignment(); 8062 unsigned AS = Load->getAddressSpace(); 8063 if (Subtarget->hasLDSMisalignedBug() && 8064 AS == AMDGPUAS::FLAT_ADDRESS && 8065 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8066 return SplitVectorLoad(Op, DAG); 8067 } 8068 8069 MachineFunction &MF = DAG.getMachineFunction(); 8070 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8071 // If there is a possibilty that flat instruction access scratch memory 8072 // then we need to use the same legalization rules we use for private. 8073 if (AS == AMDGPUAS::FLAT_ADDRESS && 8074 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8075 AS = MFI->hasFlatScratchInit() ? 8076 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8077 8078 unsigned NumElements = MemVT.getVectorNumElements(); 8079 8080 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8081 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8082 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8083 if (MemVT.isPow2VectorType()) 8084 return SDValue(); 8085 return WidenOrSplitVectorLoad(Op, DAG); 8086 } 8087 // Non-uniform loads will be selected to MUBUF instructions, so they 8088 // have the same legalization requirements as global and private 8089 // loads. 8090 // 8091 } 8092 8093 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8094 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8095 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8096 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8097 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8098 Alignment >= 4 && NumElements < 32) { 8099 if (MemVT.isPow2VectorType()) 8100 return SDValue(); 8101 return WidenOrSplitVectorLoad(Op, DAG); 8102 } 8103 // Non-uniform loads will be selected to MUBUF instructions, so they 8104 // have the same legalization requirements as global and private 8105 // loads. 8106 // 8107 } 8108 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8109 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8110 AS == AMDGPUAS::GLOBAL_ADDRESS || 8111 AS == AMDGPUAS::FLAT_ADDRESS) { 8112 if (NumElements > 4) 8113 return SplitVectorLoad(Op, DAG); 8114 // v3 loads not supported on SI. 8115 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8116 return WidenOrSplitVectorLoad(Op, DAG); 8117 8118 // v3 and v4 loads are supported for private and global memory. 8119 return SDValue(); 8120 } 8121 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8122 // Depending on the setting of the private_element_size field in the 8123 // resource descriptor, we can only make private accesses up to a certain 8124 // size. 8125 switch (Subtarget->getMaxPrivateElementSize()) { 8126 case 4: { 8127 SDValue Ops[2]; 8128 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8129 return DAG.getMergeValues(Ops, DL); 8130 } 8131 case 8: 8132 if (NumElements > 2) 8133 return SplitVectorLoad(Op, DAG); 8134 return SDValue(); 8135 case 16: 8136 // Same as global/flat 8137 if (NumElements > 4) 8138 return SplitVectorLoad(Op, DAG); 8139 // v3 loads not supported on SI. 8140 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8141 return WidenOrSplitVectorLoad(Op, DAG); 8142 8143 return SDValue(); 8144 default: 8145 llvm_unreachable("unsupported private_element_size"); 8146 } 8147 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8148 // Use ds_read_b128 or ds_read_b96 when possible. 8149 if (Subtarget->hasDS96AndDS128() && 8150 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8151 MemVT.getStoreSize() == 12) && 8152 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8153 Load->getAlign())) 8154 return SDValue(); 8155 8156 if (NumElements > 2) 8157 return SplitVectorLoad(Op, DAG); 8158 8159 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8160 // address is negative, then the instruction is incorrectly treated as 8161 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8162 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8163 // load later in the SILoadStoreOptimizer. 8164 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8165 NumElements == 2 && MemVT.getStoreSize() == 8 && 8166 Load->getAlignment() < 8) { 8167 return SplitVectorLoad(Op, DAG); 8168 } 8169 } 8170 8171 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8172 MemVT, *Load->getMemOperand())) { 8173 SDValue Ops[2]; 8174 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8175 return DAG.getMergeValues(Ops, DL); 8176 } 8177 8178 return SDValue(); 8179 } 8180 8181 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8182 EVT VT = Op.getValueType(); 8183 assert(VT.getSizeInBits() == 64); 8184 8185 SDLoc DL(Op); 8186 SDValue Cond = Op.getOperand(0); 8187 8188 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8189 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8190 8191 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8192 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8193 8194 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8195 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8196 8197 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8198 8199 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8200 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8201 8202 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8203 8204 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8205 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8206 } 8207 8208 // Catch division cases where we can use shortcuts with rcp and rsq 8209 // instructions. 8210 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8211 SelectionDAG &DAG) const { 8212 SDLoc SL(Op); 8213 SDValue LHS = Op.getOperand(0); 8214 SDValue RHS = Op.getOperand(1); 8215 EVT VT = Op.getValueType(); 8216 const SDNodeFlags Flags = Op->getFlags(); 8217 8218 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8219 8220 // Without !fpmath accuracy information, we can't do more because we don't 8221 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8222 if (!AllowInaccurateRcp) 8223 return SDValue(); 8224 8225 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8226 if (CLHS->isExactlyValue(1.0)) { 8227 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8228 // the CI documentation has a worst case error of 1 ulp. 8229 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8230 // use it as long as we aren't trying to use denormals. 8231 // 8232 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8233 8234 // 1.0 / sqrt(x) -> rsq(x) 8235 8236 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8237 // error seems really high at 2^29 ULP. 8238 if (RHS.getOpcode() == ISD::FSQRT) 8239 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8240 8241 // 1.0 / x -> rcp(x) 8242 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8243 } 8244 8245 // Same as for 1.0, but expand the sign out of the constant. 8246 if (CLHS->isExactlyValue(-1.0)) { 8247 // -1.0 / x -> rcp (fneg x) 8248 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8249 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8250 } 8251 } 8252 8253 // Turn into multiply by the reciprocal. 8254 // x / y -> x * (1.0 / y) 8255 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8256 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8257 } 8258 8259 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8260 SelectionDAG &DAG) const { 8261 SDLoc SL(Op); 8262 SDValue X = Op.getOperand(0); 8263 SDValue Y = Op.getOperand(1); 8264 EVT VT = Op.getValueType(); 8265 const SDNodeFlags Flags = Op->getFlags(); 8266 8267 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8268 DAG.getTarget().Options.UnsafeFPMath; 8269 if (!AllowInaccurateDiv) 8270 return SDValue(); 8271 8272 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8273 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8274 8275 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8276 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8277 8278 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8279 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8280 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8281 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8282 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8283 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8284 } 8285 8286 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8287 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8288 SDNodeFlags Flags) { 8289 if (GlueChain->getNumValues() <= 1) { 8290 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8291 } 8292 8293 assert(GlueChain->getNumValues() == 3); 8294 8295 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8296 switch (Opcode) { 8297 default: llvm_unreachable("no chain equivalent for opcode"); 8298 case ISD::FMUL: 8299 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8300 break; 8301 } 8302 8303 return DAG.getNode(Opcode, SL, VTList, 8304 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8305 Flags); 8306 } 8307 8308 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8309 EVT VT, SDValue A, SDValue B, SDValue C, 8310 SDValue GlueChain, SDNodeFlags Flags) { 8311 if (GlueChain->getNumValues() <= 1) { 8312 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8313 } 8314 8315 assert(GlueChain->getNumValues() == 3); 8316 8317 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8318 switch (Opcode) { 8319 default: llvm_unreachable("no chain equivalent for opcode"); 8320 case ISD::FMA: 8321 Opcode = AMDGPUISD::FMA_W_CHAIN; 8322 break; 8323 } 8324 8325 return DAG.getNode(Opcode, SL, VTList, 8326 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8327 Flags); 8328 } 8329 8330 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8331 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8332 return FastLowered; 8333 8334 SDLoc SL(Op); 8335 SDValue Src0 = Op.getOperand(0); 8336 SDValue Src1 = Op.getOperand(1); 8337 8338 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8339 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8340 8341 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8342 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8343 8344 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8345 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8346 8347 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8348 } 8349 8350 // Faster 2.5 ULP division that does not support denormals. 8351 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8352 SDLoc SL(Op); 8353 SDValue LHS = Op.getOperand(1); 8354 SDValue RHS = Op.getOperand(2); 8355 8356 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8357 8358 const APFloat K0Val(BitsToFloat(0x6f800000)); 8359 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8360 8361 const APFloat K1Val(BitsToFloat(0x2f800000)); 8362 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8363 8364 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8365 8366 EVT SetCCVT = 8367 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8368 8369 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8370 8371 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8372 8373 // TODO: Should this propagate fast-math-flags? 8374 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8375 8376 // rcp does not support denormals. 8377 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8378 8379 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8380 8381 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8382 } 8383 8384 // Returns immediate value for setting the F32 denorm mode when using the 8385 // S_DENORM_MODE instruction. 8386 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8387 const SDLoc &SL, const GCNSubtarget *ST) { 8388 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8389 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8390 ? FP_DENORM_FLUSH_NONE 8391 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8392 8393 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8394 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8395 } 8396 8397 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8398 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8399 return FastLowered; 8400 8401 // The selection matcher assumes anything with a chain selecting to a 8402 // mayRaiseFPException machine instruction. Since we're introducing a chain 8403 // here, we need to explicitly report nofpexcept for the regular fdiv 8404 // lowering. 8405 SDNodeFlags Flags = Op->getFlags(); 8406 Flags.setNoFPExcept(true); 8407 8408 SDLoc SL(Op); 8409 SDValue LHS = Op.getOperand(0); 8410 SDValue RHS = Op.getOperand(1); 8411 8412 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8413 8414 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8415 8416 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8417 {RHS, RHS, LHS}, Flags); 8418 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8419 {LHS, RHS, LHS}, Flags); 8420 8421 // Denominator is scaled to not be denormal, so using rcp is ok. 8422 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8423 DenominatorScaled, Flags); 8424 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8425 DenominatorScaled, Flags); 8426 8427 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8428 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8429 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8430 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8431 8432 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8433 8434 if (!HasFP32Denormals) { 8435 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8436 // lowering. The chain dependence is insufficient, and we need glue. We do 8437 // not need the glue variants in a strictfp function. 8438 8439 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8440 8441 SDNode *EnableDenorm; 8442 if (Subtarget->hasDenormModeInst()) { 8443 const SDValue EnableDenormValue = 8444 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8445 8446 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8447 DAG.getEntryNode(), EnableDenormValue).getNode(); 8448 } else { 8449 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8450 SL, MVT::i32); 8451 EnableDenorm = 8452 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8453 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8454 } 8455 8456 SDValue Ops[3] = { 8457 NegDivScale0, 8458 SDValue(EnableDenorm, 0), 8459 SDValue(EnableDenorm, 1) 8460 }; 8461 8462 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8463 } 8464 8465 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8466 ApproxRcp, One, NegDivScale0, Flags); 8467 8468 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8469 ApproxRcp, Fma0, Flags); 8470 8471 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8472 Fma1, Fma1, Flags); 8473 8474 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8475 NumeratorScaled, Mul, Flags); 8476 8477 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8478 Fma2, Fma1, Mul, Fma2, Flags); 8479 8480 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8481 NumeratorScaled, Fma3, Flags); 8482 8483 if (!HasFP32Denormals) { 8484 SDNode *DisableDenorm; 8485 if (Subtarget->hasDenormModeInst()) { 8486 const SDValue DisableDenormValue = 8487 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8488 8489 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8490 Fma4.getValue(1), DisableDenormValue, 8491 Fma4.getValue(2)).getNode(); 8492 } else { 8493 const SDValue DisableDenormValue = 8494 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8495 8496 DisableDenorm = DAG.getMachineNode( 8497 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8498 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8499 } 8500 8501 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8502 SDValue(DisableDenorm, 0), DAG.getRoot()); 8503 DAG.setRoot(OutputChain); 8504 } 8505 8506 SDValue Scale = NumeratorScaled.getValue(1); 8507 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8508 {Fma4, Fma1, Fma3, Scale}, Flags); 8509 8510 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8511 } 8512 8513 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8514 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8515 return FastLowered; 8516 8517 SDLoc SL(Op); 8518 SDValue X = Op.getOperand(0); 8519 SDValue Y = Op.getOperand(1); 8520 8521 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8522 8523 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8524 8525 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8526 8527 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8528 8529 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8530 8531 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8532 8533 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8534 8535 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8536 8537 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8538 8539 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8540 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8541 8542 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8543 NegDivScale0, Mul, DivScale1); 8544 8545 SDValue Scale; 8546 8547 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8548 // Workaround a hardware bug on SI where the condition output from div_scale 8549 // is not usable. 8550 8551 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8552 8553 // Figure out if the scale to use for div_fmas. 8554 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8555 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8556 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8557 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8558 8559 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8560 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8561 8562 SDValue Scale0Hi 8563 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8564 SDValue Scale1Hi 8565 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8566 8567 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8568 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8569 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8570 } else { 8571 Scale = DivScale1.getValue(1); 8572 } 8573 8574 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8575 Fma4, Fma3, Mul, Scale); 8576 8577 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8578 } 8579 8580 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8581 EVT VT = Op.getValueType(); 8582 8583 if (VT == MVT::f32) 8584 return LowerFDIV32(Op, DAG); 8585 8586 if (VT == MVT::f64) 8587 return LowerFDIV64(Op, DAG); 8588 8589 if (VT == MVT::f16) 8590 return LowerFDIV16(Op, DAG); 8591 8592 llvm_unreachable("Unexpected type for fdiv"); 8593 } 8594 8595 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8596 SDLoc DL(Op); 8597 StoreSDNode *Store = cast<StoreSDNode>(Op); 8598 EVT VT = Store->getMemoryVT(); 8599 8600 if (VT == MVT::i1) { 8601 return DAG.getTruncStore(Store->getChain(), DL, 8602 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8603 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8604 } 8605 8606 assert(VT.isVector() && 8607 Store->getValue().getValueType().getScalarType() == MVT::i32); 8608 8609 unsigned AS = Store->getAddressSpace(); 8610 if (Subtarget->hasLDSMisalignedBug() && 8611 AS == AMDGPUAS::FLAT_ADDRESS && 8612 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8613 return SplitVectorStore(Op, DAG); 8614 } 8615 8616 MachineFunction &MF = DAG.getMachineFunction(); 8617 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8618 // If there is a possibilty that flat instruction access scratch memory 8619 // then we need to use the same legalization rules we use for private. 8620 if (AS == AMDGPUAS::FLAT_ADDRESS && 8621 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8622 AS = MFI->hasFlatScratchInit() ? 8623 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8624 8625 unsigned NumElements = VT.getVectorNumElements(); 8626 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8627 AS == AMDGPUAS::FLAT_ADDRESS) { 8628 if (NumElements > 4) 8629 return SplitVectorStore(Op, DAG); 8630 // v3 stores not supported on SI. 8631 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8632 return SplitVectorStore(Op, DAG); 8633 8634 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8635 VT, *Store->getMemOperand())) 8636 return expandUnalignedStore(Store, DAG); 8637 8638 return SDValue(); 8639 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8640 switch (Subtarget->getMaxPrivateElementSize()) { 8641 case 4: 8642 return scalarizeVectorStore(Store, DAG); 8643 case 8: 8644 if (NumElements > 2) 8645 return SplitVectorStore(Op, DAG); 8646 return SDValue(); 8647 case 16: 8648 if (NumElements > 4 || 8649 (NumElements == 3 && !Subtarget->enableFlatScratch())) 8650 return SplitVectorStore(Op, DAG); 8651 return SDValue(); 8652 default: 8653 llvm_unreachable("unsupported private_element_size"); 8654 } 8655 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8656 // Use ds_write_b128 or ds_write_b96 when possible. 8657 if (Subtarget->hasDS96AndDS128() && 8658 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8659 (VT.getStoreSize() == 12)) && 8660 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8661 Store->getAlign())) 8662 return SDValue(); 8663 8664 if (NumElements > 2) 8665 return SplitVectorStore(Op, DAG); 8666 8667 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8668 // address is negative, then the instruction is incorrectly treated as 8669 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8670 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8671 // store later in the SILoadStoreOptimizer. 8672 if (!Subtarget->hasUsableDSOffset() && 8673 NumElements == 2 && VT.getStoreSize() == 8 && 8674 Store->getAlignment() < 8) { 8675 return SplitVectorStore(Op, DAG); 8676 } 8677 8678 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8679 VT, *Store->getMemOperand())) { 8680 if (VT.isVector()) 8681 return SplitVectorStore(Op, DAG); 8682 return expandUnalignedStore(Store, DAG); 8683 } 8684 8685 return SDValue(); 8686 } else { 8687 llvm_unreachable("unhandled address space"); 8688 } 8689 } 8690 8691 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8692 SDLoc DL(Op); 8693 EVT VT = Op.getValueType(); 8694 SDValue Arg = Op.getOperand(0); 8695 SDValue TrigVal; 8696 8697 // Propagate fast-math flags so that the multiply we introduce can be folded 8698 // if Arg is already the result of a multiply by constant. 8699 auto Flags = Op->getFlags(); 8700 8701 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8702 8703 if (Subtarget->hasTrigReducedRange()) { 8704 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8705 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8706 } else { 8707 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8708 } 8709 8710 switch (Op.getOpcode()) { 8711 case ISD::FCOS: 8712 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8713 case ISD::FSIN: 8714 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8715 default: 8716 llvm_unreachable("Wrong trig opcode"); 8717 } 8718 } 8719 8720 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8721 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8722 assert(AtomicNode->isCompareAndSwap()); 8723 unsigned AS = AtomicNode->getAddressSpace(); 8724 8725 // No custom lowering required for local address space 8726 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8727 return Op; 8728 8729 // Non-local address space requires custom lowering for atomic compare 8730 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8731 SDLoc DL(Op); 8732 SDValue ChainIn = Op.getOperand(0); 8733 SDValue Addr = Op.getOperand(1); 8734 SDValue Old = Op.getOperand(2); 8735 SDValue New = Op.getOperand(3); 8736 EVT VT = Op.getValueType(); 8737 MVT SimpleVT = VT.getSimpleVT(); 8738 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8739 8740 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8741 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8742 8743 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8744 Ops, VT, AtomicNode->getMemOperand()); 8745 } 8746 8747 //===----------------------------------------------------------------------===// 8748 // Custom DAG optimizations 8749 //===----------------------------------------------------------------------===// 8750 8751 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8752 DAGCombinerInfo &DCI) const { 8753 EVT VT = N->getValueType(0); 8754 EVT ScalarVT = VT.getScalarType(); 8755 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8756 return SDValue(); 8757 8758 SelectionDAG &DAG = DCI.DAG; 8759 SDLoc DL(N); 8760 8761 SDValue Src = N->getOperand(0); 8762 EVT SrcVT = Src.getValueType(); 8763 8764 // TODO: We could try to match extracting the higher bytes, which would be 8765 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8766 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8767 // about in practice. 8768 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8769 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8770 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8771 DCI.AddToWorklist(Cvt.getNode()); 8772 8773 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8774 if (ScalarVT != MVT::f32) { 8775 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8776 DAG.getTargetConstant(0, DL, MVT::i32)); 8777 } 8778 return Cvt; 8779 } 8780 } 8781 8782 return SDValue(); 8783 } 8784 8785 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8786 8787 // This is a variant of 8788 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8789 // 8790 // The normal DAG combiner will do this, but only if the add has one use since 8791 // that would increase the number of instructions. 8792 // 8793 // This prevents us from seeing a constant offset that can be folded into a 8794 // memory instruction's addressing mode. If we know the resulting add offset of 8795 // a pointer can be folded into an addressing offset, we can replace the pointer 8796 // operand with the add of new constant offset. This eliminates one of the uses, 8797 // and may allow the remaining use to also be simplified. 8798 // 8799 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8800 unsigned AddrSpace, 8801 EVT MemVT, 8802 DAGCombinerInfo &DCI) const { 8803 SDValue N0 = N->getOperand(0); 8804 SDValue N1 = N->getOperand(1); 8805 8806 // We only do this to handle cases where it's profitable when there are 8807 // multiple uses of the add, so defer to the standard combine. 8808 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8809 N0->hasOneUse()) 8810 return SDValue(); 8811 8812 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8813 if (!CN1) 8814 return SDValue(); 8815 8816 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8817 if (!CAdd) 8818 return SDValue(); 8819 8820 // If the resulting offset is too large, we can't fold it into the addressing 8821 // mode offset. 8822 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8823 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8824 8825 AddrMode AM; 8826 AM.HasBaseReg = true; 8827 AM.BaseOffs = Offset.getSExtValue(); 8828 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8829 return SDValue(); 8830 8831 SelectionDAG &DAG = DCI.DAG; 8832 SDLoc SL(N); 8833 EVT VT = N->getValueType(0); 8834 8835 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8836 SDValue COffset = DAG.getConstant(Offset, SL, VT); 8837 8838 SDNodeFlags Flags; 8839 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8840 (N0.getOpcode() == ISD::OR || 8841 N0->getFlags().hasNoUnsignedWrap())); 8842 8843 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8844 } 8845 8846 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 8847 /// by the chain and intrinsic ID. Theoretically we would also need to check the 8848 /// specific intrinsic, but they all place the pointer operand first. 8849 static unsigned getBasePtrIndex(const MemSDNode *N) { 8850 switch (N->getOpcode()) { 8851 case ISD::STORE: 8852 case ISD::INTRINSIC_W_CHAIN: 8853 case ISD::INTRINSIC_VOID: 8854 return 2; 8855 default: 8856 return 1; 8857 } 8858 } 8859 8860 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8861 DAGCombinerInfo &DCI) const { 8862 SelectionDAG &DAG = DCI.DAG; 8863 SDLoc SL(N); 8864 8865 unsigned PtrIdx = getBasePtrIndex(N); 8866 SDValue Ptr = N->getOperand(PtrIdx); 8867 8868 // TODO: We could also do this for multiplies. 8869 if (Ptr.getOpcode() == ISD::SHL) { 8870 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8871 N->getMemoryVT(), DCI); 8872 if (NewPtr) { 8873 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8874 8875 NewOps[PtrIdx] = NewPtr; 8876 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8877 } 8878 } 8879 8880 return SDValue(); 8881 } 8882 8883 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8884 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8885 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8886 (Opc == ISD::XOR && Val == 0); 8887 } 8888 8889 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8890 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8891 // integer combine opportunities since most 64-bit operations are decomposed 8892 // this way. TODO: We won't want this for SALU especially if it is an inline 8893 // immediate. 8894 SDValue SITargetLowering::splitBinaryBitConstantOp( 8895 DAGCombinerInfo &DCI, 8896 const SDLoc &SL, 8897 unsigned Opc, SDValue LHS, 8898 const ConstantSDNode *CRHS) const { 8899 uint64_t Val = CRHS->getZExtValue(); 8900 uint32_t ValLo = Lo_32(Val); 8901 uint32_t ValHi = Hi_32(Val); 8902 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8903 8904 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8905 bitOpWithConstantIsReducible(Opc, ValHi)) || 8906 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8907 // If we need to materialize a 64-bit immediate, it will be split up later 8908 // anyway. Avoid creating the harder to understand 64-bit immediate 8909 // materialization. 8910 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8911 } 8912 8913 return SDValue(); 8914 } 8915 8916 // Returns true if argument is a boolean value which is not serialized into 8917 // memory or argument and does not require v_cndmask_b32 to be deserialized. 8918 static bool isBoolSGPR(SDValue V) { 8919 if (V.getValueType() != MVT::i1) 8920 return false; 8921 switch (V.getOpcode()) { 8922 default: 8923 break; 8924 case ISD::SETCC: 8925 case AMDGPUISD::FP_CLASS: 8926 return true; 8927 case ISD::AND: 8928 case ISD::OR: 8929 case ISD::XOR: 8930 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 8931 } 8932 return false; 8933 } 8934 8935 // If a constant has all zeroes or all ones within each byte return it. 8936 // Otherwise return 0. 8937 static uint32_t getConstantPermuteMask(uint32_t C) { 8938 // 0xff for any zero byte in the mask 8939 uint32_t ZeroByteMask = 0; 8940 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8941 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8942 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8943 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8944 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8945 if ((NonZeroByteMask & C) != NonZeroByteMask) 8946 return 0; // Partial bytes selected. 8947 return C; 8948 } 8949 8950 // Check if a node selects whole bytes from its operand 0 starting at a byte 8951 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8952 // or -1 if not succeeded. 8953 // Note byte select encoding: 8954 // value 0-3 selects corresponding source byte; 8955 // value 0xc selects zero; 8956 // value 0xff selects 0xff. 8957 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8958 assert(V.getValueSizeInBits() == 32); 8959 8960 if (V.getNumOperands() != 2) 8961 return ~0; 8962 8963 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8964 if (!N1) 8965 return ~0; 8966 8967 uint32_t C = N1->getZExtValue(); 8968 8969 switch (V.getOpcode()) { 8970 default: 8971 break; 8972 case ISD::AND: 8973 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8974 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8975 } 8976 break; 8977 8978 case ISD::OR: 8979 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8980 return (0x03020100 & ~ConstMask) | ConstMask; 8981 } 8982 break; 8983 8984 case ISD::SHL: 8985 if (C % 8) 8986 return ~0; 8987 8988 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8989 8990 case ISD::SRL: 8991 if (C % 8) 8992 return ~0; 8993 8994 return uint32_t(0x0c0c0c0c03020100ull >> C); 8995 } 8996 8997 return ~0; 8998 } 8999 9000 SDValue SITargetLowering::performAndCombine(SDNode *N, 9001 DAGCombinerInfo &DCI) const { 9002 if (DCI.isBeforeLegalize()) 9003 return SDValue(); 9004 9005 SelectionDAG &DAG = DCI.DAG; 9006 EVT VT = N->getValueType(0); 9007 SDValue LHS = N->getOperand(0); 9008 SDValue RHS = N->getOperand(1); 9009 9010 9011 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9012 if (VT == MVT::i64 && CRHS) { 9013 if (SDValue Split 9014 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9015 return Split; 9016 } 9017 9018 if (CRHS && VT == MVT::i32) { 9019 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9020 // nb = number of trailing zeroes in mask 9021 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9022 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9023 uint64_t Mask = CRHS->getZExtValue(); 9024 unsigned Bits = countPopulation(Mask); 9025 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9026 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9027 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9028 unsigned Shift = CShift->getZExtValue(); 9029 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9030 unsigned Offset = NB + Shift; 9031 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9032 SDLoc SL(N); 9033 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9034 LHS->getOperand(0), 9035 DAG.getConstant(Offset, SL, MVT::i32), 9036 DAG.getConstant(Bits, SL, MVT::i32)); 9037 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9038 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9039 DAG.getValueType(NarrowVT)); 9040 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9041 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9042 return Shl; 9043 } 9044 } 9045 } 9046 9047 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9048 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9049 isa<ConstantSDNode>(LHS.getOperand(2))) { 9050 uint32_t Sel = getConstantPermuteMask(Mask); 9051 if (!Sel) 9052 return SDValue(); 9053 9054 // Select 0xc for all zero bytes 9055 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9056 SDLoc DL(N); 9057 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9058 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9059 } 9060 } 9061 9062 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9063 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9064 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9065 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9066 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9067 9068 SDValue X = LHS.getOperand(0); 9069 SDValue Y = RHS.getOperand(0); 9070 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9071 return SDValue(); 9072 9073 if (LCC == ISD::SETO) { 9074 if (X != LHS.getOperand(1)) 9075 return SDValue(); 9076 9077 if (RCC == ISD::SETUNE) { 9078 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9079 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9080 return SDValue(); 9081 9082 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9083 SIInstrFlags::N_SUBNORMAL | 9084 SIInstrFlags::N_ZERO | 9085 SIInstrFlags::P_ZERO | 9086 SIInstrFlags::P_SUBNORMAL | 9087 SIInstrFlags::P_NORMAL; 9088 9089 static_assert(((~(SIInstrFlags::S_NAN | 9090 SIInstrFlags::Q_NAN | 9091 SIInstrFlags::N_INFINITY | 9092 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9093 "mask not equal"); 9094 9095 SDLoc DL(N); 9096 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9097 X, DAG.getConstant(Mask, DL, MVT::i32)); 9098 } 9099 } 9100 } 9101 9102 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9103 std::swap(LHS, RHS); 9104 9105 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9106 RHS.hasOneUse()) { 9107 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9108 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9109 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9110 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9111 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9112 (RHS.getOperand(0) == LHS.getOperand(0) && 9113 LHS.getOperand(0) == LHS.getOperand(1))) { 9114 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9115 unsigned NewMask = LCC == ISD::SETO ? 9116 Mask->getZExtValue() & ~OrdMask : 9117 Mask->getZExtValue() & OrdMask; 9118 9119 SDLoc DL(N); 9120 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9121 DAG.getConstant(NewMask, DL, MVT::i32)); 9122 } 9123 } 9124 9125 if (VT == MVT::i32 && 9126 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9127 // and x, (sext cc from i1) => select cc, x, 0 9128 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9129 std::swap(LHS, RHS); 9130 if (isBoolSGPR(RHS.getOperand(0))) 9131 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9132 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9133 } 9134 9135 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9136 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9137 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9138 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9139 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9140 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9141 if (LHSMask != ~0u && RHSMask != ~0u) { 9142 // Canonicalize the expression in an attempt to have fewer unique masks 9143 // and therefore fewer registers used to hold the masks. 9144 if (LHSMask > RHSMask) { 9145 std::swap(LHSMask, RHSMask); 9146 std::swap(LHS, RHS); 9147 } 9148 9149 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9150 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9151 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9152 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9153 9154 // Check of we need to combine values from two sources within a byte. 9155 if (!(LHSUsedLanes & RHSUsedLanes) && 9156 // If we select high and lower word keep it for SDWA. 9157 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9158 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9159 // Each byte in each mask is either selector mask 0-3, or has higher 9160 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9161 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9162 // mask which is not 0xff wins. By anding both masks we have a correct 9163 // result except that 0x0c shall be corrected to give 0x0c only. 9164 uint32_t Mask = LHSMask & RHSMask; 9165 for (unsigned I = 0; I < 32; I += 8) { 9166 uint32_t ByteSel = 0xff << I; 9167 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9168 Mask &= (0x0c << I) & 0xffffffff; 9169 } 9170 9171 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9172 // or 0x0c. 9173 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9174 SDLoc DL(N); 9175 9176 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9177 LHS.getOperand(0), RHS.getOperand(0), 9178 DAG.getConstant(Sel, DL, MVT::i32)); 9179 } 9180 } 9181 } 9182 9183 return SDValue(); 9184 } 9185 9186 SDValue SITargetLowering::performOrCombine(SDNode *N, 9187 DAGCombinerInfo &DCI) const { 9188 SelectionDAG &DAG = DCI.DAG; 9189 SDValue LHS = N->getOperand(0); 9190 SDValue RHS = N->getOperand(1); 9191 9192 EVT VT = N->getValueType(0); 9193 if (VT == MVT::i1) { 9194 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9195 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9196 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9197 SDValue Src = LHS.getOperand(0); 9198 if (Src != RHS.getOperand(0)) 9199 return SDValue(); 9200 9201 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9202 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9203 if (!CLHS || !CRHS) 9204 return SDValue(); 9205 9206 // Only 10 bits are used. 9207 static const uint32_t MaxMask = 0x3ff; 9208 9209 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9210 SDLoc DL(N); 9211 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9212 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9213 } 9214 9215 return SDValue(); 9216 } 9217 9218 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9219 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9220 LHS.getOpcode() == AMDGPUISD::PERM && 9221 isa<ConstantSDNode>(LHS.getOperand(2))) { 9222 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9223 if (!Sel) 9224 return SDValue(); 9225 9226 Sel |= LHS.getConstantOperandVal(2); 9227 SDLoc DL(N); 9228 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9229 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9230 } 9231 9232 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9233 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9234 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9235 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9236 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9237 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9238 if (LHSMask != ~0u && RHSMask != ~0u) { 9239 // Canonicalize the expression in an attempt to have fewer unique masks 9240 // and therefore fewer registers used to hold the masks. 9241 if (LHSMask > RHSMask) { 9242 std::swap(LHSMask, RHSMask); 9243 std::swap(LHS, RHS); 9244 } 9245 9246 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9247 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9248 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9249 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9250 9251 // Check of we need to combine values from two sources within a byte. 9252 if (!(LHSUsedLanes & RHSUsedLanes) && 9253 // If we select high and lower word keep it for SDWA. 9254 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9255 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9256 // Kill zero bytes selected by other mask. Zero value is 0xc. 9257 LHSMask &= ~RHSUsedLanes; 9258 RHSMask &= ~LHSUsedLanes; 9259 // Add 4 to each active LHS lane 9260 LHSMask |= LHSUsedLanes & 0x04040404; 9261 // Combine masks 9262 uint32_t Sel = LHSMask | RHSMask; 9263 SDLoc DL(N); 9264 9265 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9266 LHS.getOperand(0), RHS.getOperand(0), 9267 DAG.getConstant(Sel, DL, MVT::i32)); 9268 } 9269 } 9270 } 9271 9272 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9273 return SDValue(); 9274 9275 // TODO: This could be a generic combine with a predicate for extracting the 9276 // high half of an integer being free. 9277 9278 // (or i64:x, (zero_extend i32:y)) -> 9279 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9280 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9281 RHS.getOpcode() != ISD::ZERO_EXTEND) 9282 std::swap(LHS, RHS); 9283 9284 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9285 SDValue ExtSrc = RHS.getOperand(0); 9286 EVT SrcVT = ExtSrc.getValueType(); 9287 if (SrcVT == MVT::i32) { 9288 SDLoc SL(N); 9289 SDValue LowLHS, HiBits; 9290 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9291 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9292 9293 DCI.AddToWorklist(LowOr.getNode()); 9294 DCI.AddToWorklist(HiBits.getNode()); 9295 9296 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9297 LowOr, HiBits); 9298 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9299 } 9300 } 9301 9302 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9303 if (CRHS) { 9304 if (SDValue Split 9305 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9306 return Split; 9307 } 9308 9309 return SDValue(); 9310 } 9311 9312 SDValue SITargetLowering::performXorCombine(SDNode *N, 9313 DAGCombinerInfo &DCI) const { 9314 EVT VT = N->getValueType(0); 9315 if (VT != MVT::i64) 9316 return SDValue(); 9317 9318 SDValue LHS = N->getOperand(0); 9319 SDValue RHS = N->getOperand(1); 9320 9321 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9322 if (CRHS) { 9323 if (SDValue Split 9324 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9325 return Split; 9326 } 9327 9328 return SDValue(); 9329 } 9330 9331 // Instructions that will be lowered with a final instruction that zeros the 9332 // high result bits. 9333 // XXX - probably only need to list legal operations. 9334 static bool fp16SrcZerosHighBits(unsigned Opc) { 9335 switch (Opc) { 9336 case ISD::FADD: 9337 case ISD::FSUB: 9338 case ISD::FMUL: 9339 case ISD::FDIV: 9340 case ISD::FREM: 9341 case ISD::FMA: 9342 case ISD::FMAD: 9343 case ISD::FCANONICALIZE: 9344 case ISD::FP_ROUND: 9345 case ISD::UINT_TO_FP: 9346 case ISD::SINT_TO_FP: 9347 case ISD::FABS: 9348 // Fabs is lowered to a bit operation, but it's an and which will clear the 9349 // high bits anyway. 9350 case ISD::FSQRT: 9351 case ISD::FSIN: 9352 case ISD::FCOS: 9353 case ISD::FPOWI: 9354 case ISD::FPOW: 9355 case ISD::FLOG: 9356 case ISD::FLOG2: 9357 case ISD::FLOG10: 9358 case ISD::FEXP: 9359 case ISD::FEXP2: 9360 case ISD::FCEIL: 9361 case ISD::FTRUNC: 9362 case ISD::FRINT: 9363 case ISD::FNEARBYINT: 9364 case ISD::FROUND: 9365 case ISD::FFLOOR: 9366 case ISD::FMINNUM: 9367 case ISD::FMAXNUM: 9368 case AMDGPUISD::FRACT: 9369 case AMDGPUISD::CLAMP: 9370 case AMDGPUISD::COS_HW: 9371 case AMDGPUISD::SIN_HW: 9372 case AMDGPUISD::FMIN3: 9373 case AMDGPUISD::FMAX3: 9374 case AMDGPUISD::FMED3: 9375 case AMDGPUISD::FMAD_FTZ: 9376 case AMDGPUISD::RCP: 9377 case AMDGPUISD::RSQ: 9378 case AMDGPUISD::RCP_IFLAG: 9379 case AMDGPUISD::LDEXP: 9380 return true; 9381 default: 9382 // fcopysign, select and others may be lowered to 32-bit bit operations 9383 // which don't zero the high bits. 9384 return false; 9385 } 9386 } 9387 9388 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9389 DAGCombinerInfo &DCI) const { 9390 if (!Subtarget->has16BitInsts() || 9391 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9392 return SDValue(); 9393 9394 EVT VT = N->getValueType(0); 9395 if (VT != MVT::i32) 9396 return SDValue(); 9397 9398 SDValue Src = N->getOperand(0); 9399 if (Src.getValueType() != MVT::i16) 9400 return SDValue(); 9401 9402 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9403 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9404 if (Src.getOpcode() == ISD::BITCAST) { 9405 SDValue BCSrc = Src.getOperand(0); 9406 if (BCSrc.getValueType() == MVT::f16 && 9407 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9408 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9409 } 9410 9411 return SDValue(); 9412 } 9413 9414 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9415 DAGCombinerInfo &DCI) 9416 const { 9417 SDValue Src = N->getOperand(0); 9418 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9419 9420 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9421 VTSign->getVT() == MVT::i8) || 9422 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9423 VTSign->getVT() == MVT::i16)) && 9424 Src.hasOneUse()) { 9425 auto *M = cast<MemSDNode>(Src); 9426 SDValue Ops[] = { 9427 Src.getOperand(0), // Chain 9428 Src.getOperand(1), // rsrc 9429 Src.getOperand(2), // vindex 9430 Src.getOperand(3), // voffset 9431 Src.getOperand(4), // soffset 9432 Src.getOperand(5), // offset 9433 Src.getOperand(6), 9434 Src.getOperand(7) 9435 }; 9436 // replace with BUFFER_LOAD_BYTE/SHORT 9437 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9438 Src.getOperand(0).getValueType()); 9439 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9440 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9441 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9442 ResList, 9443 Ops, M->getMemoryVT(), 9444 M->getMemOperand()); 9445 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9446 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9447 } 9448 return SDValue(); 9449 } 9450 9451 SDValue SITargetLowering::performClassCombine(SDNode *N, 9452 DAGCombinerInfo &DCI) const { 9453 SelectionDAG &DAG = DCI.DAG; 9454 SDValue Mask = N->getOperand(1); 9455 9456 // fp_class x, 0 -> false 9457 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9458 if (CMask->isNullValue()) 9459 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9460 } 9461 9462 if (N->getOperand(0).isUndef()) 9463 return DAG.getUNDEF(MVT::i1); 9464 9465 return SDValue(); 9466 } 9467 9468 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9469 DAGCombinerInfo &DCI) const { 9470 EVT VT = N->getValueType(0); 9471 SDValue N0 = N->getOperand(0); 9472 9473 if (N0.isUndef()) 9474 return N0; 9475 9476 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9477 N0.getOpcode() == ISD::SINT_TO_FP)) { 9478 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9479 N->getFlags()); 9480 } 9481 9482 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9483 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9484 N0.getOperand(0), N->getFlags()); 9485 } 9486 9487 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9488 } 9489 9490 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9491 unsigned MaxDepth) const { 9492 unsigned Opcode = Op.getOpcode(); 9493 if (Opcode == ISD::FCANONICALIZE) 9494 return true; 9495 9496 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9497 auto F = CFP->getValueAPF(); 9498 if (F.isNaN() && F.isSignaling()) 9499 return false; 9500 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9501 } 9502 9503 // If source is a result of another standard FP operation it is already in 9504 // canonical form. 9505 if (MaxDepth == 0) 9506 return false; 9507 9508 switch (Opcode) { 9509 // These will flush denorms if required. 9510 case ISD::FADD: 9511 case ISD::FSUB: 9512 case ISD::FMUL: 9513 case ISD::FCEIL: 9514 case ISD::FFLOOR: 9515 case ISD::FMA: 9516 case ISD::FMAD: 9517 case ISD::FSQRT: 9518 case ISD::FDIV: 9519 case ISD::FREM: 9520 case ISD::FP_ROUND: 9521 case ISD::FP_EXTEND: 9522 case AMDGPUISD::FMUL_LEGACY: 9523 case AMDGPUISD::FMAD_FTZ: 9524 case AMDGPUISD::RCP: 9525 case AMDGPUISD::RSQ: 9526 case AMDGPUISD::RSQ_CLAMP: 9527 case AMDGPUISD::RCP_LEGACY: 9528 case AMDGPUISD::RCP_IFLAG: 9529 case AMDGPUISD::DIV_SCALE: 9530 case AMDGPUISD::DIV_FMAS: 9531 case AMDGPUISD::DIV_FIXUP: 9532 case AMDGPUISD::FRACT: 9533 case AMDGPUISD::LDEXP: 9534 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9535 case AMDGPUISD::CVT_F32_UBYTE0: 9536 case AMDGPUISD::CVT_F32_UBYTE1: 9537 case AMDGPUISD::CVT_F32_UBYTE2: 9538 case AMDGPUISD::CVT_F32_UBYTE3: 9539 return true; 9540 9541 // It can/will be lowered or combined as a bit operation. 9542 // Need to check their input recursively to handle. 9543 case ISD::FNEG: 9544 case ISD::FABS: 9545 case ISD::FCOPYSIGN: 9546 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9547 9548 case ISD::FSIN: 9549 case ISD::FCOS: 9550 case ISD::FSINCOS: 9551 return Op.getValueType().getScalarType() != MVT::f16; 9552 9553 case ISD::FMINNUM: 9554 case ISD::FMAXNUM: 9555 case ISD::FMINNUM_IEEE: 9556 case ISD::FMAXNUM_IEEE: 9557 case AMDGPUISD::CLAMP: 9558 case AMDGPUISD::FMED3: 9559 case AMDGPUISD::FMAX3: 9560 case AMDGPUISD::FMIN3: { 9561 // FIXME: Shouldn't treat the generic operations different based these. 9562 // However, we aren't really required to flush the result from 9563 // minnum/maxnum.. 9564 9565 // snans will be quieted, so we only need to worry about denormals. 9566 if (Subtarget->supportsMinMaxDenormModes() || 9567 denormalsEnabledForType(DAG, Op.getValueType())) 9568 return true; 9569 9570 // Flushing may be required. 9571 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9572 // targets need to check their input recursively. 9573 9574 // FIXME: Does this apply with clamp? It's implemented with max. 9575 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9576 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9577 return false; 9578 } 9579 9580 return true; 9581 } 9582 case ISD::SELECT: { 9583 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9584 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9585 } 9586 case ISD::BUILD_VECTOR: { 9587 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9588 SDValue SrcOp = Op.getOperand(i); 9589 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9590 return false; 9591 } 9592 9593 return true; 9594 } 9595 case ISD::EXTRACT_VECTOR_ELT: 9596 case ISD::EXTRACT_SUBVECTOR: { 9597 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9598 } 9599 case ISD::INSERT_VECTOR_ELT: { 9600 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9601 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9602 } 9603 case ISD::UNDEF: 9604 // Could be anything. 9605 return false; 9606 9607 case ISD::BITCAST: { 9608 // Hack round the mess we make when legalizing extract_vector_elt 9609 SDValue Src = Op.getOperand(0); 9610 if (Src.getValueType() == MVT::i16 && 9611 Src.getOpcode() == ISD::TRUNCATE) { 9612 SDValue TruncSrc = Src.getOperand(0); 9613 if (TruncSrc.getValueType() == MVT::i32 && 9614 TruncSrc.getOpcode() == ISD::BITCAST && 9615 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9616 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9617 } 9618 } 9619 9620 return false; 9621 } 9622 case ISD::INTRINSIC_WO_CHAIN: { 9623 unsigned IntrinsicID 9624 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9625 // TODO: Handle more intrinsics 9626 switch (IntrinsicID) { 9627 case Intrinsic::amdgcn_cvt_pkrtz: 9628 case Intrinsic::amdgcn_cubeid: 9629 case Intrinsic::amdgcn_frexp_mant: 9630 case Intrinsic::amdgcn_fdot2: 9631 case Intrinsic::amdgcn_rcp: 9632 case Intrinsic::amdgcn_rsq: 9633 case Intrinsic::amdgcn_rsq_clamp: 9634 case Intrinsic::amdgcn_rcp_legacy: 9635 case Intrinsic::amdgcn_rsq_legacy: 9636 case Intrinsic::amdgcn_trig_preop: 9637 return true; 9638 default: 9639 break; 9640 } 9641 9642 LLVM_FALLTHROUGH; 9643 } 9644 default: 9645 return denormalsEnabledForType(DAG, Op.getValueType()) && 9646 DAG.isKnownNeverSNaN(Op); 9647 } 9648 9649 llvm_unreachable("invalid operation"); 9650 } 9651 9652 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 9653 unsigned MaxDepth) const { 9654 MachineRegisterInfo &MRI = MF.getRegInfo(); 9655 MachineInstr *MI = MRI.getVRegDef(Reg); 9656 unsigned Opcode = MI->getOpcode(); 9657 9658 if (Opcode == AMDGPU::G_FCANONICALIZE) 9659 return true; 9660 9661 if (Opcode == AMDGPU::G_FCONSTANT) { 9662 auto F = MI->getOperand(1).getFPImm()->getValueAPF(); 9663 if (F.isNaN() && F.isSignaling()) 9664 return false; 9665 return !F.isDenormal() || denormalsEnabledForType(MRI.getType(Reg), MF); 9666 } 9667 9668 if (MaxDepth == 0) 9669 return false; 9670 9671 switch (Opcode) { 9672 case AMDGPU::G_FMINNUM_IEEE: 9673 case AMDGPU::G_FMAXNUM_IEEE: { 9674 if (Subtarget->supportsMinMaxDenormModes() || 9675 denormalsEnabledForType(MRI.getType(Reg), MF)) 9676 return true; 9677 for (unsigned I = 1, E = MI->getNumOperands(); I != E; ++I) { 9678 if (!isCanonicalized(MI->getOperand(I).getReg(), MF, MaxDepth - 1)) 9679 return false; 9680 } 9681 return true; 9682 } 9683 default: 9684 return denormalsEnabledForType(MRI.getType(Reg), MF) && 9685 isKnownNeverSNaN(Reg, MRI); 9686 } 9687 9688 llvm_unreachable("invalid operation"); 9689 } 9690 9691 // Constant fold canonicalize. 9692 SDValue SITargetLowering::getCanonicalConstantFP( 9693 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9694 // Flush denormals to 0 if not enabled. 9695 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9696 return DAG.getConstantFP(0.0, SL, VT); 9697 9698 if (C.isNaN()) { 9699 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9700 if (C.isSignaling()) { 9701 // Quiet a signaling NaN. 9702 // FIXME: Is this supposed to preserve payload bits? 9703 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9704 } 9705 9706 // Make sure it is the canonical NaN bitpattern. 9707 // 9708 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9709 // immediate? 9710 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9711 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9712 } 9713 9714 // Already canonical. 9715 return DAG.getConstantFP(C, SL, VT); 9716 } 9717 9718 static bool vectorEltWillFoldAway(SDValue Op) { 9719 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9720 } 9721 9722 SDValue SITargetLowering::performFCanonicalizeCombine( 9723 SDNode *N, 9724 DAGCombinerInfo &DCI) const { 9725 SelectionDAG &DAG = DCI.DAG; 9726 SDValue N0 = N->getOperand(0); 9727 EVT VT = N->getValueType(0); 9728 9729 // fcanonicalize undef -> qnan 9730 if (N0.isUndef()) { 9731 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9732 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9733 } 9734 9735 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9736 EVT VT = N->getValueType(0); 9737 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9738 } 9739 9740 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9741 // (fcanonicalize k) 9742 // 9743 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9744 9745 // TODO: This could be better with wider vectors that will be split to v2f16, 9746 // and to consider uses since there aren't that many packed operations. 9747 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9748 isTypeLegal(MVT::v2f16)) { 9749 SDLoc SL(N); 9750 SDValue NewElts[2]; 9751 SDValue Lo = N0.getOperand(0); 9752 SDValue Hi = N0.getOperand(1); 9753 EVT EltVT = Lo.getValueType(); 9754 9755 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9756 for (unsigned I = 0; I != 2; ++I) { 9757 SDValue Op = N0.getOperand(I); 9758 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9759 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9760 CFP->getValueAPF()); 9761 } else if (Op.isUndef()) { 9762 // Handled below based on what the other operand is. 9763 NewElts[I] = Op; 9764 } else { 9765 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9766 } 9767 } 9768 9769 // If one half is undef, and one is constant, perfer a splat vector rather 9770 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9771 // cheaper to use and may be free with a packed operation. 9772 if (NewElts[0].isUndef()) { 9773 if (isa<ConstantFPSDNode>(NewElts[1])) 9774 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9775 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9776 } 9777 9778 if (NewElts[1].isUndef()) { 9779 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9780 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9781 } 9782 9783 return DAG.getBuildVector(VT, SL, NewElts); 9784 } 9785 } 9786 9787 unsigned SrcOpc = N0.getOpcode(); 9788 9789 // If it's free to do so, push canonicalizes further up the source, which may 9790 // find a canonical source. 9791 // 9792 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9793 // sNaNs. 9794 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9795 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9796 if (CRHS && N0.hasOneUse()) { 9797 SDLoc SL(N); 9798 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9799 N0.getOperand(0)); 9800 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9801 DCI.AddToWorklist(Canon0.getNode()); 9802 9803 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9804 } 9805 } 9806 9807 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9808 } 9809 9810 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9811 switch (Opc) { 9812 case ISD::FMAXNUM: 9813 case ISD::FMAXNUM_IEEE: 9814 return AMDGPUISD::FMAX3; 9815 case ISD::SMAX: 9816 return AMDGPUISD::SMAX3; 9817 case ISD::UMAX: 9818 return AMDGPUISD::UMAX3; 9819 case ISD::FMINNUM: 9820 case ISD::FMINNUM_IEEE: 9821 return AMDGPUISD::FMIN3; 9822 case ISD::SMIN: 9823 return AMDGPUISD::SMIN3; 9824 case ISD::UMIN: 9825 return AMDGPUISD::UMIN3; 9826 default: 9827 llvm_unreachable("Not a min/max opcode"); 9828 } 9829 } 9830 9831 SDValue SITargetLowering::performIntMed3ImmCombine( 9832 SelectionDAG &DAG, const SDLoc &SL, 9833 SDValue Op0, SDValue Op1, bool Signed) const { 9834 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9835 if (!K1) 9836 return SDValue(); 9837 9838 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9839 if (!K0) 9840 return SDValue(); 9841 9842 if (Signed) { 9843 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9844 return SDValue(); 9845 } else { 9846 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9847 return SDValue(); 9848 } 9849 9850 EVT VT = K0->getValueType(0); 9851 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9852 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9853 return DAG.getNode(Med3Opc, SL, VT, 9854 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9855 } 9856 9857 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9858 if (VT == MVT::i16) { 9859 MVT NVT = MVT::i32; 9860 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9861 9862 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9863 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9864 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9865 9866 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9867 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9868 } 9869 9870 return SDValue(); 9871 } 9872 9873 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9874 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9875 return C; 9876 9877 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9878 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9879 return C; 9880 } 9881 9882 return nullptr; 9883 } 9884 9885 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9886 const SDLoc &SL, 9887 SDValue Op0, 9888 SDValue Op1) const { 9889 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9890 if (!K1) 9891 return SDValue(); 9892 9893 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9894 if (!K0) 9895 return SDValue(); 9896 9897 // Ordered >= (although NaN inputs should have folded away by now). 9898 if (K0->getValueAPF() > K1->getValueAPF()) 9899 return SDValue(); 9900 9901 const MachineFunction &MF = DAG.getMachineFunction(); 9902 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9903 9904 // TODO: Check IEEE bit enabled? 9905 EVT VT = Op0.getValueType(); 9906 if (Info->getMode().DX10Clamp) { 9907 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9908 // hardware fmed3 behavior converting to a min. 9909 // FIXME: Should this be allowing -0.0? 9910 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9911 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9912 } 9913 9914 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9915 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9916 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9917 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9918 // then give the other result, which is different from med3 with a NaN 9919 // input. 9920 SDValue Var = Op0.getOperand(0); 9921 if (!DAG.isKnownNeverSNaN(Var)) 9922 return SDValue(); 9923 9924 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9925 9926 if ((!K0->hasOneUse() || 9927 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9928 (!K1->hasOneUse() || 9929 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9930 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9931 Var, SDValue(K0, 0), SDValue(K1, 0)); 9932 } 9933 } 9934 9935 return SDValue(); 9936 } 9937 9938 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9939 DAGCombinerInfo &DCI) const { 9940 SelectionDAG &DAG = DCI.DAG; 9941 9942 EVT VT = N->getValueType(0); 9943 unsigned Opc = N->getOpcode(); 9944 SDValue Op0 = N->getOperand(0); 9945 SDValue Op1 = N->getOperand(1); 9946 9947 // Only do this if the inner op has one use since this will just increases 9948 // register pressure for no benefit. 9949 9950 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9951 !VT.isVector() && 9952 (VT == MVT::i32 || VT == MVT::f32 || 9953 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9954 // max(max(a, b), c) -> max3(a, b, c) 9955 // min(min(a, b), c) -> min3(a, b, c) 9956 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9957 SDLoc DL(N); 9958 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9959 DL, 9960 N->getValueType(0), 9961 Op0.getOperand(0), 9962 Op0.getOperand(1), 9963 Op1); 9964 } 9965 9966 // Try commuted. 9967 // max(a, max(b, c)) -> max3(a, b, c) 9968 // min(a, min(b, c)) -> min3(a, b, c) 9969 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9970 SDLoc DL(N); 9971 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9972 DL, 9973 N->getValueType(0), 9974 Op0, 9975 Op1.getOperand(0), 9976 Op1.getOperand(1)); 9977 } 9978 } 9979 9980 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9981 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9982 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9983 return Med3; 9984 } 9985 9986 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9987 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9988 return Med3; 9989 } 9990 9991 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9992 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9993 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9994 (Opc == AMDGPUISD::FMIN_LEGACY && 9995 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9996 (VT == MVT::f32 || VT == MVT::f64 || 9997 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9998 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9999 Op0.hasOneUse()) { 10000 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 10001 return Res; 10002 } 10003 10004 return SDValue(); 10005 } 10006 10007 static bool isClampZeroToOne(SDValue A, SDValue B) { 10008 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 10009 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 10010 // FIXME: Should this be allowing -0.0? 10011 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 10012 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 10013 } 10014 } 10015 10016 return false; 10017 } 10018 10019 // FIXME: Should only worry about snans for version with chain. 10020 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10021 DAGCombinerInfo &DCI) const { 10022 EVT VT = N->getValueType(0); 10023 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10024 // NaNs. With a NaN input, the order of the operands may change the result. 10025 10026 SelectionDAG &DAG = DCI.DAG; 10027 SDLoc SL(N); 10028 10029 SDValue Src0 = N->getOperand(0); 10030 SDValue Src1 = N->getOperand(1); 10031 SDValue Src2 = N->getOperand(2); 10032 10033 if (isClampZeroToOne(Src0, Src1)) { 10034 // const_a, const_b, x -> clamp is safe in all cases including signaling 10035 // nans. 10036 // FIXME: Should this be allowing -0.0? 10037 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10038 } 10039 10040 const MachineFunction &MF = DAG.getMachineFunction(); 10041 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10042 10043 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10044 // handling no dx10-clamp? 10045 if (Info->getMode().DX10Clamp) { 10046 // If NaNs is clamped to 0, we are free to reorder the inputs. 10047 10048 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10049 std::swap(Src0, Src1); 10050 10051 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10052 std::swap(Src1, Src2); 10053 10054 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10055 std::swap(Src0, Src1); 10056 10057 if (isClampZeroToOne(Src1, Src2)) 10058 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10059 } 10060 10061 return SDValue(); 10062 } 10063 10064 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10065 DAGCombinerInfo &DCI) const { 10066 SDValue Src0 = N->getOperand(0); 10067 SDValue Src1 = N->getOperand(1); 10068 if (Src0.isUndef() && Src1.isUndef()) 10069 return DCI.DAG.getUNDEF(N->getValueType(0)); 10070 return SDValue(); 10071 } 10072 10073 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10074 // expanded into a set of cmp/select instructions. 10075 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10076 unsigned NumElem, 10077 bool IsDivergentIdx) { 10078 if (UseDivergentRegisterIndexing) 10079 return false; 10080 10081 unsigned VecSize = EltSize * NumElem; 10082 10083 // Sub-dword vectors of size 2 dword or less have better implementation. 10084 if (VecSize <= 64 && EltSize < 32) 10085 return false; 10086 10087 // Always expand the rest of sub-dword instructions, otherwise it will be 10088 // lowered via memory. 10089 if (EltSize < 32) 10090 return true; 10091 10092 // Always do this if var-idx is divergent, otherwise it will become a loop. 10093 if (IsDivergentIdx) 10094 return true; 10095 10096 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10097 unsigned NumInsts = NumElem /* Number of compares */ + 10098 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10099 return NumInsts <= 16; 10100 } 10101 10102 static bool shouldExpandVectorDynExt(SDNode *N) { 10103 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10104 if (isa<ConstantSDNode>(Idx)) 10105 return false; 10106 10107 SDValue Vec = N->getOperand(0); 10108 EVT VecVT = Vec.getValueType(); 10109 EVT EltVT = VecVT.getVectorElementType(); 10110 unsigned EltSize = EltVT.getSizeInBits(); 10111 unsigned NumElem = VecVT.getVectorNumElements(); 10112 10113 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10114 Idx->isDivergent()); 10115 } 10116 10117 SDValue SITargetLowering::performExtractVectorEltCombine( 10118 SDNode *N, DAGCombinerInfo &DCI) const { 10119 SDValue Vec = N->getOperand(0); 10120 SelectionDAG &DAG = DCI.DAG; 10121 10122 EVT VecVT = Vec.getValueType(); 10123 EVT EltVT = VecVT.getVectorElementType(); 10124 10125 if ((Vec.getOpcode() == ISD::FNEG || 10126 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10127 SDLoc SL(N); 10128 EVT EltVT = N->getValueType(0); 10129 SDValue Idx = N->getOperand(1); 10130 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10131 Vec.getOperand(0), Idx); 10132 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10133 } 10134 10135 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10136 // => 10137 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10138 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10139 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10140 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10141 SDLoc SL(N); 10142 EVT EltVT = N->getValueType(0); 10143 SDValue Idx = N->getOperand(1); 10144 unsigned Opc = Vec.getOpcode(); 10145 10146 switch(Opc) { 10147 default: 10148 break; 10149 // TODO: Support other binary operations. 10150 case ISD::FADD: 10151 case ISD::FSUB: 10152 case ISD::FMUL: 10153 case ISD::ADD: 10154 case ISD::UMIN: 10155 case ISD::UMAX: 10156 case ISD::SMIN: 10157 case ISD::SMAX: 10158 case ISD::FMAXNUM: 10159 case ISD::FMINNUM: 10160 case ISD::FMAXNUM_IEEE: 10161 case ISD::FMINNUM_IEEE: { 10162 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10163 Vec.getOperand(0), Idx); 10164 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10165 Vec.getOperand(1), Idx); 10166 10167 DCI.AddToWorklist(Elt0.getNode()); 10168 DCI.AddToWorklist(Elt1.getNode()); 10169 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10170 } 10171 } 10172 } 10173 10174 unsigned VecSize = VecVT.getSizeInBits(); 10175 unsigned EltSize = EltVT.getSizeInBits(); 10176 10177 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10178 if (::shouldExpandVectorDynExt(N)) { 10179 SDLoc SL(N); 10180 SDValue Idx = N->getOperand(1); 10181 SDValue V; 10182 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10183 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10184 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10185 if (I == 0) 10186 V = Elt; 10187 else 10188 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10189 } 10190 return V; 10191 } 10192 10193 if (!DCI.isBeforeLegalize()) 10194 return SDValue(); 10195 10196 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10197 // elements. This exposes more load reduction opportunities by replacing 10198 // multiple small extract_vector_elements with a single 32-bit extract. 10199 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10200 if (isa<MemSDNode>(Vec) && 10201 EltSize <= 16 && 10202 EltVT.isByteSized() && 10203 VecSize > 32 && 10204 VecSize % 32 == 0 && 10205 Idx) { 10206 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10207 10208 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10209 unsigned EltIdx = BitIndex / 32; 10210 unsigned LeftoverBitIdx = BitIndex % 32; 10211 SDLoc SL(N); 10212 10213 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10214 DCI.AddToWorklist(Cast.getNode()); 10215 10216 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10217 DAG.getConstant(EltIdx, SL, MVT::i32)); 10218 DCI.AddToWorklist(Elt.getNode()); 10219 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10220 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10221 DCI.AddToWorklist(Srl.getNode()); 10222 10223 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10224 DCI.AddToWorklist(Trunc.getNode()); 10225 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10226 } 10227 10228 return SDValue(); 10229 } 10230 10231 SDValue 10232 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10233 DAGCombinerInfo &DCI) const { 10234 SDValue Vec = N->getOperand(0); 10235 SDValue Idx = N->getOperand(2); 10236 EVT VecVT = Vec.getValueType(); 10237 EVT EltVT = VecVT.getVectorElementType(); 10238 10239 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10240 // => BUILD_VECTOR n x select (e, const-idx) 10241 if (!::shouldExpandVectorDynExt(N)) 10242 return SDValue(); 10243 10244 SelectionDAG &DAG = DCI.DAG; 10245 SDLoc SL(N); 10246 SDValue Ins = N->getOperand(1); 10247 EVT IdxVT = Idx.getValueType(); 10248 10249 SmallVector<SDValue, 16> Ops; 10250 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10251 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10252 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10253 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10254 Ops.push_back(V); 10255 } 10256 10257 return DAG.getBuildVector(VecVT, SL, Ops); 10258 } 10259 10260 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10261 const SDNode *N0, 10262 const SDNode *N1) const { 10263 EVT VT = N0->getValueType(0); 10264 10265 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10266 // support denormals ever. 10267 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10268 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10269 getSubtarget()->hasMadF16())) && 10270 isOperationLegal(ISD::FMAD, VT)) 10271 return ISD::FMAD; 10272 10273 const TargetOptions &Options = DAG.getTarget().Options; 10274 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10275 (N0->getFlags().hasAllowContract() && 10276 N1->getFlags().hasAllowContract())) && 10277 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10278 return ISD::FMA; 10279 } 10280 10281 return 0; 10282 } 10283 10284 // For a reassociatable opcode perform: 10285 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10286 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10287 SelectionDAG &DAG) const { 10288 EVT VT = N->getValueType(0); 10289 if (VT != MVT::i32 && VT != MVT::i64) 10290 return SDValue(); 10291 10292 unsigned Opc = N->getOpcode(); 10293 SDValue Op0 = N->getOperand(0); 10294 SDValue Op1 = N->getOperand(1); 10295 10296 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10297 return SDValue(); 10298 10299 if (Op0->isDivergent()) 10300 std::swap(Op0, Op1); 10301 10302 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10303 return SDValue(); 10304 10305 SDValue Op2 = Op1.getOperand(1); 10306 Op1 = Op1.getOperand(0); 10307 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10308 return SDValue(); 10309 10310 if (Op1->isDivergent()) 10311 std::swap(Op1, Op2); 10312 10313 // If either operand is constant this will conflict with 10314 // DAGCombiner::ReassociateOps(). 10315 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10316 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10317 return SDValue(); 10318 10319 SDLoc SL(N); 10320 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10321 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10322 } 10323 10324 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10325 EVT VT, 10326 SDValue N0, SDValue N1, SDValue N2, 10327 bool Signed) { 10328 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10329 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10330 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10331 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10332 } 10333 10334 SDValue SITargetLowering::performAddCombine(SDNode *N, 10335 DAGCombinerInfo &DCI) const { 10336 SelectionDAG &DAG = DCI.DAG; 10337 EVT VT = N->getValueType(0); 10338 SDLoc SL(N); 10339 SDValue LHS = N->getOperand(0); 10340 SDValue RHS = N->getOperand(1); 10341 10342 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10343 && Subtarget->hasMad64_32() && 10344 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10345 VT.getScalarSizeInBits() <= 64) { 10346 if (LHS.getOpcode() != ISD::MUL) 10347 std::swap(LHS, RHS); 10348 10349 SDValue MulLHS = LHS.getOperand(0); 10350 SDValue MulRHS = LHS.getOperand(1); 10351 SDValue AddRHS = RHS; 10352 10353 // TODO: Maybe restrict if SGPR inputs. 10354 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10355 numBitsUnsigned(MulRHS, DAG) <= 32) { 10356 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10357 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10358 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10359 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10360 } 10361 10362 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10363 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10364 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10365 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10366 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10367 } 10368 10369 return SDValue(); 10370 } 10371 10372 if (SDValue V = reassociateScalarOps(N, DAG)) { 10373 return V; 10374 } 10375 10376 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10377 return SDValue(); 10378 10379 // add x, zext (setcc) => addcarry x, 0, setcc 10380 // add x, sext (setcc) => subcarry x, 0, setcc 10381 unsigned Opc = LHS.getOpcode(); 10382 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10383 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10384 std::swap(RHS, LHS); 10385 10386 Opc = RHS.getOpcode(); 10387 switch (Opc) { 10388 default: break; 10389 case ISD::ZERO_EXTEND: 10390 case ISD::SIGN_EXTEND: 10391 case ISD::ANY_EXTEND: { 10392 auto Cond = RHS.getOperand(0); 10393 // If this won't be a real VOPC output, we would still need to insert an 10394 // extra instruction anyway. 10395 if (!isBoolSGPR(Cond)) 10396 break; 10397 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10398 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10399 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10400 return DAG.getNode(Opc, SL, VTList, Args); 10401 } 10402 case ISD::ADDCARRY: { 10403 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10404 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10405 if (!C || C->getZExtValue() != 0) break; 10406 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10407 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10408 } 10409 } 10410 return SDValue(); 10411 } 10412 10413 SDValue SITargetLowering::performSubCombine(SDNode *N, 10414 DAGCombinerInfo &DCI) const { 10415 SelectionDAG &DAG = DCI.DAG; 10416 EVT VT = N->getValueType(0); 10417 10418 if (VT != MVT::i32) 10419 return SDValue(); 10420 10421 SDLoc SL(N); 10422 SDValue LHS = N->getOperand(0); 10423 SDValue RHS = N->getOperand(1); 10424 10425 // sub x, zext (setcc) => subcarry x, 0, setcc 10426 // sub x, sext (setcc) => addcarry x, 0, setcc 10427 unsigned Opc = RHS.getOpcode(); 10428 switch (Opc) { 10429 default: break; 10430 case ISD::ZERO_EXTEND: 10431 case ISD::SIGN_EXTEND: 10432 case ISD::ANY_EXTEND: { 10433 auto Cond = RHS.getOperand(0); 10434 // If this won't be a real VOPC output, we would still need to insert an 10435 // extra instruction anyway. 10436 if (!isBoolSGPR(Cond)) 10437 break; 10438 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10439 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10440 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10441 return DAG.getNode(Opc, SL, VTList, Args); 10442 } 10443 } 10444 10445 if (LHS.getOpcode() == ISD::SUBCARRY) { 10446 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10447 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10448 if (!C || !C->isNullValue()) 10449 return SDValue(); 10450 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10451 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10452 } 10453 return SDValue(); 10454 } 10455 10456 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10457 DAGCombinerInfo &DCI) const { 10458 10459 if (N->getValueType(0) != MVT::i32) 10460 return SDValue(); 10461 10462 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10463 if (!C || C->getZExtValue() != 0) 10464 return SDValue(); 10465 10466 SelectionDAG &DAG = DCI.DAG; 10467 SDValue LHS = N->getOperand(0); 10468 10469 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10470 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10471 unsigned LHSOpc = LHS.getOpcode(); 10472 unsigned Opc = N->getOpcode(); 10473 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10474 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10475 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10476 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10477 } 10478 return SDValue(); 10479 } 10480 10481 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10482 DAGCombinerInfo &DCI) const { 10483 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10484 return SDValue(); 10485 10486 SelectionDAG &DAG = DCI.DAG; 10487 EVT VT = N->getValueType(0); 10488 10489 SDLoc SL(N); 10490 SDValue LHS = N->getOperand(0); 10491 SDValue RHS = N->getOperand(1); 10492 10493 // These should really be instruction patterns, but writing patterns with 10494 // source modiifiers is a pain. 10495 10496 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10497 if (LHS.getOpcode() == ISD::FADD) { 10498 SDValue A = LHS.getOperand(0); 10499 if (A == LHS.getOperand(1)) { 10500 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10501 if (FusedOp != 0) { 10502 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10503 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10504 } 10505 } 10506 } 10507 10508 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10509 if (RHS.getOpcode() == ISD::FADD) { 10510 SDValue A = RHS.getOperand(0); 10511 if (A == RHS.getOperand(1)) { 10512 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10513 if (FusedOp != 0) { 10514 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10515 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10516 } 10517 } 10518 } 10519 10520 return SDValue(); 10521 } 10522 10523 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10524 DAGCombinerInfo &DCI) const { 10525 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10526 return SDValue(); 10527 10528 SelectionDAG &DAG = DCI.DAG; 10529 SDLoc SL(N); 10530 EVT VT = N->getValueType(0); 10531 assert(!VT.isVector()); 10532 10533 // Try to get the fneg to fold into the source modifier. This undoes generic 10534 // DAG combines and folds them into the mad. 10535 // 10536 // Only do this if we are not trying to support denormals. v_mad_f32 does 10537 // not support denormals ever. 10538 SDValue LHS = N->getOperand(0); 10539 SDValue RHS = N->getOperand(1); 10540 if (LHS.getOpcode() == ISD::FADD) { 10541 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10542 SDValue A = LHS.getOperand(0); 10543 if (A == LHS.getOperand(1)) { 10544 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10545 if (FusedOp != 0){ 10546 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10547 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10548 10549 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10550 } 10551 } 10552 } 10553 10554 if (RHS.getOpcode() == ISD::FADD) { 10555 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10556 10557 SDValue A = RHS.getOperand(0); 10558 if (A == RHS.getOperand(1)) { 10559 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10560 if (FusedOp != 0){ 10561 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10562 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10563 } 10564 } 10565 } 10566 10567 return SDValue(); 10568 } 10569 10570 SDValue SITargetLowering::performFMACombine(SDNode *N, 10571 DAGCombinerInfo &DCI) const { 10572 SelectionDAG &DAG = DCI.DAG; 10573 EVT VT = N->getValueType(0); 10574 SDLoc SL(N); 10575 10576 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 10577 return SDValue(); 10578 10579 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10580 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10581 SDValue Op1 = N->getOperand(0); 10582 SDValue Op2 = N->getOperand(1); 10583 SDValue FMA = N->getOperand(2); 10584 10585 if (FMA.getOpcode() != ISD::FMA || 10586 Op1.getOpcode() != ISD::FP_EXTEND || 10587 Op2.getOpcode() != ISD::FP_EXTEND) 10588 return SDValue(); 10589 10590 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10591 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10592 // is sufficient to allow generaing fdot2. 10593 const TargetOptions &Options = DAG.getTarget().Options; 10594 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10595 (N->getFlags().hasAllowContract() && 10596 FMA->getFlags().hasAllowContract())) { 10597 Op1 = Op1.getOperand(0); 10598 Op2 = Op2.getOperand(0); 10599 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10600 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10601 return SDValue(); 10602 10603 SDValue Vec1 = Op1.getOperand(0); 10604 SDValue Idx1 = Op1.getOperand(1); 10605 SDValue Vec2 = Op2.getOperand(0); 10606 10607 SDValue FMAOp1 = FMA.getOperand(0); 10608 SDValue FMAOp2 = FMA.getOperand(1); 10609 SDValue FMAAcc = FMA.getOperand(2); 10610 10611 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10612 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10613 return SDValue(); 10614 10615 FMAOp1 = FMAOp1.getOperand(0); 10616 FMAOp2 = FMAOp2.getOperand(0); 10617 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10618 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10619 return SDValue(); 10620 10621 SDValue Vec3 = FMAOp1.getOperand(0); 10622 SDValue Vec4 = FMAOp2.getOperand(0); 10623 SDValue Idx2 = FMAOp1.getOperand(1); 10624 10625 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10626 // Idx1 and Idx2 cannot be the same. 10627 Idx1 == Idx2) 10628 return SDValue(); 10629 10630 if (Vec1 == Vec2 || Vec3 == Vec4) 10631 return SDValue(); 10632 10633 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10634 return SDValue(); 10635 10636 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10637 (Vec1 == Vec4 && Vec2 == Vec3)) { 10638 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10639 DAG.getTargetConstant(0, SL, MVT::i1)); 10640 } 10641 } 10642 return SDValue(); 10643 } 10644 10645 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10646 DAGCombinerInfo &DCI) const { 10647 SelectionDAG &DAG = DCI.DAG; 10648 SDLoc SL(N); 10649 10650 SDValue LHS = N->getOperand(0); 10651 SDValue RHS = N->getOperand(1); 10652 EVT VT = LHS.getValueType(); 10653 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10654 10655 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10656 if (!CRHS) { 10657 CRHS = dyn_cast<ConstantSDNode>(LHS); 10658 if (CRHS) { 10659 std::swap(LHS, RHS); 10660 CC = getSetCCSwappedOperands(CC); 10661 } 10662 } 10663 10664 if (CRHS) { 10665 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10666 isBoolSGPR(LHS.getOperand(0))) { 10667 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10668 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10669 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10670 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10671 if ((CRHS->isAllOnesValue() && 10672 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10673 (CRHS->isNullValue() && 10674 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10675 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10676 DAG.getConstant(-1, SL, MVT::i1)); 10677 if ((CRHS->isAllOnesValue() && 10678 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10679 (CRHS->isNullValue() && 10680 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10681 return LHS.getOperand(0); 10682 } 10683 10684 uint64_t CRHSVal = CRHS->getZExtValue(); 10685 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10686 LHS.getOpcode() == ISD::SELECT && 10687 isa<ConstantSDNode>(LHS.getOperand(1)) && 10688 isa<ConstantSDNode>(LHS.getOperand(2)) && 10689 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10690 isBoolSGPR(LHS.getOperand(0))) { 10691 // Given CT != FT: 10692 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10693 // setcc (select cc, CT, CF), CF, ne => cc 10694 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10695 // setcc (select cc, CT, CF), CT, eq => cc 10696 uint64_t CT = LHS.getConstantOperandVal(1); 10697 uint64_t CF = LHS.getConstantOperandVal(2); 10698 10699 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10700 (CT == CRHSVal && CC == ISD::SETNE)) 10701 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10702 DAG.getConstant(-1, SL, MVT::i1)); 10703 if ((CF == CRHSVal && CC == ISD::SETNE) || 10704 (CT == CRHSVal && CC == ISD::SETEQ)) 10705 return LHS.getOperand(0); 10706 } 10707 } 10708 10709 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10710 VT != MVT::f16)) 10711 return SDValue(); 10712 10713 // Match isinf/isfinite pattern 10714 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10715 // (fcmp one (fabs x), inf) -> (fp_class x, 10716 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10717 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10718 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10719 if (!CRHS) 10720 return SDValue(); 10721 10722 const APFloat &APF = CRHS->getValueAPF(); 10723 if (APF.isInfinity() && !APF.isNegative()) { 10724 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10725 SIInstrFlags::N_INFINITY; 10726 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10727 SIInstrFlags::P_ZERO | 10728 SIInstrFlags::N_NORMAL | 10729 SIInstrFlags::P_NORMAL | 10730 SIInstrFlags::N_SUBNORMAL | 10731 SIInstrFlags::P_SUBNORMAL; 10732 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10733 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10734 DAG.getConstant(Mask, SL, MVT::i32)); 10735 } 10736 } 10737 10738 return SDValue(); 10739 } 10740 10741 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10742 DAGCombinerInfo &DCI) const { 10743 SelectionDAG &DAG = DCI.DAG; 10744 SDLoc SL(N); 10745 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10746 10747 SDValue Src = N->getOperand(0); 10748 SDValue Shift = N->getOperand(0); 10749 10750 // TODO: Extend type shouldn't matter (assuming legal types). 10751 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10752 Shift = Shift.getOperand(0); 10753 10754 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10755 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10756 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10757 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10758 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10759 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10760 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10761 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10762 SDLoc(Shift.getOperand(0)), MVT::i32); 10763 10764 unsigned ShiftOffset = 8 * Offset; 10765 if (Shift.getOpcode() == ISD::SHL) 10766 ShiftOffset -= C->getZExtValue(); 10767 else 10768 ShiftOffset += C->getZExtValue(); 10769 10770 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10771 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10772 MVT::f32, Shift); 10773 } 10774 } 10775 } 10776 10777 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10778 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10779 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10780 // We simplified Src. If this node is not dead, visit it again so it is 10781 // folded properly. 10782 if (N->getOpcode() != ISD::DELETED_NODE) 10783 DCI.AddToWorklist(N); 10784 return SDValue(N, 0); 10785 } 10786 10787 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10788 if (SDValue DemandedSrc = 10789 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10790 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10791 10792 return SDValue(); 10793 } 10794 10795 SDValue SITargetLowering::performClampCombine(SDNode *N, 10796 DAGCombinerInfo &DCI) const { 10797 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10798 if (!CSrc) 10799 return SDValue(); 10800 10801 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10802 const APFloat &F = CSrc->getValueAPF(); 10803 APFloat Zero = APFloat::getZero(F.getSemantics()); 10804 if (F < Zero || 10805 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10806 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10807 } 10808 10809 APFloat One(F.getSemantics(), "1.0"); 10810 if (F > One) 10811 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10812 10813 return SDValue(CSrc, 0); 10814 } 10815 10816 10817 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10818 DAGCombinerInfo &DCI) const { 10819 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10820 return SDValue(); 10821 switch (N->getOpcode()) { 10822 case ISD::ADD: 10823 return performAddCombine(N, DCI); 10824 case ISD::SUB: 10825 return performSubCombine(N, DCI); 10826 case ISD::ADDCARRY: 10827 case ISD::SUBCARRY: 10828 return performAddCarrySubCarryCombine(N, DCI); 10829 case ISD::FADD: 10830 return performFAddCombine(N, DCI); 10831 case ISD::FSUB: 10832 return performFSubCombine(N, DCI); 10833 case ISD::SETCC: 10834 return performSetCCCombine(N, DCI); 10835 case ISD::FMAXNUM: 10836 case ISD::FMINNUM: 10837 case ISD::FMAXNUM_IEEE: 10838 case ISD::FMINNUM_IEEE: 10839 case ISD::SMAX: 10840 case ISD::SMIN: 10841 case ISD::UMAX: 10842 case ISD::UMIN: 10843 case AMDGPUISD::FMIN_LEGACY: 10844 case AMDGPUISD::FMAX_LEGACY: 10845 return performMinMaxCombine(N, DCI); 10846 case ISD::FMA: 10847 return performFMACombine(N, DCI); 10848 case ISD::AND: 10849 return performAndCombine(N, DCI); 10850 case ISD::OR: 10851 return performOrCombine(N, DCI); 10852 case ISD::XOR: 10853 return performXorCombine(N, DCI); 10854 case ISD::ZERO_EXTEND: 10855 return performZeroExtendCombine(N, DCI); 10856 case ISD::SIGN_EXTEND_INREG: 10857 return performSignExtendInRegCombine(N , DCI); 10858 case AMDGPUISD::FP_CLASS: 10859 return performClassCombine(N, DCI); 10860 case ISD::FCANONICALIZE: 10861 return performFCanonicalizeCombine(N, DCI); 10862 case AMDGPUISD::RCP: 10863 return performRcpCombine(N, DCI); 10864 case AMDGPUISD::FRACT: 10865 case AMDGPUISD::RSQ: 10866 case AMDGPUISD::RCP_LEGACY: 10867 case AMDGPUISD::RCP_IFLAG: 10868 case AMDGPUISD::RSQ_CLAMP: 10869 case AMDGPUISD::LDEXP: { 10870 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10871 SDValue Src = N->getOperand(0); 10872 if (Src.isUndef()) 10873 return Src; 10874 break; 10875 } 10876 case ISD::SINT_TO_FP: 10877 case ISD::UINT_TO_FP: 10878 return performUCharToFloatCombine(N, DCI); 10879 case AMDGPUISD::CVT_F32_UBYTE0: 10880 case AMDGPUISD::CVT_F32_UBYTE1: 10881 case AMDGPUISD::CVT_F32_UBYTE2: 10882 case AMDGPUISD::CVT_F32_UBYTE3: 10883 return performCvtF32UByteNCombine(N, DCI); 10884 case AMDGPUISD::FMED3: 10885 return performFMed3Combine(N, DCI); 10886 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10887 return performCvtPkRTZCombine(N, DCI); 10888 case AMDGPUISD::CLAMP: 10889 return performClampCombine(N, DCI); 10890 case ISD::SCALAR_TO_VECTOR: { 10891 SelectionDAG &DAG = DCI.DAG; 10892 EVT VT = N->getValueType(0); 10893 10894 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10895 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10896 SDLoc SL(N); 10897 SDValue Src = N->getOperand(0); 10898 EVT EltVT = Src.getValueType(); 10899 if (EltVT == MVT::f16) 10900 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10901 10902 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10903 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10904 } 10905 10906 break; 10907 } 10908 case ISD::EXTRACT_VECTOR_ELT: 10909 return performExtractVectorEltCombine(N, DCI); 10910 case ISD::INSERT_VECTOR_ELT: 10911 return performInsertVectorEltCombine(N, DCI); 10912 case ISD::LOAD: { 10913 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10914 return Widended; 10915 LLVM_FALLTHROUGH; 10916 } 10917 default: { 10918 if (!DCI.isBeforeLegalize()) { 10919 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 10920 return performMemSDNodeCombine(MemNode, DCI); 10921 } 10922 10923 break; 10924 } 10925 } 10926 10927 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10928 } 10929 10930 /// Helper function for adjustWritemask 10931 static unsigned SubIdx2Lane(unsigned Idx) { 10932 switch (Idx) { 10933 default: return ~0u; 10934 case AMDGPU::sub0: return 0; 10935 case AMDGPU::sub1: return 1; 10936 case AMDGPU::sub2: return 2; 10937 case AMDGPU::sub3: return 3; 10938 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10939 } 10940 } 10941 10942 /// Adjust the writemask of MIMG instructions 10943 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10944 SelectionDAG &DAG) const { 10945 unsigned Opcode = Node->getMachineOpcode(); 10946 10947 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10948 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10949 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10950 return Node; // not implemented for D16 10951 10952 SDNode *Users[5] = { nullptr }; 10953 unsigned Lane = 0; 10954 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10955 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10956 unsigned NewDmask = 0; 10957 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10958 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10959 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 10960 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10961 unsigned TFCLane = 0; 10962 bool HasChain = Node->getNumValues() > 1; 10963 10964 if (OldDmask == 0) { 10965 // These are folded out, but on the chance it happens don't assert. 10966 return Node; 10967 } 10968 10969 unsigned OldBitsSet = countPopulation(OldDmask); 10970 // Work out which is the TFE/LWE lane if that is enabled. 10971 if (UsesTFC) { 10972 TFCLane = OldBitsSet; 10973 } 10974 10975 // Try to figure out the used register components 10976 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10977 I != E; ++I) { 10978 10979 // Don't look at users of the chain. 10980 if (I.getUse().getResNo() != 0) 10981 continue; 10982 10983 // Abort if we can't understand the usage 10984 if (!I->isMachineOpcode() || 10985 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10986 return Node; 10987 10988 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10989 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10990 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10991 // set, etc. 10992 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10993 if (Lane == ~0u) 10994 return Node; 10995 10996 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10997 if (UsesTFC && Lane == TFCLane) { 10998 Users[Lane] = *I; 10999 } else { 11000 // Set which texture component corresponds to the lane. 11001 unsigned Comp; 11002 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 11003 Comp = countTrailingZeros(Dmask); 11004 Dmask &= ~(1 << Comp); 11005 } 11006 11007 // Abort if we have more than one user per component. 11008 if (Users[Lane]) 11009 return Node; 11010 11011 Users[Lane] = *I; 11012 NewDmask |= 1 << Comp; 11013 } 11014 } 11015 11016 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11017 bool NoChannels = !NewDmask; 11018 if (NoChannels) { 11019 if (!UsesTFC) { 11020 // No uses of the result and not using TFC. Then do nothing. 11021 return Node; 11022 } 11023 // If the original dmask has one channel - then nothing to do 11024 if (OldBitsSet == 1) 11025 return Node; 11026 // Use an arbitrary dmask - required for the instruction to work 11027 NewDmask = 1; 11028 } 11029 // Abort if there's no change 11030 if (NewDmask == OldDmask) 11031 return Node; 11032 11033 unsigned BitsSet = countPopulation(NewDmask); 11034 11035 // Check for TFE or LWE - increase the number of channels by one to account 11036 // for the extra return value 11037 // This will need adjustment for D16 if this is also included in 11038 // adjustWriteMask (this function) but at present D16 are excluded. 11039 unsigned NewChannels = BitsSet + UsesTFC; 11040 11041 int NewOpcode = 11042 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11043 assert(NewOpcode != -1 && 11044 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11045 "failed to find equivalent MIMG op"); 11046 11047 // Adjust the writemask in the node 11048 SmallVector<SDValue, 12> Ops; 11049 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11050 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11051 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11052 11053 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11054 11055 MVT ResultVT = NewChannels == 1 ? 11056 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11057 NewChannels == 5 ? 8 : NewChannels); 11058 SDVTList NewVTList = HasChain ? 11059 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11060 11061 11062 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11063 NewVTList, Ops); 11064 11065 if (HasChain) { 11066 // Update chain. 11067 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11068 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11069 } 11070 11071 if (NewChannels == 1) { 11072 assert(Node->hasNUsesOfValue(1, 0)); 11073 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11074 SDLoc(Node), Users[Lane]->getValueType(0), 11075 SDValue(NewNode, 0)); 11076 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11077 return nullptr; 11078 } 11079 11080 // Update the users of the node with the new indices 11081 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11082 SDNode *User = Users[i]; 11083 if (!User) { 11084 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11085 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11086 if (i || !NoChannels) 11087 continue; 11088 } else { 11089 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11090 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11091 } 11092 11093 switch (Idx) { 11094 default: break; 11095 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11096 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11097 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11098 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11099 } 11100 } 11101 11102 DAG.RemoveDeadNode(Node); 11103 return nullptr; 11104 } 11105 11106 static bool isFrameIndexOp(SDValue Op) { 11107 if (Op.getOpcode() == ISD::AssertZext) 11108 Op = Op.getOperand(0); 11109 11110 return isa<FrameIndexSDNode>(Op); 11111 } 11112 11113 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11114 /// with frame index operands. 11115 /// LLVM assumes that inputs are to these instructions are registers. 11116 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11117 SelectionDAG &DAG) const { 11118 if (Node->getOpcode() == ISD::CopyToReg) { 11119 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11120 SDValue SrcVal = Node->getOperand(2); 11121 11122 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11123 // to try understanding copies to physical registers. 11124 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11125 SDLoc SL(Node); 11126 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11127 SDValue VReg = DAG.getRegister( 11128 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11129 11130 SDNode *Glued = Node->getGluedNode(); 11131 SDValue ToVReg 11132 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11133 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11134 SDValue ToResultReg 11135 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11136 VReg, ToVReg.getValue(1)); 11137 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11138 DAG.RemoveDeadNode(Node); 11139 return ToResultReg.getNode(); 11140 } 11141 } 11142 11143 SmallVector<SDValue, 8> Ops; 11144 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11145 if (!isFrameIndexOp(Node->getOperand(i))) { 11146 Ops.push_back(Node->getOperand(i)); 11147 continue; 11148 } 11149 11150 SDLoc DL(Node); 11151 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11152 Node->getOperand(i).getValueType(), 11153 Node->getOperand(i)), 0)); 11154 } 11155 11156 return DAG.UpdateNodeOperands(Node, Ops); 11157 } 11158 11159 /// Fold the instructions after selecting them. 11160 /// Returns null if users were already updated. 11161 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11162 SelectionDAG &DAG) const { 11163 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11164 unsigned Opcode = Node->getMachineOpcode(); 11165 11166 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11167 !TII->isGather4(Opcode) && 11168 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11169 return adjustWritemask(Node, DAG); 11170 } 11171 11172 if (Opcode == AMDGPU::INSERT_SUBREG || 11173 Opcode == AMDGPU::REG_SEQUENCE) { 11174 legalizeTargetIndependentNode(Node, DAG); 11175 return Node; 11176 } 11177 11178 switch (Opcode) { 11179 case AMDGPU::V_DIV_SCALE_F32_e64: 11180 case AMDGPU::V_DIV_SCALE_F64_e64: { 11181 // Satisfy the operand register constraint when one of the inputs is 11182 // undefined. Ordinarily each undef value will have its own implicit_def of 11183 // a vreg, so force these to use a single register. 11184 SDValue Src0 = Node->getOperand(1); 11185 SDValue Src1 = Node->getOperand(3); 11186 SDValue Src2 = Node->getOperand(5); 11187 11188 if ((Src0.isMachineOpcode() && 11189 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11190 (Src0 == Src1 || Src0 == Src2)) 11191 break; 11192 11193 MVT VT = Src0.getValueType().getSimpleVT(); 11194 const TargetRegisterClass *RC = 11195 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11196 11197 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11198 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11199 11200 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11201 UndefReg, Src0, SDValue()); 11202 11203 // src0 must be the same register as src1 or src2, even if the value is 11204 // undefined, so make sure we don't violate this constraint. 11205 if (Src0.isMachineOpcode() && 11206 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11207 if (Src1.isMachineOpcode() && 11208 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11209 Src0 = Src1; 11210 else if (Src2.isMachineOpcode() && 11211 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11212 Src0 = Src2; 11213 else { 11214 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11215 Src0 = UndefReg; 11216 Src1 = UndefReg; 11217 } 11218 } else 11219 break; 11220 11221 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11222 Ops[1] = Src0; 11223 Ops[3] = Src1; 11224 Ops[5] = Src2; 11225 Ops.push_back(ImpDef.getValue(1)); 11226 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11227 } 11228 default: 11229 break; 11230 } 11231 11232 return Node; 11233 } 11234 11235 // Any MIMG instructions that use tfe or lwe require an initialization of the 11236 // result register that will be written in the case of a memory access failure. 11237 // The required code is also added to tie this init code to the result of the 11238 // img instruction. 11239 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11240 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11241 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11242 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11243 MachineBasicBlock &MBB = *MI.getParent(); 11244 11245 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11246 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11247 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11248 11249 if (!TFE && !LWE) // intersect_ray 11250 return; 11251 11252 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11253 unsigned LWEVal = LWE->getImm(); 11254 unsigned D16Val = D16 ? D16->getImm() : 0; 11255 11256 if (!TFEVal && !LWEVal) 11257 return; 11258 11259 // At least one of TFE or LWE are non-zero 11260 // We have to insert a suitable initialization of the result value and 11261 // tie this to the dest of the image instruction. 11262 11263 const DebugLoc &DL = MI.getDebugLoc(); 11264 11265 int DstIdx = 11266 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11267 11268 // Calculate which dword we have to initialize to 0. 11269 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11270 11271 // check that dmask operand is found. 11272 assert(MO_Dmask && "Expected dmask operand in instruction"); 11273 11274 unsigned dmask = MO_Dmask->getImm(); 11275 // Determine the number of active lanes taking into account the 11276 // Gather4 special case 11277 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11278 11279 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11280 11281 unsigned InitIdx = 11282 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11283 11284 // Abandon attempt if the dst size isn't large enough 11285 // - this is in fact an error but this is picked up elsewhere and 11286 // reported correctly. 11287 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11288 if (DstSize < InitIdx) 11289 return; 11290 11291 // Create a register for the intialization value. 11292 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11293 unsigned NewDst = 0; // Final initialized value will be in here 11294 11295 // If PRTStrictNull feature is enabled (the default) then initialize 11296 // all the result registers to 0, otherwise just the error indication 11297 // register (VGPRn+1) 11298 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11299 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11300 11301 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11302 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11303 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11304 // Initialize dword 11305 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11306 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11307 .addImm(0); 11308 // Insert into the super-reg 11309 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11310 .addReg(PrevDst) 11311 .addReg(SubReg) 11312 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11313 11314 PrevDst = NewDst; 11315 } 11316 11317 // Add as an implicit operand 11318 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11319 11320 // Tie the just added implicit operand to the dst 11321 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11322 } 11323 11324 /// Assign the register class depending on the number of 11325 /// bits set in the writemask 11326 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11327 SDNode *Node) const { 11328 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11329 11330 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11331 11332 if (TII->isVOP3(MI.getOpcode())) { 11333 // Make sure constant bus requirements are respected. 11334 TII->legalizeOperandsVOP3(MRI, MI); 11335 11336 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11337 // This saves a chain-copy of registers and better ballance register 11338 // use between vgpr and agpr as agpr tuples tend to be big. 11339 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 11340 unsigned Opc = MI.getOpcode(); 11341 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11342 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11343 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11344 if (I == -1) 11345 break; 11346 MachineOperand &Op = MI.getOperand(I); 11347 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 11348 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 11349 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 11350 continue; 11351 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11352 if (!Src || !Src->isCopy() || 11353 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11354 continue; 11355 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11356 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11357 // All uses of agpr64 and agpr32 can also accept vgpr except for 11358 // v_accvgpr_read, but we do not produce agpr reads during selection, 11359 // so no use checks are needed. 11360 MRI.setRegClass(Op.getReg(), NewRC); 11361 } 11362 } 11363 11364 return; 11365 } 11366 11367 // Replace unused atomics with the no return version. 11368 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11369 if (NoRetAtomicOp != -1) { 11370 if (!Node->hasAnyUseOfValue(0)) { 11371 int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11372 AMDGPU::OpName::cpol); 11373 if (CPolIdx != -1) { 11374 MachineOperand &CPol = MI.getOperand(CPolIdx); 11375 CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC); 11376 } 11377 MI.RemoveOperand(0); 11378 MI.setDesc(TII->get(NoRetAtomicOp)); 11379 return; 11380 } 11381 11382 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11383 // instruction, because the return type of these instructions is a vec2 of 11384 // the memory type, so it can be tied to the input operand. 11385 // This means these instructions always have a use, so we need to add a 11386 // special case to check if the atomic has only one extract_subreg use, 11387 // which itself has no uses. 11388 if ((Node->hasNUsesOfValue(1, 0) && 11389 Node->use_begin()->isMachineOpcode() && 11390 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11391 !Node->use_begin()->hasAnyUseOfValue(0))) { 11392 Register Def = MI.getOperand(0).getReg(); 11393 11394 // Change this into a noret atomic. 11395 MI.setDesc(TII->get(NoRetAtomicOp)); 11396 MI.RemoveOperand(0); 11397 11398 // If we only remove the def operand from the atomic instruction, the 11399 // extract_subreg will be left with a use of a vreg without a def. 11400 // So we need to insert an implicit_def to avoid machine verifier 11401 // errors. 11402 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11403 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11404 } 11405 return; 11406 } 11407 11408 if (TII->isMIMG(MI) && !MI.mayStore()) 11409 AddIMGInit(MI); 11410 } 11411 11412 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11413 uint64_t Val) { 11414 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11415 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11416 } 11417 11418 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11419 const SDLoc &DL, 11420 SDValue Ptr) const { 11421 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11422 11423 // Build the half of the subregister with the constants before building the 11424 // full 128-bit register. If we are building multiple resource descriptors, 11425 // this will allow CSEing of the 2-component register. 11426 const SDValue Ops0[] = { 11427 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11428 buildSMovImm32(DAG, DL, 0), 11429 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11430 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11431 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11432 }; 11433 11434 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11435 MVT::v2i32, Ops0), 0); 11436 11437 // Combine the constants and the pointer. 11438 const SDValue Ops1[] = { 11439 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11440 Ptr, 11441 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11442 SubRegHi, 11443 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11444 }; 11445 11446 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11447 } 11448 11449 /// Return a resource descriptor with the 'Add TID' bit enabled 11450 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11451 /// of the resource descriptor) to create an offset, which is added to 11452 /// the resource pointer. 11453 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11454 SDValue Ptr, uint32_t RsrcDword1, 11455 uint64_t RsrcDword2And3) const { 11456 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11457 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11458 if (RsrcDword1) { 11459 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11460 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11461 0); 11462 } 11463 11464 SDValue DataLo = buildSMovImm32(DAG, DL, 11465 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11466 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11467 11468 const SDValue Ops[] = { 11469 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11470 PtrLo, 11471 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11472 PtrHi, 11473 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11474 DataLo, 11475 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11476 DataHi, 11477 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11478 }; 11479 11480 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11481 } 11482 11483 //===----------------------------------------------------------------------===// 11484 // SI Inline Assembly Support 11485 //===----------------------------------------------------------------------===// 11486 11487 std::pair<unsigned, const TargetRegisterClass *> 11488 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11489 StringRef Constraint, 11490 MVT VT) const { 11491 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11492 11493 const TargetRegisterClass *RC = nullptr; 11494 if (Constraint.size() == 1) { 11495 const unsigned BitWidth = VT.getSizeInBits(); 11496 switch (Constraint[0]) { 11497 default: 11498 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11499 case 's': 11500 case 'r': 11501 switch (BitWidth) { 11502 case 16: 11503 RC = &AMDGPU::SReg_32RegClass; 11504 break; 11505 case 64: 11506 RC = &AMDGPU::SGPR_64RegClass; 11507 break; 11508 default: 11509 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11510 if (!RC) 11511 return std::make_pair(0U, nullptr); 11512 break; 11513 } 11514 break; 11515 case 'v': 11516 switch (BitWidth) { 11517 case 16: 11518 RC = &AMDGPU::VGPR_32RegClass; 11519 break; 11520 default: 11521 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11522 if (!RC) 11523 return std::make_pair(0U, nullptr); 11524 break; 11525 } 11526 break; 11527 case 'a': 11528 if (!Subtarget->hasMAIInsts()) 11529 break; 11530 switch (BitWidth) { 11531 case 16: 11532 RC = &AMDGPU::AGPR_32RegClass; 11533 break; 11534 default: 11535 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11536 if (!RC) 11537 return std::make_pair(0U, nullptr); 11538 break; 11539 } 11540 break; 11541 } 11542 // We actually support i128, i16 and f16 as inline parameters 11543 // even if they are not reported as legal 11544 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11545 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11546 return std::make_pair(0U, RC); 11547 } 11548 11549 if (Constraint.size() > 1) { 11550 if (Constraint[1] == 'v') { 11551 RC = &AMDGPU::VGPR_32RegClass; 11552 } else if (Constraint[1] == 's') { 11553 RC = &AMDGPU::SGPR_32RegClass; 11554 } else if (Constraint[1] == 'a') { 11555 RC = &AMDGPU::AGPR_32RegClass; 11556 } 11557 11558 if (RC) { 11559 uint32_t Idx; 11560 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11561 if (!Failed && Idx < RC->getNumRegs()) 11562 return std::make_pair(RC->getRegister(Idx), RC); 11563 } 11564 } 11565 11566 // FIXME: Returns VS_32 for physical SGPR constraints 11567 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11568 } 11569 11570 static bool isImmConstraint(StringRef Constraint) { 11571 if (Constraint.size() == 1) { 11572 switch (Constraint[0]) { 11573 default: break; 11574 case 'I': 11575 case 'J': 11576 case 'A': 11577 case 'B': 11578 case 'C': 11579 return true; 11580 } 11581 } else if (Constraint == "DA" || 11582 Constraint == "DB") { 11583 return true; 11584 } 11585 return false; 11586 } 11587 11588 SITargetLowering::ConstraintType 11589 SITargetLowering::getConstraintType(StringRef Constraint) const { 11590 if (Constraint.size() == 1) { 11591 switch (Constraint[0]) { 11592 default: break; 11593 case 's': 11594 case 'v': 11595 case 'a': 11596 return C_RegisterClass; 11597 } 11598 } 11599 if (isImmConstraint(Constraint)) { 11600 return C_Other; 11601 } 11602 return TargetLowering::getConstraintType(Constraint); 11603 } 11604 11605 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11606 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11607 Val = Val & maskTrailingOnes<uint64_t>(Size); 11608 } 11609 return Val; 11610 } 11611 11612 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11613 std::string &Constraint, 11614 std::vector<SDValue> &Ops, 11615 SelectionDAG &DAG) const { 11616 if (isImmConstraint(Constraint)) { 11617 uint64_t Val; 11618 if (getAsmOperandConstVal(Op, Val) && 11619 checkAsmConstraintVal(Op, Constraint, Val)) { 11620 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11621 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11622 } 11623 } else { 11624 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11625 } 11626 } 11627 11628 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11629 unsigned Size = Op.getScalarValueSizeInBits(); 11630 if (Size > 64) 11631 return false; 11632 11633 if (Size == 16 && !Subtarget->has16BitInsts()) 11634 return false; 11635 11636 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11637 Val = C->getSExtValue(); 11638 return true; 11639 } 11640 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11641 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11642 return true; 11643 } 11644 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11645 if (Size != 16 || Op.getNumOperands() != 2) 11646 return false; 11647 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11648 return false; 11649 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11650 Val = C->getSExtValue(); 11651 return true; 11652 } 11653 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11654 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11655 return true; 11656 } 11657 } 11658 11659 return false; 11660 } 11661 11662 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11663 const std::string &Constraint, 11664 uint64_t Val) const { 11665 if (Constraint.size() == 1) { 11666 switch (Constraint[0]) { 11667 case 'I': 11668 return AMDGPU::isInlinableIntLiteral(Val); 11669 case 'J': 11670 return isInt<16>(Val); 11671 case 'A': 11672 return checkAsmConstraintValA(Op, Val); 11673 case 'B': 11674 return isInt<32>(Val); 11675 case 'C': 11676 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11677 AMDGPU::isInlinableIntLiteral(Val); 11678 default: 11679 break; 11680 } 11681 } else if (Constraint.size() == 2) { 11682 if (Constraint == "DA") { 11683 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11684 int64_t LoBits = static_cast<int32_t>(Val); 11685 return checkAsmConstraintValA(Op, HiBits, 32) && 11686 checkAsmConstraintValA(Op, LoBits, 32); 11687 } 11688 if (Constraint == "DB") { 11689 return true; 11690 } 11691 } 11692 llvm_unreachable("Invalid asm constraint"); 11693 } 11694 11695 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11696 uint64_t Val, 11697 unsigned MaxSize) const { 11698 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11699 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11700 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11701 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11702 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11703 return true; 11704 } 11705 return false; 11706 } 11707 11708 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 11709 switch (UnalignedClassID) { 11710 case AMDGPU::VReg_64RegClassID: 11711 return AMDGPU::VReg_64_Align2RegClassID; 11712 case AMDGPU::VReg_96RegClassID: 11713 return AMDGPU::VReg_96_Align2RegClassID; 11714 case AMDGPU::VReg_128RegClassID: 11715 return AMDGPU::VReg_128_Align2RegClassID; 11716 case AMDGPU::VReg_160RegClassID: 11717 return AMDGPU::VReg_160_Align2RegClassID; 11718 case AMDGPU::VReg_192RegClassID: 11719 return AMDGPU::VReg_192_Align2RegClassID; 11720 case AMDGPU::VReg_256RegClassID: 11721 return AMDGPU::VReg_256_Align2RegClassID; 11722 case AMDGPU::VReg_512RegClassID: 11723 return AMDGPU::VReg_512_Align2RegClassID; 11724 case AMDGPU::VReg_1024RegClassID: 11725 return AMDGPU::VReg_1024_Align2RegClassID; 11726 case AMDGPU::AReg_64RegClassID: 11727 return AMDGPU::AReg_64_Align2RegClassID; 11728 case AMDGPU::AReg_96RegClassID: 11729 return AMDGPU::AReg_96_Align2RegClassID; 11730 case AMDGPU::AReg_128RegClassID: 11731 return AMDGPU::AReg_128_Align2RegClassID; 11732 case AMDGPU::AReg_160RegClassID: 11733 return AMDGPU::AReg_160_Align2RegClassID; 11734 case AMDGPU::AReg_192RegClassID: 11735 return AMDGPU::AReg_192_Align2RegClassID; 11736 case AMDGPU::AReg_256RegClassID: 11737 return AMDGPU::AReg_256_Align2RegClassID; 11738 case AMDGPU::AReg_512RegClassID: 11739 return AMDGPU::AReg_512_Align2RegClassID; 11740 case AMDGPU::AReg_1024RegClassID: 11741 return AMDGPU::AReg_1024_Align2RegClassID; 11742 default: 11743 return -1; 11744 } 11745 } 11746 11747 // Figure out which registers should be reserved for stack access. Only after 11748 // the function is legalized do we know all of the non-spill stack objects or if 11749 // calls are present. 11750 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11751 MachineRegisterInfo &MRI = MF.getRegInfo(); 11752 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11753 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11754 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11755 const SIInstrInfo *TII = ST.getInstrInfo(); 11756 11757 if (Info->isEntryFunction()) { 11758 // Callable functions have fixed registers used for stack access. 11759 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11760 } 11761 11762 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11763 Info->getStackPtrOffsetReg())); 11764 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11765 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11766 11767 // We need to worry about replacing the default register with itself in case 11768 // of MIR testcases missing the MFI. 11769 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11770 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11771 11772 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11773 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11774 11775 Info->limitOccupancy(MF); 11776 11777 if (ST.isWave32() && !MF.empty()) { 11778 for (auto &MBB : MF) { 11779 for (auto &MI : MBB) { 11780 TII->fixImplicitOperands(MI); 11781 } 11782 } 11783 } 11784 11785 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 11786 // classes if required. Ideally the register class constraints would differ 11787 // per-subtarget, but there's no easy way to achieve that right now. This is 11788 // not a problem for VGPRs because the correctly aligned VGPR class is implied 11789 // from using them as the register class for legal types. 11790 if (ST.needsAlignedVGPRs()) { 11791 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 11792 const Register Reg = Register::index2VirtReg(I); 11793 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 11794 if (!RC) 11795 continue; 11796 int NewClassID = getAlignedAGPRClassID(RC->getID()); 11797 if (NewClassID != -1) 11798 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 11799 } 11800 } 11801 11802 TargetLoweringBase::finalizeLowering(MF); 11803 11804 // Allocate a VGPR for future SGPR Spill if 11805 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11806 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11807 if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() && 11808 !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction()) 11809 Info->reserveVGPRforSGPRSpills(MF); 11810 } 11811 11812 void SITargetLowering::computeKnownBitsForFrameIndex( 11813 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11814 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11815 11816 // Set the high bits to zero based on the maximum allowed scratch size per 11817 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11818 // calculation won't overflow, so assume the sign bit is never set. 11819 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11820 } 11821 11822 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11823 KnownBits &Known, unsigned Dim) { 11824 unsigned MaxValue = 11825 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11826 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11827 } 11828 11829 void SITargetLowering::computeKnownBitsForTargetInstr( 11830 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11831 const MachineRegisterInfo &MRI, unsigned Depth) const { 11832 const MachineInstr *MI = MRI.getVRegDef(R); 11833 switch (MI->getOpcode()) { 11834 case AMDGPU::G_INTRINSIC: { 11835 switch (MI->getIntrinsicID()) { 11836 case Intrinsic::amdgcn_workitem_id_x: 11837 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11838 break; 11839 case Intrinsic::amdgcn_workitem_id_y: 11840 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11841 break; 11842 case Intrinsic::amdgcn_workitem_id_z: 11843 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11844 break; 11845 case Intrinsic::amdgcn_mbcnt_lo: 11846 case Intrinsic::amdgcn_mbcnt_hi: { 11847 // These return at most the wavefront size - 1. 11848 unsigned Size = MRI.getType(R).getSizeInBits(); 11849 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11850 break; 11851 } 11852 case Intrinsic::amdgcn_groupstaticsize: { 11853 // We can report everything over the maximum size as 0. We can't report 11854 // based on the actual size because we don't know if it's accurate or not 11855 // at any given point. 11856 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11857 break; 11858 } 11859 } 11860 break; 11861 } 11862 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 11863 Known.Zero.setHighBits(24); 11864 break; 11865 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 11866 Known.Zero.setHighBits(16); 11867 break; 11868 } 11869 } 11870 11871 Align SITargetLowering::computeKnownAlignForTargetInstr( 11872 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11873 unsigned Depth) const { 11874 const MachineInstr *MI = MRI.getVRegDef(R); 11875 switch (MI->getOpcode()) { 11876 case AMDGPU::G_INTRINSIC: 11877 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11878 // FIXME: Can this move to generic code? What about the case where the call 11879 // site specifies a lower alignment? 11880 Intrinsic::ID IID = MI->getIntrinsicID(); 11881 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11882 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11883 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11884 return *RetAlign; 11885 return Align(1); 11886 } 11887 default: 11888 return Align(1); 11889 } 11890 } 11891 11892 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11893 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11894 const Align CacheLineAlign = Align(64); 11895 11896 // Pre-GFX10 target did not benefit from loop alignment 11897 if (!ML || DisableLoopAlignment || 11898 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11899 getSubtarget()->hasInstFwdPrefetchBug()) 11900 return PrefAlign; 11901 11902 // On GFX10 I$ is 4 x 64 bytes cache lines. 11903 // By default prefetcher keeps one cache line behind and reads two ahead. 11904 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11905 // behind and one ahead. 11906 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11907 // If loop fits 64 bytes it always spans no more than two cache lines and 11908 // does not need an alignment. 11909 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11910 // Else if loop is less or equal 192 bytes we need two lines behind. 11911 11912 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11913 const MachineBasicBlock *Header = ML->getHeader(); 11914 if (Header->getAlignment() != PrefAlign) 11915 return Header->getAlignment(); // Already processed. 11916 11917 unsigned LoopSize = 0; 11918 for (const MachineBasicBlock *MBB : ML->blocks()) { 11919 // If inner loop block is aligned assume in average half of the alignment 11920 // size to be added as nops. 11921 if (MBB != Header) 11922 LoopSize += MBB->getAlignment().value() / 2; 11923 11924 for (const MachineInstr &MI : *MBB) { 11925 LoopSize += TII->getInstSizeInBytes(MI); 11926 if (LoopSize > 192) 11927 return PrefAlign; 11928 } 11929 } 11930 11931 if (LoopSize <= 64) 11932 return PrefAlign; 11933 11934 if (LoopSize <= 128) 11935 return CacheLineAlign; 11936 11937 // If any of parent loops is surrounded by prefetch instructions do not 11938 // insert new for inner loop, which would reset parent's settings. 11939 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11940 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11941 auto I = Exit->getFirstNonDebugInstr(); 11942 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11943 return CacheLineAlign; 11944 } 11945 } 11946 11947 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11948 MachineBasicBlock *Exit = ML->getExitBlock(); 11949 11950 if (Pre && Exit) { 11951 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11952 TII->get(AMDGPU::S_INST_PREFETCH)) 11953 .addImm(1); // prefetch 2 lines behind PC 11954 11955 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11956 TII->get(AMDGPU::S_INST_PREFETCH)) 11957 .addImm(2); // prefetch 1 line behind PC 11958 } 11959 11960 return CacheLineAlign; 11961 } 11962 11963 LLVM_ATTRIBUTE_UNUSED 11964 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11965 assert(N->getOpcode() == ISD::CopyFromReg); 11966 do { 11967 // Follow the chain until we find an INLINEASM node. 11968 N = N->getOperand(0).getNode(); 11969 if (N->getOpcode() == ISD::INLINEASM || 11970 N->getOpcode() == ISD::INLINEASM_BR) 11971 return true; 11972 } while (N->getOpcode() == ISD::CopyFromReg); 11973 return false; 11974 } 11975 11976 bool SITargetLowering::isSDNodeSourceOfDivergence( 11977 const SDNode *N, FunctionLoweringInfo *FLI, 11978 LegacyDivergenceAnalysis *KDA) const { 11979 switch (N->getOpcode()) { 11980 case ISD::CopyFromReg: { 11981 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11982 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11983 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11984 Register Reg = R->getReg(); 11985 11986 // FIXME: Why does this need to consider isLiveIn? 11987 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11988 return !TRI->isSGPRReg(MRI, Reg); 11989 11990 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11991 return KDA->isDivergent(V); 11992 11993 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11994 return !TRI->isSGPRReg(MRI, Reg); 11995 } 11996 case ISD::LOAD: { 11997 const LoadSDNode *L = cast<LoadSDNode>(N); 11998 unsigned AS = L->getAddressSpace(); 11999 // A flat load may access private memory. 12000 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 12001 } 12002 case ISD::CALLSEQ_END: 12003 return true; 12004 case ISD::INTRINSIC_WO_CHAIN: 12005 return AMDGPU::isIntrinsicSourceOfDivergence( 12006 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 12007 case ISD::INTRINSIC_W_CHAIN: 12008 return AMDGPU::isIntrinsicSourceOfDivergence( 12009 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 12010 case AMDGPUISD::ATOMIC_CMP_SWAP: 12011 case AMDGPUISD::ATOMIC_INC: 12012 case AMDGPUISD::ATOMIC_DEC: 12013 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12014 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12015 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12016 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12017 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12018 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12019 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12020 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12021 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12022 case AMDGPUISD::BUFFER_ATOMIC_AND: 12023 case AMDGPUISD::BUFFER_ATOMIC_OR: 12024 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12025 case AMDGPUISD::BUFFER_ATOMIC_INC: 12026 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12027 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12028 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12029 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12030 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12031 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12032 // Target-specific read-modify-write atomics are sources of divergence. 12033 return true; 12034 default: 12035 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12036 // Generic read-modify-write atomics are sources of divergence. 12037 return A->readMem() && A->writeMem(); 12038 } 12039 return false; 12040 } 12041 } 12042 12043 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12044 EVT VT) const { 12045 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12046 case MVT::f32: 12047 return hasFP32Denormals(DAG.getMachineFunction()); 12048 case MVT::f64: 12049 case MVT::f16: 12050 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12051 default: 12052 return false; 12053 } 12054 } 12055 12056 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12057 MachineFunction &MF) const { 12058 switch (Ty.getScalarSizeInBits()) { 12059 case 32: 12060 return hasFP32Denormals(MF); 12061 case 64: 12062 case 16: 12063 return hasFP64FP16Denormals(MF); 12064 default: 12065 return false; 12066 } 12067 } 12068 12069 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12070 const SelectionDAG &DAG, 12071 bool SNaN, 12072 unsigned Depth) const { 12073 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12074 const MachineFunction &MF = DAG.getMachineFunction(); 12075 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12076 12077 if (Info->getMode().DX10Clamp) 12078 return true; // Clamped to 0. 12079 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12080 } 12081 12082 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12083 SNaN, Depth); 12084 } 12085 12086 // Global FP atomic instructions have a hardcoded FP mode and do not support 12087 // FP32 denormals, and only support v2f16 denormals. 12088 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12089 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12090 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12091 if (&Flt == &APFloat::IEEEsingle()) 12092 return DenormMode == DenormalMode::getPreserveSign(); 12093 return DenormMode == DenormalMode::getIEEE(); 12094 } 12095 12096 TargetLowering::AtomicExpansionKind 12097 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12098 switch (RMW->getOperation()) { 12099 case AtomicRMWInst::FAdd: { 12100 Type *Ty = RMW->getType(); 12101 12102 // We don't have a way to support 16-bit atomics now, so just leave them 12103 // as-is. 12104 if (Ty->isHalfTy()) 12105 return AtomicExpansionKind::None; 12106 12107 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12108 return AtomicExpansionKind::CmpXChg; 12109 12110 // TODO: Do have these for flat. Older targets also had them for buffers. 12111 unsigned AS = RMW->getPointerAddressSpace(); 12112 12113 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12114 Subtarget->hasAtomicFaddInsts()) { 12115 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12116 // floating point atomic instructions. May generate more efficient code, 12117 // but may not respect rounding and denormal modes, and may give incorrect 12118 // results for certain memory destinations. 12119 if (!fpModeMatchesGlobalFPAtomicMode(RMW) && 12120 RMW->getFunction() 12121 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12122 .getValueAsString() != "true") 12123 return AtomicExpansionKind::CmpXChg; 12124 12125 if (Subtarget->hasGFX90AInsts()) { 12126 auto SSID = RMW->getSyncScopeID(); 12127 if (SSID == SyncScope::System || 12128 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12129 return AtomicExpansionKind::CmpXChg; 12130 12131 return (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) ? 12132 AtomicExpansionKind::CmpXChg : AtomicExpansionKind::None; 12133 } 12134 12135 if (!Subtarget->hasGFX90AInsts() && AS != AMDGPUAS::GLOBAL_ADDRESS) 12136 return AtomicExpansionKind::CmpXChg; 12137 12138 return RMW->use_empty() ? AtomicExpansionKind::None : 12139 AtomicExpansionKind::CmpXChg; 12140 } 12141 12142 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 12143 // to round-to-nearest-even. 12144 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12145 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) { 12146 return (Ty->isDoubleTy() && !fpModeMatchesGlobalFPAtomicMode(RMW)) ? 12147 AtomicExpansionKind::CmpXChg : AtomicExpansionKind::None; 12148 } 12149 12150 return AtomicExpansionKind::CmpXChg; 12151 } 12152 default: 12153 break; 12154 } 12155 12156 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12157 } 12158 12159 const TargetRegisterClass * 12160 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12161 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12162 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12163 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12164 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12165 : &AMDGPU::SReg_32RegClass; 12166 if (!TRI->isSGPRClass(RC) && !isDivergent) 12167 return TRI->getEquivalentSGPRClass(RC); 12168 else if (TRI->isSGPRClass(RC) && isDivergent) 12169 return TRI->getEquivalentVGPRClass(RC); 12170 12171 return RC; 12172 } 12173 12174 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12175 // uniform values (as produced by the mask results of control flow intrinsics) 12176 // used outside of divergent blocks. The phi users need to also be treated as 12177 // always uniform. 12178 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12179 unsigned WaveSize) { 12180 // FIXME: We asssume we never cast the mask results of a control flow 12181 // intrinsic. 12182 // Early exit if the type won't be consistent as a compile time hack. 12183 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12184 if (!IT || IT->getBitWidth() != WaveSize) 12185 return false; 12186 12187 if (!isa<Instruction>(V)) 12188 return false; 12189 if (!Visited.insert(V).second) 12190 return false; 12191 bool Result = false; 12192 for (auto U : V->users()) { 12193 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12194 if (V == U->getOperand(1)) { 12195 switch (Intrinsic->getIntrinsicID()) { 12196 default: 12197 Result = false; 12198 break; 12199 case Intrinsic::amdgcn_if_break: 12200 case Intrinsic::amdgcn_if: 12201 case Intrinsic::amdgcn_else: 12202 Result = true; 12203 break; 12204 } 12205 } 12206 if (V == U->getOperand(0)) { 12207 switch (Intrinsic->getIntrinsicID()) { 12208 default: 12209 Result = false; 12210 break; 12211 case Intrinsic::amdgcn_end_cf: 12212 case Intrinsic::amdgcn_loop: 12213 Result = true; 12214 break; 12215 } 12216 } 12217 } else { 12218 Result = hasCFUser(U, Visited, WaveSize); 12219 } 12220 if (Result) 12221 break; 12222 } 12223 return Result; 12224 } 12225 12226 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12227 const Value *V) const { 12228 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12229 if (CI->isInlineAsm()) { 12230 // FIXME: This cannot give a correct answer. This should only trigger in 12231 // the case where inline asm returns mixed SGPR and VGPR results, used 12232 // outside the defining block. We don't have a specific result to 12233 // consider, so this assumes if any value is SGPR, the overall register 12234 // also needs to be SGPR. 12235 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12236 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12237 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12238 for (auto &TC : TargetConstraints) { 12239 if (TC.Type == InlineAsm::isOutput) { 12240 ComputeConstraintToUse(TC, SDValue()); 12241 unsigned AssignedReg; 12242 const TargetRegisterClass *RC; 12243 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 12244 SIRI, TC.ConstraintCode, TC.ConstraintVT); 12245 if (RC) { 12246 MachineRegisterInfo &MRI = MF.getRegInfo(); 12247 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 12248 return true; 12249 else if (SIRI->isSGPRClass(RC)) 12250 return true; 12251 } 12252 } 12253 } 12254 } 12255 } 12256 SmallPtrSet<const Value *, 16> Visited; 12257 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12258 } 12259 12260 std::pair<int, MVT> 12261 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12262 Type *Ty) const { 12263 auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12264 auto Size = DL.getTypeSizeInBits(Ty); 12265 // Maximum load or store can handle 8 dwords for scalar and 4 for 12266 // vector ALU. Let's assume anything above 8 dwords is expensive 12267 // even if legal. 12268 if (Size <= 256) 12269 return Cost; 12270 12271 Cost.first = (Size + 255) / 256; 12272 return Cost; 12273 } 12274