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 MachineFunction &MF = DAG.getMachineFunction(); 2855 const Function &CallerF = MF.getFunction(); 2856 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2857 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2858 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2859 2860 // Kernels aren't callable, and don't have a live in return address so it 2861 // doesn't make sense to do a tail call with entry functions. 2862 if (!CallerPreserved) 2863 return false; 2864 2865 bool CCMatch = CallerCC == CalleeCC; 2866 2867 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2868 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2869 return true; 2870 return false; 2871 } 2872 2873 // TODO: Can we handle var args? 2874 if (IsVarArg) 2875 return false; 2876 2877 for (const Argument &Arg : CallerF.args()) { 2878 if (Arg.hasByValAttr()) 2879 return false; 2880 } 2881 2882 LLVMContext &Ctx = *DAG.getContext(); 2883 2884 // Check that the call results are passed in the same way. 2885 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2886 CCAssignFnForCall(CalleeCC, IsVarArg), 2887 CCAssignFnForCall(CallerCC, IsVarArg))) 2888 return false; 2889 2890 // The callee has to preserve all registers the caller needs to preserve. 2891 if (!CCMatch) { 2892 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2893 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2894 return false; 2895 } 2896 2897 // Nothing more to check if the callee is taking no arguments. 2898 if (Outs.empty()) 2899 return true; 2900 2901 SmallVector<CCValAssign, 16> ArgLocs; 2902 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2903 2904 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2905 2906 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2907 // If the stack arguments for this call do not fit into our own save area then 2908 // the call cannot be made tail. 2909 // TODO: Is this really necessary? 2910 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2911 return false; 2912 2913 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2914 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2915 } 2916 2917 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2918 if (!CI->isTailCall()) 2919 return false; 2920 2921 const Function *ParentFn = CI->getParent()->getParent(); 2922 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2923 return false; 2924 return true; 2925 } 2926 2927 // The wave scratch offset register is used as the global base pointer. 2928 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2929 SmallVectorImpl<SDValue> &InVals) const { 2930 SelectionDAG &DAG = CLI.DAG; 2931 const SDLoc &DL = CLI.DL; 2932 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2933 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2934 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2935 SDValue Chain = CLI.Chain; 2936 SDValue Callee = CLI.Callee; 2937 bool &IsTailCall = CLI.IsTailCall; 2938 CallingConv::ID CallConv = CLI.CallConv; 2939 bool IsVarArg = CLI.IsVarArg; 2940 bool IsSibCall = false; 2941 bool IsThisReturn = false; 2942 MachineFunction &MF = DAG.getMachineFunction(); 2943 2944 if (Callee.isUndef() || isNullConstant(Callee)) { 2945 if (!CLI.IsTailCall) { 2946 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2947 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2948 } 2949 2950 return Chain; 2951 } 2952 2953 if (IsVarArg) { 2954 return lowerUnhandledCall(CLI, InVals, 2955 "unsupported call to variadic function "); 2956 } 2957 2958 if (!CLI.CB) 2959 report_fatal_error("unsupported libcall legalization"); 2960 2961 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2962 return lowerUnhandledCall(CLI, InVals, 2963 "unsupported required tail call to function "); 2964 } 2965 2966 if (AMDGPU::isShader(CallConv)) { 2967 // Note the issue is with the CC of the called function, not of the call 2968 // itself. 2969 return lowerUnhandledCall(CLI, InVals, 2970 "unsupported call to a shader function "); 2971 } 2972 2973 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 2974 CallConv != CallingConv::AMDGPU_Gfx) { 2975 // Only allow calls with specific calling conventions. 2976 return lowerUnhandledCall(CLI, InVals, 2977 "unsupported calling convention for call from " 2978 "graphics shader of function "); 2979 } 2980 2981 if (IsTailCall) { 2982 IsTailCall = isEligibleForTailCallOptimization( 2983 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2984 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2985 report_fatal_error("failed to perform tail call elimination on a call " 2986 "site marked musttail"); 2987 } 2988 2989 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2990 2991 // A sibling call is one where we're under the usual C ABI and not planning 2992 // to change that but can still do a tail call: 2993 if (!TailCallOpt && IsTailCall) 2994 IsSibCall = true; 2995 2996 if (IsTailCall) 2997 ++NumTailCalls; 2998 } 2999 3000 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3001 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3002 SmallVector<SDValue, 8> MemOpChains; 3003 3004 // Analyze operands of the call, assigning locations to each operand. 3005 SmallVector<CCValAssign, 16> ArgLocs; 3006 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3007 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3008 3009 if (AMDGPUTargetMachine::EnableFixedFunctionABI && 3010 CallConv != CallingConv::AMDGPU_Gfx) { 3011 // With a fixed ABI, allocate fixed registers before user arguments. 3012 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3013 } 3014 3015 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3016 3017 // Get a count of how many bytes are to be pushed on the stack. 3018 unsigned NumBytes = CCInfo.getNextStackOffset(); 3019 3020 if (IsSibCall) { 3021 // Since we're not changing the ABI to make this a tail call, the memory 3022 // operands are already available in the caller's incoming argument space. 3023 NumBytes = 0; 3024 } 3025 3026 // FPDiff is the byte offset of the call's argument area from the callee's. 3027 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3028 // by this amount for a tail call. In a sibling call it must be 0 because the 3029 // caller will deallocate the entire stack and the callee still expects its 3030 // arguments to begin at SP+0. Completely unused for non-tail calls. 3031 int32_t FPDiff = 0; 3032 MachineFrameInfo &MFI = MF.getFrameInfo(); 3033 3034 // Adjust the stack pointer for the new arguments... 3035 // These operations are automatically eliminated by the prolog/epilog pass 3036 if (!IsSibCall) { 3037 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3038 3039 if (!Subtarget->enableFlatScratch()) { 3040 SmallVector<SDValue, 4> CopyFromChains; 3041 3042 // In the HSA case, this should be an identity copy. 3043 SDValue ScratchRSrcReg 3044 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3045 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3046 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3047 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3048 } 3049 } 3050 3051 MVT PtrVT = MVT::i32; 3052 3053 // Walk the register/memloc assignments, inserting copies/loads. 3054 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3055 CCValAssign &VA = ArgLocs[i]; 3056 SDValue Arg = OutVals[i]; 3057 3058 // Promote the value if needed. 3059 switch (VA.getLocInfo()) { 3060 case CCValAssign::Full: 3061 break; 3062 case CCValAssign::BCvt: 3063 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3064 break; 3065 case CCValAssign::ZExt: 3066 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3067 break; 3068 case CCValAssign::SExt: 3069 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3070 break; 3071 case CCValAssign::AExt: 3072 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3073 break; 3074 case CCValAssign::FPExt: 3075 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3076 break; 3077 default: 3078 llvm_unreachable("Unknown loc info!"); 3079 } 3080 3081 if (VA.isRegLoc()) { 3082 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3083 } else { 3084 assert(VA.isMemLoc()); 3085 3086 SDValue DstAddr; 3087 MachinePointerInfo DstInfo; 3088 3089 unsigned LocMemOffset = VA.getLocMemOffset(); 3090 int32_t Offset = LocMemOffset; 3091 3092 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3093 MaybeAlign Alignment; 3094 3095 if (IsTailCall) { 3096 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3097 unsigned OpSize = Flags.isByVal() ? 3098 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3099 3100 // FIXME: We can have better than the minimum byval required alignment. 3101 Alignment = 3102 Flags.isByVal() 3103 ? Flags.getNonZeroByValAlign() 3104 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3105 3106 Offset = Offset + FPDiff; 3107 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3108 3109 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3110 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3111 3112 // Make sure any stack arguments overlapping with where we're storing 3113 // are loaded before this eventual operation. Otherwise they'll be 3114 // clobbered. 3115 3116 // FIXME: Why is this really necessary? This seems to just result in a 3117 // lot of code to copy the stack and write them back to the same 3118 // locations, which are supposed to be immutable? 3119 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3120 } else { 3121 DstAddr = PtrOff; 3122 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3123 Alignment = 3124 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3125 } 3126 3127 if (Outs[i].Flags.isByVal()) { 3128 SDValue SizeNode = 3129 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3130 SDValue Cpy = 3131 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3132 Outs[i].Flags.getNonZeroByValAlign(), 3133 /*isVol = */ false, /*AlwaysInline = */ true, 3134 /*isTailCall = */ false, DstInfo, 3135 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3136 3137 MemOpChains.push_back(Cpy); 3138 } else { 3139 SDValue Store = 3140 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3141 MemOpChains.push_back(Store); 3142 } 3143 } 3144 } 3145 3146 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 3147 CallConv != CallingConv::AMDGPU_Gfx) { 3148 // Copy special input registers after user input arguments. 3149 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3150 } 3151 3152 if (!MemOpChains.empty()) 3153 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3154 3155 // Build a sequence of copy-to-reg nodes chained together with token chain 3156 // and flag operands which copy the outgoing args into the appropriate regs. 3157 SDValue InFlag; 3158 for (auto &RegToPass : RegsToPass) { 3159 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3160 RegToPass.second, InFlag); 3161 InFlag = Chain.getValue(1); 3162 } 3163 3164 3165 SDValue PhysReturnAddrReg; 3166 if (IsTailCall) { 3167 // Since the return is being combined with the call, we need to pass on the 3168 // return address. 3169 3170 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3171 SDValue ReturnAddrReg = CreateLiveInRegister( 3172 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3173 3174 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3175 MVT::i64); 3176 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3177 InFlag = Chain.getValue(1); 3178 } 3179 3180 // We don't usually want to end the call-sequence here because we would tidy 3181 // the frame up *after* the call, however in the ABI-changing tail-call case 3182 // we've carefully laid out the parameters so that when sp is reset they'll be 3183 // in the correct location. 3184 if (IsTailCall && !IsSibCall) { 3185 Chain = DAG.getCALLSEQ_END(Chain, 3186 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3187 DAG.getTargetConstant(0, DL, MVT::i32), 3188 InFlag, DL); 3189 InFlag = Chain.getValue(1); 3190 } 3191 3192 std::vector<SDValue> Ops; 3193 Ops.push_back(Chain); 3194 Ops.push_back(Callee); 3195 // Add a redundant copy of the callee global which will not be legalized, as 3196 // we need direct access to the callee later. 3197 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3198 const GlobalValue *GV = GSD->getGlobal(); 3199 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3200 } else { 3201 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3202 } 3203 3204 if (IsTailCall) { 3205 // Each tail call may have to adjust the stack by a different amount, so 3206 // this information must travel along with the operation for eventual 3207 // consumption by emitEpilogue. 3208 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3209 3210 Ops.push_back(PhysReturnAddrReg); 3211 } 3212 3213 // Add argument registers to the end of the list so that they are known live 3214 // into the call. 3215 for (auto &RegToPass : RegsToPass) { 3216 Ops.push_back(DAG.getRegister(RegToPass.first, 3217 RegToPass.second.getValueType())); 3218 } 3219 3220 // Add a register mask operand representing the call-preserved registers. 3221 3222 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3223 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3224 assert(Mask && "Missing call preserved mask for calling convention"); 3225 Ops.push_back(DAG.getRegisterMask(Mask)); 3226 3227 if (InFlag.getNode()) 3228 Ops.push_back(InFlag); 3229 3230 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3231 3232 // If we're doing a tall call, use a TC_RETURN here rather than an 3233 // actual call instruction. 3234 if (IsTailCall) { 3235 MFI.setHasTailCall(); 3236 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3237 } 3238 3239 // Returns a chain and a flag for retval copy to use. 3240 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3241 Chain = Call.getValue(0); 3242 InFlag = Call.getValue(1); 3243 3244 uint64_t CalleePopBytes = NumBytes; 3245 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3246 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3247 InFlag, DL); 3248 if (!Ins.empty()) 3249 InFlag = Chain.getValue(1); 3250 3251 // Handle result values, copying them out of physregs into vregs that we 3252 // return. 3253 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3254 InVals, IsThisReturn, 3255 IsThisReturn ? OutVals[0] : SDValue()); 3256 } 3257 3258 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3259 // except for applying the wave size scale to the increment amount. 3260 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3261 SDValue Op, SelectionDAG &DAG) const { 3262 const MachineFunction &MF = DAG.getMachineFunction(); 3263 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3264 3265 SDLoc dl(Op); 3266 EVT VT = Op.getValueType(); 3267 SDValue Tmp1 = Op; 3268 SDValue Tmp2 = Op.getValue(1); 3269 SDValue Tmp3 = Op.getOperand(2); 3270 SDValue Chain = Tmp1.getOperand(0); 3271 3272 Register SPReg = Info->getStackPtrOffsetReg(); 3273 3274 // Chain the dynamic stack allocation so that it doesn't modify the stack 3275 // pointer when other instructions are using the stack. 3276 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3277 3278 SDValue Size = Tmp2.getOperand(1); 3279 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3280 Chain = SP.getValue(1); 3281 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3282 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3283 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3284 unsigned Opc = 3285 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3286 ISD::ADD : ISD::SUB; 3287 3288 SDValue ScaledSize = DAG.getNode( 3289 ISD::SHL, dl, VT, Size, 3290 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3291 3292 Align StackAlign = TFL->getStackAlign(); 3293 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3294 if (Alignment && *Alignment > StackAlign) { 3295 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3296 DAG.getConstant(-(uint64_t)Alignment->value() 3297 << ST.getWavefrontSizeLog2(), 3298 dl, VT)); 3299 } 3300 3301 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3302 Tmp2 = DAG.getCALLSEQ_END( 3303 Chain, DAG.getIntPtrConstant(0, dl, true), 3304 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3305 3306 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3307 } 3308 3309 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3310 SelectionDAG &DAG) const { 3311 // We only handle constant sizes here to allow non-entry block, static sized 3312 // allocas. A truly dynamic value is more difficult to support because we 3313 // don't know if the size value is uniform or not. If the size isn't uniform, 3314 // we would need to do a wave reduction to get the maximum size to know how 3315 // much to increment the uniform stack pointer. 3316 SDValue Size = Op.getOperand(1); 3317 if (isa<ConstantSDNode>(Size)) 3318 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3319 3320 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3321 } 3322 3323 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3324 const MachineFunction &MF) const { 3325 Register Reg = StringSwitch<Register>(RegName) 3326 .Case("m0", AMDGPU::M0) 3327 .Case("exec", AMDGPU::EXEC) 3328 .Case("exec_lo", AMDGPU::EXEC_LO) 3329 .Case("exec_hi", AMDGPU::EXEC_HI) 3330 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3331 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3332 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3333 .Default(Register()); 3334 3335 if (Reg == AMDGPU::NoRegister) { 3336 report_fatal_error(Twine("invalid register name \"" 3337 + StringRef(RegName) + "\".")); 3338 3339 } 3340 3341 if (!Subtarget->hasFlatScrRegister() && 3342 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3343 report_fatal_error(Twine("invalid register \"" 3344 + StringRef(RegName) + "\" for subtarget.")); 3345 } 3346 3347 switch (Reg) { 3348 case AMDGPU::M0: 3349 case AMDGPU::EXEC_LO: 3350 case AMDGPU::EXEC_HI: 3351 case AMDGPU::FLAT_SCR_LO: 3352 case AMDGPU::FLAT_SCR_HI: 3353 if (VT.getSizeInBits() == 32) 3354 return Reg; 3355 break; 3356 case AMDGPU::EXEC: 3357 case AMDGPU::FLAT_SCR: 3358 if (VT.getSizeInBits() == 64) 3359 return Reg; 3360 break; 3361 default: 3362 llvm_unreachable("missing register type checking"); 3363 } 3364 3365 report_fatal_error(Twine("invalid type for register \"" 3366 + StringRef(RegName) + "\".")); 3367 } 3368 3369 // If kill is not the last instruction, split the block so kill is always a 3370 // proper terminator. 3371 MachineBasicBlock * 3372 SITargetLowering::splitKillBlock(MachineInstr &MI, 3373 MachineBasicBlock *BB) const { 3374 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3375 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3376 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3377 return SplitBB; 3378 } 3379 3380 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3381 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3382 // be the first instruction in the remainder block. 3383 // 3384 /// \returns { LoopBody, Remainder } 3385 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3386 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3387 MachineFunction *MF = MBB.getParent(); 3388 MachineBasicBlock::iterator I(&MI); 3389 3390 // To insert the loop we need to split the block. Move everything after this 3391 // point to a new block, and insert a new empty block between the two. 3392 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3393 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3394 MachineFunction::iterator MBBI(MBB); 3395 ++MBBI; 3396 3397 MF->insert(MBBI, LoopBB); 3398 MF->insert(MBBI, RemainderBB); 3399 3400 LoopBB->addSuccessor(LoopBB); 3401 LoopBB->addSuccessor(RemainderBB); 3402 3403 // Move the rest of the block into a new block. 3404 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3405 3406 if (InstInLoop) { 3407 auto Next = std::next(I); 3408 3409 // Move instruction to loop body. 3410 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3411 3412 // Move the rest of the block. 3413 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3414 } else { 3415 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3416 } 3417 3418 MBB.addSuccessor(LoopBB); 3419 3420 return std::make_pair(LoopBB, RemainderBB); 3421 } 3422 3423 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3424 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3425 MachineBasicBlock *MBB = MI.getParent(); 3426 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3427 auto I = MI.getIterator(); 3428 auto E = std::next(I); 3429 3430 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3431 .addImm(0); 3432 3433 MIBundleBuilder Bundler(*MBB, I, E); 3434 finalizeBundle(*MBB, Bundler.begin()); 3435 } 3436 3437 MachineBasicBlock * 3438 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3439 MachineBasicBlock *BB) const { 3440 const DebugLoc &DL = MI.getDebugLoc(); 3441 3442 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3443 3444 MachineBasicBlock *LoopBB; 3445 MachineBasicBlock *RemainderBB; 3446 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3447 3448 // Apparently kill flags are only valid if the def is in the same block? 3449 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3450 Src->setIsKill(false); 3451 3452 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3453 3454 MachineBasicBlock::iterator I = LoopBB->end(); 3455 3456 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3457 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3458 3459 // Clear TRAP_STS.MEM_VIOL 3460 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3461 .addImm(0) 3462 .addImm(EncodedReg); 3463 3464 bundleInstWithWaitcnt(MI); 3465 3466 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3467 3468 // Load and check TRAP_STS.MEM_VIOL 3469 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3470 .addImm(EncodedReg); 3471 3472 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3473 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3474 .addReg(Reg, RegState::Kill) 3475 .addImm(0); 3476 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3477 .addMBB(LoopBB); 3478 3479 return RemainderBB; 3480 } 3481 3482 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3483 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3484 // will only do one iteration. In the worst case, this will loop 64 times. 3485 // 3486 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3487 static MachineBasicBlock::iterator 3488 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3489 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3490 const DebugLoc &DL, const MachineOperand &Idx, 3491 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3492 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3493 Register &SGPRIdxReg) { 3494 3495 MachineFunction *MF = OrigBB.getParent(); 3496 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3497 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3498 MachineBasicBlock::iterator I = LoopBB.begin(); 3499 3500 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3501 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3502 Register NewExec = MRI.createVirtualRegister(BoolRC); 3503 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3504 Register CondReg = MRI.createVirtualRegister(BoolRC); 3505 3506 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3507 .addReg(InitReg) 3508 .addMBB(&OrigBB) 3509 .addReg(ResultReg) 3510 .addMBB(&LoopBB); 3511 3512 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3513 .addReg(InitSaveExecReg) 3514 .addMBB(&OrigBB) 3515 .addReg(NewExec) 3516 .addMBB(&LoopBB); 3517 3518 // Read the next variant <- also loop target. 3519 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3520 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3521 3522 // Compare the just read M0 value to all possible Idx values. 3523 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3524 .addReg(CurrentIdxReg) 3525 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3526 3527 // Update EXEC, save the original EXEC value to VCC. 3528 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3529 : AMDGPU::S_AND_SAVEEXEC_B64), 3530 NewExec) 3531 .addReg(CondReg, RegState::Kill); 3532 3533 MRI.setSimpleHint(NewExec, CondReg); 3534 3535 if (UseGPRIdxMode) { 3536 if (Offset == 0) { 3537 SGPRIdxReg = CurrentIdxReg; 3538 } else { 3539 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3540 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3541 .addReg(CurrentIdxReg, RegState::Kill) 3542 .addImm(Offset); 3543 } 3544 } else { 3545 // Move index from VCC into M0 3546 if (Offset == 0) { 3547 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3548 .addReg(CurrentIdxReg, RegState::Kill); 3549 } else { 3550 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3551 .addReg(CurrentIdxReg, RegState::Kill) 3552 .addImm(Offset); 3553 } 3554 } 3555 3556 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3557 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3558 MachineInstr *InsertPt = 3559 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3560 : AMDGPU::S_XOR_B64_term), Exec) 3561 .addReg(Exec) 3562 .addReg(NewExec); 3563 3564 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3565 // s_cbranch_scc0? 3566 3567 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3568 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3569 .addMBB(&LoopBB); 3570 3571 return InsertPt->getIterator(); 3572 } 3573 3574 // This has slightly sub-optimal regalloc when the source vector is killed by 3575 // the read. The register allocator does not understand that the kill is 3576 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3577 // subregister from it, using 1 more VGPR than necessary. This was saved when 3578 // this was expanded after register allocation. 3579 static MachineBasicBlock::iterator 3580 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3581 unsigned InitResultReg, unsigned PhiReg, int Offset, 3582 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3583 MachineFunction *MF = MBB.getParent(); 3584 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3585 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3586 MachineRegisterInfo &MRI = MF->getRegInfo(); 3587 const DebugLoc &DL = MI.getDebugLoc(); 3588 MachineBasicBlock::iterator I(&MI); 3589 3590 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3591 Register DstReg = MI.getOperand(0).getReg(); 3592 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3593 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3594 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3595 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3596 3597 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3598 3599 // Save the EXEC mask 3600 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3601 .addReg(Exec); 3602 3603 MachineBasicBlock *LoopBB; 3604 MachineBasicBlock *RemainderBB; 3605 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3606 3607 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3608 3609 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3610 InitResultReg, DstReg, PhiReg, TmpExec, 3611 Offset, UseGPRIdxMode, SGPRIdxReg); 3612 3613 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3614 MachineFunction::iterator MBBI(LoopBB); 3615 ++MBBI; 3616 MF->insert(MBBI, LandingPad); 3617 LoopBB->removeSuccessor(RemainderBB); 3618 LandingPad->addSuccessor(RemainderBB); 3619 LoopBB->addSuccessor(LandingPad); 3620 MachineBasicBlock::iterator First = LandingPad->begin(); 3621 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3622 .addReg(SaveExec); 3623 3624 return InsPt; 3625 } 3626 3627 // Returns subreg index, offset 3628 static std::pair<unsigned, int> 3629 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3630 const TargetRegisterClass *SuperRC, 3631 unsigned VecReg, 3632 int Offset) { 3633 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3634 3635 // Skip out of bounds offsets, or else we would end up using an undefined 3636 // register. 3637 if (Offset >= NumElts || Offset < 0) 3638 return std::make_pair(AMDGPU::sub0, Offset); 3639 3640 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3641 } 3642 3643 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3644 MachineRegisterInfo &MRI, MachineInstr &MI, 3645 int Offset) { 3646 MachineBasicBlock *MBB = MI.getParent(); 3647 const DebugLoc &DL = MI.getDebugLoc(); 3648 MachineBasicBlock::iterator I(&MI); 3649 3650 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3651 3652 assert(Idx->getReg() != AMDGPU::NoRegister); 3653 3654 if (Offset == 0) { 3655 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3656 } else { 3657 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3658 .add(*Idx) 3659 .addImm(Offset); 3660 } 3661 } 3662 3663 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3664 MachineRegisterInfo &MRI, MachineInstr &MI, 3665 int Offset) { 3666 MachineBasicBlock *MBB = MI.getParent(); 3667 const DebugLoc &DL = MI.getDebugLoc(); 3668 MachineBasicBlock::iterator I(&MI); 3669 3670 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3671 3672 if (Offset == 0) 3673 return Idx->getReg(); 3674 3675 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3676 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3677 .add(*Idx) 3678 .addImm(Offset); 3679 return Tmp; 3680 } 3681 3682 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3683 MachineBasicBlock &MBB, 3684 const GCNSubtarget &ST) { 3685 const SIInstrInfo *TII = ST.getInstrInfo(); 3686 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3687 MachineFunction *MF = MBB.getParent(); 3688 MachineRegisterInfo &MRI = MF->getRegInfo(); 3689 3690 Register Dst = MI.getOperand(0).getReg(); 3691 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3692 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3693 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3694 3695 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3696 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3697 3698 unsigned SubReg; 3699 std::tie(SubReg, Offset) 3700 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3701 3702 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3703 3704 // Check for a SGPR index. 3705 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3706 MachineBasicBlock::iterator I(&MI); 3707 const DebugLoc &DL = MI.getDebugLoc(); 3708 3709 if (UseGPRIdxMode) { 3710 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3711 // to avoid interfering with other uses, so probably requires a new 3712 // optimization pass. 3713 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3714 3715 const MCInstrDesc &GPRIDXDesc = 3716 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3717 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3718 .addReg(SrcReg) 3719 .addReg(Idx) 3720 .addImm(SubReg); 3721 } else { 3722 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3723 3724 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3725 .addReg(SrcReg, 0, SubReg) 3726 .addReg(SrcReg, RegState::Implicit); 3727 } 3728 3729 MI.eraseFromParent(); 3730 3731 return &MBB; 3732 } 3733 3734 // Control flow needs to be inserted if indexing with a VGPR. 3735 const DebugLoc &DL = MI.getDebugLoc(); 3736 MachineBasicBlock::iterator I(&MI); 3737 3738 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3739 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3740 3741 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3742 3743 Register SGPRIdxReg; 3744 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3745 UseGPRIdxMode, SGPRIdxReg); 3746 3747 MachineBasicBlock *LoopBB = InsPt->getParent(); 3748 3749 if (UseGPRIdxMode) { 3750 const MCInstrDesc &GPRIDXDesc = 3751 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3752 3753 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3754 .addReg(SrcReg) 3755 .addReg(SGPRIdxReg) 3756 .addImm(SubReg); 3757 } else { 3758 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3759 .addReg(SrcReg, 0, SubReg) 3760 .addReg(SrcReg, RegState::Implicit); 3761 } 3762 3763 MI.eraseFromParent(); 3764 3765 return LoopBB; 3766 } 3767 3768 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3769 MachineBasicBlock &MBB, 3770 const GCNSubtarget &ST) { 3771 const SIInstrInfo *TII = ST.getInstrInfo(); 3772 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3773 MachineFunction *MF = MBB.getParent(); 3774 MachineRegisterInfo &MRI = MF->getRegInfo(); 3775 3776 Register Dst = MI.getOperand(0).getReg(); 3777 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3778 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3779 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3780 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3781 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3782 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3783 3784 // This can be an immediate, but will be folded later. 3785 assert(Val->getReg()); 3786 3787 unsigned SubReg; 3788 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3789 SrcVec->getReg(), 3790 Offset); 3791 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3792 3793 if (Idx->getReg() == AMDGPU::NoRegister) { 3794 MachineBasicBlock::iterator I(&MI); 3795 const DebugLoc &DL = MI.getDebugLoc(); 3796 3797 assert(Offset == 0); 3798 3799 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3800 .add(*SrcVec) 3801 .add(*Val) 3802 .addImm(SubReg); 3803 3804 MI.eraseFromParent(); 3805 return &MBB; 3806 } 3807 3808 // Check for a SGPR index. 3809 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3810 MachineBasicBlock::iterator I(&MI); 3811 const DebugLoc &DL = MI.getDebugLoc(); 3812 3813 if (UseGPRIdxMode) { 3814 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3815 3816 const MCInstrDesc &GPRIDXDesc = 3817 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3818 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3819 .addReg(SrcVec->getReg()) 3820 .add(*Val) 3821 .addReg(Idx) 3822 .addImm(SubReg); 3823 } else { 3824 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3825 3826 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3827 TRI.getRegSizeInBits(*VecRC), 32, false); 3828 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3829 .addReg(SrcVec->getReg()) 3830 .add(*Val) 3831 .addImm(SubReg); 3832 } 3833 MI.eraseFromParent(); 3834 return &MBB; 3835 } 3836 3837 // Control flow needs to be inserted if indexing with a VGPR. 3838 if (Val->isReg()) 3839 MRI.clearKillFlags(Val->getReg()); 3840 3841 const DebugLoc &DL = MI.getDebugLoc(); 3842 3843 Register PhiReg = MRI.createVirtualRegister(VecRC); 3844 3845 Register SGPRIdxReg; 3846 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3847 UseGPRIdxMode, SGPRIdxReg); 3848 MachineBasicBlock *LoopBB = InsPt->getParent(); 3849 3850 if (UseGPRIdxMode) { 3851 const MCInstrDesc &GPRIDXDesc = 3852 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3853 3854 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3855 .addReg(PhiReg) 3856 .add(*Val) 3857 .addReg(SGPRIdxReg) 3858 .addImm(AMDGPU::sub0); 3859 } else { 3860 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3861 TRI.getRegSizeInBits(*VecRC), 32, false); 3862 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3863 .addReg(PhiReg) 3864 .add(*Val) 3865 .addImm(AMDGPU::sub0); 3866 } 3867 3868 MI.eraseFromParent(); 3869 return LoopBB; 3870 } 3871 3872 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3873 MachineInstr &MI, MachineBasicBlock *BB) const { 3874 3875 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3876 MachineFunction *MF = BB->getParent(); 3877 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3878 3879 switch (MI.getOpcode()) { 3880 case AMDGPU::S_UADDO_PSEUDO: 3881 case AMDGPU::S_USUBO_PSEUDO: { 3882 const DebugLoc &DL = MI.getDebugLoc(); 3883 MachineOperand &Dest0 = MI.getOperand(0); 3884 MachineOperand &Dest1 = MI.getOperand(1); 3885 MachineOperand &Src0 = MI.getOperand(2); 3886 MachineOperand &Src1 = MI.getOperand(3); 3887 3888 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3889 ? AMDGPU::S_ADD_I32 3890 : AMDGPU::S_SUB_I32; 3891 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3892 3893 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3894 .addImm(1) 3895 .addImm(0); 3896 3897 MI.eraseFromParent(); 3898 return BB; 3899 } 3900 case AMDGPU::S_ADD_U64_PSEUDO: 3901 case AMDGPU::S_SUB_U64_PSEUDO: { 3902 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3903 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3904 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3905 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3906 const DebugLoc &DL = MI.getDebugLoc(); 3907 3908 MachineOperand &Dest = MI.getOperand(0); 3909 MachineOperand &Src0 = MI.getOperand(1); 3910 MachineOperand &Src1 = MI.getOperand(2); 3911 3912 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3913 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3914 3915 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3916 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3917 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3918 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3919 3920 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3921 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3922 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3923 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3924 3925 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3926 3927 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3928 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3929 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3930 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3931 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3932 .addReg(DestSub0) 3933 .addImm(AMDGPU::sub0) 3934 .addReg(DestSub1) 3935 .addImm(AMDGPU::sub1); 3936 MI.eraseFromParent(); 3937 return BB; 3938 } 3939 case AMDGPU::V_ADD_U64_PSEUDO: 3940 case AMDGPU::V_SUB_U64_PSEUDO: { 3941 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3942 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3943 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3944 const DebugLoc &DL = MI.getDebugLoc(); 3945 3946 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3947 3948 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3949 3950 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3951 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3952 3953 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3954 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3955 3956 MachineOperand &Dest = MI.getOperand(0); 3957 MachineOperand &Src0 = MI.getOperand(1); 3958 MachineOperand &Src1 = MI.getOperand(2); 3959 3960 const TargetRegisterClass *Src0RC = Src0.isReg() 3961 ? MRI.getRegClass(Src0.getReg()) 3962 : &AMDGPU::VReg_64RegClass; 3963 const TargetRegisterClass *Src1RC = Src1.isReg() 3964 ? MRI.getRegClass(Src1.getReg()) 3965 : &AMDGPU::VReg_64RegClass; 3966 3967 const TargetRegisterClass *Src0SubRC = 3968 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3969 const TargetRegisterClass *Src1SubRC = 3970 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3971 3972 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3973 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3974 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3975 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3976 3977 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3978 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3979 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3980 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3981 3982 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 3983 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3984 .addReg(CarryReg, RegState::Define) 3985 .add(SrcReg0Sub0) 3986 .add(SrcReg1Sub0) 3987 .addImm(0); // clamp bit 3988 3989 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3990 MachineInstr *HiHalf = 3991 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3992 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3993 .add(SrcReg0Sub1) 3994 .add(SrcReg1Sub1) 3995 .addReg(CarryReg, RegState::Kill) 3996 .addImm(0); // clamp bit 3997 3998 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3999 .addReg(DestSub0) 4000 .addImm(AMDGPU::sub0) 4001 .addReg(DestSub1) 4002 .addImm(AMDGPU::sub1); 4003 TII->legalizeOperands(*LoHalf); 4004 TII->legalizeOperands(*HiHalf); 4005 MI.eraseFromParent(); 4006 return BB; 4007 } 4008 case AMDGPU::S_ADD_CO_PSEUDO: 4009 case AMDGPU::S_SUB_CO_PSEUDO: { 4010 // This pseudo has a chance to be selected 4011 // only from uniform add/subcarry node. All the VGPR operands 4012 // therefore assumed to be splat vectors. 4013 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4014 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4015 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4016 MachineBasicBlock::iterator MII = MI; 4017 const DebugLoc &DL = MI.getDebugLoc(); 4018 MachineOperand &Dest = MI.getOperand(0); 4019 MachineOperand &CarryDest = MI.getOperand(1); 4020 MachineOperand &Src0 = MI.getOperand(2); 4021 MachineOperand &Src1 = MI.getOperand(3); 4022 MachineOperand &Src2 = MI.getOperand(4); 4023 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4024 ? AMDGPU::S_ADDC_U32 4025 : AMDGPU::S_SUBB_U32; 4026 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4027 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4028 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4029 .addReg(Src0.getReg()); 4030 Src0.setReg(RegOp0); 4031 } 4032 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4033 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4034 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4035 .addReg(Src1.getReg()); 4036 Src1.setReg(RegOp1); 4037 } 4038 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4039 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4040 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4041 .addReg(Src2.getReg()); 4042 Src2.setReg(RegOp2); 4043 } 4044 4045 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4046 if (TRI->getRegSizeInBits(*Src2RC) == 64) { 4047 if (ST.hasScalarCompareEq64()) { 4048 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4049 .addReg(Src2.getReg()) 4050 .addImm(0); 4051 } else { 4052 const TargetRegisterClass *SubRC = 4053 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4054 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4055 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4056 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4057 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4058 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4059 4060 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4061 .add(Src2Sub0) 4062 .add(Src2Sub1); 4063 4064 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4065 .addReg(Src2_32, RegState::Kill) 4066 .addImm(0); 4067 } 4068 } else { 4069 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4070 .addReg(Src2.getReg()) 4071 .addImm(0); 4072 } 4073 4074 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4075 4076 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 4077 .addReg(AMDGPU::SCC); 4078 MI.eraseFromParent(); 4079 return BB; 4080 } 4081 case AMDGPU::SI_INIT_M0: { 4082 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4083 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4084 .add(MI.getOperand(0)); 4085 MI.eraseFromParent(); 4086 return BB; 4087 } 4088 case AMDGPU::GET_GROUPSTATICSIZE: { 4089 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4090 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4091 DebugLoc DL = MI.getDebugLoc(); 4092 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4093 .add(MI.getOperand(0)) 4094 .addImm(MFI->getLDSSize()); 4095 MI.eraseFromParent(); 4096 return BB; 4097 } 4098 case AMDGPU::SI_INDIRECT_SRC_V1: 4099 case AMDGPU::SI_INDIRECT_SRC_V2: 4100 case AMDGPU::SI_INDIRECT_SRC_V4: 4101 case AMDGPU::SI_INDIRECT_SRC_V8: 4102 case AMDGPU::SI_INDIRECT_SRC_V16: 4103 case AMDGPU::SI_INDIRECT_SRC_V32: 4104 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4105 case AMDGPU::SI_INDIRECT_DST_V1: 4106 case AMDGPU::SI_INDIRECT_DST_V2: 4107 case AMDGPU::SI_INDIRECT_DST_V4: 4108 case AMDGPU::SI_INDIRECT_DST_V8: 4109 case AMDGPU::SI_INDIRECT_DST_V16: 4110 case AMDGPU::SI_INDIRECT_DST_V32: 4111 return emitIndirectDst(MI, *BB, *getSubtarget()); 4112 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4113 case AMDGPU::SI_KILL_I1_PSEUDO: 4114 return splitKillBlock(MI, BB); 4115 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4116 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4117 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4118 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4119 4120 Register Dst = MI.getOperand(0).getReg(); 4121 Register Src0 = MI.getOperand(1).getReg(); 4122 Register Src1 = MI.getOperand(2).getReg(); 4123 const DebugLoc &DL = MI.getDebugLoc(); 4124 Register SrcCond = MI.getOperand(3).getReg(); 4125 4126 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4127 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4128 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4129 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4130 4131 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4132 .addReg(SrcCond); 4133 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4134 .addImm(0) 4135 .addReg(Src0, 0, AMDGPU::sub0) 4136 .addImm(0) 4137 .addReg(Src1, 0, AMDGPU::sub0) 4138 .addReg(SrcCondCopy); 4139 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4140 .addImm(0) 4141 .addReg(Src0, 0, AMDGPU::sub1) 4142 .addImm(0) 4143 .addReg(Src1, 0, AMDGPU::sub1) 4144 .addReg(SrcCondCopy); 4145 4146 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4147 .addReg(DstLo) 4148 .addImm(AMDGPU::sub0) 4149 .addReg(DstHi) 4150 .addImm(AMDGPU::sub1); 4151 MI.eraseFromParent(); 4152 return BB; 4153 } 4154 case AMDGPU::SI_BR_UNDEF: { 4155 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4156 const DebugLoc &DL = MI.getDebugLoc(); 4157 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4158 .add(MI.getOperand(0)); 4159 Br->getOperand(1).setIsUndef(true); // read undef SCC 4160 MI.eraseFromParent(); 4161 return BB; 4162 } 4163 case AMDGPU::ADJCALLSTACKUP: 4164 case AMDGPU::ADJCALLSTACKDOWN: { 4165 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4166 MachineInstrBuilder MIB(*MF, &MI); 4167 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4168 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4169 return BB; 4170 } 4171 case AMDGPU::SI_CALL_ISEL: { 4172 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4173 const DebugLoc &DL = MI.getDebugLoc(); 4174 4175 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4176 4177 MachineInstrBuilder MIB; 4178 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4179 4180 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4181 MIB.add(MI.getOperand(I)); 4182 4183 MIB.cloneMemRefs(MI); 4184 MI.eraseFromParent(); 4185 return BB; 4186 } 4187 case AMDGPU::V_ADD_CO_U32_e32: 4188 case AMDGPU::V_SUB_CO_U32_e32: 4189 case AMDGPU::V_SUBREV_CO_U32_e32: { 4190 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4191 const DebugLoc &DL = MI.getDebugLoc(); 4192 unsigned Opc = MI.getOpcode(); 4193 4194 bool NeedClampOperand = false; 4195 if (TII->pseudoToMCOpcode(Opc) == -1) { 4196 Opc = AMDGPU::getVOPe64(Opc); 4197 NeedClampOperand = true; 4198 } 4199 4200 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4201 if (TII->isVOP3(*I)) { 4202 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4203 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4204 I.addReg(TRI->getVCC(), RegState::Define); 4205 } 4206 I.add(MI.getOperand(1)) 4207 .add(MI.getOperand(2)); 4208 if (NeedClampOperand) 4209 I.addImm(0); // clamp bit for e64 encoding 4210 4211 TII->legalizeOperands(*I); 4212 4213 MI.eraseFromParent(); 4214 return BB; 4215 } 4216 case AMDGPU::DS_GWS_INIT: 4217 case AMDGPU::DS_GWS_SEMA_V: 4218 case AMDGPU::DS_GWS_SEMA_BR: 4219 case AMDGPU::DS_GWS_SEMA_P: 4220 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4221 case AMDGPU::DS_GWS_BARRIER: 4222 // A s_waitcnt 0 is required to be the instruction immediately following. 4223 if (getSubtarget()->hasGWSAutoReplay()) { 4224 bundleInstWithWaitcnt(MI); 4225 return BB; 4226 } 4227 4228 return emitGWSMemViolTestLoop(MI, BB); 4229 case AMDGPU::S_SETREG_B32: { 4230 // Try to optimize cases that only set the denormal mode or rounding mode. 4231 // 4232 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4233 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4234 // instead. 4235 // 4236 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4237 // allow you to have a no side effect instruction in the output of a 4238 // sideeffecting pattern. 4239 unsigned ID, Offset, Width; 4240 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4241 if (ID != AMDGPU::Hwreg::ID_MODE) 4242 return BB; 4243 4244 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4245 const unsigned SetMask = WidthMask << Offset; 4246 4247 if (getSubtarget()->hasDenormModeInst()) { 4248 unsigned SetDenormOp = 0; 4249 unsigned SetRoundOp = 0; 4250 4251 // The dedicated instructions can only set the whole denorm or round mode 4252 // at once, not a subset of bits in either. 4253 if (SetMask == 4254 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4255 // If this fully sets both the round and denorm mode, emit the two 4256 // dedicated instructions for these. 4257 SetRoundOp = AMDGPU::S_ROUND_MODE; 4258 SetDenormOp = AMDGPU::S_DENORM_MODE; 4259 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4260 SetRoundOp = AMDGPU::S_ROUND_MODE; 4261 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4262 SetDenormOp = AMDGPU::S_DENORM_MODE; 4263 } 4264 4265 if (SetRoundOp || SetDenormOp) { 4266 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4267 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4268 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4269 unsigned ImmVal = Def->getOperand(1).getImm(); 4270 if (SetRoundOp) { 4271 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4272 .addImm(ImmVal & 0xf); 4273 4274 // If we also have the denorm mode, get just the denorm mode bits. 4275 ImmVal >>= 4; 4276 } 4277 4278 if (SetDenormOp) { 4279 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4280 .addImm(ImmVal & 0xf); 4281 } 4282 4283 MI.eraseFromParent(); 4284 return BB; 4285 } 4286 } 4287 } 4288 4289 // If only FP bits are touched, used the no side effects pseudo. 4290 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4291 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4292 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4293 4294 return BB; 4295 } 4296 default: 4297 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4298 } 4299 } 4300 4301 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4302 return isTypeLegal(VT.getScalarType()); 4303 } 4304 4305 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4306 // This currently forces unfolding various combinations of fsub into fma with 4307 // free fneg'd operands. As long as we have fast FMA (controlled by 4308 // isFMAFasterThanFMulAndFAdd), we should perform these. 4309 4310 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4311 // most of these combines appear to be cycle neutral but save on instruction 4312 // count / code size. 4313 return true; 4314 } 4315 4316 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4317 EVT VT) const { 4318 if (!VT.isVector()) { 4319 return MVT::i1; 4320 } 4321 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4322 } 4323 4324 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4325 // TODO: Should i16 be used always if legal? For now it would force VALU 4326 // shifts. 4327 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4328 } 4329 4330 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4331 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4332 ? Ty.changeElementSize(16) 4333 : Ty.changeElementSize(32); 4334 } 4335 4336 // Answering this is somewhat tricky and depends on the specific device which 4337 // have different rates for fma or all f64 operations. 4338 // 4339 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4340 // regardless of which device (although the number of cycles differs between 4341 // devices), so it is always profitable for f64. 4342 // 4343 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4344 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4345 // which we can always do even without fused FP ops since it returns the same 4346 // result as the separate operations and since it is always full 4347 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4348 // however does not support denormals, so we do report fma as faster if we have 4349 // a fast fma device and require denormals. 4350 // 4351 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4352 EVT VT) const { 4353 VT = VT.getScalarType(); 4354 4355 switch (VT.getSimpleVT().SimpleTy) { 4356 case MVT::f32: { 4357 // If mad is not available this depends only on if f32 fma is full rate. 4358 if (!Subtarget->hasMadMacF32Insts()) 4359 return Subtarget->hasFastFMAF32(); 4360 4361 // Otherwise f32 mad is always full rate and returns the same result as 4362 // the separate operations so should be preferred over fma. 4363 // However does not support denomals. 4364 if (hasFP32Denormals(MF)) 4365 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4366 4367 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4368 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4369 } 4370 case MVT::f64: 4371 return true; 4372 case MVT::f16: 4373 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4374 default: 4375 break; 4376 } 4377 4378 return false; 4379 } 4380 4381 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4382 const SDNode *N) const { 4383 // TODO: Check future ftz flag 4384 // v_mad_f32/v_mac_f32 do not support denormals. 4385 EVT VT = N->getValueType(0); 4386 if (VT == MVT::f32) 4387 return Subtarget->hasMadMacF32Insts() && 4388 !hasFP32Denormals(DAG.getMachineFunction()); 4389 if (VT == MVT::f16) { 4390 return Subtarget->hasMadF16() && 4391 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4392 } 4393 4394 return false; 4395 } 4396 4397 //===----------------------------------------------------------------------===// 4398 // Custom DAG Lowering Operations 4399 //===----------------------------------------------------------------------===// 4400 4401 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4402 // wider vector type is legal. 4403 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4404 SelectionDAG &DAG) const { 4405 unsigned Opc = Op.getOpcode(); 4406 EVT VT = Op.getValueType(); 4407 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4408 4409 SDValue Lo, Hi; 4410 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4411 4412 SDLoc SL(Op); 4413 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4414 Op->getFlags()); 4415 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4416 Op->getFlags()); 4417 4418 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4419 } 4420 4421 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4422 // wider vector type is legal. 4423 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4424 SelectionDAG &DAG) const { 4425 unsigned Opc = Op.getOpcode(); 4426 EVT VT = Op.getValueType(); 4427 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4428 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4429 4430 SDValue Lo0, Hi0; 4431 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4432 SDValue Lo1, Hi1; 4433 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4434 4435 SDLoc SL(Op); 4436 4437 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4438 Op->getFlags()); 4439 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4440 Op->getFlags()); 4441 4442 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4443 } 4444 4445 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4446 SelectionDAG &DAG) const { 4447 unsigned Opc = Op.getOpcode(); 4448 EVT VT = Op.getValueType(); 4449 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4450 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4451 4452 SDValue Lo0, Hi0; 4453 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4454 SDValue Lo1, Hi1; 4455 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4456 SDValue Lo2, Hi2; 4457 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4458 4459 SDLoc SL(Op); 4460 4461 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4462 Op->getFlags()); 4463 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4464 Op->getFlags()); 4465 4466 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4467 } 4468 4469 4470 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4471 switch (Op.getOpcode()) { 4472 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4473 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4474 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4475 case ISD::LOAD: { 4476 SDValue Result = LowerLOAD(Op, DAG); 4477 assert((!Result.getNode() || 4478 Result.getNode()->getNumValues() == 2) && 4479 "Load should return a value and a chain"); 4480 return Result; 4481 } 4482 4483 case ISD::FSIN: 4484 case ISD::FCOS: 4485 return LowerTrig(Op, DAG); 4486 case ISD::SELECT: return LowerSELECT(Op, DAG); 4487 case ISD::FDIV: return LowerFDIV(Op, DAG); 4488 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4489 case ISD::STORE: return LowerSTORE(Op, DAG); 4490 case ISD::GlobalAddress: { 4491 MachineFunction &MF = DAG.getMachineFunction(); 4492 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4493 return LowerGlobalAddress(MFI, Op, DAG); 4494 } 4495 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4496 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4497 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4498 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4499 case ISD::INSERT_SUBVECTOR: 4500 return lowerINSERT_SUBVECTOR(Op, DAG); 4501 case ISD::INSERT_VECTOR_ELT: 4502 return lowerINSERT_VECTOR_ELT(Op, DAG); 4503 case ISD::EXTRACT_VECTOR_ELT: 4504 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4505 case ISD::VECTOR_SHUFFLE: 4506 return lowerVECTOR_SHUFFLE(Op, DAG); 4507 case ISD::BUILD_VECTOR: 4508 return lowerBUILD_VECTOR(Op, DAG); 4509 case ISD::FP_ROUND: 4510 return lowerFP_ROUND(Op, DAG); 4511 case ISD::TRAP: 4512 return lowerTRAP(Op, DAG); 4513 case ISD::DEBUGTRAP: 4514 return lowerDEBUGTRAP(Op, DAG); 4515 case ISD::FABS: 4516 case ISD::FNEG: 4517 case ISD::FCANONICALIZE: 4518 case ISD::BSWAP: 4519 return splitUnaryVectorOp(Op, DAG); 4520 case ISD::FMINNUM: 4521 case ISD::FMAXNUM: 4522 return lowerFMINNUM_FMAXNUM(Op, DAG); 4523 case ISD::FMA: 4524 return splitTernaryVectorOp(Op, DAG); 4525 case ISD::SHL: 4526 case ISD::SRA: 4527 case ISD::SRL: 4528 case ISD::ADD: 4529 case ISD::SUB: 4530 case ISD::MUL: 4531 case ISD::SMIN: 4532 case ISD::SMAX: 4533 case ISD::UMIN: 4534 case ISD::UMAX: 4535 case ISD::FADD: 4536 case ISD::FMUL: 4537 case ISD::FMINNUM_IEEE: 4538 case ISD::FMAXNUM_IEEE: 4539 case ISD::UADDSAT: 4540 case ISD::USUBSAT: 4541 case ISD::SADDSAT: 4542 case ISD::SSUBSAT: 4543 return splitBinaryVectorOp(Op, DAG); 4544 case ISD::SMULO: 4545 case ISD::UMULO: 4546 return lowerXMULO(Op, DAG); 4547 case ISD::DYNAMIC_STACKALLOC: 4548 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4549 } 4550 return SDValue(); 4551 } 4552 4553 // Used for D16: Casts the result of an instruction into the right vector, 4554 // packs values if loads return unpacked values. 4555 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4556 const SDLoc &DL, 4557 SelectionDAG &DAG, bool Unpacked) { 4558 if (!LoadVT.isVector()) 4559 return Result; 4560 4561 // Cast back to the original packed type or to a larger type that is a 4562 // multiple of 32 bit for D16. Widening the return type is a required for 4563 // legalization. 4564 EVT FittingLoadVT = LoadVT; 4565 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4566 FittingLoadVT = 4567 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4568 LoadVT.getVectorNumElements() + 1); 4569 } 4570 4571 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4572 // Truncate to v2i16/v4i16. 4573 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4574 4575 // Workaround legalizer not scalarizing truncate after vector op 4576 // legalization but not creating intermediate vector trunc. 4577 SmallVector<SDValue, 4> Elts; 4578 DAG.ExtractVectorElements(Result, Elts); 4579 for (SDValue &Elt : Elts) 4580 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4581 4582 // Pad illegal v1i16/v3fi6 to v4i16 4583 if ((LoadVT.getVectorNumElements() % 2) == 1) 4584 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4585 4586 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4587 4588 // Bitcast to original type (v2f16/v4f16). 4589 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4590 } 4591 4592 // Cast back to the original packed type. 4593 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4594 } 4595 4596 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4597 MemSDNode *M, 4598 SelectionDAG &DAG, 4599 ArrayRef<SDValue> Ops, 4600 bool IsIntrinsic) const { 4601 SDLoc DL(M); 4602 4603 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4604 EVT LoadVT = M->getValueType(0); 4605 4606 EVT EquivLoadVT = LoadVT; 4607 if (LoadVT.isVector()) { 4608 if (Unpacked) { 4609 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4610 LoadVT.getVectorNumElements()); 4611 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4612 // Widen v3f16 to legal type 4613 EquivLoadVT = 4614 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4615 LoadVT.getVectorNumElements() + 1); 4616 } 4617 } 4618 4619 // Change from v4f16/v2f16 to EquivLoadVT. 4620 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4621 4622 SDValue Load 4623 = DAG.getMemIntrinsicNode( 4624 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4625 VTList, Ops, M->getMemoryVT(), 4626 M->getMemOperand()); 4627 4628 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4629 4630 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4631 } 4632 4633 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4634 SelectionDAG &DAG, 4635 ArrayRef<SDValue> Ops) const { 4636 SDLoc DL(M); 4637 EVT LoadVT = M->getValueType(0); 4638 EVT EltType = LoadVT.getScalarType(); 4639 EVT IntVT = LoadVT.changeTypeToInteger(); 4640 4641 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4642 4643 unsigned Opc = 4644 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4645 4646 if (IsD16) { 4647 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4648 } 4649 4650 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4651 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4652 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4653 4654 if (isTypeLegal(LoadVT)) { 4655 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4656 M->getMemOperand(), DAG); 4657 } 4658 4659 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4660 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4661 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4662 M->getMemOperand(), DAG); 4663 return DAG.getMergeValues( 4664 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4665 DL); 4666 } 4667 4668 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4669 SDNode *N, SelectionDAG &DAG) { 4670 EVT VT = N->getValueType(0); 4671 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4672 unsigned CondCode = CD->getZExtValue(); 4673 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4674 return DAG.getUNDEF(VT); 4675 4676 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4677 4678 SDValue LHS = N->getOperand(1); 4679 SDValue RHS = N->getOperand(2); 4680 4681 SDLoc DL(N); 4682 4683 EVT CmpVT = LHS.getValueType(); 4684 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4685 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4686 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4687 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4688 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4689 } 4690 4691 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4692 4693 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4694 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4695 4696 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4697 DAG.getCondCode(CCOpcode)); 4698 if (VT.bitsEq(CCVT)) 4699 return SetCC; 4700 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4701 } 4702 4703 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4704 SDNode *N, SelectionDAG &DAG) { 4705 EVT VT = N->getValueType(0); 4706 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4707 4708 unsigned CondCode = CD->getZExtValue(); 4709 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4710 return DAG.getUNDEF(VT); 4711 4712 SDValue Src0 = N->getOperand(1); 4713 SDValue Src1 = N->getOperand(2); 4714 EVT CmpVT = Src0.getValueType(); 4715 SDLoc SL(N); 4716 4717 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4718 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4719 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4720 } 4721 4722 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4723 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4724 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4725 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4726 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4727 Src1, DAG.getCondCode(CCOpcode)); 4728 if (VT.bitsEq(CCVT)) 4729 return SetCC; 4730 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4731 } 4732 4733 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4734 SelectionDAG &DAG) { 4735 EVT VT = N->getValueType(0); 4736 SDValue Src = N->getOperand(1); 4737 SDLoc SL(N); 4738 4739 if (Src.getOpcode() == ISD::SETCC) { 4740 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4741 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4742 Src.getOperand(1), Src.getOperand(2)); 4743 } 4744 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4745 // (ballot 0) -> 0 4746 if (Arg->isNullValue()) 4747 return DAG.getConstant(0, SL, VT); 4748 4749 // (ballot 1) -> EXEC/EXEC_LO 4750 if (Arg->isOne()) { 4751 Register Exec; 4752 if (VT.getScalarSizeInBits() == 32) 4753 Exec = AMDGPU::EXEC_LO; 4754 else if (VT.getScalarSizeInBits() == 64) 4755 Exec = AMDGPU::EXEC; 4756 else 4757 return SDValue(); 4758 4759 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4760 } 4761 } 4762 4763 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4764 // ISD::SETNE) 4765 return DAG.getNode( 4766 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4767 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4768 } 4769 4770 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4771 SmallVectorImpl<SDValue> &Results, 4772 SelectionDAG &DAG) const { 4773 switch (N->getOpcode()) { 4774 case ISD::INSERT_VECTOR_ELT: { 4775 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4776 Results.push_back(Res); 4777 return; 4778 } 4779 case ISD::EXTRACT_VECTOR_ELT: { 4780 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4781 Results.push_back(Res); 4782 return; 4783 } 4784 case ISD::INTRINSIC_WO_CHAIN: { 4785 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4786 switch (IID) { 4787 case Intrinsic::amdgcn_cvt_pkrtz: { 4788 SDValue Src0 = N->getOperand(1); 4789 SDValue Src1 = N->getOperand(2); 4790 SDLoc SL(N); 4791 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4792 Src0, Src1); 4793 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4794 return; 4795 } 4796 case Intrinsic::amdgcn_cvt_pknorm_i16: 4797 case Intrinsic::amdgcn_cvt_pknorm_u16: 4798 case Intrinsic::amdgcn_cvt_pk_i16: 4799 case Intrinsic::amdgcn_cvt_pk_u16: { 4800 SDValue Src0 = N->getOperand(1); 4801 SDValue Src1 = N->getOperand(2); 4802 SDLoc SL(N); 4803 unsigned Opcode; 4804 4805 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4806 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4807 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4808 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4809 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4810 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4811 else 4812 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4813 4814 EVT VT = N->getValueType(0); 4815 if (isTypeLegal(VT)) 4816 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4817 else { 4818 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4819 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4820 } 4821 return; 4822 } 4823 } 4824 break; 4825 } 4826 case ISD::INTRINSIC_W_CHAIN: { 4827 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4828 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4829 // FIXME: Hacky 4830 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4831 Results.push_back(Res.getOperand(I)); 4832 } 4833 } else { 4834 Results.push_back(Res); 4835 Results.push_back(Res.getValue(1)); 4836 } 4837 return; 4838 } 4839 4840 break; 4841 } 4842 case ISD::SELECT: { 4843 SDLoc SL(N); 4844 EVT VT = N->getValueType(0); 4845 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4846 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4847 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4848 4849 EVT SelectVT = NewVT; 4850 if (NewVT.bitsLT(MVT::i32)) { 4851 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4852 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4853 SelectVT = MVT::i32; 4854 } 4855 4856 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4857 N->getOperand(0), LHS, RHS); 4858 4859 if (NewVT != SelectVT) 4860 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4861 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4862 return; 4863 } 4864 case ISD::FNEG: { 4865 if (N->getValueType(0) != MVT::v2f16) 4866 break; 4867 4868 SDLoc SL(N); 4869 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4870 4871 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4872 BC, 4873 DAG.getConstant(0x80008000, SL, MVT::i32)); 4874 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4875 return; 4876 } 4877 case ISD::FABS: { 4878 if (N->getValueType(0) != MVT::v2f16) 4879 break; 4880 4881 SDLoc SL(N); 4882 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4883 4884 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4885 BC, 4886 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4887 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4888 return; 4889 } 4890 default: 4891 break; 4892 } 4893 } 4894 4895 /// Helper function for LowerBRCOND 4896 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4897 4898 SDNode *Parent = Value.getNode(); 4899 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4900 I != E; ++I) { 4901 4902 if (I.getUse().get() != Value) 4903 continue; 4904 4905 if (I->getOpcode() == Opcode) 4906 return *I; 4907 } 4908 return nullptr; 4909 } 4910 4911 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4912 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4913 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4914 case Intrinsic::amdgcn_if: 4915 return AMDGPUISD::IF; 4916 case Intrinsic::amdgcn_else: 4917 return AMDGPUISD::ELSE; 4918 case Intrinsic::amdgcn_loop: 4919 return AMDGPUISD::LOOP; 4920 case Intrinsic::amdgcn_end_cf: 4921 llvm_unreachable("should not occur"); 4922 default: 4923 return 0; 4924 } 4925 } 4926 4927 // break, if_break, else_break are all only used as inputs to loop, not 4928 // directly as branch conditions. 4929 return 0; 4930 } 4931 4932 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4933 const Triple &TT = getTargetMachine().getTargetTriple(); 4934 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4935 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4936 AMDGPU::shouldEmitConstantsToTextSection(TT); 4937 } 4938 4939 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4940 // FIXME: Either avoid relying on address space here or change the default 4941 // address space for functions to avoid the explicit check. 4942 return (GV->getValueType()->isFunctionTy() || 4943 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4944 !shouldEmitFixup(GV) && 4945 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4946 } 4947 4948 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4949 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4950 } 4951 4952 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4953 if (!GV->hasExternalLinkage()) 4954 return true; 4955 4956 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4957 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4958 } 4959 4960 /// This transforms the control flow intrinsics to get the branch destination as 4961 /// last parameter, also switches branch target with BR if the need arise 4962 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4963 SelectionDAG &DAG) const { 4964 SDLoc DL(BRCOND); 4965 4966 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4967 SDValue Target = BRCOND.getOperand(2); 4968 SDNode *BR = nullptr; 4969 SDNode *SetCC = nullptr; 4970 4971 if (Intr->getOpcode() == ISD::SETCC) { 4972 // As long as we negate the condition everything is fine 4973 SetCC = Intr; 4974 Intr = SetCC->getOperand(0).getNode(); 4975 4976 } else { 4977 // Get the target from BR if we don't negate the condition 4978 BR = findUser(BRCOND, ISD::BR); 4979 assert(BR && "brcond missing unconditional branch user"); 4980 Target = BR->getOperand(1); 4981 } 4982 4983 unsigned CFNode = isCFIntrinsic(Intr); 4984 if (CFNode == 0) { 4985 // This is a uniform branch so we don't need to legalize. 4986 return BRCOND; 4987 } 4988 4989 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4990 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4991 4992 assert(!SetCC || 4993 (SetCC->getConstantOperandVal(1) == 1 && 4994 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4995 ISD::SETNE)); 4996 4997 // operands of the new intrinsic call 4998 SmallVector<SDValue, 4> Ops; 4999 if (HaveChain) 5000 Ops.push_back(BRCOND.getOperand(0)); 5001 5002 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5003 Ops.push_back(Target); 5004 5005 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5006 5007 // build the new intrinsic call 5008 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5009 5010 if (!HaveChain) { 5011 SDValue Ops[] = { 5012 SDValue(Result, 0), 5013 BRCOND.getOperand(0) 5014 }; 5015 5016 Result = DAG.getMergeValues(Ops, DL).getNode(); 5017 } 5018 5019 if (BR) { 5020 // Give the branch instruction our target 5021 SDValue Ops[] = { 5022 BR->getOperand(0), 5023 BRCOND.getOperand(2) 5024 }; 5025 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5026 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5027 } 5028 5029 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5030 5031 // Copy the intrinsic results to registers 5032 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5033 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5034 if (!CopyToReg) 5035 continue; 5036 5037 Chain = DAG.getCopyToReg( 5038 Chain, DL, 5039 CopyToReg->getOperand(1), 5040 SDValue(Result, i - 1), 5041 SDValue()); 5042 5043 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5044 } 5045 5046 // Remove the old intrinsic from the chain 5047 DAG.ReplaceAllUsesOfValueWith( 5048 SDValue(Intr, Intr->getNumValues() - 1), 5049 Intr->getOperand(0)); 5050 5051 return Chain; 5052 } 5053 5054 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5055 SelectionDAG &DAG) const { 5056 MVT VT = Op.getSimpleValueType(); 5057 SDLoc DL(Op); 5058 // Checking the depth 5059 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5060 return DAG.getConstant(0, DL, VT); 5061 5062 MachineFunction &MF = DAG.getMachineFunction(); 5063 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5064 // Check for kernel and shader functions 5065 if (Info->isEntryFunction()) 5066 return DAG.getConstant(0, DL, VT); 5067 5068 MachineFrameInfo &MFI = MF.getFrameInfo(); 5069 // There is a call to @llvm.returnaddress in this function 5070 MFI.setReturnAddressIsTaken(true); 5071 5072 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5073 // Get the return address reg and mark it as an implicit live-in 5074 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5075 5076 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5077 } 5078 5079 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5080 SDValue Op, 5081 const SDLoc &DL, 5082 EVT VT) const { 5083 return Op.getValueType().bitsLE(VT) ? 5084 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5085 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5086 DAG.getTargetConstant(0, DL, MVT::i32)); 5087 } 5088 5089 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5090 assert(Op.getValueType() == MVT::f16 && 5091 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5092 5093 SDValue Src = Op.getOperand(0); 5094 EVT SrcVT = Src.getValueType(); 5095 if (SrcVT != MVT::f64) 5096 return Op; 5097 5098 SDLoc DL(Op); 5099 5100 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5101 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5102 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5103 } 5104 5105 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5106 SelectionDAG &DAG) const { 5107 EVT VT = Op.getValueType(); 5108 const MachineFunction &MF = DAG.getMachineFunction(); 5109 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5110 bool IsIEEEMode = Info->getMode().IEEE; 5111 5112 // FIXME: Assert during selection that this is only selected for 5113 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5114 // mode functions, but this happens to be OK since it's only done in cases 5115 // where there is known no sNaN. 5116 if (IsIEEEMode) 5117 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5118 5119 if (VT == MVT::v4f16) 5120 return splitBinaryVectorOp(Op, DAG); 5121 return Op; 5122 } 5123 5124 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5125 EVT VT = Op.getValueType(); 5126 SDLoc SL(Op); 5127 SDValue LHS = Op.getOperand(0); 5128 SDValue RHS = Op.getOperand(1); 5129 bool isSigned = Op.getOpcode() == ISD::SMULO; 5130 5131 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5132 const APInt &C = RHSC->getAPIntValue(); 5133 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5134 if (C.isPowerOf2()) { 5135 // smulo(x, signed_min) is same as umulo(x, signed_min). 5136 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5137 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5138 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5139 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5140 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5141 SL, VT, Result, ShiftAmt), 5142 LHS, ISD::SETNE); 5143 return DAG.getMergeValues({ Result, Overflow }, SL); 5144 } 5145 } 5146 5147 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5148 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5149 SL, VT, LHS, RHS); 5150 5151 SDValue Sign = isSigned 5152 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5153 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5154 : DAG.getConstant(0, SL, VT); 5155 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5156 5157 return DAG.getMergeValues({ Result, Overflow }, SL); 5158 } 5159 5160 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5161 if (!Subtarget->isTrapHandlerEnabled() || 5162 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5163 return lowerTrapEndpgm(Op, DAG); 5164 5165 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5166 switch (*HsaAbiVer) { 5167 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5168 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5169 return lowerTrapHsaQueuePtr(Op, DAG); 5170 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5171 return Subtarget->supportsGetDoorbellID() ? 5172 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5173 } 5174 } 5175 5176 llvm_unreachable("Unknown trap handler"); 5177 } 5178 5179 SDValue SITargetLowering::lowerTrapEndpgm( 5180 SDValue Op, SelectionDAG &DAG) const { 5181 SDLoc SL(Op); 5182 SDValue Chain = Op.getOperand(0); 5183 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5184 } 5185 5186 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5187 SDValue Op, SelectionDAG &DAG) const { 5188 SDLoc SL(Op); 5189 SDValue Chain = Op.getOperand(0); 5190 5191 MachineFunction &MF = DAG.getMachineFunction(); 5192 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5193 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5194 assert(UserSGPR != AMDGPU::NoRegister); 5195 SDValue QueuePtr = CreateLiveInRegister( 5196 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5197 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5198 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5199 QueuePtr, SDValue()); 5200 5201 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5202 SDValue Ops[] = { 5203 ToReg, 5204 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5205 SGPR01, 5206 ToReg.getValue(1) 5207 }; 5208 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5209 } 5210 5211 SDValue SITargetLowering::lowerTrapHsa( 5212 SDValue Op, SelectionDAG &DAG) const { 5213 SDLoc SL(Op); 5214 SDValue Chain = Op.getOperand(0); 5215 5216 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5217 SDValue Ops[] = { 5218 Chain, 5219 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5220 }; 5221 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5222 } 5223 5224 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5225 SDLoc SL(Op); 5226 SDValue Chain = Op.getOperand(0); 5227 MachineFunction &MF = DAG.getMachineFunction(); 5228 5229 if (!Subtarget->isTrapHandlerEnabled() || 5230 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5231 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5232 "debugtrap handler not supported", 5233 Op.getDebugLoc(), 5234 DS_Warning); 5235 LLVMContext &Ctx = MF.getFunction().getContext(); 5236 Ctx.diagnose(NoTrap); 5237 return Chain; 5238 } 5239 5240 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5241 SDValue Ops[] = { 5242 Chain, 5243 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5244 }; 5245 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5246 } 5247 5248 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5249 SelectionDAG &DAG) const { 5250 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5251 if (Subtarget->hasApertureRegs()) { 5252 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5253 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5254 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5255 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5256 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5257 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5258 unsigned Encoding = 5259 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5260 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5261 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5262 5263 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5264 SDValue ApertureReg = SDValue( 5265 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5266 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5267 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5268 } 5269 5270 MachineFunction &MF = DAG.getMachineFunction(); 5271 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5272 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5273 assert(UserSGPR != AMDGPU::NoRegister); 5274 5275 SDValue QueuePtr = CreateLiveInRegister( 5276 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5277 5278 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5279 // private_segment_aperture_base_hi. 5280 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5281 5282 SDValue Ptr = 5283 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5284 5285 // TODO: Use custom target PseudoSourceValue. 5286 // TODO: We should use the value from the IR intrinsic call, but it might not 5287 // be available and how do we get it? 5288 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5289 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5290 commonAlignment(Align(64), StructOffset), 5291 MachineMemOperand::MODereferenceable | 5292 MachineMemOperand::MOInvariant); 5293 } 5294 5295 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5296 SelectionDAG &DAG) const { 5297 SDLoc SL(Op); 5298 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5299 5300 SDValue Src = ASC->getOperand(0); 5301 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5302 5303 const AMDGPUTargetMachine &TM = 5304 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5305 5306 // flat -> local/private 5307 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5308 unsigned DestAS = ASC->getDestAddressSpace(); 5309 5310 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5311 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5312 unsigned NullVal = TM.getNullPointerValue(DestAS); 5313 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5314 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5315 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5316 5317 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5318 NonNull, Ptr, SegmentNullPtr); 5319 } 5320 } 5321 5322 // local/private -> flat 5323 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5324 unsigned SrcAS = ASC->getSrcAddressSpace(); 5325 5326 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5327 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5328 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5329 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5330 5331 SDValue NonNull 5332 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5333 5334 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5335 SDValue CvtPtr 5336 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5337 5338 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5339 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5340 FlatNullPtr); 5341 } 5342 } 5343 5344 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5345 Src.getValueType() == MVT::i64) 5346 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5347 5348 // global <-> flat are no-ops and never emitted. 5349 5350 const MachineFunction &MF = DAG.getMachineFunction(); 5351 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5352 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5353 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5354 5355 return DAG.getUNDEF(ASC->getValueType(0)); 5356 } 5357 5358 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5359 // the small vector and inserting them into the big vector. That is better than 5360 // the default expansion of doing it via a stack slot. Even though the use of 5361 // the stack slot would be optimized away afterwards, the stack slot itself 5362 // remains. 5363 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5364 SelectionDAG &DAG) const { 5365 SDValue Vec = Op.getOperand(0); 5366 SDValue Ins = Op.getOperand(1); 5367 SDValue Idx = Op.getOperand(2); 5368 EVT VecVT = Vec.getValueType(); 5369 EVT InsVT = Ins.getValueType(); 5370 EVT EltVT = VecVT.getVectorElementType(); 5371 unsigned InsNumElts = InsVT.getVectorNumElements(); 5372 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5373 SDLoc SL(Op); 5374 5375 for (unsigned I = 0; I != InsNumElts; ++I) { 5376 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5377 DAG.getConstant(I, SL, MVT::i32)); 5378 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5379 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5380 } 5381 return Vec; 5382 } 5383 5384 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5385 SelectionDAG &DAG) const { 5386 SDValue Vec = Op.getOperand(0); 5387 SDValue InsVal = Op.getOperand(1); 5388 SDValue Idx = Op.getOperand(2); 5389 EVT VecVT = Vec.getValueType(); 5390 EVT EltVT = VecVT.getVectorElementType(); 5391 unsigned VecSize = VecVT.getSizeInBits(); 5392 unsigned EltSize = EltVT.getSizeInBits(); 5393 5394 5395 assert(VecSize <= 64); 5396 5397 unsigned NumElts = VecVT.getVectorNumElements(); 5398 SDLoc SL(Op); 5399 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5400 5401 if (NumElts == 4 && EltSize == 16 && KIdx) { 5402 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5403 5404 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5405 DAG.getConstant(0, SL, MVT::i32)); 5406 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5407 DAG.getConstant(1, SL, MVT::i32)); 5408 5409 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5410 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5411 5412 unsigned Idx = KIdx->getZExtValue(); 5413 bool InsertLo = Idx < 2; 5414 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5415 InsertLo ? LoVec : HiVec, 5416 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5417 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5418 5419 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5420 5421 SDValue Concat = InsertLo ? 5422 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5423 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5424 5425 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5426 } 5427 5428 if (isa<ConstantSDNode>(Idx)) 5429 return SDValue(); 5430 5431 MVT IntVT = MVT::getIntegerVT(VecSize); 5432 5433 // Avoid stack access for dynamic indexing. 5434 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5435 5436 // Create a congruent vector with the target value in each element so that 5437 // the required element can be masked and ORed into the target vector. 5438 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5439 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5440 5441 assert(isPowerOf2_32(EltSize)); 5442 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5443 5444 // Convert vector index to bit-index. 5445 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5446 5447 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5448 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5449 DAG.getConstant(0xffff, SL, IntVT), 5450 ScaledIdx); 5451 5452 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5453 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5454 DAG.getNOT(SL, BFM, IntVT), BCVec); 5455 5456 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5457 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5458 } 5459 5460 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5461 SelectionDAG &DAG) const { 5462 SDLoc SL(Op); 5463 5464 EVT ResultVT = Op.getValueType(); 5465 SDValue Vec = Op.getOperand(0); 5466 SDValue Idx = Op.getOperand(1); 5467 EVT VecVT = Vec.getValueType(); 5468 unsigned VecSize = VecVT.getSizeInBits(); 5469 EVT EltVT = VecVT.getVectorElementType(); 5470 assert(VecSize <= 64); 5471 5472 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5473 5474 // Make sure we do any optimizations that will make it easier to fold 5475 // source modifiers before obscuring it with bit operations. 5476 5477 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5478 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5479 return Combined; 5480 5481 unsigned EltSize = EltVT.getSizeInBits(); 5482 assert(isPowerOf2_32(EltSize)); 5483 5484 MVT IntVT = MVT::getIntegerVT(VecSize); 5485 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5486 5487 // Convert vector index to bit-index (* EltSize) 5488 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5489 5490 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5491 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5492 5493 if (ResultVT == MVT::f16) { 5494 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5495 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5496 } 5497 5498 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5499 } 5500 5501 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5502 assert(Elt % 2 == 0); 5503 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5504 } 5505 5506 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5507 SelectionDAG &DAG) const { 5508 SDLoc SL(Op); 5509 EVT ResultVT = Op.getValueType(); 5510 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5511 5512 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5513 EVT EltVT = PackVT.getVectorElementType(); 5514 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5515 5516 // vector_shuffle <0,1,6,7> lhs, rhs 5517 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5518 // 5519 // vector_shuffle <6,7,2,3> lhs, rhs 5520 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5521 // 5522 // vector_shuffle <6,7,0,1> lhs, rhs 5523 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5524 5525 // Avoid scalarizing when both halves are reading from consecutive elements. 5526 SmallVector<SDValue, 4> Pieces; 5527 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5528 if (elementPairIsContiguous(SVN->getMask(), I)) { 5529 const int Idx = SVN->getMaskElt(I); 5530 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5531 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5532 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5533 PackVT, SVN->getOperand(VecIdx), 5534 DAG.getConstant(EltIdx, SL, MVT::i32)); 5535 Pieces.push_back(SubVec); 5536 } else { 5537 const int Idx0 = SVN->getMaskElt(I); 5538 const int Idx1 = SVN->getMaskElt(I + 1); 5539 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5540 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5541 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5542 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5543 5544 SDValue Vec0 = SVN->getOperand(VecIdx0); 5545 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5546 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5547 5548 SDValue Vec1 = SVN->getOperand(VecIdx1); 5549 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5550 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5551 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5552 } 5553 } 5554 5555 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5556 } 5557 5558 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5559 SelectionDAG &DAG) const { 5560 SDLoc SL(Op); 5561 EVT VT = Op.getValueType(); 5562 5563 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5564 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5565 5566 // Turn into pair of packed build_vectors. 5567 // TODO: Special case for constants that can be materialized with s_mov_b64. 5568 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5569 { Op.getOperand(0), Op.getOperand(1) }); 5570 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5571 { Op.getOperand(2), Op.getOperand(3) }); 5572 5573 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5574 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5575 5576 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5577 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5578 } 5579 5580 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5581 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5582 5583 SDValue Lo = Op.getOperand(0); 5584 SDValue Hi = Op.getOperand(1); 5585 5586 // Avoid adding defined bits with the zero_extend. 5587 if (Hi.isUndef()) { 5588 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5589 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5590 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5591 } 5592 5593 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5594 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5595 5596 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5597 DAG.getConstant(16, SL, MVT::i32)); 5598 if (Lo.isUndef()) 5599 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5600 5601 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5602 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5603 5604 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5605 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5606 } 5607 5608 bool 5609 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5610 // We can fold offsets for anything that doesn't require a GOT relocation. 5611 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5612 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5613 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5614 !shouldEmitGOTReloc(GA->getGlobal()); 5615 } 5616 5617 static SDValue 5618 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5619 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5620 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5621 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5622 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5623 // lowered to the following code sequence: 5624 // 5625 // For constant address space: 5626 // s_getpc_b64 s[0:1] 5627 // s_add_u32 s0, s0, $symbol 5628 // s_addc_u32 s1, s1, 0 5629 // 5630 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5631 // a fixup or relocation is emitted to replace $symbol with a literal 5632 // constant, which is a pc-relative offset from the encoding of the $symbol 5633 // operand to the global variable. 5634 // 5635 // For global address space: 5636 // s_getpc_b64 s[0:1] 5637 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5638 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5639 // 5640 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5641 // fixups or relocations are emitted to replace $symbol@*@lo and 5642 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5643 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5644 // operand to the global variable. 5645 // 5646 // What we want here is an offset from the value returned by s_getpc 5647 // (which is the address of the s_add_u32 instruction) to the global 5648 // variable, but since the encoding of $symbol starts 4 bytes after the start 5649 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5650 // small. This requires us to add 4 to the global variable offset in order to 5651 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5652 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5653 // instruction. 5654 SDValue PtrLo = 5655 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5656 SDValue PtrHi; 5657 if (GAFlags == SIInstrInfo::MO_NONE) { 5658 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5659 } else { 5660 PtrHi = 5661 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5662 } 5663 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5664 } 5665 5666 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5667 SDValue Op, 5668 SelectionDAG &DAG) const { 5669 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5670 SDLoc DL(GSD); 5671 EVT PtrVT = Op.getValueType(); 5672 5673 const GlobalValue *GV = GSD->getGlobal(); 5674 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5675 shouldUseLDSConstAddress(GV)) || 5676 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5677 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5678 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5679 GV->hasExternalLinkage()) { 5680 Type *Ty = GV->getValueType(); 5681 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5682 // zero-sized type in other languages to declare the dynamic shared 5683 // memory which size is not known at the compile time. They will be 5684 // allocated by the runtime and placed directly after the static 5685 // allocated ones. They all share the same offset. 5686 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5687 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5688 // Adjust alignment for that dynamic shared memory array. 5689 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5690 return SDValue( 5691 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5692 } 5693 } 5694 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5695 } 5696 5697 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5698 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5699 SIInstrInfo::MO_ABS32_LO); 5700 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5701 } 5702 5703 if (shouldEmitFixup(GV)) 5704 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5705 else if (shouldEmitPCReloc(GV)) 5706 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5707 SIInstrInfo::MO_REL32); 5708 5709 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5710 SIInstrInfo::MO_GOTPCREL32); 5711 5712 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5713 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5714 const DataLayout &DataLayout = DAG.getDataLayout(); 5715 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5716 MachinePointerInfo PtrInfo 5717 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5718 5719 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5720 MachineMemOperand::MODereferenceable | 5721 MachineMemOperand::MOInvariant); 5722 } 5723 5724 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5725 const SDLoc &DL, SDValue V) const { 5726 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5727 // the destination register. 5728 // 5729 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5730 // so we will end up with redundant moves to m0. 5731 // 5732 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5733 5734 // A Null SDValue creates a glue result. 5735 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5736 V, Chain); 5737 return SDValue(M0, 0); 5738 } 5739 5740 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5741 SDValue Op, 5742 MVT VT, 5743 unsigned Offset) const { 5744 SDLoc SL(Op); 5745 SDValue Param = lowerKernargMemParameter( 5746 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5747 // The local size values will have the hi 16-bits as zero. 5748 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5749 DAG.getValueType(VT)); 5750 } 5751 5752 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5753 EVT VT) { 5754 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5755 "non-hsa intrinsic with hsa target", 5756 DL.getDebugLoc()); 5757 DAG.getContext()->diagnose(BadIntrin); 5758 return DAG.getUNDEF(VT); 5759 } 5760 5761 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5762 EVT VT) { 5763 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5764 "intrinsic not supported on subtarget", 5765 DL.getDebugLoc()); 5766 DAG.getContext()->diagnose(BadIntrin); 5767 return DAG.getUNDEF(VT); 5768 } 5769 5770 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5771 ArrayRef<SDValue> Elts) { 5772 assert(!Elts.empty()); 5773 MVT Type; 5774 unsigned NumElts; 5775 5776 if (Elts.size() == 1) { 5777 Type = MVT::f32; 5778 NumElts = 1; 5779 } else if (Elts.size() == 2) { 5780 Type = MVT::v2f32; 5781 NumElts = 2; 5782 } else if (Elts.size() == 3) { 5783 Type = MVT::v3f32; 5784 NumElts = 3; 5785 } else if (Elts.size() <= 4) { 5786 Type = MVT::v4f32; 5787 NumElts = 4; 5788 } else if (Elts.size() <= 8) { 5789 Type = MVT::v8f32; 5790 NumElts = 8; 5791 } else { 5792 assert(Elts.size() <= 16); 5793 Type = MVT::v16f32; 5794 NumElts = 16; 5795 } 5796 5797 SmallVector<SDValue, 16> VecElts(NumElts); 5798 for (unsigned i = 0; i < Elts.size(); ++i) { 5799 SDValue Elt = Elts[i]; 5800 if (Elt.getValueType() != MVT::f32) 5801 Elt = DAG.getBitcast(MVT::f32, Elt); 5802 VecElts[i] = Elt; 5803 } 5804 for (unsigned i = Elts.size(); i < NumElts; ++i) 5805 VecElts[i] = DAG.getUNDEF(MVT::f32); 5806 5807 if (NumElts == 1) 5808 return VecElts[0]; 5809 return DAG.getBuildVector(Type, DL, VecElts); 5810 } 5811 5812 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5813 SDValue Src, int ExtraElts) { 5814 EVT SrcVT = Src.getValueType(); 5815 5816 SmallVector<SDValue, 8> Elts; 5817 5818 if (SrcVT.isVector()) 5819 DAG.ExtractVectorElements(Src, Elts); 5820 else 5821 Elts.push_back(Src); 5822 5823 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5824 while (ExtraElts--) 5825 Elts.push_back(Undef); 5826 5827 return DAG.getBuildVector(CastVT, DL, Elts); 5828 } 5829 5830 // Re-construct the required return value for a image load intrinsic. 5831 // This is more complicated due to the optional use TexFailCtrl which means the required 5832 // return type is an aggregate 5833 static SDValue constructRetValue(SelectionDAG &DAG, 5834 MachineSDNode *Result, 5835 ArrayRef<EVT> ResultTypes, 5836 bool IsTexFail, bool Unpacked, bool IsD16, 5837 int DMaskPop, int NumVDataDwords, 5838 const SDLoc &DL) { 5839 // Determine the required return type. This is the same regardless of IsTexFail flag 5840 EVT ReqRetVT = ResultTypes[0]; 5841 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5842 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5843 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5844 5845 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5846 DMaskPop : (DMaskPop + 1) / 2; 5847 5848 MVT DataDwordVT = NumDataDwords == 1 ? 5849 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5850 5851 MVT MaskPopVT = MaskPopDwords == 1 ? 5852 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5853 5854 SDValue Data(Result, 0); 5855 SDValue TexFail; 5856 5857 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 5858 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5859 if (MaskPopVT.isVector()) { 5860 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5861 SDValue(Result, 0), ZeroIdx); 5862 } else { 5863 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5864 SDValue(Result, 0), ZeroIdx); 5865 } 5866 } 5867 5868 if (DataDwordVT.isVector()) 5869 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5870 NumDataDwords - MaskPopDwords); 5871 5872 if (IsD16) 5873 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5874 5875 EVT LegalReqRetVT = ReqRetVT; 5876 if (!ReqRetVT.isVector()) { 5877 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5878 } else { 5879 // We need to widen the return vector to a legal type 5880 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 5881 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 5882 LegalReqRetVT = 5883 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 5884 ReqRetVT.getVectorNumElements() + 1); 5885 } 5886 } 5887 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 5888 5889 if (IsTexFail) { 5890 TexFail = 5891 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 5892 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5893 5894 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5895 } 5896 5897 if (Result->getNumValues() == 1) 5898 return Data; 5899 5900 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5901 } 5902 5903 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5904 SDValue *LWE, bool &IsTexFail) { 5905 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5906 5907 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5908 if (Value) { 5909 IsTexFail = true; 5910 } 5911 5912 SDLoc DL(TexFailCtrlConst); 5913 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5914 Value &= ~(uint64_t)0x1; 5915 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5916 Value &= ~(uint64_t)0x2; 5917 5918 return Value == 0; 5919 } 5920 5921 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5922 MVT PackVectorVT, 5923 SmallVectorImpl<SDValue> &PackedAddrs, 5924 unsigned DimIdx, unsigned EndIdx, 5925 unsigned NumGradients) { 5926 SDLoc DL(Op); 5927 for (unsigned I = DimIdx; I < EndIdx; I++) { 5928 SDValue Addr = Op.getOperand(I); 5929 5930 // Gradients are packed with undef for each coordinate. 5931 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5932 // 1D: undef,dx/dh; undef,dx/dv 5933 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5934 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5935 if (((I + 1) >= EndIdx) || 5936 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5937 I == DimIdx + NumGradients - 1))) { 5938 if (Addr.getValueType() != MVT::i16) 5939 Addr = DAG.getBitcast(MVT::i16, Addr); 5940 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5941 } else { 5942 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5943 I++; 5944 } 5945 Addr = DAG.getBitcast(MVT::f32, Addr); 5946 PackedAddrs.push_back(Addr); 5947 } 5948 } 5949 5950 SDValue SITargetLowering::lowerImage(SDValue Op, 5951 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5952 SelectionDAG &DAG, bool WithChain) const { 5953 SDLoc DL(Op); 5954 MachineFunction &MF = DAG.getMachineFunction(); 5955 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5956 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5957 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5958 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5959 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5960 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5961 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5962 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5963 unsigned IntrOpcode = Intr->BaseOpcode; 5964 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 5965 5966 SmallVector<EVT, 3> ResultTypes(Op->values()); 5967 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 5968 bool IsD16 = false; 5969 bool IsG16 = false; 5970 bool IsA16 = false; 5971 SDValue VData; 5972 int NumVDataDwords; 5973 bool AdjustRetType = false; 5974 5975 // Offset of intrinsic arguments 5976 const unsigned ArgOffset = WithChain ? 2 : 1; 5977 5978 unsigned DMask; 5979 unsigned DMaskLanes = 0; 5980 5981 if (BaseOpcode->Atomic) { 5982 VData = Op.getOperand(2); 5983 5984 bool Is64Bit = VData.getValueType() == MVT::i64; 5985 if (BaseOpcode->AtomicX2) { 5986 SDValue VData2 = Op.getOperand(3); 5987 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5988 {VData, VData2}); 5989 if (Is64Bit) 5990 VData = DAG.getBitcast(MVT::v4i32, VData); 5991 5992 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5993 DMask = Is64Bit ? 0xf : 0x3; 5994 NumVDataDwords = Is64Bit ? 4 : 2; 5995 } else { 5996 DMask = Is64Bit ? 0x3 : 0x1; 5997 NumVDataDwords = Is64Bit ? 2 : 1; 5998 } 5999 } else { 6000 auto *DMaskConst = 6001 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6002 DMask = DMaskConst->getZExtValue(); 6003 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6004 6005 if (BaseOpcode->Store) { 6006 VData = Op.getOperand(2); 6007 6008 MVT StoreVT = VData.getSimpleValueType(); 6009 if (StoreVT.getScalarType() == MVT::f16) { 6010 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6011 return Op; // D16 is unsupported for this instruction 6012 6013 IsD16 = true; 6014 VData = handleD16VData(VData, DAG, true); 6015 } 6016 6017 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6018 } else { 6019 // Work out the num dwords based on the dmask popcount and underlying type 6020 // and whether packing is supported. 6021 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6022 if (LoadVT.getScalarType() == MVT::f16) { 6023 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6024 return Op; // D16 is unsupported for this instruction 6025 6026 IsD16 = true; 6027 } 6028 6029 // Confirm that the return type is large enough for the dmask specified 6030 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6031 (!LoadVT.isVector() && DMaskLanes > 1)) 6032 return Op; 6033 6034 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6035 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6036 // instructions. 6037 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6038 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6039 NumVDataDwords = (DMaskLanes + 1) / 2; 6040 else 6041 NumVDataDwords = DMaskLanes; 6042 6043 AdjustRetType = true; 6044 } 6045 } 6046 6047 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6048 SmallVector<SDValue, 4> VAddrs; 6049 6050 // Optimize _L to _LZ when _L is zero 6051 if (LZMappingInfo) { 6052 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6053 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6054 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6055 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6056 VAddrEnd--; // remove 'lod' 6057 } 6058 } 6059 } 6060 6061 // Optimize _mip away, when 'lod' is zero 6062 if (MIPMappingInfo) { 6063 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6064 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6065 if (ConstantLod->isNullValue()) { 6066 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6067 VAddrEnd--; // remove 'mip' 6068 } 6069 } 6070 } 6071 6072 // Push back extra arguments. 6073 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) 6074 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6075 6076 // Check for 16 bit addresses or derivatives and pack if true. 6077 MVT VAddrVT = 6078 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6079 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6080 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6081 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6082 6083 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6084 VAddrScalarVT = VAddrVT.getScalarType(); 6085 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6086 if (IsA16 || IsG16) { 6087 if (IsA16) { 6088 if (!ST->hasA16()) { 6089 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6090 "support 16 bit addresses\n"); 6091 return Op; 6092 } 6093 if (!IsG16) { 6094 LLVM_DEBUG( 6095 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6096 "need 16 bit derivatives but got 32 bit derivatives\n"); 6097 return Op; 6098 } 6099 } else if (!ST->hasG16()) { 6100 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6101 "support 16 bit derivatives\n"); 6102 return Op; 6103 } 6104 6105 if (BaseOpcode->Gradients && !IsA16) { 6106 if (!ST->hasG16()) { 6107 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6108 "support 16 bit derivatives\n"); 6109 return Op; 6110 } 6111 // Activate g16 6112 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6113 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6114 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6115 } 6116 6117 // Don't compress addresses for G16 6118 const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6119 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, 6120 ArgOffset + Intr->GradientStart, PackEndIdx, 6121 Intr->NumGradients); 6122 6123 if (!IsA16) { 6124 // Add uncompressed address 6125 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6126 VAddrs.push_back(Op.getOperand(I)); 6127 } 6128 } else { 6129 for (unsigned I = ArgOffset + Intr->GradientStart; I < VAddrEnd; I++) 6130 VAddrs.push_back(Op.getOperand(I)); 6131 } 6132 6133 // If the register allocator cannot place the address registers contiguously 6134 // without introducing moves, then using the non-sequential address encoding 6135 // is always preferable, since it saves VALU instructions and is usually a 6136 // wash in terms of code size or even better. 6137 // 6138 // However, we currently have no way of hinting to the register allocator that 6139 // MIMG addresses should be placed contiguously when it is possible to do so, 6140 // so force non-NSA for the common 2-address case as a heuristic. 6141 // 6142 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6143 // allocation when possible. 6144 bool UseNSA = 6145 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 6146 SDValue VAddr; 6147 if (!UseNSA) 6148 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6149 6150 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6151 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6152 SDValue Unorm; 6153 if (!BaseOpcode->Sampler) { 6154 Unorm = True; 6155 } else { 6156 auto UnormConst = 6157 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6158 6159 Unorm = UnormConst->getZExtValue() ? True : False; 6160 } 6161 6162 SDValue TFE; 6163 SDValue LWE; 6164 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6165 bool IsTexFail = false; 6166 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6167 return Op; 6168 6169 if (IsTexFail) { 6170 if (!DMaskLanes) { 6171 // Expecting to get an error flag since TFC is on - and dmask is 0 6172 // Force dmask to be at least 1 otherwise the instruction will fail 6173 DMask = 0x1; 6174 DMaskLanes = 1; 6175 NumVDataDwords = 1; 6176 } 6177 NumVDataDwords += 1; 6178 AdjustRetType = true; 6179 } 6180 6181 // Has something earlier tagged that the return type needs adjusting 6182 // This happens if the instruction is a load or has set TexFailCtrl flags 6183 if (AdjustRetType) { 6184 // NumVDataDwords reflects the true number of dwords required in the return type 6185 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6186 // This is a no-op load. This can be eliminated 6187 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6188 if (isa<MemSDNode>(Op)) 6189 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6190 return Undef; 6191 } 6192 6193 EVT NewVT = NumVDataDwords > 1 ? 6194 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6195 : MVT::i32; 6196 6197 ResultTypes[0] = NewVT; 6198 if (ResultTypes.size() == 3) { 6199 // Original result was aggregate type used for TexFailCtrl results 6200 // The actual instruction returns as a vector type which has now been 6201 // created. Remove the aggregate result. 6202 ResultTypes.erase(&ResultTypes[1]); 6203 } 6204 } 6205 6206 unsigned CPol = cast<ConstantSDNode>( 6207 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6208 if (BaseOpcode->Atomic) 6209 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6210 if (CPol & ~AMDGPU::CPol::ALL) 6211 return Op; 6212 6213 SmallVector<SDValue, 26> Ops; 6214 if (BaseOpcode->Store || BaseOpcode->Atomic) 6215 Ops.push_back(VData); // vdata 6216 if (UseNSA) 6217 append_range(Ops, VAddrs); 6218 else 6219 Ops.push_back(VAddr); 6220 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6221 if (BaseOpcode->Sampler) 6222 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6223 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6224 if (IsGFX10Plus) 6225 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6226 Ops.push_back(Unorm); 6227 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6228 Ops.push_back(IsA16 && // r128, a16 for gfx9 6229 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6230 if (IsGFX10Plus) 6231 Ops.push_back(IsA16 ? True : False); 6232 if (!Subtarget->hasGFX90AInsts()) { 6233 Ops.push_back(TFE); //tfe 6234 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6235 report_fatal_error("TFE is not supported on this GPU"); 6236 } 6237 Ops.push_back(LWE); // lwe 6238 if (!IsGFX10Plus) 6239 Ops.push_back(DimInfo->DA ? True : False); 6240 if (BaseOpcode->HasD16) 6241 Ops.push_back(IsD16 ? True : False); 6242 if (isa<MemSDNode>(Op)) 6243 Ops.push_back(Op.getOperand(0)); // chain 6244 6245 int NumVAddrDwords = 6246 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6247 int Opcode = -1; 6248 6249 if (IsGFX10Plus) { 6250 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6251 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6252 : AMDGPU::MIMGEncGfx10Default, 6253 NumVDataDwords, NumVAddrDwords); 6254 } else { 6255 if (Subtarget->hasGFX90AInsts()) { 6256 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6257 NumVDataDwords, NumVAddrDwords); 6258 if (Opcode == -1) 6259 report_fatal_error( 6260 "requested image instruction is not supported on this GPU"); 6261 } 6262 if (Opcode == -1 && 6263 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6264 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6265 NumVDataDwords, NumVAddrDwords); 6266 if (Opcode == -1) 6267 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6268 NumVDataDwords, NumVAddrDwords); 6269 } 6270 assert(Opcode != -1); 6271 6272 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6273 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6274 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6275 DAG.setNodeMemRefs(NewNode, {MemRef}); 6276 } 6277 6278 if (BaseOpcode->AtomicX2) { 6279 SmallVector<SDValue, 1> Elt; 6280 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6281 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6282 } 6283 if (BaseOpcode->Store) 6284 return SDValue(NewNode, 0); 6285 return constructRetValue(DAG, NewNode, 6286 OrigResultTypes, IsTexFail, 6287 Subtarget->hasUnpackedD16VMem(), IsD16, 6288 DMaskLanes, NumVDataDwords, DL); 6289 } 6290 6291 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6292 SDValue Offset, SDValue CachePolicy, 6293 SelectionDAG &DAG) const { 6294 MachineFunction &MF = DAG.getMachineFunction(); 6295 6296 const DataLayout &DataLayout = DAG.getDataLayout(); 6297 Align Alignment = 6298 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6299 6300 MachineMemOperand *MMO = MF.getMachineMemOperand( 6301 MachinePointerInfo(), 6302 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6303 MachineMemOperand::MOInvariant, 6304 VT.getStoreSize(), Alignment); 6305 6306 if (!Offset->isDivergent()) { 6307 SDValue Ops[] = { 6308 Rsrc, 6309 Offset, // Offset 6310 CachePolicy 6311 }; 6312 6313 // Widen vec3 load to vec4. 6314 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6315 EVT WidenedVT = 6316 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6317 auto WidenedOp = DAG.getMemIntrinsicNode( 6318 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6319 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6320 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6321 DAG.getVectorIdxConstant(0, DL)); 6322 return Subvector; 6323 } 6324 6325 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6326 DAG.getVTList(VT), Ops, VT, MMO); 6327 } 6328 6329 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6330 // assume that the buffer is unswizzled. 6331 SmallVector<SDValue, 4> Loads; 6332 unsigned NumLoads = 1; 6333 MVT LoadVT = VT.getSimpleVT(); 6334 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6335 assert((LoadVT.getScalarType() == MVT::i32 || 6336 LoadVT.getScalarType() == MVT::f32)); 6337 6338 if (NumElts == 8 || NumElts == 16) { 6339 NumLoads = NumElts / 4; 6340 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6341 } 6342 6343 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6344 SDValue Ops[] = { 6345 DAG.getEntryNode(), // Chain 6346 Rsrc, // rsrc 6347 DAG.getConstant(0, DL, MVT::i32), // vindex 6348 {}, // voffset 6349 {}, // soffset 6350 {}, // offset 6351 CachePolicy, // cachepolicy 6352 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6353 }; 6354 6355 // Use the alignment to ensure that the required offsets will fit into the 6356 // immediate offsets. 6357 setBufferOffsets(Offset, DAG, &Ops[3], 6358 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6359 6360 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6361 for (unsigned i = 0; i < NumLoads; ++i) { 6362 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6363 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6364 LoadVT, MMO, DAG)); 6365 } 6366 6367 if (NumElts == 8 || NumElts == 16) 6368 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6369 6370 return Loads[0]; 6371 } 6372 6373 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6374 SelectionDAG &DAG) const { 6375 MachineFunction &MF = DAG.getMachineFunction(); 6376 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6377 6378 EVT VT = Op.getValueType(); 6379 SDLoc DL(Op); 6380 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6381 6382 // TODO: Should this propagate fast-math-flags? 6383 6384 switch (IntrinsicID) { 6385 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6386 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6387 return emitNonHSAIntrinsicError(DAG, DL, VT); 6388 return getPreloadedValue(DAG, *MFI, VT, 6389 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6390 } 6391 case Intrinsic::amdgcn_dispatch_ptr: 6392 case Intrinsic::amdgcn_queue_ptr: { 6393 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6394 DiagnosticInfoUnsupported BadIntrin( 6395 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6396 DL.getDebugLoc()); 6397 DAG.getContext()->diagnose(BadIntrin); 6398 return DAG.getUNDEF(VT); 6399 } 6400 6401 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6402 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6403 return getPreloadedValue(DAG, *MFI, VT, RegID); 6404 } 6405 case Intrinsic::amdgcn_implicitarg_ptr: { 6406 if (MFI->isEntryFunction()) 6407 return getImplicitArgPtr(DAG, DL); 6408 return getPreloadedValue(DAG, *MFI, VT, 6409 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6410 } 6411 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6412 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6413 // This only makes sense to call in a kernel, so just lower to null. 6414 return DAG.getConstant(0, DL, VT); 6415 } 6416 6417 return getPreloadedValue(DAG, *MFI, VT, 6418 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6419 } 6420 case Intrinsic::amdgcn_dispatch_id: { 6421 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6422 } 6423 case Intrinsic::amdgcn_rcp: 6424 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6425 case Intrinsic::amdgcn_rsq: 6426 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6427 case Intrinsic::amdgcn_rsq_legacy: 6428 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6429 return emitRemovedIntrinsicError(DAG, DL, VT); 6430 return SDValue(); 6431 case Intrinsic::amdgcn_rcp_legacy: 6432 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6433 return emitRemovedIntrinsicError(DAG, DL, VT); 6434 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6435 case Intrinsic::amdgcn_rsq_clamp: { 6436 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6437 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6438 6439 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6440 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6441 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6442 6443 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6444 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6445 DAG.getConstantFP(Max, DL, VT)); 6446 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6447 DAG.getConstantFP(Min, DL, VT)); 6448 } 6449 case Intrinsic::r600_read_ngroups_x: 6450 if (Subtarget->isAmdHsaOS()) 6451 return emitNonHSAIntrinsicError(DAG, DL, VT); 6452 6453 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6454 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6455 false); 6456 case Intrinsic::r600_read_ngroups_y: 6457 if (Subtarget->isAmdHsaOS()) 6458 return emitNonHSAIntrinsicError(DAG, DL, VT); 6459 6460 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6461 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6462 false); 6463 case Intrinsic::r600_read_ngroups_z: 6464 if (Subtarget->isAmdHsaOS()) 6465 return emitNonHSAIntrinsicError(DAG, DL, VT); 6466 6467 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6468 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6469 false); 6470 case Intrinsic::r600_read_global_size_x: 6471 if (Subtarget->isAmdHsaOS()) 6472 return emitNonHSAIntrinsicError(DAG, DL, VT); 6473 6474 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6475 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6476 Align(4), false); 6477 case Intrinsic::r600_read_global_size_y: 6478 if (Subtarget->isAmdHsaOS()) 6479 return emitNonHSAIntrinsicError(DAG, DL, VT); 6480 6481 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6482 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6483 Align(4), false); 6484 case Intrinsic::r600_read_global_size_z: 6485 if (Subtarget->isAmdHsaOS()) 6486 return emitNonHSAIntrinsicError(DAG, DL, VT); 6487 6488 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6489 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6490 Align(4), false); 6491 case Intrinsic::r600_read_local_size_x: 6492 if (Subtarget->isAmdHsaOS()) 6493 return emitNonHSAIntrinsicError(DAG, DL, VT); 6494 6495 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6496 SI::KernelInputOffsets::LOCAL_SIZE_X); 6497 case Intrinsic::r600_read_local_size_y: 6498 if (Subtarget->isAmdHsaOS()) 6499 return emitNonHSAIntrinsicError(DAG, DL, VT); 6500 6501 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6502 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6503 case Intrinsic::r600_read_local_size_z: 6504 if (Subtarget->isAmdHsaOS()) 6505 return emitNonHSAIntrinsicError(DAG, DL, VT); 6506 6507 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6508 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6509 case Intrinsic::amdgcn_workgroup_id_x: 6510 return getPreloadedValue(DAG, *MFI, VT, 6511 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6512 case Intrinsic::amdgcn_workgroup_id_y: 6513 return getPreloadedValue(DAG, *MFI, VT, 6514 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6515 case Intrinsic::amdgcn_workgroup_id_z: 6516 return getPreloadedValue(DAG, *MFI, VT, 6517 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6518 case Intrinsic::amdgcn_workitem_id_x: 6519 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6520 SDLoc(DAG.getEntryNode()), 6521 MFI->getArgInfo().WorkItemIDX); 6522 case Intrinsic::amdgcn_workitem_id_y: 6523 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6524 SDLoc(DAG.getEntryNode()), 6525 MFI->getArgInfo().WorkItemIDY); 6526 case Intrinsic::amdgcn_workitem_id_z: 6527 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6528 SDLoc(DAG.getEntryNode()), 6529 MFI->getArgInfo().WorkItemIDZ); 6530 case Intrinsic::amdgcn_wavefrontsize: 6531 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6532 SDLoc(Op), MVT::i32); 6533 case Intrinsic::amdgcn_s_buffer_load: { 6534 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6535 if (CPol & ~AMDGPU::CPol::ALL) 6536 return Op; 6537 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6538 DAG); 6539 } 6540 case Intrinsic::amdgcn_fdiv_fast: 6541 return lowerFDIV_FAST(Op, DAG); 6542 case Intrinsic::amdgcn_sin: 6543 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6544 6545 case Intrinsic::amdgcn_cos: 6546 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6547 6548 case Intrinsic::amdgcn_mul_u24: 6549 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6550 case Intrinsic::amdgcn_mul_i24: 6551 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6552 6553 case Intrinsic::amdgcn_log_clamp: { 6554 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6555 return SDValue(); 6556 6557 return emitRemovedIntrinsicError(DAG, DL, VT); 6558 } 6559 case Intrinsic::amdgcn_ldexp: 6560 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6561 Op.getOperand(1), Op.getOperand(2)); 6562 6563 case Intrinsic::amdgcn_fract: 6564 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6565 6566 case Intrinsic::amdgcn_class: 6567 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6568 Op.getOperand(1), Op.getOperand(2)); 6569 case Intrinsic::amdgcn_div_fmas: 6570 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6571 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6572 Op.getOperand(4)); 6573 6574 case Intrinsic::amdgcn_div_fixup: 6575 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6576 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6577 6578 case Intrinsic::amdgcn_div_scale: { 6579 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6580 6581 // Translate to the operands expected by the machine instruction. The 6582 // first parameter must be the same as the first instruction. 6583 SDValue Numerator = Op.getOperand(1); 6584 SDValue Denominator = Op.getOperand(2); 6585 6586 // Note this order is opposite of the machine instruction's operations, 6587 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6588 // intrinsic has the numerator as the first operand to match a normal 6589 // division operation. 6590 6591 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6592 6593 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6594 Denominator, Numerator); 6595 } 6596 case Intrinsic::amdgcn_icmp: { 6597 // There is a Pat that handles this variant, so return it as-is. 6598 if (Op.getOperand(1).getValueType() == MVT::i1 && 6599 Op.getConstantOperandVal(2) == 0 && 6600 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6601 return Op; 6602 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6603 } 6604 case Intrinsic::amdgcn_fcmp: { 6605 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6606 } 6607 case Intrinsic::amdgcn_ballot: 6608 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6609 case Intrinsic::amdgcn_fmed3: 6610 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6611 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6612 case Intrinsic::amdgcn_fdot2: 6613 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6614 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6615 Op.getOperand(4)); 6616 case Intrinsic::amdgcn_fmul_legacy: 6617 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6618 Op.getOperand(1), Op.getOperand(2)); 6619 case Intrinsic::amdgcn_sffbh: 6620 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6621 case Intrinsic::amdgcn_sbfe: 6622 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6623 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6624 case Intrinsic::amdgcn_ubfe: 6625 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6626 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6627 case Intrinsic::amdgcn_cvt_pkrtz: 6628 case Intrinsic::amdgcn_cvt_pknorm_i16: 6629 case Intrinsic::amdgcn_cvt_pknorm_u16: 6630 case Intrinsic::amdgcn_cvt_pk_i16: 6631 case Intrinsic::amdgcn_cvt_pk_u16: { 6632 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6633 EVT VT = Op.getValueType(); 6634 unsigned Opcode; 6635 6636 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6637 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6638 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6639 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6640 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6641 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6642 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6643 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6644 else 6645 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6646 6647 if (isTypeLegal(VT)) 6648 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6649 6650 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6651 Op.getOperand(1), Op.getOperand(2)); 6652 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6653 } 6654 case Intrinsic::amdgcn_fmad_ftz: 6655 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6656 Op.getOperand(2), Op.getOperand(3)); 6657 6658 case Intrinsic::amdgcn_if_break: 6659 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6660 Op->getOperand(1), Op->getOperand(2)), 0); 6661 6662 case Intrinsic::amdgcn_groupstaticsize: { 6663 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6664 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6665 return Op; 6666 6667 const Module *M = MF.getFunction().getParent(); 6668 const GlobalValue *GV = 6669 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6670 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6671 SIInstrInfo::MO_ABS32_LO); 6672 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6673 } 6674 case Intrinsic::amdgcn_is_shared: 6675 case Intrinsic::amdgcn_is_private: { 6676 SDLoc SL(Op); 6677 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6678 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6679 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6680 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6681 Op.getOperand(1)); 6682 6683 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6684 DAG.getConstant(1, SL, MVT::i32)); 6685 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6686 } 6687 case Intrinsic::amdgcn_alignbit: 6688 return DAG.getNode(ISD::FSHR, DL, VT, 6689 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6690 case Intrinsic::amdgcn_reloc_constant: { 6691 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6692 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6693 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6694 auto RelocSymbol = cast<GlobalVariable>( 6695 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6696 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6697 SIInstrInfo::MO_ABS32_LO); 6698 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6699 } 6700 default: 6701 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6702 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6703 return lowerImage(Op, ImageDimIntr, DAG, false); 6704 6705 return Op; 6706 } 6707 } 6708 6709 // This function computes an appropriate offset to pass to 6710 // MachineMemOperand::setOffset() based on the offset inputs to 6711 // an intrinsic. If any of the offsets are non-contstant or 6712 // if VIndex is non-zero then this function returns 0. Otherwise, 6713 // it returns the sum of VOffset, SOffset, and Offset. 6714 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6715 SDValue SOffset, 6716 SDValue Offset, 6717 SDValue VIndex = SDValue()) { 6718 6719 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6720 !isa<ConstantSDNode>(Offset)) 6721 return 0; 6722 6723 if (VIndex) { 6724 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6725 return 0; 6726 } 6727 6728 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6729 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6730 cast<ConstantSDNode>(Offset)->getSExtValue(); 6731 } 6732 6733 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6734 SelectionDAG &DAG, 6735 unsigned NewOpcode) const { 6736 SDLoc DL(Op); 6737 6738 SDValue VData = Op.getOperand(2); 6739 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6740 SDValue Ops[] = { 6741 Op.getOperand(0), // Chain 6742 VData, // vdata 6743 Op.getOperand(3), // rsrc 6744 DAG.getConstant(0, DL, MVT::i32), // vindex 6745 Offsets.first, // voffset 6746 Op.getOperand(5), // soffset 6747 Offsets.second, // offset 6748 Op.getOperand(6), // cachepolicy 6749 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6750 }; 6751 6752 auto *M = cast<MemSDNode>(Op); 6753 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6754 6755 EVT MemVT = VData.getValueType(); 6756 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6757 M->getMemOperand()); 6758 } 6759 6760 SDValue 6761 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6762 unsigned NewOpcode) const { 6763 SDLoc DL(Op); 6764 6765 SDValue VData = Op.getOperand(2); 6766 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6767 SDValue Ops[] = { 6768 Op.getOperand(0), // Chain 6769 VData, // vdata 6770 Op.getOperand(3), // rsrc 6771 Op.getOperand(4), // vindex 6772 Offsets.first, // voffset 6773 Op.getOperand(6), // soffset 6774 Offsets.second, // offset 6775 Op.getOperand(7), // cachepolicy 6776 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6777 }; 6778 6779 auto *M = cast<MemSDNode>(Op); 6780 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6781 Ops[3])); 6782 6783 EVT MemVT = VData.getValueType(); 6784 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6785 M->getMemOperand()); 6786 } 6787 6788 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6789 SelectionDAG &DAG) const { 6790 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6791 SDLoc DL(Op); 6792 6793 switch (IntrID) { 6794 case Intrinsic::amdgcn_ds_ordered_add: 6795 case Intrinsic::amdgcn_ds_ordered_swap: { 6796 MemSDNode *M = cast<MemSDNode>(Op); 6797 SDValue Chain = M->getOperand(0); 6798 SDValue M0 = M->getOperand(2); 6799 SDValue Value = M->getOperand(3); 6800 unsigned IndexOperand = M->getConstantOperandVal(7); 6801 unsigned WaveRelease = M->getConstantOperandVal(8); 6802 unsigned WaveDone = M->getConstantOperandVal(9); 6803 6804 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6805 IndexOperand &= ~0x3f; 6806 unsigned CountDw = 0; 6807 6808 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6809 CountDw = (IndexOperand >> 24) & 0xf; 6810 IndexOperand &= ~(0xf << 24); 6811 6812 if (CountDw < 1 || CountDw > 4) { 6813 report_fatal_error( 6814 "ds_ordered_count: dword count must be between 1 and 4"); 6815 } 6816 } 6817 6818 if (IndexOperand) 6819 report_fatal_error("ds_ordered_count: bad index operand"); 6820 6821 if (WaveDone && !WaveRelease) 6822 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6823 6824 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6825 unsigned ShaderType = 6826 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6827 unsigned Offset0 = OrderedCountIndex << 2; 6828 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6829 (Instruction << 4); 6830 6831 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6832 Offset1 |= (CountDw - 1) << 6; 6833 6834 unsigned Offset = Offset0 | (Offset1 << 8); 6835 6836 SDValue Ops[] = { 6837 Chain, 6838 Value, 6839 DAG.getTargetConstant(Offset, DL, MVT::i16), 6840 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6841 }; 6842 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6843 M->getVTList(), Ops, M->getMemoryVT(), 6844 M->getMemOperand()); 6845 } 6846 case Intrinsic::amdgcn_ds_fadd: { 6847 MemSDNode *M = cast<MemSDNode>(Op); 6848 unsigned Opc; 6849 switch (IntrID) { 6850 case Intrinsic::amdgcn_ds_fadd: 6851 Opc = ISD::ATOMIC_LOAD_FADD; 6852 break; 6853 } 6854 6855 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6856 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6857 M->getMemOperand()); 6858 } 6859 case Intrinsic::amdgcn_atomic_inc: 6860 case Intrinsic::amdgcn_atomic_dec: 6861 case Intrinsic::amdgcn_ds_fmin: 6862 case Intrinsic::amdgcn_ds_fmax: { 6863 MemSDNode *M = cast<MemSDNode>(Op); 6864 unsigned Opc; 6865 switch (IntrID) { 6866 case Intrinsic::amdgcn_atomic_inc: 6867 Opc = AMDGPUISD::ATOMIC_INC; 6868 break; 6869 case Intrinsic::amdgcn_atomic_dec: 6870 Opc = AMDGPUISD::ATOMIC_DEC; 6871 break; 6872 case Intrinsic::amdgcn_ds_fmin: 6873 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6874 break; 6875 case Intrinsic::amdgcn_ds_fmax: 6876 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6877 break; 6878 default: 6879 llvm_unreachable("Unknown intrinsic!"); 6880 } 6881 SDValue Ops[] = { 6882 M->getOperand(0), // Chain 6883 M->getOperand(2), // Ptr 6884 M->getOperand(3) // Value 6885 }; 6886 6887 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6888 M->getMemoryVT(), M->getMemOperand()); 6889 } 6890 case Intrinsic::amdgcn_buffer_load: 6891 case Intrinsic::amdgcn_buffer_load_format: { 6892 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6893 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6894 unsigned IdxEn = 1; 6895 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6896 IdxEn = Idx->getZExtValue() != 0; 6897 SDValue Ops[] = { 6898 Op.getOperand(0), // Chain 6899 Op.getOperand(2), // rsrc 6900 Op.getOperand(3), // vindex 6901 SDValue(), // voffset -- will be set by setBufferOffsets 6902 SDValue(), // soffset -- will be set by setBufferOffsets 6903 SDValue(), // offset -- will be set by setBufferOffsets 6904 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6905 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6906 }; 6907 6908 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6909 // We don't know the offset if vindex is non-zero, so clear it. 6910 if (IdxEn) 6911 Offset = 0; 6912 6913 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6914 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6915 6916 EVT VT = Op.getValueType(); 6917 EVT IntVT = VT.changeTypeToInteger(); 6918 auto *M = cast<MemSDNode>(Op); 6919 M->getMemOperand()->setOffset(Offset); 6920 EVT LoadVT = Op.getValueType(); 6921 6922 if (LoadVT.getScalarType() == MVT::f16) 6923 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6924 M, DAG, Ops); 6925 6926 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6927 if (LoadVT.getScalarType() == MVT::i8 || 6928 LoadVT.getScalarType() == MVT::i16) 6929 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6930 6931 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6932 M->getMemOperand(), DAG); 6933 } 6934 case Intrinsic::amdgcn_raw_buffer_load: 6935 case Intrinsic::amdgcn_raw_buffer_load_format: { 6936 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6937 6938 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6939 SDValue Ops[] = { 6940 Op.getOperand(0), // Chain 6941 Op.getOperand(2), // rsrc 6942 DAG.getConstant(0, DL, MVT::i32), // vindex 6943 Offsets.first, // voffset 6944 Op.getOperand(4), // soffset 6945 Offsets.second, // offset 6946 Op.getOperand(5), // cachepolicy, swizzled buffer 6947 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6948 }; 6949 6950 auto *M = cast<MemSDNode>(Op); 6951 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6952 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6953 } 6954 case Intrinsic::amdgcn_struct_buffer_load: 6955 case Intrinsic::amdgcn_struct_buffer_load_format: { 6956 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6957 6958 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6959 SDValue Ops[] = { 6960 Op.getOperand(0), // Chain 6961 Op.getOperand(2), // rsrc 6962 Op.getOperand(3), // vindex 6963 Offsets.first, // voffset 6964 Op.getOperand(5), // soffset 6965 Offsets.second, // offset 6966 Op.getOperand(6), // cachepolicy, swizzled buffer 6967 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6968 }; 6969 6970 auto *M = cast<MemSDNode>(Op); 6971 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6972 Ops[2])); 6973 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6974 } 6975 case Intrinsic::amdgcn_tbuffer_load: { 6976 MemSDNode *M = cast<MemSDNode>(Op); 6977 EVT LoadVT = Op.getValueType(); 6978 6979 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6980 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6981 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6982 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6983 unsigned IdxEn = 1; 6984 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6985 IdxEn = Idx->getZExtValue() != 0; 6986 SDValue Ops[] = { 6987 Op.getOperand(0), // Chain 6988 Op.getOperand(2), // rsrc 6989 Op.getOperand(3), // vindex 6990 Op.getOperand(4), // voffset 6991 Op.getOperand(5), // soffset 6992 Op.getOperand(6), // offset 6993 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6994 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6995 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6996 }; 6997 6998 if (LoadVT.getScalarType() == MVT::f16) 6999 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7000 M, DAG, Ops); 7001 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7002 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7003 DAG); 7004 } 7005 case Intrinsic::amdgcn_raw_tbuffer_load: { 7006 MemSDNode *M = cast<MemSDNode>(Op); 7007 EVT LoadVT = Op.getValueType(); 7008 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7009 7010 SDValue Ops[] = { 7011 Op.getOperand(0), // Chain 7012 Op.getOperand(2), // rsrc 7013 DAG.getConstant(0, DL, MVT::i32), // vindex 7014 Offsets.first, // voffset 7015 Op.getOperand(4), // soffset 7016 Offsets.second, // offset 7017 Op.getOperand(5), // format 7018 Op.getOperand(6), // cachepolicy, swizzled buffer 7019 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7020 }; 7021 7022 if (LoadVT.getScalarType() == MVT::f16) 7023 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7024 M, DAG, Ops); 7025 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7026 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7027 DAG); 7028 } 7029 case Intrinsic::amdgcn_struct_tbuffer_load: { 7030 MemSDNode *M = cast<MemSDNode>(Op); 7031 EVT LoadVT = Op.getValueType(); 7032 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7033 7034 SDValue Ops[] = { 7035 Op.getOperand(0), // Chain 7036 Op.getOperand(2), // rsrc 7037 Op.getOperand(3), // vindex 7038 Offsets.first, // voffset 7039 Op.getOperand(5), // soffset 7040 Offsets.second, // offset 7041 Op.getOperand(6), // format 7042 Op.getOperand(7), // cachepolicy, swizzled buffer 7043 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7044 }; 7045 7046 if (LoadVT.getScalarType() == MVT::f16) 7047 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7048 M, DAG, Ops); 7049 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7050 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7051 DAG); 7052 } 7053 case Intrinsic::amdgcn_buffer_atomic_swap: 7054 case Intrinsic::amdgcn_buffer_atomic_add: 7055 case Intrinsic::amdgcn_buffer_atomic_sub: 7056 case Intrinsic::amdgcn_buffer_atomic_csub: 7057 case Intrinsic::amdgcn_buffer_atomic_smin: 7058 case Intrinsic::amdgcn_buffer_atomic_umin: 7059 case Intrinsic::amdgcn_buffer_atomic_smax: 7060 case Intrinsic::amdgcn_buffer_atomic_umax: 7061 case Intrinsic::amdgcn_buffer_atomic_and: 7062 case Intrinsic::amdgcn_buffer_atomic_or: 7063 case Intrinsic::amdgcn_buffer_atomic_xor: 7064 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7065 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7066 unsigned IdxEn = 1; 7067 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7068 IdxEn = Idx->getZExtValue() != 0; 7069 SDValue Ops[] = { 7070 Op.getOperand(0), // Chain 7071 Op.getOperand(2), // vdata 7072 Op.getOperand(3), // rsrc 7073 Op.getOperand(4), // vindex 7074 SDValue(), // voffset -- will be set by setBufferOffsets 7075 SDValue(), // soffset -- will be set by setBufferOffsets 7076 SDValue(), // offset -- will be set by setBufferOffsets 7077 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7078 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7079 }; 7080 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7081 // We don't know the offset if vindex is non-zero, so clear it. 7082 if (IdxEn) 7083 Offset = 0; 7084 EVT VT = Op.getValueType(); 7085 7086 auto *M = cast<MemSDNode>(Op); 7087 M->getMemOperand()->setOffset(Offset); 7088 unsigned Opcode = 0; 7089 7090 switch (IntrID) { 7091 case Intrinsic::amdgcn_buffer_atomic_swap: 7092 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7093 break; 7094 case Intrinsic::amdgcn_buffer_atomic_add: 7095 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7096 break; 7097 case Intrinsic::amdgcn_buffer_atomic_sub: 7098 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7099 break; 7100 case Intrinsic::amdgcn_buffer_atomic_csub: 7101 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7102 break; 7103 case Intrinsic::amdgcn_buffer_atomic_smin: 7104 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7105 break; 7106 case Intrinsic::amdgcn_buffer_atomic_umin: 7107 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7108 break; 7109 case Intrinsic::amdgcn_buffer_atomic_smax: 7110 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7111 break; 7112 case Intrinsic::amdgcn_buffer_atomic_umax: 7113 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7114 break; 7115 case Intrinsic::amdgcn_buffer_atomic_and: 7116 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7117 break; 7118 case Intrinsic::amdgcn_buffer_atomic_or: 7119 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7120 break; 7121 case Intrinsic::amdgcn_buffer_atomic_xor: 7122 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7123 break; 7124 case Intrinsic::amdgcn_buffer_atomic_fadd: 7125 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7126 DiagnosticInfoUnsupported 7127 NoFpRet(DAG.getMachineFunction().getFunction(), 7128 "return versions of fp atomics not supported", 7129 DL.getDebugLoc(), DS_Error); 7130 DAG.getContext()->diagnose(NoFpRet); 7131 return SDValue(); 7132 } 7133 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7134 break; 7135 default: 7136 llvm_unreachable("unhandled atomic opcode"); 7137 } 7138 7139 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7140 M->getMemOperand()); 7141 } 7142 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7143 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7144 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7145 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7146 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7147 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7148 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7149 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7150 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7151 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7152 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7153 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7154 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7155 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7156 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7157 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7158 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7159 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7160 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7161 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7162 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7163 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7164 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7165 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7166 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7167 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7168 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7169 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7170 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7171 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7172 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7173 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7174 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7175 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7176 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7177 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7178 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7179 return lowerStructBufferAtomicIntrin(Op, DAG, 7180 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7181 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7182 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7183 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7184 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7185 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7186 return lowerStructBufferAtomicIntrin(Op, DAG, 7187 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7188 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7189 return lowerStructBufferAtomicIntrin(Op, DAG, 7190 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7191 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7192 return lowerStructBufferAtomicIntrin(Op, DAG, 7193 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7194 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7195 return lowerStructBufferAtomicIntrin(Op, DAG, 7196 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7197 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7198 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7199 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7200 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7201 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7202 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7203 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7204 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7205 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7206 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7207 7208 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7209 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7210 unsigned IdxEn = 1; 7211 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7212 IdxEn = Idx->getZExtValue() != 0; 7213 SDValue Ops[] = { 7214 Op.getOperand(0), // Chain 7215 Op.getOperand(2), // src 7216 Op.getOperand(3), // cmp 7217 Op.getOperand(4), // rsrc 7218 Op.getOperand(5), // vindex 7219 SDValue(), // voffset -- will be set by setBufferOffsets 7220 SDValue(), // soffset -- will be set by setBufferOffsets 7221 SDValue(), // offset -- will be set by setBufferOffsets 7222 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7223 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7224 }; 7225 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7226 // We don't know the offset if vindex is non-zero, so clear it. 7227 if (IdxEn) 7228 Offset = 0; 7229 EVT VT = Op.getValueType(); 7230 auto *M = cast<MemSDNode>(Op); 7231 M->getMemOperand()->setOffset(Offset); 7232 7233 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7234 Op->getVTList(), Ops, VT, M->getMemOperand()); 7235 } 7236 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7237 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7238 SDValue Ops[] = { 7239 Op.getOperand(0), // Chain 7240 Op.getOperand(2), // src 7241 Op.getOperand(3), // cmp 7242 Op.getOperand(4), // rsrc 7243 DAG.getConstant(0, DL, MVT::i32), // vindex 7244 Offsets.first, // voffset 7245 Op.getOperand(6), // soffset 7246 Offsets.second, // offset 7247 Op.getOperand(7), // cachepolicy 7248 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7249 }; 7250 EVT VT = Op.getValueType(); 7251 auto *M = cast<MemSDNode>(Op); 7252 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7253 7254 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7255 Op->getVTList(), Ops, VT, M->getMemOperand()); 7256 } 7257 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7258 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7259 SDValue Ops[] = { 7260 Op.getOperand(0), // Chain 7261 Op.getOperand(2), // src 7262 Op.getOperand(3), // cmp 7263 Op.getOperand(4), // rsrc 7264 Op.getOperand(5), // vindex 7265 Offsets.first, // voffset 7266 Op.getOperand(7), // soffset 7267 Offsets.second, // offset 7268 Op.getOperand(8), // cachepolicy 7269 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7270 }; 7271 EVT VT = Op.getValueType(); 7272 auto *M = cast<MemSDNode>(Op); 7273 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7274 Ops[4])); 7275 7276 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7277 Op->getVTList(), Ops, VT, M->getMemOperand()); 7278 } 7279 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7280 SDLoc DL(Op); 7281 MemSDNode *M = cast<MemSDNode>(Op); 7282 SDValue NodePtr = M->getOperand(2); 7283 SDValue RayExtent = M->getOperand(3); 7284 SDValue RayOrigin = M->getOperand(4); 7285 SDValue RayDir = M->getOperand(5); 7286 SDValue RayInvDir = M->getOperand(6); 7287 SDValue TDescr = M->getOperand(7); 7288 7289 assert(NodePtr.getValueType() == MVT::i32 || 7290 NodePtr.getValueType() == MVT::i64); 7291 assert(RayDir.getValueType() == MVT::v4f16 || 7292 RayDir.getValueType() == MVT::v4f32); 7293 7294 bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7295 bool Is64 = NodePtr.getValueType() == MVT::i64; 7296 unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa 7297 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa 7298 : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa 7299 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa; 7300 7301 SmallVector<SDValue, 16> Ops; 7302 7303 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7304 SmallVector<SDValue, 3> Lanes; 7305 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7306 if (Lanes[0].getValueSizeInBits() == 32) { 7307 for (unsigned I = 0; I < 3; ++I) 7308 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7309 } else { 7310 if (IsAligned) { 7311 Ops.push_back( 7312 DAG.getBitcast(MVT::i32, 7313 DAG.getBuildVector(MVT::v2f16, DL, 7314 { Lanes[0], Lanes[1] }))); 7315 Ops.push_back(Lanes[2]); 7316 } else { 7317 SDValue Elt0 = Ops.pop_back_val(); 7318 Ops.push_back( 7319 DAG.getBitcast(MVT::i32, 7320 DAG.getBuildVector(MVT::v2f16, DL, 7321 { Elt0, Lanes[0] }))); 7322 Ops.push_back( 7323 DAG.getBitcast(MVT::i32, 7324 DAG.getBuildVector(MVT::v2f16, DL, 7325 { Lanes[1], Lanes[2] }))); 7326 } 7327 } 7328 }; 7329 7330 if (Is64) 7331 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7332 else 7333 Ops.push_back(NodePtr); 7334 7335 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7336 packLanes(RayOrigin, true); 7337 packLanes(RayDir, true); 7338 packLanes(RayInvDir, false); 7339 Ops.push_back(TDescr); 7340 if (IsA16) 7341 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7342 Ops.push_back(M->getChain()); 7343 7344 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7345 MachineMemOperand *MemRef = M->getMemOperand(); 7346 DAG.setNodeMemRefs(NewNode, {MemRef}); 7347 return SDValue(NewNode, 0); 7348 } 7349 case Intrinsic::amdgcn_global_atomic_fadd: 7350 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7351 DiagnosticInfoUnsupported 7352 NoFpRet(DAG.getMachineFunction().getFunction(), 7353 "return versions of fp atomics not supported", 7354 DL.getDebugLoc(), DS_Error); 7355 DAG.getContext()->diagnose(NoFpRet); 7356 return SDValue(); 7357 } 7358 LLVM_FALLTHROUGH; 7359 case Intrinsic::amdgcn_global_atomic_fmin: 7360 case Intrinsic::amdgcn_global_atomic_fmax: 7361 case Intrinsic::amdgcn_flat_atomic_fadd: 7362 case Intrinsic::amdgcn_flat_atomic_fmin: 7363 case Intrinsic::amdgcn_flat_atomic_fmax: { 7364 MemSDNode *M = cast<MemSDNode>(Op); 7365 SDValue Ops[] = { 7366 M->getOperand(0), // Chain 7367 M->getOperand(2), // Ptr 7368 M->getOperand(3) // Value 7369 }; 7370 unsigned Opcode = 0; 7371 switch (IntrID) { 7372 case Intrinsic::amdgcn_global_atomic_fadd: 7373 case Intrinsic::amdgcn_flat_atomic_fadd: { 7374 EVT VT = Op.getOperand(3).getValueType(); 7375 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7376 DAG.getVTList(VT, MVT::Other), Ops, 7377 M->getMemOperand()); 7378 } 7379 case Intrinsic::amdgcn_global_atomic_fmin: 7380 case Intrinsic::amdgcn_flat_atomic_fmin: { 7381 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7382 break; 7383 } 7384 case Intrinsic::amdgcn_global_atomic_fmax: 7385 case Intrinsic::amdgcn_flat_atomic_fmax: { 7386 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7387 break; 7388 } 7389 default: 7390 llvm_unreachable("unhandled atomic opcode"); 7391 } 7392 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7393 M->getVTList(), Ops, M->getMemoryVT(), 7394 M->getMemOperand()); 7395 } 7396 default: 7397 7398 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7399 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7400 return lowerImage(Op, ImageDimIntr, DAG, true); 7401 7402 return SDValue(); 7403 } 7404 } 7405 7406 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7407 // dwordx4 if on SI. 7408 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7409 SDVTList VTList, 7410 ArrayRef<SDValue> Ops, EVT MemVT, 7411 MachineMemOperand *MMO, 7412 SelectionDAG &DAG) const { 7413 EVT VT = VTList.VTs[0]; 7414 EVT WidenedVT = VT; 7415 EVT WidenedMemVT = MemVT; 7416 if (!Subtarget->hasDwordx3LoadStores() && 7417 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7418 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7419 WidenedVT.getVectorElementType(), 4); 7420 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7421 WidenedMemVT.getVectorElementType(), 4); 7422 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7423 } 7424 7425 assert(VTList.NumVTs == 2); 7426 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7427 7428 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7429 WidenedMemVT, MMO); 7430 if (WidenedVT != VT) { 7431 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7432 DAG.getVectorIdxConstant(0, DL)); 7433 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7434 } 7435 return NewOp; 7436 } 7437 7438 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7439 bool ImageStore) const { 7440 EVT StoreVT = VData.getValueType(); 7441 7442 // No change for f16 and legal vector D16 types. 7443 if (!StoreVT.isVector()) 7444 return VData; 7445 7446 SDLoc DL(VData); 7447 unsigned NumElements = StoreVT.getVectorNumElements(); 7448 7449 if (Subtarget->hasUnpackedD16VMem()) { 7450 // We need to unpack the packed data to store. 7451 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7452 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7453 7454 EVT EquivStoreVT = 7455 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7456 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7457 return DAG.UnrollVectorOp(ZExt.getNode()); 7458 } 7459 7460 // The sq block of gfx8.1 does not estimate register use correctly for d16 7461 // image store instructions. The data operand is computed as if it were not a 7462 // d16 image instruction. 7463 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7464 // Bitcast to i16 7465 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7466 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7467 7468 // Decompose into scalars 7469 SmallVector<SDValue, 4> Elts; 7470 DAG.ExtractVectorElements(IntVData, Elts); 7471 7472 // Group pairs of i16 into v2i16 and bitcast to i32 7473 SmallVector<SDValue, 4> PackedElts; 7474 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7475 SDValue Pair = 7476 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7477 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7478 PackedElts.push_back(IntPair); 7479 } 7480 if ((NumElements % 2) == 1) { 7481 // Handle v3i16 7482 unsigned I = Elts.size() / 2; 7483 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7484 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7485 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7486 PackedElts.push_back(IntPair); 7487 } 7488 7489 // Pad using UNDEF 7490 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7491 7492 // Build final vector 7493 EVT VecVT = 7494 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7495 return DAG.getBuildVector(VecVT, DL, PackedElts); 7496 } 7497 7498 if (NumElements == 3) { 7499 EVT IntStoreVT = 7500 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7501 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7502 7503 EVT WidenedStoreVT = EVT::getVectorVT( 7504 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7505 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7506 WidenedStoreVT.getStoreSizeInBits()); 7507 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7508 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7509 } 7510 7511 assert(isTypeLegal(StoreVT)); 7512 return VData; 7513 } 7514 7515 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7516 SelectionDAG &DAG) const { 7517 SDLoc DL(Op); 7518 SDValue Chain = Op.getOperand(0); 7519 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7520 MachineFunction &MF = DAG.getMachineFunction(); 7521 7522 switch (IntrinsicID) { 7523 case Intrinsic::amdgcn_exp_compr: { 7524 SDValue Src0 = Op.getOperand(4); 7525 SDValue Src1 = Op.getOperand(5); 7526 // Hack around illegal type on SI by directly selecting it. 7527 if (isTypeLegal(Src0.getValueType())) 7528 return SDValue(); 7529 7530 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7531 SDValue Undef = DAG.getUNDEF(MVT::f32); 7532 const SDValue Ops[] = { 7533 Op.getOperand(2), // tgt 7534 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7535 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7536 Undef, // src2 7537 Undef, // src3 7538 Op.getOperand(7), // vm 7539 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7540 Op.getOperand(3), // en 7541 Op.getOperand(0) // Chain 7542 }; 7543 7544 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7545 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7546 } 7547 case Intrinsic::amdgcn_s_barrier: { 7548 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7549 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7550 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7551 if (WGSize <= ST.getWavefrontSize()) 7552 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7553 Op.getOperand(0)), 0); 7554 } 7555 return SDValue(); 7556 }; 7557 case Intrinsic::amdgcn_tbuffer_store: { 7558 SDValue VData = Op.getOperand(2); 7559 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7560 if (IsD16) 7561 VData = handleD16VData(VData, DAG); 7562 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7563 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7564 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7565 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7566 unsigned IdxEn = 1; 7567 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7568 IdxEn = Idx->getZExtValue() != 0; 7569 SDValue Ops[] = { 7570 Chain, 7571 VData, // vdata 7572 Op.getOperand(3), // rsrc 7573 Op.getOperand(4), // vindex 7574 Op.getOperand(5), // voffset 7575 Op.getOperand(6), // soffset 7576 Op.getOperand(7), // offset 7577 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7578 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7579 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7580 }; 7581 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7582 AMDGPUISD::TBUFFER_STORE_FORMAT; 7583 MemSDNode *M = cast<MemSDNode>(Op); 7584 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7585 M->getMemoryVT(), M->getMemOperand()); 7586 } 7587 7588 case Intrinsic::amdgcn_struct_tbuffer_store: { 7589 SDValue VData = Op.getOperand(2); 7590 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7591 if (IsD16) 7592 VData = handleD16VData(VData, DAG); 7593 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7594 SDValue Ops[] = { 7595 Chain, 7596 VData, // vdata 7597 Op.getOperand(3), // rsrc 7598 Op.getOperand(4), // vindex 7599 Offsets.first, // voffset 7600 Op.getOperand(6), // soffset 7601 Offsets.second, // offset 7602 Op.getOperand(7), // format 7603 Op.getOperand(8), // cachepolicy, swizzled buffer 7604 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7605 }; 7606 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7607 AMDGPUISD::TBUFFER_STORE_FORMAT; 7608 MemSDNode *M = cast<MemSDNode>(Op); 7609 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7610 M->getMemoryVT(), M->getMemOperand()); 7611 } 7612 7613 case Intrinsic::amdgcn_raw_tbuffer_store: { 7614 SDValue VData = Op.getOperand(2); 7615 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7616 if (IsD16) 7617 VData = handleD16VData(VData, DAG); 7618 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7619 SDValue Ops[] = { 7620 Chain, 7621 VData, // vdata 7622 Op.getOperand(3), // rsrc 7623 DAG.getConstant(0, DL, MVT::i32), // vindex 7624 Offsets.first, // voffset 7625 Op.getOperand(5), // soffset 7626 Offsets.second, // offset 7627 Op.getOperand(6), // format 7628 Op.getOperand(7), // cachepolicy, swizzled buffer 7629 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7630 }; 7631 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7632 AMDGPUISD::TBUFFER_STORE_FORMAT; 7633 MemSDNode *M = cast<MemSDNode>(Op); 7634 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7635 M->getMemoryVT(), M->getMemOperand()); 7636 } 7637 7638 case Intrinsic::amdgcn_buffer_store: 7639 case Intrinsic::amdgcn_buffer_store_format: { 7640 SDValue VData = Op.getOperand(2); 7641 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7642 if (IsD16) 7643 VData = handleD16VData(VData, DAG); 7644 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7645 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7646 unsigned IdxEn = 1; 7647 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7648 IdxEn = Idx->getZExtValue() != 0; 7649 SDValue Ops[] = { 7650 Chain, 7651 VData, 7652 Op.getOperand(3), // rsrc 7653 Op.getOperand(4), // vindex 7654 SDValue(), // voffset -- will be set by setBufferOffsets 7655 SDValue(), // soffset -- will be set by setBufferOffsets 7656 SDValue(), // offset -- will be set by setBufferOffsets 7657 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7658 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7659 }; 7660 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7661 // We don't know the offset if vindex is non-zero, so clear it. 7662 if (IdxEn) 7663 Offset = 0; 7664 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7665 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7666 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7667 MemSDNode *M = cast<MemSDNode>(Op); 7668 M->getMemOperand()->setOffset(Offset); 7669 7670 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7671 EVT VDataType = VData.getValueType().getScalarType(); 7672 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7673 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7674 7675 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7676 M->getMemoryVT(), M->getMemOperand()); 7677 } 7678 7679 case Intrinsic::amdgcn_raw_buffer_store: 7680 case Intrinsic::amdgcn_raw_buffer_store_format: { 7681 const bool IsFormat = 7682 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7683 7684 SDValue VData = Op.getOperand(2); 7685 EVT VDataVT = VData.getValueType(); 7686 EVT EltType = VDataVT.getScalarType(); 7687 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7688 if (IsD16) { 7689 VData = handleD16VData(VData, DAG); 7690 VDataVT = VData.getValueType(); 7691 } 7692 7693 if (!isTypeLegal(VDataVT)) { 7694 VData = 7695 DAG.getNode(ISD::BITCAST, DL, 7696 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7697 } 7698 7699 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7700 SDValue Ops[] = { 7701 Chain, 7702 VData, 7703 Op.getOperand(3), // rsrc 7704 DAG.getConstant(0, DL, MVT::i32), // vindex 7705 Offsets.first, // voffset 7706 Op.getOperand(5), // soffset 7707 Offsets.second, // offset 7708 Op.getOperand(6), // cachepolicy, swizzled buffer 7709 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7710 }; 7711 unsigned Opc = 7712 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7713 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7714 MemSDNode *M = cast<MemSDNode>(Op); 7715 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7716 7717 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7718 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7719 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7720 7721 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7722 M->getMemoryVT(), M->getMemOperand()); 7723 } 7724 7725 case Intrinsic::amdgcn_struct_buffer_store: 7726 case Intrinsic::amdgcn_struct_buffer_store_format: { 7727 const bool IsFormat = 7728 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7729 7730 SDValue VData = Op.getOperand(2); 7731 EVT VDataVT = VData.getValueType(); 7732 EVT EltType = VDataVT.getScalarType(); 7733 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7734 7735 if (IsD16) { 7736 VData = handleD16VData(VData, DAG); 7737 VDataVT = VData.getValueType(); 7738 } 7739 7740 if (!isTypeLegal(VDataVT)) { 7741 VData = 7742 DAG.getNode(ISD::BITCAST, DL, 7743 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7744 } 7745 7746 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7747 SDValue Ops[] = { 7748 Chain, 7749 VData, 7750 Op.getOperand(3), // rsrc 7751 Op.getOperand(4), // vindex 7752 Offsets.first, // voffset 7753 Op.getOperand(6), // soffset 7754 Offsets.second, // offset 7755 Op.getOperand(7), // cachepolicy, swizzled buffer 7756 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7757 }; 7758 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7759 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7760 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7761 MemSDNode *M = cast<MemSDNode>(Op); 7762 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7763 Ops[3])); 7764 7765 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7766 EVT VDataType = VData.getValueType().getScalarType(); 7767 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7768 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7769 7770 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7771 M->getMemoryVT(), M->getMemOperand()); 7772 } 7773 case Intrinsic::amdgcn_end_cf: 7774 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7775 Op->getOperand(2), Chain), 0); 7776 7777 default: { 7778 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7779 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7780 return lowerImage(Op, ImageDimIntr, DAG, true); 7781 7782 return Op; 7783 } 7784 } 7785 } 7786 7787 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7788 // offset (the offset that is included in bounds checking and swizzling, to be 7789 // split between the instruction's voffset and immoffset fields) and soffset 7790 // (the offset that is excluded from bounds checking and swizzling, to go in 7791 // the instruction's soffset field). This function takes the first kind of 7792 // offset and figures out how to split it between voffset and immoffset. 7793 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7794 SDValue Offset, SelectionDAG &DAG) const { 7795 SDLoc DL(Offset); 7796 const unsigned MaxImm = 4095; 7797 SDValue N0 = Offset; 7798 ConstantSDNode *C1 = nullptr; 7799 7800 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7801 N0 = SDValue(); 7802 else if (DAG.isBaseWithConstantOffset(N0)) { 7803 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7804 N0 = N0.getOperand(0); 7805 } 7806 7807 if (C1) { 7808 unsigned ImmOffset = C1->getZExtValue(); 7809 // If the immediate value is too big for the immoffset field, put the value 7810 // and -4096 into the immoffset field so that the value that is copied/added 7811 // for the voffset field is a multiple of 4096, and it stands more chance 7812 // of being CSEd with the copy/add for another similar load/store. 7813 // However, do not do that rounding down to a multiple of 4096 if that is a 7814 // negative number, as it appears to be illegal to have a negative offset 7815 // in the vgpr, even if adding the immediate offset makes it positive. 7816 unsigned Overflow = ImmOffset & ~MaxImm; 7817 ImmOffset -= Overflow; 7818 if ((int32_t)Overflow < 0) { 7819 Overflow += ImmOffset; 7820 ImmOffset = 0; 7821 } 7822 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7823 if (Overflow) { 7824 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7825 if (!N0) 7826 N0 = OverflowVal; 7827 else { 7828 SDValue Ops[] = { N0, OverflowVal }; 7829 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7830 } 7831 } 7832 } 7833 if (!N0) 7834 N0 = DAG.getConstant(0, DL, MVT::i32); 7835 if (!C1) 7836 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7837 return {N0, SDValue(C1, 0)}; 7838 } 7839 7840 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7841 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7842 // pointed to by Offsets. 7843 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7844 SelectionDAG &DAG, SDValue *Offsets, 7845 Align Alignment) const { 7846 SDLoc DL(CombinedOffset); 7847 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7848 uint32_t Imm = C->getZExtValue(); 7849 uint32_t SOffset, ImmOffset; 7850 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7851 Alignment)) { 7852 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7853 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7854 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7855 return SOffset + ImmOffset; 7856 } 7857 } 7858 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7859 SDValue N0 = CombinedOffset.getOperand(0); 7860 SDValue N1 = CombinedOffset.getOperand(1); 7861 uint32_t SOffset, ImmOffset; 7862 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7863 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7864 Subtarget, Alignment)) { 7865 Offsets[0] = N0; 7866 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7867 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7868 return 0; 7869 } 7870 } 7871 Offsets[0] = CombinedOffset; 7872 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7873 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7874 return 0; 7875 } 7876 7877 // Handle 8 bit and 16 bit buffer loads 7878 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7879 EVT LoadVT, SDLoc DL, 7880 ArrayRef<SDValue> Ops, 7881 MemSDNode *M) const { 7882 EVT IntVT = LoadVT.changeTypeToInteger(); 7883 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7884 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7885 7886 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7887 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7888 Ops, IntVT, 7889 M->getMemOperand()); 7890 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7891 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7892 7893 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7894 } 7895 7896 // Handle 8 bit and 16 bit buffer stores 7897 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7898 EVT VDataType, SDLoc DL, 7899 SDValue Ops[], 7900 MemSDNode *M) const { 7901 if (VDataType == MVT::f16) 7902 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7903 7904 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7905 Ops[1] = BufferStoreExt; 7906 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7907 AMDGPUISD::BUFFER_STORE_SHORT; 7908 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7909 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7910 M->getMemOperand()); 7911 } 7912 7913 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7914 ISD::LoadExtType ExtType, SDValue Op, 7915 const SDLoc &SL, EVT VT) { 7916 if (VT.bitsLT(Op.getValueType())) 7917 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7918 7919 switch (ExtType) { 7920 case ISD::SEXTLOAD: 7921 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7922 case ISD::ZEXTLOAD: 7923 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7924 case ISD::EXTLOAD: 7925 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7926 case ISD::NON_EXTLOAD: 7927 return Op; 7928 } 7929 7930 llvm_unreachable("invalid ext type"); 7931 } 7932 7933 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7934 SelectionDAG &DAG = DCI.DAG; 7935 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7936 return SDValue(); 7937 7938 // FIXME: Constant loads should all be marked invariant. 7939 unsigned AS = Ld->getAddressSpace(); 7940 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7941 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7942 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7943 return SDValue(); 7944 7945 // Don't do this early, since it may interfere with adjacent load merging for 7946 // illegal types. We can avoid losing alignment information for exotic types 7947 // pre-legalize. 7948 EVT MemVT = Ld->getMemoryVT(); 7949 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7950 MemVT.getSizeInBits() >= 32) 7951 return SDValue(); 7952 7953 SDLoc SL(Ld); 7954 7955 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7956 "unexpected vector extload"); 7957 7958 // TODO: Drop only high part of range. 7959 SDValue Ptr = Ld->getBasePtr(); 7960 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7961 MVT::i32, SL, Ld->getChain(), Ptr, 7962 Ld->getOffset(), 7963 Ld->getPointerInfo(), MVT::i32, 7964 Ld->getAlignment(), 7965 Ld->getMemOperand()->getFlags(), 7966 Ld->getAAInfo(), 7967 nullptr); // Drop ranges 7968 7969 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7970 if (MemVT.isFloatingPoint()) { 7971 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7972 "unexpected fp extload"); 7973 TruncVT = MemVT.changeTypeToInteger(); 7974 } 7975 7976 SDValue Cvt = NewLoad; 7977 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7978 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7979 DAG.getValueType(TruncVT)); 7980 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7981 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7982 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7983 } else { 7984 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7985 } 7986 7987 EVT VT = Ld->getValueType(0); 7988 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7989 7990 DCI.AddToWorklist(Cvt.getNode()); 7991 7992 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7993 // the appropriate extension from the 32-bit load. 7994 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7995 DCI.AddToWorklist(Cvt.getNode()); 7996 7997 // Handle conversion back to floating point if necessary. 7998 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7999 8000 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8001 } 8002 8003 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8004 SDLoc DL(Op); 8005 LoadSDNode *Load = cast<LoadSDNode>(Op); 8006 ISD::LoadExtType ExtType = Load->getExtensionType(); 8007 EVT MemVT = Load->getMemoryVT(); 8008 8009 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8010 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8011 return SDValue(); 8012 8013 // FIXME: Copied from PPC 8014 // First, load into 32 bits, then truncate to 1 bit. 8015 8016 SDValue Chain = Load->getChain(); 8017 SDValue BasePtr = Load->getBasePtr(); 8018 MachineMemOperand *MMO = Load->getMemOperand(); 8019 8020 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8021 8022 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8023 BasePtr, RealMemVT, MMO); 8024 8025 if (!MemVT.isVector()) { 8026 SDValue Ops[] = { 8027 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8028 NewLD.getValue(1) 8029 }; 8030 8031 return DAG.getMergeValues(Ops, DL); 8032 } 8033 8034 SmallVector<SDValue, 3> Elts; 8035 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8036 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8037 DAG.getConstant(I, DL, MVT::i32)); 8038 8039 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8040 } 8041 8042 SDValue Ops[] = { 8043 DAG.getBuildVector(MemVT, DL, Elts), 8044 NewLD.getValue(1) 8045 }; 8046 8047 return DAG.getMergeValues(Ops, DL); 8048 } 8049 8050 if (!MemVT.isVector()) 8051 return SDValue(); 8052 8053 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8054 "Custom lowering for non-i32 vectors hasn't been implemented."); 8055 8056 unsigned Alignment = Load->getAlignment(); 8057 unsigned AS = Load->getAddressSpace(); 8058 if (Subtarget->hasLDSMisalignedBug() && 8059 AS == AMDGPUAS::FLAT_ADDRESS && 8060 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8061 return SplitVectorLoad(Op, DAG); 8062 } 8063 8064 MachineFunction &MF = DAG.getMachineFunction(); 8065 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8066 // If there is a possibilty that flat instruction access scratch memory 8067 // then we need to use the same legalization rules we use for private. 8068 if (AS == AMDGPUAS::FLAT_ADDRESS && 8069 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8070 AS = MFI->hasFlatScratchInit() ? 8071 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8072 8073 unsigned NumElements = MemVT.getVectorNumElements(); 8074 8075 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8076 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8077 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8078 if (MemVT.isPow2VectorType()) 8079 return SDValue(); 8080 return WidenOrSplitVectorLoad(Op, DAG); 8081 } 8082 // Non-uniform loads will be selected to MUBUF instructions, so they 8083 // have the same legalization requirements as global and private 8084 // loads. 8085 // 8086 } 8087 8088 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8089 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8090 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8091 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8092 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8093 Alignment >= 4 && NumElements < 32) { 8094 if (MemVT.isPow2VectorType()) 8095 return SDValue(); 8096 return WidenOrSplitVectorLoad(Op, DAG); 8097 } 8098 // Non-uniform loads will be selected to MUBUF instructions, so they 8099 // have the same legalization requirements as global and private 8100 // loads. 8101 // 8102 } 8103 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8104 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8105 AS == AMDGPUAS::GLOBAL_ADDRESS || 8106 AS == AMDGPUAS::FLAT_ADDRESS) { 8107 if (NumElements > 4) 8108 return SplitVectorLoad(Op, DAG); 8109 // v3 loads not supported on SI. 8110 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8111 return WidenOrSplitVectorLoad(Op, DAG); 8112 8113 // v3 and v4 loads are supported for private and global memory. 8114 return SDValue(); 8115 } 8116 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8117 // Depending on the setting of the private_element_size field in the 8118 // resource descriptor, we can only make private accesses up to a certain 8119 // size. 8120 switch (Subtarget->getMaxPrivateElementSize()) { 8121 case 4: { 8122 SDValue Ops[2]; 8123 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8124 return DAG.getMergeValues(Ops, DL); 8125 } 8126 case 8: 8127 if (NumElements > 2) 8128 return SplitVectorLoad(Op, DAG); 8129 return SDValue(); 8130 case 16: 8131 // Same as global/flat 8132 if (NumElements > 4) 8133 return SplitVectorLoad(Op, DAG); 8134 // v3 loads not supported on SI. 8135 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8136 return WidenOrSplitVectorLoad(Op, DAG); 8137 8138 return SDValue(); 8139 default: 8140 llvm_unreachable("unsupported private_element_size"); 8141 } 8142 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8143 // Use ds_read_b128 or ds_read_b96 when possible. 8144 if (Subtarget->hasDS96AndDS128() && 8145 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8146 MemVT.getStoreSize() == 12) && 8147 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8148 Load->getAlign())) 8149 return SDValue(); 8150 8151 if (NumElements > 2) 8152 return SplitVectorLoad(Op, DAG); 8153 8154 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8155 // address is negative, then the instruction is incorrectly treated as 8156 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8157 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8158 // load later in the SILoadStoreOptimizer. 8159 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8160 NumElements == 2 && MemVT.getStoreSize() == 8 && 8161 Load->getAlignment() < 8) { 8162 return SplitVectorLoad(Op, DAG); 8163 } 8164 } 8165 8166 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8167 MemVT, *Load->getMemOperand())) { 8168 SDValue Ops[2]; 8169 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8170 return DAG.getMergeValues(Ops, DL); 8171 } 8172 8173 return SDValue(); 8174 } 8175 8176 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8177 EVT VT = Op.getValueType(); 8178 assert(VT.getSizeInBits() == 64); 8179 8180 SDLoc DL(Op); 8181 SDValue Cond = Op.getOperand(0); 8182 8183 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8184 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8185 8186 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8187 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8188 8189 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8190 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8191 8192 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8193 8194 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8195 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8196 8197 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8198 8199 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8200 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8201 } 8202 8203 // Catch division cases where we can use shortcuts with rcp and rsq 8204 // instructions. 8205 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8206 SelectionDAG &DAG) const { 8207 SDLoc SL(Op); 8208 SDValue LHS = Op.getOperand(0); 8209 SDValue RHS = Op.getOperand(1); 8210 EVT VT = Op.getValueType(); 8211 const SDNodeFlags Flags = Op->getFlags(); 8212 8213 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8214 8215 // Without !fpmath accuracy information, we can't do more because we don't 8216 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8217 if (!AllowInaccurateRcp) 8218 return SDValue(); 8219 8220 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8221 if (CLHS->isExactlyValue(1.0)) { 8222 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8223 // the CI documentation has a worst case error of 1 ulp. 8224 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8225 // use it as long as we aren't trying to use denormals. 8226 // 8227 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8228 8229 // 1.0 / sqrt(x) -> rsq(x) 8230 8231 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8232 // error seems really high at 2^29 ULP. 8233 if (RHS.getOpcode() == ISD::FSQRT) 8234 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8235 8236 // 1.0 / x -> rcp(x) 8237 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8238 } 8239 8240 // Same as for 1.0, but expand the sign out of the constant. 8241 if (CLHS->isExactlyValue(-1.0)) { 8242 // -1.0 / x -> rcp (fneg x) 8243 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8244 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8245 } 8246 } 8247 8248 // Turn into multiply by the reciprocal. 8249 // x / y -> x * (1.0 / y) 8250 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8251 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8252 } 8253 8254 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8255 SelectionDAG &DAG) const { 8256 SDLoc SL(Op); 8257 SDValue X = Op.getOperand(0); 8258 SDValue Y = Op.getOperand(1); 8259 EVT VT = Op.getValueType(); 8260 const SDNodeFlags Flags = Op->getFlags(); 8261 8262 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8263 DAG.getTarget().Options.UnsafeFPMath; 8264 if (!AllowInaccurateDiv) 8265 return SDValue(); 8266 8267 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8268 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8269 8270 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8271 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8272 8273 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8274 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8275 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8276 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8277 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8278 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8279 } 8280 8281 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8282 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8283 SDNodeFlags Flags) { 8284 if (GlueChain->getNumValues() <= 1) { 8285 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8286 } 8287 8288 assert(GlueChain->getNumValues() == 3); 8289 8290 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8291 switch (Opcode) { 8292 default: llvm_unreachable("no chain equivalent for opcode"); 8293 case ISD::FMUL: 8294 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8295 break; 8296 } 8297 8298 return DAG.getNode(Opcode, SL, VTList, 8299 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8300 Flags); 8301 } 8302 8303 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8304 EVT VT, SDValue A, SDValue B, SDValue C, 8305 SDValue GlueChain, SDNodeFlags Flags) { 8306 if (GlueChain->getNumValues() <= 1) { 8307 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8308 } 8309 8310 assert(GlueChain->getNumValues() == 3); 8311 8312 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8313 switch (Opcode) { 8314 default: llvm_unreachable("no chain equivalent for opcode"); 8315 case ISD::FMA: 8316 Opcode = AMDGPUISD::FMA_W_CHAIN; 8317 break; 8318 } 8319 8320 return DAG.getNode(Opcode, SL, VTList, 8321 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8322 Flags); 8323 } 8324 8325 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8326 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8327 return FastLowered; 8328 8329 SDLoc SL(Op); 8330 SDValue Src0 = Op.getOperand(0); 8331 SDValue Src1 = Op.getOperand(1); 8332 8333 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8334 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8335 8336 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8337 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8338 8339 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8340 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8341 8342 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8343 } 8344 8345 // Faster 2.5 ULP division that does not support denormals. 8346 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8347 SDLoc SL(Op); 8348 SDValue LHS = Op.getOperand(1); 8349 SDValue RHS = Op.getOperand(2); 8350 8351 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8352 8353 const APFloat K0Val(BitsToFloat(0x6f800000)); 8354 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8355 8356 const APFloat K1Val(BitsToFloat(0x2f800000)); 8357 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8358 8359 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8360 8361 EVT SetCCVT = 8362 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8363 8364 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8365 8366 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8367 8368 // TODO: Should this propagate fast-math-flags? 8369 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8370 8371 // rcp does not support denormals. 8372 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8373 8374 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8375 8376 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8377 } 8378 8379 // Returns immediate value for setting the F32 denorm mode when using the 8380 // S_DENORM_MODE instruction. 8381 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8382 const SDLoc &SL, const GCNSubtarget *ST) { 8383 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8384 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8385 ? FP_DENORM_FLUSH_NONE 8386 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8387 8388 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8389 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8390 } 8391 8392 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8393 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8394 return FastLowered; 8395 8396 // The selection matcher assumes anything with a chain selecting to a 8397 // mayRaiseFPException machine instruction. Since we're introducing a chain 8398 // here, we need to explicitly report nofpexcept for the regular fdiv 8399 // lowering. 8400 SDNodeFlags Flags = Op->getFlags(); 8401 Flags.setNoFPExcept(true); 8402 8403 SDLoc SL(Op); 8404 SDValue LHS = Op.getOperand(0); 8405 SDValue RHS = Op.getOperand(1); 8406 8407 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8408 8409 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8410 8411 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8412 {RHS, RHS, LHS}, Flags); 8413 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8414 {LHS, RHS, LHS}, Flags); 8415 8416 // Denominator is scaled to not be denormal, so using rcp is ok. 8417 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8418 DenominatorScaled, Flags); 8419 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8420 DenominatorScaled, Flags); 8421 8422 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8423 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8424 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8425 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8426 8427 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8428 8429 if (!HasFP32Denormals) { 8430 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8431 // lowering. The chain dependence is insufficient, and we need glue. We do 8432 // not need the glue variants in a strictfp function. 8433 8434 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8435 8436 SDNode *EnableDenorm; 8437 if (Subtarget->hasDenormModeInst()) { 8438 const SDValue EnableDenormValue = 8439 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8440 8441 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8442 DAG.getEntryNode(), EnableDenormValue).getNode(); 8443 } else { 8444 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8445 SL, MVT::i32); 8446 EnableDenorm = 8447 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8448 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8449 } 8450 8451 SDValue Ops[3] = { 8452 NegDivScale0, 8453 SDValue(EnableDenorm, 0), 8454 SDValue(EnableDenorm, 1) 8455 }; 8456 8457 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8458 } 8459 8460 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8461 ApproxRcp, One, NegDivScale0, Flags); 8462 8463 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8464 ApproxRcp, Fma0, Flags); 8465 8466 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8467 Fma1, Fma1, Flags); 8468 8469 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8470 NumeratorScaled, Mul, Flags); 8471 8472 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8473 Fma2, Fma1, Mul, Fma2, Flags); 8474 8475 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8476 NumeratorScaled, Fma3, Flags); 8477 8478 if (!HasFP32Denormals) { 8479 SDNode *DisableDenorm; 8480 if (Subtarget->hasDenormModeInst()) { 8481 const SDValue DisableDenormValue = 8482 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8483 8484 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8485 Fma4.getValue(1), DisableDenormValue, 8486 Fma4.getValue(2)).getNode(); 8487 } else { 8488 const SDValue DisableDenormValue = 8489 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8490 8491 DisableDenorm = DAG.getMachineNode( 8492 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8493 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8494 } 8495 8496 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8497 SDValue(DisableDenorm, 0), DAG.getRoot()); 8498 DAG.setRoot(OutputChain); 8499 } 8500 8501 SDValue Scale = NumeratorScaled.getValue(1); 8502 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8503 {Fma4, Fma1, Fma3, Scale}, Flags); 8504 8505 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8506 } 8507 8508 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8509 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8510 return FastLowered; 8511 8512 SDLoc SL(Op); 8513 SDValue X = Op.getOperand(0); 8514 SDValue Y = Op.getOperand(1); 8515 8516 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8517 8518 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8519 8520 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8521 8522 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8523 8524 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8525 8526 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8527 8528 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8529 8530 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8531 8532 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8533 8534 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8535 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8536 8537 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8538 NegDivScale0, Mul, DivScale1); 8539 8540 SDValue Scale; 8541 8542 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8543 // Workaround a hardware bug on SI where the condition output from div_scale 8544 // is not usable. 8545 8546 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8547 8548 // Figure out if the scale to use for div_fmas. 8549 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8550 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8551 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8552 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8553 8554 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8555 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8556 8557 SDValue Scale0Hi 8558 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8559 SDValue Scale1Hi 8560 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8561 8562 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8563 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8564 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8565 } else { 8566 Scale = DivScale1.getValue(1); 8567 } 8568 8569 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8570 Fma4, Fma3, Mul, Scale); 8571 8572 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8573 } 8574 8575 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8576 EVT VT = Op.getValueType(); 8577 8578 if (VT == MVT::f32) 8579 return LowerFDIV32(Op, DAG); 8580 8581 if (VT == MVT::f64) 8582 return LowerFDIV64(Op, DAG); 8583 8584 if (VT == MVT::f16) 8585 return LowerFDIV16(Op, DAG); 8586 8587 llvm_unreachable("Unexpected type for fdiv"); 8588 } 8589 8590 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8591 SDLoc DL(Op); 8592 StoreSDNode *Store = cast<StoreSDNode>(Op); 8593 EVT VT = Store->getMemoryVT(); 8594 8595 if (VT == MVT::i1) { 8596 return DAG.getTruncStore(Store->getChain(), DL, 8597 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8598 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8599 } 8600 8601 assert(VT.isVector() && 8602 Store->getValue().getValueType().getScalarType() == MVT::i32); 8603 8604 unsigned AS = Store->getAddressSpace(); 8605 if (Subtarget->hasLDSMisalignedBug() && 8606 AS == AMDGPUAS::FLAT_ADDRESS && 8607 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8608 return SplitVectorStore(Op, DAG); 8609 } 8610 8611 MachineFunction &MF = DAG.getMachineFunction(); 8612 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8613 // If there is a possibilty that flat instruction access scratch memory 8614 // then we need to use the same legalization rules we use for private. 8615 if (AS == AMDGPUAS::FLAT_ADDRESS && 8616 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8617 AS = MFI->hasFlatScratchInit() ? 8618 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8619 8620 unsigned NumElements = VT.getVectorNumElements(); 8621 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8622 AS == AMDGPUAS::FLAT_ADDRESS) { 8623 if (NumElements > 4) 8624 return SplitVectorStore(Op, DAG); 8625 // v3 stores not supported on SI. 8626 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8627 return SplitVectorStore(Op, DAG); 8628 8629 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8630 VT, *Store->getMemOperand())) 8631 return expandUnalignedStore(Store, DAG); 8632 8633 return SDValue(); 8634 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8635 switch (Subtarget->getMaxPrivateElementSize()) { 8636 case 4: 8637 return scalarizeVectorStore(Store, DAG); 8638 case 8: 8639 if (NumElements > 2) 8640 return SplitVectorStore(Op, DAG); 8641 return SDValue(); 8642 case 16: 8643 if (NumElements > 4 || 8644 (NumElements == 3 && !Subtarget->enableFlatScratch())) 8645 return SplitVectorStore(Op, DAG); 8646 return SDValue(); 8647 default: 8648 llvm_unreachable("unsupported private_element_size"); 8649 } 8650 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8651 // Use ds_write_b128 or ds_write_b96 when possible. 8652 if (Subtarget->hasDS96AndDS128() && 8653 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8654 (VT.getStoreSize() == 12)) && 8655 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8656 Store->getAlign())) 8657 return SDValue(); 8658 8659 if (NumElements > 2) 8660 return SplitVectorStore(Op, DAG); 8661 8662 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8663 // address is negative, then the instruction is incorrectly treated as 8664 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8665 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8666 // store later in the SILoadStoreOptimizer. 8667 if (!Subtarget->hasUsableDSOffset() && 8668 NumElements == 2 && VT.getStoreSize() == 8 && 8669 Store->getAlignment() < 8) { 8670 return SplitVectorStore(Op, DAG); 8671 } 8672 8673 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8674 VT, *Store->getMemOperand())) { 8675 if (VT.isVector()) 8676 return SplitVectorStore(Op, DAG); 8677 return expandUnalignedStore(Store, DAG); 8678 } 8679 8680 return SDValue(); 8681 } else { 8682 llvm_unreachable("unhandled address space"); 8683 } 8684 } 8685 8686 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8687 SDLoc DL(Op); 8688 EVT VT = Op.getValueType(); 8689 SDValue Arg = Op.getOperand(0); 8690 SDValue TrigVal; 8691 8692 // Propagate fast-math flags so that the multiply we introduce can be folded 8693 // if Arg is already the result of a multiply by constant. 8694 auto Flags = Op->getFlags(); 8695 8696 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8697 8698 if (Subtarget->hasTrigReducedRange()) { 8699 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8700 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8701 } else { 8702 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8703 } 8704 8705 switch (Op.getOpcode()) { 8706 case ISD::FCOS: 8707 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8708 case ISD::FSIN: 8709 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8710 default: 8711 llvm_unreachable("Wrong trig opcode"); 8712 } 8713 } 8714 8715 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8716 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8717 assert(AtomicNode->isCompareAndSwap()); 8718 unsigned AS = AtomicNode->getAddressSpace(); 8719 8720 // No custom lowering required for local address space 8721 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8722 return Op; 8723 8724 // Non-local address space requires custom lowering for atomic compare 8725 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8726 SDLoc DL(Op); 8727 SDValue ChainIn = Op.getOperand(0); 8728 SDValue Addr = Op.getOperand(1); 8729 SDValue Old = Op.getOperand(2); 8730 SDValue New = Op.getOperand(3); 8731 EVT VT = Op.getValueType(); 8732 MVT SimpleVT = VT.getSimpleVT(); 8733 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8734 8735 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8736 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8737 8738 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8739 Ops, VT, AtomicNode->getMemOperand()); 8740 } 8741 8742 //===----------------------------------------------------------------------===// 8743 // Custom DAG optimizations 8744 //===----------------------------------------------------------------------===// 8745 8746 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8747 DAGCombinerInfo &DCI) const { 8748 EVT VT = N->getValueType(0); 8749 EVT ScalarVT = VT.getScalarType(); 8750 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8751 return SDValue(); 8752 8753 SelectionDAG &DAG = DCI.DAG; 8754 SDLoc DL(N); 8755 8756 SDValue Src = N->getOperand(0); 8757 EVT SrcVT = Src.getValueType(); 8758 8759 // TODO: We could try to match extracting the higher bytes, which would be 8760 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8761 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8762 // about in practice. 8763 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8764 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8765 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8766 DCI.AddToWorklist(Cvt.getNode()); 8767 8768 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8769 if (ScalarVT != MVT::f32) { 8770 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8771 DAG.getTargetConstant(0, DL, MVT::i32)); 8772 } 8773 return Cvt; 8774 } 8775 } 8776 8777 return SDValue(); 8778 } 8779 8780 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8781 8782 // This is a variant of 8783 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8784 // 8785 // The normal DAG combiner will do this, but only if the add has one use since 8786 // that would increase the number of instructions. 8787 // 8788 // This prevents us from seeing a constant offset that can be folded into a 8789 // memory instruction's addressing mode. If we know the resulting add offset of 8790 // a pointer can be folded into an addressing offset, we can replace the pointer 8791 // operand with the add of new constant offset. This eliminates one of the uses, 8792 // and may allow the remaining use to also be simplified. 8793 // 8794 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8795 unsigned AddrSpace, 8796 EVT MemVT, 8797 DAGCombinerInfo &DCI) const { 8798 SDValue N0 = N->getOperand(0); 8799 SDValue N1 = N->getOperand(1); 8800 8801 // We only do this to handle cases where it's profitable when there are 8802 // multiple uses of the add, so defer to the standard combine. 8803 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8804 N0->hasOneUse()) 8805 return SDValue(); 8806 8807 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8808 if (!CN1) 8809 return SDValue(); 8810 8811 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8812 if (!CAdd) 8813 return SDValue(); 8814 8815 // If the resulting offset is too large, we can't fold it into the addressing 8816 // mode offset. 8817 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8818 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8819 8820 AddrMode AM; 8821 AM.HasBaseReg = true; 8822 AM.BaseOffs = Offset.getSExtValue(); 8823 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8824 return SDValue(); 8825 8826 SelectionDAG &DAG = DCI.DAG; 8827 SDLoc SL(N); 8828 EVT VT = N->getValueType(0); 8829 8830 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8831 SDValue COffset = DAG.getConstant(Offset, SL, VT); 8832 8833 SDNodeFlags Flags; 8834 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8835 (N0.getOpcode() == ISD::OR || 8836 N0->getFlags().hasNoUnsignedWrap())); 8837 8838 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8839 } 8840 8841 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 8842 /// by the chain and intrinsic ID. Theoretically we would also need to check the 8843 /// specific intrinsic, but they all place the pointer operand first. 8844 static unsigned getBasePtrIndex(const MemSDNode *N) { 8845 switch (N->getOpcode()) { 8846 case ISD::STORE: 8847 case ISD::INTRINSIC_W_CHAIN: 8848 case ISD::INTRINSIC_VOID: 8849 return 2; 8850 default: 8851 return 1; 8852 } 8853 } 8854 8855 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8856 DAGCombinerInfo &DCI) const { 8857 SelectionDAG &DAG = DCI.DAG; 8858 SDLoc SL(N); 8859 8860 unsigned PtrIdx = getBasePtrIndex(N); 8861 SDValue Ptr = N->getOperand(PtrIdx); 8862 8863 // TODO: We could also do this for multiplies. 8864 if (Ptr.getOpcode() == ISD::SHL) { 8865 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8866 N->getMemoryVT(), DCI); 8867 if (NewPtr) { 8868 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8869 8870 NewOps[PtrIdx] = NewPtr; 8871 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8872 } 8873 } 8874 8875 return SDValue(); 8876 } 8877 8878 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8879 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8880 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8881 (Opc == ISD::XOR && Val == 0); 8882 } 8883 8884 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8885 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8886 // integer combine opportunities since most 64-bit operations are decomposed 8887 // this way. TODO: We won't want this for SALU especially if it is an inline 8888 // immediate. 8889 SDValue SITargetLowering::splitBinaryBitConstantOp( 8890 DAGCombinerInfo &DCI, 8891 const SDLoc &SL, 8892 unsigned Opc, SDValue LHS, 8893 const ConstantSDNode *CRHS) const { 8894 uint64_t Val = CRHS->getZExtValue(); 8895 uint32_t ValLo = Lo_32(Val); 8896 uint32_t ValHi = Hi_32(Val); 8897 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8898 8899 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8900 bitOpWithConstantIsReducible(Opc, ValHi)) || 8901 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8902 // If we need to materialize a 64-bit immediate, it will be split up later 8903 // anyway. Avoid creating the harder to understand 64-bit immediate 8904 // materialization. 8905 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8906 } 8907 8908 return SDValue(); 8909 } 8910 8911 // Returns true if argument is a boolean value which is not serialized into 8912 // memory or argument and does not require v_cndmask_b32 to be deserialized. 8913 static bool isBoolSGPR(SDValue V) { 8914 if (V.getValueType() != MVT::i1) 8915 return false; 8916 switch (V.getOpcode()) { 8917 default: 8918 break; 8919 case ISD::SETCC: 8920 case AMDGPUISD::FP_CLASS: 8921 return true; 8922 case ISD::AND: 8923 case ISD::OR: 8924 case ISD::XOR: 8925 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 8926 } 8927 return false; 8928 } 8929 8930 // If a constant has all zeroes or all ones within each byte return it. 8931 // Otherwise return 0. 8932 static uint32_t getConstantPermuteMask(uint32_t C) { 8933 // 0xff for any zero byte in the mask 8934 uint32_t ZeroByteMask = 0; 8935 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8936 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8937 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8938 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8939 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8940 if ((NonZeroByteMask & C) != NonZeroByteMask) 8941 return 0; // Partial bytes selected. 8942 return C; 8943 } 8944 8945 // Check if a node selects whole bytes from its operand 0 starting at a byte 8946 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8947 // or -1 if not succeeded. 8948 // Note byte select encoding: 8949 // value 0-3 selects corresponding source byte; 8950 // value 0xc selects zero; 8951 // value 0xff selects 0xff. 8952 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8953 assert(V.getValueSizeInBits() == 32); 8954 8955 if (V.getNumOperands() != 2) 8956 return ~0; 8957 8958 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8959 if (!N1) 8960 return ~0; 8961 8962 uint32_t C = N1->getZExtValue(); 8963 8964 switch (V.getOpcode()) { 8965 default: 8966 break; 8967 case ISD::AND: 8968 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8969 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8970 } 8971 break; 8972 8973 case ISD::OR: 8974 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8975 return (0x03020100 & ~ConstMask) | ConstMask; 8976 } 8977 break; 8978 8979 case ISD::SHL: 8980 if (C % 8) 8981 return ~0; 8982 8983 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8984 8985 case ISD::SRL: 8986 if (C % 8) 8987 return ~0; 8988 8989 return uint32_t(0x0c0c0c0c03020100ull >> C); 8990 } 8991 8992 return ~0; 8993 } 8994 8995 SDValue SITargetLowering::performAndCombine(SDNode *N, 8996 DAGCombinerInfo &DCI) const { 8997 if (DCI.isBeforeLegalize()) 8998 return SDValue(); 8999 9000 SelectionDAG &DAG = DCI.DAG; 9001 EVT VT = N->getValueType(0); 9002 SDValue LHS = N->getOperand(0); 9003 SDValue RHS = N->getOperand(1); 9004 9005 9006 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9007 if (VT == MVT::i64 && CRHS) { 9008 if (SDValue Split 9009 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9010 return Split; 9011 } 9012 9013 if (CRHS && VT == MVT::i32) { 9014 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9015 // nb = number of trailing zeroes in mask 9016 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9017 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9018 uint64_t Mask = CRHS->getZExtValue(); 9019 unsigned Bits = countPopulation(Mask); 9020 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9021 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9022 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9023 unsigned Shift = CShift->getZExtValue(); 9024 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9025 unsigned Offset = NB + Shift; 9026 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9027 SDLoc SL(N); 9028 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9029 LHS->getOperand(0), 9030 DAG.getConstant(Offset, SL, MVT::i32), 9031 DAG.getConstant(Bits, SL, MVT::i32)); 9032 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9033 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9034 DAG.getValueType(NarrowVT)); 9035 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9036 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9037 return Shl; 9038 } 9039 } 9040 } 9041 9042 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9043 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9044 isa<ConstantSDNode>(LHS.getOperand(2))) { 9045 uint32_t Sel = getConstantPermuteMask(Mask); 9046 if (!Sel) 9047 return SDValue(); 9048 9049 // Select 0xc for all zero bytes 9050 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9051 SDLoc DL(N); 9052 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9053 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9054 } 9055 } 9056 9057 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9058 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9059 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9060 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9061 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9062 9063 SDValue X = LHS.getOperand(0); 9064 SDValue Y = RHS.getOperand(0); 9065 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9066 return SDValue(); 9067 9068 if (LCC == ISD::SETO) { 9069 if (X != LHS.getOperand(1)) 9070 return SDValue(); 9071 9072 if (RCC == ISD::SETUNE) { 9073 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9074 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9075 return SDValue(); 9076 9077 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9078 SIInstrFlags::N_SUBNORMAL | 9079 SIInstrFlags::N_ZERO | 9080 SIInstrFlags::P_ZERO | 9081 SIInstrFlags::P_SUBNORMAL | 9082 SIInstrFlags::P_NORMAL; 9083 9084 static_assert(((~(SIInstrFlags::S_NAN | 9085 SIInstrFlags::Q_NAN | 9086 SIInstrFlags::N_INFINITY | 9087 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9088 "mask not equal"); 9089 9090 SDLoc DL(N); 9091 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9092 X, DAG.getConstant(Mask, DL, MVT::i32)); 9093 } 9094 } 9095 } 9096 9097 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9098 std::swap(LHS, RHS); 9099 9100 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9101 RHS.hasOneUse()) { 9102 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9103 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9104 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9105 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9106 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9107 (RHS.getOperand(0) == LHS.getOperand(0) && 9108 LHS.getOperand(0) == LHS.getOperand(1))) { 9109 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9110 unsigned NewMask = LCC == ISD::SETO ? 9111 Mask->getZExtValue() & ~OrdMask : 9112 Mask->getZExtValue() & OrdMask; 9113 9114 SDLoc DL(N); 9115 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9116 DAG.getConstant(NewMask, DL, MVT::i32)); 9117 } 9118 } 9119 9120 if (VT == MVT::i32 && 9121 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9122 // and x, (sext cc from i1) => select cc, x, 0 9123 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9124 std::swap(LHS, RHS); 9125 if (isBoolSGPR(RHS.getOperand(0))) 9126 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9127 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9128 } 9129 9130 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9131 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9132 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9133 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9134 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9135 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9136 if (LHSMask != ~0u && RHSMask != ~0u) { 9137 // Canonicalize the expression in an attempt to have fewer unique masks 9138 // and therefore fewer registers used to hold the masks. 9139 if (LHSMask > RHSMask) { 9140 std::swap(LHSMask, RHSMask); 9141 std::swap(LHS, RHS); 9142 } 9143 9144 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9145 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9146 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9147 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9148 9149 // Check of we need to combine values from two sources within a byte. 9150 if (!(LHSUsedLanes & RHSUsedLanes) && 9151 // If we select high and lower word keep it for SDWA. 9152 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9153 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9154 // Each byte in each mask is either selector mask 0-3, or has higher 9155 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9156 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9157 // mask which is not 0xff wins. By anding both masks we have a correct 9158 // result except that 0x0c shall be corrected to give 0x0c only. 9159 uint32_t Mask = LHSMask & RHSMask; 9160 for (unsigned I = 0; I < 32; I += 8) { 9161 uint32_t ByteSel = 0xff << I; 9162 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9163 Mask &= (0x0c << I) & 0xffffffff; 9164 } 9165 9166 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9167 // or 0x0c. 9168 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9169 SDLoc DL(N); 9170 9171 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9172 LHS.getOperand(0), RHS.getOperand(0), 9173 DAG.getConstant(Sel, DL, MVT::i32)); 9174 } 9175 } 9176 } 9177 9178 return SDValue(); 9179 } 9180 9181 SDValue SITargetLowering::performOrCombine(SDNode *N, 9182 DAGCombinerInfo &DCI) const { 9183 SelectionDAG &DAG = DCI.DAG; 9184 SDValue LHS = N->getOperand(0); 9185 SDValue RHS = N->getOperand(1); 9186 9187 EVT VT = N->getValueType(0); 9188 if (VT == MVT::i1) { 9189 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9190 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9191 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9192 SDValue Src = LHS.getOperand(0); 9193 if (Src != RHS.getOperand(0)) 9194 return SDValue(); 9195 9196 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9197 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9198 if (!CLHS || !CRHS) 9199 return SDValue(); 9200 9201 // Only 10 bits are used. 9202 static const uint32_t MaxMask = 0x3ff; 9203 9204 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9205 SDLoc DL(N); 9206 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9207 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9208 } 9209 9210 return SDValue(); 9211 } 9212 9213 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9214 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9215 LHS.getOpcode() == AMDGPUISD::PERM && 9216 isa<ConstantSDNode>(LHS.getOperand(2))) { 9217 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9218 if (!Sel) 9219 return SDValue(); 9220 9221 Sel |= LHS.getConstantOperandVal(2); 9222 SDLoc DL(N); 9223 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9224 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9225 } 9226 9227 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9228 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9229 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9230 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9231 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9232 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9233 if (LHSMask != ~0u && RHSMask != ~0u) { 9234 // Canonicalize the expression in an attempt to have fewer unique masks 9235 // and therefore fewer registers used to hold the masks. 9236 if (LHSMask > RHSMask) { 9237 std::swap(LHSMask, RHSMask); 9238 std::swap(LHS, RHS); 9239 } 9240 9241 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9242 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9243 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9244 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9245 9246 // Check of we need to combine values from two sources within a byte. 9247 if (!(LHSUsedLanes & RHSUsedLanes) && 9248 // If we select high and lower word keep it for SDWA. 9249 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9250 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9251 // Kill zero bytes selected by other mask. Zero value is 0xc. 9252 LHSMask &= ~RHSUsedLanes; 9253 RHSMask &= ~LHSUsedLanes; 9254 // Add 4 to each active LHS lane 9255 LHSMask |= LHSUsedLanes & 0x04040404; 9256 // Combine masks 9257 uint32_t Sel = LHSMask | RHSMask; 9258 SDLoc DL(N); 9259 9260 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9261 LHS.getOperand(0), RHS.getOperand(0), 9262 DAG.getConstant(Sel, DL, MVT::i32)); 9263 } 9264 } 9265 } 9266 9267 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9268 return SDValue(); 9269 9270 // TODO: This could be a generic combine with a predicate for extracting the 9271 // high half of an integer being free. 9272 9273 // (or i64:x, (zero_extend i32:y)) -> 9274 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9275 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9276 RHS.getOpcode() != ISD::ZERO_EXTEND) 9277 std::swap(LHS, RHS); 9278 9279 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9280 SDValue ExtSrc = RHS.getOperand(0); 9281 EVT SrcVT = ExtSrc.getValueType(); 9282 if (SrcVT == MVT::i32) { 9283 SDLoc SL(N); 9284 SDValue LowLHS, HiBits; 9285 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9286 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9287 9288 DCI.AddToWorklist(LowOr.getNode()); 9289 DCI.AddToWorklist(HiBits.getNode()); 9290 9291 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9292 LowOr, HiBits); 9293 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9294 } 9295 } 9296 9297 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9298 if (CRHS) { 9299 if (SDValue Split 9300 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9301 return Split; 9302 } 9303 9304 return SDValue(); 9305 } 9306 9307 SDValue SITargetLowering::performXorCombine(SDNode *N, 9308 DAGCombinerInfo &DCI) const { 9309 EVT VT = N->getValueType(0); 9310 if (VT != MVT::i64) 9311 return SDValue(); 9312 9313 SDValue LHS = N->getOperand(0); 9314 SDValue RHS = N->getOperand(1); 9315 9316 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9317 if (CRHS) { 9318 if (SDValue Split 9319 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9320 return Split; 9321 } 9322 9323 return SDValue(); 9324 } 9325 9326 // Instructions that will be lowered with a final instruction that zeros the 9327 // high result bits. 9328 // XXX - probably only need to list legal operations. 9329 static bool fp16SrcZerosHighBits(unsigned Opc) { 9330 switch (Opc) { 9331 case ISD::FADD: 9332 case ISD::FSUB: 9333 case ISD::FMUL: 9334 case ISD::FDIV: 9335 case ISD::FREM: 9336 case ISD::FMA: 9337 case ISD::FMAD: 9338 case ISD::FCANONICALIZE: 9339 case ISD::FP_ROUND: 9340 case ISD::UINT_TO_FP: 9341 case ISD::SINT_TO_FP: 9342 case ISD::FABS: 9343 // Fabs is lowered to a bit operation, but it's an and which will clear the 9344 // high bits anyway. 9345 case ISD::FSQRT: 9346 case ISD::FSIN: 9347 case ISD::FCOS: 9348 case ISD::FPOWI: 9349 case ISD::FPOW: 9350 case ISD::FLOG: 9351 case ISD::FLOG2: 9352 case ISD::FLOG10: 9353 case ISD::FEXP: 9354 case ISD::FEXP2: 9355 case ISD::FCEIL: 9356 case ISD::FTRUNC: 9357 case ISD::FRINT: 9358 case ISD::FNEARBYINT: 9359 case ISD::FROUND: 9360 case ISD::FFLOOR: 9361 case ISD::FMINNUM: 9362 case ISD::FMAXNUM: 9363 case AMDGPUISD::FRACT: 9364 case AMDGPUISD::CLAMP: 9365 case AMDGPUISD::COS_HW: 9366 case AMDGPUISD::SIN_HW: 9367 case AMDGPUISD::FMIN3: 9368 case AMDGPUISD::FMAX3: 9369 case AMDGPUISD::FMED3: 9370 case AMDGPUISD::FMAD_FTZ: 9371 case AMDGPUISD::RCP: 9372 case AMDGPUISD::RSQ: 9373 case AMDGPUISD::RCP_IFLAG: 9374 case AMDGPUISD::LDEXP: 9375 return true; 9376 default: 9377 // fcopysign, select and others may be lowered to 32-bit bit operations 9378 // which don't zero the high bits. 9379 return false; 9380 } 9381 } 9382 9383 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9384 DAGCombinerInfo &DCI) const { 9385 if (!Subtarget->has16BitInsts() || 9386 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9387 return SDValue(); 9388 9389 EVT VT = N->getValueType(0); 9390 if (VT != MVT::i32) 9391 return SDValue(); 9392 9393 SDValue Src = N->getOperand(0); 9394 if (Src.getValueType() != MVT::i16) 9395 return SDValue(); 9396 9397 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9398 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9399 if (Src.getOpcode() == ISD::BITCAST) { 9400 SDValue BCSrc = Src.getOperand(0); 9401 if (BCSrc.getValueType() == MVT::f16 && 9402 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9403 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9404 } 9405 9406 return SDValue(); 9407 } 9408 9409 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9410 DAGCombinerInfo &DCI) 9411 const { 9412 SDValue Src = N->getOperand(0); 9413 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9414 9415 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9416 VTSign->getVT() == MVT::i8) || 9417 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9418 VTSign->getVT() == MVT::i16)) && 9419 Src.hasOneUse()) { 9420 auto *M = cast<MemSDNode>(Src); 9421 SDValue Ops[] = { 9422 Src.getOperand(0), // Chain 9423 Src.getOperand(1), // rsrc 9424 Src.getOperand(2), // vindex 9425 Src.getOperand(3), // voffset 9426 Src.getOperand(4), // soffset 9427 Src.getOperand(5), // offset 9428 Src.getOperand(6), 9429 Src.getOperand(7) 9430 }; 9431 // replace with BUFFER_LOAD_BYTE/SHORT 9432 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9433 Src.getOperand(0).getValueType()); 9434 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9435 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9436 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9437 ResList, 9438 Ops, M->getMemoryVT(), 9439 M->getMemOperand()); 9440 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9441 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9442 } 9443 return SDValue(); 9444 } 9445 9446 SDValue SITargetLowering::performClassCombine(SDNode *N, 9447 DAGCombinerInfo &DCI) const { 9448 SelectionDAG &DAG = DCI.DAG; 9449 SDValue Mask = N->getOperand(1); 9450 9451 // fp_class x, 0 -> false 9452 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9453 if (CMask->isNullValue()) 9454 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9455 } 9456 9457 if (N->getOperand(0).isUndef()) 9458 return DAG.getUNDEF(MVT::i1); 9459 9460 return SDValue(); 9461 } 9462 9463 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9464 DAGCombinerInfo &DCI) const { 9465 EVT VT = N->getValueType(0); 9466 SDValue N0 = N->getOperand(0); 9467 9468 if (N0.isUndef()) 9469 return N0; 9470 9471 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9472 N0.getOpcode() == ISD::SINT_TO_FP)) { 9473 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9474 N->getFlags()); 9475 } 9476 9477 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9478 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9479 N0.getOperand(0), N->getFlags()); 9480 } 9481 9482 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9483 } 9484 9485 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9486 unsigned MaxDepth) const { 9487 unsigned Opcode = Op.getOpcode(); 9488 if (Opcode == ISD::FCANONICALIZE) 9489 return true; 9490 9491 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9492 auto F = CFP->getValueAPF(); 9493 if (F.isNaN() && F.isSignaling()) 9494 return false; 9495 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9496 } 9497 9498 // If source is a result of another standard FP operation it is already in 9499 // canonical form. 9500 if (MaxDepth == 0) 9501 return false; 9502 9503 switch (Opcode) { 9504 // These will flush denorms if required. 9505 case ISD::FADD: 9506 case ISD::FSUB: 9507 case ISD::FMUL: 9508 case ISD::FCEIL: 9509 case ISD::FFLOOR: 9510 case ISD::FMA: 9511 case ISD::FMAD: 9512 case ISD::FSQRT: 9513 case ISD::FDIV: 9514 case ISD::FREM: 9515 case ISD::FP_ROUND: 9516 case ISD::FP_EXTEND: 9517 case AMDGPUISD::FMUL_LEGACY: 9518 case AMDGPUISD::FMAD_FTZ: 9519 case AMDGPUISD::RCP: 9520 case AMDGPUISD::RSQ: 9521 case AMDGPUISD::RSQ_CLAMP: 9522 case AMDGPUISD::RCP_LEGACY: 9523 case AMDGPUISD::RCP_IFLAG: 9524 case AMDGPUISD::DIV_SCALE: 9525 case AMDGPUISD::DIV_FMAS: 9526 case AMDGPUISD::DIV_FIXUP: 9527 case AMDGPUISD::FRACT: 9528 case AMDGPUISD::LDEXP: 9529 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9530 case AMDGPUISD::CVT_F32_UBYTE0: 9531 case AMDGPUISD::CVT_F32_UBYTE1: 9532 case AMDGPUISD::CVT_F32_UBYTE2: 9533 case AMDGPUISD::CVT_F32_UBYTE3: 9534 return true; 9535 9536 // It can/will be lowered or combined as a bit operation. 9537 // Need to check their input recursively to handle. 9538 case ISD::FNEG: 9539 case ISD::FABS: 9540 case ISD::FCOPYSIGN: 9541 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9542 9543 case ISD::FSIN: 9544 case ISD::FCOS: 9545 case ISD::FSINCOS: 9546 return Op.getValueType().getScalarType() != MVT::f16; 9547 9548 case ISD::FMINNUM: 9549 case ISD::FMAXNUM: 9550 case ISD::FMINNUM_IEEE: 9551 case ISD::FMAXNUM_IEEE: 9552 case AMDGPUISD::CLAMP: 9553 case AMDGPUISD::FMED3: 9554 case AMDGPUISD::FMAX3: 9555 case AMDGPUISD::FMIN3: { 9556 // FIXME: Shouldn't treat the generic operations different based these. 9557 // However, we aren't really required to flush the result from 9558 // minnum/maxnum.. 9559 9560 // snans will be quieted, so we only need to worry about denormals. 9561 if (Subtarget->supportsMinMaxDenormModes() || 9562 denormalsEnabledForType(DAG, Op.getValueType())) 9563 return true; 9564 9565 // Flushing may be required. 9566 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9567 // targets need to check their input recursively. 9568 9569 // FIXME: Does this apply with clamp? It's implemented with max. 9570 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9571 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9572 return false; 9573 } 9574 9575 return true; 9576 } 9577 case ISD::SELECT: { 9578 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9579 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9580 } 9581 case ISD::BUILD_VECTOR: { 9582 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9583 SDValue SrcOp = Op.getOperand(i); 9584 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9585 return false; 9586 } 9587 9588 return true; 9589 } 9590 case ISD::EXTRACT_VECTOR_ELT: 9591 case ISD::EXTRACT_SUBVECTOR: { 9592 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9593 } 9594 case ISD::INSERT_VECTOR_ELT: { 9595 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9596 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9597 } 9598 case ISD::UNDEF: 9599 // Could be anything. 9600 return false; 9601 9602 case ISD::BITCAST: { 9603 // Hack round the mess we make when legalizing extract_vector_elt 9604 SDValue Src = Op.getOperand(0); 9605 if (Src.getValueType() == MVT::i16 && 9606 Src.getOpcode() == ISD::TRUNCATE) { 9607 SDValue TruncSrc = Src.getOperand(0); 9608 if (TruncSrc.getValueType() == MVT::i32 && 9609 TruncSrc.getOpcode() == ISD::BITCAST && 9610 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9611 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9612 } 9613 } 9614 9615 return false; 9616 } 9617 case ISD::INTRINSIC_WO_CHAIN: { 9618 unsigned IntrinsicID 9619 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9620 // TODO: Handle more intrinsics 9621 switch (IntrinsicID) { 9622 case Intrinsic::amdgcn_cvt_pkrtz: 9623 case Intrinsic::amdgcn_cubeid: 9624 case Intrinsic::amdgcn_frexp_mant: 9625 case Intrinsic::amdgcn_fdot2: 9626 case Intrinsic::amdgcn_rcp: 9627 case Intrinsic::amdgcn_rsq: 9628 case Intrinsic::amdgcn_rsq_clamp: 9629 case Intrinsic::amdgcn_rcp_legacy: 9630 case Intrinsic::amdgcn_rsq_legacy: 9631 case Intrinsic::amdgcn_trig_preop: 9632 return true; 9633 default: 9634 break; 9635 } 9636 9637 LLVM_FALLTHROUGH; 9638 } 9639 default: 9640 return denormalsEnabledForType(DAG, Op.getValueType()) && 9641 DAG.isKnownNeverSNaN(Op); 9642 } 9643 9644 llvm_unreachable("invalid operation"); 9645 } 9646 9647 // Constant fold canonicalize. 9648 SDValue SITargetLowering::getCanonicalConstantFP( 9649 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9650 // Flush denormals to 0 if not enabled. 9651 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9652 return DAG.getConstantFP(0.0, SL, VT); 9653 9654 if (C.isNaN()) { 9655 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9656 if (C.isSignaling()) { 9657 // Quiet a signaling NaN. 9658 // FIXME: Is this supposed to preserve payload bits? 9659 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9660 } 9661 9662 // Make sure it is the canonical NaN bitpattern. 9663 // 9664 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9665 // immediate? 9666 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9667 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9668 } 9669 9670 // Already canonical. 9671 return DAG.getConstantFP(C, SL, VT); 9672 } 9673 9674 static bool vectorEltWillFoldAway(SDValue Op) { 9675 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9676 } 9677 9678 SDValue SITargetLowering::performFCanonicalizeCombine( 9679 SDNode *N, 9680 DAGCombinerInfo &DCI) const { 9681 SelectionDAG &DAG = DCI.DAG; 9682 SDValue N0 = N->getOperand(0); 9683 EVT VT = N->getValueType(0); 9684 9685 // fcanonicalize undef -> qnan 9686 if (N0.isUndef()) { 9687 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9688 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9689 } 9690 9691 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9692 EVT VT = N->getValueType(0); 9693 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9694 } 9695 9696 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9697 // (fcanonicalize k) 9698 // 9699 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9700 9701 // TODO: This could be better with wider vectors that will be split to v2f16, 9702 // and to consider uses since there aren't that many packed operations. 9703 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9704 isTypeLegal(MVT::v2f16)) { 9705 SDLoc SL(N); 9706 SDValue NewElts[2]; 9707 SDValue Lo = N0.getOperand(0); 9708 SDValue Hi = N0.getOperand(1); 9709 EVT EltVT = Lo.getValueType(); 9710 9711 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9712 for (unsigned I = 0; I != 2; ++I) { 9713 SDValue Op = N0.getOperand(I); 9714 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9715 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9716 CFP->getValueAPF()); 9717 } else if (Op.isUndef()) { 9718 // Handled below based on what the other operand is. 9719 NewElts[I] = Op; 9720 } else { 9721 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9722 } 9723 } 9724 9725 // If one half is undef, and one is constant, perfer a splat vector rather 9726 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9727 // cheaper to use and may be free with a packed operation. 9728 if (NewElts[0].isUndef()) { 9729 if (isa<ConstantFPSDNode>(NewElts[1])) 9730 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9731 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9732 } 9733 9734 if (NewElts[1].isUndef()) { 9735 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9736 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9737 } 9738 9739 return DAG.getBuildVector(VT, SL, NewElts); 9740 } 9741 } 9742 9743 unsigned SrcOpc = N0.getOpcode(); 9744 9745 // If it's free to do so, push canonicalizes further up the source, which may 9746 // find a canonical source. 9747 // 9748 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9749 // sNaNs. 9750 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9751 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9752 if (CRHS && N0.hasOneUse()) { 9753 SDLoc SL(N); 9754 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9755 N0.getOperand(0)); 9756 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9757 DCI.AddToWorklist(Canon0.getNode()); 9758 9759 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9760 } 9761 } 9762 9763 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9764 } 9765 9766 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9767 switch (Opc) { 9768 case ISD::FMAXNUM: 9769 case ISD::FMAXNUM_IEEE: 9770 return AMDGPUISD::FMAX3; 9771 case ISD::SMAX: 9772 return AMDGPUISD::SMAX3; 9773 case ISD::UMAX: 9774 return AMDGPUISD::UMAX3; 9775 case ISD::FMINNUM: 9776 case ISD::FMINNUM_IEEE: 9777 return AMDGPUISD::FMIN3; 9778 case ISD::SMIN: 9779 return AMDGPUISD::SMIN3; 9780 case ISD::UMIN: 9781 return AMDGPUISD::UMIN3; 9782 default: 9783 llvm_unreachable("Not a min/max opcode"); 9784 } 9785 } 9786 9787 SDValue SITargetLowering::performIntMed3ImmCombine( 9788 SelectionDAG &DAG, const SDLoc &SL, 9789 SDValue Op0, SDValue Op1, bool Signed) const { 9790 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9791 if (!K1) 9792 return SDValue(); 9793 9794 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9795 if (!K0) 9796 return SDValue(); 9797 9798 if (Signed) { 9799 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9800 return SDValue(); 9801 } else { 9802 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9803 return SDValue(); 9804 } 9805 9806 EVT VT = K0->getValueType(0); 9807 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9808 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9809 return DAG.getNode(Med3Opc, SL, VT, 9810 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9811 } 9812 9813 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9814 if (VT == MVT::i16) { 9815 MVT NVT = MVT::i32; 9816 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9817 9818 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9819 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9820 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9821 9822 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9823 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9824 } 9825 9826 return SDValue(); 9827 } 9828 9829 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9830 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9831 return C; 9832 9833 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9834 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9835 return C; 9836 } 9837 9838 return nullptr; 9839 } 9840 9841 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9842 const SDLoc &SL, 9843 SDValue Op0, 9844 SDValue Op1) const { 9845 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9846 if (!K1) 9847 return SDValue(); 9848 9849 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9850 if (!K0) 9851 return SDValue(); 9852 9853 // Ordered >= (although NaN inputs should have folded away by now). 9854 if (K0->getValueAPF() > K1->getValueAPF()) 9855 return SDValue(); 9856 9857 const MachineFunction &MF = DAG.getMachineFunction(); 9858 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9859 9860 // TODO: Check IEEE bit enabled? 9861 EVT VT = Op0.getValueType(); 9862 if (Info->getMode().DX10Clamp) { 9863 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9864 // hardware fmed3 behavior converting to a min. 9865 // FIXME: Should this be allowing -0.0? 9866 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9867 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9868 } 9869 9870 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9871 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9872 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9873 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9874 // then give the other result, which is different from med3 with a NaN 9875 // input. 9876 SDValue Var = Op0.getOperand(0); 9877 if (!DAG.isKnownNeverSNaN(Var)) 9878 return SDValue(); 9879 9880 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9881 9882 if ((!K0->hasOneUse() || 9883 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9884 (!K1->hasOneUse() || 9885 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9886 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9887 Var, SDValue(K0, 0), SDValue(K1, 0)); 9888 } 9889 } 9890 9891 return SDValue(); 9892 } 9893 9894 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9895 DAGCombinerInfo &DCI) const { 9896 SelectionDAG &DAG = DCI.DAG; 9897 9898 EVT VT = N->getValueType(0); 9899 unsigned Opc = N->getOpcode(); 9900 SDValue Op0 = N->getOperand(0); 9901 SDValue Op1 = N->getOperand(1); 9902 9903 // Only do this if the inner op has one use since this will just increases 9904 // register pressure for no benefit. 9905 9906 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9907 !VT.isVector() && 9908 (VT == MVT::i32 || VT == MVT::f32 || 9909 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9910 // max(max(a, b), c) -> max3(a, b, c) 9911 // min(min(a, b), c) -> min3(a, b, c) 9912 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9913 SDLoc DL(N); 9914 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9915 DL, 9916 N->getValueType(0), 9917 Op0.getOperand(0), 9918 Op0.getOperand(1), 9919 Op1); 9920 } 9921 9922 // Try commuted. 9923 // max(a, max(b, c)) -> max3(a, b, c) 9924 // min(a, min(b, c)) -> min3(a, b, c) 9925 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9926 SDLoc DL(N); 9927 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9928 DL, 9929 N->getValueType(0), 9930 Op0, 9931 Op1.getOperand(0), 9932 Op1.getOperand(1)); 9933 } 9934 } 9935 9936 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9937 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9938 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9939 return Med3; 9940 } 9941 9942 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9943 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9944 return Med3; 9945 } 9946 9947 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9948 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9949 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9950 (Opc == AMDGPUISD::FMIN_LEGACY && 9951 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9952 (VT == MVT::f32 || VT == MVT::f64 || 9953 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9954 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9955 Op0.hasOneUse()) { 9956 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9957 return Res; 9958 } 9959 9960 return SDValue(); 9961 } 9962 9963 static bool isClampZeroToOne(SDValue A, SDValue B) { 9964 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9965 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9966 // FIXME: Should this be allowing -0.0? 9967 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9968 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9969 } 9970 } 9971 9972 return false; 9973 } 9974 9975 // FIXME: Should only worry about snans for version with chain. 9976 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9977 DAGCombinerInfo &DCI) const { 9978 EVT VT = N->getValueType(0); 9979 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9980 // NaNs. With a NaN input, the order of the operands may change the result. 9981 9982 SelectionDAG &DAG = DCI.DAG; 9983 SDLoc SL(N); 9984 9985 SDValue Src0 = N->getOperand(0); 9986 SDValue Src1 = N->getOperand(1); 9987 SDValue Src2 = N->getOperand(2); 9988 9989 if (isClampZeroToOne(Src0, Src1)) { 9990 // const_a, const_b, x -> clamp is safe in all cases including signaling 9991 // nans. 9992 // FIXME: Should this be allowing -0.0? 9993 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9994 } 9995 9996 const MachineFunction &MF = DAG.getMachineFunction(); 9997 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9998 9999 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10000 // handling no dx10-clamp? 10001 if (Info->getMode().DX10Clamp) { 10002 // If NaNs is clamped to 0, we are free to reorder the inputs. 10003 10004 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10005 std::swap(Src0, Src1); 10006 10007 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10008 std::swap(Src1, Src2); 10009 10010 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10011 std::swap(Src0, Src1); 10012 10013 if (isClampZeroToOne(Src1, Src2)) 10014 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10015 } 10016 10017 return SDValue(); 10018 } 10019 10020 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10021 DAGCombinerInfo &DCI) const { 10022 SDValue Src0 = N->getOperand(0); 10023 SDValue Src1 = N->getOperand(1); 10024 if (Src0.isUndef() && Src1.isUndef()) 10025 return DCI.DAG.getUNDEF(N->getValueType(0)); 10026 return SDValue(); 10027 } 10028 10029 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10030 // expanded into a set of cmp/select instructions. 10031 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10032 unsigned NumElem, 10033 bool IsDivergentIdx) { 10034 if (UseDivergentRegisterIndexing) 10035 return false; 10036 10037 unsigned VecSize = EltSize * NumElem; 10038 10039 // Sub-dword vectors of size 2 dword or less have better implementation. 10040 if (VecSize <= 64 && EltSize < 32) 10041 return false; 10042 10043 // Always expand the rest of sub-dword instructions, otherwise it will be 10044 // lowered via memory. 10045 if (EltSize < 32) 10046 return true; 10047 10048 // Always do this if var-idx is divergent, otherwise it will become a loop. 10049 if (IsDivergentIdx) 10050 return true; 10051 10052 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10053 unsigned NumInsts = NumElem /* Number of compares */ + 10054 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10055 return NumInsts <= 16; 10056 } 10057 10058 static bool shouldExpandVectorDynExt(SDNode *N) { 10059 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10060 if (isa<ConstantSDNode>(Idx)) 10061 return false; 10062 10063 SDValue Vec = N->getOperand(0); 10064 EVT VecVT = Vec.getValueType(); 10065 EVT EltVT = VecVT.getVectorElementType(); 10066 unsigned EltSize = EltVT.getSizeInBits(); 10067 unsigned NumElem = VecVT.getVectorNumElements(); 10068 10069 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10070 Idx->isDivergent()); 10071 } 10072 10073 SDValue SITargetLowering::performExtractVectorEltCombine( 10074 SDNode *N, DAGCombinerInfo &DCI) const { 10075 SDValue Vec = N->getOperand(0); 10076 SelectionDAG &DAG = DCI.DAG; 10077 10078 EVT VecVT = Vec.getValueType(); 10079 EVT EltVT = VecVT.getVectorElementType(); 10080 10081 if ((Vec.getOpcode() == ISD::FNEG || 10082 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10083 SDLoc SL(N); 10084 EVT EltVT = N->getValueType(0); 10085 SDValue Idx = N->getOperand(1); 10086 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10087 Vec.getOperand(0), Idx); 10088 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10089 } 10090 10091 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10092 // => 10093 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10094 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10095 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10096 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10097 SDLoc SL(N); 10098 EVT EltVT = N->getValueType(0); 10099 SDValue Idx = N->getOperand(1); 10100 unsigned Opc = Vec.getOpcode(); 10101 10102 switch(Opc) { 10103 default: 10104 break; 10105 // TODO: Support other binary operations. 10106 case ISD::FADD: 10107 case ISD::FSUB: 10108 case ISD::FMUL: 10109 case ISD::ADD: 10110 case ISD::UMIN: 10111 case ISD::UMAX: 10112 case ISD::SMIN: 10113 case ISD::SMAX: 10114 case ISD::FMAXNUM: 10115 case ISD::FMINNUM: 10116 case ISD::FMAXNUM_IEEE: 10117 case ISD::FMINNUM_IEEE: { 10118 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10119 Vec.getOperand(0), Idx); 10120 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10121 Vec.getOperand(1), Idx); 10122 10123 DCI.AddToWorklist(Elt0.getNode()); 10124 DCI.AddToWorklist(Elt1.getNode()); 10125 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10126 } 10127 } 10128 } 10129 10130 unsigned VecSize = VecVT.getSizeInBits(); 10131 unsigned EltSize = EltVT.getSizeInBits(); 10132 10133 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10134 if (::shouldExpandVectorDynExt(N)) { 10135 SDLoc SL(N); 10136 SDValue Idx = N->getOperand(1); 10137 SDValue V; 10138 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10139 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10140 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10141 if (I == 0) 10142 V = Elt; 10143 else 10144 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10145 } 10146 return V; 10147 } 10148 10149 if (!DCI.isBeforeLegalize()) 10150 return SDValue(); 10151 10152 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10153 // elements. This exposes more load reduction opportunities by replacing 10154 // multiple small extract_vector_elements with a single 32-bit extract. 10155 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10156 if (isa<MemSDNode>(Vec) && 10157 EltSize <= 16 && 10158 EltVT.isByteSized() && 10159 VecSize > 32 && 10160 VecSize % 32 == 0 && 10161 Idx) { 10162 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10163 10164 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10165 unsigned EltIdx = BitIndex / 32; 10166 unsigned LeftoverBitIdx = BitIndex % 32; 10167 SDLoc SL(N); 10168 10169 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10170 DCI.AddToWorklist(Cast.getNode()); 10171 10172 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10173 DAG.getConstant(EltIdx, SL, MVT::i32)); 10174 DCI.AddToWorklist(Elt.getNode()); 10175 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10176 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10177 DCI.AddToWorklist(Srl.getNode()); 10178 10179 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10180 DCI.AddToWorklist(Trunc.getNode()); 10181 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10182 } 10183 10184 return SDValue(); 10185 } 10186 10187 SDValue 10188 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10189 DAGCombinerInfo &DCI) const { 10190 SDValue Vec = N->getOperand(0); 10191 SDValue Idx = N->getOperand(2); 10192 EVT VecVT = Vec.getValueType(); 10193 EVT EltVT = VecVT.getVectorElementType(); 10194 10195 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10196 // => BUILD_VECTOR n x select (e, const-idx) 10197 if (!::shouldExpandVectorDynExt(N)) 10198 return SDValue(); 10199 10200 SelectionDAG &DAG = DCI.DAG; 10201 SDLoc SL(N); 10202 SDValue Ins = N->getOperand(1); 10203 EVT IdxVT = Idx.getValueType(); 10204 10205 SmallVector<SDValue, 16> Ops; 10206 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10207 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10208 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10209 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10210 Ops.push_back(V); 10211 } 10212 10213 return DAG.getBuildVector(VecVT, SL, Ops); 10214 } 10215 10216 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10217 const SDNode *N0, 10218 const SDNode *N1) const { 10219 EVT VT = N0->getValueType(0); 10220 10221 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10222 // support denormals ever. 10223 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10224 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10225 getSubtarget()->hasMadF16())) && 10226 isOperationLegal(ISD::FMAD, VT)) 10227 return ISD::FMAD; 10228 10229 const TargetOptions &Options = DAG.getTarget().Options; 10230 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10231 (N0->getFlags().hasAllowContract() && 10232 N1->getFlags().hasAllowContract())) && 10233 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10234 return ISD::FMA; 10235 } 10236 10237 return 0; 10238 } 10239 10240 // For a reassociatable opcode perform: 10241 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10242 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10243 SelectionDAG &DAG) const { 10244 EVT VT = N->getValueType(0); 10245 if (VT != MVT::i32 && VT != MVT::i64) 10246 return SDValue(); 10247 10248 unsigned Opc = N->getOpcode(); 10249 SDValue Op0 = N->getOperand(0); 10250 SDValue Op1 = N->getOperand(1); 10251 10252 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10253 return SDValue(); 10254 10255 if (Op0->isDivergent()) 10256 std::swap(Op0, Op1); 10257 10258 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10259 return SDValue(); 10260 10261 SDValue Op2 = Op1.getOperand(1); 10262 Op1 = Op1.getOperand(0); 10263 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10264 return SDValue(); 10265 10266 if (Op1->isDivergent()) 10267 std::swap(Op1, Op2); 10268 10269 // If either operand is constant this will conflict with 10270 // DAGCombiner::ReassociateOps(). 10271 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10272 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10273 return SDValue(); 10274 10275 SDLoc SL(N); 10276 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10277 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10278 } 10279 10280 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10281 EVT VT, 10282 SDValue N0, SDValue N1, SDValue N2, 10283 bool Signed) { 10284 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10285 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10286 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10287 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10288 } 10289 10290 SDValue SITargetLowering::performAddCombine(SDNode *N, 10291 DAGCombinerInfo &DCI) const { 10292 SelectionDAG &DAG = DCI.DAG; 10293 EVT VT = N->getValueType(0); 10294 SDLoc SL(N); 10295 SDValue LHS = N->getOperand(0); 10296 SDValue RHS = N->getOperand(1); 10297 10298 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10299 && Subtarget->hasMad64_32() && 10300 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10301 VT.getScalarSizeInBits() <= 64) { 10302 if (LHS.getOpcode() != ISD::MUL) 10303 std::swap(LHS, RHS); 10304 10305 SDValue MulLHS = LHS.getOperand(0); 10306 SDValue MulRHS = LHS.getOperand(1); 10307 SDValue AddRHS = RHS; 10308 10309 // TODO: Maybe restrict if SGPR inputs. 10310 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10311 numBitsUnsigned(MulRHS, DAG) <= 32) { 10312 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10313 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10314 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10315 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10316 } 10317 10318 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10319 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10320 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10321 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10322 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10323 } 10324 10325 return SDValue(); 10326 } 10327 10328 if (SDValue V = reassociateScalarOps(N, DAG)) { 10329 return V; 10330 } 10331 10332 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10333 return SDValue(); 10334 10335 // add x, zext (setcc) => addcarry x, 0, setcc 10336 // add x, sext (setcc) => subcarry x, 0, setcc 10337 unsigned Opc = LHS.getOpcode(); 10338 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10339 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10340 std::swap(RHS, LHS); 10341 10342 Opc = RHS.getOpcode(); 10343 switch (Opc) { 10344 default: break; 10345 case ISD::ZERO_EXTEND: 10346 case ISD::SIGN_EXTEND: 10347 case ISD::ANY_EXTEND: { 10348 auto Cond = RHS.getOperand(0); 10349 // If this won't be a real VOPC output, we would still need to insert an 10350 // extra instruction anyway. 10351 if (!isBoolSGPR(Cond)) 10352 break; 10353 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10354 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10355 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10356 return DAG.getNode(Opc, SL, VTList, Args); 10357 } 10358 case ISD::ADDCARRY: { 10359 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10360 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10361 if (!C || C->getZExtValue() != 0) break; 10362 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10363 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10364 } 10365 } 10366 return SDValue(); 10367 } 10368 10369 SDValue SITargetLowering::performSubCombine(SDNode *N, 10370 DAGCombinerInfo &DCI) const { 10371 SelectionDAG &DAG = DCI.DAG; 10372 EVT VT = N->getValueType(0); 10373 10374 if (VT != MVT::i32) 10375 return SDValue(); 10376 10377 SDLoc SL(N); 10378 SDValue LHS = N->getOperand(0); 10379 SDValue RHS = N->getOperand(1); 10380 10381 // sub x, zext (setcc) => subcarry x, 0, setcc 10382 // sub x, sext (setcc) => addcarry x, 0, setcc 10383 unsigned Opc = RHS.getOpcode(); 10384 switch (Opc) { 10385 default: break; 10386 case ISD::ZERO_EXTEND: 10387 case ISD::SIGN_EXTEND: 10388 case ISD::ANY_EXTEND: { 10389 auto Cond = RHS.getOperand(0); 10390 // If this won't be a real VOPC output, we would still need to insert an 10391 // extra instruction anyway. 10392 if (!isBoolSGPR(Cond)) 10393 break; 10394 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10395 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10396 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10397 return DAG.getNode(Opc, SL, VTList, Args); 10398 } 10399 } 10400 10401 if (LHS.getOpcode() == ISD::SUBCARRY) { 10402 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10403 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10404 if (!C || !C->isNullValue()) 10405 return SDValue(); 10406 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10407 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10408 } 10409 return SDValue(); 10410 } 10411 10412 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10413 DAGCombinerInfo &DCI) const { 10414 10415 if (N->getValueType(0) != MVT::i32) 10416 return SDValue(); 10417 10418 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10419 if (!C || C->getZExtValue() != 0) 10420 return SDValue(); 10421 10422 SelectionDAG &DAG = DCI.DAG; 10423 SDValue LHS = N->getOperand(0); 10424 10425 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10426 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10427 unsigned LHSOpc = LHS.getOpcode(); 10428 unsigned Opc = N->getOpcode(); 10429 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10430 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10431 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10432 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10433 } 10434 return SDValue(); 10435 } 10436 10437 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10438 DAGCombinerInfo &DCI) const { 10439 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10440 return SDValue(); 10441 10442 SelectionDAG &DAG = DCI.DAG; 10443 EVT VT = N->getValueType(0); 10444 10445 SDLoc SL(N); 10446 SDValue LHS = N->getOperand(0); 10447 SDValue RHS = N->getOperand(1); 10448 10449 // These should really be instruction patterns, but writing patterns with 10450 // source modiifiers is a pain. 10451 10452 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10453 if (LHS.getOpcode() == ISD::FADD) { 10454 SDValue A = LHS.getOperand(0); 10455 if (A == LHS.getOperand(1)) { 10456 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10457 if (FusedOp != 0) { 10458 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10459 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10460 } 10461 } 10462 } 10463 10464 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10465 if (RHS.getOpcode() == ISD::FADD) { 10466 SDValue A = RHS.getOperand(0); 10467 if (A == RHS.getOperand(1)) { 10468 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10469 if (FusedOp != 0) { 10470 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10471 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10472 } 10473 } 10474 } 10475 10476 return SDValue(); 10477 } 10478 10479 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10480 DAGCombinerInfo &DCI) const { 10481 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10482 return SDValue(); 10483 10484 SelectionDAG &DAG = DCI.DAG; 10485 SDLoc SL(N); 10486 EVT VT = N->getValueType(0); 10487 assert(!VT.isVector()); 10488 10489 // Try to get the fneg to fold into the source modifier. This undoes generic 10490 // DAG combines and folds them into the mad. 10491 // 10492 // Only do this if we are not trying to support denormals. v_mad_f32 does 10493 // not support denormals ever. 10494 SDValue LHS = N->getOperand(0); 10495 SDValue RHS = N->getOperand(1); 10496 if (LHS.getOpcode() == ISD::FADD) { 10497 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 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 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10504 10505 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10506 } 10507 } 10508 } 10509 10510 if (RHS.getOpcode() == ISD::FADD) { 10511 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10512 10513 SDValue A = RHS.getOperand(0); 10514 if (A == RHS.getOperand(1)) { 10515 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10516 if (FusedOp != 0){ 10517 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10518 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10519 } 10520 } 10521 } 10522 10523 return SDValue(); 10524 } 10525 10526 SDValue SITargetLowering::performFMACombine(SDNode *N, 10527 DAGCombinerInfo &DCI) const { 10528 SelectionDAG &DAG = DCI.DAG; 10529 EVT VT = N->getValueType(0); 10530 SDLoc SL(N); 10531 10532 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 10533 return SDValue(); 10534 10535 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10536 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10537 SDValue Op1 = N->getOperand(0); 10538 SDValue Op2 = N->getOperand(1); 10539 SDValue FMA = N->getOperand(2); 10540 10541 if (FMA.getOpcode() != ISD::FMA || 10542 Op1.getOpcode() != ISD::FP_EXTEND || 10543 Op2.getOpcode() != ISD::FP_EXTEND) 10544 return SDValue(); 10545 10546 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10547 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10548 // is sufficient to allow generaing fdot2. 10549 const TargetOptions &Options = DAG.getTarget().Options; 10550 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10551 (N->getFlags().hasAllowContract() && 10552 FMA->getFlags().hasAllowContract())) { 10553 Op1 = Op1.getOperand(0); 10554 Op2 = Op2.getOperand(0); 10555 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10556 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10557 return SDValue(); 10558 10559 SDValue Vec1 = Op1.getOperand(0); 10560 SDValue Idx1 = Op1.getOperand(1); 10561 SDValue Vec2 = Op2.getOperand(0); 10562 10563 SDValue FMAOp1 = FMA.getOperand(0); 10564 SDValue FMAOp2 = FMA.getOperand(1); 10565 SDValue FMAAcc = FMA.getOperand(2); 10566 10567 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10568 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10569 return SDValue(); 10570 10571 FMAOp1 = FMAOp1.getOperand(0); 10572 FMAOp2 = FMAOp2.getOperand(0); 10573 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10574 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10575 return SDValue(); 10576 10577 SDValue Vec3 = FMAOp1.getOperand(0); 10578 SDValue Vec4 = FMAOp2.getOperand(0); 10579 SDValue Idx2 = FMAOp1.getOperand(1); 10580 10581 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10582 // Idx1 and Idx2 cannot be the same. 10583 Idx1 == Idx2) 10584 return SDValue(); 10585 10586 if (Vec1 == Vec2 || Vec3 == Vec4) 10587 return SDValue(); 10588 10589 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10590 return SDValue(); 10591 10592 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10593 (Vec1 == Vec4 && Vec2 == Vec3)) { 10594 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10595 DAG.getTargetConstant(0, SL, MVT::i1)); 10596 } 10597 } 10598 return SDValue(); 10599 } 10600 10601 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10602 DAGCombinerInfo &DCI) const { 10603 SelectionDAG &DAG = DCI.DAG; 10604 SDLoc SL(N); 10605 10606 SDValue LHS = N->getOperand(0); 10607 SDValue RHS = N->getOperand(1); 10608 EVT VT = LHS.getValueType(); 10609 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10610 10611 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10612 if (!CRHS) { 10613 CRHS = dyn_cast<ConstantSDNode>(LHS); 10614 if (CRHS) { 10615 std::swap(LHS, RHS); 10616 CC = getSetCCSwappedOperands(CC); 10617 } 10618 } 10619 10620 if (CRHS) { 10621 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10622 isBoolSGPR(LHS.getOperand(0))) { 10623 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10624 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10625 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10626 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10627 if ((CRHS->isAllOnesValue() && 10628 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10629 (CRHS->isNullValue() && 10630 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10631 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10632 DAG.getConstant(-1, SL, MVT::i1)); 10633 if ((CRHS->isAllOnesValue() && 10634 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10635 (CRHS->isNullValue() && 10636 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10637 return LHS.getOperand(0); 10638 } 10639 10640 uint64_t CRHSVal = CRHS->getZExtValue(); 10641 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10642 LHS.getOpcode() == ISD::SELECT && 10643 isa<ConstantSDNode>(LHS.getOperand(1)) && 10644 isa<ConstantSDNode>(LHS.getOperand(2)) && 10645 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10646 isBoolSGPR(LHS.getOperand(0))) { 10647 // Given CT != FT: 10648 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10649 // setcc (select cc, CT, CF), CF, ne => cc 10650 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10651 // setcc (select cc, CT, CF), CT, eq => cc 10652 uint64_t CT = LHS.getConstantOperandVal(1); 10653 uint64_t CF = LHS.getConstantOperandVal(2); 10654 10655 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10656 (CT == CRHSVal && CC == ISD::SETNE)) 10657 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10658 DAG.getConstant(-1, SL, MVT::i1)); 10659 if ((CF == CRHSVal && CC == ISD::SETNE) || 10660 (CT == CRHSVal && CC == ISD::SETEQ)) 10661 return LHS.getOperand(0); 10662 } 10663 } 10664 10665 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10666 VT != MVT::f16)) 10667 return SDValue(); 10668 10669 // Match isinf/isfinite pattern 10670 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10671 // (fcmp one (fabs x), inf) -> (fp_class x, 10672 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10673 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10674 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10675 if (!CRHS) 10676 return SDValue(); 10677 10678 const APFloat &APF = CRHS->getValueAPF(); 10679 if (APF.isInfinity() && !APF.isNegative()) { 10680 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10681 SIInstrFlags::N_INFINITY; 10682 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10683 SIInstrFlags::P_ZERO | 10684 SIInstrFlags::N_NORMAL | 10685 SIInstrFlags::P_NORMAL | 10686 SIInstrFlags::N_SUBNORMAL | 10687 SIInstrFlags::P_SUBNORMAL; 10688 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10689 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10690 DAG.getConstant(Mask, SL, MVT::i32)); 10691 } 10692 } 10693 10694 return SDValue(); 10695 } 10696 10697 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10698 DAGCombinerInfo &DCI) const { 10699 SelectionDAG &DAG = DCI.DAG; 10700 SDLoc SL(N); 10701 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10702 10703 SDValue Src = N->getOperand(0); 10704 SDValue Shift = N->getOperand(0); 10705 10706 // TODO: Extend type shouldn't matter (assuming legal types). 10707 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10708 Shift = Shift.getOperand(0); 10709 10710 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10711 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10712 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10713 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10714 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10715 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10716 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10717 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10718 SDLoc(Shift.getOperand(0)), MVT::i32); 10719 10720 unsigned ShiftOffset = 8 * Offset; 10721 if (Shift.getOpcode() == ISD::SHL) 10722 ShiftOffset -= C->getZExtValue(); 10723 else 10724 ShiftOffset += C->getZExtValue(); 10725 10726 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10727 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10728 MVT::f32, Shift); 10729 } 10730 } 10731 } 10732 10733 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10734 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10735 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10736 // We simplified Src. If this node is not dead, visit it again so it is 10737 // folded properly. 10738 if (N->getOpcode() != ISD::DELETED_NODE) 10739 DCI.AddToWorklist(N); 10740 return SDValue(N, 0); 10741 } 10742 10743 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10744 if (SDValue DemandedSrc = 10745 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10746 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10747 10748 return SDValue(); 10749 } 10750 10751 SDValue SITargetLowering::performClampCombine(SDNode *N, 10752 DAGCombinerInfo &DCI) const { 10753 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10754 if (!CSrc) 10755 return SDValue(); 10756 10757 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10758 const APFloat &F = CSrc->getValueAPF(); 10759 APFloat Zero = APFloat::getZero(F.getSemantics()); 10760 if (F < Zero || 10761 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10762 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10763 } 10764 10765 APFloat One(F.getSemantics(), "1.0"); 10766 if (F > One) 10767 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10768 10769 return SDValue(CSrc, 0); 10770 } 10771 10772 10773 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10774 DAGCombinerInfo &DCI) const { 10775 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10776 return SDValue(); 10777 switch (N->getOpcode()) { 10778 case ISD::ADD: 10779 return performAddCombine(N, DCI); 10780 case ISD::SUB: 10781 return performSubCombine(N, DCI); 10782 case ISD::ADDCARRY: 10783 case ISD::SUBCARRY: 10784 return performAddCarrySubCarryCombine(N, DCI); 10785 case ISD::FADD: 10786 return performFAddCombine(N, DCI); 10787 case ISD::FSUB: 10788 return performFSubCombine(N, DCI); 10789 case ISD::SETCC: 10790 return performSetCCCombine(N, DCI); 10791 case ISD::FMAXNUM: 10792 case ISD::FMINNUM: 10793 case ISD::FMAXNUM_IEEE: 10794 case ISD::FMINNUM_IEEE: 10795 case ISD::SMAX: 10796 case ISD::SMIN: 10797 case ISD::UMAX: 10798 case ISD::UMIN: 10799 case AMDGPUISD::FMIN_LEGACY: 10800 case AMDGPUISD::FMAX_LEGACY: 10801 return performMinMaxCombine(N, DCI); 10802 case ISD::FMA: 10803 return performFMACombine(N, DCI); 10804 case ISD::AND: 10805 return performAndCombine(N, DCI); 10806 case ISD::OR: 10807 return performOrCombine(N, DCI); 10808 case ISD::XOR: 10809 return performXorCombine(N, DCI); 10810 case ISD::ZERO_EXTEND: 10811 return performZeroExtendCombine(N, DCI); 10812 case ISD::SIGN_EXTEND_INREG: 10813 return performSignExtendInRegCombine(N , DCI); 10814 case AMDGPUISD::FP_CLASS: 10815 return performClassCombine(N, DCI); 10816 case ISD::FCANONICALIZE: 10817 return performFCanonicalizeCombine(N, DCI); 10818 case AMDGPUISD::RCP: 10819 return performRcpCombine(N, DCI); 10820 case AMDGPUISD::FRACT: 10821 case AMDGPUISD::RSQ: 10822 case AMDGPUISD::RCP_LEGACY: 10823 case AMDGPUISD::RCP_IFLAG: 10824 case AMDGPUISD::RSQ_CLAMP: 10825 case AMDGPUISD::LDEXP: { 10826 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10827 SDValue Src = N->getOperand(0); 10828 if (Src.isUndef()) 10829 return Src; 10830 break; 10831 } 10832 case ISD::SINT_TO_FP: 10833 case ISD::UINT_TO_FP: 10834 return performUCharToFloatCombine(N, DCI); 10835 case AMDGPUISD::CVT_F32_UBYTE0: 10836 case AMDGPUISD::CVT_F32_UBYTE1: 10837 case AMDGPUISD::CVT_F32_UBYTE2: 10838 case AMDGPUISD::CVT_F32_UBYTE3: 10839 return performCvtF32UByteNCombine(N, DCI); 10840 case AMDGPUISD::FMED3: 10841 return performFMed3Combine(N, DCI); 10842 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10843 return performCvtPkRTZCombine(N, DCI); 10844 case AMDGPUISD::CLAMP: 10845 return performClampCombine(N, DCI); 10846 case ISD::SCALAR_TO_VECTOR: { 10847 SelectionDAG &DAG = DCI.DAG; 10848 EVT VT = N->getValueType(0); 10849 10850 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10851 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10852 SDLoc SL(N); 10853 SDValue Src = N->getOperand(0); 10854 EVT EltVT = Src.getValueType(); 10855 if (EltVT == MVT::f16) 10856 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10857 10858 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10859 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10860 } 10861 10862 break; 10863 } 10864 case ISD::EXTRACT_VECTOR_ELT: 10865 return performExtractVectorEltCombine(N, DCI); 10866 case ISD::INSERT_VECTOR_ELT: 10867 return performInsertVectorEltCombine(N, DCI); 10868 case ISD::LOAD: { 10869 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10870 return Widended; 10871 LLVM_FALLTHROUGH; 10872 } 10873 default: { 10874 if (!DCI.isBeforeLegalize()) { 10875 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 10876 return performMemSDNodeCombine(MemNode, DCI); 10877 } 10878 10879 break; 10880 } 10881 } 10882 10883 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10884 } 10885 10886 /// Helper function for adjustWritemask 10887 static unsigned SubIdx2Lane(unsigned Idx) { 10888 switch (Idx) { 10889 default: return ~0u; 10890 case AMDGPU::sub0: return 0; 10891 case AMDGPU::sub1: return 1; 10892 case AMDGPU::sub2: return 2; 10893 case AMDGPU::sub3: return 3; 10894 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10895 } 10896 } 10897 10898 /// Adjust the writemask of MIMG instructions 10899 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10900 SelectionDAG &DAG) const { 10901 unsigned Opcode = Node->getMachineOpcode(); 10902 10903 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10904 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10905 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10906 return Node; // not implemented for D16 10907 10908 SDNode *Users[5] = { nullptr }; 10909 unsigned Lane = 0; 10910 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10911 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10912 unsigned NewDmask = 0; 10913 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10914 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10915 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 10916 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10917 unsigned TFCLane = 0; 10918 bool HasChain = Node->getNumValues() > 1; 10919 10920 if (OldDmask == 0) { 10921 // These are folded out, but on the chance it happens don't assert. 10922 return Node; 10923 } 10924 10925 unsigned OldBitsSet = countPopulation(OldDmask); 10926 // Work out which is the TFE/LWE lane if that is enabled. 10927 if (UsesTFC) { 10928 TFCLane = OldBitsSet; 10929 } 10930 10931 // Try to figure out the used register components 10932 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10933 I != E; ++I) { 10934 10935 // Don't look at users of the chain. 10936 if (I.getUse().getResNo() != 0) 10937 continue; 10938 10939 // Abort if we can't understand the usage 10940 if (!I->isMachineOpcode() || 10941 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10942 return Node; 10943 10944 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10945 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10946 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10947 // set, etc. 10948 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10949 if (Lane == ~0u) 10950 return Node; 10951 10952 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10953 if (UsesTFC && Lane == TFCLane) { 10954 Users[Lane] = *I; 10955 } else { 10956 // Set which texture component corresponds to the lane. 10957 unsigned Comp; 10958 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10959 Comp = countTrailingZeros(Dmask); 10960 Dmask &= ~(1 << Comp); 10961 } 10962 10963 // Abort if we have more than one user per component. 10964 if (Users[Lane]) 10965 return Node; 10966 10967 Users[Lane] = *I; 10968 NewDmask |= 1 << Comp; 10969 } 10970 } 10971 10972 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10973 bool NoChannels = !NewDmask; 10974 if (NoChannels) { 10975 if (!UsesTFC) { 10976 // No uses of the result and not using TFC. Then do nothing. 10977 return Node; 10978 } 10979 // If the original dmask has one channel - then nothing to do 10980 if (OldBitsSet == 1) 10981 return Node; 10982 // Use an arbitrary dmask - required for the instruction to work 10983 NewDmask = 1; 10984 } 10985 // Abort if there's no change 10986 if (NewDmask == OldDmask) 10987 return Node; 10988 10989 unsigned BitsSet = countPopulation(NewDmask); 10990 10991 // Check for TFE or LWE - increase the number of channels by one to account 10992 // for the extra return value 10993 // This will need adjustment for D16 if this is also included in 10994 // adjustWriteMask (this function) but at present D16 are excluded. 10995 unsigned NewChannels = BitsSet + UsesTFC; 10996 10997 int NewOpcode = 10998 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10999 assert(NewOpcode != -1 && 11000 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11001 "failed to find equivalent MIMG op"); 11002 11003 // Adjust the writemask in the node 11004 SmallVector<SDValue, 12> Ops; 11005 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11006 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11007 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11008 11009 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11010 11011 MVT ResultVT = NewChannels == 1 ? 11012 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11013 NewChannels == 5 ? 8 : NewChannels); 11014 SDVTList NewVTList = HasChain ? 11015 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11016 11017 11018 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11019 NewVTList, Ops); 11020 11021 if (HasChain) { 11022 // Update chain. 11023 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11024 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11025 } 11026 11027 if (NewChannels == 1) { 11028 assert(Node->hasNUsesOfValue(1, 0)); 11029 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11030 SDLoc(Node), Users[Lane]->getValueType(0), 11031 SDValue(NewNode, 0)); 11032 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11033 return nullptr; 11034 } 11035 11036 // Update the users of the node with the new indices 11037 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11038 SDNode *User = Users[i]; 11039 if (!User) { 11040 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11041 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11042 if (i || !NoChannels) 11043 continue; 11044 } else { 11045 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11046 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11047 } 11048 11049 switch (Idx) { 11050 default: break; 11051 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11052 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11053 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11054 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11055 } 11056 } 11057 11058 DAG.RemoveDeadNode(Node); 11059 return nullptr; 11060 } 11061 11062 static bool isFrameIndexOp(SDValue Op) { 11063 if (Op.getOpcode() == ISD::AssertZext) 11064 Op = Op.getOperand(0); 11065 11066 return isa<FrameIndexSDNode>(Op); 11067 } 11068 11069 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11070 /// with frame index operands. 11071 /// LLVM assumes that inputs are to these instructions are registers. 11072 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11073 SelectionDAG &DAG) const { 11074 if (Node->getOpcode() == ISD::CopyToReg) { 11075 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11076 SDValue SrcVal = Node->getOperand(2); 11077 11078 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11079 // to try understanding copies to physical registers. 11080 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11081 SDLoc SL(Node); 11082 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11083 SDValue VReg = DAG.getRegister( 11084 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11085 11086 SDNode *Glued = Node->getGluedNode(); 11087 SDValue ToVReg 11088 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11089 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11090 SDValue ToResultReg 11091 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11092 VReg, ToVReg.getValue(1)); 11093 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11094 DAG.RemoveDeadNode(Node); 11095 return ToResultReg.getNode(); 11096 } 11097 } 11098 11099 SmallVector<SDValue, 8> Ops; 11100 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11101 if (!isFrameIndexOp(Node->getOperand(i))) { 11102 Ops.push_back(Node->getOperand(i)); 11103 continue; 11104 } 11105 11106 SDLoc DL(Node); 11107 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11108 Node->getOperand(i).getValueType(), 11109 Node->getOperand(i)), 0)); 11110 } 11111 11112 return DAG.UpdateNodeOperands(Node, Ops); 11113 } 11114 11115 /// Fold the instructions after selecting them. 11116 /// Returns null if users were already updated. 11117 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11118 SelectionDAG &DAG) const { 11119 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11120 unsigned Opcode = Node->getMachineOpcode(); 11121 11122 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11123 !TII->isGather4(Opcode) && 11124 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11125 return adjustWritemask(Node, DAG); 11126 } 11127 11128 if (Opcode == AMDGPU::INSERT_SUBREG || 11129 Opcode == AMDGPU::REG_SEQUENCE) { 11130 legalizeTargetIndependentNode(Node, DAG); 11131 return Node; 11132 } 11133 11134 switch (Opcode) { 11135 case AMDGPU::V_DIV_SCALE_F32_e64: 11136 case AMDGPU::V_DIV_SCALE_F64_e64: { 11137 // Satisfy the operand register constraint when one of the inputs is 11138 // undefined. Ordinarily each undef value will have its own implicit_def of 11139 // a vreg, so force these to use a single register. 11140 SDValue Src0 = Node->getOperand(1); 11141 SDValue Src1 = Node->getOperand(3); 11142 SDValue Src2 = Node->getOperand(5); 11143 11144 if ((Src0.isMachineOpcode() && 11145 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11146 (Src0 == Src1 || Src0 == Src2)) 11147 break; 11148 11149 MVT VT = Src0.getValueType().getSimpleVT(); 11150 const TargetRegisterClass *RC = 11151 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11152 11153 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11154 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11155 11156 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11157 UndefReg, Src0, SDValue()); 11158 11159 // src0 must be the same register as src1 or src2, even if the value is 11160 // undefined, so make sure we don't violate this constraint. 11161 if (Src0.isMachineOpcode() && 11162 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11163 if (Src1.isMachineOpcode() && 11164 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11165 Src0 = Src1; 11166 else if (Src2.isMachineOpcode() && 11167 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11168 Src0 = Src2; 11169 else { 11170 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11171 Src0 = UndefReg; 11172 Src1 = UndefReg; 11173 } 11174 } else 11175 break; 11176 11177 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11178 Ops[1] = Src0; 11179 Ops[3] = Src1; 11180 Ops[5] = Src2; 11181 Ops.push_back(ImpDef.getValue(1)); 11182 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11183 } 11184 default: 11185 break; 11186 } 11187 11188 return Node; 11189 } 11190 11191 // Any MIMG instructions that use tfe or lwe require an initialization of the 11192 // result register that will be written in the case of a memory access failure. 11193 // The required code is also added to tie this init code to the result of the 11194 // img instruction. 11195 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11196 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11197 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11198 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11199 MachineBasicBlock &MBB = *MI.getParent(); 11200 11201 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11202 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11203 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11204 11205 if (!TFE && !LWE) // intersect_ray 11206 return; 11207 11208 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11209 unsigned LWEVal = LWE->getImm(); 11210 unsigned D16Val = D16 ? D16->getImm() : 0; 11211 11212 if (!TFEVal && !LWEVal) 11213 return; 11214 11215 // At least one of TFE or LWE are non-zero 11216 // We have to insert a suitable initialization of the result value and 11217 // tie this to the dest of the image instruction. 11218 11219 const DebugLoc &DL = MI.getDebugLoc(); 11220 11221 int DstIdx = 11222 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11223 11224 // Calculate which dword we have to initialize to 0. 11225 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11226 11227 // check that dmask operand is found. 11228 assert(MO_Dmask && "Expected dmask operand in instruction"); 11229 11230 unsigned dmask = MO_Dmask->getImm(); 11231 // Determine the number of active lanes taking into account the 11232 // Gather4 special case 11233 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11234 11235 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11236 11237 unsigned InitIdx = 11238 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11239 11240 // Abandon attempt if the dst size isn't large enough 11241 // - this is in fact an error but this is picked up elsewhere and 11242 // reported correctly. 11243 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11244 if (DstSize < InitIdx) 11245 return; 11246 11247 // Create a register for the intialization value. 11248 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11249 unsigned NewDst = 0; // Final initialized value will be in here 11250 11251 // If PRTStrictNull feature is enabled (the default) then initialize 11252 // all the result registers to 0, otherwise just the error indication 11253 // register (VGPRn+1) 11254 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11255 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11256 11257 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11258 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11259 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11260 // Initialize dword 11261 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11262 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11263 .addImm(0); 11264 // Insert into the super-reg 11265 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11266 .addReg(PrevDst) 11267 .addReg(SubReg) 11268 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11269 11270 PrevDst = NewDst; 11271 } 11272 11273 // Add as an implicit operand 11274 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11275 11276 // Tie the just added implicit operand to the dst 11277 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11278 } 11279 11280 /// Assign the register class depending on the number of 11281 /// bits set in the writemask 11282 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11283 SDNode *Node) const { 11284 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11285 11286 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11287 11288 if (TII->isVOP3(MI.getOpcode())) { 11289 // Make sure constant bus requirements are respected. 11290 TII->legalizeOperandsVOP3(MRI, MI); 11291 11292 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11293 // This saves a chain-copy of registers and better ballance register 11294 // use between vgpr and agpr as agpr tuples tend to be big. 11295 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 11296 unsigned Opc = MI.getOpcode(); 11297 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11298 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11299 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11300 if (I == -1) 11301 break; 11302 MachineOperand &Op = MI.getOperand(I); 11303 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 11304 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 11305 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 11306 continue; 11307 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11308 if (!Src || !Src->isCopy() || 11309 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11310 continue; 11311 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11312 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11313 // All uses of agpr64 and agpr32 can also accept vgpr except for 11314 // v_accvgpr_read, but we do not produce agpr reads during selection, 11315 // so no use checks are needed. 11316 MRI.setRegClass(Op.getReg(), NewRC); 11317 } 11318 } 11319 11320 return; 11321 } 11322 11323 // Replace unused atomics with the no return version. 11324 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11325 if (NoRetAtomicOp != -1) { 11326 if (!Node->hasAnyUseOfValue(0)) { 11327 int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11328 AMDGPU::OpName::cpol); 11329 if (CPolIdx != -1) { 11330 MachineOperand &CPol = MI.getOperand(CPolIdx); 11331 CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC); 11332 } 11333 MI.RemoveOperand(0); 11334 MI.setDesc(TII->get(NoRetAtomicOp)); 11335 return; 11336 } 11337 11338 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11339 // instruction, because the return type of these instructions is a vec2 of 11340 // the memory type, so it can be tied to the input operand. 11341 // This means these instructions always have a use, so we need to add a 11342 // special case to check if the atomic has only one extract_subreg use, 11343 // which itself has no uses. 11344 if ((Node->hasNUsesOfValue(1, 0) && 11345 Node->use_begin()->isMachineOpcode() && 11346 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11347 !Node->use_begin()->hasAnyUseOfValue(0))) { 11348 Register Def = MI.getOperand(0).getReg(); 11349 11350 // Change this into a noret atomic. 11351 MI.setDesc(TII->get(NoRetAtomicOp)); 11352 MI.RemoveOperand(0); 11353 11354 // If we only remove the def operand from the atomic instruction, the 11355 // extract_subreg will be left with a use of a vreg without a def. 11356 // So we need to insert an implicit_def to avoid machine verifier 11357 // errors. 11358 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11359 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11360 } 11361 return; 11362 } 11363 11364 if (TII->isMIMG(MI) && !MI.mayStore()) 11365 AddIMGInit(MI); 11366 } 11367 11368 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11369 uint64_t Val) { 11370 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11371 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11372 } 11373 11374 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11375 const SDLoc &DL, 11376 SDValue Ptr) const { 11377 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11378 11379 // Build the half of the subregister with the constants before building the 11380 // full 128-bit register. If we are building multiple resource descriptors, 11381 // this will allow CSEing of the 2-component register. 11382 const SDValue Ops0[] = { 11383 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11384 buildSMovImm32(DAG, DL, 0), 11385 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11386 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11387 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11388 }; 11389 11390 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11391 MVT::v2i32, Ops0), 0); 11392 11393 // Combine the constants and the pointer. 11394 const SDValue Ops1[] = { 11395 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11396 Ptr, 11397 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11398 SubRegHi, 11399 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11400 }; 11401 11402 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11403 } 11404 11405 /// Return a resource descriptor with the 'Add TID' bit enabled 11406 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11407 /// of the resource descriptor) to create an offset, which is added to 11408 /// the resource pointer. 11409 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11410 SDValue Ptr, uint32_t RsrcDword1, 11411 uint64_t RsrcDword2And3) const { 11412 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11413 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11414 if (RsrcDword1) { 11415 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11416 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11417 0); 11418 } 11419 11420 SDValue DataLo = buildSMovImm32(DAG, DL, 11421 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11422 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11423 11424 const SDValue Ops[] = { 11425 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11426 PtrLo, 11427 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11428 PtrHi, 11429 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11430 DataLo, 11431 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11432 DataHi, 11433 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11434 }; 11435 11436 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11437 } 11438 11439 //===----------------------------------------------------------------------===// 11440 // SI Inline Assembly Support 11441 //===----------------------------------------------------------------------===// 11442 11443 std::pair<unsigned, const TargetRegisterClass *> 11444 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11445 StringRef Constraint, 11446 MVT VT) const { 11447 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11448 11449 const TargetRegisterClass *RC = nullptr; 11450 if (Constraint.size() == 1) { 11451 const unsigned BitWidth = VT.getSizeInBits(); 11452 switch (Constraint[0]) { 11453 default: 11454 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11455 case 's': 11456 case 'r': 11457 switch (BitWidth) { 11458 case 16: 11459 RC = &AMDGPU::SReg_32RegClass; 11460 break; 11461 case 64: 11462 RC = &AMDGPU::SGPR_64RegClass; 11463 break; 11464 default: 11465 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11466 if (!RC) 11467 return std::make_pair(0U, nullptr); 11468 break; 11469 } 11470 break; 11471 case 'v': 11472 switch (BitWidth) { 11473 case 16: 11474 RC = &AMDGPU::VGPR_32RegClass; 11475 break; 11476 default: 11477 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11478 if (!RC) 11479 return std::make_pair(0U, nullptr); 11480 break; 11481 } 11482 break; 11483 case 'a': 11484 if (!Subtarget->hasMAIInsts()) 11485 break; 11486 switch (BitWidth) { 11487 case 16: 11488 RC = &AMDGPU::AGPR_32RegClass; 11489 break; 11490 default: 11491 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11492 if (!RC) 11493 return std::make_pair(0U, nullptr); 11494 break; 11495 } 11496 break; 11497 } 11498 // We actually support i128, i16 and f16 as inline parameters 11499 // even if they are not reported as legal 11500 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11501 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11502 return std::make_pair(0U, RC); 11503 } 11504 11505 if (Constraint.size() > 1) { 11506 if (Constraint[1] == 'v') { 11507 RC = &AMDGPU::VGPR_32RegClass; 11508 } else if (Constraint[1] == 's') { 11509 RC = &AMDGPU::SGPR_32RegClass; 11510 } else if (Constraint[1] == 'a') { 11511 RC = &AMDGPU::AGPR_32RegClass; 11512 } 11513 11514 if (RC) { 11515 uint32_t Idx; 11516 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11517 if (!Failed && Idx < RC->getNumRegs()) 11518 return std::make_pair(RC->getRegister(Idx), RC); 11519 } 11520 } 11521 11522 // FIXME: Returns VS_32 for physical SGPR constraints 11523 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11524 } 11525 11526 static bool isImmConstraint(StringRef Constraint) { 11527 if (Constraint.size() == 1) { 11528 switch (Constraint[0]) { 11529 default: break; 11530 case 'I': 11531 case 'J': 11532 case 'A': 11533 case 'B': 11534 case 'C': 11535 return true; 11536 } 11537 } else if (Constraint == "DA" || 11538 Constraint == "DB") { 11539 return true; 11540 } 11541 return false; 11542 } 11543 11544 SITargetLowering::ConstraintType 11545 SITargetLowering::getConstraintType(StringRef Constraint) const { 11546 if (Constraint.size() == 1) { 11547 switch (Constraint[0]) { 11548 default: break; 11549 case 's': 11550 case 'v': 11551 case 'a': 11552 return C_RegisterClass; 11553 } 11554 } 11555 if (isImmConstraint(Constraint)) { 11556 return C_Other; 11557 } 11558 return TargetLowering::getConstraintType(Constraint); 11559 } 11560 11561 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11562 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11563 Val = Val & maskTrailingOnes<uint64_t>(Size); 11564 } 11565 return Val; 11566 } 11567 11568 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11569 std::string &Constraint, 11570 std::vector<SDValue> &Ops, 11571 SelectionDAG &DAG) const { 11572 if (isImmConstraint(Constraint)) { 11573 uint64_t Val; 11574 if (getAsmOperandConstVal(Op, Val) && 11575 checkAsmConstraintVal(Op, Constraint, Val)) { 11576 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11577 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11578 } 11579 } else { 11580 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11581 } 11582 } 11583 11584 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11585 unsigned Size = Op.getScalarValueSizeInBits(); 11586 if (Size > 64) 11587 return false; 11588 11589 if (Size == 16 && !Subtarget->has16BitInsts()) 11590 return false; 11591 11592 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11593 Val = C->getSExtValue(); 11594 return true; 11595 } 11596 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11597 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11598 return true; 11599 } 11600 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11601 if (Size != 16 || Op.getNumOperands() != 2) 11602 return false; 11603 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11604 return false; 11605 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11606 Val = C->getSExtValue(); 11607 return true; 11608 } 11609 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11610 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11611 return true; 11612 } 11613 } 11614 11615 return false; 11616 } 11617 11618 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11619 const std::string &Constraint, 11620 uint64_t Val) const { 11621 if (Constraint.size() == 1) { 11622 switch (Constraint[0]) { 11623 case 'I': 11624 return AMDGPU::isInlinableIntLiteral(Val); 11625 case 'J': 11626 return isInt<16>(Val); 11627 case 'A': 11628 return checkAsmConstraintValA(Op, Val); 11629 case 'B': 11630 return isInt<32>(Val); 11631 case 'C': 11632 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11633 AMDGPU::isInlinableIntLiteral(Val); 11634 default: 11635 break; 11636 } 11637 } else if (Constraint.size() == 2) { 11638 if (Constraint == "DA") { 11639 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11640 int64_t LoBits = static_cast<int32_t>(Val); 11641 return checkAsmConstraintValA(Op, HiBits, 32) && 11642 checkAsmConstraintValA(Op, LoBits, 32); 11643 } 11644 if (Constraint == "DB") { 11645 return true; 11646 } 11647 } 11648 llvm_unreachable("Invalid asm constraint"); 11649 } 11650 11651 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11652 uint64_t Val, 11653 unsigned MaxSize) const { 11654 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11655 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11656 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11657 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11658 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11659 return true; 11660 } 11661 return false; 11662 } 11663 11664 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 11665 switch (UnalignedClassID) { 11666 case AMDGPU::VReg_64RegClassID: 11667 return AMDGPU::VReg_64_Align2RegClassID; 11668 case AMDGPU::VReg_96RegClassID: 11669 return AMDGPU::VReg_96_Align2RegClassID; 11670 case AMDGPU::VReg_128RegClassID: 11671 return AMDGPU::VReg_128_Align2RegClassID; 11672 case AMDGPU::VReg_160RegClassID: 11673 return AMDGPU::VReg_160_Align2RegClassID; 11674 case AMDGPU::VReg_192RegClassID: 11675 return AMDGPU::VReg_192_Align2RegClassID; 11676 case AMDGPU::VReg_256RegClassID: 11677 return AMDGPU::VReg_256_Align2RegClassID; 11678 case AMDGPU::VReg_512RegClassID: 11679 return AMDGPU::VReg_512_Align2RegClassID; 11680 case AMDGPU::VReg_1024RegClassID: 11681 return AMDGPU::VReg_1024_Align2RegClassID; 11682 case AMDGPU::AReg_64RegClassID: 11683 return AMDGPU::AReg_64_Align2RegClassID; 11684 case AMDGPU::AReg_96RegClassID: 11685 return AMDGPU::AReg_96_Align2RegClassID; 11686 case AMDGPU::AReg_128RegClassID: 11687 return AMDGPU::AReg_128_Align2RegClassID; 11688 case AMDGPU::AReg_160RegClassID: 11689 return AMDGPU::AReg_160_Align2RegClassID; 11690 case AMDGPU::AReg_192RegClassID: 11691 return AMDGPU::AReg_192_Align2RegClassID; 11692 case AMDGPU::AReg_256RegClassID: 11693 return AMDGPU::AReg_256_Align2RegClassID; 11694 case AMDGPU::AReg_512RegClassID: 11695 return AMDGPU::AReg_512_Align2RegClassID; 11696 case AMDGPU::AReg_1024RegClassID: 11697 return AMDGPU::AReg_1024_Align2RegClassID; 11698 default: 11699 return -1; 11700 } 11701 } 11702 11703 // Figure out which registers should be reserved for stack access. Only after 11704 // the function is legalized do we know all of the non-spill stack objects or if 11705 // calls are present. 11706 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11707 MachineRegisterInfo &MRI = MF.getRegInfo(); 11708 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11709 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11710 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11711 const SIInstrInfo *TII = ST.getInstrInfo(); 11712 11713 if (Info->isEntryFunction()) { 11714 // Callable functions have fixed registers used for stack access. 11715 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11716 } 11717 11718 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11719 Info->getStackPtrOffsetReg())); 11720 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11721 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11722 11723 // We need to worry about replacing the default register with itself in case 11724 // of MIR testcases missing the MFI. 11725 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11726 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11727 11728 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11729 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11730 11731 Info->limitOccupancy(MF); 11732 11733 if (ST.isWave32() && !MF.empty()) { 11734 for (auto &MBB : MF) { 11735 for (auto &MI : MBB) { 11736 TII->fixImplicitOperands(MI); 11737 } 11738 } 11739 } 11740 11741 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 11742 // classes if required. Ideally the register class constraints would differ 11743 // per-subtarget, but there's no easy way to achieve that right now. This is 11744 // not a problem for VGPRs because the correctly aligned VGPR class is implied 11745 // from using them as the register class for legal types. 11746 if (ST.needsAlignedVGPRs()) { 11747 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 11748 const Register Reg = Register::index2VirtReg(I); 11749 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 11750 if (!RC) 11751 continue; 11752 int NewClassID = getAlignedAGPRClassID(RC->getID()); 11753 if (NewClassID != -1) 11754 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 11755 } 11756 } 11757 11758 TargetLoweringBase::finalizeLowering(MF); 11759 11760 // Allocate a VGPR for future SGPR Spill if 11761 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11762 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11763 if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() && 11764 !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction()) 11765 Info->reserveVGPRforSGPRSpills(MF); 11766 } 11767 11768 void SITargetLowering::computeKnownBitsForFrameIndex( 11769 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11770 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11771 11772 // Set the high bits to zero based on the maximum allowed scratch size per 11773 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11774 // calculation won't overflow, so assume the sign bit is never set. 11775 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11776 } 11777 11778 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11779 KnownBits &Known, unsigned Dim) { 11780 unsigned MaxValue = 11781 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11782 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11783 } 11784 11785 void SITargetLowering::computeKnownBitsForTargetInstr( 11786 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11787 const MachineRegisterInfo &MRI, unsigned Depth) const { 11788 const MachineInstr *MI = MRI.getVRegDef(R); 11789 switch (MI->getOpcode()) { 11790 case AMDGPU::G_INTRINSIC: { 11791 switch (MI->getIntrinsicID()) { 11792 case Intrinsic::amdgcn_workitem_id_x: 11793 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11794 break; 11795 case Intrinsic::amdgcn_workitem_id_y: 11796 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11797 break; 11798 case Intrinsic::amdgcn_workitem_id_z: 11799 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11800 break; 11801 case Intrinsic::amdgcn_mbcnt_lo: 11802 case Intrinsic::amdgcn_mbcnt_hi: { 11803 // These return at most the wavefront size - 1. 11804 unsigned Size = MRI.getType(R).getSizeInBits(); 11805 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11806 break; 11807 } 11808 case Intrinsic::amdgcn_groupstaticsize: { 11809 // We can report everything over the maximum size as 0. We can't report 11810 // based on the actual size because we don't know if it's accurate or not 11811 // at any given point. 11812 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11813 break; 11814 } 11815 } 11816 break; 11817 } 11818 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 11819 Known.Zero.setHighBits(24); 11820 break; 11821 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 11822 Known.Zero.setHighBits(16); 11823 break; 11824 } 11825 } 11826 11827 Align SITargetLowering::computeKnownAlignForTargetInstr( 11828 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11829 unsigned Depth) const { 11830 const MachineInstr *MI = MRI.getVRegDef(R); 11831 switch (MI->getOpcode()) { 11832 case AMDGPU::G_INTRINSIC: 11833 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11834 // FIXME: Can this move to generic code? What about the case where the call 11835 // site specifies a lower alignment? 11836 Intrinsic::ID IID = MI->getIntrinsicID(); 11837 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11838 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11839 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11840 return *RetAlign; 11841 return Align(1); 11842 } 11843 default: 11844 return Align(1); 11845 } 11846 } 11847 11848 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11849 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11850 const Align CacheLineAlign = Align(64); 11851 11852 // Pre-GFX10 target did not benefit from loop alignment 11853 if (!ML || DisableLoopAlignment || 11854 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11855 getSubtarget()->hasInstFwdPrefetchBug()) 11856 return PrefAlign; 11857 11858 // On GFX10 I$ is 4 x 64 bytes cache lines. 11859 // By default prefetcher keeps one cache line behind and reads two ahead. 11860 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11861 // behind and one ahead. 11862 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11863 // If loop fits 64 bytes it always spans no more than two cache lines and 11864 // does not need an alignment. 11865 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11866 // Else if loop is less or equal 192 bytes we need two lines behind. 11867 11868 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11869 const MachineBasicBlock *Header = ML->getHeader(); 11870 if (Header->getAlignment() != PrefAlign) 11871 return Header->getAlignment(); // Already processed. 11872 11873 unsigned LoopSize = 0; 11874 for (const MachineBasicBlock *MBB : ML->blocks()) { 11875 // If inner loop block is aligned assume in average half of the alignment 11876 // size to be added as nops. 11877 if (MBB != Header) 11878 LoopSize += MBB->getAlignment().value() / 2; 11879 11880 for (const MachineInstr &MI : *MBB) { 11881 LoopSize += TII->getInstSizeInBytes(MI); 11882 if (LoopSize > 192) 11883 return PrefAlign; 11884 } 11885 } 11886 11887 if (LoopSize <= 64) 11888 return PrefAlign; 11889 11890 if (LoopSize <= 128) 11891 return CacheLineAlign; 11892 11893 // If any of parent loops is surrounded by prefetch instructions do not 11894 // insert new for inner loop, which would reset parent's settings. 11895 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11896 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11897 auto I = Exit->getFirstNonDebugInstr(); 11898 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11899 return CacheLineAlign; 11900 } 11901 } 11902 11903 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11904 MachineBasicBlock *Exit = ML->getExitBlock(); 11905 11906 if (Pre && Exit) { 11907 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11908 TII->get(AMDGPU::S_INST_PREFETCH)) 11909 .addImm(1); // prefetch 2 lines behind PC 11910 11911 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11912 TII->get(AMDGPU::S_INST_PREFETCH)) 11913 .addImm(2); // prefetch 1 line behind PC 11914 } 11915 11916 return CacheLineAlign; 11917 } 11918 11919 LLVM_ATTRIBUTE_UNUSED 11920 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11921 assert(N->getOpcode() == ISD::CopyFromReg); 11922 do { 11923 // Follow the chain until we find an INLINEASM node. 11924 N = N->getOperand(0).getNode(); 11925 if (N->getOpcode() == ISD::INLINEASM || 11926 N->getOpcode() == ISD::INLINEASM_BR) 11927 return true; 11928 } while (N->getOpcode() == ISD::CopyFromReg); 11929 return false; 11930 } 11931 11932 bool SITargetLowering::isSDNodeSourceOfDivergence( 11933 const SDNode *N, FunctionLoweringInfo *FLI, 11934 LegacyDivergenceAnalysis *KDA) const { 11935 switch (N->getOpcode()) { 11936 case ISD::CopyFromReg: { 11937 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11938 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11939 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11940 Register Reg = R->getReg(); 11941 11942 // FIXME: Why does this need to consider isLiveIn? 11943 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11944 return !TRI->isSGPRReg(MRI, Reg); 11945 11946 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11947 return KDA->isDivergent(V); 11948 11949 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11950 return !TRI->isSGPRReg(MRI, Reg); 11951 } 11952 case ISD::LOAD: { 11953 const LoadSDNode *L = cast<LoadSDNode>(N); 11954 unsigned AS = L->getAddressSpace(); 11955 // A flat load may access private memory. 11956 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11957 } 11958 case ISD::CALLSEQ_END: 11959 return true; 11960 case ISD::INTRINSIC_WO_CHAIN: 11961 return AMDGPU::isIntrinsicSourceOfDivergence( 11962 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11963 case ISD::INTRINSIC_W_CHAIN: 11964 return AMDGPU::isIntrinsicSourceOfDivergence( 11965 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11966 case AMDGPUISD::ATOMIC_CMP_SWAP: 11967 case AMDGPUISD::ATOMIC_INC: 11968 case AMDGPUISD::ATOMIC_DEC: 11969 case AMDGPUISD::ATOMIC_LOAD_FMIN: 11970 case AMDGPUISD::ATOMIC_LOAD_FMAX: 11971 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 11972 case AMDGPUISD::BUFFER_ATOMIC_ADD: 11973 case AMDGPUISD::BUFFER_ATOMIC_SUB: 11974 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 11975 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 11976 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 11977 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 11978 case AMDGPUISD::BUFFER_ATOMIC_AND: 11979 case AMDGPUISD::BUFFER_ATOMIC_OR: 11980 case AMDGPUISD::BUFFER_ATOMIC_XOR: 11981 case AMDGPUISD::BUFFER_ATOMIC_INC: 11982 case AMDGPUISD::BUFFER_ATOMIC_DEC: 11983 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 11984 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 11985 case AMDGPUISD::BUFFER_ATOMIC_FADD: 11986 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 11987 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 11988 // Target-specific read-modify-write atomics are sources of divergence. 11989 return true; 11990 default: 11991 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 11992 // Generic read-modify-write atomics are sources of divergence. 11993 return A->readMem() && A->writeMem(); 11994 } 11995 return false; 11996 } 11997 } 11998 11999 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12000 EVT VT) const { 12001 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12002 case MVT::f32: 12003 return hasFP32Denormals(DAG.getMachineFunction()); 12004 case MVT::f64: 12005 case MVT::f16: 12006 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12007 default: 12008 return false; 12009 } 12010 } 12011 12012 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12013 const SelectionDAG &DAG, 12014 bool SNaN, 12015 unsigned Depth) const { 12016 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12017 const MachineFunction &MF = DAG.getMachineFunction(); 12018 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12019 12020 if (Info->getMode().DX10Clamp) 12021 return true; // Clamped to 0. 12022 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12023 } 12024 12025 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12026 SNaN, Depth); 12027 } 12028 12029 // Global FP atomic instructions have a hardcoded FP mode and do not support 12030 // FP32 denormals, and only support v2f16 denormals. 12031 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12032 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12033 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12034 if (&Flt == &APFloat::IEEEsingle()) 12035 return DenormMode == DenormalMode::getPreserveSign(); 12036 return DenormMode == DenormalMode::getIEEE(); 12037 } 12038 12039 TargetLowering::AtomicExpansionKind 12040 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12041 switch (RMW->getOperation()) { 12042 case AtomicRMWInst::FAdd: { 12043 Type *Ty = RMW->getType(); 12044 12045 // We don't have a way to support 16-bit atomics now, so just leave them 12046 // as-is. 12047 if (Ty->isHalfTy()) 12048 return AtomicExpansionKind::None; 12049 12050 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12051 return AtomicExpansionKind::CmpXChg; 12052 12053 // TODO: Do have these for flat. Older targets also had them for buffers. 12054 unsigned AS = RMW->getPointerAddressSpace(); 12055 12056 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12057 Subtarget->hasAtomicFaddInsts()) { 12058 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12059 // floating point atomic instructions. May generate more efficient code, 12060 // but may not respect rounding and denormal modes, and may give incorrect 12061 // results for certain memory destinations. 12062 if (!fpModeMatchesGlobalFPAtomicMode(RMW) && 12063 RMW->getFunction() 12064 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12065 .getValueAsString() != "true") 12066 return AtomicExpansionKind::CmpXChg; 12067 12068 if (Subtarget->hasGFX90AInsts()) { 12069 auto SSID = RMW->getSyncScopeID(); 12070 if (SSID == SyncScope::System || 12071 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12072 return AtomicExpansionKind::CmpXChg; 12073 12074 return (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) ? 12075 AtomicExpansionKind::CmpXChg : AtomicExpansionKind::None; 12076 } 12077 12078 if (!Subtarget->hasGFX90AInsts() && AS != AMDGPUAS::GLOBAL_ADDRESS) 12079 return AtomicExpansionKind::CmpXChg; 12080 12081 return RMW->use_empty() ? AtomicExpansionKind::None : 12082 AtomicExpansionKind::CmpXChg; 12083 } 12084 12085 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 12086 // to round-to-nearest-even. 12087 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12088 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) { 12089 return (Ty->isDoubleTy() && !fpModeMatchesGlobalFPAtomicMode(RMW)) ? 12090 AtomicExpansionKind::CmpXChg : AtomicExpansionKind::None; 12091 } 12092 12093 return AtomicExpansionKind::CmpXChg; 12094 } 12095 default: 12096 break; 12097 } 12098 12099 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12100 } 12101 12102 const TargetRegisterClass * 12103 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12104 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12105 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12106 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12107 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12108 : &AMDGPU::SReg_32RegClass; 12109 if (!TRI->isSGPRClass(RC) && !isDivergent) 12110 return TRI->getEquivalentSGPRClass(RC); 12111 else if (TRI->isSGPRClass(RC) && isDivergent) 12112 return TRI->getEquivalentVGPRClass(RC); 12113 12114 return RC; 12115 } 12116 12117 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12118 // uniform values (as produced by the mask results of control flow intrinsics) 12119 // used outside of divergent blocks. The phi users need to also be treated as 12120 // always uniform. 12121 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12122 unsigned WaveSize) { 12123 // FIXME: We asssume we never cast the mask results of a control flow 12124 // intrinsic. 12125 // Early exit if the type won't be consistent as a compile time hack. 12126 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12127 if (!IT || IT->getBitWidth() != WaveSize) 12128 return false; 12129 12130 if (!isa<Instruction>(V)) 12131 return false; 12132 if (!Visited.insert(V).second) 12133 return false; 12134 bool Result = false; 12135 for (auto U : V->users()) { 12136 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12137 if (V == U->getOperand(1)) { 12138 switch (Intrinsic->getIntrinsicID()) { 12139 default: 12140 Result = false; 12141 break; 12142 case Intrinsic::amdgcn_if_break: 12143 case Intrinsic::amdgcn_if: 12144 case Intrinsic::amdgcn_else: 12145 Result = true; 12146 break; 12147 } 12148 } 12149 if (V == U->getOperand(0)) { 12150 switch (Intrinsic->getIntrinsicID()) { 12151 default: 12152 Result = false; 12153 break; 12154 case Intrinsic::amdgcn_end_cf: 12155 case Intrinsic::amdgcn_loop: 12156 Result = true; 12157 break; 12158 } 12159 } 12160 } else { 12161 Result = hasCFUser(U, Visited, WaveSize); 12162 } 12163 if (Result) 12164 break; 12165 } 12166 return Result; 12167 } 12168 12169 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12170 const Value *V) const { 12171 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12172 if (CI->isInlineAsm()) { 12173 // FIXME: This cannot give a correct answer. This should only trigger in 12174 // the case where inline asm returns mixed SGPR and VGPR results, used 12175 // outside the defining block. We don't have a specific result to 12176 // consider, so this assumes if any value is SGPR, the overall register 12177 // also needs to be SGPR. 12178 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12179 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12180 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12181 for (auto &TC : TargetConstraints) { 12182 if (TC.Type == InlineAsm::isOutput) { 12183 ComputeConstraintToUse(TC, SDValue()); 12184 unsigned AssignedReg; 12185 const TargetRegisterClass *RC; 12186 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 12187 SIRI, TC.ConstraintCode, TC.ConstraintVT); 12188 if (RC) { 12189 MachineRegisterInfo &MRI = MF.getRegInfo(); 12190 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 12191 return true; 12192 else if (SIRI->isSGPRClass(RC)) 12193 return true; 12194 } 12195 } 12196 } 12197 } 12198 } 12199 SmallPtrSet<const Value *, 16> Visited; 12200 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12201 } 12202 12203 std::pair<int, MVT> 12204 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12205 Type *Ty) const { 12206 auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12207 auto Size = DL.getTypeSizeInBits(Ty); 12208 // Maximum load or store can handle 8 dwords for scalar and 4 for 12209 // vector ALU. Let's assume anything above 8 dwords is expensive 12210 // even if legal. 12211 if (Size <= 256) 12212 return Cost; 12213 12214 Cost.first = (Size + 255) / 256; 12215 return Cost; 12216 } 12217