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, Custom); 535 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom); 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 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 && 1572 VT.getScalarType().bitsLE(MVT::i16)) 1573 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1574 return TargetLoweringBase::getPreferredVectorAction(VT); 1575 } 1576 1577 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1578 Type *Ty) const { 1579 // FIXME: Could be smarter if called for vector constants. 1580 return true; 1581 } 1582 1583 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1584 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1585 switch (Op) { 1586 case ISD::LOAD: 1587 case ISD::STORE: 1588 1589 // These operations are done with 32-bit instructions anyway. 1590 case ISD::AND: 1591 case ISD::OR: 1592 case ISD::XOR: 1593 case ISD::SELECT: 1594 // TODO: Extensions? 1595 return true; 1596 default: 1597 return false; 1598 } 1599 } 1600 1601 // SimplifySetCC uses this function to determine whether or not it should 1602 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1603 if (VT == MVT::i1 && Op == ISD::SETCC) 1604 return false; 1605 1606 return TargetLowering::isTypeDesirableForOp(Op, VT); 1607 } 1608 1609 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1610 const SDLoc &SL, 1611 SDValue Chain, 1612 uint64_t Offset) const { 1613 const DataLayout &DL = DAG.getDataLayout(); 1614 MachineFunction &MF = DAG.getMachineFunction(); 1615 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1616 1617 const ArgDescriptor *InputPtrReg; 1618 const TargetRegisterClass *RC; 1619 LLT ArgTy; 1620 1621 std::tie(InputPtrReg, RC, ArgTy) = 1622 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1623 1624 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1625 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1626 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1627 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1628 1629 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1630 } 1631 1632 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1633 const SDLoc &SL) const { 1634 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1635 FIRST_IMPLICIT); 1636 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1637 } 1638 1639 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1640 const SDLoc &SL, SDValue Val, 1641 bool Signed, 1642 const ISD::InputArg *Arg) const { 1643 // First, if it is a widened vector, narrow it. 1644 if (VT.isVector() && 1645 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1646 EVT NarrowedVT = 1647 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1648 VT.getVectorNumElements()); 1649 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1650 DAG.getConstant(0, SL, MVT::i32)); 1651 } 1652 1653 // Then convert the vector elements or scalar value. 1654 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1655 VT.bitsLT(MemVT)) { 1656 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1657 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1658 } 1659 1660 if (MemVT.isFloatingPoint()) 1661 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1662 else if (Signed) 1663 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1664 else 1665 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1666 1667 return Val; 1668 } 1669 1670 SDValue SITargetLowering::lowerKernargMemParameter( 1671 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1672 uint64_t Offset, Align Alignment, bool Signed, 1673 const ISD::InputArg *Arg) const { 1674 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1675 1676 // Try to avoid using an extload by loading earlier than the argument address, 1677 // and extracting the relevant bits. The load should hopefully be merged with 1678 // the previous argument. 1679 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1680 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1681 int64_t AlignDownOffset = alignDown(Offset, 4); 1682 int64_t OffsetDiff = Offset - AlignDownOffset; 1683 1684 EVT IntVT = MemVT.changeTypeToInteger(); 1685 1686 // TODO: If we passed in the base kernel offset we could have a better 1687 // alignment than 4, but we don't really need it. 1688 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1689 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1690 MachineMemOperand::MODereferenceable | 1691 MachineMemOperand::MOInvariant); 1692 1693 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1694 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1695 1696 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1697 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1698 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1699 1700 1701 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1702 } 1703 1704 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1705 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1706 MachineMemOperand::MODereferenceable | 1707 MachineMemOperand::MOInvariant); 1708 1709 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1710 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1711 } 1712 1713 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1714 const SDLoc &SL, SDValue Chain, 1715 const ISD::InputArg &Arg) const { 1716 MachineFunction &MF = DAG.getMachineFunction(); 1717 MachineFrameInfo &MFI = MF.getFrameInfo(); 1718 1719 if (Arg.Flags.isByVal()) { 1720 unsigned Size = Arg.Flags.getByValSize(); 1721 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1722 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1723 } 1724 1725 unsigned ArgOffset = VA.getLocMemOffset(); 1726 unsigned ArgSize = VA.getValVT().getStoreSize(); 1727 1728 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1729 1730 // Create load nodes to retrieve arguments from the stack. 1731 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1732 SDValue ArgValue; 1733 1734 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1735 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1736 MVT MemVT = VA.getValVT(); 1737 1738 switch (VA.getLocInfo()) { 1739 default: 1740 break; 1741 case CCValAssign::BCvt: 1742 MemVT = VA.getLocVT(); 1743 break; 1744 case CCValAssign::SExt: 1745 ExtType = ISD::SEXTLOAD; 1746 break; 1747 case CCValAssign::ZExt: 1748 ExtType = ISD::ZEXTLOAD; 1749 break; 1750 case CCValAssign::AExt: 1751 ExtType = ISD::EXTLOAD; 1752 break; 1753 } 1754 1755 ArgValue = DAG.getExtLoad( 1756 ExtType, SL, VA.getLocVT(), Chain, FIN, 1757 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1758 MemVT); 1759 return ArgValue; 1760 } 1761 1762 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1763 const SIMachineFunctionInfo &MFI, 1764 EVT VT, 1765 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1766 const ArgDescriptor *Reg; 1767 const TargetRegisterClass *RC; 1768 LLT Ty; 1769 1770 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1771 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1772 } 1773 1774 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1775 CallingConv::ID CallConv, 1776 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1777 FunctionType *FType, 1778 SIMachineFunctionInfo *Info) { 1779 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1780 const ISD::InputArg *Arg = &Ins[I]; 1781 1782 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1783 "vector type argument should have been split"); 1784 1785 // First check if it's a PS input addr. 1786 if (CallConv == CallingConv::AMDGPU_PS && 1787 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1788 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1789 1790 // Inconveniently only the first part of the split is marked as isSplit, 1791 // so skip to the end. We only want to increment PSInputNum once for the 1792 // entire split argument. 1793 if (Arg->Flags.isSplit()) { 1794 while (!Arg->Flags.isSplitEnd()) { 1795 assert((!Arg->VT.isVector() || 1796 Arg->VT.getScalarSizeInBits() == 16) && 1797 "unexpected vector split in ps argument type"); 1798 if (!SkipArg) 1799 Splits.push_back(*Arg); 1800 Arg = &Ins[++I]; 1801 } 1802 } 1803 1804 if (SkipArg) { 1805 // We can safely skip PS inputs. 1806 Skipped.set(Arg->getOrigArgIndex()); 1807 ++PSInputNum; 1808 continue; 1809 } 1810 1811 Info->markPSInputAllocated(PSInputNum); 1812 if (Arg->Used) 1813 Info->markPSInputEnabled(PSInputNum); 1814 1815 ++PSInputNum; 1816 } 1817 1818 Splits.push_back(*Arg); 1819 } 1820 } 1821 1822 // Allocate special inputs passed in VGPRs. 1823 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1824 MachineFunction &MF, 1825 const SIRegisterInfo &TRI, 1826 SIMachineFunctionInfo &Info) const { 1827 const LLT S32 = LLT::scalar(32); 1828 MachineRegisterInfo &MRI = MF.getRegInfo(); 1829 1830 if (Info.hasWorkItemIDX()) { 1831 Register Reg = AMDGPU::VGPR0; 1832 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1833 1834 CCInfo.AllocateReg(Reg); 1835 unsigned Mask = (Subtarget->hasPackedTID() && 1836 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 1837 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1838 } 1839 1840 if (Info.hasWorkItemIDY()) { 1841 assert(Info.hasWorkItemIDX()); 1842 if (Subtarget->hasPackedTID()) { 1843 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1844 0x3ff << 10)); 1845 } else { 1846 unsigned Reg = AMDGPU::VGPR1; 1847 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1848 1849 CCInfo.AllocateReg(Reg); 1850 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1851 } 1852 } 1853 1854 if (Info.hasWorkItemIDZ()) { 1855 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 1856 if (Subtarget->hasPackedTID()) { 1857 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1858 0x3ff << 20)); 1859 } else { 1860 unsigned Reg = AMDGPU::VGPR2; 1861 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1862 1863 CCInfo.AllocateReg(Reg); 1864 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1865 } 1866 } 1867 } 1868 1869 // Try to allocate a VGPR at the end of the argument list, or if no argument 1870 // VGPRs are left allocating a stack slot. 1871 // If \p Mask is is given it indicates bitfield position in the register. 1872 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1873 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1874 ArgDescriptor Arg = ArgDescriptor()) { 1875 if (Arg.isSet()) 1876 return ArgDescriptor::createArg(Arg, Mask); 1877 1878 ArrayRef<MCPhysReg> ArgVGPRs 1879 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1880 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1881 if (RegIdx == ArgVGPRs.size()) { 1882 // Spill to stack required. 1883 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1884 1885 return ArgDescriptor::createStack(Offset, Mask); 1886 } 1887 1888 unsigned Reg = ArgVGPRs[RegIdx]; 1889 Reg = CCInfo.AllocateReg(Reg); 1890 assert(Reg != AMDGPU::NoRegister); 1891 1892 MachineFunction &MF = CCInfo.getMachineFunction(); 1893 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1894 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1895 return ArgDescriptor::createRegister(Reg, Mask); 1896 } 1897 1898 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1899 const TargetRegisterClass *RC, 1900 unsigned NumArgRegs) { 1901 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1902 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1903 if (RegIdx == ArgSGPRs.size()) 1904 report_fatal_error("ran out of SGPRs for arguments"); 1905 1906 unsigned Reg = ArgSGPRs[RegIdx]; 1907 Reg = CCInfo.AllocateReg(Reg); 1908 assert(Reg != AMDGPU::NoRegister); 1909 1910 MachineFunction &MF = CCInfo.getMachineFunction(); 1911 MF.addLiveIn(Reg, RC); 1912 return ArgDescriptor::createRegister(Reg); 1913 } 1914 1915 // If this has a fixed position, we still should allocate the register in the 1916 // CCInfo state. Technically we could get away with this for values passed 1917 // outside of the normal argument range. 1918 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 1919 const TargetRegisterClass *RC, 1920 MCRegister Reg) { 1921 Reg = CCInfo.AllocateReg(Reg); 1922 assert(Reg != AMDGPU::NoRegister); 1923 MachineFunction &MF = CCInfo.getMachineFunction(); 1924 MF.addLiveIn(Reg, RC); 1925 } 1926 1927 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 1928 if (Arg) { 1929 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 1930 Arg.getRegister()); 1931 } else 1932 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1933 } 1934 1935 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 1936 if (Arg) { 1937 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 1938 Arg.getRegister()); 1939 } else 1940 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1941 } 1942 1943 /// Allocate implicit function VGPR arguments at the end of allocated user 1944 /// arguments. 1945 void SITargetLowering::allocateSpecialInputVGPRs( 1946 CCState &CCInfo, MachineFunction &MF, 1947 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1948 const unsigned Mask = 0x3ff; 1949 ArgDescriptor Arg; 1950 1951 if (Info.hasWorkItemIDX()) { 1952 Arg = allocateVGPR32Input(CCInfo, Mask); 1953 Info.setWorkItemIDX(Arg); 1954 } 1955 1956 if (Info.hasWorkItemIDY()) { 1957 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1958 Info.setWorkItemIDY(Arg); 1959 } 1960 1961 if (Info.hasWorkItemIDZ()) 1962 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1963 } 1964 1965 /// Allocate implicit function VGPR arguments in fixed registers. 1966 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1967 CCState &CCInfo, MachineFunction &MF, 1968 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1969 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1970 if (!Reg) 1971 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1972 1973 const unsigned Mask = 0x3ff; 1974 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1975 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1976 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1977 } 1978 1979 void SITargetLowering::allocateSpecialInputSGPRs( 1980 CCState &CCInfo, 1981 MachineFunction &MF, 1982 const SIRegisterInfo &TRI, 1983 SIMachineFunctionInfo &Info) const { 1984 auto &ArgInfo = Info.getArgInfo(); 1985 1986 // TODO: Unify handling with private memory pointers. 1987 1988 if (Info.hasDispatchPtr()) 1989 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 1990 1991 if (Info.hasQueuePtr()) 1992 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 1993 1994 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1995 // constant offset from the kernarg segment. 1996 if (Info.hasImplicitArgPtr()) 1997 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 1998 1999 if (Info.hasDispatchID()) 2000 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 2001 2002 // flat_scratch_init is not applicable for non-kernel functions. 2003 2004 if (Info.hasWorkGroupIDX()) 2005 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2006 2007 if (Info.hasWorkGroupIDY()) 2008 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2009 2010 if (Info.hasWorkGroupIDZ()) 2011 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2012 } 2013 2014 // Allocate special inputs passed in user SGPRs. 2015 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2016 MachineFunction &MF, 2017 const SIRegisterInfo &TRI, 2018 SIMachineFunctionInfo &Info) const { 2019 if (Info.hasImplicitBufferPtr()) { 2020 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2021 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2022 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2023 } 2024 2025 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2026 if (Info.hasPrivateSegmentBuffer()) { 2027 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2028 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2029 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2030 } 2031 2032 if (Info.hasDispatchPtr()) { 2033 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2034 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2035 CCInfo.AllocateReg(DispatchPtrReg); 2036 } 2037 2038 if (Info.hasQueuePtr()) { 2039 Register QueuePtrReg = Info.addQueuePtr(TRI); 2040 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2041 CCInfo.AllocateReg(QueuePtrReg); 2042 } 2043 2044 if (Info.hasKernargSegmentPtr()) { 2045 MachineRegisterInfo &MRI = MF.getRegInfo(); 2046 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2047 CCInfo.AllocateReg(InputPtrReg); 2048 2049 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2050 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2051 } 2052 2053 if (Info.hasDispatchID()) { 2054 Register DispatchIDReg = Info.addDispatchID(TRI); 2055 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2056 CCInfo.AllocateReg(DispatchIDReg); 2057 } 2058 2059 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2060 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2061 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2062 CCInfo.AllocateReg(FlatScratchInitReg); 2063 } 2064 2065 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2066 // these from the dispatch pointer. 2067 } 2068 2069 // Allocate special input registers that are initialized per-wave. 2070 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2071 MachineFunction &MF, 2072 SIMachineFunctionInfo &Info, 2073 CallingConv::ID CallConv, 2074 bool IsShader) const { 2075 if (Info.hasWorkGroupIDX()) { 2076 Register Reg = Info.addWorkGroupIDX(); 2077 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2078 CCInfo.AllocateReg(Reg); 2079 } 2080 2081 if (Info.hasWorkGroupIDY()) { 2082 Register Reg = Info.addWorkGroupIDY(); 2083 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2084 CCInfo.AllocateReg(Reg); 2085 } 2086 2087 if (Info.hasWorkGroupIDZ()) { 2088 Register Reg = Info.addWorkGroupIDZ(); 2089 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2090 CCInfo.AllocateReg(Reg); 2091 } 2092 2093 if (Info.hasWorkGroupInfo()) { 2094 Register Reg = Info.addWorkGroupInfo(); 2095 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2096 CCInfo.AllocateReg(Reg); 2097 } 2098 2099 if (Info.hasPrivateSegmentWaveByteOffset()) { 2100 // Scratch wave offset passed in system SGPR. 2101 unsigned PrivateSegmentWaveByteOffsetReg; 2102 2103 if (IsShader) { 2104 PrivateSegmentWaveByteOffsetReg = 2105 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2106 2107 // This is true if the scratch wave byte offset doesn't have a fixed 2108 // location. 2109 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2110 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2111 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2112 } 2113 } else 2114 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2115 2116 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2117 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2118 } 2119 } 2120 2121 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2122 MachineFunction &MF, 2123 const SIRegisterInfo &TRI, 2124 SIMachineFunctionInfo &Info) { 2125 // Now that we've figured out where the scratch register inputs are, see if 2126 // should reserve the arguments and use them directly. 2127 MachineFrameInfo &MFI = MF.getFrameInfo(); 2128 bool HasStackObjects = MFI.hasStackObjects(); 2129 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2130 2131 // Record that we know we have non-spill stack objects so we don't need to 2132 // check all stack objects later. 2133 if (HasStackObjects) 2134 Info.setHasNonSpillStackObjects(true); 2135 2136 // Everything live out of a block is spilled with fast regalloc, so it's 2137 // almost certain that spilling will be required. 2138 if (TM.getOptLevel() == CodeGenOpt::None) 2139 HasStackObjects = true; 2140 2141 // For now assume stack access is needed in any callee functions, so we need 2142 // the scratch registers to pass in. 2143 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2144 2145 if (!ST.enableFlatScratch()) { 2146 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2147 // If we have stack objects, we unquestionably need the private buffer 2148 // resource. For the Code Object V2 ABI, this will be the first 4 user 2149 // SGPR inputs. We can reserve those and use them directly. 2150 2151 Register PrivateSegmentBufferReg = 2152 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2153 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2154 } else { 2155 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2156 // We tentatively reserve the last registers (skipping the last registers 2157 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2158 // we'll replace these with the ones immediately after those which were 2159 // really allocated. In the prologue copies will be inserted from the 2160 // argument to these reserved registers. 2161 2162 // Without HSA, relocations are used for the scratch pointer and the 2163 // buffer resource setup is always inserted in the prologue. Scratch wave 2164 // offset is still in an input SGPR. 2165 Info.setScratchRSrcReg(ReservedBufferReg); 2166 } 2167 } 2168 2169 MachineRegisterInfo &MRI = MF.getRegInfo(); 2170 2171 // For entry functions we have to set up the stack pointer if we use it, 2172 // whereas non-entry functions get this "for free". This means there is no 2173 // intrinsic advantage to using S32 over S34 in cases where we do not have 2174 // calls but do need a frame pointer (i.e. if we are requested to have one 2175 // because frame pointer elimination is disabled). To keep things simple we 2176 // only ever use S32 as the call ABI stack pointer, and so using it does not 2177 // imply we need a separate frame pointer. 2178 // 2179 // Try to use s32 as the SP, but move it if it would interfere with input 2180 // arguments. This won't work with calls though. 2181 // 2182 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2183 // registers. 2184 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2185 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2186 } else { 2187 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2188 2189 if (MFI.hasCalls()) 2190 report_fatal_error("call in graphics shader with too many input SGPRs"); 2191 2192 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2193 if (!MRI.isLiveIn(Reg)) { 2194 Info.setStackPtrOffsetReg(Reg); 2195 break; 2196 } 2197 } 2198 2199 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2200 report_fatal_error("failed to find register for SP"); 2201 } 2202 2203 // hasFP should be accurate for entry functions even before the frame is 2204 // finalized, because it does not rely on the known stack size, only 2205 // properties like whether variable sized objects are present. 2206 if (ST.getFrameLowering()->hasFP(MF)) { 2207 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2208 } 2209 } 2210 2211 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2212 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2213 return !Info->isEntryFunction(); 2214 } 2215 2216 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2217 2218 } 2219 2220 void SITargetLowering::insertCopiesSplitCSR( 2221 MachineBasicBlock *Entry, 2222 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2223 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2224 2225 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2226 if (!IStart) 2227 return; 2228 2229 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2230 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2231 MachineBasicBlock::iterator MBBI = Entry->begin(); 2232 for (const MCPhysReg *I = IStart; *I; ++I) { 2233 const TargetRegisterClass *RC = nullptr; 2234 if (AMDGPU::SReg_64RegClass.contains(*I)) 2235 RC = &AMDGPU::SGPR_64RegClass; 2236 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2237 RC = &AMDGPU::SGPR_32RegClass; 2238 else 2239 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2240 2241 Register NewVR = MRI->createVirtualRegister(RC); 2242 // Create copy from CSR to a virtual register. 2243 Entry->addLiveIn(*I); 2244 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2245 .addReg(*I); 2246 2247 // Insert the copy-back instructions right before the terminator. 2248 for (auto *Exit : Exits) 2249 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2250 TII->get(TargetOpcode::COPY), *I) 2251 .addReg(NewVR); 2252 } 2253 } 2254 2255 SDValue SITargetLowering::LowerFormalArguments( 2256 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2257 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2258 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2259 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2260 2261 MachineFunction &MF = DAG.getMachineFunction(); 2262 const Function &Fn = MF.getFunction(); 2263 FunctionType *FType = MF.getFunction().getFunctionType(); 2264 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2265 2266 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2267 DiagnosticInfoUnsupported NoGraphicsHSA( 2268 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2269 DAG.getContext()->diagnose(NoGraphicsHSA); 2270 return DAG.getEntryNode(); 2271 } 2272 2273 Info->allocateModuleLDSGlobal(Fn.getParent()); 2274 2275 SmallVector<ISD::InputArg, 16> Splits; 2276 SmallVector<CCValAssign, 16> ArgLocs; 2277 BitVector Skipped(Ins.size()); 2278 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2279 *DAG.getContext()); 2280 2281 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2282 bool IsKernel = AMDGPU::isKernel(CallConv); 2283 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2284 2285 if (IsGraphics) { 2286 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2287 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2288 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2289 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2290 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2291 !Info->hasWorkItemIDZ()); 2292 } 2293 2294 if (CallConv == CallingConv::AMDGPU_PS) { 2295 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2296 2297 // At least one interpolation mode must be enabled or else the GPU will 2298 // hang. 2299 // 2300 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2301 // set PSInputAddr, the user wants to enable some bits after the compilation 2302 // based on run-time states. Since we can't know what the final PSInputEna 2303 // will look like, so we shouldn't do anything here and the user should take 2304 // responsibility for the correct programming. 2305 // 2306 // Otherwise, the following restrictions apply: 2307 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2308 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2309 // enabled too. 2310 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2311 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2312 CCInfo.AllocateReg(AMDGPU::VGPR0); 2313 CCInfo.AllocateReg(AMDGPU::VGPR1); 2314 Info->markPSInputAllocated(0); 2315 Info->markPSInputEnabled(0); 2316 } 2317 if (Subtarget->isAmdPalOS()) { 2318 // For isAmdPalOS, the user does not enable some bits after compilation 2319 // based on run-time states; the register values being generated here are 2320 // the final ones set in hardware. Therefore we need to apply the 2321 // workaround to PSInputAddr and PSInputEnable together. (The case where 2322 // a bit is set in PSInputAddr but not PSInputEnable is where the 2323 // frontend set up an input arg for a particular interpolation mode, but 2324 // nothing uses that input arg. Really we should have an earlier pass 2325 // that removes such an arg.) 2326 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2327 if ((PsInputBits & 0x7F) == 0 || 2328 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2329 Info->markPSInputEnabled( 2330 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2331 } 2332 } else if (IsKernel) { 2333 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2334 } else { 2335 Splits.append(Ins.begin(), Ins.end()); 2336 } 2337 2338 if (IsEntryFunc) { 2339 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2340 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2341 } else { 2342 // For the fixed ABI, pass workitem IDs in the last argument register. 2343 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2344 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2345 } 2346 2347 if (IsKernel) { 2348 analyzeFormalArgumentsCompute(CCInfo, Ins); 2349 } else { 2350 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2351 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2352 } 2353 2354 SmallVector<SDValue, 16> Chains; 2355 2356 // FIXME: This is the minimum kernel argument alignment. We should improve 2357 // this to the maximum alignment of the arguments. 2358 // 2359 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2360 // kern arg offset. 2361 const Align KernelArgBaseAlign = Align(16); 2362 2363 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2364 const ISD::InputArg &Arg = Ins[i]; 2365 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2366 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2367 continue; 2368 } 2369 2370 CCValAssign &VA = ArgLocs[ArgIdx++]; 2371 MVT VT = VA.getLocVT(); 2372 2373 if (IsEntryFunc && VA.isMemLoc()) { 2374 VT = Ins[i].VT; 2375 EVT MemVT = VA.getLocVT(); 2376 2377 const uint64_t Offset = VA.getLocMemOffset(); 2378 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2379 2380 if (Arg.Flags.isByRef()) { 2381 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2382 2383 const GCNTargetMachine &TM = 2384 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2385 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2386 Arg.Flags.getPointerAddrSpace())) { 2387 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2388 Arg.Flags.getPointerAddrSpace()); 2389 } 2390 2391 InVals.push_back(Ptr); 2392 continue; 2393 } 2394 2395 SDValue Arg = lowerKernargMemParameter( 2396 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2397 Chains.push_back(Arg.getValue(1)); 2398 2399 auto *ParamTy = 2400 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2401 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2402 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2403 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2404 // On SI local pointers are just offsets into LDS, so they are always 2405 // less than 16-bits. On CI and newer they could potentially be 2406 // real pointers, so we can't guarantee their size. 2407 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2408 DAG.getValueType(MVT::i16)); 2409 } 2410 2411 InVals.push_back(Arg); 2412 continue; 2413 } else if (!IsEntryFunc && VA.isMemLoc()) { 2414 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2415 InVals.push_back(Val); 2416 if (!Arg.Flags.isByVal()) 2417 Chains.push_back(Val.getValue(1)); 2418 continue; 2419 } 2420 2421 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2422 2423 Register Reg = VA.getLocReg(); 2424 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2425 EVT ValVT = VA.getValVT(); 2426 2427 Reg = MF.addLiveIn(Reg, RC); 2428 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2429 2430 if (Arg.Flags.isSRet()) { 2431 // The return object should be reasonably addressable. 2432 2433 // FIXME: This helps when the return is a real sret. If it is a 2434 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2435 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2436 unsigned NumBits 2437 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2438 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2439 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2440 } 2441 2442 // If this is an 8 or 16-bit value, it is really passed promoted 2443 // to 32 bits. Insert an assert[sz]ext to capture this, then 2444 // truncate to the right size. 2445 switch (VA.getLocInfo()) { 2446 case CCValAssign::Full: 2447 break; 2448 case CCValAssign::BCvt: 2449 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2450 break; 2451 case CCValAssign::SExt: 2452 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2453 DAG.getValueType(ValVT)); 2454 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2455 break; 2456 case CCValAssign::ZExt: 2457 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2458 DAG.getValueType(ValVT)); 2459 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2460 break; 2461 case CCValAssign::AExt: 2462 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2463 break; 2464 default: 2465 llvm_unreachable("Unknown loc info!"); 2466 } 2467 2468 InVals.push_back(Val); 2469 } 2470 2471 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2472 // Special inputs come after user arguments. 2473 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2474 } 2475 2476 // Start adding system SGPRs. 2477 if (IsEntryFunc) { 2478 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2479 } else { 2480 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2481 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2482 } 2483 2484 auto &ArgUsageInfo = 2485 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2486 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2487 2488 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2489 Info->setBytesInStackArgArea(StackArgSize); 2490 2491 return Chains.empty() ? Chain : 2492 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2493 } 2494 2495 // TODO: If return values can't fit in registers, we should return as many as 2496 // possible in registers before passing on stack. 2497 bool SITargetLowering::CanLowerReturn( 2498 CallingConv::ID CallConv, 2499 MachineFunction &MF, bool IsVarArg, 2500 const SmallVectorImpl<ISD::OutputArg> &Outs, 2501 LLVMContext &Context) const { 2502 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2503 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2504 // for shaders. Vector types should be explicitly handled by CC. 2505 if (AMDGPU::isEntryFunctionCC(CallConv)) 2506 return true; 2507 2508 SmallVector<CCValAssign, 16> RVLocs; 2509 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2510 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2511 } 2512 2513 SDValue 2514 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2515 bool isVarArg, 2516 const SmallVectorImpl<ISD::OutputArg> &Outs, 2517 const SmallVectorImpl<SDValue> &OutVals, 2518 const SDLoc &DL, SelectionDAG &DAG) const { 2519 MachineFunction &MF = DAG.getMachineFunction(); 2520 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2521 2522 if (AMDGPU::isKernel(CallConv)) { 2523 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2524 OutVals, DL, DAG); 2525 } 2526 2527 bool IsShader = AMDGPU::isShader(CallConv); 2528 2529 Info->setIfReturnsVoid(Outs.empty()); 2530 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2531 2532 // CCValAssign - represent the assignment of the return value to a location. 2533 SmallVector<CCValAssign, 48> RVLocs; 2534 SmallVector<ISD::OutputArg, 48> Splits; 2535 2536 // CCState - Info about the registers and stack slots. 2537 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2538 *DAG.getContext()); 2539 2540 // Analyze outgoing return values. 2541 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2542 2543 SDValue Flag; 2544 SmallVector<SDValue, 48> RetOps; 2545 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2546 2547 // Add return address for callable functions. 2548 if (!Info->isEntryFunction()) { 2549 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2550 SDValue ReturnAddrReg = CreateLiveInRegister( 2551 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2552 2553 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2554 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2555 MVT::i64); 2556 Chain = 2557 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2558 Flag = Chain.getValue(1); 2559 RetOps.push_back(ReturnAddrVirtualReg); 2560 } 2561 2562 // Copy the result values into the output registers. 2563 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2564 ++I, ++RealRVLocIdx) { 2565 CCValAssign &VA = RVLocs[I]; 2566 assert(VA.isRegLoc() && "Can only return in registers!"); 2567 // TODO: Partially return in registers if return values don't fit. 2568 SDValue Arg = OutVals[RealRVLocIdx]; 2569 2570 // Copied from other backends. 2571 switch (VA.getLocInfo()) { 2572 case CCValAssign::Full: 2573 break; 2574 case CCValAssign::BCvt: 2575 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2576 break; 2577 case CCValAssign::SExt: 2578 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2579 break; 2580 case CCValAssign::ZExt: 2581 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2582 break; 2583 case CCValAssign::AExt: 2584 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2585 break; 2586 default: 2587 llvm_unreachable("Unknown loc info!"); 2588 } 2589 2590 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2591 Flag = Chain.getValue(1); 2592 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2593 } 2594 2595 // FIXME: Does sret work properly? 2596 if (!Info->isEntryFunction()) { 2597 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2598 const MCPhysReg *I = 2599 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2600 if (I) { 2601 for (; *I; ++I) { 2602 if (AMDGPU::SReg_64RegClass.contains(*I)) 2603 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2604 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2605 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2606 else 2607 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2608 } 2609 } 2610 } 2611 2612 // Update chain and glue. 2613 RetOps[0] = Chain; 2614 if (Flag.getNode()) 2615 RetOps.push_back(Flag); 2616 2617 unsigned Opc = AMDGPUISD::ENDPGM; 2618 if (!IsWaveEnd) 2619 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2620 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2621 } 2622 2623 SDValue SITargetLowering::LowerCallResult( 2624 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2625 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2626 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2627 SDValue ThisVal) const { 2628 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2629 2630 // Assign locations to each value returned by this call. 2631 SmallVector<CCValAssign, 16> RVLocs; 2632 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2633 *DAG.getContext()); 2634 CCInfo.AnalyzeCallResult(Ins, RetCC); 2635 2636 // Copy all of the result registers out of their specified physreg. 2637 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2638 CCValAssign VA = RVLocs[i]; 2639 SDValue Val; 2640 2641 if (VA.isRegLoc()) { 2642 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2643 Chain = Val.getValue(1); 2644 InFlag = Val.getValue(2); 2645 } else if (VA.isMemLoc()) { 2646 report_fatal_error("TODO: return values in memory"); 2647 } else 2648 llvm_unreachable("unknown argument location type"); 2649 2650 switch (VA.getLocInfo()) { 2651 case CCValAssign::Full: 2652 break; 2653 case CCValAssign::BCvt: 2654 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2655 break; 2656 case CCValAssign::ZExt: 2657 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2658 DAG.getValueType(VA.getValVT())); 2659 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2660 break; 2661 case CCValAssign::SExt: 2662 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2663 DAG.getValueType(VA.getValVT())); 2664 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2665 break; 2666 case CCValAssign::AExt: 2667 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2668 break; 2669 default: 2670 llvm_unreachable("Unknown loc info!"); 2671 } 2672 2673 InVals.push_back(Val); 2674 } 2675 2676 return Chain; 2677 } 2678 2679 // Add code to pass special inputs required depending on used features separate 2680 // from the explicit user arguments present in the IR. 2681 void SITargetLowering::passSpecialInputs( 2682 CallLoweringInfo &CLI, 2683 CCState &CCInfo, 2684 const SIMachineFunctionInfo &Info, 2685 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2686 SmallVectorImpl<SDValue> &MemOpChains, 2687 SDValue Chain) const { 2688 // If we don't have a call site, this was a call inserted by 2689 // legalization. These can never use special inputs. 2690 if (!CLI.CB) 2691 return; 2692 2693 SelectionDAG &DAG = CLI.DAG; 2694 const SDLoc &DL = CLI.DL; 2695 2696 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2697 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2698 2699 const AMDGPUFunctionArgInfo *CalleeArgInfo 2700 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2701 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2702 auto &ArgUsageInfo = 2703 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2704 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2705 } 2706 2707 // TODO: Unify with private memory register handling. This is complicated by 2708 // the fact that at least in kernels, the input argument is not necessarily 2709 // in the same location as the input. 2710 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2711 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2712 AMDGPUFunctionArgInfo::QUEUE_PTR, 2713 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2714 AMDGPUFunctionArgInfo::DISPATCH_ID, 2715 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2716 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2717 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2718 }; 2719 2720 for (auto InputID : InputRegs) { 2721 const ArgDescriptor *OutgoingArg; 2722 const TargetRegisterClass *ArgRC; 2723 LLT ArgTy; 2724 2725 std::tie(OutgoingArg, ArgRC, ArgTy) = 2726 CalleeArgInfo->getPreloadedValue(InputID); 2727 if (!OutgoingArg) 2728 continue; 2729 2730 const ArgDescriptor *IncomingArg; 2731 const TargetRegisterClass *IncomingArgRC; 2732 LLT Ty; 2733 std::tie(IncomingArg, IncomingArgRC, Ty) = 2734 CallerArgInfo.getPreloadedValue(InputID); 2735 assert(IncomingArgRC == ArgRC); 2736 2737 // All special arguments are ints for now. 2738 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2739 SDValue InputReg; 2740 2741 if (IncomingArg) { 2742 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2743 } else { 2744 // The implicit arg ptr is special because it doesn't have a corresponding 2745 // input for kernels, and is computed from the kernarg segment pointer. 2746 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2747 InputReg = getImplicitArgPtr(DAG, DL); 2748 } 2749 2750 if (OutgoingArg->isRegister()) { 2751 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2752 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2753 report_fatal_error("failed to allocate implicit input argument"); 2754 } else { 2755 unsigned SpecialArgOffset = 2756 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2757 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2758 SpecialArgOffset); 2759 MemOpChains.push_back(ArgStore); 2760 } 2761 } 2762 2763 // Pack workitem IDs into a single register or pass it as is if already 2764 // packed. 2765 const ArgDescriptor *OutgoingArg; 2766 const TargetRegisterClass *ArgRC; 2767 LLT Ty; 2768 2769 std::tie(OutgoingArg, ArgRC, Ty) = 2770 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2771 if (!OutgoingArg) 2772 std::tie(OutgoingArg, ArgRC, Ty) = 2773 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2774 if (!OutgoingArg) 2775 std::tie(OutgoingArg, ArgRC, Ty) = 2776 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2777 if (!OutgoingArg) 2778 return; 2779 2780 const ArgDescriptor *IncomingArgX = std::get<0>( 2781 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2782 const ArgDescriptor *IncomingArgY = std::get<0>( 2783 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2784 const ArgDescriptor *IncomingArgZ = std::get<0>( 2785 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2786 2787 SDValue InputReg; 2788 SDLoc SL; 2789 2790 // If incoming ids are not packed we need to pack them. 2791 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2792 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2793 2794 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2795 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2796 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2797 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2798 InputReg = InputReg.getNode() ? 2799 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2800 } 2801 2802 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2803 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2804 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2805 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2806 InputReg = InputReg.getNode() ? 2807 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2808 } 2809 2810 if (!InputReg.getNode()) { 2811 // Workitem ids are already packed, any of present incoming arguments 2812 // will carry all required fields. 2813 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2814 IncomingArgX ? *IncomingArgX : 2815 IncomingArgY ? *IncomingArgY : 2816 *IncomingArgZ, ~0u); 2817 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2818 } 2819 2820 if (OutgoingArg->isRegister()) { 2821 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2822 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2823 } else { 2824 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2825 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2826 SpecialArgOffset); 2827 MemOpChains.push_back(ArgStore); 2828 } 2829 } 2830 2831 static bool canGuaranteeTCO(CallingConv::ID CC) { 2832 return CC == CallingConv::Fast; 2833 } 2834 2835 /// Return true if we might ever do TCO for calls with this calling convention. 2836 static bool mayTailCallThisCC(CallingConv::ID CC) { 2837 switch (CC) { 2838 case CallingConv::C: 2839 case CallingConv::AMDGPU_Gfx: 2840 return true; 2841 default: 2842 return canGuaranteeTCO(CC); 2843 } 2844 } 2845 2846 bool SITargetLowering::isEligibleForTailCallOptimization( 2847 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2848 const SmallVectorImpl<ISD::OutputArg> &Outs, 2849 const SmallVectorImpl<SDValue> &OutVals, 2850 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2851 if (!mayTailCallThisCC(CalleeCC)) 2852 return false; 2853 2854 // For a divergent call target, we need to do a waterfall loop over the 2855 // possible callees which precludes us from using a simple jump. 2856 if (Callee->isDivergent()) 2857 return false; 2858 2859 MachineFunction &MF = DAG.getMachineFunction(); 2860 const Function &CallerF = MF.getFunction(); 2861 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2862 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2863 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2864 2865 // Kernels aren't callable, and don't have a live in return address so it 2866 // doesn't make sense to do a tail call with entry functions. 2867 if (!CallerPreserved) 2868 return false; 2869 2870 bool CCMatch = CallerCC == CalleeCC; 2871 2872 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2873 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2874 return true; 2875 return false; 2876 } 2877 2878 // TODO: Can we handle var args? 2879 if (IsVarArg) 2880 return false; 2881 2882 for (const Argument &Arg : CallerF.args()) { 2883 if (Arg.hasByValAttr()) 2884 return false; 2885 } 2886 2887 LLVMContext &Ctx = *DAG.getContext(); 2888 2889 // Check that the call results are passed in the same way. 2890 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2891 CCAssignFnForCall(CalleeCC, IsVarArg), 2892 CCAssignFnForCall(CallerCC, IsVarArg))) 2893 return false; 2894 2895 // The callee has to preserve all registers the caller needs to preserve. 2896 if (!CCMatch) { 2897 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2898 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2899 return false; 2900 } 2901 2902 // Nothing more to check if the callee is taking no arguments. 2903 if (Outs.empty()) 2904 return true; 2905 2906 SmallVector<CCValAssign, 16> ArgLocs; 2907 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2908 2909 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2910 2911 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2912 // If the stack arguments for this call do not fit into our own save area then 2913 // the call cannot be made tail. 2914 // TODO: Is this really necessary? 2915 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2916 return false; 2917 2918 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2919 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2920 } 2921 2922 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2923 if (!CI->isTailCall()) 2924 return false; 2925 2926 const Function *ParentFn = CI->getParent()->getParent(); 2927 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2928 return false; 2929 return true; 2930 } 2931 2932 // The wave scratch offset register is used as the global base pointer. 2933 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2934 SmallVectorImpl<SDValue> &InVals) const { 2935 SelectionDAG &DAG = CLI.DAG; 2936 const SDLoc &DL = CLI.DL; 2937 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2938 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2939 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2940 SDValue Chain = CLI.Chain; 2941 SDValue Callee = CLI.Callee; 2942 bool &IsTailCall = CLI.IsTailCall; 2943 CallingConv::ID CallConv = CLI.CallConv; 2944 bool IsVarArg = CLI.IsVarArg; 2945 bool IsSibCall = false; 2946 bool IsThisReturn = false; 2947 MachineFunction &MF = DAG.getMachineFunction(); 2948 2949 if (Callee.isUndef() || isNullConstant(Callee)) { 2950 if (!CLI.IsTailCall) { 2951 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2952 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2953 } 2954 2955 return Chain; 2956 } 2957 2958 if (IsVarArg) { 2959 return lowerUnhandledCall(CLI, InVals, 2960 "unsupported call to variadic function "); 2961 } 2962 2963 if (!CLI.CB) 2964 report_fatal_error("unsupported libcall legalization"); 2965 2966 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2967 return lowerUnhandledCall(CLI, InVals, 2968 "unsupported required tail call to function "); 2969 } 2970 2971 if (AMDGPU::isShader(CallConv)) { 2972 // Note the issue is with the CC of the called function, not of the call 2973 // itself. 2974 return lowerUnhandledCall(CLI, InVals, 2975 "unsupported call to a shader function "); 2976 } 2977 2978 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 2979 CallConv != CallingConv::AMDGPU_Gfx) { 2980 // Only allow calls with specific calling conventions. 2981 return lowerUnhandledCall(CLI, InVals, 2982 "unsupported calling convention for call from " 2983 "graphics shader of function "); 2984 } 2985 2986 if (IsTailCall) { 2987 IsTailCall = isEligibleForTailCallOptimization( 2988 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2989 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2990 report_fatal_error("failed to perform tail call elimination on a call " 2991 "site marked musttail"); 2992 } 2993 2994 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2995 2996 // A sibling call is one where we're under the usual C ABI and not planning 2997 // to change that but can still do a tail call: 2998 if (!TailCallOpt && IsTailCall) 2999 IsSibCall = true; 3000 3001 if (IsTailCall) 3002 ++NumTailCalls; 3003 } 3004 3005 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3006 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3007 SmallVector<SDValue, 8> MemOpChains; 3008 3009 // Analyze operands of the call, assigning locations to each operand. 3010 SmallVector<CCValAssign, 16> ArgLocs; 3011 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3012 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3013 3014 if (AMDGPUTargetMachine::EnableFixedFunctionABI && 3015 CallConv != CallingConv::AMDGPU_Gfx) { 3016 // With a fixed ABI, allocate fixed registers before user arguments. 3017 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3018 } 3019 3020 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3021 3022 // Get a count of how many bytes are to be pushed on the stack. 3023 unsigned NumBytes = CCInfo.getNextStackOffset(); 3024 3025 if (IsSibCall) { 3026 // Since we're not changing the ABI to make this a tail call, the memory 3027 // operands are already available in the caller's incoming argument space. 3028 NumBytes = 0; 3029 } 3030 3031 // FPDiff is the byte offset of the call's argument area from the callee's. 3032 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3033 // by this amount for a tail call. In a sibling call it must be 0 because the 3034 // caller will deallocate the entire stack and the callee still expects its 3035 // arguments to begin at SP+0. Completely unused for non-tail calls. 3036 int32_t FPDiff = 0; 3037 MachineFrameInfo &MFI = MF.getFrameInfo(); 3038 3039 // Adjust the stack pointer for the new arguments... 3040 // These operations are automatically eliminated by the prolog/epilog pass 3041 if (!IsSibCall) { 3042 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3043 3044 if (!Subtarget->enableFlatScratch()) { 3045 SmallVector<SDValue, 4> CopyFromChains; 3046 3047 // In the HSA case, this should be an identity copy. 3048 SDValue ScratchRSrcReg 3049 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3050 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3051 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3052 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3053 } 3054 } 3055 3056 MVT PtrVT = MVT::i32; 3057 3058 // Walk the register/memloc assignments, inserting copies/loads. 3059 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3060 CCValAssign &VA = ArgLocs[i]; 3061 SDValue Arg = OutVals[i]; 3062 3063 // Promote the value if needed. 3064 switch (VA.getLocInfo()) { 3065 case CCValAssign::Full: 3066 break; 3067 case CCValAssign::BCvt: 3068 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3069 break; 3070 case CCValAssign::ZExt: 3071 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3072 break; 3073 case CCValAssign::SExt: 3074 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3075 break; 3076 case CCValAssign::AExt: 3077 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3078 break; 3079 case CCValAssign::FPExt: 3080 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3081 break; 3082 default: 3083 llvm_unreachable("Unknown loc info!"); 3084 } 3085 3086 if (VA.isRegLoc()) { 3087 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3088 } else { 3089 assert(VA.isMemLoc()); 3090 3091 SDValue DstAddr; 3092 MachinePointerInfo DstInfo; 3093 3094 unsigned LocMemOffset = VA.getLocMemOffset(); 3095 int32_t Offset = LocMemOffset; 3096 3097 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3098 MaybeAlign Alignment; 3099 3100 if (IsTailCall) { 3101 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3102 unsigned OpSize = Flags.isByVal() ? 3103 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3104 3105 // FIXME: We can have better than the minimum byval required alignment. 3106 Alignment = 3107 Flags.isByVal() 3108 ? Flags.getNonZeroByValAlign() 3109 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3110 3111 Offset = Offset + FPDiff; 3112 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3113 3114 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3115 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3116 3117 // Make sure any stack arguments overlapping with where we're storing 3118 // are loaded before this eventual operation. Otherwise they'll be 3119 // clobbered. 3120 3121 // FIXME: Why is this really necessary? This seems to just result in a 3122 // lot of code to copy the stack and write them back to the same 3123 // locations, which are supposed to be immutable? 3124 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3125 } else { 3126 // Stores to the argument stack area are relative to the stack pointer. 3127 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(), 3128 MVT::i32); 3129 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff); 3130 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3131 Alignment = 3132 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3133 } 3134 3135 if (Outs[i].Flags.isByVal()) { 3136 SDValue SizeNode = 3137 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3138 SDValue Cpy = 3139 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3140 Outs[i].Flags.getNonZeroByValAlign(), 3141 /*isVol = */ false, /*AlwaysInline = */ true, 3142 /*isTailCall = */ false, DstInfo, 3143 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3144 3145 MemOpChains.push_back(Cpy); 3146 } else { 3147 SDValue Store = 3148 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3149 MemOpChains.push_back(Store); 3150 } 3151 } 3152 } 3153 3154 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 3155 CallConv != CallingConv::AMDGPU_Gfx) { 3156 // Copy special input registers after user input arguments. 3157 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3158 } 3159 3160 if (!MemOpChains.empty()) 3161 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3162 3163 // Build a sequence of copy-to-reg nodes chained together with token chain 3164 // and flag operands which copy the outgoing args into the appropriate regs. 3165 SDValue InFlag; 3166 for (auto &RegToPass : RegsToPass) { 3167 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3168 RegToPass.second, InFlag); 3169 InFlag = Chain.getValue(1); 3170 } 3171 3172 3173 SDValue PhysReturnAddrReg; 3174 if (IsTailCall) { 3175 // Since the return is being combined with the call, we need to pass on the 3176 // return address. 3177 3178 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3179 SDValue ReturnAddrReg = CreateLiveInRegister( 3180 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3181 3182 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3183 MVT::i64); 3184 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3185 InFlag = Chain.getValue(1); 3186 } 3187 3188 // We don't usually want to end the call-sequence here because we would tidy 3189 // the frame up *after* the call, however in the ABI-changing tail-call case 3190 // we've carefully laid out the parameters so that when sp is reset they'll be 3191 // in the correct location. 3192 if (IsTailCall && !IsSibCall) { 3193 Chain = DAG.getCALLSEQ_END(Chain, 3194 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3195 DAG.getTargetConstant(0, DL, MVT::i32), 3196 InFlag, DL); 3197 InFlag = Chain.getValue(1); 3198 } 3199 3200 std::vector<SDValue> Ops; 3201 Ops.push_back(Chain); 3202 Ops.push_back(Callee); 3203 // Add a redundant copy of the callee global which will not be legalized, as 3204 // we need direct access to the callee later. 3205 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3206 const GlobalValue *GV = GSD->getGlobal(); 3207 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3208 } else { 3209 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3210 } 3211 3212 if (IsTailCall) { 3213 // Each tail call may have to adjust the stack by a different amount, so 3214 // this information must travel along with the operation for eventual 3215 // consumption by emitEpilogue. 3216 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3217 3218 Ops.push_back(PhysReturnAddrReg); 3219 } 3220 3221 // Add argument registers to the end of the list so that they are known live 3222 // into the call. 3223 for (auto &RegToPass : RegsToPass) { 3224 Ops.push_back(DAG.getRegister(RegToPass.first, 3225 RegToPass.second.getValueType())); 3226 } 3227 3228 // Add a register mask operand representing the call-preserved registers. 3229 3230 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3231 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3232 assert(Mask && "Missing call preserved mask for calling convention"); 3233 Ops.push_back(DAG.getRegisterMask(Mask)); 3234 3235 if (InFlag.getNode()) 3236 Ops.push_back(InFlag); 3237 3238 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3239 3240 // If we're doing a tall call, use a TC_RETURN here rather than an 3241 // actual call instruction. 3242 if (IsTailCall) { 3243 MFI.setHasTailCall(); 3244 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3245 } 3246 3247 // Returns a chain and a flag for retval copy to use. 3248 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3249 Chain = Call.getValue(0); 3250 InFlag = Call.getValue(1); 3251 3252 uint64_t CalleePopBytes = NumBytes; 3253 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3254 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3255 InFlag, DL); 3256 if (!Ins.empty()) 3257 InFlag = Chain.getValue(1); 3258 3259 // Handle result values, copying them out of physregs into vregs that we 3260 // return. 3261 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3262 InVals, IsThisReturn, 3263 IsThisReturn ? OutVals[0] : SDValue()); 3264 } 3265 3266 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3267 // except for applying the wave size scale to the increment amount. 3268 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3269 SDValue Op, SelectionDAG &DAG) const { 3270 const MachineFunction &MF = DAG.getMachineFunction(); 3271 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3272 3273 SDLoc dl(Op); 3274 EVT VT = Op.getValueType(); 3275 SDValue Tmp1 = Op; 3276 SDValue Tmp2 = Op.getValue(1); 3277 SDValue Tmp3 = Op.getOperand(2); 3278 SDValue Chain = Tmp1.getOperand(0); 3279 3280 Register SPReg = Info->getStackPtrOffsetReg(); 3281 3282 // Chain the dynamic stack allocation so that it doesn't modify the stack 3283 // pointer when other instructions are using the stack. 3284 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3285 3286 SDValue Size = Tmp2.getOperand(1); 3287 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3288 Chain = SP.getValue(1); 3289 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3290 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3291 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3292 unsigned Opc = 3293 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3294 ISD::ADD : ISD::SUB; 3295 3296 SDValue ScaledSize = DAG.getNode( 3297 ISD::SHL, dl, VT, Size, 3298 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3299 3300 Align StackAlign = TFL->getStackAlign(); 3301 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3302 if (Alignment && *Alignment > StackAlign) { 3303 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3304 DAG.getConstant(-(uint64_t)Alignment->value() 3305 << ST.getWavefrontSizeLog2(), 3306 dl, VT)); 3307 } 3308 3309 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3310 Tmp2 = DAG.getCALLSEQ_END( 3311 Chain, DAG.getIntPtrConstant(0, dl, true), 3312 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3313 3314 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3315 } 3316 3317 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3318 SelectionDAG &DAG) const { 3319 // We only handle constant sizes here to allow non-entry block, static sized 3320 // allocas. A truly dynamic value is more difficult to support because we 3321 // don't know if the size value is uniform or not. If the size isn't uniform, 3322 // we would need to do a wave reduction to get the maximum size to know how 3323 // much to increment the uniform stack pointer. 3324 SDValue Size = Op.getOperand(1); 3325 if (isa<ConstantSDNode>(Size)) 3326 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3327 3328 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3329 } 3330 3331 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3332 const MachineFunction &MF) const { 3333 Register Reg = StringSwitch<Register>(RegName) 3334 .Case("m0", AMDGPU::M0) 3335 .Case("exec", AMDGPU::EXEC) 3336 .Case("exec_lo", AMDGPU::EXEC_LO) 3337 .Case("exec_hi", AMDGPU::EXEC_HI) 3338 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3339 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3340 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3341 .Default(Register()); 3342 3343 if (Reg == AMDGPU::NoRegister) { 3344 report_fatal_error(Twine("invalid register name \"" 3345 + StringRef(RegName) + "\".")); 3346 3347 } 3348 3349 if (!Subtarget->hasFlatScrRegister() && 3350 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3351 report_fatal_error(Twine("invalid register \"" 3352 + StringRef(RegName) + "\" for subtarget.")); 3353 } 3354 3355 switch (Reg) { 3356 case AMDGPU::M0: 3357 case AMDGPU::EXEC_LO: 3358 case AMDGPU::EXEC_HI: 3359 case AMDGPU::FLAT_SCR_LO: 3360 case AMDGPU::FLAT_SCR_HI: 3361 if (VT.getSizeInBits() == 32) 3362 return Reg; 3363 break; 3364 case AMDGPU::EXEC: 3365 case AMDGPU::FLAT_SCR: 3366 if (VT.getSizeInBits() == 64) 3367 return Reg; 3368 break; 3369 default: 3370 llvm_unreachable("missing register type checking"); 3371 } 3372 3373 report_fatal_error(Twine("invalid type for register \"" 3374 + StringRef(RegName) + "\".")); 3375 } 3376 3377 // If kill is not the last instruction, split the block so kill is always a 3378 // proper terminator. 3379 MachineBasicBlock * 3380 SITargetLowering::splitKillBlock(MachineInstr &MI, 3381 MachineBasicBlock *BB) const { 3382 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3383 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3384 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3385 return SplitBB; 3386 } 3387 3388 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3389 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3390 // be the first instruction in the remainder block. 3391 // 3392 /// \returns { LoopBody, Remainder } 3393 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3394 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3395 MachineFunction *MF = MBB.getParent(); 3396 MachineBasicBlock::iterator I(&MI); 3397 3398 // To insert the loop we need to split the block. Move everything after this 3399 // point to a new block, and insert a new empty block between the two. 3400 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3401 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3402 MachineFunction::iterator MBBI(MBB); 3403 ++MBBI; 3404 3405 MF->insert(MBBI, LoopBB); 3406 MF->insert(MBBI, RemainderBB); 3407 3408 LoopBB->addSuccessor(LoopBB); 3409 LoopBB->addSuccessor(RemainderBB); 3410 3411 // Move the rest of the block into a new block. 3412 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3413 3414 if (InstInLoop) { 3415 auto Next = std::next(I); 3416 3417 // Move instruction to loop body. 3418 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3419 3420 // Move the rest of the block. 3421 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3422 } else { 3423 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3424 } 3425 3426 MBB.addSuccessor(LoopBB); 3427 3428 return std::make_pair(LoopBB, RemainderBB); 3429 } 3430 3431 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3432 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3433 MachineBasicBlock *MBB = MI.getParent(); 3434 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3435 auto I = MI.getIterator(); 3436 auto E = std::next(I); 3437 3438 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3439 .addImm(0); 3440 3441 MIBundleBuilder Bundler(*MBB, I, E); 3442 finalizeBundle(*MBB, Bundler.begin()); 3443 } 3444 3445 MachineBasicBlock * 3446 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3447 MachineBasicBlock *BB) const { 3448 const DebugLoc &DL = MI.getDebugLoc(); 3449 3450 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3451 3452 MachineBasicBlock *LoopBB; 3453 MachineBasicBlock *RemainderBB; 3454 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3455 3456 // Apparently kill flags are only valid if the def is in the same block? 3457 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3458 Src->setIsKill(false); 3459 3460 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3461 3462 MachineBasicBlock::iterator I = LoopBB->end(); 3463 3464 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3465 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3466 3467 // Clear TRAP_STS.MEM_VIOL 3468 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3469 .addImm(0) 3470 .addImm(EncodedReg); 3471 3472 bundleInstWithWaitcnt(MI); 3473 3474 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3475 3476 // Load and check TRAP_STS.MEM_VIOL 3477 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3478 .addImm(EncodedReg); 3479 3480 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3481 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3482 .addReg(Reg, RegState::Kill) 3483 .addImm(0); 3484 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3485 .addMBB(LoopBB); 3486 3487 return RemainderBB; 3488 } 3489 3490 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3491 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3492 // will only do one iteration. In the worst case, this will loop 64 times. 3493 // 3494 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3495 static MachineBasicBlock::iterator 3496 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3497 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3498 const DebugLoc &DL, const MachineOperand &Idx, 3499 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3500 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3501 Register &SGPRIdxReg) { 3502 3503 MachineFunction *MF = OrigBB.getParent(); 3504 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3505 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3506 MachineBasicBlock::iterator I = LoopBB.begin(); 3507 3508 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3509 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3510 Register NewExec = MRI.createVirtualRegister(BoolRC); 3511 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3512 Register CondReg = MRI.createVirtualRegister(BoolRC); 3513 3514 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3515 .addReg(InitReg) 3516 .addMBB(&OrigBB) 3517 .addReg(ResultReg) 3518 .addMBB(&LoopBB); 3519 3520 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3521 .addReg(InitSaveExecReg) 3522 .addMBB(&OrigBB) 3523 .addReg(NewExec) 3524 .addMBB(&LoopBB); 3525 3526 // Read the next variant <- also loop target. 3527 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3528 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3529 3530 // Compare the just read M0 value to all possible Idx values. 3531 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3532 .addReg(CurrentIdxReg) 3533 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3534 3535 // Update EXEC, save the original EXEC value to VCC. 3536 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3537 : AMDGPU::S_AND_SAVEEXEC_B64), 3538 NewExec) 3539 .addReg(CondReg, RegState::Kill); 3540 3541 MRI.setSimpleHint(NewExec, CondReg); 3542 3543 if (UseGPRIdxMode) { 3544 if (Offset == 0) { 3545 SGPRIdxReg = CurrentIdxReg; 3546 } else { 3547 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3548 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3549 .addReg(CurrentIdxReg, RegState::Kill) 3550 .addImm(Offset); 3551 } 3552 } else { 3553 // Move index from VCC into M0 3554 if (Offset == 0) { 3555 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3556 .addReg(CurrentIdxReg, RegState::Kill); 3557 } else { 3558 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3559 .addReg(CurrentIdxReg, RegState::Kill) 3560 .addImm(Offset); 3561 } 3562 } 3563 3564 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3565 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3566 MachineInstr *InsertPt = 3567 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3568 : AMDGPU::S_XOR_B64_term), Exec) 3569 .addReg(Exec) 3570 .addReg(NewExec); 3571 3572 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3573 // s_cbranch_scc0? 3574 3575 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3576 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3577 .addMBB(&LoopBB); 3578 3579 return InsertPt->getIterator(); 3580 } 3581 3582 // This has slightly sub-optimal regalloc when the source vector is killed by 3583 // the read. The register allocator does not understand that the kill is 3584 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3585 // subregister from it, using 1 more VGPR than necessary. This was saved when 3586 // this was expanded after register allocation. 3587 static MachineBasicBlock::iterator 3588 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3589 unsigned InitResultReg, unsigned PhiReg, int Offset, 3590 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3591 MachineFunction *MF = MBB.getParent(); 3592 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3593 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3594 MachineRegisterInfo &MRI = MF->getRegInfo(); 3595 const DebugLoc &DL = MI.getDebugLoc(); 3596 MachineBasicBlock::iterator I(&MI); 3597 3598 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3599 Register DstReg = MI.getOperand(0).getReg(); 3600 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3601 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3602 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3603 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3604 3605 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3606 3607 // Save the EXEC mask 3608 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3609 .addReg(Exec); 3610 3611 MachineBasicBlock *LoopBB; 3612 MachineBasicBlock *RemainderBB; 3613 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3614 3615 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3616 3617 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3618 InitResultReg, DstReg, PhiReg, TmpExec, 3619 Offset, UseGPRIdxMode, SGPRIdxReg); 3620 3621 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3622 MachineFunction::iterator MBBI(LoopBB); 3623 ++MBBI; 3624 MF->insert(MBBI, LandingPad); 3625 LoopBB->removeSuccessor(RemainderBB); 3626 LandingPad->addSuccessor(RemainderBB); 3627 LoopBB->addSuccessor(LandingPad); 3628 MachineBasicBlock::iterator First = LandingPad->begin(); 3629 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3630 .addReg(SaveExec); 3631 3632 return InsPt; 3633 } 3634 3635 // Returns subreg index, offset 3636 static std::pair<unsigned, int> 3637 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3638 const TargetRegisterClass *SuperRC, 3639 unsigned VecReg, 3640 int Offset) { 3641 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3642 3643 // Skip out of bounds offsets, or else we would end up using an undefined 3644 // register. 3645 if (Offset >= NumElts || Offset < 0) 3646 return std::make_pair(AMDGPU::sub0, Offset); 3647 3648 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3649 } 3650 3651 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3652 MachineRegisterInfo &MRI, MachineInstr &MI, 3653 int Offset) { 3654 MachineBasicBlock *MBB = MI.getParent(); 3655 const DebugLoc &DL = MI.getDebugLoc(); 3656 MachineBasicBlock::iterator I(&MI); 3657 3658 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3659 3660 assert(Idx->getReg() != AMDGPU::NoRegister); 3661 3662 if (Offset == 0) { 3663 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3664 } else { 3665 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3666 .add(*Idx) 3667 .addImm(Offset); 3668 } 3669 } 3670 3671 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3672 MachineRegisterInfo &MRI, MachineInstr &MI, 3673 int Offset) { 3674 MachineBasicBlock *MBB = MI.getParent(); 3675 const DebugLoc &DL = MI.getDebugLoc(); 3676 MachineBasicBlock::iterator I(&MI); 3677 3678 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3679 3680 if (Offset == 0) 3681 return Idx->getReg(); 3682 3683 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3684 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3685 .add(*Idx) 3686 .addImm(Offset); 3687 return Tmp; 3688 } 3689 3690 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3691 MachineBasicBlock &MBB, 3692 const GCNSubtarget &ST) { 3693 const SIInstrInfo *TII = ST.getInstrInfo(); 3694 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3695 MachineFunction *MF = MBB.getParent(); 3696 MachineRegisterInfo &MRI = MF->getRegInfo(); 3697 3698 Register Dst = MI.getOperand(0).getReg(); 3699 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3700 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3701 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3702 3703 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3704 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3705 3706 unsigned SubReg; 3707 std::tie(SubReg, Offset) 3708 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3709 3710 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3711 3712 // Check for a SGPR index. 3713 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3714 MachineBasicBlock::iterator I(&MI); 3715 const DebugLoc &DL = MI.getDebugLoc(); 3716 3717 if (UseGPRIdxMode) { 3718 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3719 // to avoid interfering with other uses, so probably requires a new 3720 // optimization pass. 3721 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3722 3723 const MCInstrDesc &GPRIDXDesc = 3724 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3725 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3726 .addReg(SrcReg) 3727 .addReg(Idx) 3728 .addImm(SubReg); 3729 } else { 3730 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3731 3732 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3733 .addReg(SrcReg, 0, SubReg) 3734 .addReg(SrcReg, RegState::Implicit); 3735 } 3736 3737 MI.eraseFromParent(); 3738 3739 return &MBB; 3740 } 3741 3742 // Control flow needs to be inserted if indexing with a VGPR. 3743 const DebugLoc &DL = MI.getDebugLoc(); 3744 MachineBasicBlock::iterator I(&MI); 3745 3746 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3747 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3748 3749 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3750 3751 Register SGPRIdxReg; 3752 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3753 UseGPRIdxMode, SGPRIdxReg); 3754 3755 MachineBasicBlock *LoopBB = InsPt->getParent(); 3756 3757 if (UseGPRIdxMode) { 3758 const MCInstrDesc &GPRIDXDesc = 3759 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3760 3761 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3762 .addReg(SrcReg) 3763 .addReg(SGPRIdxReg) 3764 .addImm(SubReg); 3765 } else { 3766 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3767 .addReg(SrcReg, 0, SubReg) 3768 .addReg(SrcReg, RegState::Implicit); 3769 } 3770 3771 MI.eraseFromParent(); 3772 3773 return LoopBB; 3774 } 3775 3776 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3777 MachineBasicBlock &MBB, 3778 const GCNSubtarget &ST) { 3779 const SIInstrInfo *TII = ST.getInstrInfo(); 3780 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3781 MachineFunction *MF = MBB.getParent(); 3782 MachineRegisterInfo &MRI = MF->getRegInfo(); 3783 3784 Register Dst = MI.getOperand(0).getReg(); 3785 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3786 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3787 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3788 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3789 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3790 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3791 3792 // This can be an immediate, but will be folded later. 3793 assert(Val->getReg()); 3794 3795 unsigned SubReg; 3796 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3797 SrcVec->getReg(), 3798 Offset); 3799 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3800 3801 if (Idx->getReg() == AMDGPU::NoRegister) { 3802 MachineBasicBlock::iterator I(&MI); 3803 const DebugLoc &DL = MI.getDebugLoc(); 3804 3805 assert(Offset == 0); 3806 3807 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3808 .add(*SrcVec) 3809 .add(*Val) 3810 .addImm(SubReg); 3811 3812 MI.eraseFromParent(); 3813 return &MBB; 3814 } 3815 3816 // Check for a SGPR index. 3817 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3818 MachineBasicBlock::iterator I(&MI); 3819 const DebugLoc &DL = MI.getDebugLoc(); 3820 3821 if (UseGPRIdxMode) { 3822 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3823 3824 const MCInstrDesc &GPRIDXDesc = 3825 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3826 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3827 .addReg(SrcVec->getReg()) 3828 .add(*Val) 3829 .addReg(Idx) 3830 .addImm(SubReg); 3831 } else { 3832 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3833 3834 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3835 TRI.getRegSizeInBits(*VecRC), 32, false); 3836 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3837 .addReg(SrcVec->getReg()) 3838 .add(*Val) 3839 .addImm(SubReg); 3840 } 3841 MI.eraseFromParent(); 3842 return &MBB; 3843 } 3844 3845 // Control flow needs to be inserted if indexing with a VGPR. 3846 if (Val->isReg()) 3847 MRI.clearKillFlags(Val->getReg()); 3848 3849 const DebugLoc &DL = MI.getDebugLoc(); 3850 3851 Register PhiReg = MRI.createVirtualRegister(VecRC); 3852 3853 Register SGPRIdxReg; 3854 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3855 UseGPRIdxMode, SGPRIdxReg); 3856 MachineBasicBlock *LoopBB = InsPt->getParent(); 3857 3858 if (UseGPRIdxMode) { 3859 const MCInstrDesc &GPRIDXDesc = 3860 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3861 3862 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3863 .addReg(PhiReg) 3864 .add(*Val) 3865 .addReg(SGPRIdxReg) 3866 .addImm(AMDGPU::sub0); 3867 } else { 3868 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3869 TRI.getRegSizeInBits(*VecRC), 32, false); 3870 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3871 .addReg(PhiReg) 3872 .add(*Val) 3873 .addImm(AMDGPU::sub0); 3874 } 3875 3876 MI.eraseFromParent(); 3877 return LoopBB; 3878 } 3879 3880 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3881 MachineInstr &MI, MachineBasicBlock *BB) const { 3882 3883 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3884 MachineFunction *MF = BB->getParent(); 3885 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3886 3887 switch (MI.getOpcode()) { 3888 case AMDGPU::S_UADDO_PSEUDO: 3889 case AMDGPU::S_USUBO_PSEUDO: { 3890 const DebugLoc &DL = MI.getDebugLoc(); 3891 MachineOperand &Dest0 = MI.getOperand(0); 3892 MachineOperand &Dest1 = MI.getOperand(1); 3893 MachineOperand &Src0 = MI.getOperand(2); 3894 MachineOperand &Src1 = MI.getOperand(3); 3895 3896 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3897 ? AMDGPU::S_ADD_I32 3898 : AMDGPU::S_SUB_I32; 3899 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3900 3901 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3902 .addImm(1) 3903 .addImm(0); 3904 3905 MI.eraseFromParent(); 3906 return BB; 3907 } 3908 case AMDGPU::S_ADD_U64_PSEUDO: 3909 case AMDGPU::S_SUB_U64_PSEUDO: { 3910 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3911 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3912 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3913 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3914 const DebugLoc &DL = MI.getDebugLoc(); 3915 3916 MachineOperand &Dest = MI.getOperand(0); 3917 MachineOperand &Src0 = MI.getOperand(1); 3918 MachineOperand &Src1 = MI.getOperand(2); 3919 3920 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3921 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3922 3923 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3924 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3925 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3926 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3927 3928 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3929 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3930 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3931 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3932 3933 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3934 3935 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3936 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3937 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3938 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3939 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3940 .addReg(DestSub0) 3941 .addImm(AMDGPU::sub0) 3942 .addReg(DestSub1) 3943 .addImm(AMDGPU::sub1); 3944 MI.eraseFromParent(); 3945 return BB; 3946 } 3947 case AMDGPU::V_ADD_U64_PSEUDO: 3948 case AMDGPU::V_SUB_U64_PSEUDO: { 3949 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3950 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3951 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3952 const DebugLoc &DL = MI.getDebugLoc(); 3953 3954 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3955 3956 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3957 3958 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3959 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3960 3961 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3962 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3963 3964 MachineOperand &Dest = MI.getOperand(0); 3965 MachineOperand &Src0 = MI.getOperand(1); 3966 MachineOperand &Src1 = MI.getOperand(2); 3967 3968 const TargetRegisterClass *Src0RC = Src0.isReg() 3969 ? MRI.getRegClass(Src0.getReg()) 3970 : &AMDGPU::VReg_64RegClass; 3971 const TargetRegisterClass *Src1RC = Src1.isReg() 3972 ? MRI.getRegClass(Src1.getReg()) 3973 : &AMDGPU::VReg_64RegClass; 3974 3975 const TargetRegisterClass *Src0SubRC = 3976 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3977 const TargetRegisterClass *Src1SubRC = 3978 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3979 3980 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3981 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3982 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3983 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3984 3985 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3986 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3987 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3988 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3989 3990 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 3991 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3992 .addReg(CarryReg, RegState::Define) 3993 .add(SrcReg0Sub0) 3994 .add(SrcReg1Sub0) 3995 .addImm(0); // clamp bit 3996 3997 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3998 MachineInstr *HiHalf = 3999 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 4000 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 4001 .add(SrcReg0Sub1) 4002 .add(SrcReg1Sub1) 4003 .addReg(CarryReg, RegState::Kill) 4004 .addImm(0); // clamp bit 4005 4006 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4007 .addReg(DestSub0) 4008 .addImm(AMDGPU::sub0) 4009 .addReg(DestSub1) 4010 .addImm(AMDGPU::sub1); 4011 TII->legalizeOperands(*LoHalf); 4012 TII->legalizeOperands(*HiHalf); 4013 MI.eraseFromParent(); 4014 return BB; 4015 } 4016 case AMDGPU::S_ADD_CO_PSEUDO: 4017 case AMDGPU::S_SUB_CO_PSEUDO: { 4018 // This pseudo has a chance to be selected 4019 // only from uniform add/subcarry node. All the VGPR operands 4020 // therefore assumed to be splat vectors. 4021 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4022 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4023 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4024 MachineBasicBlock::iterator MII = MI; 4025 const DebugLoc &DL = MI.getDebugLoc(); 4026 MachineOperand &Dest = MI.getOperand(0); 4027 MachineOperand &CarryDest = MI.getOperand(1); 4028 MachineOperand &Src0 = MI.getOperand(2); 4029 MachineOperand &Src1 = MI.getOperand(3); 4030 MachineOperand &Src2 = MI.getOperand(4); 4031 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4032 ? AMDGPU::S_ADDC_U32 4033 : AMDGPU::S_SUBB_U32; 4034 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4035 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4036 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4037 .addReg(Src0.getReg()); 4038 Src0.setReg(RegOp0); 4039 } 4040 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4041 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4042 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4043 .addReg(Src1.getReg()); 4044 Src1.setReg(RegOp1); 4045 } 4046 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4047 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4048 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4049 .addReg(Src2.getReg()); 4050 Src2.setReg(RegOp2); 4051 } 4052 4053 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4054 if (TRI->getRegSizeInBits(*Src2RC) == 64) { 4055 if (ST.hasScalarCompareEq64()) { 4056 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4057 .addReg(Src2.getReg()) 4058 .addImm(0); 4059 } else { 4060 const TargetRegisterClass *SubRC = 4061 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4062 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4063 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4064 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4065 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4066 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4067 4068 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4069 .add(Src2Sub0) 4070 .add(Src2Sub1); 4071 4072 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4073 .addReg(Src2_32, RegState::Kill) 4074 .addImm(0); 4075 } 4076 } else { 4077 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4078 .addReg(Src2.getReg()) 4079 .addImm(0); 4080 } 4081 4082 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4083 4084 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 4085 .addReg(AMDGPU::SCC); 4086 MI.eraseFromParent(); 4087 return BB; 4088 } 4089 case AMDGPU::SI_INIT_M0: { 4090 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4091 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4092 .add(MI.getOperand(0)); 4093 MI.eraseFromParent(); 4094 return BB; 4095 } 4096 case AMDGPU::GET_GROUPSTATICSIZE: { 4097 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4098 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4099 DebugLoc DL = MI.getDebugLoc(); 4100 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4101 .add(MI.getOperand(0)) 4102 .addImm(MFI->getLDSSize()); 4103 MI.eraseFromParent(); 4104 return BB; 4105 } 4106 case AMDGPU::SI_INDIRECT_SRC_V1: 4107 case AMDGPU::SI_INDIRECT_SRC_V2: 4108 case AMDGPU::SI_INDIRECT_SRC_V4: 4109 case AMDGPU::SI_INDIRECT_SRC_V8: 4110 case AMDGPU::SI_INDIRECT_SRC_V16: 4111 case AMDGPU::SI_INDIRECT_SRC_V32: 4112 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4113 case AMDGPU::SI_INDIRECT_DST_V1: 4114 case AMDGPU::SI_INDIRECT_DST_V2: 4115 case AMDGPU::SI_INDIRECT_DST_V4: 4116 case AMDGPU::SI_INDIRECT_DST_V8: 4117 case AMDGPU::SI_INDIRECT_DST_V16: 4118 case AMDGPU::SI_INDIRECT_DST_V32: 4119 return emitIndirectDst(MI, *BB, *getSubtarget()); 4120 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4121 case AMDGPU::SI_KILL_I1_PSEUDO: 4122 return splitKillBlock(MI, BB); 4123 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4124 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4125 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4126 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4127 4128 Register Dst = MI.getOperand(0).getReg(); 4129 Register Src0 = MI.getOperand(1).getReg(); 4130 Register Src1 = MI.getOperand(2).getReg(); 4131 const DebugLoc &DL = MI.getDebugLoc(); 4132 Register SrcCond = MI.getOperand(3).getReg(); 4133 4134 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4135 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4136 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4137 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4138 4139 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4140 .addReg(SrcCond); 4141 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4142 .addImm(0) 4143 .addReg(Src0, 0, AMDGPU::sub0) 4144 .addImm(0) 4145 .addReg(Src1, 0, AMDGPU::sub0) 4146 .addReg(SrcCondCopy); 4147 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4148 .addImm(0) 4149 .addReg(Src0, 0, AMDGPU::sub1) 4150 .addImm(0) 4151 .addReg(Src1, 0, AMDGPU::sub1) 4152 .addReg(SrcCondCopy); 4153 4154 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4155 .addReg(DstLo) 4156 .addImm(AMDGPU::sub0) 4157 .addReg(DstHi) 4158 .addImm(AMDGPU::sub1); 4159 MI.eraseFromParent(); 4160 return BB; 4161 } 4162 case AMDGPU::SI_BR_UNDEF: { 4163 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4164 const DebugLoc &DL = MI.getDebugLoc(); 4165 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4166 .add(MI.getOperand(0)); 4167 Br->getOperand(1).setIsUndef(true); // read undef SCC 4168 MI.eraseFromParent(); 4169 return BB; 4170 } 4171 case AMDGPU::ADJCALLSTACKUP: 4172 case AMDGPU::ADJCALLSTACKDOWN: { 4173 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4174 MachineInstrBuilder MIB(*MF, &MI); 4175 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4176 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4177 return BB; 4178 } 4179 case AMDGPU::SI_CALL_ISEL: { 4180 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4181 const DebugLoc &DL = MI.getDebugLoc(); 4182 4183 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4184 4185 MachineInstrBuilder MIB; 4186 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4187 4188 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4189 MIB.add(MI.getOperand(I)); 4190 4191 MIB.cloneMemRefs(MI); 4192 MI.eraseFromParent(); 4193 return BB; 4194 } 4195 case AMDGPU::V_ADD_CO_U32_e32: 4196 case AMDGPU::V_SUB_CO_U32_e32: 4197 case AMDGPU::V_SUBREV_CO_U32_e32: { 4198 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4199 const DebugLoc &DL = MI.getDebugLoc(); 4200 unsigned Opc = MI.getOpcode(); 4201 4202 bool NeedClampOperand = false; 4203 if (TII->pseudoToMCOpcode(Opc) == -1) { 4204 Opc = AMDGPU::getVOPe64(Opc); 4205 NeedClampOperand = true; 4206 } 4207 4208 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4209 if (TII->isVOP3(*I)) { 4210 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4211 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4212 I.addReg(TRI->getVCC(), RegState::Define); 4213 } 4214 I.add(MI.getOperand(1)) 4215 .add(MI.getOperand(2)); 4216 if (NeedClampOperand) 4217 I.addImm(0); // clamp bit for e64 encoding 4218 4219 TII->legalizeOperands(*I); 4220 4221 MI.eraseFromParent(); 4222 return BB; 4223 } 4224 case AMDGPU::DS_GWS_INIT: 4225 case AMDGPU::DS_GWS_SEMA_BR: 4226 case AMDGPU::DS_GWS_BARRIER: 4227 if (Subtarget->needsAlignedVGPRs()) { 4228 // Add implicit aligned super-reg to force alignment on the data operand. 4229 const DebugLoc &DL = MI.getDebugLoc(); 4230 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4231 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 4232 MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0); 4233 Register DataReg = Op->getReg(); 4234 bool IsAGPR = TRI->isAGPR(MRI, DataReg); 4235 Register Undef = MRI.createVirtualRegister( 4236 IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass); 4237 BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef); 4238 Register NewVR = 4239 MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass 4240 : &AMDGPU::VReg_64_Align2RegClass); 4241 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR) 4242 .addReg(DataReg, 0, Op->getSubReg()) 4243 .addImm(AMDGPU::sub0) 4244 .addReg(Undef) 4245 .addImm(AMDGPU::sub1); 4246 Op->setReg(NewVR); 4247 Op->setSubReg(AMDGPU::sub0); 4248 MI.addOperand(MachineOperand::CreateReg(NewVR, false, true)); 4249 } 4250 LLVM_FALLTHROUGH; 4251 case AMDGPU::DS_GWS_SEMA_V: 4252 case AMDGPU::DS_GWS_SEMA_P: 4253 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4254 // A s_waitcnt 0 is required to be the instruction immediately following. 4255 if (getSubtarget()->hasGWSAutoReplay()) { 4256 bundleInstWithWaitcnt(MI); 4257 return BB; 4258 } 4259 4260 return emitGWSMemViolTestLoop(MI, BB); 4261 case AMDGPU::S_SETREG_B32: { 4262 // Try to optimize cases that only set the denormal mode or rounding mode. 4263 // 4264 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4265 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4266 // instead. 4267 // 4268 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4269 // allow you to have a no side effect instruction in the output of a 4270 // sideeffecting pattern. 4271 unsigned ID, Offset, Width; 4272 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4273 if (ID != AMDGPU::Hwreg::ID_MODE) 4274 return BB; 4275 4276 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4277 const unsigned SetMask = WidthMask << Offset; 4278 4279 if (getSubtarget()->hasDenormModeInst()) { 4280 unsigned SetDenormOp = 0; 4281 unsigned SetRoundOp = 0; 4282 4283 // The dedicated instructions can only set the whole denorm or round mode 4284 // at once, not a subset of bits in either. 4285 if (SetMask == 4286 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4287 // If this fully sets both the round and denorm mode, emit the two 4288 // dedicated instructions for these. 4289 SetRoundOp = AMDGPU::S_ROUND_MODE; 4290 SetDenormOp = AMDGPU::S_DENORM_MODE; 4291 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4292 SetRoundOp = AMDGPU::S_ROUND_MODE; 4293 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4294 SetDenormOp = AMDGPU::S_DENORM_MODE; 4295 } 4296 4297 if (SetRoundOp || SetDenormOp) { 4298 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4299 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4300 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4301 unsigned ImmVal = Def->getOperand(1).getImm(); 4302 if (SetRoundOp) { 4303 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4304 .addImm(ImmVal & 0xf); 4305 4306 // If we also have the denorm mode, get just the denorm mode bits. 4307 ImmVal >>= 4; 4308 } 4309 4310 if (SetDenormOp) { 4311 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4312 .addImm(ImmVal & 0xf); 4313 } 4314 4315 MI.eraseFromParent(); 4316 return BB; 4317 } 4318 } 4319 } 4320 4321 // If only FP bits are touched, used the no side effects pseudo. 4322 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4323 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4324 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4325 4326 return BB; 4327 } 4328 default: 4329 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4330 } 4331 } 4332 4333 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4334 return isTypeLegal(VT.getScalarType()); 4335 } 4336 4337 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4338 // This currently forces unfolding various combinations of fsub into fma with 4339 // free fneg'd operands. As long as we have fast FMA (controlled by 4340 // isFMAFasterThanFMulAndFAdd), we should perform these. 4341 4342 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4343 // most of these combines appear to be cycle neutral but save on instruction 4344 // count / code size. 4345 return true; 4346 } 4347 4348 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4349 EVT VT) const { 4350 if (!VT.isVector()) { 4351 return MVT::i1; 4352 } 4353 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4354 } 4355 4356 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4357 // TODO: Should i16 be used always if legal? For now it would force VALU 4358 // shifts. 4359 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4360 } 4361 4362 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4363 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4364 ? Ty.changeElementSize(16) 4365 : Ty.changeElementSize(32); 4366 } 4367 4368 // Answering this is somewhat tricky and depends on the specific device which 4369 // have different rates for fma or all f64 operations. 4370 // 4371 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4372 // regardless of which device (although the number of cycles differs between 4373 // devices), so it is always profitable for f64. 4374 // 4375 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4376 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4377 // which we can always do even without fused FP ops since it returns the same 4378 // result as the separate operations and since it is always full 4379 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4380 // however does not support denormals, so we do report fma as faster if we have 4381 // a fast fma device and require denormals. 4382 // 4383 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4384 EVT VT) const { 4385 VT = VT.getScalarType(); 4386 4387 switch (VT.getSimpleVT().SimpleTy) { 4388 case MVT::f32: { 4389 // If mad is not available this depends only on if f32 fma is full rate. 4390 if (!Subtarget->hasMadMacF32Insts()) 4391 return Subtarget->hasFastFMAF32(); 4392 4393 // Otherwise f32 mad is always full rate and returns the same result as 4394 // the separate operations so should be preferred over fma. 4395 // However does not support denomals. 4396 if (hasFP32Denormals(MF)) 4397 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4398 4399 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4400 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4401 } 4402 case MVT::f64: 4403 return true; 4404 case MVT::f16: 4405 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4406 default: 4407 break; 4408 } 4409 4410 return false; 4411 } 4412 4413 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4414 const SDNode *N) const { 4415 // TODO: Check future ftz flag 4416 // v_mad_f32/v_mac_f32 do not support denormals. 4417 EVT VT = N->getValueType(0); 4418 if (VT == MVT::f32) 4419 return Subtarget->hasMadMacF32Insts() && 4420 !hasFP32Denormals(DAG.getMachineFunction()); 4421 if (VT == MVT::f16) { 4422 return Subtarget->hasMadF16() && 4423 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4424 } 4425 4426 return false; 4427 } 4428 4429 //===----------------------------------------------------------------------===// 4430 // Custom DAG Lowering Operations 4431 //===----------------------------------------------------------------------===// 4432 4433 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4434 // wider vector type is legal. 4435 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4436 SelectionDAG &DAG) const { 4437 unsigned Opc = Op.getOpcode(); 4438 EVT VT = Op.getValueType(); 4439 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4440 4441 SDValue Lo, Hi; 4442 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4443 4444 SDLoc SL(Op); 4445 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4446 Op->getFlags()); 4447 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4448 Op->getFlags()); 4449 4450 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4451 } 4452 4453 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4454 // wider vector type is legal. 4455 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4456 SelectionDAG &DAG) const { 4457 unsigned Opc = Op.getOpcode(); 4458 EVT VT = Op.getValueType(); 4459 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4460 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4461 4462 SDValue Lo0, Hi0; 4463 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4464 SDValue Lo1, Hi1; 4465 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4466 4467 SDLoc SL(Op); 4468 4469 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4470 Op->getFlags()); 4471 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4472 Op->getFlags()); 4473 4474 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4475 } 4476 4477 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4478 SelectionDAG &DAG) const { 4479 unsigned Opc = Op.getOpcode(); 4480 EVT VT = Op.getValueType(); 4481 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4482 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4483 4484 SDValue Lo0, Hi0; 4485 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4486 SDValue Lo1, Hi1; 4487 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4488 SDValue Lo2, Hi2; 4489 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4490 4491 SDLoc SL(Op); 4492 4493 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4494 Op->getFlags()); 4495 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4496 Op->getFlags()); 4497 4498 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4499 } 4500 4501 4502 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4503 switch (Op.getOpcode()) { 4504 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4505 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4506 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4507 case ISD::LOAD: { 4508 SDValue Result = LowerLOAD(Op, DAG); 4509 assert((!Result.getNode() || 4510 Result.getNode()->getNumValues() == 2) && 4511 "Load should return a value and a chain"); 4512 return Result; 4513 } 4514 4515 case ISD::FSIN: 4516 case ISD::FCOS: 4517 return LowerTrig(Op, DAG); 4518 case ISD::SELECT: return LowerSELECT(Op, DAG); 4519 case ISD::FDIV: return LowerFDIV(Op, DAG); 4520 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4521 case ISD::STORE: return LowerSTORE(Op, DAG); 4522 case ISD::GlobalAddress: { 4523 MachineFunction &MF = DAG.getMachineFunction(); 4524 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4525 return LowerGlobalAddress(MFI, Op, DAG); 4526 } 4527 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4528 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4529 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4530 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4531 case ISD::INSERT_SUBVECTOR: 4532 return lowerINSERT_SUBVECTOR(Op, DAG); 4533 case ISD::INSERT_VECTOR_ELT: 4534 return lowerINSERT_VECTOR_ELT(Op, DAG); 4535 case ISD::EXTRACT_VECTOR_ELT: 4536 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4537 case ISD::VECTOR_SHUFFLE: 4538 return lowerVECTOR_SHUFFLE(Op, DAG); 4539 case ISD::BUILD_VECTOR: 4540 return lowerBUILD_VECTOR(Op, DAG); 4541 case ISD::FP_ROUND: 4542 return lowerFP_ROUND(Op, DAG); 4543 case ISD::TRAP: 4544 return lowerTRAP(Op, DAG); 4545 case ISD::DEBUGTRAP: 4546 return lowerDEBUGTRAP(Op, DAG); 4547 case ISD::FABS: 4548 case ISD::FNEG: 4549 case ISD::FCANONICALIZE: 4550 case ISD::BSWAP: 4551 return splitUnaryVectorOp(Op, DAG); 4552 case ISD::FMINNUM: 4553 case ISD::FMAXNUM: 4554 return lowerFMINNUM_FMAXNUM(Op, DAG); 4555 case ISD::FMA: 4556 return splitTernaryVectorOp(Op, DAG); 4557 case ISD::FP_TO_SINT: 4558 case ISD::FP_TO_UINT: 4559 return LowerFP_TO_INT(Op, DAG); 4560 case ISD::SHL: 4561 case ISD::SRA: 4562 case ISD::SRL: 4563 case ISD::ADD: 4564 case ISD::SUB: 4565 case ISD::MUL: 4566 case ISD::SMIN: 4567 case ISD::SMAX: 4568 case ISD::UMIN: 4569 case ISD::UMAX: 4570 case ISD::FADD: 4571 case ISD::FMUL: 4572 case ISD::FMINNUM_IEEE: 4573 case ISD::FMAXNUM_IEEE: 4574 case ISD::UADDSAT: 4575 case ISD::USUBSAT: 4576 case ISD::SADDSAT: 4577 case ISD::SSUBSAT: 4578 return splitBinaryVectorOp(Op, DAG); 4579 case ISD::SMULO: 4580 case ISD::UMULO: 4581 return lowerXMULO(Op, DAG); 4582 case ISD::DYNAMIC_STACKALLOC: 4583 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4584 } 4585 return SDValue(); 4586 } 4587 4588 // Used for D16: Casts the result of an instruction into the right vector, 4589 // packs values if loads return unpacked values. 4590 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4591 const SDLoc &DL, 4592 SelectionDAG &DAG, bool Unpacked) { 4593 if (!LoadVT.isVector()) 4594 return Result; 4595 4596 // Cast back to the original packed type or to a larger type that is a 4597 // multiple of 32 bit for D16. Widening the return type is a required for 4598 // legalization. 4599 EVT FittingLoadVT = LoadVT; 4600 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4601 FittingLoadVT = 4602 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4603 LoadVT.getVectorNumElements() + 1); 4604 } 4605 4606 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4607 // Truncate to v2i16/v4i16. 4608 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4609 4610 // Workaround legalizer not scalarizing truncate after vector op 4611 // legalization but not creating intermediate vector trunc. 4612 SmallVector<SDValue, 4> Elts; 4613 DAG.ExtractVectorElements(Result, Elts); 4614 for (SDValue &Elt : Elts) 4615 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4616 4617 // Pad illegal v1i16/v3fi6 to v4i16 4618 if ((LoadVT.getVectorNumElements() % 2) == 1) 4619 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4620 4621 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4622 4623 // Bitcast to original type (v2f16/v4f16). 4624 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4625 } 4626 4627 // Cast back to the original packed type. 4628 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4629 } 4630 4631 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4632 MemSDNode *M, 4633 SelectionDAG &DAG, 4634 ArrayRef<SDValue> Ops, 4635 bool IsIntrinsic) const { 4636 SDLoc DL(M); 4637 4638 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4639 EVT LoadVT = M->getValueType(0); 4640 4641 EVT EquivLoadVT = LoadVT; 4642 if (LoadVT.isVector()) { 4643 if (Unpacked) { 4644 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4645 LoadVT.getVectorNumElements()); 4646 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4647 // Widen v3f16 to legal type 4648 EquivLoadVT = 4649 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4650 LoadVT.getVectorNumElements() + 1); 4651 } 4652 } 4653 4654 // Change from v4f16/v2f16 to EquivLoadVT. 4655 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4656 4657 SDValue Load 4658 = DAG.getMemIntrinsicNode( 4659 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4660 VTList, Ops, M->getMemoryVT(), 4661 M->getMemOperand()); 4662 4663 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4664 4665 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4666 } 4667 4668 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4669 SelectionDAG &DAG, 4670 ArrayRef<SDValue> Ops) const { 4671 SDLoc DL(M); 4672 EVT LoadVT = M->getValueType(0); 4673 EVT EltType = LoadVT.getScalarType(); 4674 EVT IntVT = LoadVT.changeTypeToInteger(); 4675 4676 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4677 4678 unsigned Opc = 4679 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4680 4681 if (IsD16) { 4682 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4683 } 4684 4685 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4686 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4687 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4688 4689 if (isTypeLegal(LoadVT)) { 4690 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4691 M->getMemOperand(), DAG); 4692 } 4693 4694 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4695 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4696 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4697 M->getMemOperand(), DAG); 4698 return DAG.getMergeValues( 4699 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4700 DL); 4701 } 4702 4703 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4704 SDNode *N, SelectionDAG &DAG) { 4705 EVT VT = N->getValueType(0); 4706 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4707 unsigned CondCode = CD->getZExtValue(); 4708 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4709 return DAG.getUNDEF(VT); 4710 4711 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4712 4713 SDValue LHS = N->getOperand(1); 4714 SDValue RHS = N->getOperand(2); 4715 4716 SDLoc DL(N); 4717 4718 EVT CmpVT = LHS.getValueType(); 4719 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4720 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4721 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4722 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4723 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4724 } 4725 4726 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4727 4728 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4729 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4730 4731 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4732 DAG.getCondCode(CCOpcode)); 4733 if (VT.bitsEq(CCVT)) 4734 return SetCC; 4735 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4736 } 4737 4738 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4739 SDNode *N, SelectionDAG &DAG) { 4740 EVT VT = N->getValueType(0); 4741 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4742 4743 unsigned CondCode = CD->getZExtValue(); 4744 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4745 return DAG.getUNDEF(VT); 4746 4747 SDValue Src0 = N->getOperand(1); 4748 SDValue Src1 = N->getOperand(2); 4749 EVT CmpVT = Src0.getValueType(); 4750 SDLoc SL(N); 4751 4752 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4753 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4754 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4755 } 4756 4757 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4758 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4759 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4760 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4761 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4762 Src1, DAG.getCondCode(CCOpcode)); 4763 if (VT.bitsEq(CCVT)) 4764 return SetCC; 4765 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4766 } 4767 4768 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4769 SelectionDAG &DAG) { 4770 EVT VT = N->getValueType(0); 4771 SDValue Src = N->getOperand(1); 4772 SDLoc SL(N); 4773 4774 if (Src.getOpcode() == ISD::SETCC) { 4775 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4776 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4777 Src.getOperand(1), Src.getOperand(2)); 4778 } 4779 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4780 // (ballot 0) -> 0 4781 if (Arg->isNullValue()) 4782 return DAG.getConstant(0, SL, VT); 4783 4784 // (ballot 1) -> EXEC/EXEC_LO 4785 if (Arg->isOne()) { 4786 Register Exec; 4787 if (VT.getScalarSizeInBits() == 32) 4788 Exec = AMDGPU::EXEC_LO; 4789 else if (VT.getScalarSizeInBits() == 64) 4790 Exec = AMDGPU::EXEC; 4791 else 4792 return SDValue(); 4793 4794 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4795 } 4796 } 4797 4798 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4799 // ISD::SETNE) 4800 return DAG.getNode( 4801 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4802 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4803 } 4804 4805 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4806 SmallVectorImpl<SDValue> &Results, 4807 SelectionDAG &DAG) const { 4808 switch (N->getOpcode()) { 4809 case ISD::INSERT_VECTOR_ELT: { 4810 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4811 Results.push_back(Res); 4812 return; 4813 } 4814 case ISD::EXTRACT_VECTOR_ELT: { 4815 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4816 Results.push_back(Res); 4817 return; 4818 } 4819 case ISD::INTRINSIC_WO_CHAIN: { 4820 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4821 switch (IID) { 4822 case Intrinsic::amdgcn_cvt_pkrtz: { 4823 SDValue Src0 = N->getOperand(1); 4824 SDValue Src1 = N->getOperand(2); 4825 SDLoc SL(N); 4826 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4827 Src0, Src1); 4828 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4829 return; 4830 } 4831 case Intrinsic::amdgcn_cvt_pknorm_i16: 4832 case Intrinsic::amdgcn_cvt_pknorm_u16: 4833 case Intrinsic::amdgcn_cvt_pk_i16: 4834 case Intrinsic::amdgcn_cvt_pk_u16: { 4835 SDValue Src0 = N->getOperand(1); 4836 SDValue Src1 = N->getOperand(2); 4837 SDLoc SL(N); 4838 unsigned Opcode; 4839 4840 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4841 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4842 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4843 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4844 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4845 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4846 else 4847 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4848 4849 EVT VT = N->getValueType(0); 4850 if (isTypeLegal(VT)) 4851 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4852 else { 4853 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4854 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4855 } 4856 return; 4857 } 4858 } 4859 break; 4860 } 4861 case ISD::INTRINSIC_W_CHAIN: { 4862 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4863 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4864 // FIXME: Hacky 4865 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4866 Results.push_back(Res.getOperand(I)); 4867 } 4868 } else { 4869 Results.push_back(Res); 4870 Results.push_back(Res.getValue(1)); 4871 } 4872 return; 4873 } 4874 4875 break; 4876 } 4877 case ISD::SELECT: { 4878 SDLoc SL(N); 4879 EVT VT = N->getValueType(0); 4880 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4881 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4882 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4883 4884 EVT SelectVT = NewVT; 4885 if (NewVT.bitsLT(MVT::i32)) { 4886 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4887 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4888 SelectVT = MVT::i32; 4889 } 4890 4891 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4892 N->getOperand(0), LHS, RHS); 4893 4894 if (NewVT != SelectVT) 4895 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4896 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4897 return; 4898 } 4899 case ISD::FNEG: { 4900 if (N->getValueType(0) != MVT::v2f16) 4901 break; 4902 4903 SDLoc SL(N); 4904 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4905 4906 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4907 BC, 4908 DAG.getConstant(0x80008000, SL, MVT::i32)); 4909 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4910 return; 4911 } 4912 case ISD::FABS: { 4913 if (N->getValueType(0) != MVT::v2f16) 4914 break; 4915 4916 SDLoc SL(N); 4917 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4918 4919 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4920 BC, 4921 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4922 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4923 return; 4924 } 4925 default: 4926 break; 4927 } 4928 } 4929 4930 /// Helper function for LowerBRCOND 4931 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4932 4933 SDNode *Parent = Value.getNode(); 4934 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4935 I != E; ++I) { 4936 4937 if (I.getUse().get() != Value) 4938 continue; 4939 4940 if (I->getOpcode() == Opcode) 4941 return *I; 4942 } 4943 return nullptr; 4944 } 4945 4946 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4947 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4948 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4949 case Intrinsic::amdgcn_if: 4950 return AMDGPUISD::IF; 4951 case Intrinsic::amdgcn_else: 4952 return AMDGPUISD::ELSE; 4953 case Intrinsic::amdgcn_loop: 4954 return AMDGPUISD::LOOP; 4955 case Intrinsic::amdgcn_end_cf: 4956 llvm_unreachable("should not occur"); 4957 default: 4958 return 0; 4959 } 4960 } 4961 4962 // break, if_break, else_break are all only used as inputs to loop, not 4963 // directly as branch conditions. 4964 return 0; 4965 } 4966 4967 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4968 const Triple &TT = getTargetMachine().getTargetTriple(); 4969 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4970 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4971 AMDGPU::shouldEmitConstantsToTextSection(TT); 4972 } 4973 4974 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4975 // FIXME: Either avoid relying on address space here or change the default 4976 // address space for functions to avoid the explicit check. 4977 return (GV->getValueType()->isFunctionTy() || 4978 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4979 !shouldEmitFixup(GV) && 4980 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4981 } 4982 4983 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4984 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4985 } 4986 4987 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4988 if (!GV->hasExternalLinkage()) 4989 return true; 4990 4991 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4992 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4993 } 4994 4995 /// This transforms the control flow intrinsics to get the branch destination as 4996 /// last parameter, also switches branch target with BR if the need arise 4997 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4998 SelectionDAG &DAG) const { 4999 SDLoc DL(BRCOND); 5000 5001 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5002 SDValue Target = BRCOND.getOperand(2); 5003 SDNode *BR = nullptr; 5004 SDNode *SetCC = nullptr; 5005 5006 if (Intr->getOpcode() == ISD::SETCC) { 5007 // As long as we negate the condition everything is fine 5008 SetCC = Intr; 5009 Intr = SetCC->getOperand(0).getNode(); 5010 5011 } else { 5012 // Get the target from BR if we don't negate the condition 5013 BR = findUser(BRCOND, ISD::BR); 5014 assert(BR && "brcond missing unconditional branch user"); 5015 Target = BR->getOperand(1); 5016 } 5017 5018 unsigned CFNode = isCFIntrinsic(Intr); 5019 if (CFNode == 0) { 5020 // This is a uniform branch so we don't need to legalize. 5021 return BRCOND; 5022 } 5023 5024 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5025 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5026 5027 assert(!SetCC || 5028 (SetCC->getConstantOperandVal(1) == 1 && 5029 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5030 ISD::SETNE)); 5031 5032 // operands of the new intrinsic call 5033 SmallVector<SDValue, 4> Ops; 5034 if (HaveChain) 5035 Ops.push_back(BRCOND.getOperand(0)); 5036 5037 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5038 Ops.push_back(Target); 5039 5040 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5041 5042 // build the new intrinsic call 5043 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5044 5045 if (!HaveChain) { 5046 SDValue Ops[] = { 5047 SDValue(Result, 0), 5048 BRCOND.getOperand(0) 5049 }; 5050 5051 Result = DAG.getMergeValues(Ops, DL).getNode(); 5052 } 5053 5054 if (BR) { 5055 // Give the branch instruction our target 5056 SDValue Ops[] = { 5057 BR->getOperand(0), 5058 BRCOND.getOperand(2) 5059 }; 5060 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5061 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5062 } 5063 5064 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5065 5066 // Copy the intrinsic results to registers 5067 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5068 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5069 if (!CopyToReg) 5070 continue; 5071 5072 Chain = DAG.getCopyToReg( 5073 Chain, DL, 5074 CopyToReg->getOperand(1), 5075 SDValue(Result, i - 1), 5076 SDValue()); 5077 5078 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5079 } 5080 5081 // Remove the old intrinsic from the chain 5082 DAG.ReplaceAllUsesOfValueWith( 5083 SDValue(Intr, Intr->getNumValues() - 1), 5084 Intr->getOperand(0)); 5085 5086 return Chain; 5087 } 5088 5089 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5090 SelectionDAG &DAG) const { 5091 MVT VT = Op.getSimpleValueType(); 5092 SDLoc DL(Op); 5093 // Checking the depth 5094 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5095 return DAG.getConstant(0, DL, VT); 5096 5097 MachineFunction &MF = DAG.getMachineFunction(); 5098 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5099 // Check for kernel and shader functions 5100 if (Info->isEntryFunction()) 5101 return DAG.getConstant(0, DL, VT); 5102 5103 MachineFrameInfo &MFI = MF.getFrameInfo(); 5104 // There is a call to @llvm.returnaddress in this function 5105 MFI.setReturnAddressIsTaken(true); 5106 5107 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5108 // Get the return address reg and mark it as an implicit live-in 5109 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5110 5111 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5112 } 5113 5114 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5115 SDValue Op, 5116 const SDLoc &DL, 5117 EVT VT) const { 5118 return Op.getValueType().bitsLE(VT) ? 5119 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5120 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5121 DAG.getTargetConstant(0, DL, MVT::i32)); 5122 } 5123 5124 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5125 assert(Op.getValueType() == MVT::f16 && 5126 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5127 5128 SDValue Src = Op.getOperand(0); 5129 EVT SrcVT = Src.getValueType(); 5130 if (SrcVT != MVT::f64) 5131 return Op; 5132 5133 SDLoc DL(Op); 5134 5135 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5136 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5137 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5138 } 5139 5140 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5141 SelectionDAG &DAG) const { 5142 EVT VT = Op.getValueType(); 5143 const MachineFunction &MF = DAG.getMachineFunction(); 5144 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5145 bool IsIEEEMode = Info->getMode().IEEE; 5146 5147 // FIXME: Assert during selection that this is only selected for 5148 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5149 // mode functions, but this happens to be OK since it's only done in cases 5150 // where there is known no sNaN. 5151 if (IsIEEEMode) 5152 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5153 5154 if (VT == MVT::v4f16) 5155 return splitBinaryVectorOp(Op, DAG); 5156 return Op; 5157 } 5158 5159 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5160 EVT VT = Op.getValueType(); 5161 SDLoc SL(Op); 5162 SDValue LHS = Op.getOperand(0); 5163 SDValue RHS = Op.getOperand(1); 5164 bool isSigned = Op.getOpcode() == ISD::SMULO; 5165 5166 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5167 const APInt &C = RHSC->getAPIntValue(); 5168 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5169 if (C.isPowerOf2()) { 5170 // smulo(x, signed_min) is same as umulo(x, signed_min). 5171 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5172 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5173 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5174 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5175 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5176 SL, VT, Result, ShiftAmt), 5177 LHS, ISD::SETNE); 5178 return DAG.getMergeValues({ Result, Overflow }, SL); 5179 } 5180 } 5181 5182 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5183 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5184 SL, VT, LHS, RHS); 5185 5186 SDValue Sign = isSigned 5187 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5188 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5189 : DAG.getConstant(0, SL, VT); 5190 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5191 5192 return DAG.getMergeValues({ Result, Overflow }, SL); 5193 } 5194 5195 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5196 if (!Subtarget->isTrapHandlerEnabled() || 5197 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5198 return lowerTrapEndpgm(Op, DAG); 5199 5200 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5201 switch (*HsaAbiVer) { 5202 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5203 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5204 return lowerTrapHsaQueuePtr(Op, DAG); 5205 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5206 return Subtarget->supportsGetDoorbellID() ? 5207 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5208 } 5209 } 5210 5211 llvm_unreachable("Unknown trap handler"); 5212 } 5213 5214 SDValue SITargetLowering::lowerTrapEndpgm( 5215 SDValue Op, SelectionDAG &DAG) const { 5216 SDLoc SL(Op); 5217 SDValue Chain = Op.getOperand(0); 5218 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5219 } 5220 5221 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5222 SDValue Op, SelectionDAG &DAG) const { 5223 SDLoc SL(Op); 5224 SDValue Chain = Op.getOperand(0); 5225 5226 MachineFunction &MF = DAG.getMachineFunction(); 5227 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5228 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5229 assert(UserSGPR != AMDGPU::NoRegister); 5230 SDValue QueuePtr = CreateLiveInRegister( 5231 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5232 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5233 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5234 QueuePtr, SDValue()); 5235 5236 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5237 SDValue Ops[] = { 5238 ToReg, 5239 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5240 SGPR01, 5241 ToReg.getValue(1) 5242 }; 5243 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5244 } 5245 5246 SDValue SITargetLowering::lowerTrapHsa( 5247 SDValue Op, SelectionDAG &DAG) const { 5248 SDLoc SL(Op); 5249 SDValue Chain = Op.getOperand(0); 5250 5251 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5252 SDValue Ops[] = { 5253 Chain, 5254 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5255 }; 5256 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5257 } 5258 5259 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5260 SDLoc SL(Op); 5261 SDValue Chain = Op.getOperand(0); 5262 MachineFunction &MF = DAG.getMachineFunction(); 5263 5264 if (!Subtarget->isTrapHandlerEnabled() || 5265 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5266 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5267 "debugtrap handler not supported", 5268 Op.getDebugLoc(), 5269 DS_Warning); 5270 LLVMContext &Ctx = MF.getFunction().getContext(); 5271 Ctx.diagnose(NoTrap); 5272 return Chain; 5273 } 5274 5275 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5276 SDValue Ops[] = { 5277 Chain, 5278 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5279 }; 5280 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5281 } 5282 5283 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5284 SelectionDAG &DAG) const { 5285 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5286 if (Subtarget->hasApertureRegs()) { 5287 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5288 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5289 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5290 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5291 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5292 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5293 unsigned Encoding = 5294 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5295 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5296 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5297 5298 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5299 SDValue ApertureReg = SDValue( 5300 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5301 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5302 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5303 } 5304 5305 MachineFunction &MF = DAG.getMachineFunction(); 5306 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5307 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5308 assert(UserSGPR != AMDGPU::NoRegister); 5309 5310 SDValue QueuePtr = CreateLiveInRegister( 5311 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5312 5313 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5314 // private_segment_aperture_base_hi. 5315 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5316 5317 SDValue Ptr = 5318 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5319 5320 // TODO: Use custom target PseudoSourceValue. 5321 // TODO: We should use the value from the IR intrinsic call, but it might not 5322 // be available and how do we get it? 5323 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5324 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5325 commonAlignment(Align(64), StructOffset), 5326 MachineMemOperand::MODereferenceable | 5327 MachineMemOperand::MOInvariant); 5328 } 5329 5330 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5331 SelectionDAG &DAG) const { 5332 SDLoc SL(Op); 5333 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5334 5335 SDValue Src = ASC->getOperand(0); 5336 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5337 5338 const AMDGPUTargetMachine &TM = 5339 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5340 5341 // flat -> local/private 5342 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5343 unsigned DestAS = ASC->getDestAddressSpace(); 5344 5345 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5346 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5347 unsigned NullVal = TM.getNullPointerValue(DestAS); 5348 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5349 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5350 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5351 5352 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5353 NonNull, Ptr, SegmentNullPtr); 5354 } 5355 } 5356 5357 // local/private -> flat 5358 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5359 unsigned SrcAS = ASC->getSrcAddressSpace(); 5360 5361 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5362 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5363 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5364 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5365 5366 SDValue NonNull 5367 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5368 5369 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5370 SDValue CvtPtr 5371 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5372 5373 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5374 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5375 FlatNullPtr); 5376 } 5377 } 5378 5379 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5380 Src.getValueType() == MVT::i64) 5381 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5382 5383 // global <-> flat are no-ops and never emitted. 5384 5385 const MachineFunction &MF = DAG.getMachineFunction(); 5386 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5387 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5388 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5389 5390 return DAG.getUNDEF(ASC->getValueType(0)); 5391 } 5392 5393 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5394 // the small vector and inserting them into the big vector. That is better than 5395 // the default expansion of doing it via a stack slot. Even though the use of 5396 // the stack slot would be optimized away afterwards, the stack slot itself 5397 // remains. 5398 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5399 SelectionDAG &DAG) const { 5400 SDValue Vec = Op.getOperand(0); 5401 SDValue Ins = Op.getOperand(1); 5402 SDValue Idx = Op.getOperand(2); 5403 EVT VecVT = Vec.getValueType(); 5404 EVT InsVT = Ins.getValueType(); 5405 EVT EltVT = VecVT.getVectorElementType(); 5406 unsigned InsNumElts = InsVT.getVectorNumElements(); 5407 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5408 SDLoc SL(Op); 5409 5410 for (unsigned I = 0; I != InsNumElts; ++I) { 5411 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5412 DAG.getConstant(I, SL, MVT::i32)); 5413 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5414 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5415 } 5416 return Vec; 5417 } 5418 5419 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5420 SelectionDAG &DAG) const { 5421 SDValue Vec = Op.getOperand(0); 5422 SDValue InsVal = Op.getOperand(1); 5423 SDValue Idx = Op.getOperand(2); 5424 EVT VecVT = Vec.getValueType(); 5425 EVT EltVT = VecVT.getVectorElementType(); 5426 unsigned VecSize = VecVT.getSizeInBits(); 5427 unsigned EltSize = EltVT.getSizeInBits(); 5428 5429 5430 assert(VecSize <= 64); 5431 5432 unsigned NumElts = VecVT.getVectorNumElements(); 5433 SDLoc SL(Op); 5434 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5435 5436 if (NumElts == 4 && EltSize == 16 && KIdx) { 5437 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5438 5439 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5440 DAG.getConstant(0, SL, MVT::i32)); 5441 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5442 DAG.getConstant(1, SL, MVT::i32)); 5443 5444 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5445 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5446 5447 unsigned Idx = KIdx->getZExtValue(); 5448 bool InsertLo = Idx < 2; 5449 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5450 InsertLo ? LoVec : HiVec, 5451 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5452 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5453 5454 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5455 5456 SDValue Concat = InsertLo ? 5457 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5458 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5459 5460 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5461 } 5462 5463 if (isa<ConstantSDNode>(Idx)) 5464 return SDValue(); 5465 5466 MVT IntVT = MVT::getIntegerVT(VecSize); 5467 5468 // Avoid stack access for dynamic indexing. 5469 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5470 5471 // Create a congruent vector with the target value in each element so that 5472 // the required element can be masked and ORed into the target vector. 5473 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5474 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5475 5476 assert(isPowerOf2_32(EltSize)); 5477 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5478 5479 // Convert vector index to bit-index. 5480 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5481 5482 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5483 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5484 DAG.getConstant(0xffff, SL, IntVT), 5485 ScaledIdx); 5486 5487 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5488 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5489 DAG.getNOT(SL, BFM, IntVT), BCVec); 5490 5491 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5492 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5493 } 5494 5495 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5496 SelectionDAG &DAG) const { 5497 SDLoc SL(Op); 5498 5499 EVT ResultVT = Op.getValueType(); 5500 SDValue Vec = Op.getOperand(0); 5501 SDValue Idx = Op.getOperand(1); 5502 EVT VecVT = Vec.getValueType(); 5503 unsigned VecSize = VecVT.getSizeInBits(); 5504 EVT EltVT = VecVT.getVectorElementType(); 5505 assert(VecSize <= 64); 5506 5507 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5508 5509 // Make sure we do any optimizations that will make it easier to fold 5510 // source modifiers before obscuring it with bit operations. 5511 5512 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5513 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5514 return Combined; 5515 5516 unsigned EltSize = EltVT.getSizeInBits(); 5517 assert(isPowerOf2_32(EltSize)); 5518 5519 MVT IntVT = MVT::getIntegerVT(VecSize); 5520 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5521 5522 // Convert vector index to bit-index (* EltSize) 5523 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5524 5525 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5526 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5527 5528 if (ResultVT == MVT::f16) { 5529 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5530 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5531 } 5532 5533 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5534 } 5535 5536 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5537 assert(Elt % 2 == 0); 5538 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5539 } 5540 5541 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5542 SelectionDAG &DAG) const { 5543 SDLoc SL(Op); 5544 EVT ResultVT = Op.getValueType(); 5545 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5546 5547 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5548 EVT EltVT = PackVT.getVectorElementType(); 5549 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5550 5551 // vector_shuffle <0,1,6,7> lhs, rhs 5552 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5553 // 5554 // vector_shuffle <6,7,2,3> lhs, rhs 5555 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5556 // 5557 // vector_shuffle <6,7,0,1> lhs, rhs 5558 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5559 5560 // Avoid scalarizing when both halves are reading from consecutive elements. 5561 SmallVector<SDValue, 4> Pieces; 5562 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5563 if (elementPairIsContiguous(SVN->getMask(), I)) { 5564 const int Idx = SVN->getMaskElt(I); 5565 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5566 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5567 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5568 PackVT, SVN->getOperand(VecIdx), 5569 DAG.getConstant(EltIdx, SL, MVT::i32)); 5570 Pieces.push_back(SubVec); 5571 } else { 5572 const int Idx0 = SVN->getMaskElt(I); 5573 const int Idx1 = SVN->getMaskElt(I + 1); 5574 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5575 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5576 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5577 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5578 5579 SDValue Vec0 = SVN->getOperand(VecIdx0); 5580 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5581 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5582 5583 SDValue Vec1 = SVN->getOperand(VecIdx1); 5584 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5585 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5586 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5587 } 5588 } 5589 5590 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5591 } 5592 5593 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5594 SelectionDAG &DAG) const { 5595 SDLoc SL(Op); 5596 EVT VT = Op.getValueType(); 5597 5598 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5599 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5600 5601 // Turn into pair of packed build_vectors. 5602 // TODO: Special case for constants that can be materialized with s_mov_b64. 5603 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5604 { Op.getOperand(0), Op.getOperand(1) }); 5605 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5606 { Op.getOperand(2), Op.getOperand(3) }); 5607 5608 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5609 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5610 5611 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5612 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5613 } 5614 5615 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5616 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5617 5618 SDValue Lo = Op.getOperand(0); 5619 SDValue Hi = Op.getOperand(1); 5620 5621 // Avoid adding defined bits with the zero_extend. 5622 if (Hi.isUndef()) { 5623 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5624 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5625 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5626 } 5627 5628 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5629 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5630 5631 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5632 DAG.getConstant(16, SL, MVT::i32)); 5633 if (Lo.isUndef()) 5634 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5635 5636 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5637 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5638 5639 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5640 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5641 } 5642 5643 bool 5644 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5645 // We can fold offsets for anything that doesn't require a GOT relocation. 5646 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5647 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5648 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5649 !shouldEmitGOTReloc(GA->getGlobal()); 5650 } 5651 5652 static SDValue 5653 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5654 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5655 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5656 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5657 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5658 // lowered to the following code sequence: 5659 // 5660 // For constant address space: 5661 // s_getpc_b64 s[0:1] 5662 // s_add_u32 s0, s0, $symbol 5663 // s_addc_u32 s1, s1, 0 5664 // 5665 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5666 // a fixup or relocation is emitted to replace $symbol with a literal 5667 // constant, which is a pc-relative offset from the encoding of the $symbol 5668 // operand to the global variable. 5669 // 5670 // For global address space: 5671 // s_getpc_b64 s[0:1] 5672 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5673 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5674 // 5675 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5676 // fixups or relocations are emitted to replace $symbol@*@lo and 5677 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5678 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5679 // operand to the global variable. 5680 // 5681 // What we want here is an offset from the value returned by s_getpc 5682 // (which is the address of the s_add_u32 instruction) to the global 5683 // variable, but since the encoding of $symbol starts 4 bytes after the start 5684 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5685 // small. This requires us to add 4 to the global variable offset in order to 5686 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5687 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5688 // instruction. 5689 SDValue PtrLo = 5690 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5691 SDValue PtrHi; 5692 if (GAFlags == SIInstrInfo::MO_NONE) { 5693 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5694 } else { 5695 PtrHi = 5696 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5697 } 5698 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5699 } 5700 5701 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5702 SDValue Op, 5703 SelectionDAG &DAG) const { 5704 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5705 SDLoc DL(GSD); 5706 EVT PtrVT = Op.getValueType(); 5707 5708 const GlobalValue *GV = GSD->getGlobal(); 5709 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5710 shouldUseLDSConstAddress(GV)) || 5711 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5712 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5713 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5714 GV->hasExternalLinkage()) { 5715 Type *Ty = GV->getValueType(); 5716 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5717 // zero-sized type in other languages to declare the dynamic shared 5718 // memory which size is not known at the compile time. They will be 5719 // allocated by the runtime and placed directly after the static 5720 // allocated ones. They all share the same offset. 5721 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5722 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5723 // Adjust alignment for that dynamic shared memory array. 5724 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5725 return SDValue( 5726 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5727 } 5728 } 5729 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5730 } 5731 5732 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5733 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5734 SIInstrInfo::MO_ABS32_LO); 5735 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5736 } 5737 5738 if (shouldEmitFixup(GV)) 5739 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5740 else if (shouldEmitPCReloc(GV)) 5741 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5742 SIInstrInfo::MO_REL32); 5743 5744 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5745 SIInstrInfo::MO_GOTPCREL32); 5746 5747 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5748 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5749 const DataLayout &DataLayout = DAG.getDataLayout(); 5750 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5751 MachinePointerInfo PtrInfo 5752 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5753 5754 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5755 MachineMemOperand::MODereferenceable | 5756 MachineMemOperand::MOInvariant); 5757 } 5758 5759 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5760 const SDLoc &DL, SDValue V) const { 5761 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5762 // the destination register. 5763 // 5764 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5765 // so we will end up with redundant moves to m0. 5766 // 5767 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5768 5769 // A Null SDValue creates a glue result. 5770 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5771 V, Chain); 5772 return SDValue(M0, 0); 5773 } 5774 5775 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5776 SDValue Op, 5777 MVT VT, 5778 unsigned Offset) const { 5779 SDLoc SL(Op); 5780 SDValue Param = lowerKernargMemParameter( 5781 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5782 // The local size values will have the hi 16-bits as zero. 5783 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5784 DAG.getValueType(VT)); 5785 } 5786 5787 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5788 EVT VT) { 5789 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5790 "non-hsa intrinsic with hsa target", 5791 DL.getDebugLoc()); 5792 DAG.getContext()->diagnose(BadIntrin); 5793 return DAG.getUNDEF(VT); 5794 } 5795 5796 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5797 EVT VT) { 5798 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5799 "intrinsic not supported on subtarget", 5800 DL.getDebugLoc()); 5801 DAG.getContext()->diagnose(BadIntrin); 5802 return DAG.getUNDEF(VT); 5803 } 5804 5805 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5806 ArrayRef<SDValue> Elts) { 5807 assert(!Elts.empty()); 5808 MVT Type; 5809 unsigned NumElts; 5810 5811 if (Elts.size() == 1) { 5812 Type = MVT::f32; 5813 NumElts = 1; 5814 } else if (Elts.size() == 2) { 5815 Type = MVT::v2f32; 5816 NumElts = 2; 5817 } else if (Elts.size() == 3) { 5818 Type = MVT::v3f32; 5819 NumElts = 3; 5820 } else if (Elts.size() <= 4) { 5821 Type = MVT::v4f32; 5822 NumElts = 4; 5823 } else if (Elts.size() <= 8) { 5824 Type = MVT::v8f32; 5825 NumElts = 8; 5826 } else { 5827 assert(Elts.size() <= 16); 5828 Type = MVT::v16f32; 5829 NumElts = 16; 5830 } 5831 5832 SmallVector<SDValue, 16> VecElts(NumElts); 5833 for (unsigned i = 0; i < Elts.size(); ++i) { 5834 SDValue Elt = Elts[i]; 5835 if (Elt.getValueType() != MVT::f32) 5836 Elt = DAG.getBitcast(MVT::f32, Elt); 5837 VecElts[i] = Elt; 5838 } 5839 for (unsigned i = Elts.size(); i < NumElts; ++i) 5840 VecElts[i] = DAG.getUNDEF(MVT::f32); 5841 5842 if (NumElts == 1) 5843 return VecElts[0]; 5844 return DAG.getBuildVector(Type, DL, VecElts); 5845 } 5846 5847 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5848 SDValue Src, int ExtraElts) { 5849 EVT SrcVT = Src.getValueType(); 5850 5851 SmallVector<SDValue, 8> Elts; 5852 5853 if (SrcVT.isVector()) 5854 DAG.ExtractVectorElements(Src, Elts); 5855 else 5856 Elts.push_back(Src); 5857 5858 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5859 while (ExtraElts--) 5860 Elts.push_back(Undef); 5861 5862 return DAG.getBuildVector(CastVT, DL, Elts); 5863 } 5864 5865 // Re-construct the required return value for a image load intrinsic. 5866 // This is more complicated due to the optional use TexFailCtrl which means the required 5867 // return type is an aggregate 5868 static SDValue constructRetValue(SelectionDAG &DAG, 5869 MachineSDNode *Result, 5870 ArrayRef<EVT> ResultTypes, 5871 bool IsTexFail, bool Unpacked, bool IsD16, 5872 int DMaskPop, int NumVDataDwords, 5873 const SDLoc &DL) { 5874 // Determine the required return type. This is the same regardless of IsTexFail flag 5875 EVT ReqRetVT = ResultTypes[0]; 5876 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5877 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5878 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5879 5880 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5881 DMaskPop : (DMaskPop + 1) / 2; 5882 5883 MVT DataDwordVT = NumDataDwords == 1 ? 5884 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5885 5886 MVT MaskPopVT = MaskPopDwords == 1 ? 5887 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5888 5889 SDValue Data(Result, 0); 5890 SDValue TexFail; 5891 5892 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 5893 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5894 if (MaskPopVT.isVector()) { 5895 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5896 SDValue(Result, 0), ZeroIdx); 5897 } else { 5898 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5899 SDValue(Result, 0), ZeroIdx); 5900 } 5901 } 5902 5903 if (DataDwordVT.isVector()) 5904 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5905 NumDataDwords - MaskPopDwords); 5906 5907 if (IsD16) 5908 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5909 5910 EVT LegalReqRetVT = ReqRetVT; 5911 if (!ReqRetVT.isVector()) { 5912 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5913 } else { 5914 // We need to widen the return vector to a legal type 5915 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 5916 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 5917 LegalReqRetVT = 5918 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 5919 ReqRetVT.getVectorNumElements() + 1); 5920 } 5921 } 5922 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 5923 5924 if (IsTexFail) { 5925 TexFail = 5926 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 5927 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5928 5929 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5930 } 5931 5932 if (Result->getNumValues() == 1) 5933 return Data; 5934 5935 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5936 } 5937 5938 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5939 SDValue *LWE, bool &IsTexFail) { 5940 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5941 5942 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5943 if (Value) { 5944 IsTexFail = true; 5945 } 5946 5947 SDLoc DL(TexFailCtrlConst); 5948 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5949 Value &= ~(uint64_t)0x1; 5950 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5951 Value &= ~(uint64_t)0x2; 5952 5953 return Value == 0; 5954 } 5955 5956 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op, 5957 MVT PackVectorVT, 5958 SmallVectorImpl<SDValue> &PackedAddrs, 5959 unsigned DimIdx, unsigned EndIdx, 5960 unsigned NumGradients) { 5961 SDLoc DL(Op); 5962 for (unsigned I = DimIdx; I < EndIdx; I++) { 5963 SDValue Addr = Op.getOperand(I); 5964 5965 // Gradients are packed with undef for each coordinate. 5966 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5967 // 1D: undef,dx/dh; undef,dx/dv 5968 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5969 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5970 if (((I + 1) >= EndIdx) || 5971 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5972 I == DimIdx + NumGradients - 1))) { 5973 if (Addr.getValueType() != MVT::i16) 5974 Addr = DAG.getBitcast(MVT::i16, Addr); 5975 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5976 } else { 5977 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5978 I++; 5979 } 5980 Addr = DAG.getBitcast(MVT::f32, Addr); 5981 PackedAddrs.push_back(Addr); 5982 } 5983 } 5984 5985 SDValue SITargetLowering::lowerImage(SDValue Op, 5986 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5987 SelectionDAG &DAG, bool WithChain) const { 5988 SDLoc DL(Op); 5989 MachineFunction &MF = DAG.getMachineFunction(); 5990 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5991 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5992 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5993 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5994 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5995 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5996 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5997 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5998 unsigned IntrOpcode = Intr->BaseOpcode; 5999 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6000 6001 SmallVector<EVT, 3> ResultTypes(Op->values()); 6002 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 6003 bool IsD16 = false; 6004 bool IsG16 = false; 6005 bool IsA16 = false; 6006 SDValue VData; 6007 int NumVDataDwords; 6008 bool AdjustRetType = false; 6009 6010 // Offset of intrinsic arguments 6011 const unsigned ArgOffset = WithChain ? 2 : 1; 6012 6013 unsigned DMask; 6014 unsigned DMaskLanes = 0; 6015 6016 if (BaseOpcode->Atomic) { 6017 VData = Op.getOperand(2); 6018 6019 bool Is64Bit = VData.getValueType() == MVT::i64; 6020 if (BaseOpcode->AtomicX2) { 6021 SDValue VData2 = Op.getOperand(3); 6022 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6023 {VData, VData2}); 6024 if (Is64Bit) 6025 VData = DAG.getBitcast(MVT::v4i32, VData); 6026 6027 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6028 DMask = Is64Bit ? 0xf : 0x3; 6029 NumVDataDwords = Is64Bit ? 4 : 2; 6030 } else { 6031 DMask = Is64Bit ? 0x3 : 0x1; 6032 NumVDataDwords = Is64Bit ? 2 : 1; 6033 } 6034 } else { 6035 auto *DMaskConst = 6036 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6037 DMask = DMaskConst->getZExtValue(); 6038 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6039 6040 if (BaseOpcode->Store) { 6041 VData = Op.getOperand(2); 6042 6043 MVT StoreVT = VData.getSimpleValueType(); 6044 if (StoreVT.getScalarType() == MVT::f16) { 6045 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6046 return Op; // D16 is unsupported for this instruction 6047 6048 IsD16 = true; 6049 VData = handleD16VData(VData, DAG, true); 6050 } 6051 6052 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6053 } else { 6054 // Work out the num dwords based on the dmask popcount and underlying type 6055 // and whether packing is supported. 6056 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6057 if (LoadVT.getScalarType() == MVT::f16) { 6058 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6059 return Op; // D16 is unsupported for this instruction 6060 6061 IsD16 = true; 6062 } 6063 6064 // Confirm that the return type is large enough for the dmask specified 6065 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6066 (!LoadVT.isVector() && DMaskLanes > 1)) 6067 return Op; 6068 6069 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6070 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6071 // instructions. 6072 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6073 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6074 NumVDataDwords = (DMaskLanes + 1) / 2; 6075 else 6076 NumVDataDwords = DMaskLanes; 6077 6078 AdjustRetType = true; 6079 } 6080 } 6081 6082 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6083 SmallVector<SDValue, 4> VAddrs; 6084 6085 // Optimize _L to _LZ when _L is zero 6086 if (LZMappingInfo) { 6087 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6088 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6089 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6090 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6091 VAddrEnd--; // remove 'lod' 6092 } 6093 } 6094 } 6095 6096 // Optimize _mip away, when 'lod' is zero 6097 if (MIPMappingInfo) { 6098 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6099 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6100 if (ConstantLod->isNullValue()) { 6101 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6102 VAddrEnd--; // remove 'mip' 6103 } 6104 } 6105 } 6106 6107 // Push back extra arguments. 6108 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) 6109 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6110 6111 // Check for 16 bit addresses or derivatives and pack if true. 6112 MVT VAddrVT = 6113 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6114 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6115 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6116 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6117 6118 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6119 VAddrScalarVT = VAddrVT.getScalarType(); 6120 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6121 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6122 6123 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) { 6124 // 16 bit gradients are supported, but are tied to the A16 control 6125 // so both gradients and addresses must be 16 bit 6126 LLVM_DEBUG( 6127 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6128 "require 16 bit args for both gradients and addresses"); 6129 return Op; 6130 } 6131 6132 if (IsA16) { 6133 if (!ST->hasA16()) { 6134 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6135 "support 16 bit addresses\n"); 6136 return Op; 6137 } 6138 } 6139 6140 // We've dealt with incorrect input so we know that if IsA16, IsG16 6141 // are set then we have to compress/pack operands (either address, 6142 // gradient or both) 6143 // In the case where a16 and gradients are tied (no G16 support) then we 6144 // have already verified that both IsA16 and IsG16 are true 6145 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) { 6146 // Activate g16 6147 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6148 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6149 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6150 } 6151 6152 // Add gradients (packed or unpacked) 6153 if (IsG16) { 6154 // Pack the gradients 6155 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6156 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs, 6157 ArgOffset + Intr->GradientStart, 6158 ArgOffset + Intr->CoordStart, Intr->NumGradients); 6159 } else { 6160 for (unsigned I = ArgOffset + Intr->GradientStart; 6161 I < ArgOffset + Intr->CoordStart; I++) 6162 VAddrs.push_back(Op.getOperand(I)); 6163 } 6164 6165 // Add addresses (packed or unpacked) 6166 if (IsA16) { 6167 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs, 6168 ArgOffset + Intr->CoordStart, VAddrEnd, 6169 0 /* No gradients */); 6170 } else { 6171 // Add uncompressed address 6172 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6173 VAddrs.push_back(Op.getOperand(I)); 6174 } 6175 6176 // If the register allocator cannot place the address registers contiguously 6177 // without introducing moves, then using the non-sequential address encoding 6178 // is always preferable, since it saves VALU instructions and is usually a 6179 // wash in terms of code size or even better. 6180 // 6181 // However, we currently have no way of hinting to the register allocator that 6182 // MIMG addresses should be placed contiguously when it is possible to do so, 6183 // so force non-NSA for the common 2-address case as a heuristic. 6184 // 6185 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6186 // allocation when possible. 6187 bool UseNSA = 6188 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 6189 SDValue VAddr; 6190 if (!UseNSA) 6191 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6192 6193 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6194 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6195 SDValue Unorm; 6196 if (!BaseOpcode->Sampler) { 6197 Unorm = True; 6198 } else { 6199 auto UnormConst = 6200 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6201 6202 Unorm = UnormConst->getZExtValue() ? True : False; 6203 } 6204 6205 SDValue TFE; 6206 SDValue LWE; 6207 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6208 bool IsTexFail = false; 6209 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6210 return Op; 6211 6212 if (IsTexFail) { 6213 if (!DMaskLanes) { 6214 // Expecting to get an error flag since TFC is on - and dmask is 0 6215 // Force dmask to be at least 1 otherwise the instruction will fail 6216 DMask = 0x1; 6217 DMaskLanes = 1; 6218 NumVDataDwords = 1; 6219 } 6220 NumVDataDwords += 1; 6221 AdjustRetType = true; 6222 } 6223 6224 // Has something earlier tagged that the return type needs adjusting 6225 // This happens if the instruction is a load or has set TexFailCtrl flags 6226 if (AdjustRetType) { 6227 // NumVDataDwords reflects the true number of dwords required in the return type 6228 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6229 // This is a no-op load. This can be eliminated 6230 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6231 if (isa<MemSDNode>(Op)) 6232 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6233 return Undef; 6234 } 6235 6236 EVT NewVT = NumVDataDwords > 1 ? 6237 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6238 : MVT::i32; 6239 6240 ResultTypes[0] = NewVT; 6241 if (ResultTypes.size() == 3) { 6242 // Original result was aggregate type used for TexFailCtrl results 6243 // The actual instruction returns as a vector type which has now been 6244 // created. Remove the aggregate result. 6245 ResultTypes.erase(&ResultTypes[1]); 6246 } 6247 } 6248 6249 unsigned CPol = cast<ConstantSDNode>( 6250 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6251 if (BaseOpcode->Atomic) 6252 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6253 if (CPol & ~AMDGPU::CPol::ALL) 6254 return Op; 6255 6256 SmallVector<SDValue, 26> Ops; 6257 if (BaseOpcode->Store || BaseOpcode->Atomic) 6258 Ops.push_back(VData); // vdata 6259 if (UseNSA) 6260 append_range(Ops, VAddrs); 6261 else 6262 Ops.push_back(VAddr); 6263 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6264 if (BaseOpcode->Sampler) 6265 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6266 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6267 if (IsGFX10Plus) 6268 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6269 Ops.push_back(Unorm); 6270 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6271 Ops.push_back(IsA16 && // r128, a16 for gfx9 6272 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6273 if (IsGFX10Plus) 6274 Ops.push_back(IsA16 ? True : False); 6275 if (!Subtarget->hasGFX90AInsts()) { 6276 Ops.push_back(TFE); //tfe 6277 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6278 report_fatal_error("TFE is not supported on this GPU"); 6279 } 6280 Ops.push_back(LWE); // lwe 6281 if (!IsGFX10Plus) 6282 Ops.push_back(DimInfo->DA ? True : False); 6283 if (BaseOpcode->HasD16) 6284 Ops.push_back(IsD16 ? True : False); 6285 if (isa<MemSDNode>(Op)) 6286 Ops.push_back(Op.getOperand(0)); // chain 6287 6288 int NumVAddrDwords = 6289 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6290 int Opcode = -1; 6291 6292 if (IsGFX10Plus) { 6293 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6294 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6295 : AMDGPU::MIMGEncGfx10Default, 6296 NumVDataDwords, NumVAddrDwords); 6297 } else { 6298 if (Subtarget->hasGFX90AInsts()) { 6299 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6300 NumVDataDwords, NumVAddrDwords); 6301 if (Opcode == -1) 6302 report_fatal_error( 6303 "requested image instruction is not supported on this GPU"); 6304 } 6305 if (Opcode == -1 && 6306 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6307 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6308 NumVDataDwords, NumVAddrDwords); 6309 if (Opcode == -1) 6310 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6311 NumVDataDwords, NumVAddrDwords); 6312 } 6313 assert(Opcode != -1); 6314 6315 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6316 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6317 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6318 DAG.setNodeMemRefs(NewNode, {MemRef}); 6319 } 6320 6321 if (BaseOpcode->AtomicX2) { 6322 SmallVector<SDValue, 1> Elt; 6323 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6324 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6325 } 6326 if (BaseOpcode->Store) 6327 return SDValue(NewNode, 0); 6328 return constructRetValue(DAG, NewNode, 6329 OrigResultTypes, IsTexFail, 6330 Subtarget->hasUnpackedD16VMem(), IsD16, 6331 DMaskLanes, NumVDataDwords, DL); 6332 } 6333 6334 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6335 SDValue Offset, SDValue CachePolicy, 6336 SelectionDAG &DAG) const { 6337 MachineFunction &MF = DAG.getMachineFunction(); 6338 6339 const DataLayout &DataLayout = DAG.getDataLayout(); 6340 Align Alignment = 6341 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6342 6343 MachineMemOperand *MMO = MF.getMachineMemOperand( 6344 MachinePointerInfo(), 6345 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6346 MachineMemOperand::MOInvariant, 6347 VT.getStoreSize(), Alignment); 6348 6349 if (!Offset->isDivergent()) { 6350 SDValue Ops[] = { 6351 Rsrc, 6352 Offset, // Offset 6353 CachePolicy 6354 }; 6355 6356 // Widen vec3 load to vec4. 6357 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6358 EVT WidenedVT = 6359 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6360 auto WidenedOp = DAG.getMemIntrinsicNode( 6361 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6362 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6363 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6364 DAG.getVectorIdxConstant(0, DL)); 6365 return Subvector; 6366 } 6367 6368 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6369 DAG.getVTList(VT), Ops, VT, MMO); 6370 } 6371 6372 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6373 // assume that the buffer is unswizzled. 6374 SmallVector<SDValue, 4> Loads; 6375 unsigned NumLoads = 1; 6376 MVT LoadVT = VT.getSimpleVT(); 6377 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6378 assert((LoadVT.getScalarType() == MVT::i32 || 6379 LoadVT.getScalarType() == MVT::f32)); 6380 6381 if (NumElts == 8 || NumElts == 16) { 6382 NumLoads = NumElts / 4; 6383 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6384 } 6385 6386 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6387 SDValue Ops[] = { 6388 DAG.getEntryNode(), // Chain 6389 Rsrc, // rsrc 6390 DAG.getConstant(0, DL, MVT::i32), // vindex 6391 {}, // voffset 6392 {}, // soffset 6393 {}, // offset 6394 CachePolicy, // cachepolicy 6395 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6396 }; 6397 6398 // Use the alignment to ensure that the required offsets will fit into the 6399 // immediate offsets. 6400 setBufferOffsets(Offset, DAG, &Ops[3], 6401 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6402 6403 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6404 for (unsigned i = 0; i < NumLoads; ++i) { 6405 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6406 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6407 LoadVT, MMO, DAG)); 6408 } 6409 6410 if (NumElts == 8 || NumElts == 16) 6411 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6412 6413 return Loads[0]; 6414 } 6415 6416 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6417 SelectionDAG &DAG) const { 6418 MachineFunction &MF = DAG.getMachineFunction(); 6419 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6420 6421 EVT VT = Op.getValueType(); 6422 SDLoc DL(Op); 6423 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6424 6425 // TODO: Should this propagate fast-math-flags? 6426 6427 switch (IntrinsicID) { 6428 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6429 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6430 return emitNonHSAIntrinsicError(DAG, DL, VT); 6431 return getPreloadedValue(DAG, *MFI, VT, 6432 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6433 } 6434 case Intrinsic::amdgcn_dispatch_ptr: 6435 case Intrinsic::amdgcn_queue_ptr: { 6436 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6437 DiagnosticInfoUnsupported BadIntrin( 6438 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6439 DL.getDebugLoc()); 6440 DAG.getContext()->diagnose(BadIntrin); 6441 return DAG.getUNDEF(VT); 6442 } 6443 6444 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6445 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6446 return getPreloadedValue(DAG, *MFI, VT, RegID); 6447 } 6448 case Intrinsic::amdgcn_implicitarg_ptr: { 6449 if (MFI->isEntryFunction()) 6450 return getImplicitArgPtr(DAG, DL); 6451 return getPreloadedValue(DAG, *MFI, VT, 6452 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6453 } 6454 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6455 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6456 // This only makes sense to call in a kernel, so just lower to null. 6457 return DAG.getConstant(0, DL, VT); 6458 } 6459 6460 return getPreloadedValue(DAG, *MFI, VT, 6461 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6462 } 6463 case Intrinsic::amdgcn_dispatch_id: { 6464 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6465 } 6466 case Intrinsic::amdgcn_rcp: 6467 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6468 case Intrinsic::amdgcn_rsq: 6469 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6470 case Intrinsic::amdgcn_rsq_legacy: 6471 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6472 return emitRemovedIntrinsicError(DAG, DL, VT); 6473 return SDValue(); 6474 case Intrinsic::amdgcn_rcp_legacy: 6475 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6476 return emitRemovedIntrinsicError(DAG, DL, VT); 6477 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6478 case Intrinsic::amdgcn_rsq_clamp: { 6479 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6480 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6481 6482 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6483 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6484 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6485 6486 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6487 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6488 DAG.getConstantFP(Max, DL, VT)); 6489 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6490 DAG.getConstantFP(Min, DL, VT)); 6491 } 6492 case Intrinsic::r600_read_ngroups_x: 6493 if (Subtarget->isAmdHsaOS()) 6494 return emitNonHSAIntrinsicError(DAG, DL, VT); 6495 6496 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6497 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6498 false); 6499 case Intrinsic::r600_read_ngroups_y: 6500 if (Subtarget->isAmdHsaOS()) 6501 return emitNonHSAIntrinsicError(DAG, DL, VT); 6502 6503 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6504 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6505 false); 6506 case Intrinsic::r600_read_ngroups_z: 6507 if (Subtarget->isAmdHsaOS()) 6508 return emitNonHSAIntrinsicError(DAG, DL, VT); 6509 6510 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6511 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6512 false); 6513 case Intrinsic::r600_read_global_size_x: 6514 if (Subtarget->isAmdHsaOS()) 6515 return emitNonHSAIntrinsicError(DAG, DL, VT); 6516 6517 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6518 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6519 Align(4), false); 6520 case Intrinsic::r600_read_global_size_y: 6521 if (Subtarget->isAmdHsaOS()) 6522 return emitNonHSAIntrinsicError(DAG, DL, VT); 6523 6524 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6525 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6526 Align(4), false); 6527 case Intrinsic::r600_read_global_size_z: 6528 if (Subtarget->isAmdHsaOS()) 6529 return emitNonHSAIntrinsicError(DAG, DL, VT); 6530 6531 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6532 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6533 Align(4), false); 6534 case Intrinsic::r600_read_local_size_x: 6535 if (Subtarget->isAmdHsaOS()) 6536 return emitNonHSAIntrinsicError(DAG, DL, VT); 6537 6538 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6539 SI::KernelInputOffsets::LOCAL_SIZE_X); 6540 case Intrinsic::r600_read_local_size_y: 6541 if (Subtarget->isAmdHsaOS()) 6542 return emitNonHSAIntrinsicError(DAG, DL, VT); 6543 6544 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6545 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6546 case Intrinsic::r600_read_local_size_z: 6547 if (Subtarget->isAmdHsaOS()) 6548 return emitNonHSAIntrinsicError(DAG, DL, VT); 6549 6550 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6551 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6552 case Intrinsic::amdgcn_workgroup_id_x: 6553 return getPreloadedValue(DAG, *MFI, VT, 6554 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6555 case Intrinsic::amdgcn_workgroup_id_y: 6556 return getPreloadedValue(DAG, *MFI, VT, 6557 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6558 case Intrinsic::amdgcn_workgroup_id_z: 6559 return getPreloadedValue(DAG, *MFI, VT, 6560 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6561 case Intrinsic::amdgcn_workitem_id_x: 6562 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6563 SDLoc(DAG.getEntryNode()), 6564 MFI->getArgInfo().WorkItemIDX); 6565 case Intrinsic::amdgcn_workitem_id_y: 6566 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6567 SDLoc(DAG.getEntryNode()), 6568 MFI->getArgInfo().WorkItemIDY); 6569 case Intrinsic::amdgcn_workitem_id_z: 6570 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6571 SDLoc(DAG.getEntryNode()), 6572 MFI->getArgInfo().WorkItemIDZ); 6573 case Intrinsic::amdgcn_wavefrontsize: 6574 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6575 SDLoc(Op), MVT::i32); 6576 case Intrinsic::amdgcn_s_buffer_load: { 6577 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6578 if (CPol & ~AMDGPU::CPol::ALL) 6579 return Op; 6580 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6581 DAG); 6582 } 6583 case Intrinsic::amdgcn_fdiv_fast: 6584 return lowerFDIV_FAST(Op, DAG); 6585 case Intrinsic::amdgcn_sin: 6586 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6587 6588 case Intrinsic::amdgcn_cos: 6589 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6590 6591 case Intrinsic::amdgcn_mul_u24: 6592 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6593 case Intrinsic::amdgcn_mul_i24: 6594 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6595 6596 case Intrinsic::amdgcn_log_clamp: { 6597 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6598 return SDValue(); 6599 6600 return emitRemovedIntrinsicError(DAG, DL, VT); 6601 } 6602 case Intrinsic::amdgcn_ldexp: 6603 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6604 Op.getOperand(1), Op.getOperand(2)); 6605 6606 case Intrinsic::amdgcn_fract: 6607 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6608 6609 case Intrinsic::amdgcn_class: 6610 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6611 Op.getOperand(1), Op.getOperand(2)); 6612 case Intrinsic::amdgcn_div_fmas: 6613 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6614 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6615 Op.getOperand(4)); 6616 6617 case Intrinsic::amdgcn_div_fixup: 6618 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6619 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6620 6621 case Intrinsic::amdgcn_div_scale: { 6622 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6623 6624 // Translate to the operands expected by the machine instruction. The 6625 // first parameter must be the same as the first instruction. 6626 SDValue Numerator = Op.getOperand(1); 6627 SDValue Denominator = Op.getOperand(2); 6628 6629 // Note this order is opposite of the machine instruction's operations, 6630 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6631 // intrinsic has the numerator as the first operand to match a normal 6632 // division operation. 6633 6634 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6635 6636 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6637 Denominator, Numerator); 6638 } 6639 case Intrinsic::amdgcn_icmp: { 6640 // There is a Pat that handles this variant, so return it as-is. 6641 if (Op.getOperand(1).getValueType() == MVT::i1 && 6642 Op.getConstantOperandVal(2) == 0 && 6643 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6644 return Op; 6645 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6646 } 6647 case Intrinsic::amdgcn_fcmp: { 6648 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6649 } 6650 case Intrinsic::amdgcn_ballot: 6651 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6652 case Intrinsic::amdgcn_fmed3: 6653 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6654 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6655 case Intrinsic::amdgcn_fdot2: 6656 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6657 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6658 Op.getOperand(4)); 6659 case Intrinsic::amdgcn_fmul_legacy: 6660 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6661 Op.getOperand(1), Op.getOperand(2)); 6662 case Intrinsic::amdgcn_sffbh: 6663 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6664 case Intrinsic::amdgcn_sbfe: 6665 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6666 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6667 case Intrinsic::amdgcn_ubfe: 6668 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6669 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6670 case Intrinsic::amdgcn_cvt_pkrtz: 6671 case Intrinsic::amdgcn_cvt_pknorm_i16: 6672 case Intrinsic::amdgcn_cvt_pknorm_u16: 6673 case Intrinsic::amdgcn_cvt_pk_i16: 6674 case Intrinsic::amdgcn_cvt_pk_u16: { 6675 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6676 EVT VT = Op.getValueType(); 6677 unsigned Opcode; 6678 6679 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6680 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6681 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6682 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6683 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6684 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6685 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6686 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6687 else 6688 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6689 6690 if (isTypeLegal(VT)) 6691 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6692 6693 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6694 Op.getOperand(1), Op.getOperand(2)); 6695 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6696 } 6697 case Intrinsic::amdgcn_fmad_ftz: 6698 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6699 Op.getOperand(2), Op.getOperand(3)); 6700 6701 case Intrinsic::amdgcn_if_break: 6702 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6703 Op->getOperand(1), Op->getOperand(2)), 0); 6704 6705 case Intrinsic::amdgcn_groupstaticsize: { 6706 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6707 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6708 return Op; 6709 6710 const Module *M = MF.getFunction().getParent(); 6711 const GlobalValue *GV = 6712 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6713 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6714 SIInstrInfo::MO_ABS32_LO); 6715 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6716 } 6717 case Intrinsic::amdgcn_is_shared: 6718 case Intrinsic::amdgcn_is_private: { 6719 SDLoc SL(Op); 6720 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6721 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6722 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6723 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6724 Op.getOperand(1)); 6725 6726 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6727 DAG.getConstant(1, SL, MVT::i32)); 6728 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6729 } 6730 case Intrinsic::amdgcn_alignbit: 6731 return DAG.getNode(ISD::FSHR, DL, VT, 6732 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6733 case Intrinsic::amdgcn_perm: 6734 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1), 6735 Op.getOperand(2), Op.getOperand(3)); 6736 case Intrinsic::amdgcn_reloc_constant: { 6737 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6738 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6739 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6740 auto RelocSymbol = cast<GlobalVariable>( 6741 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6742 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6743 SIInstrInfo::MO_ABS32_LO); 6744 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6745 } 6746 default: 6747 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6748 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6749 return lowerImage(Op, ImageDimIntr, DAG, false); 6750 6751 return Op; 6752 } 6753 } 6754 6755 // This function computes an appropriate offset to pass to 6756 // MachineMemOperand::setOffset() based on the offset inputs to 6757 // an intrinsic. If any of the offsets are non-contstant or 6758 // if VIndex is non-zero then this function returns 0. Otherwise, 6759 // it returns the sum of VOffset, SOffset, and Offset. 6760 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6761 SDValue SOffset, 6762 SDValue Offset, 6763 SDValue VIndex = SDValue()) { 6764 6765 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6766 !isa<ConstantSDNode>(Offset)) 6767 return 0; 6768 6769 if (VIndex) { 6770 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6771 return 0; 6772 } 6773 6774 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6775 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6776 cast<ConstantSDNode>(Offset)->getSExtValue(); 6777 } 6778 6779 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6780 SelectionDAG &DAG, 6781 unsigned NewOpcode) const { 6782 SDLoc DL(Op); 6783 6784 SDValue VData = Op.getOperand(2); 6785 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6786 SDValue Ops[] = { 6787 Op.getOperand(0), // Chain 6788 VData, // vdata 6789 Op.getOperand(3), // rsrc 6790 DAG.getConstant(0, DL, MVT::i32), // vindex 6791 Offsets.first, // voffset 6792 Op.getOperand(5), // soffset 6793 Offsets.second, // offset 6794 Op.getOperand(6), // cachepolicy 6795 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6796 }; 6797 6798 auto *M = cast<MemSDNode>(Op); 6799 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6800 6801 EVT MemVT = VData.getValueType(); 6802 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6803 M->getMemOperand()); 6804 } 6805 6806 SDValue 6807 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6808 unsigned NewOpcode) const { 6809 SDLoc DL(Op); 6810 6811 SDValue VData = Op.getOperand(2); 6812 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6813 SDValue Ops[] = { 6814 Op.getOperand(0), // Chain 6815 VData, // vdata 6816 Op.getOperand(3), // rsrc 6817 Op.getOperand(4), // vindex 6818 Offsets.first, // voffset 6819 Op.getOperand(6), // soffset 6820 Offsets.second, // offset 6821 Op.getOperand(7), // cachepolicy 6822 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6823 }; 6824 6825 auto *M = cast<MemSDNode>(Op); 6826 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6827 Ops[3])); 6828 6829 EVT MemVT = VData.getValueType(); 6830 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6831 M->getMemOperand()); 6832 } 6833 6834 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6835 SelectionDAG &DAG) const { 6836 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6837 SDLoc DL(Op); 6838 6839 switch (IntrID) { 6840 case Intrinsic::amdgcn_ds_ordered_add: 6841 case Intrinsic::amdgcn_ds_ordered_swap: { 6842 MemSDNode *M = cast<MemSDNode>(Op); 6843 SDValue Chain = M->getOperand(0); 6844 SDValue M0 = M->getOperand(2); 6845 SDValue Value = M->getOperand(3); 6846 unsigned IndexOperand = M->getConstantOperandVal(7); 6847 unsigned WaveRelease = M->getConstantOperandVal(8); 6848 unsigned WaveDone = M->getConstantOperandVal(9); 6849 6850 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6851 IndexOperand &= ~0x3f; 6852 unsigned CountDw = 0; 6853 6854 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6855 CountDw = (IndexOperand >> 24) & 0xf; 6856 IndexOperand &= ~(0xf << 24); 6857 6858 if (CountDw < 1 || CountDw > 4) { 6859 report_fatal_error( 6860 "ds_ordered_count: dword count must be between 1 and 4"); 6861 } 6862 } 6863 6864 if (IndexOperand) 6865 report_fatal_error("ds_ordered_count: bad index operand"); 6866 6867 if (WaveDone && !WaveRelease) 6868 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6869 6870 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6871 unsigned ShaderType = 6872 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6873 unsigned Offset0 = OrderedCountIndex << 2; 6874 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6875 (Instruction << 4); 6876 6877 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6878 Offset1 |= (CountDw - 1) << 6; 6879 6880 unsigned Offset = Offset0 | (Offset1 << 8); 6881 6882 SDValue Ops[] = { 6883 Chain, 6884 Value, 6885 DAG.getTargetConstant(Offset, DL, MVT::i16), 6886 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6887 }; 6888 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6889 M->getVTList(), Ops, M->getMemoryVT(), 6890 M->getMemOperand()); 6891 } 6892 case Intrinsic::amdgcn_ds_fadd: { 6893 MemSDNode *M = cast<MemSDNode>(Op); 6894 unsigned Opc; 6895 switch (IntrID) { 6896 case Intrinsic::amdgcn_ds_fadd: 6897 Opc = ISD::ATOMIC_LOAD_FADD; 6898 break; 6899 } 6900 6901 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6902 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6903 M->getMemOperand()); 6904 } 6905 case Intrinsic::amdgcn_atomic_inc: 6906 case Intrinsic::amdgcn_atomic_dec: 6907 case Intrinsic::amdgcn_ds_fmin: 6908 case Intrinsic::amdgcn_ds_fmax: { 6909 MemSDNode *M = cast<MemSDNode>(Op); 6910 unsigned Opc; 6911 switch (IntrID) { 6912 case Intrinsic::amdgcn_atomic_inc: 6913 Opc = AMDGPUISD::ATOMIC_INC; 6914 break; 6915 case Intrinsic::amdgcn_atomic_dec: 6916 Opc = AMDGPUISD::ATOMIC_DEC; 6917 break; 6918 case Intrinsic::amdgcn_ds_fmin: 6919 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6920 break; 6921 case Intrinsic::amdgcn_ds_fmax: 6922 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6923 break; 6924 default: 6925 llvm_unreachable("Unknown intrinsic!"); 6926 } 6927 SDValue Ops[] = { 6928 M->getOperand(0), // Chain 6929 M->getOperand(2), // Ptr 6930 M->getOperand(3) // Value 6931 }; 6932 6933 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6934 M->getMemoryVT(), M->getMemOperand()); 6935 } 6936 case Intrinsic::amdgcn_buffer_load: 6937 case Intrinsic::amdgcn_buffer_load_format: { 6938 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6939 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6940 unsigned IdxEn = 1; 6941 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6942 IdxEn = Idx->getZExtValue() != 0; 6943 SDValue Ops[] = { 6944 Op.getOperand(0), // Chain 6945 Op.getOperand(2), // rsrc 6946 Op.getOperand(3), // vindex 6947 SDValue(), // voffset -- will be set by setBufferOffsets 6948 SDValue(), // soffset -- will be set by setBufferOffsets 6949 SDValue(), // offset -- will be set by setBufferOffsets 6950 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6951 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6952 }; 6953 6954 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6955 // We don't know the offset if vindex is non-zero, so clear it. 6956 if (IdxEn) 6957 Offset = 0; 6958 6959 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6960 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6961 6962 EVT VT = Op.getValueType(); 6963 EVT IntVT = VT.changeTypeToInteger(); 6964 auto *M = cast<MemSDNode>(Op); 6965 M->getMemOperand()->setOffset(Offset); 6966 EVT LoadVT = Op.getValueType(); 6967 6968 if (LoadVT.getScalarType() == MVT::f16) 6969 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6970 M, DAG, Ops); 6971 6972 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6973 if (LoadVT.getScalarType() == MVT::i8 || 6974 LoadVT.getScalarType() == MVT::i16) 6975 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6976 6977 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6978 M->getMemOperand(), DAG); 6979 } 6980 case Intrinsic::amdgcn_raw_buffer_load: 6981 case Intrinsic::amdgcn_raw_buffer_load_format: { 6982 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6983 6984 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6985 SDValue Ops[] = { 6986 Op.getOperand(0), // Chain 6987 Op.getOperand(2), // rsrc 6988 DAG.getConstant(0, DL, MVT::i32), // vindex 6989 Offsets.first, // voffset 6990 Op.getOperand(4), // soffset 6991 Offsets.second, // offset 6992 Op.getOperand(5), // cachepolicy, swizzled buffer 6993 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6994 }; 6995 6996 auto *M = cast<MemSDNode>(Op); 6997 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6998 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6999 } 7000 case Intrinsic::amdgcn_struct_buffer_load: 7001 case Intrinsic::amdgcn_struct_buffer_load_format: { 7002 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7003 7004 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7005 SDValue Ops[] = { 7006 Op.getOperand(0), // Chain 7007 Op.getOperand(2), // rsrc 7008 Op.getOperand(3), // vindex 7009 Offsets.first, // voffset 7010 Op.getOperand(5), // soffset 7011 Offsets.second, // offset 7012 Op.getOperand(6), // cachepolicy, swizzled buffer 7013 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7014 }; 7015 7016 auto *M = cast<MemSDNode>(Op); 7017 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 7018 Ops[2])); 7019 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7020 } 7021 case Intrinsic::amdgcn_tbuffer_load: { 7022 MemSDNode *M = cast<MemSDNode>(Op); 7023 EVT LoadVT = Op.getValueType(); 7024 7025 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7026 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7027 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7028 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7029 unsigned IdxEn = 1; 7030 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 7031 IdxEn = Idx->getZExtValue() != 0; 7032 SDValue Ops[] = { 7033 Op.getOperand(0), // Chain 7034 Op.getOperand(2), // rsrc 7035 Op.getOperand(3), // vindex 7036 Op.getOperand(4), // voffset 7037 Op.getOperand(5), // soffset 7038 Op.getOperand(6), // offset 7039 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7040 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7041 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7042 }; 7043 7044 if (LoadVT.getScalarType() == MVT::f16) 7045 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7046 M, DAG, Ops); 7047 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7048 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7049 DAG); 7050 } 7051 case Intrinsic::amdgcn_raw_tbuffer_load: { 7052 MemSDNode *M = cast<MemSDNode>(Op); 7053 EVT LoadVT = Op.getValueType(); 7054 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7055 7056 SDValue Ops[] = { 7057 Op.getOperand(0), // Chain 7058 Op.getOperand(2), // rsrc 7059 DAG.getConstant(0, DL, MVT::i32), // vindex 7060 Offsets.first, // voffset 7061 Op.getOperand(4), // soffset 7062 Offsets.second, // offset 7063 Op.getOperand(5), // format 7064 Op.getOperand(6), // cachepolicy, swizzled buffer 7065 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7066 }; 7067 7068 if (LoadVT.getScalarType() == MVT::f16) 7069 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7070 M, DAG, Ops); 7071 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7072 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7073 DAG); 7074 } 7075 case Intrinsic::amdgcn_struct_tbuffer_load: { 7076 MemSDNode *M = cast<MemSDNode>(Op); 7077 EVT LoadVT = Op.getValueType(); 7078 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7079 7080 SDValue Ops[] = { 7081 Op.getOperand(0), // Chain 7082 Op.getOperand(2), // rsrc 7083 Op.getOperand(3), // vindex 7084 Offsets.first, // voffset 7085 Op.getOperand(5), // soffset 7086 Offsets.second, // offset 7087 Op.getOperand(6), // format 7088 Op.getOperand(7), // cachepolicy, swizzled buffer 7089 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7090 }; 7091 7092 if (LoadVT.getScalarType() == MVT::f16) 7093 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7094 M, DAG, Ops); 7095 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7096 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7097 DAG); 7098 } 7099 case Intrinsic::amdgcn_buffer_atomic_swap: 7100 case Intrinsic::amdgcn_buffer_atomic_add: 7101 case Intrinsic::amdgcn_buffer_atomic_sub: 7102 case Intrinsic::amdgcn_buffer_atomic_csub: 7103 case Intrinsic::amdgcn_buffer_atomic_smin: 7104 case Intrinsic::amdgcn_buffer_atomic_umin: 7105 case Intrinsic::amdgcn_buffer_atomic_smax: 7106 case Intrinsic::amdgcn_buffer_atomic_umax: 7107 case Intrinsic::amdgcn_buffer_atomic_and: 7108 case Intrinsic::amdgcn_buffer_atomic_or: 7109 case Intrinsic::amdgcn_buffer_atomic_xor: 7110 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7111 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7112 unsigned IdxEn = 1; 7113 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7114 IdxEn = Idx->getZExtValue() != 0; 7115 SDValue Ops[] = { 7116 Op.getOperand(0), // Chain 7117 Op.getOperand(2), // vdata 7118 Op.getOperand(3), // rsrc 7119 Op.getOperand(4), // vindex 7120 SDValue(), // voffset -- will be set by setBufferOffsets 7121 SDValue(), // soffset -- will be set by setBufferOffsets 7122 SDValue(), // offset -- will be set by setBufferOffsets 7123 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7124 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7125 }; 7126 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7127 // We don't know the offset if vindex is non-zero, so clear it. 7128 if (IdxEn) 7129 Offset = 0; 7130 EVT VT = Op.getValueType(); 7131 7132 auto *M = cast<MemSDNode>(Op); 7133 M->getMemOperand()->setOffset(Offset); 7134 unsigned Opcode = 0; 7135 7136 switch (IntrID) { 7137 case Intrinsic::amdgcn_buffer_atomic_swap: 7138 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7139 break; 7140 case Intrinsic::amdgcn_buffer_atomic_add: 7141 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7142 break; 7143 case Intrinsic::amdgcn_buffer_atomic_sub: 7144 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7145 break; 7146 case Intrinsic::amdgcn_buffer_atomic_csub: 7147 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7148 break; 7149 case Intrinsic::amdgcn_buffer_atomic_smin: 7150 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7151 break; 7152 case Intrinsic::amdgcn_buffer_atomic_umin: 7153 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7154 break; 7155 case Intrinsic::amdgcn_buffer_atomic_smax: 7156 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7157 break; 7158 case Intrinsic::amdgcn_buffer_atomic_umax: 7159 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7160 break; 7161 case Intrinsic::amdgcn_buffer_atomic_and: 7162 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7163 break; 7164 case Intrinsic::amdgcn_buffer_atomic_or: 7165 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7166 break; 7167 case Intrinsic::amdgcn_buffer_atomic_xor: 7168 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7169 break; 7170 case Intrinsic::amdgcn_buffer_atomic_fadd: 7171 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7172 DiagnosticInfoUnsupported 7173 NoFpRet(DAG.getMachineFunction().getFunction(), 7174 "return versions of fp atomics not supported", 7175 DL.getDebugLoc(), DS_Error); 7176 DAG.getContext()->diagnose(NoFpRet); 7177 return SDValue(); 7178 } 7179 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7180 break; 7181 default: 7182 llvm_unreachable("unhandled atomic opcode"); 7183 } 7184 7185 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7186 M->getMemOperand()); 7187 } 7188 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7189 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7190 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7191 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7192 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7193 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7194 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7195 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7196 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7197 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7198 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7199 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7200 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7201 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7202 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7203 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7204 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7205 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7206 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7207 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7208 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7209 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7210 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7211 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7212 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7213 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7214 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7215 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7216 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7217 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7218 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7219 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7220 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7221 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7222 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7223 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7224 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7225 return lowerStructBufferAtomicIntrin(Op, DAG, 7226 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7227 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7228 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7229 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7230 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7231 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7232 return lowerStructBufferAtomicIntrin(Op, DAG, 7233 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7234 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7235 return lowerStructBufferAtomicIntrin(Op, DAG, 7236 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7237 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7238 return lowerStructBufferAtomicIntrin(Op, DAG, 7239 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7240 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7241 return lowerStructBufferAtomicIntrin(Op, DAG, 7242 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7243 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7244 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7245 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7246 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7247 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7248 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7249 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7250 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7251 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7252 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7253 7254 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7255 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7256 unsigned IdxEn = 1; 7257 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7258 IdxEn = Idx->getZExtValue() != 0; 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 SDValue(), // voffset -- will be set by setBufferOffsets 7266 SDValue(), // soffset -- will be set by setBufferOffsets 7267 SDValue(), // offset -- will be set by setBufferOffsets 7268 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7269 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7270 }; 7271 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7272 // We don't know the offset if vindex is non-zero, so clear it. 7273 if (IdxEn) 7274 Offset = 0; 7275 EVT VT = Op.getValueType(); 7276 auto *M = cast<MemSDNode>(Op); 7277 M->getMemOperand()->setOffset(Offset); 7278 7279 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7280 Op->getVTList(), Ops, VT, M->getMemOperand()); 7281 } 7282 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7283 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7284 SDValue Ops[] = { 7285 Op.getOperand(0), // Chain 7286 Op.getOperand(2), // src 7287 Op.getOperand(3), // cmp 7288 Op.getOperand(4), // rsrc 7289 DAG.getConstant(0, DL, MVT::i32), // vindex 7290 Offsets.first, // voffset 7291 Op.getOperand(6), // soffset 7292 Offsets.second, // offset 7293 Op.getOperand(7), // cachepolicy 7294 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7295 }; 7296 EVT VT = Op.getValueType(); 7297 auto *M = cast<MemSDNode>(Op); 7298 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7299 7300 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7301 Op->getVTList(), Ops, VT, M->getMemOperand()); 7302 } 7303 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7304 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7305 SDValue Ops[] = { 7306 Op.getOperand(0), // Chain 7307 Op.getOperand(2), // src 7308 Op.getOperand(3), // cmp 7309 Op.getOperand(4), // rsrc 7310 Op.getOperand(5), // vindex 7311 Offsets.first, // voffset 7312 Op.getOperand(7), // soffset 7313 Offsets.second, // offset 7314 Op.getOperand(8), // cachepolicy 7315 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7316 }; 7317 EVT VT = Op.getValueType(); 7318 auto *M = cast<MemSDNode>(Op); 7319 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7320 Ops[4])); 7321 7322 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7323 Op->getVTList(), Ops, VT, M->getMemOperand()); 7324 } 7325 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7326 SDLoc DL(Op); 7327 MemSDNode *M = cast<MemSDNode>(Op); 7328 SDValue NodePtr = M->getOperand(2); 7329 SDValue RayExtent = M->getOperand(3); 7330 SDValue RayOrigin = M->getOperand(4); 7331 SDValue RayDir = M->getOperand(5); 7332 SDValue RayInvDir = M->getOperand(6); 7333 SDValue TDescr = M->getOperand(7); 7334 7335 assert(NodePtr.getValueType() == MVT::i32 || 7336 NodePtr.getValueType() == MVT::i64); 7337 assert(RayDir.getValueType() == MVT::v4f16 || 7338 RayDir.getValueType() == MVT::v4f32); 7339 7340 bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7341 bool Is64 = NodePtr.getValueType() == MVT::i64; 7342 unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa 7343 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa 7344 : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa 7345 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa; 7346 7347 SmallVector<SDValue, 16> Ops; 7348 7349 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7350 SmallVector<SDValue, 3> Lanes; 7351 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7352 if (Lanes[0].getValueSizeInBits() == 32) { 7353 for (unsigned I = 0; I < 3; ++I) 7354 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7355 } else { 7356 if (IsAligned) { 7357 Ops.push_back( 7358 DAG.getBitcast(MVT::i32, 7359 DAG.getBuildVector(MVT::v2f16, DL, 7360 { Lanes[0], Lanes[1] }))); 7361 Ops.push_back(Lanes[2]); 7362 } else { 7363 SDValue Elt0 = Ops.pop_back_val(); 7364 Ops.push_back( 7365 DAG.getBitcast(MVT::i32, 7366 DAG.getBuildVector(MVT::v2f16, DL, 7367 { Elt0, Lanes[0] }))); 7368 Ops.push_back( 7369 DAG.getBitcast(MVT::i32, 7370 DAG.getBuildVector(MVT::v2f16, DL, 7371 { Lanes[1], Lanes[2] }))); 7372 } 7373 } 7374 }; 7375 7376 if (Is64) 7377 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7378 else 7379 Ops.push_back(NodePtr); 7380 7381 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7382 packLanes(RayOrigin, true); 7383 packLanes(RayDir, true); 7384 packLanes(RayInvDir, false); 7385 Ops.push_back(TDescr); 7386 if (IsA16) 7387 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7388 Ops.push_back(M->getChain()); 7389 7390 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7391 MachineMemOperand *MemRef = M->getMemOperand(); 7392 DAG.setNodeMemRefs(NewNode, {MemRef}); 7393 return SDValue(NewNode, 0); 7394 } 7395 case Intrinsic::amdgcn_global_atomic_fadd: 7396 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7397 DiagnosticInfoUnsupported 7398 NoFpRet(DAG.getMachineFunction().getFunction(), 7399 "return versions of fp atomics not supported", 7400 DL.getDebugLoc(), DS_Error); 7401 DAG.getContext()->diagnose(NoFpRet); 7402 return SDValue(); 7403 } 7404 LLVM_FALLTHROUGH; 7405 case Intrinsic::amdgcn_global_atomic_fmin: 7406 case Intrinsic::amdgcn_global_atomic_fmax: 7407 case Intrinsic::amdgcn_flat_atomic_fadd: 7408 case Intrinsic::amdgcn_flat_atomic_fmin: 7409 case Intrinsic::amdgcn_flat_atomic_fmax: { 7410 MemSDNode *M = cast<MemSDNode>(Op); 7411 SDValue Ops[] = { 7412 M->getOperand(0), // Chain 7413 M->getOperand(2), // Ptr 7414 M->getOperand(3) // Value 7415 }; 7416 unsigned Opcode = 0; 7417 switch (IntrID) { 7418 case Intrinsic::amdgcn_global_atomic_fadd: 7419 case Intrinsic::amdgcn_flat_atomic_fadd: { 7420 EVT VT = Op.getOperand(3).getValueType(); 7421 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7422 DAG.getVTList(VT, MVT::Other), Ops, 7423 M->getMemOperand()); 7424 } 7425 case Intrinsic::amdgcn_global_atomic_fmin: 7426 case Intrinsic::amdgcn_flat_atomic_fmin: { 7427 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7428 break; 7429 } 7430 case Intrinsic::amdgcn_global_atomic_fmax: 7431 case Intrinsic::amdgcn_flat_atomic_fmax: { 7432 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7433 break; 7434 } 7435 default: 7436 llvm_unreachable("unhandled atomic opcode"); 7437 } 7438 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7439 M->getVTList(), Ops, M->getMemoryVT(), 7440 M->getMemOperand()); 7441 } 7442 default: 7443 7444 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7445 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7446 return lowerImage(Op, ImageDimIntr, DAG, true); 7447 7448 return SDValue(); 7449 } 7450 } 7451 7452 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7453 // dwordx4 if on SI. 7454 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7455 SDVTList VTList, 7456 ArrayRef<SDValue> Ops, EVT MemVT, 7457 MachineMemOperand *MMO, 7458 SelectionDAG &DAG) const { 7459 EVT VT = VTList.VTs[0]; 7460 EVT WidenedVT = VT; 7461 EVT WidenedMemVT = MemVT; 7462 if (!Subtarget->hasDwordx3LoadStores() && 7463 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7464 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7465 WidenedVT.getVectorElementType(), 4); 7466 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7467 WidenedMemVT.getVectorElementType(), 4); 7468 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7469 } 7470 7471 assert(VTList.NumVTs == 2); 7472 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7473 7474 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7475 WidenedMemVT, MMO); 7476 if (WidenedVT != VT) { 7477 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7478 DAG.getVectorIdxConstant(0, DL)); 7479 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7480 } 7481 return NewOp; 7482 } 7483 7484 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7485 bool ImageStore) const { 7486 EVT StoreVT = VData.getValueType(); 7487 7488 // No change for f16 and legal vector D16 types. 7489 if (!StoreVT.isVector()) 7490 return VData; 7491 7492 SDLoc DL(VData); 7493 unsigned NumElements = StoreVT.getVectorNumElements(); 7494 7495 if (Subtarget->hasUnpackedD16VMem()) { 7496 // We need to unpack the packed data to store. 7497 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7498 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7499 7500 EVT EquivStoreVT = 7501 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7502 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7503 return DAG.UnrollVectorOp(ZExt.getNode()); 7504 } 7505 7506 // The sq block of gfx8.1 does not estimate register use correctly for d16 7507 // image store instructions. The data operand is computed as if it were not a 7508 // d16 image instruction. 7509 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7510 // Bitcast to i16 7511 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7512 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7513 7514 // Decompose into scalars 7515 SmallVector<SDValue, 4> Elts; 7516 DAG.ExtractVectorElements(IntVData, Elts); 7517 7518 // Group pairs of i16 into v2i16 and bitcast to i32 7519 SmallVector<SDValue, 4> PackedElts; 7520 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7521 SDValue Pair = 7522 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7523 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7524 PackedElts.push_back(IntPair); 7525 } 7526 if ((NumElements % 2) == 1) { 7527 // Handle v3i16 7528 unsigned I = Elts.size() / 2; 7529 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7530 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7531 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7532 PackedElts.push_back(IntPair); 7533 } 7534 7535 // Pad using UNDEF 7536 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7537 7538 // Build final vector 7539 EVT VecVT = 7540 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7541 return DAG.getBuildVector(VecVT, DL, PackedElts); 7542 } 7543 7544 if (NumElements == 3) { 7545 EVT IntStoreVT = 7546 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7547 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7548 7549 EVT WidenedStoreVT = EVT::getVectorVT( 7550 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7551 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7552 WidenedStoreVT.getStoreSizeInBits()); 7553 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7554 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7555 } 7556 7557 assert(isTypeLegal(StoreVT)); 7558 return VData; 7559 } 7560 7561 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7562 SelectionDAG &DAG) const { 7563 SDLoc DL(Op); 7564 SDValue Chain = Op.getOperand(0); 7565 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7566 MachineFunction &MF = DAG.getMachineFunction(); 7567 7568 switch (IntrinsicID) { 7569 case Intrinsic::amdgcn_exp_compr: { 7570 SDValue Src0 = Op.getOperand(4); 7571 SDValue Src1 = Op.getOperand(5); 7572 // Hack around illegal type on SI by directly selecting it. 7573 if (isTypeLegal(Src0.getValueType())) 7574 return SDValue(); 7575 7576 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7577 SDValue Undef = DAG.getUNDEF(MVT::f32); 7578 const SDValue Ops[] = { 7579 Op.getOperand(2), // tgt 7580 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7581 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7582 Undef, // src2 7583 Undef, // src3 7584 Op.getOperand(7), // vm 7585 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7586 Op.getOperand(3), // en 7587 Op.getOperand(0) // Chain 7588 }; 7589 7590 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7591 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7592 } 7593 case Intrinsic::amdgcn_s_barrier: { 7594 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7595 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7596 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7597 if (WGSize <= ST.getWavefrontSize()) 7598 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7599 Op.getOperand(0)), 0); 7600 } 7601 return SDValue(); 7602 }; 7603 case Intrinsic::amdgcn_tbuffer_store: { 7604 SDValue VData = Op.getOperand(2); 7605 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7606 if (IsD16) 7607 VData = handleD16VData(VData, DAG); 7608 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7609 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7610 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7611 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7612 unsigned IdxEn = 1; 7613 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7614 IdxEn = Idx->getZExtValue() != 0; 7615 SDValue Ops[] = { 7616 Chain, 7617 VData, // vdata 7618 Op.getOperand(3), // rsrc 7619 Op.getOperand(4), // vindex 7620 Op.getOperand(5), // voffset 7621 Op.getOperand(6), // soffset 7622 Op.getOperand(7), // offset 7623 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7624 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7625 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7626 }; 7627 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7628 AMDGPUISD::TBUFFER_STORE_FORMAT; 7629 MemSDNode *M = cast<MemSDNode>(Op); 7630 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7631 M->getMemoryVT(), M->getMemOperand()); 7632 } 7633 7634 case Intrinsic::amdgcn_struct_tbuffer_store: { 7635 SDValue VData = Op.getOperand(2); 7636 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7637 if (IsD16) 7638 VData = handleD16VData(VData, DAG); 7639 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7640 SDValue Ops[] = { 7641 Chain, 7642 VData, // vdata 7643 Op.getOperand(3), // rsrc 7644 Op.getOperand(4), // vindex 7645 Offsets.first, // voffset 7646 Op.getOperand(6), // soffset 7647 Offsets.second, // offset 7648 Op.getOperand(7), // format 7649 Op.getOperand(8), // cachepolicy, swizzled buffer 7650 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7651 }; 7652 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7653 AMDGPUISD::TBUFFER_STORE_FORMAT; 7654 MemSDNode *M = cast<MemSDNode>(Op); 7655 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7656 M->getMemoryVT(), M->getMemOperand()); 7657 } 7658 7659 case Intrinsic::amdgcn_raw_tbuffer_store: { 7660 SDValue VData = Op.getOperand(2); 7661 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7662 if (IsD16) 7663 VData = handleD16VData(VData, DAG); 7664 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7665 SDValue Ops[] = { 7666 Chain, 7667 VData, // vdata 7668 Op.getOperand(3), // rsrc 7669 DAG.getConstant(0, DL, MVT::i32), // vindex 7670 Offsets.first, // voffset 7671 Op.getOperand(5), // soffset 7672 Offsets.second, // offset 7673 Op.getOperand(6), // format 7674 Op.getOperand(7), // cachepolicy, swizzled buffer 7675 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7676 }; 7677 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7678 AMDGPUISD::TBUFFER_STORE_FORMAT; 7679 MemSDNode *M = cast<MemSDNode>(Op); 7680 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7681 M->getMemoryVT(), M->getMemOperand()); 7682 } 7683 7684 case Intrinsic::amdgcn_buffer_store: 7685 case Intrinsic::amdgcn_buffer_store_format: { 7686 SDValue VData = Op.getOperand(2); 7687 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7688 if (IsD16) 7689 VData = handleD16VData(VData, DAG); 7690 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7691 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7692 unsigned IdxEn = 1; 7693 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7694 IdxEn = Idx->getZExtValue() != 0; 7695 SDValue Ops[] = { 7696 Chain, 7697 VData, 7698 Op.getOperand(3), // rsrc 7699 Op.getOperand(4), // vindex 7700 SDValue(), // voffset -- will be set by setBufferOffsets 7701 SDValue(), // soffset -- will be set by setBufferOffsets 7702 SDValue(), // offset -- will be set by setBufferOffsets 7703 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7704 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7705 }; 7706 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7707 // We don't know the offset if vindex is non-zero, so clear it. 7708 if (IdxEn) 7709 Offset = 0; 7710 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7711 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7712 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7713 MemSDNode *M = cast<MemSDNode>(Op); 7714 M->getMemOperand()->setOffset(Offset); 7715 7716 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7717 EVT VDataType = VData.getValueType().getScalarType(); 7718 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7719 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7720 7721 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7722 M->getMemoryVT(), M->getMemOperand()); 7723 } 7724 7725 case Intrinsic::amdgcn_raw_buffer_store: 7726 case Intrinsic::amdgcn_raw_buffer_store_format: { 7727 const bool IsFormat = 7728 IntrinsicID == Intrinsic::amdgcn_raw_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 if (IsD16) { 7735 VData = handleD16VData(VData, DAG); 7736 VDataVT = VData.getValueType(); 7737 } 7738 7739 if (!isTypeLegal(VDataVT)) { 7740 VData = 7741 DAG.getNode(ISD::BITCAST, DL, 7742 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7743 } 7744 7745 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7746 SDValue Ops[] = { 7747 Chain, 7748 VData, 7749 Op.getOperand(3), // rsrc 7750 DAG.getConstant(0, DL, MVT::i32), // vindex 7751 Offsets.first, // voffset 7752 Op.getOperand(5), // soffset 7753 Offsets.second, // offset 7754 Op.getOperand(6), // cachepolicy, swizzled buffer 7755 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7756 }; 7757 unsigned Opc = 7758 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7759 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7760 MemSDNode *M = cast<MemSDNode>(Op); 7761 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7762 7763 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7764 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7765 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7766 7767 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7768 M->getMemoryVT(), M->getMemOperand()); 7769 } 7770 7771 case Intrinsic::amdgcn_struct_buffer_store: 7772 case Intrinsic::amdgcn_struct_buffer_store_format: { 7773 const bool IsFormat = 7774 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7775 7776 SDValue VData = Op.getOperand(2); 7777 EVT VDataVT = VData.getValueType(); 7778 EVT EltType = VDataVT.getScalarType(); 7779 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7780 7781 if (IsD16) { 7782 VData = handleD16VData(VData, DAG); 7783 VDataVT = VData.getValueType(); 7784 } 7785 7786 if (!isTypeLegal(VDataVT)) { 7787 VData = 7788 DAG.getNode(ISD::BITCAST, DL, 7789 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7790 } 7791 7792 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7793 SDValue Ops[] = { 7794 Chain, 7795 VData, 7796 Op.getOperand(3), // rsrc 7797 Op.getOperand(4), // vindex 7798 Offsets.first, // voffset 7799 Op.getOperand(6), // soffset 7800 Offsets.second, // offset 7801 Op.getOperand(7), // cachepolicy, swizzled buffer 7802 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7803 }; 7804 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7805 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7806 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7807 MemSDNode *M = cast<MemSDNode>(Op); 7808 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7809 Ops[3])); 7810 7811 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7812 EVT VDataType = VData.getValueType().getScalarType(); 7813 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7814 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7815 7816 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7817 M->getMemoryVT(), M->getMemOperand()); 7818 } 7819 case Intrinsic::amdgcn_end_cf: 7820 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7821 Op->getOperand(2), Chain), 0); 7822 7823 default: { 7824 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7825 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7826 return lowerImage(Op, ImageDimIntr, DAG, true); 7827 7828 return Op; 7829 } 7830 } 7831 } 7832 7833 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7834 // offset (the offset that is included in bounds checking and swizzling, to be 7835 // split between the instruction's voffset and immoffset fields) and soffset 7836 // (the offset that is excluded from bounds checking and swizzling, to go in 7837 // the instruction's soffset field). This function takes the first kind of 7838 // offset and figures out how to split it between voffset and immoffset. 7839 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7840 SDValue Offset, SelectionDAG &DAG) const { 7841 SDLoc DL(Offset); 7842 const unsigned MaxImm = 4095; 7843 SDValue N0 = Offset; 7844 ConstantSDNode *C1 = nullptr; 7845 7846 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7847 N0 = SDValue(); 7848 else if (DAG.isBaseWithConstantOffset(N0)) { 7849 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7850 N0 = N0.getOperand(0); 7851 } 7852 7853 if (C1) { 7854 unsigned ImmOffset = C1->getZExtValue(); 7855 // If the immediate value is too big for the immoffset field, put the value 7856 // and -4096 into the immoffset field so that the value that is copied/added 7857 // for the voffset field is a multiple of 4096, and it stands more chance 7858 // of being CSEd with the copy/add for another similar load/store. 7859 // However, do not do that rounding down to a multiple of 4096 if that is a 7860 // negative number, as it appears to be illegal to have a negative offset 7861 // in the vgpr, even if adding the immediate offset makes it positive. 7862 unsigned Overflow = ImmOffset & ~MaxImm; 7863 ImmOffset -= Overflow; 7864 if ((int32_t)Overflow < 0) { 7865 Overflow += ImmOffset; 7866 ImmOffset = 0; 7867 } 7868 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7869 if (Overflow) { 7870 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7871 if (!N0) 7872 N0 = OverflowVal; 7873 else { 7874 SDValue Ops[] = { N0, OverflowVal }; 7875 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7876 } 7877 } 7878 } 7879 if (!N0) 7880 N0 = DAG.getConstant(0, DL, MVT::i32); 7881 if (!C1) 7882 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7883 return {N0, SDValue(C1, 0)}; 7884 } 7885 7886 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7887 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7888 // pointed to by Offsets. 7889 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7890 SelectionDAG &DAG, SDValue *Offsets, 7891 Align Alignment) const { 7892 SDLoc DL(CombinedOffset); 7893 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7894 uint32_t Imm = C->getZExtValue(); 7895 uint32_t SOffset, ImmOffset; 7896 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7897 Alignment)) { 7898 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7899 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7900 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7901 return SOffset + ImmOffset; 7902 } 7903 } 7904 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7905 SDValue N0 = CombinedOffset.getOperand(0); 7906 SDValue N1 = CombinedOffset.getOperand(1); 7907 uint32_t SOffset, ImmOffset; 7908 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7909 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7910 Subtarget, Alignment)) { 7911 Offsets[0] = N0; 7912 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7913 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7914 return 0; 7915 } 7916 } 7917 Offsets[0] = CombinedOffset; 7918 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7919 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7920 return 0; 7921 } 7922 7923 // Handle 8 bit and 16 bit buffer loads 7924 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7925 EVT LoadVT, SDLoc DL, 7926 ArrayRef<SDValue> Ops, 7927 MemSDNode *M) const { 7928 EVT IntVT = LoadVT.changeTypeToInteger(); 7929 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7930 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7931 7932 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7933 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7934 Ops, IntVT, 7935 M->getMemOperand()); 7936 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7937 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7938 7939 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7940 } 7941 7942 // Handle 8 bit and 16 bit buffer stores 7943 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7944 EVT VDataType, SDLoc DL, 7945 SDValue Ops[], 7946 MemSDNode *M) const { 7947 if (VDataType == MVT::f16) 7948 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7949 7950 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7951 Ops[1] = BufferStoreExt; 7952 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7953 AMDGPUISD::BUFFER_STORE_SHORT; 7954 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7955 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7956 M->getMemOperand()); 7957 } 7958 7959 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7960 ISD::LoadExtType ExtType, SDValue Op, 7961 const SDLoc &SL, EVT VT) { 7962 if (VT.bitsLT(Op.getValueType())) 7963 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7964 7965 switch (ExtType) { 7966 case ISD::SEXTLOAD: 7967 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7968 case ISD::ZEXTLOAD: 7969 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7970 case ISD::EXTLOAD: 7971 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7972 case ISD::NON_EXTLOAD: 7973 return Op; 7974 } 7975 7976 llvm_unreachable("invalid ext type"); 7977 } 7978 7979 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7980 SelectionDAG &DAG = DCI.DAG; 7981 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7982 return SDValue(); 7983 7984 // FIXME: Constant loads should all be marked invariant. 7985 unsigned AS = Ld->getAddressSpace(); 7986 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7987 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7988 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7989 return SDValue(); 7990 7991 // Don't do this early, since it may interfere with adjacent load merging for 7992 // illegal types. We can avoid losing alignment information for exotic types 7993 // pre-legalize. 7994 EVT MemVT = Ld->getMemoryVT(); 7995 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7996 MemVT.getSizeInBits() >= 32) 7997 return SDValue(); 7998 7999 SDLoc SL(Ld); 8000 8001 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 8002 "unexpected vector extload"); 8003 8004 // TODO: Drop only high part of range. 8005 SDValue Ptr = Ld->getBasePtr(); 8006 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 8007 MVT::i32, SL, Ld->getChain(), Ptr, 8008 Ld->getOffset(), 8009 Ld->getPointerInfo(), MVT::i32, 8010 Ld->getAlignment(), 8011 Ld->getMemOperand()->getFlags(), 8012 Ld->getAAInfo(), 8013 nullptr); // Drop ranges 8014 8015 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 8016 if (MemVT.isFloatingPoint()) { 8017 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 8018 "unexpected fp extload"); 8019 TruncVT = MemVT.changeTypeToInteger(); 8020 } 8021 8022 SDValue Cvt = NewLoad; 8023 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 8024 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 8025 DAG.getValueType(TruncVT)); 8026 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 8027 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 8028 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 8029 } else { 8030 assert(Ld->getExtensionType() == ISD::EXTLOAD); 8031 } 8032 8033 EVT VT = Ld->getValueType(0); 8034 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8035 8036 DCI.AddToWorklist(Cvt.getNode()); 8037 8038 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8039 // the appropriate extension from the 32-bit load. 8040 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8041 DCI.AddToWorklist(Cvt.getNode()); 8042 8043 // Handle conversion back to floating point if necessary. 8044 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8045 8046 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8047 } 8048 8049 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8050 SDLoc DL(Op); 8051 LoadSDNode *Load = cast<LoadSDNode>(Op); 8052 ISD::LoadExtType ExtType = Load->getExtensionType(); 8053 EVT MemVT = Load->getMemoryVT(); 8054 8055 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8056 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8057 return SDValue(); 8058 8059 // FIXME: Copied from PPC 8060 // First, load into 32 bits, then truncate to 1 bit. 8061 8062 SDValue Chain = Load->getChain(); 8063 SDValue BasePtr = Load->getBasePtr(); 8064 MachineMemOperand *MMO = Load->getMemOperand(); 8065 8066 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8067 8068 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8069 BasePtr, RealMemVT, MMO); 8070 8071 if (!MemVT.isVector()) { 8072 SDValue Ops[] = { 8073 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8074 NewLD.getValue(1) 8075 }; 8076 8077 return DAG.getMergeValues(Ops, DL); 8078 } 8079 8080 SmallVector<SDValue, 3> Elts; 8081 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8082 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8083 DAG.getConstant(I, DL, MVT::i32)); 8084 8085 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8086 } 8087 8088 SDValue Ops[] = { 8089 DAG.getBuildVector(MemVT, DL, Elts), 8090 NewLD.getValue(1) 8091 }; 8092 8093 return DAG.getMergeValues(Ops, DL); 8094 } 8095 8096 if (!MemVT.isVector()) 8097 return SDValue(); 8098 8099 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8100 "Custom lowering for non-i32 vectors hasn't been implemented."); 8101 8102 unsigned Alignment = Load->getAlignment(); 8103 unsigned AS = Load->getAddressSpace(); 8104 if (Subtarget->hasLDSMisalignedBug() && 8105 AS == AMDGPUAS::FLAT_ADDRESS && 8106 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8107 return SplitVectorLoad(Op, DAG); 8108 } 8109 8110 MachineFunction &MF = DAG.getMachineFunction(); 8111 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8112 // If there is a possibilty that flat instruction access scratch memory 8113 // then we need to use the same legalization rules we use for private. 8114 if (AS == AMDGPUAS::FLAT_ADDRESS && 8115 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8116 AS = MFI->hasFlatScratchInit() ? 8117 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8118 8119 unsigned NumElements = MemVT.getVectorNumElements(); 8120 8121 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8122 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8123 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8124 if (MemVT.isPow2VectorType()) 8125 return SDValue(); 8126 return WidenOrSplitVectorLoad(Op, DAG); 8127 } 8128 // Non-uniform loads will be selected to MUBUF instructions, so they 8129 // have the same legalization requirements as global and private 8130 // loads. 8131 // 8132 } 8133 8134 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8135 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8136 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8137 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8138 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8139 Alignment >= 4 && NumElements < 32) { 8140 if (MemVT.isPow2VectorType()) 8141 return SDValue(); 8142 return WidenOrSplitVectorLoad(Op, DAG); 8143 } 8144 // Non-uniform loads will be selected to MUBUF instructions, so they 8145 // have the same legalization requirements as global and private 8146 // loads. 8147 // 8148 } 8149 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8150 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8151 AS == AMDGPUAS::GLOBAL_ADDRESS || 8152 AS == AMDGPUAS::FLAT_ADDRESS) { 8153 if (NumElements > 4) 8154 return SplitVectorLoad(Op, DAG); 8155 // v3 loads not supported on SI. 8156 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8157 return WidenOrSplitVectorLoad(Op, DAG); 8158 8159 // v3 and v4 loads are supported for private and global memory. 8160 return SDValue(); 8161 } 8162 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8163 // Depending on the setting of the private_element_size field in the 8164 // resource descriptor, we can only make private accesses up to a certain 8165 // size. 8166 switch (Subtarget->getMaxPrivateElementSize()) { 8167 case 4: { 8168 SDValue Ops[2]; 8169 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8170 return DAG.getMergeValues(Ops, DL); 8171 } 8172 case 8: 8173 if (NumElements > 2) 8174 return SplitVectorLoad(Op, DAG); 8175 return SDValue(); 8176 case 16: 8177 // Same as global/flat 8178 if (NumElements > 4) 8179 return SplitVectorLoad(Op, DAG); 8180 // v3 loads not supported on SI. 8181 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8182 return WidenOrSplitVectorLoad(Op, DAG); 8183 8184 return SDValue(); 8185 default: 8186 llvm_unreachable("unsupported private_element_size"); 8187 } 8188 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8189 // Use ds_read_b128 or ds_read_b96 when possible. 8190 if (Subtarget->hasDS96AndDS128() && 8191 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8192 MemVT.getStoreSize() == 12) && 8193 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8194 Load->getAlign())) 8195 return SDValue(); 8196 8197 if (NumElements > 2) 8198 return SplitVectorLoad(Op, DAG); 8199 8200 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8201 // address is negative, then the instruction is incorrectly treated as 8202 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8203 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8204 // load later in the SILoadStoreOptimizer. 8205 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8206 NumElements == 2 && MemVT.getStoreSize() == 8 && 8207 Load->getAlignment() < 8) { 8208 return SplitVectorLoad(Op, DAG); 8209 } 8210 } 8211 8212 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8213 MemVT, *Load->getMemOperand())) { 8214 SDValue Ops[2]; 8215 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8216 return DAG.getMergeValues(Ops, DL); 8217 } 8218 8219 return SDValue(); 8220 } 8221 8222 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8223 EVT VT = Op.getValueType(); 8224 assert(VT.getSizeInBits() == 64); 8225 8226 SDLoc DL(Op); 8227 SDValue Cond = Op.getOperand(0); 8228 8229 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8230 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8231 8232 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8233 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8234 8235 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8236 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8237 8238 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8239 8240 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8241 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8242 8243 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8244 8245 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8246 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8247 } 8248 8249 // Catch division cases where we can use shortcuts with rcp and rsq 8250 // instructions. 8251 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8252 SelectionDAG &DAG) const { 8253 SDLoc SL(Op); 8254 SDValue LHS = Op.getOperand(0); 8255 SDValue RHS = Op.getOperand(1); 8256 EVT VT = Op.getValueType(); 8257 const SDNodeFlags Flags = Op->getFlags(); 8258 8259 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8260 8261 // Without !fpmath accuracy information, we can't do more because we don't 8262 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8263 if (!AllowInaccurateRcp) 8264 return SDValue(); 8265 8266 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8267 if (CLHS->isExactlyValue(1.0)) { 8268 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8269 // the CI documentation has a worst case error of 1 ulp. 8270 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8271 // use it as long as we aren't trying to use denormals. 8272 // 8273 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8274 8275 // 1.0 / sqrt(x) -> rsq(x) 8276 8277 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8278 // error seems really high at 2^29 ULP. 8279 if (RHS.getOpcode() == ISD::FSQRT) 8280 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8281 8282 // 1.0 / x -> rcp(x) 8283 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8284 } 8285 8286 // Same as for 1.0, but expand the sign out of the constant. 8287 if (CLHS->isExactlyValue(-1.0)) { 8288 // -1.0 / x -> rcp (fneg x) 8289 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8290 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8291 } 8292 } 8293 8294 // Turn into multiply by the reciprocal. 8295 // x / y -> x * (1.0 / y) 8296 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8297 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8298 } 8299 8300 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8301 SelectionDAG &DAG) const { 8302 SDLoc SL(Op); 8303 SDValue X = Op.getOperand(0); 8304 SDValue Y = Op.getOperand(1); 8305 EVT VT = Op.getValueType(); 8306 const SDNodeFlags Flags = Op->getFlags(); 8307 8308 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8309 DAG.getTarget().Options.UnsafeFPMath; 8310 if (!AllowInaccurateDiv) 8311 return SDValue(); 8312 8313 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8314 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8315 8316 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8317 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8318 8319 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8320 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8321 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8322 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8323 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8324 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8325 } 8326 8327 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8328 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8329 SDNodeFlags Flags) { 8330 if (GlueChain->getNumValues() <= 1) { 8331 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8332 } 8333 8334 assert(GlueChain->getNumValues() == 3); 8335 8336 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8337 switch (Opcode) { 8338 default: llvm_unreachable("no chain equivalent for opcode"); 8339 case ISD::FMUL: 8340 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8341 break; 8342 } 8343 8344 return DAG.getNode(Opcode, SL, VTList, 8345 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8346 Flags); 8347 } 8348 8349 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8350 EVT VT, SDValue A, SDValue B, SDValue C, 8351 SDValue GlueChain, SDNodeFlags Flags) { 8352 if (GlueChain->getNumValues() <= 1) { 8353 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8354 } 8355 8356 assert(GlueChain->getNumValues() == 3); 8357 8358 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8359 switch (Opcode) { 8360 default: llvm_unreachable("no chain equivalent for opcode"); 8361 case ISD::FMA: 8362 Opcode = AMDGPUISD::FMA_W_CHAIN; 8363 break; 8364 } 8365 8366 return DAG.getNode(Opcode, SL, VTList, 8367 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8368 Flags); 8369 } 8370 8371 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8372 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8373 return FastLowered; 8374 8375 SDLoc SL(Op); 8376 SDValue Src0 = Op.getOperand(0); 8377 SDValue Src1 = Op.getOperand(1); 8378 8379 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8380 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8381 8382 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8383 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8384 8385 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8386 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8387 8388 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8389 } 8390 8391 // Faster 2.5 ULP division that does not support denormals. 8392 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8393 SDLoc SL(Op); 8394 SDValue LHS = Op.getOperand(1); 8395 SDValue RHS = Op.getOperand(2); 8396 8397 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8398 8399 const APFloat K0Val(BitsToFloat(0x6f800000)); 8400 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8401 8402 const APFloat K1Val(BitsToFloat(0x2f800000)); 8403 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8404 8405 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8406 8407 EVT SetCCVT = 8408 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8409 8410 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8411 8412 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8413 8414 // TODO: Should this propagate fast-math-flags? 8415 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8416 8417 // rcp does not support denormals. 8418 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8419 8420 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8421 8422 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8423 } 8424 8425 // Returns immediate value for setting the F32 denorm mode when using the 8426 // S_DENORM_MODE instruction. 8427 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8428 const SDLoc &SL, const GCNSubtarget *ST) { 8429 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8430 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8431 ? FP_DENORM_FLUSH_NONE 8432 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8433 8434 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8435 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8436 } 8437 8438 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8439 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8440 return FastLowered; 8441 8442 // The selection matcher assumes anything with a chain selecting to a 8443 // mayRaiseFPException machine instruction. Since we're introducing a chain 8444 // here, we need to explicitly report nofpexcept for the regular fdiv 8445 // lowering. 8446 SDNodeFlags Flags = Op->getFlags(); 8447 Flags.setNoFPExcept(true); 8448 8449 SDLoc SL(Op); 8450 SDValue LHS = Op.getOperand(0); 8451 SDValue RHS = Op.getOperand(1); 8452 8453 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8454 8455 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8456 8457 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8458 {RHS, RHS, LHS}, Flags); 8459 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8460 {LHS, RHS, LHS}, Flags); 8461 8462 // Denominator is scaled to not be denormal, so using rcp is ok. 8463 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8464 DenominatorScaled, Flags); 8465 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8466 DenominatorScaled, Flags); 8467 8468 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8469 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8470 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8471 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8472 8473 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8474 8475 if (!HasFP32Denormals) { 8476 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8477 // lowering. The chain dependence is insufficient, and we need glue. We do 8478 // not need the glue variants in a strictfp function. 8479 8480 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8481 8482 SDNode *EnableDenorm; 8483 if (Subtarget->hasDenormModeInst()) { 8484 const SDValue EnableDenormValue = 8485 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8486 8487 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8488 DAG.getEntryNode(), EnableDenormValue).getNode(); 8489 } else { 8490 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8491 SL, MVT::i32); 8492 EnableDenorm = 8493 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8494 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8495 } 8496 8497 SDValue Ops[3] = { 8498 NegDivScale0, 8499 SDValue(EnableDenorm, 0), 8500 SDValue(EnableDenorm, 1) 8501 }; 8502 8503 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8504 } 8505 8506 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8507 ApproxRcp, One, NegDivScale0, Flags); 8508 8509 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8510 ApproxRcp, Fma0, Flags); 8511 8512 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8513 Fma1, Fma1, Flags); 8514 8515 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8516 NumeratorScaled, Mul, Flags); 8517 8518 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8519 Fma2, Fma1, Mul, Fma2, Flags); 8520 8521 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8522 NumeratorScaled, Fma3, Flags); 8523 8524 if (!HasFP32Denormals) { 8525 SDNode *DisableDenorm; 8526 if (Subtarget->hasDenormModeInst()) { 8527 const SDValue DisableDenormValue = 8528 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8529 8530 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8531 Fma4.getValue(1), DisableDenormValue, 8532 Fma4.getValue(2)).getNode(); 8533 } else { 8534 const SDValue DisableDenormValue = 8535 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8536 8537 DisableDenorm = DAG.getMachineNode( 8538 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8539 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8540 } 8541 8542 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8543 SDValue(DisableDenorm, 0), DAG.getRoot()); 8544 DAG.setRoot(OutputChain); 8545 } 8546 8547 SDValue Scale = NumeratorScaled.getValue(1); 8548 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8549 {Fma4, Fma1, Fma3, Scale}, Flags); 8550 8551 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8552 } 8553 8554 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8555 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8556 return FastLowered; 8557 8558 SDLoc SL(Op); 8559 SDValue X = Op.getOperand(0); 8560 SDValue Y = Op.getOperand(1); 8561 8562 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8563 8564 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8565 8566 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8567 8568 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8569 8570 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8571 8572 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8573 8574 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8575 8576 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8577 8578 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8579 8580 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8581 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8582 8583 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8584 NegDivScale0, Mul, DivScale1); 8585 8586 SDValue Scale; 8587 8588 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8589 // Workaround a hardware bug on SI where the condition output from div_scale 8590 // is not usable. 8591 8592 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8593 8594 // Figure out if the scale to use for div_fmas. 8595 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8596 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8597 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8598 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8599 8600 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8601 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8602 8603 SDValue Scale0Hi 8604 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8605 SDValue Scale1Hi 8606 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8607 8608 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8609 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8610 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8611 } else { 8612 Scale = DivScale1.getValue(1); 8613 } 8614 8615 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8616 Fma4, Fma3, Mul, Scale); 8617 8618 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8619 } 8620 8621 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8622 EVT VT = Op.getValueType(); 8623 8624 if (VT == MVT::f32) 8625 return LowerFDIV32(Op, DAG); 8626 8627 if (VT == MVT::f64) 8628 return LowerFDIV64(Op, DAG); 8629 8630 if (VT == MVT::f16) 8631 return LowerFDIV16(Op, DAG); 8632 8633 llvm_unreachable("Unexpected type for fdiv"); 8634 } 8635 8636 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8637 SDLoc DL(Op); 8638 StoreSDNode *Store = cast<StoreSDNode>(Op); 8639 EVT VT = Store->getMemoryVT(); 8640 8641 if (VT == MVT::i1) { 8642 return DAG.getTruncStore(Store->getChain(), DL, 8643 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8644 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8645 } 8646 8647 assert(VT.isVector() && 8648 Store->getValue().getValueType().getScalarType() == MVT::i32); 8649 8650 unsigned AS = Store->getAddressSpace(); 8651 if (Subtarget->hasLDSMisalignedBug() && 8652 AS == AMDGPUAS::FLAT_ADDRESS && 8653 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8654 return SplitVectorStore(Op, DAG); 8655 } 8656 8657 MachineFunction &MF = DAG.getMachineFunction(); 8658 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8659 // If there is a possibilty that flat instruction access scratch memory 8660 // then we need to use the same legalization rules we use for private. 8661 if (AS == AMDGPUAS::FLAT_ADDRESS && 8662 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8663 AS = MFI->hasFlatScratchInit() ? 8664 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8665 8666 unsigned NumElements = VT.getVectorNumElements(); 8667 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8668 AS == AMDGPUAS::FLAT_ADDRESS) { 8669 if (NumElements > 4) 8670 return SplitVectorStore(Op, DAG); 8671 // v3 stores not supported on SI. 8672 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8673 return SplitVectorStore(Op, DAG); 8674 8675 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8676 VT, *Store->getMemOperand())) 8677 return expandUnalignedStore(Store, DAG); 8678 8679 return SDValue(); 8680 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8681 switch (Subtarget->getMaxPrivateElementSize()) { 8682 case 4: 8683 return scalarizeVectorStore(Store, DAG); 8684 case 8: 8685 if (NumElements > 2) 8686 return SplitVectorStore(Op, DAG); 8687 return SDValue(); 8688 case 16: 8689 if (NumElements > 4 || 8690 (NumElements == 3 && !Subtarget->enableFlatScratch())) 8691 return SplitVectorStore(Op, DAG); 8692 return SDValue(); 8693 default: 8694 llvm_unreachable("unsupported private_element_size"); 8695 } 8696 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8697 // Use ds_write_b128 or ds_write_b96 when possible. 8698 if (Subtarget->hasDS96AndDS128() && 8699 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8700 (VT.getStoreSize() == 12)) && 8701 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8702 Store->getAlign())) 8703 return SDValue(); 8704 8705 if (NumElements > 2) 8706 return SplitVectorStore(Op, DAG); 8707 8708 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8709 // address is negative, then the instruction is incorrectly treated as 8710 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8711 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8712 // store later in the SILoadStoreOptimizer. 8713 if (!Subtarget->hasUsableDSOffset() && 8714 NumElements == 2 && VT.getStoreSize() == 8 && 8715 Store->getAlignment() < 8) { 8716 return SplitVectorStore(Op, DAG); 8717 } 8718 8719 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8720 VT, *Store->getMemOperand())) { 8721 if (VT.isVector()) 8722 return SplitVectorStore(Op, DAG); 8723 return expandUnalignedStore(Store, DAG); 8724 } 8725 8726 return SDValue(); 8727 } else { 8728 llvm_unreachable("unhandled address space"); 8729 } 8730 } 8731 8732 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8733 SDLoc DL(Op); 8734 EVT VT = Op.getValueType(); 8735 SDValue Arg = Op.getOperand(0); 8736 SDValue TrigVal; 8737 8738 // Propagate fast-math flags so that the multiply we introduce can be folded 8739 // if Arg is already the result of a multiply by constant. 8740 auto Flags = Op->getFlags(); 8741 8742 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8743 8744 if (Subtarget->hasTrigReducedRange()) { 8745 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8746 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8747 } else { 8748 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8749 } 8750 8751 switch (Op.getOpcode()) { 8752 case ISD::FCOS: 8753 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8754 case ISD::FSIN: 8755 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8756 default: 8757 llvm_unreachable("Wrong trig opcode"); 8758 } 8759 } 8760 8761 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8762 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8763 assert(AtomicNode->isCompareAndSwap()); 8764 unsigned AS = AtomicNode->getAddressSpace(); 8765 8766 // No custom lowering required for local address space 8767 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8768 return Op; 8769 8770 // Non-local address space requires custom lowering for atomic compare 8771 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8772 SDLoc DL(Op); 8773 SDValue ChainIn = Op.getOperand(0); 8774 SDValue Addr = Op.getOperand(1); 8775 SDValue Old = Op.getOperand(2); 8776 SDValue New = Op.getOperand(3); 8777 EVT VT = Op.getValueType(); 8778 MVT SimpleVT = VT.getSimpleVT(); 8779 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8780 8781 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8782 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8783 8784 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8785 Ops, VT, AtomicNode->getMemOperand()); 8786 } 8787 8788 //===----------------------------------------------------------------------===// 8789 // Custom DAG optimizations 8790 //===----------------------------------------------------------------------===// 8791 8792 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8793 DAGCombinerInfo &DCI) const { 8794 EVT VT = N->getValueType(0); 8795 EVT ScalarVT = VT.getScalarType(); 8796 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8797 return SDValue(); 8798 8799 SelectionDAG &DAG = DCI.DAG; 8800 SDLoc DL(N); 8801 8802 SDValue Src = N->getOperand(0); 8803 EVT SrcVT = Src.getValueType(); 8804 8805 // TODO: We could try to match extracting the higher bytes, which would be 8806 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8807 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8808 // about in practice. 8809 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8810 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8811 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8812 DCI.AddToWorklist(Cvt.getNode()); 8813 8814 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8815 if (ScalarVT != MVT::f32) { 8816 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8817 DAG.getTargetConstant(0, DL, MVT::i32)); 8818 } 8819 return Cvt; 8820 } 8821 } 8822 8823 return SDValue(); 8824 } 8825 8826 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8827 8828 // This is a variant of 8829 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8830 // 8831 // The normal DAG combiner will do this, but only if the add has one use since 8832 // that would increase the number of instructions. 8833 // 8834 // This prevents us from seeing a constant offset that can be folded into a 8835 // memory instruction's addressing mode. If we know the resulting add offset of 8836 // a pointer can be folded into an addressing offset, we can replace the pointer 8837 // operand with the add of new constant offset. This eliminates one of the uses, 8838 // and may allow the remaining use to also be simplified. 8839 // 8840 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8841 unsigned AddrSpace, 8842 EVT MemVT, 8843 DAGCombinerInfo &DCI) const { 8844 SDValue N0 = N->getOperand(0); 8845 SDValue N1 = N->getOperand(1); 8846 8847 // We only do this to handle cases where it's profitable when there are 8848 // multiple uses of the add, so defer to the standard combine. 8849 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8850 N0->hasOneUse()) 8851 return SDValue(); 8852 8853 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8854 if (!CN1) 8855 return SDValue(); 8856 8857 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8858 if (!CAdd) 8859 return SDValue(); 8860 8861 // If the resulting offset is too large, we can't fold it into the addressing 8862 // mode offset. 8863 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8864 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8865 8866 AddrMode AM; 8867 AM.HasBaseReg = true; 8868 AM.BaseOffs = Offset.getSExtValue(); 8869 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8870 return SDValue(); 8871 8872 SelectionDAG &DAG = DCI.DAG; 8873 SDLoc SL(N); 8874 EVT VT = N->getValueType(0); 8875 8876 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8877 SDValue COffset = DAG.getConstant(Offset, SL, VT); 8878 8879 SDNodeFlags Flags; 8880 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8881 (N0.getOpcode() == ISD::OR || 8882 N0->getFlags().hasNoUnsignedWrap())); 8883 8884 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8885 } 8886 8887 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 8888 /// by the chain and intrinsic ID. Theoretically we would also need to check the 8889 /// specific intrinsic, but they all place the pointer operand first. 8890 static unsigned getBasePtrIndex(const MemSDNode *N) { 8891 switch (N->getOpcode()) { 8892 case ISD::STORE: 8893 case ISD::INTRINSIC_W_CHAIN: 8894 case ISD::INTRINSIC_VOID: 8895 return 2; 8896 default: 8897 return 1; 8898 } 8899 } 8900 8901 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8902 DAGCombinerInfo &DCI) const { 8903 SelectionDAG &DAG = DCI.DAG; 8904 SDLoc SL(N); 8905 8906 unsigned PtrIdx = getBasePtrIndex(N); 8907 SDValue Ptr = N->getOperand(PtrIdx); 8908 8909 // TODO: We could also do this for multiplies. 8910 if (Ptr.getOpcode() == ISD::SHL) { 8911 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8912 N->getMemoryVT(), DCI); 8913 if (NewPtr) { 8914 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8915 8916 NewOps[PtrIdx] = NewPtr; 8917 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8918 } 8919 } 8920 8921 return SDValue(); 8922 } 8923 8924 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8925 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8926 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8927 (Opc == ISD::XOR && Val == 0); 8928 } 8929 8930 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8931 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8932 // integer combine opportunities since most 64-bit operations are decomposed 8933 // this way. TODO: We won't want this for SALU especially if it is an inline 8934 // immediate. 8935 SDValue SITargetLowering::splitBinaryBitConstantOp( 8936 DAGCombinerInfo &DCI, 8937 const SDLoc &SL, 8938 unsigned Opc, SDValue LHS, 8939 const ConstantSDNode *CRHS) const { 8940 uint64_t Val = CRHS->getZExtValue(); 8941 uint32_t ValLo = Lo_32(Val); 8942 uint32_t ValHi = Hi_32(Val); 8943 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8944 8945 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8946 bitOpWithConstantIsReducible(Opc, ValHi)) || 8947 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8948 // If we need to materialize a 64-bit immediate, it will be split up later 8949 // anyway. Avoid creating the harder to understand 64-bit immediate 8950 // materialization. 8951 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8952 } 8953 8954 return SDValue(); 8955 } 8956 8957 // Returns true if argument is a boolean value which is not serialized into 8958 // memory or argument and does not require v_cndmask_b32 to be deserialized. 8959 static bool isBoolSGPR(SDValue V) { 8960 if (V.getValueType() != MVT::i1) 8961 return false; 8962 switch (V.getOpcode()) { 8963 default: 8964 break; 8965 case ISD::SETCC: 8966 case AMDGPUISD::FP_CLASS: 8967 return true; 8968 case ISD::AND: 8969 case ISD::OR: 8970 case ISD::XOR: 8971 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 8972 } 8973 return false; 8974 } 8975 8976 // If a constant has all zeroes or all ones within each byte return it. 8977 // Otherwise return 0. 8978 static uint32_t getConstantPermuteMask(uint32_t C) { 8979 // 0xff for any zero byte in the mask 8980 uint32_t ZeroByteMask = 0; 8981 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8982 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8983 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8984 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8985 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8986 if ((NonZeroByteMask & C) != NonZeroByteMask) 8987 return 0; // Partial bytes selected. 8988 return C; 8989 } 8990 8991 // Check if a node selects whole bytes from its operand 0 starting at a byte 8992 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8993 // or -1 if not succeeded. 8994 // Note byte select encoding: 8995 // value 0-3 selects corresponding source byte; 8996 // value 0xc selects zero; 8997 // value 0xff selects 0xff. 8998 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8999 assert(V.getValueSizeInBits() == 32); 9000 9001 if (V.getNumOperands() != 2) 9002 return ~0; 9003 9004 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 9005 if (!N1) 9006 return ~0; 9007 9008 uint32_t C = N1->getZExtValue(); 9009 9010 switch (V.getOpcode()) { 9011 default: 9012 break; 9013 case ISD::AND: 9014 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9015 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 9016 } 9017 break; 9018 9019 case ISD::OR: 9020 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9021 return (0x03020100 & ~ConstMask) | ConstMask; 9022 } 9023 break; 9024 9025 case ISD::SHL: 9026 if (C % 8) 9027 return ~0; 9028 9029 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 9030 9031 case ISD::SRL: 9032 if (C % 8) 9033 return ~0; 9034 9035 return uint32_t(0x0c0c0c0c03020100ull >> C); 9036 } 9037 9038 return ~0; 9039 } 9040 9041 SDValue SITargetLowering::performAndCombine(SDNode *N, 9042 DAGCombinerInfo &DCI) const { 9043 if (DCI.isBeforeLegalize()) 9044 return SDValue(); 9045 9046 SelectionDAG &DAG = DCI.DAG; 9047 EVT VT = N->getValueType(0); 9048 SDValue LHS = N->getOperand(0); 9049 SDValue RHS = N->getOperand(1); 9050 9051 9052 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9053 if (VT == MVT::i64 && CRHS) { 9054 if (SDValue Split 9055 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9056 return Split; 9057 } 9058 9059 if (CRHS && VT == MVT::i32) { 9060 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9061 // nb = number of trailing zeroes in mask 9062 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9063 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9064 uint64_t Mask = CRHS->getZExtValue(); 9065 unsigned Bits = countPopulation(Mask); 9066 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9067 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9068 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9069 unsigned Shift = CShift->getZExtValue(); 9070 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9071 unsigned Offset = NB + Shift; 9072 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9073 SDLoc SL(N); 9074 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9075 LHS->getOperand(0), 9076 DAG.getConstant(Offset, SL, MVT::i32), 9077 DAG.getConstant(Bits, SL, MVT::i32)); 9078 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9079 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9080 DAG.getValueType(NarrowVT)); 9081 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9082 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9083 return Shl; 9084 } 9085 } 9086 } 9087 9088 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9089 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9090 isa<ConstantSDNode>(LHS.getOperand(2))) { 9091 uint32_t Sel = getConstantPermuteMask(Mask); 9092 if (!Sel) 9093 return SDValue(); 9094 9095 // Select 0xc for all zero bytes 9096 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9097 SDLoc DL(N); 9098 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9099 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9100 } 9101 } 9102 9103 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9104 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9105 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9106 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9107 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9108 9109 SDValue X = LHS.getOperand(0); 9110 SDValue Y = RHS.getOperand(0); 9111 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9112 return SDValue(); 9113 9114 if (LCC == ISD::SETO) { 9115 if (X != LHS.getOperand(1)) 9116 return SDValue(); 9117 9118 if (RCC == ISD::SETUNE) { 9119 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9120 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9121 return SDValue(); 9122 9123 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9124 SIInstrFlags::N_SUBNORMAL | 9125 SIInstrFlags::N_ZERO | 9126 SIInstrFlags::P_ZERO | 9127 SIInstrFlags::P_SUBNORMAL | 9128 SIInstrFlags::P_NORMAL; 9129 9130 static_assert(((~(SIInstrFlags::S_NAN | 9131 SIInstrFlags::Q_NAN | 9132 SIInstrFlags::N_INFINITY | 9133 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9134 "mask not equal"); 9135 9136 SDLoc DL(N); 9137 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9138 X, DAG.getConstant(Mask, DL, MVT::i32)); 9139 } 9140 } 9141 } 9142 9143 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9144 std::swap(LHS, RHS); 9145 9146 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9147 RHS.hasOneUse()) { 9148 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9149 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9150 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9151 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9152 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9153 (RHS.getOperand(0) == LHS.getOperand(0) && 9154 LHS.getOperand(0) == LHS.getOperand(1))) { 9155 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9156 unsigned NewMask = LCC == ISD::SETO ? 9157 Mask->getZExtValue() & ~OrdMask : 9158 Mask->getZExtValue() & OrdMask; 9159 9160 SDLoc DL(N); 9161 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9162 DAG.getConstant(NewMask, DL, MVT::i32)); 9163 } 9164 } 9165 9166 if (VT == MVT::i32 && 9167 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9168 // and x, (sext cc from i1) => select cc, x, 0 9169 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9170 std::swap(LHS, RHS); 9171 if (isBoolSGPR(RHS.getOperand(0))) 9172 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9173 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9174 } 9175 9176 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9177 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9178 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9179 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9180 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9181 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9182 if (LHSMask != ~0u && RHSMask != ~0u) { 9183 // Canonicalize the expression in an attempt to have fewer unique masks 9184 // and therefore fewer registers used to hold the masks. 9185 if (LHSMask > RHSMask) { 9186 std::swap(LHSMask, RHSMask); 9187 std::swap(LHS, RHS); 9188 } 9189 9190 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9191 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9192 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9193 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9194 9195 // Check of we need to combine values from two sources within a byte. 9196 if (!(LHSUsedLanes & RHSUsedLanes) && 9197 // If we select high and lower word keep it for SDWA. 9198 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9199 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9200 // Each byte in each mask is either selector mask 0-3, or has higher 9201 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9202 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9203 // mask which is not 0xff wins. By anding both masks we have a correct 9204 // result except that 0x0c shall be corrected to give 0x0c only. 9205 uint32_t Mask = LHSMask & RHSMask; 9206 for (unsigned I = 0; I < 32; I += 8) { 9207 uint32_t ByteSel = 0xff << I; 9208 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9209 Mask &= (0x0c << I) & 0xffffffff; 9210 } 9211 9212 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9213 // or 0x0c. 9214 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9215 SDLoc DL(N); 9216 9217 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9218 LHS.getOperand(0), RHS.getOperand(0), 9219 DAG.getConstant(Sel, DL, MVT::i32)); 9220 } 9221 } 9222 } 9223 9224 return SDValue(); 9225 } 9226 9227 SDValue SITargetLowering::performOrCombine(SDNode *N, 9228 DAGCombinerInfo &DCI) const { 9229 SelectionDAG &DAG = DCI.DAG; 9230 SDValue LHS = N->getOperand(0); 9231 SDValue RHS = N->getOperand(1); 9232 9233 EVT VT = N->getValueType(0); 9234 if (VT == MVT::i1) { 9235 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9236 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9237 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9238 SDValue Src = LHS.getOperand(0); 9239 if (Src != RHS.getOperand(0)) 9240 return SDValue(); 9241 9242 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9243 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9244 if (!CLHS || !CRHS) 9245 return SDValue(); 9246 9247 // Only 10 bits are used. 9248 static const uint32_t MaxMask = 0x3ff; 9249 9250 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9251 SDLoc DL(N); 9252 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9253 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9254 } 9255 9256 return SDValue(); 9257 } 9258 9259 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9260 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9261 LHS.getOpcode() == AMDGPUISD::PERM && 9262 isa<ConstantSDNode>(LHS.getOperand(2))) { 9263 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9264 if (!Sel) 9265 return SDValue(); 9266 9267 Sel |= LHS.getConstantOperandVal(2); 9268 SDLoc DL(N); 9269 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9270 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9271 } 9272 9273 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9274 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9275 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9276 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9277 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9278 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9279 if (LHSMask != ~0u && RHSMask != ~0u) { 9280 // Canonicalize the expression in an attempt to have fewer unique masks 9281 // and therefore fewer registers used to hold the masks. 9282 if (LHSMask > RHSMask) { 9283 std::swap(LHSMask, RHSMask); 9284 std::swap(LHS, RHS); 9285 } 9286 9287 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9288 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9289 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9290 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9291 9292 // Check of we need to combine values from two sources within a byte. 9293 if (!(LHSUsedLanes & RHSUsedLanes) && 9294 // If we select high and lower word keep it for SDWA. 9295 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9296 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9297 // Kill zero bytes selected by other mask. Zero value is 0xc. 9298 LHSMask &= ~RHSUsedLanes; 9299 RHSMask &= ~LHSUsedLanes; 9300 // Add 4 to each active LHS lane 9301 LHSMask |= LHSUsedLanes & 0x04040404; 9302 // Combine masks 9303 uint32_t Sel = LHSMask | RHSMask; 9304 SDLoc DL(N); 9305 9306 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9307 LHS.getOperand(0), RHS.getOperand(0), 9308 DAG.getConstant(Sel, DL, MVT::i32)); 9309 } 9310 } 9311 } 9312 9313 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9314 return SDValue(); 9315 9316 // TODO: This could be a generic combine with a predicate for extracting the 9317 // high half of an integer being free. 9318 9319 // (or i64:x, (zero_extend i32:y)) -> 9320 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9321 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9322 RHS.getOpcode() != ISD::ZERO_EXTEND) 9323 std::swap(LHS, RHS); 9324 9325 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9326 SDValue ExtSrc = RHS.getOperand(0); 9327 EVT SrcVT = ExtSrc.getValueType(); 9328 if (SrcVT == MVT::i32) { 9329 SDLoc SL(N); 9330 SDValue LowLHS, HiBits; 9331 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9332 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9333 9334 DCI.AddToWorklist(LowOr.getNode()); 9335 DCI.AddToWorklist(HiBits.getNode()); 9336 9337 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9338 LowOr, HiBits); 9339 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9340 } 9341 } 9342 9343 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9344 if (CRHS) { 9345 if (SDValue Split 9346 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9347 return Split; 9348 } 9349 9350 return SDValue(); 9351 } 9352 9353 SDValue SITargetLowering::performXorCombine(SDNode *N, 9354 DAGCombinerInfo &DCI) const { 9355 EVT VT = N->getValueType(0); 9356 if (VT != MVT::i64) 9357 return SDValue(); 9358 9359 SDValue LHS = N->getOperand(0); 9360 SDValue RHS = N->getOperand(1); 9361 9362 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9363 if (CRHS) { 9364 if (SDValue Split 9365 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9366 return Split; 9367 } 9368 9369 return SDValue(); 9370 } 9371 9372 // Instructions that will be lowered with a final instruction that zeros the 9373 // high result bits. 9374 // XXX - probably only need to list legal operations. 9375 static bool fp16SrcZerosHighBits(unsigned Opc) { 9376 switch (Opc) { 9377 case ISD::FADD: 9378 case ISD::FSUB: 9379 case ISD::FMUL: 9380 case ISD::FDIV: 9381 case ISD::FREM: 9382 case ISD::FMA: 9383 case ISD::FMAD: 9384 case ISD::FCANONICALIZE: 9385 case ISD::FP_ROUND: 9386 case ISD::UINT_TO_FP: 9387 case ISD::SINT_TO_FP: 9388 case ISD::FABS: 9389 // Fabs is lowered to a bit operation, but it's an and which will clear the 9390 // high bits anyway. 9391 case ISD::FSQRT: 9392 case ISD::FSIN: 9393 case ISD::FCOS: 9394 case ISD::FPOWI: 9395 case ISD::FPOW: 9396 case ISD::FLOG: 9397 case ISD::FLOG2: 9398 case ISD::FLOG10: 9399 case ISD::FEXP: 9400 case ISD::FEXP2: 9401 case ISD::FCEIL: 9402 case ISD::FTRUNC: 9403 case ISD::FRINT: 9404 case ISD::FNEARBYINT: 9405 case ISD::FROUND: 9406 case ISD::FFLOOR: 9407 case ISD::FMINNUM: 9408 case ISD::FMAXNUM: 9409 case AMDGPUISD::FRACT: 9410 case AMDGPUISD::CLAMP: 9411 case AMDGPUISD::COS_HW: 9412 case AMDGPUISD::SIN_HW: 9413 case AMDGPUISD::FMIN3: 9414 case AMDGPUISD::FMAX3: 9415 case AMDGPUISD::FMED3: 9416 case AMDGPUISD::FMAD_FTZ: 9417 case AMDGPUISD::RCP: 9418 case AMDGPUISD::RSQ: 9419 case AMDGPUISD::RCP_IFLAG: 9420 case AMDGPUISD::LDEXP: 9421 return true; 9422 default: 9423 // fcopysign, select and others may be lowered to 32-bit bit operations 9424 // which don't zero the high bits. 9425 return false; 9426 } 9427 } 9428 9429 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9430 DAGCombinerInfo &DCI) const { 9431 if (!Subtarget->has16BitInsts() || 9432 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9433 return SDValue(); 9434 9435 EVT VT = N->getValueType(0); 9436 if (VT != MVT::i32) 9437 return SDValue(); 9438 9439 SDValue Src = N->getOperand(0); 9440 if (Src.getValueType() != MVT::i16) 9441 return SDValue(); 9442 9443 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9444 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9445 if (Src.getOpcode() == ISD::BITCAST) { 9446 SDValue BCSrc = Src.getOperand(0); 9447 if (BCSrc.getValueType() == MVT::f16 && 9448 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9449 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9450 } 9451 9452 return SDValue(); 9453 } 9454 9455 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9456 DAGCombinerInfo &DCI) 9457 const { 9458 SDValue Src = N->getOperand(0); 9459 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9460 9461 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9462 VTSign->getVT() == MVT::i8) || 9463 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9464 VTSign->getVT() == MVT::i16)) && 9465 Src.hasOneUse()) { 9466 auto *M = cast<MemSDNode>(Src); 9467 SDValue Ops[] = { 9468 Src.getOperand(0), // Chain 9469 Src.getOperand(1), // rsrc 9470 Src.getOperand(2), // vindex 9471 Src.getOperand(3), // voffset 9472 Src.getOperand(4), // soffset 9473 Src.getOperand(5), // offset 9474 Src.getOperand(6), 9475 Src.getOperand(7) 9476 }; 9477 // replace with BUFFER_LOAD_BYTE/SHORT 9478 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9479 Src.getOperand(0).getValueType()); 9480 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9481 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9482 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9483 ResList, 9484 Ops, M->getMemoryVT(), 9485 M->getMemOperand()); 9486 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9487 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9488 } 9489 return SDValue(); 9490 } 9491 9492 SDValue SITargetLowering::performClassCombine(SDNode *N, 9493 DAGCombinerInfo &DCI) const { 9494 SelectionDAG &DAG = DCI.DAG; 9495 SDValue Mask = N->getOperand(1); 9496 9497 // fp_class x, 0 -> false 9498 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9499 if (CMask->isNullValue()) 9500 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9501 } 9502 9503 if (N->getOperand(0).isUndef()) 9504 return DAG.getUNDEF(MVT::i1); 9505 9506 return SDValue(); 9507 } 9508 9509 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9510 DAGCombinerInfo &DCI) const { 9511 EVT VT = N->getValueType(0); 9512 SDValue N0 = N->getOperand(0); 9513 9514 if (N0.isUndef()) 9515 return N0; 9516 9517 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9518 N0.getOpcode() == ISD::SINT_TO_FP)) { 9519 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9520 N->getFlags()); 9521 } 9522 9523 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9524 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9525 N0.getOperand(0), N->getFlags()); 9526 } 9527 9528 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9529 } 9530 9531 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9532 unsigned MaxDepth) const { 9533 unsigned Opcode = Op.getOpcode(); 9534 if (Opcode == ISD::FCANONICALIZE) 9535 return true; 9536 9537 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9538 auto F = CFP->getValueAPF(); 9539 if (F.isNaN() && F.isSignaling()) 9540 return false; 9541 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9542 } 9543 9544 // If source is a result of another standard FP operation it is already in 9545 // canonical form. 9546 if (MaxDepth == 0) 9547 return false; 9548 9549 switch (Opcode) { 9550 // These will flush denorms if required. 9551 case ISD::FADD: 9552 case ISD::FSUB: 9553 case ISD::FMUL: 9554 case ISD::FCEIL: 9555 case ISD::FFLOOR: 9556 case ISD::FMA: 9557 case ISD::FMAD: 9558 case ISD::FSQRT: 9559 case ISD::FDIV: 9560 case ISD::FREM: 9561 case ISD::FP_ROUND: 9562 case ISD::FP_EXTEND: 9563 case AMDGPUISD::FMUL_LEGACY: 9564 case AMDGPUISD::FMAD_FTZ: 9565 case AMDGPUISD::RCP: 9566 case AMDGPUISD::RSQ: 9567 case AMDGPUISD::RSQ_CLAMP: 9568 case AMDGPUISD::RCP_LEGACY: 9569 case AMDGPUISD::RCP_IFLAG: 9570 case AMDGPUISD::DIV_SCALE: 9571 case AMDGPUISD::DIV_FMAS: 9572 case AMDGPUISD::DIV_FIXUP: 9573 case AMDGPUISD::FRACT: 9574 case AMDGPUISD::LDEXP: 9575 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9576 case AMDGPUISD::CVT_F32_UBYTE0: 9577 case AMDGPUISD::CVT_F32_UBYTE1: 9578 case AMDGPUISD::CVT_F32_UBYTE2: 9579 case AMDGPUISD::CVT_F32_UBYTE3: 9580 return true; 9581 9582 // It can/will be lowered or combined as a bit operation. 9583 // Need to check their input recursively to handle. 9584 case ISD::FNEG: 9585 case ISD::FABS: 9586 case ISD::FCOPYSIGN: 9587 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9588 9589 case ISD::FSIN: 9590 case ISD::FCOS: 9591 case ISD::FSINCOS: 9592 return Op.getValueType().getScalarType() != MVT::f16; 9593 9594 case ISD::FMINNUM: 9595 case ISD::FMAXNUM: 9596 case ISD::FMINNUM_IEEE: 9597 case ISD::FMAXNUM_IEEE: 9598 case AMDGPUISD::CLAMP: 9599 case AMDGPUISD::FMED3: 9600 case AMDGPUISD::FMAX3: 9601 case AMDGPUISD::FMIN3: { 9602 // FIXME: Shouldn't treat the generic operations different based these. 9603 // However, we aren't really required to flush the result from 9604 // minnum/maxnum.. 9605 9606 // snans will be quieted, so we only need to worry about denormals. 9607 if (Subtarget->supportsMinMaxDenormModes() || 9608 denormalsEnabledForType(DAG, Op.getValueType())) 9609 return true; 9610 9611 // Flushing may be required. 9612 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9613 // targets need to check their input recursively. 9614 9615 // FIXME: Does this apply with clamp? It's implemented with max. 9616 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9617 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9618 return false; 9619 } 9620 9621 return true; 9622 } 9623 case ISD::SELECT: { 9624 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9625 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9626 } 9627 case ISD::BUILD_VECTOR: { 9628 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9629 SDValue SrcOp = Op.getOperand(i); 9630 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9631 return false; 9632 } 9633 9634 return true; 9635 } 9636 case ISD::EXTRACT_VECTOR_ELT: 9637 case ISD::EXTRACT_SUBVECTOR: { 9638 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9639 } 9640 case ISD::INSERT_VECTOR_ELT: { 9641 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9642 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9643 } 9644 case ISD::UNDEF: 9645 // Could be anything. 9646 return false; 9647 9648 case ISD::BITCAST: 9649 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9650 case ISD::TRUNCATE: { 9651 // Hack round the mess we make when legalizing extract_vector_elt 9652 if (Op.getValueType() == MVT::i16) { 9653 SDValue TruncSrc = Op.getOperand(0); 9654 if (TruncSrc.getValueType() == MVT::i32 && 9655 TruncSrc.getOpcode() == ISD::BITCAST && 9656 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9657 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9658 } 9659 } 9660 return false; 9661 } 9662 case ISD::INTRINSIC_WO_CHAIN: { 9663 unsigned IntrinsicID 9664 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9665 // TODO: Handle more intrinsics 9666 switch (IntrinsicID) { 9667 case Intrinsic::amdgcn_cvt_pkrtz: 9668 case Intrinsic::amdgcn_cubeid: 9669 case Intrinsic::amdgcn_frexp_mant: 9670 case Intrinsic::amdgcn_fdot2: 9671 case Intrinsic::amdgcn_rcp: 9672 case Intrinsic::amdgcn_rsq: 9673 case Intrinsic::amdgcn_rsq_clamp: 9674 case Intrinsic::amdgcn_rcp_legacy: 9675 case Intrinsic::amdgcn_rsq_legacy: 9676 case Intrinsic::amdgcn_trig_preop: 9677 return true; 9678 default: 9679 break; 9680 } 9681 9682 LLVM_FALLTHROUGH; 9683 } 9684 default: 9685 return denormalsEnabledForType(DAG, Op.getValueType()) && 9686 DAG.isKnownNeverSNaN(Op); 9687 } 9688 9689 llvm_unreachable("invalid operation"); 9690 } 9691 9692 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 9693 unsigned MaxDepth) const { 9694 MachineRegisterInfo &MRI = MF.getRegInfo(); 9695 MachineInstr *MI = MRI.getVRegDef(Reg); 9696 unsigned Opcode = MI->getOpcode(); 9697 9698 if (Opcode == AMDGPU::G_FCANONICALIZE) 9699 return true; 9700 9701 if (Opcode == AMDGPU::G_FCONSTANT) { 9702 auto F = MI->getOperand(1).getFPImm()->getValueAPF(); 9703 if (F.isNaN() && F.isSignaling()) 9704 return false; 9705 return !F.isDenormal() || denormalsEnabledForType(MRI.getType(Reg), MF); 9706 } 9707 9708 if (MaxDepth == 0) 9709 return false; 9710 9711 switch (Opcode) { 9712 case AMDGPU::G_FMINNUM_IEEE: 9713 case AMDGPU::G_FMAXNUM_IEEE: { 9714 if (Subtarget->supportsMinMaxDenormModes() || 9715 denormalsEnabledForType(MRI.getType(Reg), MF)) 9716 return true; 9717 for (unsigned I = 1, E = MI->getNumOperands(); I != E; ++I) { 9718 if (!isCanonicalized(MI->getOperand(I).getReg(), MF, MaxDepth - 1)) 9719 return false; 9720 } 9721 return true; 9722 } 9723 default: 9724 return denormalsEnabledForType(MRI.getType(Reg), MF) && 9725 isKnownNeverSNaN(Reg, MRI); 9726 } 9727 9728 llvm_unreachable("invalid operation"); 9729 } 9730 9731 // Constant fold canonicalize. 9732 SDValue SITargetLowering::getCanonicalConstantFP( 9733 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9734 // Flush denormals to 0 if not enabled. 9735 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9736 return DAG.getConstantFP(0.0, SL, VT); 9737 9738 if (C.isNaN()) { 9739 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9740 if (C.isSignaling()) { 9741 // Quiet a signaling NaN. 9742 // FIXME: Is this supposed to preserve payload bits? 9743 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9744 } 9745 9746 // Make sure it is the canonical NaN bitpattern. 9747 // 9748 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9749 // immediate? 9750 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9751 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9752 } 9753 9754 // Already canonical. 9755 return DAG.getConstantFP(C, SL, VT); 9756 } 9757 9758 static bool vectorEltWillFoldAway(SDValue Op) { 9759 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9760 } 9761 9762 SDValue SITargetLowering::performFCanonicalizeCombine( 9763 SDNode *N, 9764 DAGCombinerInfo &DCI) const { 9765 SelectionDAG &DAG = DCI.DAG; 9766 SDValue N0 = N->getOperand(0); 9767 EVT VT = N->getValueType(0); 9768 9769 // fcanonicalize undef -> qnan 9770 if (N0.isUndef()) { 9771 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9772 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9773 } 9774 9775 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9776 EVT VT = N->getValueType(0); 9777 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9778 } 9779 9780 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9781 // (fcanonicalize k) 9782 // 9783 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9784 9785 // TODO: This could be better with wider vectors that will be split to v2f16, 9786 // and to consider uses since there aren't that many packed operations. 9787 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9788 isTypeLegal(MVT::v2f16)) { 9789 SDLoc SL(N); 9790 SDValue NewElts[2]; 9791 SDValue Lo = N0.getOperand(0); 9792 SDValue Hi = N0.getOperand(1); 9793 EVT EltVT = Lo.getValueType(); 9794 9795 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9796 for (unsigned I = 0; I != 2; ++I) { 9797 SDValue Op = N0.getOperand(I); 9798 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9799 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9800 CFP->getValueAPF()); 9801 } else if (Op.isUndef()) { 9802 // Handled below based on what the other operand is. 9803 NewElts[I] = Op; 9804 } else { 9805 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9806 } 9807 } 9808 9809 // If one half is undef, and one is constant, perfer a splat vector rather 9810 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9811 // cheaper to use and may be free with a packed operation. 9812 if (NewElts[0].isUndef()) { 9813 if (isa<ConstantFPSDNode>(NewElts[1])) 9814 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9815 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9816 } 9817 9818 if (NewElts[1].isUndef()) { 9819 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9820 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9821 } 9822 9823 return DAG.getBuildVector(VT, SL, NewElts); 9824 } 9825 } 9826 9827 unsigned SrcOpc = N0.getOpcode(); 9828 9829 // If it's free to do so, push canonicalizes further up the source, which may 9830 // find a canonical source. 9831 // 9832 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9833 // sNaNs. 9834 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9835 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9836 if (CRHS && N0.hasOneUse()) { 9837 SDLoc SL(N); 9838 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9839 N0.getOperand(0)); 9840 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9841 DCI.AddToWorklist(Canon0.getNode()); 9842 9843 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9844 } 9845 } 9846 9847 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9848 } 9849 9850 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9851 switch (Opc) { 9852 case ISD::FMAXNUM: 9853 case ISD::FMAXNUM_IEEE: 9854 return AMDGPUISD::FMAX3; 9855 case ISD::SMAX: 9856 return AMDGPUISD::SMAX3; 9857 case ISD::UMAX: 9858 return AMDGPUISD::UMAX3; 9859 case ISD::FMINNUM: 9860 case ISD::FMINNUM_IEEE: 9861 return AMDGPUISD::FMIN3; 9862 case ISD::SMIN: 9863 return AMDGPUISD::SMIN3; 9864 case ISD::UMIN: 9865 return AMDGPUISD::UMIN3; 9866 default: 9867 llvm_unreachable("Not a min/max opcode"); 9868 } 9869 } 9870 9871 SDValue SITargetLowering::performIntMed3ImmCombine( 9872 SelectionDAG &DAG, const SDLoc &SL, 9873 SDValue Op0, SDValue Op1, bool Signed) const { 9874 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9875 if (!K1) 9876 return SDValue(); 9877 9878 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9879 if (!K0) 9880 return SDValue(); 9881 9882 if (Signed) { 9883 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9884 return SDValue(); 9885 } else { 9886 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9887 return SDValue(); 9888 } 9889 9890 EVT VT = K0->getValueType(0); 9891 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9892 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9893 return DAG.getNode(Med3Opc, SL, VT, 9894 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9895 } 9896 9897 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9898 if (VT == MVT::i16) { 9899 MVT NVT = MVT::i32; 9900 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9901 9902 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9903 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9904 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9905 9906 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9907 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9908 } 9909 9910 return SDValue(); 9911 } 9912 9913 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9914 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9915 return C; 9916 9917 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9918 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9919 return C; 9920 } 9921 9922 return nullptr; 9923 } 9924 9925 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9926 const SDLoc &SL, 9927 SDValue Op0, 9928 SDValue Op1) const { 9929 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9930 if (!K1) 9931 return SDValue(); 9932 9933 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9934 if (!K0) 9935 return SDValue(); 9936 9937 // Ordered >= (although NaN inputs should have folded away by now). 9938 if (K0->getValueAPF() > K1->getValueAPF()) 9939 return SDValue(); 9940 9941 const MachineFunction &MF = DAG.getMachineFunction(); 9942 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9943 9944 // TODO: Check IEEE bit enabled? 9945 EVT VT = Op0.getValueType(); 9946 if (Info->getMode().DX10Clamp) { 9947 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9948 // hardware fmed3 behavior converting to a min. 9949 // FIXME: Should this be allowing -0.0? 9950 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9951 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9952 } 9953 9954 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9955 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9956 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9957 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9958 // then give the other result, which is different from med3 with a NaN 9959 // input. 9960 SDValue Var = Op0.getOperand(0); 9961 if (!DAG.isKnownNeverSNaN(Var)) 9962 return SDValue(); 9963 9964 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9965 9966 if ((!K0->hasOneUse() || 9967 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9968 (!K1->hasOneUse() || 9969 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9970 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9971 Var, SDValue(K0, 0), SDValue(K1, 0)); 9972 } 9973 } 9974 9975 return SDValue(); 9976 } 9977 9978 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9979 DAGCombinerInfo &DCI) const { 9980 SelectionDAG &DAG = DCI.DAG; 9981 9982 EVT VT = N->getValueType(0); 9983 unsigned Opc = N->getOpcode(); 9984 SDValue Op0 = N->getOperand(0); 9985 SDValue Op1 = N->getOperand(1); 9986 9987 // Only do this if the inner op has one use since this will just increases 9988 // register pressure for no benefit. 9989 9990 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9991 !VT.isVector() && 9992 (VT == MVT::i32 || VT == MVT::f32 || 9993 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9994 // max(max(a, b), c) -> max3(a, b, c) 9995 // min(min(a, b), c) -> min3(a, b, c) 9996 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9997 SDLoc DL(N); 9998 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9999 DL, 10000 N->getValueType(0), 10001 Op0.getOperand(0), 10002 Op0.getOperand(1), 10003 Op1); 10004 } 10005 10006 // Try commuted. 10007 // max(a, max(b, c)) -> max3(a, b, c) 10008 // min(a, min(b, c)) -> min3(a, b, c) 10009 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 10010 SDLoc DL(N); 10011 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10012 DL, 10013 N->getValueType(0), 10014 Op0, 10015 Op1.getOperand(0), 10016 Op1.getOperand(1)); 10017 } 10018 } 10019 10020 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 10021 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 10022 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 10023 return Med3; 10024 } 10025 10026 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 10027 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 10028 return Med3; 10029 } 10030 10031 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 10032 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 10033 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 10034 (Opc == AMDGPUISD::FMIN_LEGACY && 10035 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 10036 (VT == MVT::f32 || VT == MVT::f64 || 10037 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 10038 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 10039 Op0.hasOneUse()) { 10040 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 10041 return Res; 10042 } 10043 10044 return SDValue(); 10045 } 10046 10047 static bool isClampZeroToOne(SDValue A, SDValue B) { 10048 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 10049 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 10050 // FIXME: Should this be allowing -0.0? 10051 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 10052 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 10053 } 10054 } 10055 10056 return false; 10057 } 10058 10059 // FIXME: Should only worry about snans for version with chain. 10060 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10061 DAGCombinerInfo &DCI) const { 10062 EVT VT = N->getValueType(0); 10063 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10064 // NaNs. With a NaN input, the order of the operands may change the result. 10065 10066 SelectionDAG &DAG = DCI.DAG; 10067 SDLoc SL(N); 10068 10069 SDValue Src0 = N->getOperand(0); 10070 SDValue Src1 = N->getOperand(1); 10071 SDValue Src2 = N->getOperand(2); 10072 10073 if (isClampZeroToOne(Src0, Src1)) { 10074 // const_a, const_b, x -> clamp is safe in all cases including signaling 10075 // nans. 10076 // FIXME: Should this be allowing -0.0? 10077 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10078 } 10079 10080 const MachineFunction &MF = DAG.getMachineFunction(); 10081 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10082 10083 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10084 // handling no dx10-clamp? 10085 if (Info->getMode().DX10Clamp) { 10086 // If NaNs is clamped to 0, we are free to reorder the inputs. 10087 10088 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10089 std::swap(Src0, Src1); 10090 10091 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10092 std::swap(Src1, Src2); 10093 10094 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10095 std::swap(Src0, Src1); 10096 10097 if (isClampZeroToOne(Src1, Src2)) 10098 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10099 } 10100 10101 return SDValue(); 10102 } 10103 10104 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10105 DAGCombinerInfo &DCI) const { 10106 SDValue Src0 = N->getOperand(0); 10107 SDValue Src1 = N->getOperand(1); 10108 if (Src0.isUndef() && Src1.isUndef()) 10109 return DCI.DAG.getUNDEF(N->getValueType(0)); 10110 return SDValue(); 10111 } 10112 10113 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10114 // expanded into a set of cmp/select instructions. 10115 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10116 unsigned NumElem, 10117 bool IsDivergentIdx) { 10118 if (UseDivergentRegisterIndexing) 10119 return false; 10120 10121 unsigned VecSize = EltSize * NumElem; 10122 10123 // Sub-dword vectors of size 2 dword or less have better implementation. 10124 if (VecSize <= 64 && EltSize < 32) 10125 return false; 10126 10127 // Always expand the rest of sub-dword instructions, otherwise it will be 10128 // lowered via memory. 10129 if (EltSize < 32) 10130 return true; 10131 10132 // Always do this if var-idx is divergent, otherwise it will become a loop. 10133 if (IsDivergentIdx) 10134 return true; 10135 10136 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10137 unsigned NumInsts = NumElem /* Number of compares */ + 10138 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10139 return NumInsts <= 16; 10140 } 10141 10142 static bool shouldExpandVectorDynExt(SDNode *N) { 10143 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10144 if (isa<ConstantSDNode>(Idx)) 10145 return false; 10146 10147 SDValue Vec = N->getOperand(0); 10148 EVT VecVT = Vec.getValueType(); 10149 EVT EltVT = VecVT.getVectorElementType(); 10150 unsigned EltSize = EltVT.getSizeInBits(); 10151 unsigned NumElem = VecVT.getVectorNumElements(); 10152 10153 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10154 Idx->isDivergent()); 10155 } 10156 10157 SDValue SITargetLowering::performExtractVectorEltCombine( 10158 SDNode *N, DAGCombinerInfo &DCI) const { 10159 SDValue Vec = N->getOperand(0); 10160 SelectionDAG &DAG = DCI.DAG; 10161 10162 EVT VecVT = Vec.getValueType(); 10163 EVT EltVT = VecVT.getVectorElementType(); 10164 10165 if ((Vec.getOpcode() == ISD::FNEG || 10166 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10167 SDLoc SL(N); 10168 EVT EltVT = N->getValueType(0); 10169 SDValue Idx = N->getOperand(1); 10170 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10171 Vec.getOperand(0), Idx); 10172 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10173 } 10174 10175 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10176 // => 10177 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10178 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10179 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10180 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10181 SDLoc SL(N); 10182 EVT EltVT = N->getValueType(0); 10183 SDValue Idx = N->getOperand(1); 10184 unsigned Opc = Vec.getOpcode(); 10185 10186 switch(Opc) { 10187 default: 10188 break; 10189 // TODO: Support other binary operations. 10190 case ISD::FADD: 10191 case ISD::FSUB: 10192 case ISD::FMUL: 10193 case ISD::ADD: 10194 case ISD::UMIN: 10195 case ISD::UMAX: 10196 case ISD::SMIN: 10197 case ISD::SMAX: 10198 case ISD::FMAXNUM: 10199 case ISD::FMINNUM: 10200 case ISD::FMAXNUM_IEEE: 10201 case ISD::FMINNUM_IEEE: { 10202 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10203 Vec.getOperand(0), Idx); 10204 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10205 Vec.getOperand(1), Idx); 10206 10207 DCI.AddToWorklist(Elt0.getNode()); 10208 DCI.AddToWorklist(Elt1.getNode()); 10209 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10210 } 10211 } 10212 } 10213 10214 unsigned VecSize = VecVT.getSizeInBits(); 10215 unsigned EltSize = EltVT.getSizeInBits(); 10216 10217 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10218 if (::shouldExpandVectorDynExt(N)) { 10219 SDLoc SL(N); 10220 SDValue Idx = N->getOperand(1); 10221 SDValue V; 10222 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10223 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10224 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10225 if (I == 0) 10226 V = Elt; 10227 else 10228 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10229 } 10230 return V; 10231 } 10232 10233 if (!DCI.isBeforeLegalize()) 10234 return SDValue(); 10235 10236 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10237 // elements. This exposes more load reduction opportunities by replacing 10238 // multiple small extract_vector_elements with a single 32-bit extract. 10239 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10240 if (isa<MemSDNode>(Vec) && 10241 EltSize <= 16 && 10242 EltVT.isByteSized() && 10243 VecSize > 32 && 10244 VecSize % 32 == 0 && 10245 Idx) { 10246 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10247 10248 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10249 unsigned EltIdx = BitIndex / 32; 10250 unsigned LeftoverBitIdx = BitIndex % 32; 10251 SDLoc SL(N); 10252 10253 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10254 DCI.AddToWorklist(Cast.getNode()); 10255 10256 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10257 DAG.getConstant(EltIdx, SL, MVT::i32)); 10258 DCI.AddToWorklist(Elt.getNode()); 10259 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10260 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10261 DCI.AddToWorklist(Srl.getNode()); 10262 10263 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10264 DCI.AddToWorklist(Trunc.getNode()); 10265 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10266 } 10267 10268 return SDValue(); 10269 } 10270 10271 SDValue 10272 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10273 DAGCombinerInfo &DCI) const { 10274 SDValue Vec = N->getOperand(0); 10275 SDValue Idx = N->getOperand(2); 10276 EVT VecVT = Vec.getValueType(); 10277 EVT EltVT = VecVT.getVectorElementType(); 10278 10279 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10280 // => BUILD_VECTOR n x select (e, const-idx) 10281 if (!::shouldExpandVectorDynExt(N)) 10282 return SDValue(); 10283 10284 SelectionDAG &DAG = DCI.DAG; 10285 SDLoc SL(N); 10286 SDValue Ins = N->getOperand(1); 10287 EVT IdxVT = Idx.getValueType(); 10288 10289 SmallVector<SDValue, 16> Ops; 10290 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10291 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10292 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10293 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10294 Ops.push_back(V); 10295 } 10296 10297 return DAG.getBuildVector(VecVT, SL, Ops); 10298 } 10299 10300 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10301 const SDNode *N0, 10302 const SDNode *N1) const { 10303 EVT VT = N0->getValueType(0); 10304 10305 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10306 // support denormals ever. 10307 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10308 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10309 getSubtarget()->hasMadF16())) && 10310 isOperationLegal(ISD::FMAD, VT)) 10311 return ISD::FMAD; 10312 10313 const TargetOptions &Options = DAG.getTarget().Options; 10314 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10315 (N0->getFlags().hasAllowContract() && 10316 N1->getFlags().hasAllowContract())) && 10317 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10318 return ISD::FMA; 10319 } 10320 10321 return 0; 10322 } 10323 10324 // For a reassociatable opcode perform: 10325 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10326 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10327 SelectionDAG &DAG) const { 10328 EVT VT = N->getValueType(0); 10329 if (VT != MVT::i32 && VT != MVT::i64) 10330 return SDValue(); 10331 10332 unsigned Opc = N->getOpcode(); 10333 SDValue Op0 = N->getOperand(0); 10334 SDValue Op1 = N->getOperand(1); 10335 10336 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10337 return SDValue(); 10338 10339 if (Op0->isDivergent()) 10340 std::swap(Op0, Op1); 10341 10342 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10343 return SDValue(); 10344 10345 SDValue Op2 = Op1.getOperand(1); 10346 Op1 = Op1.getOperand(0); 10347 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10348 return SDValue(); 10349 10350 if (Op1->isDivergent()) 10351 std::swap(Op1, Op2); 10352 10353 // If either operand is constant this will conflict with 10354 // DAGCombiner::ReassociateOps(). 10355 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10356 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10357 return SDValue(); 10358 10359 SDLoc SL(N); 10360 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10361 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10362 } 10363 10364 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10365 EVT VT, 10366 SDValue N0, SDValue N1, SDValue N2, 10367 bool Signed) { 10368 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10369 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10370 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10371 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10372 } 10373 10374 SDValue SITargetLowering::performAddCombine(SDNode *N, 10375 DAGCombinerInfo &DCI) const { 10376 SelectionDAG &DAG = DCI.DAG; 10377 EVT VT = N->getValueType(0); 10378 SDLoc SL(N); 10379 SDValue LHS = N->getOperand(0); 10380 SDValue RHS = N->getOperand(1); 10381 10382 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10383 && Subtarget->hasMad64_32() && 10384 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10385 VT.getScalarSizeInBits() <= 64) { 10386 if (LHS.getOpcode() != ISD::MUL) 10387 std::swap(LHS, RHS); 10388 10389 SDValue MulLHS = LHS.getOperand(0); 10390 SDValue MulRHS = LHS.getOperand(1); 10391 SDValue AddRHS = RHS; 10392 10393 // TODO: Maybe restrict if SGPR inputs. 10394 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10395 numBitsUnsigned(MulRHS, DAG) <= 32) { 10396 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10397 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10398 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10399 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10400 } 10401 10402 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10403 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10404 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10405 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10406 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10407 } 10408 10409 return SDValue(); 10410 } 10411 10412 if (SDValue V = reassociateScalarOps(N, DAG)) { 10413 return V; 10414 } 10415 10416 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10417 return SDValue(); 10418 10419 // add x, zext (setcc) => addcarry x, 0, setcc 10420 // add x, sext (setcc) => subcarry x, 0, setcc 10421 unsigned Opc = LHS.getOpcode(); 10422 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10423 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10424 std::swap(RHS, LHS); 10425 10426 Opc = RHS.getOpcode(); 10427 switch (Opc) { 10428 default: break; 10429 case ISD::ZERO_EXTEND: 10430 case ISD::SIGN_EXTEND: 10431 case ISD::ANY_EXTEND: { 10432 auto Cond = RHS.getOperand(0); 10433 // If this won't be a real VOPC output, we would still need to insert an 10434 // extra instruction anyway. 10435 if (!isBoolSGPR(Cond)) 10436 break; 10437 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10438 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10439 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10440 return DAG.getNode(Opc, SL, VTList, Args); 10441 } 10442 case ISD::ADDCARRY: { 10443 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10444 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10445 if (!C || C->getZExtValue() != 0) break; 10446 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10447 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10448 } 10449 } 10450 return SDValue(); 10451 } 10452 10453 SDValue SITargetLowering::performSubCombine(SDNode *N, 10454 DAGCombinerInfo &DCI) const { 10455 SelectionDAG &DAG = DCI.DAG; 10456 EVT VT = N->getValueType(0); 10457 10458 if (VT != MVT::i32) 10459 return SDValue(); 10460 10461 SDLoc SL(N); 10462 SDValue LHS = N->getOperand(0); 10463 SDValue RHS = N->getOperand(1); 10464 10465 // sub x, zext (setcc) => subcarry x, 0, setcc 10466 // sub x, sext (setcc) => addcarry x, 0, setcc 10467 unsigned Opc = RHS.getOpcode(); 10468 switch (Opc) { 10469 default: break; 10470 case ISD::ZERO_EXTEND: 10471 case ISD::SIGN_EXTEND: 10472 case ISD::ANY_EXTEND: { 10473 auto Cond = RHS.getOperand(0); 10474 // If this won't be a real VOPC output, we would still need to insert an 10475 // extra instruction anyway. 10476 if (!isBoolSGPR(Cond)) 10477 break; 10478 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10479 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10480 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10481 return DAG.getNode(Opc, SL, VTList, Args); 10482 } 10483 } 10484 10485 if (LHS.getOpcode() == ISD::SUBCARRY) { 10486 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10487 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10488 if (!C || !C->isNullValue()) 10489 return SDValue(); 10490 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10491 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10492 } 10493 return SDValue(); 10494 } 10495 10496 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10497 DAGCombinerInfo &DCI) const { 10498 10499 if (N->getValueType(0) != MVT::i32) 10500 return SDValue(); 10501 10502 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10503 if (!C || C->getZExtValue() != 0) 10504 return SDValue(); 10505 10506 SelectionDAG &DAG = DCI.DAG; 10507 SDValue LHS = N->getOperand(0); 10508 10509 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10510 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10511 unsigned LHSOpc = LHS.getOpcode(); 10512 unsigned Opc = N->getOpcode(); 10513 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10514 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10515 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10516 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10517 } 10518 return SDValue(); 10519 } 10520 10521 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10522 DAGCombinerInfo &DCI) const { 10523 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10524 return SDValue(); 10525 10526 SelectionDAG &DAG = DCI.DAG; 10527 EVT VT = N->getValueType(0); 10528 10529 SDLoc SL(N); 10530 SDValue LHS = N->getOperand(0); 10531 SDValue RHS = N->getOperand(1); 10532 10533 // These should really be instruction patterns, but writing patterns with 10534 // source modiifiers is a pain. 10535 10536 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10537 if (LHS.getOpcode() == ISD::FADD) { 10538 SDValue A = LHS.getOperand(0); 10539 if (A == LHS.getOperand(1)) { 10540 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10541 if (FusedOp != 0) { 10542 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10543 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10544 } 10545 } 10546 } 10547 10548 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10549 if (RHS.getOpcode() == ISD::FADD) { 10550 SDValue A = RHS.getOperand(0); 10551 if (A == RHS.getOperand(1)) { 10552 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10553 if (FusedOp != 0) { 10554 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10555 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10556 } 10557 } 10558 } 10559 10560 return SDValue(); 10561 } 10562 10563 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10564 DAGCombinerInfo &DCI) const { 10565 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10566 return SDValue(); 10567 10568 SelectionDAG &DAG = DCI.DAG; 10569 SDLoc SL(N); 10570 EVT VT = N->getValueType(0); 10571 assert(!VT.isVector()); 10572 10573 // Try to get the fneg to fold into the source modifier. This undoes generic 10574 // DAG combines and folds them into the mad. 10575 // 10576 // Only do this if we are not trying to support denormals. v_mad_f32 does 10577 // not support denormals ever. 10578 SDValue LHS = N->getOperand(0); 10579 SDValue RHS = N->getOperand(1); 10580 if (LHS.getOpcode() == ISD::FADD) { 10581 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10582 SDValue A = LHS.getOperand(0); 10583 if (A == LHS.getOperand(1)) { 10584 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10585 if (FusedOp != 0){ 10586 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10587 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10588 10589 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10590 } 10591 } 10592 } 10593 10594 if (RHS.getOpcode() == ISD::FADD) { 10595 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10596 10597 SDValue A = RHS.getOperand(0); 10598 if (A == RHS.getOperand(1)) { 10599 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10600 if (FusedOp != 0){ 10601 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10602 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10603 } 10604 } 10605 } 10606 10607 return SDValue(); 10608 } 10609 10610 SDValue SITargetLowering::performFMACombine(SDNode *N, 10611 DAGCombinerInfo &DCI) const { 10612 SelectionDAG &DAG = DCI.DAG; 10613 EVT VT = N->getValueType(0); 10614 SDLoc SL(N); 10615 10616 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 10617 return SDValue(); 10618 10619 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10620 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10621 SDValue Op1 = N->getOperand(0); 10622 SDValue Op2 = N->getOperand(1); 10623 SDValue FMA = N->getOperand(2); 10624 10625 if (FMA.getOpcode() != ISD::FMA || 10626 Op1.getOpcode() != ISD::FP_EXTEND || 10627 Op2.getOpcode() != ISD::FP_EXTEND) 10628 return SDValue(); 10629 10630 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10631 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10632 // is sufficient to allow generaing fdot2. 10633 const TargetOptions &Options = DAG.getTarget().Options; 10634 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10635 (N->getFlags().hasAllowContract() && 10636 FMA->getFlags().hasAllowContract())) { 10637 Op1 = Op1.getOperand(0); 10638 Op2 = Op2.getOperand(0); 10639 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10640 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10641 return SDValue(); 10642 10643 SDValue Vec1 = Op1.getOperand(0); 10644 SDValue Idx1 = Op1.getOperand(1); 10645 SDValue Vec2 = Op2.getOperand(0); 10646 10647 SDValue FMAOp1 = FMA.getOperand(0); 10648 SDValue FMAOp2 = FMA.getOperand(1); 10649 SDValue FMAAcc = FMA.getOperand(2); 10650 10651 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10652 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10653 return SDValue(); 10654 10655 FMAOp1 = FMAOp1.getOperand(0); 10656 FMAOp2 = FMAOp2.getOperand(0); 10657 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10658 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10659 return SDValue(); 10660 10661 SDValue Vec3 = FMAOp1.getOperand(0); 10662 SDValue Vec4 = FMAOp2.getOperand(0); 10663 SDValue Idx2 = FMAOp1.getOperand(1); 10664 10665 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10666 // Idx1 and Idx2 cannot be the same. 10667 Idx1 == Idx2) 10668 return SDValue(); 10669 10670 if (Vec1 == Vec2 || Vec3 == Vec4) 10671 return SDValue(); 10672 10673 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10674 return SDValue(); 10675 10676 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10677 (Vec1 == Vec4 && Vec2 == Vec3)) { 10678 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10679 DAG.getTargetConstant(0, SL, MVT::i1)); 10680 } 10681 } 10682 return SDValue(); 10683 } 10684 10685 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10686 DAGCombinerInfo &DCI) const { 10687 SelectionDAG &DAG = DCI.DAG; 10688 SDLoc SL(N); 10689 10690 SDValue LHS = N->getOperand(0); 10691 SDValue RHS = N->getOperand(1); 10692 EVT VT = LHS.getValueType(); 10693 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10694 10695 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10696 if (!CRHS) { 10697 CRHS = dyn_cast<ConstantSDNode>(LHS); 10698 if (CRHS) { 10699 std::swap(LHS, RHS); 10700 CC = getSetCCSwappedOperands(CC); 10701 } 10702 } 10703 10704 if (CRHS) { 10705 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10706 isBoolSGPR(LHS.getOperand(0))) { 10707 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10708 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10709 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10710 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10711 if ((CRHS->isAllOnesValue() && 10712 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10713 (CRHS->isNullValue() && 10714 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10715 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10716 DAG.getConstant(-1, SL, MVT::i1)); 10717 if ((CRHS->isAllOnesValue() && 10718 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10719 (CRHS->isNullValue() && 10720 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10721 return LHS.getOperand(0); 10722 } 10723 10724 uint64_t CRHSVal = CRHS->getZExtValue(); 10725 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10726 LHS.getOpcode() == ISD::SELECT && 10727 isa<ConstantSDNode>(LHS.getOperand(1)) && 10728 isa<ConstantSDNode>(LHS.getOperand(2)) && 10729 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10730 isBoolSGPR(LHS.getOperand(0))) { 10731 // Given CT != FT: 10732 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10733 // setcc (select cc, CT, CF), CF, ne => cc 10734 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10735 // setcc (select cc, CT, CF), CT, eq => cc 10736 uint64_t CT = LHS.getConstantOperandVal(1); 10737 uint64_t CF = LHS.getConstantOperandVal(2); 10738 10739 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10740 (CT == CRHSVal && CC == ISD::SETNE)) 10741 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10742 DAG.getConstant(-1, SL, MVT::i1)); 10743 if ((CF == CRHSVal && CC == ISD::SETNE) || 10744 (CT == CRHSVal && CC == ISD::SETEQ)) 10745 return LHS.getOperand(0); 10746 } 10747 } 10748 10749 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10750 VT != MVT::f16)) 10751 return SDValue(); 10752 10753 // Match isinf/isfinite pattern 10754 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10755 // (fcmp one (fabs x), inf) -> (fp_class x, 10756 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10757 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10758 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10759 if (!CRHS) 10760 return SDValue(); 10761 10762 const APFloat &APF = CRHS->getValueAPF(); 10763 if (APF.isInfinity() && !APF.isNegative()) { 10764 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10765 SIInstrFlags::N_INFINITY; 10766 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10767 SIInstrFlags::P_ZERO | 10768 SIInstrFlags::N_NORMAL | 10769 SIInstrFlags::P_NORMAL | 10770 SIInstrFlags::N_SUBNORMAL | 10771 SIInstrFlags::P_SUBNORMAL; 10772 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10773 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10774 DAG.getConstant(Mask, SL, MVT::i32)); 10775 } 10776 } 10777 10778 return SDValue(); 10779 } 10780 10781 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10782 DAGCombinerInfo &DCI) const { 10783 SelectionDAG &DAG = DCI.DAG; 10784 SDLoc SL(N); 10785 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10786 10787 SDValue Src = N->getOperand(0); 10788 SDValue Shift = N->getOperand(0); 10789 10790 // TODO: Extend type shouldn't matter (assuming legal types). 10791 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10792 Shift = Shift.getOperand(0); 10793 10794 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10795 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10796 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10797 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10798 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10799 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10800 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10801 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10802 SDLoc(Shift.getOperand(0)), MVT::i32); 10803 10804 unsigned ShiftOffset = 8 * Offset; 10805 if (Shift.getOpcode() == ISD::SHL) 10806 ShiftOffset -= C->getZExtValue(); 10807 else 10808 ShiftOffset += C->getZExtValue(); 10809 10810 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10811 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10812 MVT::f32, Shift); 10813 } 10814 } 10815 } 10816 10817 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10818 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10819 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10820 // We simplified Src. If this node is not dead, visit it again so it is 10821 // folded properly. 10822 if (N->getOpcode() != ISD::DELETED_NODE) 10823 DCI.AddToWorklist(N); 10824 return SDValue(N, 0); 10825 } 10826 10827 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10828 if (SDValue DemandedSrc = 10829 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10830 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10831 10832 return SDValue(); 10833 } 10834 10835 SDValue SITargetLowering::performClampCombine(SDNode *N, 10836 DAGCombinerInfo &DCI) const { 10837 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10838 if (!CSrc) 10839 return SDValue(); 10840 10841 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10842 const APFloat &F = CSrc->getValueAPF(); 10843 APFloat Zero = APFloat::getZero(F.getSemantics()); 10844 if (F < Zero || 10845 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10846 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10847 } 10848 10849 APFloat One(F.getSemantics(), "1.0"); 10850 if (F > One) 10851 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10852 10853 return SDValue(CSrc, 0); 10854 } 10855 10856 10857 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10858 DAGCombinerInfo &DCI) const { 10859 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10860 return SDValue(); 10861 switch (N->getOpcode()) { 10862 case ISD::ADD: 10863 return performAddCombine(N, DCI); 10864 case ISD::SUB: 10865 return performSubCombine(N, DCI); 10866 case ISD::ADDCARRY: 10867 case ISD::SUBCARRY: 10868 return performAddCarrySubCarryCombine(N, DCI); 10869 case ISD::FADD: 10870 return performFAddCombine(N, DCI); 10871 case ISD::FSUB: 10872 return performFSubCombine(N, DCI); 10873 case ISD::SETCC: 10874 return performSetCCCombine(N, DCI); 10875 case ISD::FMAXNUM: 10876 case ISD::FMINNUM: 10877 case ISD::FMAXNUM_IEEE: 10878 case ISD::FMINNUM_IEEE: 10879 case ISD::SMAX: 10880 case ISD::SMIN: 10881 case ISD::UMAX: 10882 case ISD::UMIN: 10883 case AMDGPUISD::FMIN_LEGACY: 10884 case AMDGPUISD::FMAX_LEGACY: 10885 return performMinMaxCombine(N, DCI); 10886 case ISD::FMA: 10887 return performFMACombine(N, DCI); 10888 case ISD::AND: 10889 return performAndCombine(N, DCI); 10890 case ISD::OR: 10891 return performOrCombine(N, DCI); 10892 case ISD::XOR: 10893 return performXorCombine(N, DCI); 10894 case ISD::ZERO_EXTEND: 10895 return performZeroExtendCombine(N, DCI); 10896 case ISD::SIGN_EXTEND_INREG: 10897 return performSignExtendInRegCombine(N , DCI); 10898 case AMDGPUISD::FP_CLASS: 10899 return performClassCombine(N, DCI); 10900 case ISD::FCANONICALIZE: 10901 return performFCanonicalizeCombine(N, DCI); 10902 case AMDGPUISD::RCP: 10903 return performRcpCombine(N, DCI); 10904 case AMDGPUISD::FRACT: 10905 case AMDGPUISD::RSQ: 10906 case AMDGPUISD::RCP_LEGACY: 10907 case AMDGPUISD::RCP_IFLAG: 10908 case AMDGPUISD::RSQ_CLAMP: 10909 case AMDGPUISD::LDEXP: { 10910 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10911 SDValue Src = N->getOperand(0); 10912 if (Src.isUndef()) 10913 return Src; 10914 break; 10915 } 10916 case ISD::SINT_TO_FP: 10917 case ISD::UINT_TO_FP: 10918 return performUCharToFloatCombine(N, DCI); 10919 case AMDGPUISD::CVT_F32_UBYTE0: 10920 case AMDGPUISD::CVT_F32_UBYTE1: 10921 case AMDGPUISD::CVT_F32_UBYTE2: 10922 case AMDGPUISD::CVT_F32_UBYTE3: 10923 return performCvtF32UByteNCombine(N, DCI); 10924 case AMDGPUISD::FMED3: 10925 return performFMed3Combine(N, DCI); 10926 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10927 return performCvtPkRTZCombine(N, DCI); 10928 case AMDGPUISD::CLAMP: 10929 return performClampCombine(N, DCI); 10930 case ISD::SCALAR_TO_VECTOR: { 10931 SelectionDAG &DAG = DCI.DAG; 10932 EVT VT = N->getValueType(0); 10933 10934 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10935 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10936 SDLoc SL(N); 10937 SDValue Src = N->getOperand(0); 10938 EVT EltVT = Src.getValueType(); 10939 if (EltVT == MVT::f16) 10940 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10941 10942 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10943 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10944 } 10945 10946 break; 10947 } 10948 case ISD::EXTRACT_VECTOR_ELT: 10949 return performExtractVectorEltCombine(N, DCI); 10950 case ISD::INSERT_VECTOR_ELT: 10951 return performInsertVectorEltCombine(N, DCI); 10952 case ISD::LOAD: { 10953 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10954 return Widended; 10955 LLVM_FALLTHROUGH; 10956 } 10957 default: { 10958 if (!DCI.isBeforeLegalize()) { 10959 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 10960 return performMemSDNodeCombine(MemNode, DCI); 10961 } 10962 10963 break; 10964 } 10965 } 10966 10967 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10968 } 10969 10970 /// Helper function for adjustWritemask 10971 static unsigned SubIdx2Lane(unsigned Idx) { 10972 switch (Idx) { 10973 default: return ~0u; 10974 case AMDGPU::sub0: return 0; 10975 case AMDGPU::sub1: return 1; 10976 case AMDGPU::sub2: return 2; 10977 case AMDGPU::sub3: return 3; 10978 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10979 } 10980 } 10981 10982 /// Adjust the writemask of MIMG instructions 10983 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10984 SelectionDAG &DAG) const { 10985 unsigned Opcode = Node->getMachineOpcode(); 10986 10987 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10988 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10989 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10990 return Node; // not implemented for D16 10991 10992 SDNode *Users[5] = { nullptr }; 10993 unsigned Lane = 0; 10994 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10995 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10996 unsigned NewDmask = 0; 10997 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10998 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10999 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 11000 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 11001 unsigned TFCLane = 0; 11002 bool HasChain = Node->getNumValues() > 1; 11003 11004 if (OldDmask == 0) { 11005 // These are folded out, but on the chance it happens don't assert. 11006 return Node; 11007 } 11008 11009 unsigned OldBitsSet = countPopulation(OldDmask); 11010 // Work out which is the TFE/LWE lane if that is enabled. 11011 if (UsesTFC) { 11012 TFCLane = OldBitsSet; 11013 } 11014 11015 // Try to figure out the used register components 11016 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 11017 I != E; ++I) { 11018 11019 // Don't look at users of the chain. 11020 if (I.getUse().getResNo() != 0) 11021 continue; 11022 11023 // Abort if we can't understand the usage 11024 if (!I->isMachineOpcode() || 11025 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 11026 return Node; 11027 11028 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 11029 // Note that subregs are packed, i.e. Lane==0 is the first bit set 11030 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 11031 // set, etc. 11032 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 11033 if (Lane == ~0u) 11034 return Node; 11035 11036 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 11037 if (UsesTFC && Lane == TFCLane) { 11038 Users[Lane] = *I; 11039 } else { 11040 // Set which texture component corresponds to the lane. 11041 unsigned Comp; 11042 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 11043 Comp = countTrailingZeros(Dmask); 11044 Dmask &= ~(1 << Comp); 11045 } 11046 11047 // Abort if we have more than one user per component. 11048 if (Users[Lane]) 11049 return Node; 11050 11051 Users[Lane] = *I; 11052 NewDmask |= 1 << Comp; 11053 } 11054 } 11055 11056 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11057 bool NoChannels = !NewDmask; 11058 if (NoChannels) { 11059 if (!UsesTFC) { 11060 // No uses of the result and not using TFC. Then do nothing. 11061 return Node; 11062 } 11063 // If the original dmask has one channel - then nothing to do 11064 if (OldBitsSet == 1) 11065 return Node; 11066 // Use an arbitrary dmask - required for the instruction to work 11067 NewDmask = 1; 11068 } 11069 // Abort if there's no change 11070 if (NewDmask == OldDmask) 11071 return Node; 11072 11073 unsigned BitsSet = countPopulation(NewDmask); 11074 11075 // Check for TFE or LWE - increase the number of channels by one to account 11076 // for the extra return value 11077 // This will need adjustment for D16 if this is also included in 11078 // adjustWriteMask (this function) but at present D16 are excluded. 11079 unsigned NewChannels = BitsSet + UsesTFC; 11080 11081 int NewOpcode = 11082 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11083 assert(NewOpcode != -1 && 11084 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11085 "failed to find equivalent MIMG op"); 11086 11087 // Adjust the writemask in the node 11088 SmallVector<SDValue, 12> Ops; 11089 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11090 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11091 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11092 11093 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11094 11095 MVT ResultVT = NewChannels == 1 ? 11096 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11097 NewChannels == 5 ? 8 : NewChannels); 11098 SDVTList NewVTList = HasChain ? 11099 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11100 11101 11102 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11103 NewVTList, Ops); 11104 11105 if (HasChain) { 11106 // Update chain. 11107 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11108 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11109 } 11110 11111 if (NewChannels == 1) { 11112 assert(Node->hasNUsesOfValue(1, 0)); 11113 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11114 SDLoc(Node), Users[Lane]->getValueType(0), 11115 SDValue(NewNode, 0)); 11116 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11117 return nullptr; 11118 } 11119 11120 // Update the users of the node with the new indices 11121 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11122 SDNode *User = Users[i]; 11123 if (!User) { 11124 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11125 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11126 if (i || !NoChannels) 11127 continue; 11128 } else { 11129 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11130 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11131 } 11132 11133 switch (Idx) { 11134 default: break; 11135 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11136 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11137 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11138 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11139 } 11140 } 11141 11142 DAG.RemoveDeadNode(Node); 11143 return nullptr; 11144 } 11145 11146 static bool isFrameIndexOp(SDValue Op) { 11147 if (Op.getOpcode() == ISD::AssertZext) 11148 Op = Op.getOperand(0); 11149 11150 return isa<FrameIndexSDNode>(Op); 11151 } 11152 11153 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11154 /// with frame index operands. 11155 /// LLVM assumes that inputs are to these instructions are registers. 11156 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11157 SelectionDAG &DAG) const { 11158 if (Node->getOpcode() == ISD::CopyToReg) { 11159 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11160 SDValue SrcVal = Node->getOperand(2); 11161 11162 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11163 // to try understanding copies to physical registers. 11164 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11165 SDLoc SL(Node); 11166 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11167 SDValue VReg = DAG.getRegister( 11168 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11169 11170 SDNode *Glued = Node->getGluedNode(); 11171 SDValue ToVReg 11172 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11173 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11174 SDValue ToResultReg 11175 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11176 VReg, ToVReg.getValue(1)); 11177 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11178 DAG.RemoveDeadNode(Node); 11179 return ToResultReg.getNode(); 11180 } 11181 } 11182 11183 SmallVector<SDValue, 8> Ops; 11184 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11185 if (!isFrameIndexOp(Node->getOperand(i))) { 11186 Ops.push_back(Node->getOperand(i)); 11187 continue; 11188 } 11189 11190 SDLoc DL(Node); 11191 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11192 Node->getOperand(i).getValueType(), 11193 Node->getOperand(i)), 0)); 11194 } 11195 11196 return DAG.UpdateNodeOperands(Node, Ops); 11197 } 11198 11199 /// Fold the instructions after selecting them. 11200 /// Returns null if users were already updated. 11201 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11202 SelectionDAG &DAG) const { 11203 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11204 unsigned Opcode = Node->getMachineOpcode(); 11205 11206 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11207 !TII->isGather4(Opcode) && 11208 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11209 return adjustWritemask(Node, DAG); 11210 } 11211 11212 if (Opcode == AMDGPU::INSERT_SUBREG || 11213 Opcode == AMDGPU::REG_SEQUENCE) { 11214 legalizeTargetIndependentNode(Node, DAG); 11215 return Node; 11216 } 11217 11218 switch (Opcode) { 11219 case AMDGPU::V_DIV_SCALE_F32_e64: 11220 case AMDGPU::V_DIV_SCALE_F64_e64: { 11221 // Satisfy the operand register constraint when one of the inputs is 11222 // undefined. Ordinarily each undef value will have its own implicit_def of 11223 // a vreg, so force these to use a single register. 11224 SDValue Src0 = Node->getOperand(1); 11225 SDValue Src1 = Node->getOperand(3); 11226 SDValue Src2 = Node->getOperand(5); 11227 11228 if ((Src0.isMachineOpcode() && 11229 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11230 (Src0 == Src1 || Src0 == Src2)) 11231 break; 11232 11233 MVT VT = Src0.getValueType().getSimpleVT(); 11234 const TargetRegisterClass *RC = 11235 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11236 11237 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11238 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11239 11240 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11241 UndefReg, Src0, SDValue()); 11242 11243 // src0 must be the same register as src1 or src2, even if the value is 11244 // undefined, so make sure we don't violate this constraint. 11245 if (Src0.isMachineOpcode() && 11246 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11247 if (Src1.isMachineOpcode() && 11248 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11249 Src0 = Src1; 11250 else if (Src2.isMachineOpcode() && 11251 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11252 Src0 = Src2; 11253 else { 11254 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11255 Src0 = UndefReg; 11256 Src1 = UndefReg; 11257 } 11258 } else 11259 break; 11260 11261 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11262 Ops[1] = Src0; 11263 Ops[3] = Src1; 11264 Ops[5] = Src2; 11265 Ops.push_back(ImpDef.getValue(1)); 11266 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11267 } 11268 default: 11269 break; 11270 } 11271 11272 return Node; 11273 } 11274 11275 // Any MIMG instructions that use tfe or lwe require an initialization of the 11276 // result register that will be written in the case of a memory access failure. 11277 // The required code is also added to tie this init code to the result of the 11278 // img instruction. 11279 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11280 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11281 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11282 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11283 MachineBasicBlock &MBB = *MI.getParent(); 11284 11285 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11286 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11287 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11288 11289 if (!TFE && !LWE) // intersect_ray 11290 return; 11291 11292 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11293 unsigned LWEVal = LWE->getImm(); 11294 unsigned D16Val = D16 ? D16->getImm() : 0; 11295 11296 if (!TFEVal && !LWEVal) 11297 return; 11298 11299 // At least one of TFE or LWE are non-zero 11300 // We have to insert a suitable initialization of the result value and 11301 // tie this to the dest of the image instruction. 11302 11303 const DebugLoc &DL = MI.getDebugLoc(); 11304 11305 int DstIdx = 11306 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11307 11308 // Calculate which dword we have to initialize to 0. 11309 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11310 11311 // check that dmask operand is found. 11312 assert(MO_Dmask && "Expected dmask operand in instruction"); 11313 11314 unsigned dmask = MO_Dmask->getImm(); 11315 // Determine the number of active lanes taking into account the 11316 // Gather4 special case 11317 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11318 11319 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11320 11321 unsigned InitIdx = 11322 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11323 11324 // Abandon attempt if the dst size isn't large enough 11325 // - this is in fact an error but this is picked up elsewhere and 11326 // reported correctly. 11327 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11328 if (DstSize < InitIdx) 11329 return; 11330 11331 // Create a register for the intialization value. 11332 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11333 unsigned NewDst = 0; // Final initialized value will be in here 11334 11335 // If PRTStrictNull feature is enabled (the default) then initialize 11336 // all the result registers to 0, otherwise just the error indication 11337 // register (VGPRn+1) 11338 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11339 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11340 11341 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11342 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11343 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11344 // Initialize dword 11345 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11346 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11347 .addImm(0); 11348 // Insert into the super-reg 11349 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11350 .addReg(PrevDst) 11351 .addReg(SubReg) 11352 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11353 11354 PrevDst = NewDst; 11355 } 11356 11357 // Add as an implicit operand 11358 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11359 11360 // Tie the just added implicit operand to the dst 11361 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11362 } 11363 11364 /// Assign the register class depending on the number of 11365 /// bits set in the writemask 11366 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11367 SDNode *Node) const { 11368 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11369 11370 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11371 11372 if (TII->isVOP3(MI.getOpcode())) { 11373 // Make sure constant bus requirements are respected. 11374 TII->legalizeOperandsVOP3(MRI, MI); 11375 11376 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11377 // This saves a chain-copy of registers and better ballance register 11378 // use between vgpr and agpr as agpr tuples tend to be big. 11379 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 11380 unsigned Opc = MI.getOpcode(); 11381 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11382 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11383 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11384 if (I == -1) 11385 break; 11386 MachineOperand &Op = MI.getOperand(I); 11387 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 11388 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 11389 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 11390 continue; 11391 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11392 if (!Src || !Src->isCopy() || 11393 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11394 continue; 11395 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11396 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11397 // All uses of agpr64 and agpr32 can also accept vgpr except for 11398 // v_accvgpr_read, but we do not produce agpr reads during selection, 11399 // so no use checks are needed. 11400 MRI.setRegClass(Op.getReg(), NewRC); 11401 } 11402 } 11403 11404 return; 11405 } 11406 11407 // Replace unused atomics with the no return version. 11408 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11409 if (NoRetAtomicOp != -1) { 11410 if (!Node->hasAnyUseOfValue(0)) { 11411 int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11412 AMDGPU::OpName::cpol); 11413 if (CPolIdx != -1) { 11414 MachineOperand &CPol = MI.getOperand(CPolIdx); 11415 CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC); 11416 } 11417 MI.RemoveOperand(0); 11418 MI.setDesc(TII->get(NoRetAtomicOp)); 11419 return; 11420 } 11421 11422 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11423 // instruction, because the return type of these instructions is a vec2 of 11424 // the memory type, so it can be tied to the input operand. 11425 // This means these instructions always have a use, so we need to add a 11426 // special case to check if the atomic has only one extract_subreg use, 11427 // which itself has no uses. 11428 if ((Node->hasNUsesOfValue(1, 0) && 11429 Node->use_begin()->isMachineOpcode() && 11430 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11431 !Node->use_begin()->hasAnyUseOfValue(0))) { 11432 Register Def = MI.getOperand(0).getReg(); 11433 11434 // Change this into a noret atomic. 11435 MI.setDesc(TII->get(NoRetAtomicOp)); 11436 MI.RemoveOperand(0); 11437 11438 // If we only remove the def operand from the atomic instruction, the 11439 // extract_subreg will be left with a use of a vreg without a def. 11440 // So we need to insert an implicit_def to avoid machine verifier 11441 // errors. 11442 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11443 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11444 } 11445 return; 11446 } 11447 11448 if (TII->isMIMG(MI) && !MI.mayStore()) 11449 AddIMGInit(MI); 11450 } 11451 11452 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11453 uint64_t Val) { 11454 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11455 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11456 } 11457 11458 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11459 const SDLoc &DL, 11460 SDValue Ptr) const { 11461 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11462 11463 // Build the half of the subregister with the constants before building the 11464 // full 128-bit register. If we are building multiple resource descriptors, 11465 // this will allow CSEing of the 2-component register. 11466 const SDValue Ops0[] = { 11467 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11468 buildSMovImm32(DAG, DL, 0), 11469 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11470 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11471 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11472 }; 11473 11474 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11475 MVT::v2i32, Ops0), 0); 11476 11477 // Combine the constants and the pointer. 11478 const SDValue Ops1[] = { 11479 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11480 Ptr, 11481 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11482 SubRegHi, 11483 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11484 }; 11485 11486 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11487 } 11488 11489 /// Return a resource descriptor with the 'Add TID' bit enabled 11490 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11491 /// of the resource descriptor) to create an offset, which is added to 11492 /// the resource pointer. 11493 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11494 SDValue Ptr, uint32_t RsrcDword1, 11495 uint64_t RsrcDword2And3) const { 11496 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11497 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11498 if (RsrcDword1) { 11499 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11500 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11501 0); 11502 } 11503 11504 SDValue DataLo = buildSMovImm32(DAG, DL, 11505 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11506 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11507 11508 const SDValue Ops[] = { 11509 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11510 PtrLo, 11511 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11512 PtrHi, 11513 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11514 DataLo, 11515 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11516 DataHi, 11517 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11518 }; 11519 11520 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11521 } 11522 11523 //===----------------------------------------------------------------------===// 11524 // SI Inline Assembly Support 11525 //===----------------------------------------------------------------------===// 11526 11527 std::pair<unsigned, const TargetRegisterClass *> 11528 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11529 StringRef Constraint, 11530 MVT VT) const { 11531 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11532 11533 const TargetRegisterClass *RC = nullptr; 11534 if (Constraint.size() == 1) { 11535 const unsigned BitWidth = VT.getSizeInBits(); 11536 switch (Constraint[0]) { 11537 default: 11538 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11539 case 's': 11540 case 'r': 11541 switch (BitWidth) { 11542 case 16: 11543 RC = &AMDGPU::SReg_32RegClass; 11544 break; 11545 case 64: 11546 RC = &AMDGPU::SGPR_64RegClass; 11547 break; 11548 default: 11549 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11550 if (!RC) 11551 return std::make_pair(0U, nullptr); 11552 break; 11553 } 11554 break; 11555 case 'v': 11556 switch (BitWidth) { 11557 case 16: 11558 RC = &AMDGPU::VGPR_32RegClass; 11559 break; 11560 default: 11561 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11562 if (!RC) 11563 return std::make_pair(0U, nullptr); 11564 break; 11565 } 11566 break; 11567 case 'a': 11568 if (!Subtarget->hasMAIInsts()) 11569 break; 11570 switch (BitWidth) { 11571 case 16: 11572 RC = &AMDGPU::AGPR_32RegClass; 11573 break; 11574 default: 11575 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11576 if (!RC) 11577 return std::make_pair(0U, nullptr); 11578 break; 11579 } 11580 break; 11581 } 11582 // We actually support i128, i16 and f16 as inline parameters 11583 // even if they are not reported as legal 11584 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11585 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11586 return std::make_pair(0U, RC); 11587 } 11588 11589 if (Constraint.size() > 1) { 11590 if (Constraint[1] == 'v') { 11591 RC = &AMDGPU::VGPR_32RegClass; 11592 } else if (Constraint[1] == 's') { 11593 RC = &AMDGPU::SGPR_32RegClass; 11594 } else if (Constraint[1] == 'a') { 11595 RC = &AMDGPU::AGPR_32RegClass; 11596 } 11597 11598 if (RC) { 11599 uint32_t Idx; 11600 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11601 if (!Failed && Idx < RC->getNumRegs()) 11602 return std::make_pair(RC->getRegister(Idx), RC); 11603 } 11604 } 11605 11606 // FIXME: Returns VS_32 for physical SGPR constraints 11607 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11608 } 11609 11610 static bool isImmConstraint(StringRef Constraint) { 11611 if (Constraint.size() == 1) { 11612 switch (Constraint[0]) { 11613 default: break; 11614 case 'I': 11615 case 'J': 11616 case 'A': 11617 case 'B': 11618 case 'C': 11619 return true; 11620 } 11621 } else if (Constraint == "DA" || 11622 Constraint == "DB") { 11623 return true; 11624 } 11625 return false; 11626 } 11627 11628 SITargetLowering::ConstraintType 11629 SITargetLowering::getConstraintType(StringRef Constraint) const { 11630 if (Constraint.size() == 1) { 11631 switch (Constraint[0]) { 11632 default: break; 11633 case 's': 11634 case 'v': 11635 case 'a': 11636 return C_RegisterClass; 11637 } 11638 } 11639 if (isImmConstraint(Constraint)) { 11640 return C_Other; 11641 } 11642 return TargetLowering::getConstraintType(Constraint); 11643 } 11644 11645 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11646 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11647 Val = Val & maskTrailingOnes<uint64_t>(Size); 11648 } 11649 return Val; 11650 } 11651 11652 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11653 std::string &Constraint, 11654 std::vector<SDValue> &Ops, 11655 SelectionDAG &DAG) const { 11656 if (isImmConstraint(Constraint)) { 11657 uint64_t Val; 11658 if (getAsmOperandConstVal(Op, Val) && 11659 checkAsmConstraintVal(Op, Constraint, Val)) { 11660 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11661 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11662 } 11663 } else { 11664 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11665 } 11666 } 11667 11668 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11669 unsigned Size = Op.getScalarValueSizeInBits(); 11670 if (Size > 64) 11671 return false; 11672 11673 if (Size == 16 && !Subtarget->has16BitInsts()) 11674 return false; 11675 11676 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11677 Val = C->getSExtValue(); 11678 return true; 11679 } 11680 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11681 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11682 return true; 11683 } 11684 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11685 if (Size != 16 || Op.getNumOperands() != 2) 11686 return false; 11687 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11688 return false; 11689 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11690 Val = C->getSExtValue(); 11691 return true; 11692 } 11693 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11694 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11695 return true; 11696 } 11697 } 11698 11699 return false; 11700 } 11701 11702 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11703 const std::string &Constraint, 11704 uint64_t Val) const { 11705 if (Constraint.size() == 1) { 11706 switch (Constraint[0]) { 11707 case 'I': 11708 return AMDGPU::isInlinableIntLiteral(Val); 11709 case 'J': 11710 return isInt<16>(Val); 11711 case 'A': 11712 return checkAsmConstraintValA(Op, Val); 11713 case 'B': 11714 return isInt<32>(Val); 11715 case 'C': 11716 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11717 AMDGPU::isInlinableIntLiteral(Val); 11718 default: 11719 break; 11720 } 11721 } else if (Constraint.size() == 2) { 11722 if (Constraint == "DA") { 11723 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11724 int64_t LoBits = static_cast<int32_t>(Val); 11725 return checkAsmConstraintValA(Op, HiBits, 32) && 11726 checkAsmConstraintValA(Op, LoBits, 32); 11727 } 11728 if (Constraint == "DB") { 11729 return true; 11730 } 11731 } 11732 llvm_unreachable("Invalid asm constraint"); 11733 } 11734 11735 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11736 uint64_t Val, 11737 unsigned MaxSize) const { 11738 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11739 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11740 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11741 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11742 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11743 return true; 11744 } 11745 return false; 11746 } 11747 11748 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 11749 switch (UnalignedClassID) { 11750 case AMDGPU::VReg_64RegClassID: 11751 return AMDGPU::VReg_64_Align2RegClassID; 11752 case AMDGPU::VReg_96RegClassID: 11753 return AMDGPU::VReg_96_Align2RegClassID; 11754 case AMDGPU::VReg_128RegClassID: 11755 return AMDGPU::VReg_128_Align2RegClassID; 11756 case AMDGPU::VReg_160RegClassID: 11757 return AMDGPU::VReg_160_Align2RegClassID; 11758 case AMDGPU::VReg_192RegClassID: 11759 return AMDGPU::VReg_192_Align2RegClassID; 11760 case AMDGPU::VReg_256RegClassID: 11761 return AMDGPU::VReg_256_Align2RegClassID; 11762 case AMDGPU::VReg_512RegClassID: 11763 return AMDGPU::VReg_512_Align2RegClassID; 11764 case AMDGPU::VReg_1024RegClassID: 11765 return AMDGPU::VReg_1024_Align2RegClassID; 11766 case AMDGPU::AReg_64RegClassID: 11767 return AMDGPU::AReg_64_Align2RegClassID; 11768 case AMDGPU::AReg_96RegClassID: 11769 return AMDGPU::AReg_96_Align2RegClassID; 11770 case AMDGPU::AReg_128RegClassID: 11771 return AMDGPU::AReg_128_Align2RegClassID; 11772 case AMDGPU::AReg_160RegClassID: 11773 return AMDGPU::AReg_160_Align2RegClassID; 11774 case AMDGPU::AReg_192RegClassID: 11775 return AMDGPU::AReg_192_Align2RegClassID; 11776 case AMDGPU::AReg_256RegClassID: 11777 return AMDGPU::AReg_256_Align2RegClassID; 11778 case AMDGPU::AReg_512RegClassID: 11779 return AMDGPU::AReg_512_Align2RegClassID; 11780 case AMDGPU::AReg_1024RegClassID: 11781 return AMDGPU::AReg_1024_Align2RegClassID; 11782 default: 11783 return -1; 11784 } 11785 } 11786 11787 // Figure out which registers should be reserved for stack access. Only after 11788 // the function is legalized do we know all of the non-spill stack objects or if 11789 // calls are present. 11790 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11791 MachineRegisterInfo &MRI = MF.getRegInfo(); 11792 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11793 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11794 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11795 const SIInstrInfo *TII = ST.getInstrInfo(); 11796 11797 if (Info->isEntryFunction()) { 11798 // Callable functions have fixed registers used for stack access. 11799 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11800 } 11801 11802 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11803 Info->getStackPtrOffsetReg())); 11804 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11805 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11806 11807 // We need to worry about replacing the default register with itself in case 11808 // of MIR testcases missing the MFI. 11809 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11810 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11811 11812 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11813 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11814 11815 Info->limitOccupancy(MF); 11816 11817 if (ST.isWave32() && !MF.empty()) { 11818 for (auto &MBB : MF) { 11819 for (auto &MI : MBB) { 11820 TII->fixImplicitOperands(MI); 11821 } 11822 } 11823 } 11824 11825 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 11826 // classes if required. Ideally the register class constraints would differ 11827 // per-subtarget, but there's no easy way to achieve that right now. This is 11828 // not a problem for VGPRs because the correctly aligned VGPR class is implied 11829 // from using them as the register class for legal types. 11830 if (ST.needsAlignedVGPRs()) { 11831 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 11832 const Register Reg = Register::index2VirtReg(I); 11833 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 11834 if (!RC) 11835 continue; 11836 int NewClassID = getAlignedAGPRClassID(RC->getID()); 11837 if (NewClassID != -1) 11838 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 11839 } 11840 } 11841 11842 TargetLoweringBase::finalizeLowering(MF); 11843 11844 // Allocate a VGPR for future SGPR Spill if 11845 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11846 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11847 if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() && 11848 !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction()) 11849 Info->reserveVGPRforSGPRSpills(MF); 11850 } 11851 11852 void SITargetLowering::computeKnownBitsForFrameIndex( 11853 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11854 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11855 11856 // Set the high bits to zero based on the maximum allowed scratch size per 11857 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11858 // calculation won't overflow, so assume the sign bit is never set. 11859 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11860 } 11861 11862 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11863 KnownBits &Known, unsigned Dim) { 11864 unsigned MaxValue = 11865 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11866 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11867 } 11868 11869 void SITargetLowering::computeKnownBitsForTargetInstr( 11870 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11871 const MachineRegisterInfo &MRI, unsigned Depth) const { 11872 const MachineInstr *MI = MRI.getVRegDef(R); 11873 switch (MI->getOpcode()) { 11874 case AMDGPU::G_INTRINSIC: { 11875 switch (MI->getIntrinsicID()) { 11876 case Intrinsic::amdgcn_workitem_id_x: 11877 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11878 break; 11879 case Intrinsic::amdgcn_workitem_id_y: 11880 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11881 break; 11882 case Intrinsic::amdgcn_workitem_id_z: 11883 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11884 break; 11885 case Intrinsic::amdgcn_mbcnt_lo: 11886 case Intrinsic::amdgcn_mbcnt_hi: { 11887 // These return at most the wavefront size - 1. 11888 unsigned Size = MRI.getType(R).getSizeInBits(); 11889 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11890 break; 11891 } 11892 case Intrinsic::amdgcn_groupstaticsize: { 11893 // We can report everything over the maximum size as 0. We can't report 11894 // based on the actual size because we don't know if it's accurate or not 11895 // at any given point. 11896 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11897 break; 11898 } 11899 } 11900 break; 11901 } 11902 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 11903 Known.Zero.setHighBits(24); 11904 break; 11905 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 11906 Known.Zero.setHighBits(16); 11907 break; 11908 } 11909 } 11910 11911 Align SITargetLowering::computeKnownAlignForTargetInstr( 11912 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11913 unsigned Depth) const { 11914 const MachineInstr *MI = MRI.getVRegDef(R); 11915 switch (MI->getOpcode()) { 11916 case AMDGPU::G_INTRINSIC: 11917 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11918 // FIXME: Can this move to generic code? What about the case where the call 11919 // site specifies a lower alignment? 11920 Intrinsic::ID IID = MI->getIntrinsicID(); 11921 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11922 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11923 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11924 return *RetAlign; 11925 return Align(1); 11926 } 11927 default: 11928 return Align(1); 11929 } 11930 } 11931 11932 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11933 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11934 const Align CacheLineAlign = Align(64); 11935 11936 // Pre-GFX10 target did not benefit from loop alignment 11937 if (!ML || DisableLoopAlignment || 11938 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11939 getSubtarget()->hasInstFwdPrefetchBug()) 11940 return PrefAlign; 11941 11942 // On GFX10 I$ is 4 x 64 bytes cache lines. 11943 // By default prefetcher keeps one cache line behind and reads two ahead. 11944 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11945 // behind and one ahead. 11946 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11947 // If loop fits 64 bytes it always spans no more than two cache lines and 11948 // does not need an alignment. 11949 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11950 // Else if loop is less or equal 192 bytes we need two lines behind. 11951 11952 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11953 const MachineBasicBlock *Header = ML->getHeader(); 11954 if (Header->getAlignment() != PrefAlign) 11955 return Header->getAlignment(); // Already processed. 11956 11957 unsigned LoopSize = 0; 11958 for (const MachineBasicBlock *MBB : ML->blocks()) { 11959 // If inner loop block is aligned assume in average half of the alignment 11960 // size to be added as nops. 11961 if (MBB != Header) 11962 LoopSize += MBB->getAlignment().value() / 2; 11963 11964 for (const MachineInstr &MI : *MBB) { 11965 LoopSize += TII->getInstSizeInBytes(MI); 11966 if (LoopSize > 192) 11967 return PrefAlign; 11968 } 11969 } 11970 11971 if (LoopSize <= 64) 11972 return PrefAlign; 11973 11974 if (LoopSize <= 128) 11975 return CacheLineAlign; 11976 11977 // If any of parent loops is surrounded by prefetch instructions do not 11978 // insert new for inner loop, which would reset parent's settings. 11979 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11980 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11981 auto I = Exit->getFirstNonDebugInstr(); 11982 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11983 return CacheLineAlign; 11984 } 11985 } 11986 11987 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11988 MachineBasicBlock *Exit = ML->getExitBlock(); 11989 11990 if (Pre && Exit) { 11991 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11992 TII->get(AMDGPU::S_INST_PREFETCH)) 11993 .addImm(1); // prefetch 2 lines behind PC 11994 11995 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11996 TII->get(AMDGPU::S_INST_PREFETCH)) 11997 .addImm(2); // prefetch 1 line behind PC 11998 } 11999 12000 return CacheLineAlign; 12001 } 12002 12003 LLVM_ATTRIBUTE_UNUSED 12004 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 12005 assert(N->getOpcode() == ISD::CopyFromReg); 12006 do { 12007 // Follow the chain until we find an INLINEASM node. 12008 N = N->getOperand(0).getNode(); 12009 if (N->getOpcode() == ISD::INLINEASM || 12010 N->getOpcode() == ISD::INLINEASM_BR) 12011 return true; 12012 } while (N->getOpcode() == ISD::CopyFromReg); 12013 return false; 12014 } 12015 12016 bool SITargetLowering::isSDNodeSourceOfDivergence( 12017 const SDNode *N, FunctionLoweringInfo *FLI, 12018 LegacyDivergenceAnalysis *KDA) const { 12019 switch (N->getOpcode()) { 12020 case ISD::CopyFromReg: { 12021 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 12022 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 12023 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12024 Register Reg = R->getReg(); 12025 12026 // FIXME: Why does this need to consider isLiveIn? 12027 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 12028 return !TRI->isSGPRReg(MRI, Reg); 12029 12030 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 12031 return KDA->isDivergent(V); 12032 12033 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 12034 return !TRI->isSGPRReg(MRI, Reg); 12035 } 12036 case ISD::LOAD: { 12037 const LoadSDNode *L = cast<LoadSDNode>(N); 12038 unsigned AS = L->getAddressSpace(); 12039 // A flat load may access private memory. 12040 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 12041 } 12042 case ISD::CALLSEQ_END: 12043 return true; 12044 case ISD::INTRINSIC_WO_CHAIN: 12045 return AMDGPU::isIntrinsicSourceOfDivergence( 12046 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 12047 case ISD::INTRINSIC_W_CHAIN: 12048 return AMDGPU::isIntrinsicSourceOfDivergence( 12049 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 12050 case AMDGPUISD::ATOMIC_CMP_SWAP: 12051 case AMDGPUISD::ATOMIC_INC: 12052 case AMDGPUISD::ATOMIC_DEC: 12053 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12054 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12055 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12056 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12057 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12058 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12059 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12060 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12061 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12062 case AMDGPUISD::BUFFER_ATOMIC_AND: 12063 case AMDGPUISD::BUFFER_ATOMIC_OR: 12064 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12065 case AMDGPUISD::BUFFER_ATOMIC_INC: 12066 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12067 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12068 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12069 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12070 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12071 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12072 // Target-specific read-modify-write atomics are sources of divergence. 12073 return true; 12074 default: 12075 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12076 // Generic read-modify-write atomics are sources of divergence. 12077 return A->readMem() && A->writeMem(); 12078 } 12079 return false; 12080 } 12081 } 12082 12083 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12084 EVT VT) const { 12085 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12086 case MVT::f32: 12087 return hasFP32Denormals(DAG.getMachineFunction()); 12088 case MVT::f64: 12089 case MVT::f16: 12090 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12091 default: 12092 return false; 12093 } 12094 } 12095 12096 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12097 MachineFunction &MF) const { 12098 switch (Ty.getScalarSizeInBits()) { 12099 case 32: 12100 return hasFP32Denormals(MF); 12101 case 64: 12102 case 16: 12103 return hasFP64FP16Denormals(MF); 12104 default: 12105 return false; 12106 } 12107 } 12108 12109 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12110 const SelectionDAG &DAG, 12111 bool SNaN, 12112 unsigned Depth) const { 12113 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12114 const MachineFunction &MF = DAG.getMachineFunction(); 12115 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12116 12117 if (Info->getMode().DX10Clamp) 12118 return true; // Clamped to 0. 12119 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12120 } 12121 12122 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12123 SNaN, Depth); 12124 } 12125 12126 // Global FP atomic instructions have a hardcoded FP mode and do not support 12127 // FP32 denormals, and only support v2f16 denormals. 12128 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12129 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12130 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12131 if (&Flt == &APFloat::IEEEsingle()) 12132 return DenormMode == DenormalMode::getPreserveSign(); 12133 return DenormMode == DenormalMode::getIEEE(); 12134 } 12135 12136 TargetLowering::AtomicExpansionKind 12137 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12138 switch (RMW->getOperation()) { 12139 case AtomicRMWInst::FAdd: { 12140 Type *Ty = RMW->getType(); 12141 12142 // We don't have a way to support 16-bit atomics now, so just leave them 12143 // as-is. 12144 if (Ty->isHalfTy()) 12145 return AtomicExpansionKind::None; 12146 12147 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12148 return AtomicExpansionKind::CmpXChg; 12149 12150 unsigned AS = RMW->getPointerAddressSpace(); 12151 12152 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12153 Subtarget->hasAtomicFaddInsts()) { 12154 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12155 // floating point atomic instructions. May generate more efficient code, 12156 // but may not respect rounding and denormal modes, and may give incorrect 12157 // results for certain memory destinations. 12158 if (RMW->getFunction() 12159 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12160 .getValueAsString() != "true") 12161 return AtomicExpansionKind::CmpXChg; 12162 12163 if (Subtarget->hasGFX90AInsts()) { 12164 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) 12165 return AtomicExpansionKind::CmpXChg; 12166 12167 auto SSID = RMW->getSyncScopeID(); 12168 if (SSID == SyncScope::System || 12169 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12170 return AtomicExpansionKind::CmpXChg; 12171 12172 return AtomicExpansionKind::None; 12173 } 12174 12175 if (AS == AMDGPUAS::FLAT_ADDRESS) 12176 return AtomicExpansionKind::CmpXChg; 12177 12178 return RMW->use_empty() ? AtomicExpansionKind::None 12179 : AtomicExpansionKind::CmpXChg; 12180 } 12181 12182 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 12183 // to round-to-nearest-even. 12184 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12185 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) { 12186 if (!Ty->isDoubleTy()) 12187 return AtomicExpansionKind::None; 12188 12189 return (fpModeMatchesGlobalFPAtomicMode(RMW) || 12190 RMW->getFunction() 12191 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12192 .getValueAsString() == "true") 12193 ? AtomicExpansionKind::None 12194 : AtomicExpansionKind::CmpXChg; 12195 } 12196 12197 return AtomicExpansionKind::CmpXChg; 12198 } 12199 default: 12200 break; 12201 } 12202 12203 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12204 } 12205 12206 const TargetRegisterClass * 12207 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12208 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12209 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12210 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12211 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12212 : &AMDGPU::SReg_32RegClass; 12213 if (!TRI->isSGPRClass(RC) && !isDivergent) 12214 return TRI->getEquivalentSGPRClass(RC); 12215 else if (TRI->isSGPRClass(RC) && isDivergent) 12216 return TRI->getEquivalentVGPRClass(RC); 12217 12218 return RC; 12219 } 12220 12221 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12222 // uniform values (as produced by the mask results of control flow intrinsics) 12223 // used outside of divergent blocks. The phi users need to also be treated as 12224 // always uniform. 12225 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12226 unsigned WaveSize) { 12227 // FIXME: We asssume we never cast the mask results of a control flow 12228 // intrinsic. 12229 // Early exit if the type won't be consistent as a compile time hack. 12230 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12231 if (!IT || IT->getBitWidth() != WaveSize) 12232 return false; 12233 12234 if (!isa<Instruction>(V)) 12235 return false; 12236 if (!Visited.insert(V).second) 12237 return false; 12238 bool Result = false; 12239 for (auto U : V->users()) { 12240 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12241 if (V == U->getOperand(1)) { 12242 switch (Intrinsic->getIntrinsicID()) { 12243 default: 12244 Result = false; 12245 break; 12246 case Intrinsic::amdgcn_if_break: 12247 case Intrinsic::amdgcn_if: 12248 case Intrinsic::amdgcn_else: 12249 Result = true; 12250 break; 12251 } 12252 } 12253 if (V == U->getOperand(0)) { 12254 switch (Intrinsic->getIntrinsicID()) { 12255 default: 12256 Result = false; 12257 break; 12258 case Intrinsic::amdgcn_end_cf: 12259 case Intrinsic::amdgcn_loop: 12260 Result = true; 12261 break; 12262 } 12263 } 12264 } else { 12265 Result = hasCFUser(U, Visited, WaveSize); 12266 } 12267 if (Result) 12268 break; 12269 } 12270 return Result; 12271 } 12272 12273 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12274 const Value *V) const { 12275 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12276 if (CI->isInlineAsm()) { 12277 // FIXME: This cannot give a correct answer. This should only trigger in 12278 // the case where inline asm returns mixed SGPR and VGPR results, used 12279 // outside the defining block. We don't have a specific result to 12280 // consider, so this assumes if any value is SGPR, the overall register 12281 // also needs to be SGPR. 12282 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12283 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12284 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12285 for (auto &TC : TargetConstraints) { 12286 if (TC.Type == InlineAsm::isOutput) { 12287 ComputeConstraintToUse(TC, SDValue()); 12288 unsigned AssignedReg; 12289 const TargetRegisterClass *RC; 12290 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 12291 SIRI, TC.ConstraintCode, TC.ConstraintVT); 12292 if (RC) { 12293 MachineRegisterInfo &MRI = MF.getRegInfo(); 12294 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 12295 return true; 12296 else if (SIRI->isSGPRClass(RC)) 12297 return true; 12298 } 12299 } 12300 } 12301 } 12302 } 12303 SmallPtrSet<const Value *, 16> Visited; 12304 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12305 } 12306 12307 std::pair<InstructionCost, MVT> 12308 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12309 Type *Ty) const { 12310 std::pair<InstructionCost, MVT> Cost = 12311 TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12312 auto Size = DL.getTypeSizeInBits(Ty); 12313 // Maximum load or store can handle 8 dwords for scalar and 4 for 12314 // vector ALU. Let's assume anything above 8 dwords is expensive 12315 // even if legal. 12316 if (Size <= 256) 12317 return Cost; 12318 12319 Cost.first = (Size + 255) / 256; 12320 return Cost; 12321 } 12322