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/CodeGen/Analysis.h" 23 #include "llvm/CodeGen/FunctionLoweringInfo.h" 24 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 25 #include "llvm/CodeGen/MachineLoopInfo.h" 26 #include "llvm/IR/DiagnosticInfo.h" 27 #include "llvm/IR/IntrinsicsAMDGPU.h" 28 #include "llvm/IR/IntrinsicsR600.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Support/KnownBits.h" 31 32 using namespace llvm; 33 34 #define DEBUG_TYPE "si-lower" 35 36 STATISTIC(NumTailCalls, "Number of tail calls"); 37 38 static cl::opt<bool> DisableLoopAlignment( 39 "amdgpu-disable-loop-alignment", 40 cl::desc("Do not align and prefetch loops"), 41 cl::init(false)); 42 43 static cl::opt<bool> VGPRReserveforSGPRSpill( 44 "amdgpu-reserve-vgpr-for-sgpr-spill", 45 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 46 47 static cl::opt<bool> UseDivergentRegisterIndexing( 48 "amdgpu-use-divergent-register-indexing", 49 cl::Hidden, 50 cl::desc("Use indirect register addressing for divergent indexes"), 51 cl::init(false)); 52 53 static bool hasFP32Denormals(const MachineFunction &MF) { 54 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 55 return Info->getMode().allFP32Denormals(); 56 } 57 58 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 59 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 60 return Info->getMode().allFP64FP16Denormals(); 61 } 62 63 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 64 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 65 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 66 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 67 return AMDGPU::SGPR0 + Reg; 68 } 69 } 70 llvm_unreachable("Cannot allocate sgpr"); 71 } 72 73 SITargetLowering::SITargetLowering(const TargetMachine &TM, 74 const GCNSubtarget &STI) 75 : AMDGPUTargetLowering(TM, STI), 76 Subtarget(&STI) { 77 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 78 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 79 80 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 81 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 82 83 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 84 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 85 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 86 87 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 88 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 89 90 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 91 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 92 93 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 94 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 95 96 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 97 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 98 99 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 100 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 101 102 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 103 addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass); 104 105 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 106 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 107 108 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 109 addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass); 110 111 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 112 addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass); 113 114 if (Subtarget->has16BitInsts()) { 115 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 116 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 117 118 // Unless there are also VOP3P operations, not operations are really legal. 119 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 120 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 121 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 122 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 123 } 124 125 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 126 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 127 128 computeRegisterProperties(Subtarget->getRegisterInfo()); 129 130 // The boolean content concept here is too inflexible. Compares only ever 131 // really produce a 1-bit result. Any copy/extend from these will turn into a 132 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 133 // it's what most targets use. 134 setBooleanContents(ZeroOrOneBooleanContent); 135 setBooleanVectorContents(ZeroOrOneBooleanContent); 136 137 // We need to custom lower vector stores from local memory 138 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 139 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 140 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 141 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 142 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 143 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 144 setOperationAction(ISD::LOAD, MVT::i1, Custom); 145 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 146 147 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 148 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 149 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 150 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 151 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 152 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 153 setOperationAction(ISD::STORE, MVT::i1, Custom); 154 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 155 156 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 157 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 158 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 159 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 160 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 161 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 162 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 163 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 164 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 165 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 166 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 167 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 168 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 169 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 170 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 171 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 172 173 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 174 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 175 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 176 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 177 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 178 179 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 180 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 181 182 setOperationAction(ISD::SELECT, MVT::i1, Promote); 183 setOperationAction(ISD::SELECT, MVT::i64, Custom); 184 setOperationAction(ISD::SELECT, MVT::f64, Promote); 185 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 186 187 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 188 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 189 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 190 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 191 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 192 193 setOperationAction(ISD::SETCC, MVT::i1, Promote); 194 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 195 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 196 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 197 198 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 199 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 200 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 201 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 202 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 203 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 204 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 205 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 206 207 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 208 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 209 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 210 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 211 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 212 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 213 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 215 216 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 217 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 218 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 219 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 220 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 221 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 222 223 setOperationAction(ISD::UADDO, MVT::i32, Legal); 224 setOperationAction(ISD::USUBO, MVT::i32, Legal); 225 226 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 227 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 228 229 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 230 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 231 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 232 233 #if 0 234 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 235 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 236 #endif 237 238 // We only support LOAD/STORE and vector manipulation ops for vectors 239 // with > 4 elements. 240 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 241 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 242 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 243 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 244 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 245 switch (Op) { 246 case ISD::LOAD: 247 case ISD::STORE: 248 case ISD::BUILD_VECTOR: 249 case ISD::BITCAST: 250 case ISD::EXTRACT_VECTOR_ELT: 251 case ISD::INSERT_VECTOR_ELT: 252 case ISD::INSERT_SUBVECTOR: 253 case ISD::EXTRACT_SUBVECTOR: 254 case ISD::SCALAR_TO_VECTOR: 255 break; 256 case ISD::CONCAT_VECTORS: 257 setOperationAction(Op, VT, Custom); 258 break; 259 default: 260 setOperationAction(Op, VT, Expand); 261 break; 262 } 263 } 264 } 265 266 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 267 268 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 269 // is expanded to avoid having two separate loops in case the index is a VGPR. 270 271 // Most operations are naturally 32-bit vector operations. We only support 272 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 273 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 274 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 275 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 276 277 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 278 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 279 280 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 281 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 282 283 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 284 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 285 } 286 287 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 288 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 289 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 290 291 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 292 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 293 294 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 295 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 296 297 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 298 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 299 } 300 301 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 302 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 303 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 304 305 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 306 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 307 308 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 309 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 310 311 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 312 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 313 } 314 315 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 316 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 317 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 318 319 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 320 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 321 322 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 323 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 324 325 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 326 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 327 } 328 329 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 330 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 331 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 332 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 333 334 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 335 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 336 337 // Avoid stack access for these. 338 // TODO: Generalize to more vector types. 339 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 340 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 341 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 342 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 343 344 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 345 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 346 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 347 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 348 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 349 350 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 351 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 352 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 353 354 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 355 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 356 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 357 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 358 359 // Deal with vec3 vector operations when widened to vec4. 360 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 361 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 362 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 363 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 364 365 // Deal with vec5 vector operations when widened to vec8. 366 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 367 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 368 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 369 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 370 371 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 372 // and output demarshalling 373 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 374 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 375 376 // We can't return success/failure, only the old value, 377 // let LLVM add the comparison 378 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 379 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 380 381 if (Subtarget->hasFlatAddressSpace()) { 382 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 383 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 384 } 385 386 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 387 388 // FIXME: This should be narrowed to i32, but that only happens if i64 is 389 // illegal. 390 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 391 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 392 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 393 394 // On SI this is s_memtime and s_memrealtime on VI. 395 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 396 setOperationAction(ISD::TRAP, MVT::Other, Custom); 397 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 398 399 if (Subtarget->has16BitInsts()) { 400 setOperationAction(ISD::FPOW, MVT::f16, Promote); 401 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 402 setOperationAction(ISD::FLOG, MVT::f16, Custom); 403 setOperationAction(ISD::FEXP, MVT::f16, Custom); 404 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 405 } 406 407 if (Subtarget->hasMadMacF32Insts()) 408 setOperationAction(ISD::FMAD, MVT::f32, Legal); 409 410 if (!Subtarget->hasBFI()) { 411 // fcopysign can be done in a single instruction with BFI. 412 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 413 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 414 } 415 416 if (!Subtarget->hasBCNT(32)) 417 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 418 419 if (!Subtarget->hasBCNT(64)) 420 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 421 422 if (Subtarget->hasFFBH()) 423 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 424 425 if (Subtarget->hasFFBL()) 426 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 427 428 // We only really have 32-bit BFE instructions (and 16-bit on VI). 429 // 430 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 431 // effort to match them now. We want this to be false for i64 cases when the 432 // extraction isn't restricted to the upper or lower half. Ideally we would 433 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 434 // span the midpoint are probably relatively rare, so don't worry about them 435 // for now. 436 if (Subtarget->hasBFE()) 437 setHasExtractBitsInsn(true); 438 439 // Clamp modifier on add/sub 440 if (Subtarget->hasIntClamp()) { 441 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 442 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 443 } 444 445 if (Subtarget->hasAddNoCarry()) { 446 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 447 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 448 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 449 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 450 } 451 452 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 453 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 454 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 455 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 456 457 458 // These are really only legal for ieee_mode functions. We should be avoiding 459 // them for functions that don't have ieee_mode enabled, so just say they are 460 // legal. 461 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 462 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 463 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 464 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 465 466 467 if (Subtarget->haveRoundOpsF64()) { 468 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 469 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 470 setOperationAction(ISD::FRINT, MVT::f64, Legal); 471 } else { 472 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 473 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 474 setOperationAction(ISD::FRINT, MVT::f64, Custom); 475 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 476 } 477 478 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 479 480 setOperationAction(ISD::FSIN, MVT::f32, Custom); 481 setOperationAction(ISD::FCOS, MVT::f32, Custom); 482 setOperationAction(ISD::FDIV, MVT::f32, Custom); 483 setOperationAction(ISD::FDIV, MVT::f64, Custom); 484 485 if (Subtarget->has16BitInsts()) { 486 setOperationAction(ISD::Constant, MVT::i16, Legal); 487 488 setOperationAction(ISD::SMIN, MVT::i16, Legal); 489 setOperationAction(ISD::SMAX, MVT::i16, Legal); 490 491 setOperationAction(ISD::UMIN, MVT::i16, Legal); 492 setOperationAction(ISD::UMAX, MVT::i16, Legal); 493 494 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 495 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 496 497 setOperationAction(ISD::ROTR, MVT::i16, Expand); 498 setOperationAction(ISD::ROTL, MVT::i16, Expand); 499 500 setOperationAction(ISD::SDIV, MVT::i16, Promote); 501 setOperationAction(ISD::UDIV, MVT::i16, Promote); 502 setOperationAction(ISD::SREM, MVT::i16, Promote); 503 setOperationAction(ISD::UREM, MVT::i16, Promote); 504 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 505 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 506 507 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 508 509 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 510 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 511 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 512 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 513 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 514 515 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 516 517 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 518 519 setOperationAction(ISD::LOAD, MVT::i16, Custom); 520 521 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 522 523 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 524 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 525 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 526 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 527 528 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 529 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 530 531 // F16 - Constant Actions. 532 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 533 534 // F16 - Load/Store Actions. 535 setOperationAction(ISD::LOAD, MVT::f16, Promote); 536 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 537 setOperationAction(ISD::STORE, MVT::f16, Promote); 538 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 539 540 // F16 - VOP1 Actions. 541 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 542 setOperationAction(ISD::FCOS, MVT::f16, Custom); 543 setOperationAction(ISD::FSIN, MVT::f16, Custom); 544 545 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 546 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 547 548 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 549 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 550 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 551 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 552 setOperationAction(ISD::FROUND, MVT::f16, Custom); 553 554 // F16 - VOP2 Actions. 555 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 556 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 557 558 setOperationAction(ISD::FDIV, MVT::f16, Custom); 559 560 // F16 - VOP3 Actions. 561 setOperationAction(ISD::FMA, MVT::f16, Legal); 562 if (STI.hasMadF16()) 563 setOperationAction(ISD::FMAD, MVT::f16, Legal); 564 565 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 566 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 567 switch (Op) { 568 case ISD::LOAD: 569 case ISD::STORE: 570 case ISD::BUILD_VECTOR: 571 case ISD::BITCAST: 572 case ISD::EXTRACT_VECTOR_ELT: 573 case ISD::INSERT_VECTOR_ELT: 574 case ISD::INSERT_SUBVECTOR: 575 case ISD::EXTRACT_SUBVECTOR: 576 case ISD::SCALAR_TO_VECTOR: 577 break; 578 case ISD::CONCAT_VECTORS: 579 setOperationAction(Op, VT, Custom); 580 break; 581 default: 582 setOperationAction(Op, VT, Expand); 583 break; 584 } 585 } 586 } 587 588 // v_perm_b32 can handle either of these. 589 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 590 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 591 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 592 593 // XXX - Do these do anything? Vector constants turn into build_vector. 594 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 595 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 596 597 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 598 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 599 600 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 601 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 602 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 603 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 604 605 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 606 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 607 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 608 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 609 610 setOperationAction(ISD::AND, MVT::v2i16, Promote); 611 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 612 setOperationAction(ISD::OR, MVT::v2i16, Promote); 613 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 614 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 615 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 616 617 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 618 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 619 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 620 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 621 622 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 623 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 624 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 625 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 626 627 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 628 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 629 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 630 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 631 632 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 633 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 634 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 635 636 if (!Subtarget->hasVOP3PInsts()) { 637 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 638 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 639 } 640 641 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 642 // This isn't really legal, but this avoids the legalizer unrolling it (and 643 // allows matching fneg (fabs x) patterns) 644 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 645 646 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 647 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 648 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 649 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 650 651 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 652 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 653 654 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 655 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 656 } 657 658 if (Subtarget->hasVOP3PInsts()) { 659 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 660 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 661 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 662 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 663 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 664 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 665 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 666 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 667 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 668 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 669 670 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 671 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 672 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 673 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 674 675 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 676 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 677 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 678 679 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 680 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 681 682 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 683 684 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 685 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 686 687 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 688 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 689 690 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 691 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 692 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 693 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 694 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 695 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 696 697 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 698 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 699 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 700 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 701 702 setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom); 703 setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom); 704 setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom); 705 setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom); 706 707 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 708 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 709 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 710 711 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 712 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 713 714 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 715 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 716 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 717 718 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 719 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 720 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 721 722 if (Subtarget->hasPackedFP32Ops()) { 723 setOperationAction(ISD::FADD, MVT::v2f32, Legal); 724 setOperationAction(ISD::FMUL, MVT::v2f32, Legal); 725 setOperationAction(ISD::FMA, MVT::v2f32, Legal); 726 setOperationAction(ISD::FNEG, MVT::v2f32, Legal); 727 728 for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) { 729 setOperationAction(ISD::FADD, VT, Custom); 730 setOperationAction(ISD::FMUL, VT, Custom); 731 setOperationAction(ISD::FMA, VT, Custom); 732 } 733 } 734 } 735 736 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 737 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 738 739 if (Subtarget->has16BitInsts()) { 740 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 741 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 742 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 743 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 744 } else { 745 // Legalization hack. 746 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 747 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 748 749 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 750 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 751 } 752 753 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 754 setOperationAction(ISD::SELECT, VT, Custom); 755 } 756 757 setOperationAction(ISD::SMULO, MVT::i64, Custom); 758 setOperationAction(ISD::UMULO, MVT::i64, Custom); 759 760 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 761 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 762 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 763 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 764 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 765 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 766 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 767 768 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 769 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 770 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 771 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 772 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 773 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 774 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 775 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 776 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 777 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 778 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 779 780 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 781 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 782 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 783 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 784 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 785 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 786 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 787 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 788 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 789 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 790 791 setTargetDAGCombine(ISD::ADD); 792 setTargetDAGCombine(ISD::ADDCARRY); 793 setTargetDAGCombine(ISD::SUB); 794 setTargetDAGCombine(ISD::SUBCARRY); 795 setTargetDAGCombine(ISD::FADD); 796 setTargetDAGCombine(ISD::FSUB); 797 setTargetDAGCombine(ISD::FMINNUM); 798 setTargetDAGCombine(ISD::FMAXNUM); 799 setTargetDAGCombine(ISD::FMINNUM_IEEE); 800 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 801 setTargetDAGCombine(ISD::FMA); 802 setTargetDAGCombine(ISD::SMIN); 803 setTargetDAGCombine(ISD::SMAX); 804 setTargetDAGCombine(ISD::UMIN); 805 setTargetDAGCombine(ISD::UMAX); 806 setTargetDAGCombine(ISD::SETCC); 807 setTargetDAGCombine(ISD::AND); 808 setTargetDAGCombine(ISD::OR); 809 setTargetDAGCombine(ISD::XOR); 810 setTargetDAGCombine(ISD::SINT_TO_FP); 811 setTargetDAGCombine(ISD::UINT_TO_FP); 812 setTargetDAGCombine(ISD::FCANONICALIZE); 813 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 814 setTargetDAGCombine(ISD::ZERO_EXTEND); 815 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 816 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 817 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 818 819 // All memory operations. Some folding on the pointer operand is done to help 820 // matching the constant offsets in the addressing modes. 821 setTargetDAGCombine(ISD::LOAD); 822 setTargetDAGCombine(ISD::STORE); 823 setTargetDAGCombine(ISD::ATOMIC_LOAD); 824 setTargetDAGCombine(ISD::ATOMIC_STORE); 825 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 826 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 827 setTargetDAGCombine(ISD::ATOMIC_SWAP); 828 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 829 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 830 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 831 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 832 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 833 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 834 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 835 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 836 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 837 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 838 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 839 setTargetDAGCombine(ISD::INTRINSIC_VOID); 840 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 841 842 // FIXME: In other contexts we pretend this is a per-function property. 843 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 844 845 setSchedulingPreference(Sched::RegPressure); 846 } 847 848 const GCNSubtarget *SITargetLowering::getSubtarget() const { 849 return Subtarget; 850 } 851 852 //===----------------------------------------------------------------------===// 853 // TargetLowering queries 854 //===----------------------------------------------------------------------===// 855 856 // v_mad_mix* support a conversion from f16 to f32. 857 // 858 // There is only one special case when denormals are enabled we don't currently, 859 // where this is OK to use. 860 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 861 EVT DestVT, EVT SrcVT) const { 862 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 863 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 864 DestVT.getScalarType() == MVT::f32 && 865 SrcVT.getScalarType() == MVT::f16 && 866 // TODO: This probably only requires no input flushing? 867 !hasFP32Denormals(DAG.getMachineFunction()); 868 } 869 870 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 871 // SI has some legal vector types, but no legal vector operations. Say no 872 // shuffles are legal in order to prefer scalarizing some vector operations. 873 return false; 874 } 875 876 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 877 CallingConv::ID CC, 878 EVT VT) const { 879 if (CC == CallingConv::AMDGPU_KERNEL) 880 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 881 882 if (VT.isVector()) { 883 EVT ScalarVT = VT.getScalarType(); 884 unsigned Size = ScalarVT.getSizeInBits(); 885 if (Size == 16) { 886 if (Subtarget->has16BitInsts()) 887 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 888 return VT.isInteger() ? MVT::i32 : MVT::f32; 889 } 890 891 if (Size < 16) 892 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 893 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 894 } 895 896 if (VT.getSizeInBits() > 32) 897 return MVT::i32; 898 899 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 900 } 901 902 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 903 CallingConv::ID CC, 904 EVT VT) const { 905 if (CC == CallingConv::AMDGPU_KERNEL) 906 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 907 908 if (VT.isVector()) { 909 unsigned NumElts = VT.getVectorNumElements(); 910 EVT ScalarVT = VT.getScalarType(); 911 unsigned Size = ScalarVT.getSizeInBits(); 912 913 // FIXME: Should probably promote 8-bit vectors to i16. 914 if (Size == 16 && Subtarget->has16BitInsts()) 915 return (NumElts + 1) / 2; 916 917 if (Size <= 32) 918 return NumElts; 919 920 if (Size > 32) 921 return NumElts * ((Size + 31) / 32); 922 } else if (VT.getSizeInBits() > 32) 923 return (VT.getSizeInBits() + 31) / 32; 924 925 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 926 } 927 928 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 929 LLVMContext &Context, CallingConv::ID CC, 930 EVT VT, EVT &IntermediateVT, 931 unsigned &NumIntermediates, MVT &RegisterVT) const { 932 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 933 unsigned NumElts = VT.getVectorNumElements(); 934 EVT ScalarVT = VT.getScalarType(); 935 unsigned Size = ScalarVT.getSizeInBits(); 936 // FIXME: We should fix the ABI to be the same on targets without 16-bit 937 // support, but unless we can properly handle 3-vectors, it will be still be 938 // inconsistent. 939 if (Size == 16 && Subtarget->has16BitInsts()) { 940 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 941 IntermediateVT = RegisterVT; 942 NumIntermediates = (NumElts + 1) / 2; 943 return NumIntermediates; 944 } 945 946 if (Size == 32) { 947 RegisterVT = ScalarVT.getSimpleVT(); 948 IntermediateVT = RegisterVT; 949 NumIntermediates = NumElts; 950 return NumIntermediates; 951 } 952 953 if (Size < 16 && Subtarget->has16BitInsts()) { 954 // FIXME: Should probably form v2i16 pieces 955 RegisterVT = MVT::i16; 956 IntermediateVT = ScalarVT; 957 NumIntermediates = NumElts; 958 return NumIntermediates; 959 } 960 961 962 if (Size != 16 && Size <= 32) { 963 RegisterVT = MVT::i32; 964 IntermediateVT = ScalarVT; 965 NumIntermediates = NumElts; 966 return NumIntermediates; 967 } 968 969 if (Size > 32) { 970 RegisterVT = MVT::i32; 971 IntermediateVT = RegisterVT; 972 NumIntermediates = NumElts * ((Size + 31) / 32); 973 return NumIntermediates; 974 } 975 } 976 977 return TargetLowering::getVectorTypeBreakdownForCallingConv( 978 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 979 } 980 981 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 982 assert(DMaskLanes != 0); 983 984 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 985 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 986 return EVT::getVectorVT(Ty->getContext(), 987 EVT::getEVT(VT->getElementType()), 988 NumElts); 989 } 990 991 return EVT::getEVT(Ty); 992 } 993 994 // Peek through TFE struct returns to only use the data size. 995 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 996 auto *ST = dyn_cast<StructType>(Ty); 997 if (!ST) 998 return memVTFromImageData(Ty, DMaskLanes); 999 1000 // Some intrinsics return an aggregate type - special case to work out the 1001 // correct memVT. 1002 // 1003 // Only limited forms of aggregate type currently expected. 1004 if (ST->getNumContainedTypes() != 2 || 1005 !ST->getContainedType(1)->isIntegerTy(32)) 1006 return EVT(); 1007 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1008 } 1009 1010 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1011 const CallInst &CI, 1012 MachineFunction &MF, 1013 unsigned IntrID) const { 1014 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1015 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1016 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1017 (Intrinsic::ID)IntrID); 1018 if (Attr.hasFnAttribute(Attribute::ReadNone)) 1019 return false; 1020 1021 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1022 1023 if (RsrcIntr->IsImage) { 1024 Info.ptrVal = 1025 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1026 Info.align.reset(); 1027 } else { 1028 Info.ptrVal = 1029 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1030 } 1031 1032 Info.flags = MachineMemOperand::MODereferenceable; 1033 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 1034 unsigned DMaskLanes = 4; 1035 1036 if (RsrcIntr->IsImage) { 1037 const AMDGPU::ImageDimIntrinsicInfo *Intr 1038 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1039 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1040 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1041 1042 if (!BaseOpcode->Gather4) { 1043 // If this isn't a gather, we may have excess loaded elements in the 1044 // IR type. Check the dmask for the real number of elements loaded. 1045 unsigned DMask 1046 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1047 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1048 } 1049 1050 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1051 } else 1052 Info.memVT = EVT::getEVT(CI.getType()); 1053 1054 // FIXME: What does alignment mean for an image? 1055 Info.opc = ISD::INTRINSIC_W_CHAIN; 1056 Info.flags |= MachineMemOperand::MOLoad; 1057 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1058 Info.opc = ISD::INTRINSIC_VOID; 1059 1060 Type *DataTy = CI.getArgOperand(0)->getType(); 1061 if (RsrcIntr->IsImage) { 1062 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1063 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1064 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1065 } else 1066 Info.memVT = EVT::getEVT(DataTy); 1067 1068 Info.flags |= MachineMemOperand::MOStore; 1069 } else { 1070 // Atomic 1071 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1072 ISD::INTRINSIC_W_CHAIN; 1073 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1074 Info.flags = MachineMemOperand::MOLoad | 1075 MachineMemOperand::MOStore | 1076 MachineMemOperand::MODereferenceable; 1077 1078 // XXX - Should this be volatile without known ordering? 1079 Info.flags |= MachineMemOperand::MOVolatile; 1080 } 1081 return true; 1082 } 1083 1084 switch (IntrID) { 1085 case Intrinsic::amdgcn_atomic_inc: 1086 case Intrinsic::amdgcn_atomic_dec: 1087 case Intrinsic::amdgcn_ds_ordered_add: 1088 case Intrinsic::amdgcn_ds_ordered_swap: 1089 case Intrinsic::amdgcn_ds_fadd: 1090 case Intrinsic::amdgcn_ds_fmin: 1091 case Intrinsic::amdgcn_ds_fmax: { 1092 Info.opc = ISD::INTRINSIC_W_CHAIN; 1093 Info.memVT = MVT::getVT(CI.getType()); 1094 Info.ptrVal = CI.getOperand(0); 1095 Info.align.reset(); 1096 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1097 1098 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1099 if (!Vol->isZero()) 1100 Info.flags |= MachineMemOperand::MOVolatile; 1101 1102 return true; 1103 } 1104 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1105 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1106 1107 Info.opc = ISD::INTRINSIC_W_CHAIN; 1108 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1109 Info.ptrVal = 1110 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1111 Info.align.reset(); 1112 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1113 1114 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1115 if (!Vol || !Vol->isZero()) 1116 Info.flags |= MachineMemOperand::MOVolatile; 1117 1118 return true; 1119 } 1120 case Intrinsic::amdgcn_ds_append: 1121 case Intrinsic::amdgcn_ds_consume: { 1122 Info.opc = ISD::INTRINSIC_W_CHAIN; 1123 Info.memVT = MVT::getVT(CI.getType()); 1124 Info.ptrVal = CI.getOperand(0); 1125 Info.align.reset(); 1126 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1127 1128 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1129 if (!Vol->isZero()) 1130 Info.flags |= MachineMemOperand::MOVolatile; 1131 1132 return true; 1133 } 1134 case Intrinsic::amdgcn_global_atomic_csub: { 1135 Info.opc = ISD::INTRINSIC_W_CHAIN; 1136 Info.memVT = MVT::getVT(CI.getType()); 1137 Info.ptrVal = CI.getOperand(0); 1138 Info.align.reset(); 1139 Info.flags = MachineMemOperand::MOLoad | 1140 MachineMemOperand::MOStore | 1141 MachineMemOperand::MOVolatile; 1142 return true; 1143 } 1144 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1145 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1146 Info.opc = ISD::INTRINSIC_W_CHAIN; 1147 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1148 Info.ptrVal = 1149 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1150 Info.align.reset(); 1151 Info.flags = MachineMemOperand::MOLoad | 1152 MachineMemOperand::MODereferenceable; 1153 return true; 1154 } 1155 case Intrinsic::amdgcn_global_atomic_fadd: 1156 case Intrinsic::amdgcn_global_atomic_fmin: 1157 case Intrinsic::amdgcn_global_atomic_fmax: 1158 case Intrinsic::amdgcn_flat_atomic_fadd: 1159 case Intrinsic::amdgcn_flat_atomic_fmin: 1160 case Intrinsic::amdgcn_flat_atomic_fmax: { 1161 Info.opc = ISD::INTRINSIC_W_CHAIN; 1162 Info.memVT = MVT::getVT(CI.getType()); 1163 Info.ptrVal = CI.getOperand(0); 1164 Info.align.reset(); 1165 Info.flags = MachineMemOperand::MOLoad | 1166 MachineMemOperand::MOStore | 1167 MachineMemOperand::MODereferenceable | 1168 MachineMemOperand::MOVolatile; 1169 return true; 1170 } 1171 case Intrinsic::amdgcn_ds_gws_init: 1172 case Intrinsic::amdgcn_ds_gws_barrier: 1173 case Intrinsic::amdgcn_ds_gws_sema_v: 1174 case Intrinsic::amdgcn_ds_gws_sema_br: 1175 case Intrinsic::amdgcn_ds_gws_sema_p: 1176 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1177 Info.opc = ISD::INTRINSIC_VOID; 1178 1179 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1180 Info.ptrVal = 1181 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1182 1183 // This is an abstract access, but we need to specify a type and size. 1184 Info.memVT = MVT::i32; 1185 Info.size = 4; 1186 Info.align = Align(4); 1187 1188 Info.flags = MachineMemOperand::MOStore; 1189 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1190 Info.flags = MachineMemOperand::MOLoad; 1191 return true; 1192 } 1193 default: 1194 return false; 1195 } 1196 } 1197 1198 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1199 SmallVectorImpl<Value*> &Ops, 1200 Type *&AccessTy) const { 1201 switch (II->getIntrinsicID()) { 1202 case Intrinsic::amdgcn_atomic_inc: 1203 case Intrinsic::amdgcn_atomic_dec: 1204 case Intrinsic::amdgcn_ds_ordered_add: 1205 case Intrinsic::amdgcn_ds_ordered_swap: 1206 case Intrinsic::amdgcn_ds_append: 1207 case Intrinsic::amdgcn_ds_consume: 1208 case Intrinsic::amdgcn_ds_fadd: 1209 case Intrinsic::amdgcn_ds_fmin: 1210 case Intrinsic::amdgcn_ds_fmax: 1211 case Intrinsic::amdgcn_global_atomic_fadd: 1212 case Intrinsic::amdgcn_flat_atomic_fadd: 1213 case Intrinsic::amdgcn_flat_atomic_fmin: 1214 case Intrinsic::amdgcn_flat_atomic_fmax: 1215 case Intrinsic::amdgcn_global_atomic_csub: { 1216 Value *Ptr = II->getArgOperand(0); 1217 AccessTy = II->getType(); 1218 Ops.push_back(Ptr); 1219 return true; 1220 } 1221 default: 1222 return false; 1223 } 1224 } 1225 1226 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1227 if (!Subtarget->hasFlatInstOffsets()) { 1228 // Flat instructions do not have offsets, and only have the register 1229 // address. 1230 return AM.BaseOffs == 0 && AM.Scale == 0; 1231 } 1232 1233 return AM.Scale == 0 && 1234 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1235 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1236 /*Signed=*/false)); 1237 } 1238 1239 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1240 if (Subtarget->hasFlatGlobalInsts()) 1241 return AM.Scale == 0 && 1242 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1243 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1244 /*Signed=*/true)); 1245 1246 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1247 // Assume the we will use FLAT for all global memory accesses 1248 // on VI. 1249 // FIXME: This assumption is currently wrong. On VI we still use 1250 // MUBUF instructions for the r + i addressing mode. As currently 1251 // implemented, the MUBUF instructions only work on buffer < 4GB. 1252 // It may be possible to support > 4GB buffers with MUBUF instructions, 1253 // by setting the stride value in the resource descriptor which would 1254 // increase the size limit to (stride * 4GB). However, this is risky, 1255 // because it has never been validated. 1256 return isLegalFlatAddressingMode(AM); 1257 } 1258 1259 return isLegalMUBUFAddressingMode(AM); 1260 } 1261 1262 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1263 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1264 // additionally can do r + r + i with addr64. 32-bit has more addressing 1265 // mode options. Depending on the resource constant, it can also do 1266 // (i64 r0) + (i32 r1) * (i14 i). 1267 // 1268 // Private arrays end up using a scratch buffer most of the time, so also 1269 // assume those use MUBUF instructions. Scratch loads / stores are currently 1270 // implemented as mubuf instructions with offen bit set, so slightly 1271 // different than the normal addr64. 1272 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1273 return false; 1274 1275 // FIXME: Since we can split immediate into soffset and immediate offset, 1276 // would it make sense to allow any immediate? 1277 1278 switch (AM.Scale) { 1279 case 0: // r + i or just i, depending on HasBaseReg. 1280 return true; 1281 case 1: 1282 return true; // We have r + r or r + i. 1283 case 2: 1284 if (AM.HasBaseReg) { 1285 // Reject 2 * r + r. 1286 return false; 1287 } 1288 1289 // Allow 2 * r as r + r 1290 // Or 2 * r + i is allowed as r + r + i. 1291 return true; 1292 default: // Don't allow n * r 1293 return false; 1294 } 1295 } 1296 1297 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1298 const AddrMode &AM, Type *Ty, 1299 unsigned AS, Instruction *I) const { 1300 // No global is ever allowed as a base. 1301 if (AM.BaseGV) 1302 return false; 1303 1304 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1305 return isLegalGlobalAddressingMode(AM); 1306 1307 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1308 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1309 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1310 // If the offset isn't a multiple of 4, it probably isn't going to be 1311 // correctly aligned. 1312 // FIXME: Can we get the real alignment here? 1313 if (AM.BaseOffs % 4 != 0) 1314 return isLegalMUBUFAddressingMode(AM); 1315 1316 // There are no SMRD extloads, so if we have to do a small type access we 1317 // will use a MUBUF load. 1318 // FIXME?: We also need to do this if unaligned, but we don't know the 1319 // alignment here. 1320 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1321 return isLegalGlobalAddressingMode(AM); 1322 1323 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1324 // SMRD instructions have an 8-bit, dword offset on SI. 1325 if (!isUInt<8>(AM.BaseOffs / 4)) 1326 return false; 1327 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1328 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1329 // in 8-bits, it can use a smaller encoding. 1330 if (!isUInt<32>(AM.BaseOffs / 4)) 1331 return false; 1332 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1333 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1334 if (!isUInt<20>(AM.BaseOffs)) 1335 return false; 1336 } else 1337 llvm_unreachable("unhandled generation"); 1338 1339 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1340 return true; 1341 1342 if (AM.Scale == 1 && AM.HasBaseReg) 1343 return true; 1344 1345 return false; 1346 1347 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1348 return isLegalMUBUFAddressingMode(AM); 1349 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1350 AS == AMDGPUAS::REGION_ADDRESS) { 1351 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1352 // field. 1353 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1354 // an 8-bit dword offset but we don't know the alignment here. 1355 if (!isUInt<16>(AM.BaseOffs)) 1356 return false; 1357 1358 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1359 return true; 1360 1361 if (AM.Scale == 1 && AM.HasBaseReg) 1362 return true; 1363 1364 return false; 1365 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1366 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1367 // For an unknown address space, this usually means that this is for some 1368 // reason being used for pure arithmetic, and not based on some addressing 1369 // computation. We don't have instructions that compute pointers with any 1370 // addressing modes, so treat them as having no offset like flat 1371 // instructions. 1372 return isLegalFlatAddressingMode(AM); 1373 } 1374 1375 // Assume a user alias of global for unknown address spaces. 1376 return isLegalGlobalAddressingMode(AM); 1377 } 1378 1379 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1380 const SelectionDAG &DAG) const { 1381 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1382 return (MemVT.getSizeInBits() <= 4 * 32); 1383 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1384 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1385 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1386 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1387 return (MemVT.getSizeInBits() <= 2 * 32); 1388 } 1389 return true; 1390 } 1391 1392 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1393 unsigned Size, unsigned AddrSpace, Align Alignment, 1394 MachineMemOperand::Flags Flags, bool *IsFast) const { 1395 if (IsFast) 1396 *IsFast = false; 1397 1398 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1399 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1400 // Check if alignment requirements for ds_read/write instructions are 1401 // disabled. 1402 if (Subtarget->hasUnalignedDSAccessEnabled() && 1403 !Subtarget->hasLDSMisalignedBug()) { 1404 if (IsFast) 1405 *IsFast = Alignment != Align(2); 1406 return true; 1407 } 1408 1409 if (Size == 64) { 1410 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1411 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1412 // with adjacent offsets. 1413 bool AlignedBy4 = Alignment >= Align(4); 1414 if (IsFast) 1415 *IsFast = AlignedBy4; 1416 1417 return AlignedBy4; 1418 } 1419 if (Size == 96) { 1420 // ds_read/write_b96 require 16-byte alignment on gfx8 and older. 1421 bool Aligned = Alignment >= Align(16); 1422 if (IsFast) 1423 *IsFast = Aligned; 1424 1425 return Aligned; 1426 } 1427 if (Size == 128) { 1428 // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we 1429 // can do a 8 byte aligned, 16 byte access in a single operation using 1430 // ds_read2/write2_b64. 1431 bool Aligned = Alignment >= Align(8); 1432 if (IsFast) 1433 *IsFast = Aligned; 1434 1435 return Aligned; 1436 } 1437 } 1438 1439 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1440 bool AlignedBy4 = Alignment >= Align(4); 1441 if (IsFast) 1442 *IsFast = AlignedBy4; 1443 1444 return AlignedBy4 || 1445 Subtarget->enableFlatScratch() || 1446 Subtarget->hasUnalignedScratchAccess(); 1447 } 1448 1449 // FIXME: We have to be conservative here and assume that flat operations 1450 // will access scratch. If we had access to the IR function, then we 1451 // could determine if any private memory was used in the function. 1452 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1453 !Subtarget->hasUnalignedScratchAccess()) { 1454 bool AlignedBy4 = Alignment >= Align(4); 1455 if (IsFast) 1456 *IsFast = AlignedBy4; 1457 1458 return AlignedBy4; 1459 } 1460 1461 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1462 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1463 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1464 // If we have an uniform constant load, it still requires using a slow 1465 // buffer instruction if unaligned. 1466 if (IsFast) { 1467 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1468 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1469 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1470 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1471 Alignment >= Align(4) : Alignment != Align(2); 1472 } 1473 1474 return true; 1475 } 1476 1477 // Smaller than dword value must be aligned. 1478 if (Size < 32) 1479 return false; 1480 1481 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1482 // byte-address are ignored, thus forcing Dword alignment. 1483 // This applies to private, global, and constant memory. 1484 if (IsFast) 1485 *IsFast = true; 1486 1487 return Size >= 32 && Alignment >= Align(4); 1488 } 1489 1490 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1491 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1492 bool *IsFast) const { 1493 if (IsFast) 1494 *IsFast = false; 1495 1496 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1497 // which isn't a simple VT. 1498 // Until MVT is extended to handle this, simply check for the size and 1499 // rely on the condition below: allow accesses if the size is a multiple of 4. 1500 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1501 VT.getStoreSize() > 16)) { 1502 return false; 1503 } 1504 1505 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1506 Alignment, Flags, IsFast); 1507 } 1508 1509 EVT SITargetLowering::getOptimalMemOpType( 1510 const MemOp &Op, const AttributeList &FuncAttributes) const { 1511 // FIXME: Should account for address space here. 1512 1513 // The default fallback uses the private pointer size as a guess for a type to 1514 // use. Make sure we switch these to 64-bit accesses. 1515 1516 if (Op.size() >= 16 && 1517 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1518 return MVT::v4i32; 1519 1520 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1521 return MVT::v2i32; 1522 1523 // Use the default. 1524 return MVT::Other; 1525 } 1526 1527 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1528 const MemSDNode *MemNode = cast<MemSDNode>(N); 1529 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1530 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1531 return I && I->getMetadata("amdgpu.noclobber"); 1532 } 1533 1534 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1535 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1536 AS == AMDGPUAS::PRIVATE_ADDRESS; 1537 } 1538 1539 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1540 unsigned DestAS) const { 1541 // Flat -> private/local is a simple truncate. 1542 // Flat -> global is no-op 1543 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1544 return true; 1545 1546 const GCNTargetMachine &TM = 1547 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1548 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1549 } 1550 1551 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1552 const MemSDNode *MemNode = cast<MemSDNode>(N); 1553 1554 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1555 } 1556 1557 TargetLoweringBase::LegalizeTypeAction 1558 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1559 int NumElts = VT.getVectorNumElements(); 1560 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1561 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1562 return TargetLoweringBase::getPreferredVectorAction(VT); 1563 } 1564 1565 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1566 Type *Ty) const { 1567 // FIXME: Could be smarter if called for vector constants. 1568 return true; 1569 } 1570 1571 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1572 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1573 switch (Op) { 1574 case ISD::LOAD: 1575 case ISD::STORE: 1576 1577 // These operations are done with 32-bit instructions anyway. 1578 case ISD::AND: 1579 case ISD::OR: 1580 case ISD::XOR: 1581 case ISD::SELECT: 1582 // TODO: Extensions? 1583 return true; 1584 default: 1585 return false; 1586 } 1587 } 1588 1589 // SimplifySetCC uses this function to determine whether or not it should 1590 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1591 if (VT == MVT::i1 && Op == ISD::SETCC) 1592 return false; 1593 1594 return TargetLowering::isTypeDesirableForOp(Op, VT); 1595 } 1596 1597 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1598 const SDLoc &SL, 1599 SDValue Chain, 1600 uint64_t Offset) const { 1601 const DataLayout &DL = DAG.getDataLayout(); 1602 MachineFunction &MF = DAG.getMachineFunction(); 1603 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1604 1605 const ArgDescriptor *InputPtrReg; 1606 const TargetRegisterClass *RC; 1607 LLT ArgTy; 1608 1609 std::tie(InputPtrReg, RC, ArgTy) = 1610 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1611 1612 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1613 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1614 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1615 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1616 1617 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1618 } 1619 1620 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1621 const SDLoc &SL) const { 1622 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1623 FIRST_IMPLICIT); 1624 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1625 } 1626 1627 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1628 const SDLoc &SL, SDValue Val, 1629 bool Signed, 1630 const ISD::InputArg *Arg) const { 1631 // First, if it is a widened vector, narrow it. 1632 if (VT.isVector() && 1633 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1634 EVT NarrowedVT = 1635 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1636 VT.getVectorNumElements()); 1637 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1638 DAG.getConstant(0, SL, MVT::i32)); 1639 } 1640 1641 // Then convert the vector elements or scalar value. 1642 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1643 VT.bitsLT(MemVT)) { 1644 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1645 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1646 } 1647 1648 if (MemVT.isFloatingPoint()) 1649 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1650 else if (Signed) 1651 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1652 else 1653 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1654 1655 return Val; 1656 } 1657 1658 SDValue SITargetLowering::lowerKernargMemParameter( 1659 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1660 uint64_t Offset, Align Alignment, bool Signed, 1661 const ISD::InputArg *Arg) const { 1662 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1663 1664 // Try to avoid using an extload by loading earlier than the argument address, 1665 // and extracting the relevant bits. The load should hopefully be merged with 1666 // the previous argument. 1667 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1668 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1669 int64_t AlignDownOffset = alignDown(Offset, 4); 1670 int64_t OffsetDiff = Offset - AlignDownOffset; 1671 1672 EVT IntVT = MemVT.changeTypeToInteger(); 1673 1674 // TODO: If we passed in the base kernel offset we could have a better 1675 // alignment than 4, but we don't really need it. 1676 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1677 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1678 MachineMemOperand::MODereferenceable | 1679 MachineMemOperand::MOInvariant); 1680 1681 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1682 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1683 1684 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1685 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1686 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1687 1688 1689 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1690 } 1691 1692 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1693 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1694 MachineMemOperand::MODereferenceable | 1695 MachineMemOperand::MOInvariant); 1696 1697 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1698 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1699 } 1700 1701 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1702 const SDLoc &SL, SDValue Chain, 1703 const ISD::InputArg &Arg) const { 1704 MachineFunction &MF = DAG.getMachineFunction(); 1705 MachineFrameInfo &MFI = MF.getFrameInfo(); 1706 1707 if (Arg.Flags.isByVal()) { 1708 unsigned Size = Arg.Flags.getByValSize(); 1709 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1710 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1711 } 1712 1713 unsigned ArgOffset = VA.getLocMemOffset(); 1714 unsigned ArgSize = VA.getValVT().getStoreSize(); 1715 1716 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1717 1718 // Create load nodes to retrieve arguments from the stack. 1719 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1720 SDValue ArgValue; 1721 1722 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1723 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1724 MVT MemVT = VA.getValVT(); 1725 1726 switch (VA.getLocInfo()) { 1727 default: 1728 break; 1729 case CCValAssign::BCvt: 1730 MemVT = VA.getLocVT(); 1731 break; 1732 case CCValAssign::SExt: 1733 ExtType = ISD::SEXTLOAD; 1734 break; 1735 case CCValAssign::ZExt: 1736 ExtType = ISD::ZEXTLOAD; 1737 break; 1738 case CCValAssign::AExt: 1739 ExtType = ISD::EXTLOAD; 1740 break; 1741 } 1742 1743 ArgValue = DAG.getExtLoad( 1744 ExtType, SL, VA.getLocVT(), Chain, FIN, 1745 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1746 MemVT); 1747 return ArgValue; 1748 } 1749 1750 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1751 const SIMachineFunctionInfo &MFI, 1752 EVT VT, 1753 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1754 const ArgDescriptor *Reg; 1755 const TargetRegisterClass *RC; 1756 LLT Ty; 1757 1758 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1759 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1760 } 1761 1762 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1763 CallingConv::ID CallConv, 1764 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1765 FunctionType *FType, 1766 SIMachineFunctionInfo *Info) { 1767 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1768 const ISD::InputArg *Arg = &Ins[I]; 1769 1770 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1771 "vector type argument should have been split"); 1772 1773 // First check if it's a PS input addr. 1774 if (CallConv == CallingConv::AMDGPU_PS && 1775 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1776 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1777 1778 // Inconveniently only the first part of the split is marked as isSplit, 1779 // so skip to the end. We only want to increment PSInputNum once for the 1780 // entire split argument. 1781 if (Arg->Flags.isSplit()) { 1782 while (!Arg->Flags.isSplitEnd()) { 1783 assert((!Arg->VT.isVector() || 1784 Arg->VT.getScalarSizeInBits() == 16) && 1785 "unexpected vector split in ps argument type"); 1786 if (!SkipArg) 1787 Splits.push_back(*Arg); 1788 Arg = &Ins[++I]; 1789 } 1790 } 1791 1792 if (SkipArg) { 1793 // We can safely skip PS inputs. 1794 Skipped.set(Arg->getOrigArgIndex()); 1795 ++PSInputNum; 1796 continue; 1797 } 1798 1799 Info->markPSInputAllocated(PSInputNum); 1800 if (Arg->Used) 1801 Info->markPSInputEnabled(PSInputNum); 1802 1803 ++PSInputNum; 1804 } 1805 1806 Splits.push_back(*Arg); 1807 } 1808 } 1809 1810 // Allocate special inputs passed in VGPRs. 1811 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1812 MachineFunction &MF, 1813 const SIRegisterInfo &TRI, 1814 SIMachineFunctionInfo &Info) const { 1815 const LLT S32 = LLT::scalar(32); 1816 MachineRegisterInfo &MRI = MF.getRegInfo(); 1817 1818 if (Info.hasWorkItemIDX()) { 1819 Register Reg = AMDGPU::VGPR0; 1820 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1821 1822 CCInfo.AllocateReg(Reg); 1823 unsigned Mask = (Subtarget->hasPackedTID() && 1824 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 1825 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1826 } 1827 1828 if (Info.hasWorkItemIDY()) { 1829 assert(Info.hasWorkItemIDX()); 1830 if (Subtarget->hasPackedTID()) { 1831 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1832 0x3ff << 10)); 1833 } else { 1834 unsigned Reg = AMDGPU::VGPR1; 1835 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1836 1837 CCInfo.AllocateReg(Reg); 1838 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1839 } 1840 } 1841 1842 if (Info.hasWorkItemIDZ()) { 1843 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 1844 if (Subtarget->hasPackedTID()) { 1845 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1846 0x3ff << 20)); 1847 } else { 1848 unsigned Reg = AMDGPU::VGPR2; 1849 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1850 1851 CCInfo.AllocateReg(Reg); 1852 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1853 } 1854 } 1855 } 1856 1857 // Try to allocate a VGPR at the end of the argument list, or if no argument 1858 // VGPRs are left allocating a stack slot. 1859 // If \p Mask is is given it indicates bitfield position in the register. 1860 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1861 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1862 ArgDescriptor Arg = ArgDescriptor()) { 1863 if (Arg.isSet()) 1864 return ArgDescriptor::createArg(Arg, Mask); 1865 1866 ArrayRef<MCPhysReg> ArgVGPRs 1867 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1868 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1869 if (RegIdx == ArgVGPRs.size()) { 1870 // Spill to stack required. 1871 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1872 1873 return ArgDescriptor::createStack(Offset, Mask); 1874 } 1875 1876 unsigned Reg = ArgVGPRs[RegIdx]; 1877 Reg = CCInfo.AllocateReg(Reg); 1878 assert(Reg != AMDGPU::NoRegister); 1879 1880 MachineFunction &MF = CCInfo.getMachineFunction(); 1881 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1882 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1883 return ArgDescriptor::createRegister(Reg, Mask); 1884 } 1885 1886 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1887 const TargetRegisterClass *RC, 1888 unsigned NumArgRegs) { 1889 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1890 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1891 if (RegIdx == ArgSGPRs.size()) 1892 report_fatal_error("ran out of SGPRs for arguments"); 1893 1894 unsigned Reg = ArgSGPRs[RegIdx]; 1895 Reg = CCInfo.AllocateReg(Reg); 1896 assert(Reg != AMDGPU::NoRegister); 1897 1898 MachineFunction &MF = CCInfo.getMachineFunction(); 1899 MF.addLiveIn(Reg, RC); 1900 return ArgDescriptor::createRegister(Reg); 1901 } 1902 1903 // If this has a fixed position, we still should allocate the register in the 1904 // CCInfo state. Technically we could get away with this for values passed 1905 // outside of the normal argument range. 1906 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 1907 const TargetRegisterClass *RC, 1908 MCRegister Reg) { 1909 Reg = CCInfo.AllocateReg(Reg); 1910 assert(Reg != AMDGPU::NoRegister); 1911 MachineFunction &MF = CCInfo.getMachineFunction(); 1912 MF.addLiveIn(Reg, RC); 1913 } 1914 1915 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 1916 if (Arg) { 1917 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 1918 Arg.getRegister()); 1919 } else 1920 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1921 } 1922 1923 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 1924 if (Arg) { 1925 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 1926 Arg.getRegister()); 1927 } else 1928 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1929 } 1930 1931 /// Allocate implicit function VGPR arguments at the end of allocated user 1932 /// arguments. 1933 void SITargetLowering::allocateSpecialInputVGPRs( 1934 CCState &CCInfo, MachineFunction &MF, 1935 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1936 const unsigned Mask = 0x3ff; 1937 ArgDescriptor Arg; 1938 1939 if (Info.hasWorkItemIDX()) { 1940 Arg = allocateVGPR32Input(CCInfo, Mask); 1941 Info.setWorkItemIDX(Arg); 1942 } 1943 1944 if (Info.hasWorkItemIDY()) { 1945 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1946 Info.setWorkItemIDY(Arg); 1947 } 1948 1949 if (Info.hasWorkItemIDZ()) 1950 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1951 } 1952 1953 /// Allocate implicit function VGPR arguments in fixed registers. 1954 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1955 CCState &CCInfo, MachineFunction &MF, 1956 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1957 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1958 if (!Reg) 1959 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1960 1961 const unsigned Mask = 0x3ff; 1962 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1963 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1964 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1965 } 1966 1967 void SITargetLowering::allocateSpecialInputSGPRs( 1968 CCState &CCInfo, 1969 MachineFunction &MF, 1970 const SIRegisterInfo &TRI, 1971 SIMachineFunctionInfo &Info) const { 1972 auto &ArgInfo = Info.getArgInfo(); 1973 1974 // TODO: Unify handling with private memory pointers. 1975 1976 if (Info.hasDispatchPtr()) 1977 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 1978 1979 if (Info.hasQueuePtr()) 1980 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 1981 1982 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1983 // constant offset from the kernarg segment. 1984 if (Info.hasImplicitArgPtr()) 1985 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 1986 1987 if (Info.hasDispatchID()) 1988 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 1989 1990 // flat_scratch_init is not applicable for non-kernel functions. 1991 1992 if (Info.hasWorkGroupIDX()) 1993 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 1994 1995 if (Info.hasWorkGroupIDY()) 1996 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 1997 1998 if (Info.hasWorkGroupIDZ()) 1999 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2000 } 2001 2002 // Allocate special inputs passed in user SGPRs. 2003 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2004 MachineFunction &MF, 2005 const SIRegisterInfo &TRI, 2006 SIMachineFunctionInfo &Info) const { 2007 if (Info.hasImplicitBufferPtr()) { 2008 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2009 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2010 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2011 } 2012 2013 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2014 if (Info.hasPrivateSegmentBuffer()) { 2015 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2016 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2017 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2018 } 2019 2020 if (Info.hasDispatchPtr()) { 2021 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2022 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2023 CCInfo.AllocateReg(DispatchPtrReg); 2024 } 2025 2026 if (Info.hasQueuePtr()) { 2027 Register QueuePtrReg = Info.addQueuePtr(TRI); 2028 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2029 CCInfo.AllocateReg(QueuePtrReg); 2030 } 2031 2032 if (Info.hasKernargSegmentPtr()) { 2033 MachineRegisterInfo &MRI = MF.getRegInfo(); 2034 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2035 CCInfo.AllocateReg(InputPtrReg); 2036 2037 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2038 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2039 } 2040 2041 if (Info.hasDispatchID()) { 2042 Register DispatchIDReg = Info.addDispatchID(TRI); 2043 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2044 CCInfo.AllocateReg(DispatchIDReg); 2045 } 2046 2047 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2048 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2049 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2050 CCInfo.AllocateReg(FlatScratchInitReg); 2051 } 2052 2053 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2054 // these from the dispatch pointer. 2055 } 2056 2057 // Allocate special input registers that are initialized per-wave. 2058 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2059 MachineFunction &MF, 2060 SIMachineFunctionInfo &Info, 2061 CallingConv::ID CallConv, 2062 bool IsShader) const { 2063 if (Info.hasWorkGroupIDX()) { 2064 Register Reg = Info.addWorkGroupIDX(); 2065 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2066 CCInfo.AllocateReg(Reg); 2067 } 2068 2069 if (Info.hasWorkGroupIDY()) { 2070 Register Reg = Info.addWorkGroupIDY(); 2071 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2072 CCInfo.AllocateReg(Reg); 2073 } 2074 2075 if (Info.hasWorkGroupIDZ()) { 2076 Register Reg = Info.addWorkGroupIDZ(); 2077 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2078 CCInfo.AllocateReg(Reg); 2079 } 2080 2081 if (Info.hasWorkGroupInfo()) { 2082 Register Reg = Info.addWorkGroupInfo(); 2083 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2084 CCInfo.AllocateReg(Reg); 2085 } 2086 2087 if (Info.hasPrivateSegmentWaveByteOffset()) { 2088 // Scratch wave offset passed in system SGPR. 2089 unsigned PrivateSegmentWaveByteOffsetReg; 2090 2091 if (IsShader) { 2092 PrivateSegmentWaveByteOffsetReg = 2093 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2094 2095 // This is true if the scratch wave byte offset doesn't have a fixed 2096 // location. 2097 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2098 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2099 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2100 } 2101 } else 2102 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2103 2104 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2105 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2106 } 2107 } 2108 2109 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2110 MachineFunction &MF, 2111 const SIRegisterInfo &TRI, 2112 SIMachineFunctionInfo &Info) { 2113 // Now that we've figured out where the scratch register inputs are, see if 2114 // should reserve the arguments and use them directly. 2115 MachineFrameInfo &MFI = MF.getFrameInfo(); 2116 bool HasStackObjects = MFI.hasStackObjects(); 2117 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2118 2119 // Record that we know we have non-spill stack objects so we don't need to 2120 // check all stack objects later. 2121 if (HasStackObjects) 2122 Info.setHasNonSpillStackObjects(true); 2123 2124 // Everything live out of a block is spilled with fast regalloc, so it's 2125 // almost certain that spilling will be required. 2126 if (TM.getOptLevel() == CodeGenOpt::None) 2127 HasStackObjects = true; 2128 2129 // For now assume stack access is needed in any callee functions, so we need 2130 // the scratch registers to pass in. 2131 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2132 2133 if (!ST.enableFlatScratch()) { 2134 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2135 // If we have stack objects, we unquestionably need the private buffer 2136 // resource. For the Code Object V2 ABI, this will be the first 4 user 2137 // SGPR inputs. We can reserve those and use them directly. 2138 2139 Register PrivateSegmentBufferReg = 2140 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2141 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2142 } else { 2143 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2144 // We tentatively reserve the last registers (skipping the last registers 2145 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2146 // we'll replace these with the ones immediately after those which were 2147 // really allocated. In the prologue copies will be inserted from the 2148 // argument to these reserved registers. 2149 2150 // Without HSA, relocations are used for the scratch pointer and the 2151 // buffer resource setup is always inserted in the prologue. Scratch wave 2152 // offset is still in an input SGPR. 2153 Info.setScratchRSrcReg(ReservedBufferReg); 2154 } 2155 } 2156 2157 MachineRegisterInfo &MRI = MF.getRegInfo(); 2158 2159 // For entry functions we have to set up the stack pointer if we use it, 2160 // whereas non-entry functions get this "for free". This means there is no 2161 // intrinsic advantage to using S32 over S34 in cases where we do not have 2162 // calls but do need a frame pointer (i.e. if we are requested to have one 2163 // because frame pointer elimination is disabled). To keep things simple we 2164 // only ever use S32 as the call ABI stack pointer, and so using it does not 2165 // imply we need a separate frame pointer. 2166 // 2167 // Try to use s32 as the SP, but move it if it would interfere with input 2168 // arguments. This won't work with calls though. 2169 // 2170 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2171 // registers. 2172 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2173 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2174 } else { 2175 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2176 2177 if (MFI.hasCalls()) 2178 report_fatal_error("call in graphics shader with too many input SGPRs"); 2179 2180 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2181 if (!MRI.isLiveIn(Reg)) { 2182 Info.setStackPtrOffsetReg(Reg); 2183 break; 2184 } 2185 } 2186 2187 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2188 report_fatal_error("failed to find register for SP"); 2189 } 2190 2191 // hasFP should be accurate for entry functions even before the frame is 2192 // finalized, because it does not rely on the known stack size, only 2193 // properties like whether variable sized objects are present. 2194 if (ST.getFrameLowering()->hasFP(MF)) { 2195 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2196 } 2197 } 2198 2199 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2200 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2201 return !Info->isEntryFunction(); 2202 } 2203 2204 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2205 2206 } 2207 2208 void SITargetLowering::insertCopiesSplitCSR( 2209 MachineBasicBlock *Entry, 2210 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2211 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2212 2213 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2214 if (!IStart) 2215 return; 2216 2217 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2218 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2219 MachineBasicBlock::iterator MBBI = Entry->begin(); 2220 for (const MCPhysReg *I = IStart; *I; ++I) { 2221 const TargetRegisterClass *RC = nullptr; 2222 if (AMDGPU::SReg_64RegClass.contains(*I)) 2223 RC = &AMDGPU::SGPR_64RegClass; 2224 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2225 RC = &AMDGPU::SGPR_32RegClass; 2226 else 2227 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2228 2229 Register NewVR = MRI->createVirtualRegister(RC); 2230 // Create copy from CSR to a virtual register. 2231 Entry->addLiveIn(*I); 2232 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2233 .addReg(*I); 2234 2235 // Insert the copy-back instructions right before the terminator. 2236 for (auto *Exit : Exits) 2237 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2238 TII->get(TargetOpcode::COPY), *I) 2239 .addReg(NewVR); 2240 } 2241 } 2242 2243 SDValue SITargetLowering::LowerFormalArguments( 2244 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2245 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2246 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2247 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2248 2249 MachineFunction &MF = DAG.getMachineFunction(); 2250 const Function &Fn = MF.getFunction(); 2251 FunctionType *FType = MF.getFunction().getFunctionType(); 2252 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2253 2254 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2255 DiagnosticInfoUnsupported NoGraphicsHSA( 2256 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2257 DAG.getContext()->diagnose(NoGraphicsHSA); 2258 return DAG.getEntryNode(); 2259 } 2260 2261 SmallVector<ISD::InputArg, 16> Splits; 2262 SmallVector<CCValAssign, 16> ArgLocs; 2263 BitVector Skipped(Ins.size()); 2264 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2265 *DAG.getContext()); 2266 2267 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2268 bool IsKernel = AMDGPU::isKernel(CallConv); 2269 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2270 2271 if (IsGraphics) { 2272 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2273 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2274 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2275 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2276 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2277 !Info->hasWorkItemIDZ()); 2278 } 2279 2280 if (CallConv == CallingConv::AMDGPU_PS) { 2281 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2282 2283 // At least one interpolation mode must be enabled or else the GPU will 2284 // hang. 2285 // 2286 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2287 // set PSInputAddr, the user wants to enable some bits after the compilation 2288 // based on run-time states. Since we can't know what the final PSInputEna 2289 // will look like, so we shouldn't do anything here and the user should take 2290 // responsibility for the correct programming. 2291 // 2292 // Otherwise, the following restrictions apply: 2293 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2294 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2295 // enabled too. 2296 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2297 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2298 CCInfo.AllocateReg(AMDGPU::VGPR0); 2299 CCInfo.AllocateReg(AMDGPU::VGPR1); 2300 Info->markPSInputAllocated(0); 2301 Info->markPSInputEnabled(0); 2302 } 2303 if (Subtarget->isAmdPalOS()) { 2304 // For isAmdPalOS, the user does not enable some bits after compilation 2305 // based on run-time states; the register values being generated here are 2306 // the final ones set in hardware. Therefore we need to apply the 2307 // workaround to PSInputAddr and PSInputEnable together. (The case where 2308 // a bit is set in PSInputAddr but not PSInputEnable is where the 2309 // frontend set up an input arg for a particular interpolation mode, but 2310 // nothing uses that input arg. Really we should have an earlier pass 2311 // that removes such an arg.) 2312 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2313 if ((PsInputBits & 0x7F) == 0 || 2314 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2315 Info->markPSInputEnabled( 2316 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2317 } 2318 } else if (IsKernel) { 2319 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2320 } else { 2321 Splits.append(Ins.begin(), Ins.end()); 2322 } 2323 2324 if (IsEntryFunc) { 2325 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2326 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2327 } else { 2328 // For the fixed ABI, pass workitem IDs in the last argument register. 2329 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2330 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2331 } 2332 2333 if (IsKernel) { 2334 analyzeFormalArgumentsCompute(CCInfo, Ins); 2335 } else { 2336 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2337 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2338 } 2339 2340 SmallVector<SDValue, 16> Chains; 2341 2342 // FIXME: This is the minimum kernel argument alignment. We should improve 2343 // this to the maximum alignment of the arguments. 2344 // 2345 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2346 // kern arg offset. 2347 const Align KernelArgBaseAlign = Align(16); 2348 2349 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2350 const ISD::InputArg &Arg = Ins[i]; 2351 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2352 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2353 continue; 2354 } 2355 2356 CCValAssign &VA = ArgLocs[ArgIdx++]; 2357 MVT VT = VA.getLocVT(); 2358 2359 if (IsEntryFunc && VA.isMemLoc()) { 2360 VT = Ins[i].VT; 2361 EVT MemVT = VA.getLocVT(); 2362 2363 const uint64_t Offset = VA.getLocMemOffset(); 2364 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2365 2366 if (Arg.Flags.isByRef()) { 2367 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2368 2369 const GCNTargetMachine &TM = 2370 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2371 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2372 Arg.Flags.getPointerAddrSpace())) { 2373 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2374 Arg.Flags.getPointerAddrSpace()); 2375 } 2376 2377 InVals.push_back(Ptr); 2378 continue; 2379 } 2380 2381 SDValue Arg = lowerKernargMemParameter( 2382 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2383 Chains.push_back(Arg.getValue(1)); 2384 2385 auto *ParamTy = 2386 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2387 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2388 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2389 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2390 // On SI local pointers are just offsets into LDS, so they are always 2391 // less than 16-bits. On CI and newer they could potentially be 2392 // real pointers, so we can't guarantee their size. 2393 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2394 DAG.getValueType(MVT::i16)); 2395 } 2396 2397 InVals.push_back(Arg); 2398 continue; 2399 } else if (!IsEntryFunc && VA.isMemLoc()) { 2400 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2401 InVals.push_back(Val); 2402 if (!Arg.Flags.isByVal()) 2403 Chains.push_back(Val.getValue(1)); 2404 continue; 2405 } 2406 2407 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2408 2409 Register Reg = VA.getLocReg(); 2410 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2411 EVT ValVT = VA.getValVT(); 2412 2413 Reg = MF.addLiveIn(Reg, RC); 2414 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2415 2416 if (Arg.Flags.isSRet()) { 2417 // The return object should be reasonably addressable. 2418 2419 // FIXME: This helps when the return is a real sret. If it is a 2420 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2421 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2422 unsigned NumBits 2423 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2424 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2425 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2426 } 2427 2428 // If this is an 8 or 16-bit value, it is really passed promoted 2429 // to 32 bits. Insert an assert[sz]ext to capture this, then 2430 // truncate to the right size. 2431 switch (VA.getLocInfo()) { 2432 case CCValAssign::Full: 2433 break; 2434 case CCValAssign::BCvt: 2435 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2436 break; 2437 case CCValAssign::SExt: 2438 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2439 DAG.getValueType(ValVT)); 2440 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2441 break; 2442 case CCValAssign::ZExt: 2443 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2444 DAG.getValueType(ValVT)); 2445 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2446 break; 2447 case CCValAssign::AExt: 2448 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2449 break; 2450 default: 2451 llvm_unreachable("Unknown loc info!"); 2452 } 2453 2454 InVals.push_back(Val); 2455 } 2456 2457 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2458 // Special inputs come after user arguments. 2459 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2460 } 2461 2462 // Start adding system SGPRs. 2463 if (IsEntryFunc) { 2464 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2465 } else { 2466 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2467 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2468 } 2469 2470 auto &ArgUsageInfo = 2471 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2472 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2473 2474 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2475 Info->setBytesInStackArgArea(StackArgSize); 2476 2477 return Chains.empty() ? Chain : 2478 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2479 } 2480 2481 // TODO: If return values can't fit in registers, we should return as many as 2482 // possible in registers before passing on stack. 2483 bool SITargetLowering::CanLowerReturn( 2484 CallingConv::ID CallConv, 2485 MachineFunction &MF, bool IsVarArg, 2486 const SmallVectorImpl<ISD::OutputArg> &Outs, 2487 LLVMContext &Context) const { 2488 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2489 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2490 // for shaders. Vector types should be explicitly handled by CC. 2491 if (AMDGPU::isEntryFunctionCC(CallConv)) 2492 return true; 2493 2494 SmallVector<CCValAssign, 16> RVLocs; 2495 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2496 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2497 } 2498 2499 SDValue 2500 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2501 bool isVarArg, 2502 const SmallVectorImpl<ISD::OutputArg> &Outs, 2503 const SmallVectorImpl<SDValue> &OutVals, 2504 const SDLoc &DL, SelectionDAG &DAG) const { 2505 MachineFunction &MF = DAG.getMachineFunction(); 2506 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2507 2508 if (AMDGPU::isKernel(CallConv)) { 2509 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2510 OutVals, DL, DAG); 2511 } 2512 2513 bool IsShader = AMDGPU::isShader(CallConv); 2514 2515 Info->setIfReturnsVoid(Outs.empty()); 2516 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2517 2518 // CCValAssign - represent the assignment of the return value to a location. 2519 SmallVector<CCValAssign, 48> RVLocs; 2520 SmallVector<ISD::OutputArg, 48> Splits; 2521 2522 // CCState - Info about the registers and stack slots. 2523 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2524 *DAG.getContext()); 2525 2526 // Analyze outgoing return values. 2527 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2528 2529 SDValue Flag; 2530 SmallVector<SDValue, 48> RetOps; 2531 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2532 2533 // Add return address for callable functions. 2534 if (!Info->isEntryFunction()) { 2535 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2536 SDValue ReturnAddrReg = CreateLiveInRegister( 2537 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2538 2539 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2540 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2541 MVT::i64); 2542 Chain = 2543 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2544 Flag = Chain.getValue(1); 2545 RetOps.push_back(ReturnAddrVirtualReg); 2546 } 2547 2548 // Copy the result values into the output registers. 2549 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2550 ++I, ++RealRVLocIdx) { 2551 CCValAssign &VA = RVLocs[I]; 2552 assert(VA.isRegLoc() && "Can only return in registers!"); 2553 // TODO: Partially return in registers if return values don't fit. 2554 SDValue Arg = OutVals[RealRVLocIdx]; 2555 2556 // Copied from other backends. 2557 switch (VA.getLocInfo()) { 2558 case CCValAssign::Full: 2559 break; 2560 case CCValAssign::BCvt: 2561 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2562 break; 2563 case CCValAssign::SExt: 2564 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2565 break; 2566 case CCValAssign::ZExt: 2567 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2568 break; 2569 case CCValAssign::AExt: 2570 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2571 break; 2572 default: 2573 llvm_unreachable("Unknown loc info!"); 2574 } 2575 2576 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2577 Flag = Chain.getValue(1); 2578 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2579 } 2580 2581 // FIXME: Does sret work properly? 2582 if (!Info->isEntryFunction()) { 2583 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2584 const MCPhysReg *I = 2585 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2586 if (I) { 2587 for (; *I; ++I) { 2588 if (AMDGPU::SReg_64RegClass.contains(*I)) 2589 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2590 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2591 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2592 else 2593 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2594 } 2595 } 2596 } 2597 2598 // Update chain and glue. 2599 RetOps[0] = Chain; 2600 if (Flag.getNode()) 2601 RetOps.push_back(Flag); 2602 2603 unsigned Opc = AMDGPUISD::ENDPGM; 2604 if (!IsWaveEnd) 2605 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2606 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2607 } 2608 2609 SDValue SITargetLowering::LowerCallResult( 2610 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2611 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2612 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2613 SDValue ThisVal) const { 2614 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2615 2616 // Assign locations to each value returned by this call. 2617 SmallVector<CCValAssign, 16> RVLocs; 2618 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2619 *DAG.getContext()); 2620 CCInfo.AnalyzeCallResult(Ins, RetCC); 2621 2622 // Copy all of the result registers out of their specified physreg. 2623 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2624 CCValAssign VA = RVLocs[i]; 2625 SDValue Val; 2626 2627 if (VA.isRegLoc()) { 2628 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2629 Chain = Val.getValue(1); 2630 InFlag = Val.getValue(2); 2631 } else if (VA.isMemLoc()) { 2632 report_fatal_error("TODO: return values in memory"); 2633 } else 2634 llvm_unreachable("unknown argument location type"); 2635 2636 switch (VA.getLocInfo()) { 2637 case CCValAssign::Full: 2638 break; 2639 case CCValAssign::BCvt: 2640 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2641 break; 2642 case CCValAssign::ZExt: 2643 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2644 DAG.getValueType(VA.getValVT())); 2645 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2646 break; 2647 case CCValAssign::SExt: 2648 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2649 DAG.getValueType(VA.getValVT())); 2650 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2651 break; 2652 case CCValAssign::AExt: 2653 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2654 break; 2655 default: 2656 llvm_unreachable("Unknown loc info!"); 2657 } 2658 2659 InVals.push_back(Val); 2660 } 2661 2662 return Chain; 2663 } 2664 2665 // Add code to pass special inputs required depending on used features separate 2666 // from the explicit user arguments present in the IR. 2667 void SITargetLowering::passSpecialInputs( 2668 CallLoweringInfo &CLI, 2669 CCState &CCInfo, 2670 const SIMachineFunctionInfo &Info, 2671 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2672 SmallVectorImpl<SDValue> &MemOpChains, 2673 SDValue Chain) const { 2674 // If we don't have a call site, this was a call inserted by 2675 // legalization. These can never use special inputs. 2676 if (!CLI.CB) 2677 return; 2678 2679 SelectionDAG &DAG = CLI.DAG; 2680 const SDLoc &DL = CLI.DL; 2681 2682 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2683 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2684 2685 const AMDGPUFunctionArgInfo *CalleeArgInfo 2686 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2687 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2688 auto &ArgUsageInfo = 2689 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2690 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2691 } 2692 2693 // TODO: Unify with private memory register handling. This is complicated by 2694 // the fact that at least in kernels, the input argument is not necessarily 2695 // in the same location as the input. 2696 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2697 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2698 AMDGPUFunctionArgInfo::QUEUE_PTR, 2699 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2700 AMDGPUFunctionArgInfo::DISPATCH_ID, 2701 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2702 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2703 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2704 }; 2705 2706 for (auto InputID : InputRegs) { 2707 const ArgDescriptor *OutgoingArg; 2708 const TargetRegisterClass *ArgRC; 2709 LLT ArgTy; 2710 2711 std::tie(OutgoingArg, ArgRC, ArgTy) = 2712 CalleeArgInfo->getPreloadedValue(InputID); 2713 if (!OutgoingArg) 2714 continue; 2715 2716 const ArgDescriptor *IncomingArg; 2717 const TargetRegisterClass *IncomingArgRC; 2718 LLT Ty; 2719 std::tie(IncomingArg, IncomingArgRC, Ty) = 2720 CallerArgInfo.getPreloadedValue(InputID); 2721 assert(IncomingArgRC == ArgRC); 2722 2723 // All special arguments are ints for now. 2724 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2725 SDValue InputReg; 2726 2727 if (IncomingArg) { 2728 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2729 } else { 2730 // The implicit arg ptr is special because it doesn't have a corresponding 2731 // input for kernels, and is computed from the kernarg segment pointer. 2732 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2733 InputReg = getImplicitArgPtr(DAG, DL); 2734 } 2735 2736 if (OutgoingArg->isRegister()) { 2737 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2738 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2739 report_fatal_error("failed to allocate implicit input argument"); 2740 } else { 2741 unsigned SpecialArgOffset = 2742 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2743 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2744 SpecialArgOffset); 2745 MemOpChains.push_back(ArgStore); 2746 } 2747 } 2748 2749 // Pack workitem IDs into a single register or pass it as is if already 2750 // packed. 2751 const ArgDescriptor *OutgoingArg; 2752 const TargetRegisterClass *ArgRC; 2753 LLT Ty; 2754 2755 std::tie(OutgoingArg, ArgRC, Ty) = 2756 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2757 if (!OutgoingArg) 2758 std::tie(OutgoingArg, ArgRC, Ty) = 2759 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2760 if (!OutgoingArg) 2761 std::tie(OutgoingArg, ArgRC, Ty) = 2762 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2763 if (!OutgoingArg) 2764 return; 2765 2766 const ArgDescriptor *IncomingArgX = std::get<0>( 2767 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2768 const ArgDescriptor *IncomingArgY = std::get<0>( 2769 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2770 const ArgDescriptor *IncomingArgZ = std::get<0>( 2771 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2772 2773 SDValue InputReg; 2774 SDLoc SL; 2775 2776 // If incoming ids are not packed we need to pack them. 2777 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2778 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2779 2780 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2781 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2782 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2783 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2784 InputReg = InputReg.getNode() ? 2785 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2786 } 2787 2788 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2789 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2790 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2791 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2792 InputReg = InputReg.getNode() ? 2793 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2794 } 2795 2796 if (!InputReg.getNode()) { 2797 // Workitem ids are already packed, any of present incoming arguments 2798 // will carry all required fields. 2799 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2800 IncomingArgX ? *IncomingArgX : 2801 IncomingArgY ? *IncomingArgY : 2802 *IncomingArgZ, ~0u); 2803 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2804 } 2805 2806 if (OutgoingArg->isRegister()) { 2807 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2808 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2809 } else { 2810 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2811 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2812 SpecialArgOffset); 2813 MemOpChains.push_back(ArgStore); 2814 } 2815 } 2816 2817 static bool canGuaranteeTCO(CallingConv::ID CC) { 2818 return CC == CallingConv::Fast; 2819 } 2820 2821 /// Return true if we might ever do TCO for calls with this calling convention. 2822 static bool mayTailCallThisCC(CallingConv::ID CC) { 2823 switch (CC) { 2824 case CallingConv::C: 2825 return true; 2826 default: 2827 return canGuaranteeTCO(CC); 2828 } 2829 } 2830 2831 bool SITargetLowering::isEligibleForTailCallOptimization( 2832 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2833 const SmallVectorImpl<ISD::OutputArg> &Outs, 2834 const SmallVectorImpl<SDValue> &OutVals, 2835 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2836 if (!mayTailCallThisCC(CalleeCC)) 2837 return false; 2838 2839 MachineFunction &MF = DAG.getMachineFunction(); 2840 const Function &CallerF = MF.getFunction(); 2841 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2842 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2843 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2844 2845 // Kernels aren't callable, and don't have a live in return address so it 2846 // doesn't make sense to do a tail call with entry functions. 2847 if (!CallerPreserved) 2848 return false; 2849 2850 bool CCMatch = CallerCC == CalleeCC; 2851 2852 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2853 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2854 return true; 2855 return false; 2856 } 2857 2858 // TODO: Can we handle var args? 2859 if (IsVarArg) 2860 return false; 2861 2862 for (const Argument &Arg : CallerF.args()) { 2863 if (Arg.hasByValAttr()) 2864 return false; 2865 } 2866 2867 LLVMContext &Ctx = *DAG.getContext(); 2868 2869 // Check that the call results are passed in the same way. 2870 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2871 CCAssignFnForCall(CalleeCC, IsVarArg), 2872 CCAssignFnForCall(CallerCC, IsVarArg))) 2873 return false; 2874 2875 // The callee has to preserve all registers the caller needs to preserve. 2876 if (!CCMatch) { 2877 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2878 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2879 return false; 2880 } 2881 2882 // Nothing more to check if the callee is taking no arguments. 2883 if (Outs.empty()) 2884 return true; 2885 2886 SmallVector<CCValAssign, 16> ArgLocs; 2887 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2888 2889 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2890 2891 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2892 // If the stack arguments for this call do not fit into our own save area then 2893 // the call cannot be made tail. 2894 // TODO: Is this really necessary? 2895 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2896 return false; 2897 2898 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2899 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2900 } 2901 2902 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2903 if (!CI->isTailCall()) 2904 return false; 2905 2906 const Function *ParentFn = CI->getParent()->getParent(); 2907 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2908 return false; 2909 return true; 2910 } 2911 2912 // The wave scratch offset register is used as the global base pointer. 2913 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2914 SmallVectorImpl<SDValue> &InVals) const { 2915 SelectionDAG &DAG = CLI.DAG; 2916 const SDLoc &DL = CLI.DL; 2917 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2918 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2919 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2920 SDValue Chain = CLI.Chain; 2921 SDValue Callee = CLI.Callee; 2922 bool &IsTailCall = CLI.IsTailCall; 2923 CallingConv::ID CallConv = CLI.CallConv; 2924 bool IsVarArg = CLI.IsVarArg; 2925 bool IsSibCall = false; 2926 bool IsThisReturn = false; 2927 MachineFunction &MF = DAG.getMachineFunction(); 2928 2929 if (Callee.isUndef() || isNullConstant(Callee)) { 2930 if (!CLI.IsTailCall) { 2931 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2932 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2933 } 2934 2935 return Chain; 2936 } 2937 2938 if (IsVarArg) { 2939 return lowerUnhandledCall(CLI, InVals, 2940 "unsupported call to variadic function "); 2941 } 2942 2943 if (!CLI.CB) 2944 report_fatal_error("unsupported libcall legalization"); 2945 2946 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2947 !CLI.CB->getCalledFunction() && CallConv != CallingConv::AMDGPU_Gfx) { 2948 return lowerUnhandledCall(CLI, InVals, 2949 "unsupported indirect call to function "); 2950 } 2951 2952 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2953 return lowerUnhandledCall(CLI, InVals, 2954 "unsupported required tail call to function "); 2955 } 2956 2957 if (AMDGPU::isShader(CallConv)) { 2958 // Note the issue is with the CC of the called function, not of the call 2959 // itself. 2960 return lowerUnhandledCall(CLI, InVals, 2961 "unsupported call to a shader function "); 2962 } 2963 2964 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 2965 CallConv != CallingConv::AMDGPU_Gfx) { 2966 // Only allow calls with specific calling conventions. 2967 return lowerUnhandledCall(CLI, InVals, 2968 "unsupported calling convention for call from " 2969 "graphics shader of function "); 2970 } 2971 2972 if (IsTailCall) { 2973 IsTailCall = isEligibleForTailCallOptimization( 2974 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2975 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2976 report_fatal_error("failed to perform tail call elimination on a call " 2977 "site marked musttail"); 2978 } 2979 2980 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2981 2982 // A sibling call is one where we're under the usual C ABI and not planning 2983 // to change that but can still do a tail call: 2984 if (!TailCallOpt && IsTailCall) 2985 IsSibCall = true; 2986 2987 if (IsTailCall) 2988 ++NumTailCalls; 2989 } 2990 2991 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2992 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2993 SmallVector<SDValue, 8> MemOpChains; 2994 2995 // Analyze operands of the call, assigning locations to each operand. 2996 SmallVector<CCValAssign, 16> ArgLocs; 2997 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2998 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2999 3000 if (AMDGPUTargetMachine::EnableFixedFunctionABI && 3001 CallConv != CallingConv::AMDGPU_Gfx) { 3002 // With a fixed ABI, allocate fixed registers before user arguments. 3003 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3004 } 3005 3006 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3007 3008 // Get a count of how many bytes are to be pushed on the stack. 3009 unsigned NumBytes = CCInfo.getNextStackOffset(); 3010 3011 if (IsSibCall) { 3012 // Since we're not changing the ABI to make this a tail call, the memory 3013 // operands are already available in the caller's incoming argument space. 3014 NumBytes = 0; 3015 } 3016 3017 // FPDiff is the byte offset of the call's argument area from the callee's. 3018 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3019 // by this amount for a tail call. In a sibling call it must be 0 because the 3020 // caller will deallocate the entire stack and the callee still expects its 3021 // arguments to begin at SP+0. Completely unused for non-tail calls. 3022 int32_t FPDiff = 0; 3023 MachineFrameInfo &MFI = MF.getFrameInfo(); 3024 3025 // Adjust the stack pointer for the new arguments... 3026 // These operations are automatically eliminated by the prolog/epilog pass 3027 if (!IsSibCall) { 3028 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3029 3030 if (!Subtarget->enableFlatScratch()) { 3031 SmallVector<SDValue, 4> CopyFromChains; 3032 3033 // In the HSA case, this should be an identity copy. 3034 SDValue ScratchRSrcReg 3035 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3036 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3037 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3038 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3039 } 3040 } 3041 3042 MVT PtrVT = MVT::i32; 3043 3044 // Walk the register/memloc assignments, inserting copies/loads. 3045 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3046 CCValAssign &VA = ArgLocs[i]; 3047 SDValue Arg = OutVals[i]; 3048 3049 // Promote the value if needed. 3050 switch (VA.getLocInfo()) { 3051 case CCValAssign::Full: 3052 break; 3053 case CCValAssign::BCvt: 3054 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3055 break; 3056 case CCValAssign::ZExt: 3057 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3058 break; 3059 case CCValAssign::SExt: 3060 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3061 break; 3062 case CCValAssign::AExt: 3063 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3064 break; 3065 case CCValAssign::FPExt: 3066 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3067 break; 3068 default: 3069 llvm_unreachable("Unknown loc info!"); 3070 } 3071 3072 if (VA.isRegLoc()) { 3073 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3074 } else { 3075 assert(VA.isMemLoc()); 3076 3077 SDValue DstAddr; 3078 MachinePointerInfo DstInfo; 3079 3080 unsigned LocMemOffset = VA.getLocMemOffset(); 3081 int32_t Offset = LocMemOffset; 3082 3083 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3084 MaybeAlign Alignment; 3085 3086 if (IsTailCall) { 3087 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3088 unsigned OpSize = Flags.isByVal() ? 3089 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3090 3091 // FIXME: We can have better than the minimum byval required alignment. 3092 Alignment = 3093 Flags.isByVal() 3094 ? Flags.getNonZeroByValAlign() 3095 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3096 3097 Offset = Offset + FPDiff; 3098 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3099 3100 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3101 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3102 3103 // Make sure any stack arguments overlapping with where we're storing 3104 // are loaded before this eventual operation. Otherwise they'll be 3105 // clobbered. 3106 3107 // FIXME: Why is this really necessary? This seems to just result in a 3108 // lot of code to copy the stack and write them back to the same 3109 // locations, which are supposed to be immutable? 3110 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3111 } else { 3112 DstAddr = PtrOff; 3113 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3114 Alignment = 3115 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3116 } 3117 3118 if (Outs[i].Flags.isByVal()) { 3119 SDValue SizeNode = 3120 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3121 SDValue Cpy = 3122 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3123 Outs[i].Flags.getNonZeroByValAlign(), 3124 /*isVol = */ false, /*AlwaysInline = */ true, 3125 /*isTailCall = */ false, DstInfo, 3126 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3127 3128 MemOpChains.push_back(Cpy); 3129 } else { 3130 SDValue Store = 3131 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3132 MemOpChains.push_back(Store); 3133 } 3134 } 3135 } 3136 3137 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 3138 CallConv != CallingConv::AMDGPU_Gfx) { 3139 // Copy special input registers after user input arguments. 3140 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3141 } 3142 3143 if (!MemOpChains.empty()) 3144 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3145 3146 // Build a sequence of copy-to-reg nodes chained together with token chain 3147 // and flag operands which copy the outgoing args into the appropriate regs. 3148 SDValue InFlag; 3149 for (auto &RegToPass : RegsToPass) { 3150 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3151 RegToPass.second, InFlag); 3152 InFlag = Chain.getValue(1); 3153 } 3154 3155 3156 SDValue PhysReturnAddrReg; 3157 if (IsTailCall) { 3158 // Since the return is being combined with the call, we need to pass on the 3159 // return address. 3160 3161 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3162 SDValue ReturnAddrReg = CreateLiveInRegister( 3163 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3164 3165 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3166 MVT::i64); 3167 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3168 InFlag = Chain.getValue(1); 3169 } 3170 3171 // We don't usually want to end the call-sequence here because we would tidy 3172 // the frame up *after* the call, however in the ABI-changing tail-call case 3173 // we've carefully laid out the parameters so that when sp is reset they'll be 3174 // in the correct location. 3175 if (IsTailCall && !IsSibCall) { 3176 Chain = DAG.getCALLSEQ_END(Chain, 3177 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3178 DAG.getTargetConstant(0, DL, MVT::i32), 3179 InFlag, DL); 3180 InFlag = Chain.getValue(1); 3181 } 3182 3183 std::vector<SDValue> Ops; 3184 Ops.push_back(Chain); 3185 Ops.push_back(Callee); 3186 // Add a redundant copy of the callee global which will not be legalized, as 3187 // we need direct access to the callee later. 3188 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3189 const GlobalValue *GV = GSD->getGlobal(); 3190 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3191 } else { 3192 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3193 } 3194 3195 if (IsTailCall) { 3196 // Each tail call may have to adjust the stack by a different amount, so 3197 // this information must travel along with the operation for eventual 3198 // consumption by emitEpilogue. 3199 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3200 3201 Ops.push_back(PhysReturnAddrReg); 3202 } 3203 3204 // Add argument registers to the end of the list so that they are known live 3205 // into the call. 3206 for (auto &RegToPass : RegsToPass) { 3207 Ops.push_back(DAG.getRegister(RegToPass.first, 3208 RegToPass.second.getValueType())); 3209 } 3210 3211 // Add a register mask operand representing the call-preserved registers. 3212 3213 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3214 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3215 assert(Mask && "Missing call preserved mask for calling convention"); 3216 Ops.push_back(DAG.getRegisterMask(Mask)); 3217 3218 if (InFlag.getNode()) 3219 Ops.push_back(InFlag); 3220 3221 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3222 3223 // If we're doing a tall call, use a TC_RETURN here rather than an 3224 // actual call instruction. 3225 if (IsTailCall) { 3226 MFI.setHasTailCall(); 3227 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3228 } 3229 3230 // Returns a chain and a flag for retval copy to use. 3231 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3232 Chain = Call.getValue(0); 3233 InFlag = Call.getValue(1); 3234 3235 uint64_t CalleePopBytes = NumBytes; 3236 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3237 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3238 InFlag, DL); 3239 if (!Ins.empty()) 3240 InFlag = Chain.getValue(1); 3241 3242 // Handle result values, copying them out of physregs into vregs that we 3243 // return. 3244 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3245 InVals, IsThisReturn, 3246 IsThisReturn ? OutVals[0] : SDValue()); 3247 } 3248 3249 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3250 // except for applying the wave size scale to the increment amount. 3251 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3252 SDValue Op, SelectionDAG &DAG) const { 3253 const MachineFunction &MF = DAG.getMachineFunction(); 3254 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3255 3256 SDLoc dl(Op); 3257 EVT VT = Op.getValueType(); 3258 SDValue Tmp1 = Op; 3259 SDValue Tmp2 = Op.getValue(1); 3260 SDValue Tmp3 = Op.getOperand(2); 3261 SDValue Chain = Tmp1.getOperand(0); 3262 3263 Register SPReg = Info->getStackPtrOffsetReg(); 3264 3265 // Chain the dynamic stack allocation so that it doesn't modify the stack 3266 // pointer when other instructions are using the stack. 3267 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3268 3269 SDValue Size = Tmp2.getOperand(1); 3270 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3271 Chain = SP.getValue(1); 3272 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3273 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3274 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3275 unsigned Opc = 3276 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3277 ISD::ADD : ISD::SUB; 3278 3279 SDValue ScaledSize = DAG.getNode( 3280 ISD::SHL, dl, VT, Size, 3281 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3282 3283 Align StackAlign = TFL->getStackAlign(); 3284 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3285 if (Alignment && *Alignment > StackAlign) { 3286 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3287 DAG.getConstant(-(uint64_t)Alignment->value() 3288 << ST.getWavefrontSizeLog2(), 3289 dl, VT)); 3290 } 3291 3292 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3293 Tmp2 = DAG.getCALLSEQ_END( 3294 Chain, DAG.getIntPtrConstant(0, dl, true), 3295 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3296 3297 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3298 } 3299 3300 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3301 SelectionDAG &DAG) const { 3302 // We only handle constant sizes here to allow non-entry block, static sized 3303 // allocas. A truly dynamic value is more difficult to support because we 3304 // don't know if the size value is uniform or not. If the size isn't uniform, 3305 // we would need to do a wave reduction to get the maximum size to know how 3306 // much to increment the uniform stack pointer. 3307 SDValue Size = Op.getOperand(1); 3308 if (isa<ConstantSDNode>(Size)) 3309 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3310 3311 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3312 } 3313 3314 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3315 const MachineFunction &MF) const { 3316 Register Reg = StringSwitch<Register>(RegName) 3317 .Case("m0", AMDGPU::M0) 3318 .Case("exec", AMDGPU::EXEC) 3319 .Case("exec_lo", AMDGPU::EXEC_LO) 3320 .Case("exec_hi", AMDGPU::EXEC_HI) 3321 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3322 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3323 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3324 .Default(Register()); 3325 3326 if (Reg == AMDGPU::NoRegister) { 3327 report_fatal_error(Twine("invalid register name \"" 3328 + StringRef(RegName) + "\".")); 3329 3330 } 3331 3332 if (!Subtarget->hasFlatScrRegister() && 3333 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3334 report_fatal_error(Twine("invalid register \"" 3335 + StringRef(RegName) + "\" for subtarget.")); 3336 } 3337 3338 switch (Reg) { 3339 case AMDGPU::M0: 3340 case AMDGPU::EXEC_LO: 3341 case AMDGPU::EXEC_HI: 3342 case AMDGPU::FLAT_SCR_LO: 3343 case AMDGPU::FLAT_SCR_HI: 3344 if (VT.getSizeInBits() == 32) 3345 return Reg; 3346 break; 3347 case AMDGPU::EXEC: 3348 case AMDGPU::FLAT_SCR: 3349 if (VT.getSizeInBits() == 64) 3350 return Reg; 3351 break; 3352 default: 3353 llvm_unreachable("missing register type checking"); 3354 } 3355 3356 report_fatal_error(Twine("invalid type for register \"" 3357 + StringRef(RegName) + "\".")); 3358 } 3359 3360 // If kill is not the last instruction, split the block so kill is always a 3361 // proper terminator. 3362 MachineBasicBlock * 3363 SITargetLowering::splitKillBlock(MachineInstr &MI, 3364 MachineBasicBlock *BB) const { 3365 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3366 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3367 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3368 return SplitBB; 3369 } 3370 3371 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3372 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3373 // be the first instruction in the remainder block. 3374 // 3375 /// \returns { LoopBody, Remainder } 3376 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3377 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3378 MachineFunction *MF = MBB.getParent(); 3379 MachineBasicBlock::iterator I(&MI); 3380 3381 // To insert the loop we need to split the block. Move everything after this 3382 // point to a new block, and insert a new empty block between the two. 3383 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3384 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3385 MachineFunction::iterator MBBI(MBB); 3386 ++MBBI; 3387 3388 MF->insert(MBBI, LoopBB); 3389 MF->insert(MBBI, RemainderBB); 3390 3391 LoopBB->addSuccessor(LoopBB); 3392 LoopBB->addSuccessor(RemainderBB); 3393 3394 // Move the rest of the block into a new block. 3395 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3396 3397 if (InstInLoop) { 3398 auto Next = std::next(I); 3399 3400 // Move instruction to loop body. 3401 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3402 3403 // Move the rest of the block. 3404 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3405 } else { 3406 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3407 } 3408 3409 MBB.addSuccessor(LoopBB); 3410 3411 return std::make_pair(LoopBB, RemainderBB); 3412 } 3413 3414 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3415 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3416 MachineBasicBlock *MBB = MI.getParent(); 3417 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3418 auto I = MI.getIterator(); 3419 auto E = std::next(I); 3420 3421 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3422 .addImm(0); 3423 3424 MIBundleBuilder Bundler(*MBB, I, E); 3425 finalizeBundle(*MBB, Bundler.begin()); 3426 } 3427 3428 MachineBasicBlock * 3429 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3430 MachineBasicBlock *BB) const { 3431 const DebugLoc &DL = MI.getDebugLoc(); 3432 3433 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3434 3435 MachineBasicBlock *LoopBB; 3436 MachineBasicBlock *RemainderBB; 3437 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3438 3439 // Apparently kill flags are only valid if the def is in the same block? 3440 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3441 Src->setIsKill(false); 3442 3443 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3444 3445 MachineBasicBlock::iterator I = LoopBB->end(); 3446 3447 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3448 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3449 3450 // Clear TRAP_STS.MEM_VIOL 3451 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3452 .addImm(0) 3453 .addImm(EncodedReg); 3454 3455 bundleInstWithWaitcnt(MI); 3456 3457 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3458 3459 // Load and check TRAP_STS.MEM_VIOL 3460 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3461 .addImm(EncodedReg); 3462 3463 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3464 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3465 .addReg(Reg, RegState::Kill) 3466 .addImm(0); 3467 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3468 .addMBB(LoopBB); 3469 3470 return RemainderBB; 3471 } 3472 3473 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3474 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3475 // will only do one iteration. In the worst case, this will loop 64 times. 3476 // 3477 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3478 static MachineBasicBlock::iterator 3479 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3480 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3481 const DebugLoc &DL, const MachineOperand &Idx, 3482 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3483 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3484 Register &SGPRIdxReg) { 3485 3486 MachineFunction *MF = OrigBB.getParent(); 3487 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3488 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3489 MachineBasicBlock::iterator I = LoopBB.begin(); 3490 3491 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3492 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3493 Register NewExec = MRI.createVirtualRegister(BoolRC); 3494 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3495 Register CondReg = MRI.createVirtualRegister(BoolRC); 3496 3497 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3498 .addReg(InitReg) 3499 .addMBB(&OrigBB) 3500 .addReg(ResultReg) 3501 .addMBB(&LoopBB); 3502 3503 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3504 .addReg(InitSaveExecReg) 3505 .addMBB(&OrigBB) 3506 .addReg(NewExec) 3507 .addMBB(&LoopBB); 3508 3509 // Read the next variant <- also loop target. 3510 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3511 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3512 3513 // Compare the just read M0 value to all possible Idx values. 3514 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3515 .addReg(CurrentIdxReg) 3516 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3517 3518 // Update EXEC, save the original EXEC value to VCC. 3519 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3520 : AMDGPU::S_AND_SAVEEXEC_B64), 3521 NewExec) 3522 .addReg(CondReg, RegState::Kill); 3523 3524 MRI.setSimpleHint(NewExec, CondReg); 3525 3526 if (UseGPRIdxMode) { 3527 if (Offset == 0) { 3528 SGPRIdxReg = CurrentIdxReg; 3529 } else { 3530 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3531 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3532 .addReg(CurrentIdxReg, RegState::Kill) 3533 .addImm(Offset); 3534 } 3535 } else { 3536 // Move index from VCC into M0 3537 if (Offset == 0) { 3538 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3539 .addReg(CurrentIdxReg, RegState::Kill); 3540 } else { 3541 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3542 .addReg(CurrentIdxReg, RegState::Kill) 3543 .addImm(Offset); 3544 } 3545 } 3546 3547 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3548 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3549 MachineInstr *InsertPt = 3550 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3551 : AMDGPU::S_XOR_B64_term), Exec) 3552 .addReg(Exec) 3553 .addReg(NewExec); 3554 3555 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3556 // s_cbranch_scc0? 3557 3558 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3559 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3560 .addMBB(&LoopBB); 3561 3562 return InsertPt->getIterator(); 3563 } 3564 3565 // This has slightly sub-optimal regalloc when the source vector is killed by 3566 // the read. The register allocator does not understand that the kill is 3567 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3568 // subregister from it, using 1 more VGPR than necessary. This was saved when 3569 // this was expanded after register allocation. 3570 static MachineBasicBlock::iterator 3571 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3572 unsigned InitResultReg, unsigned PhiReg, int Offset, 3573 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3574 MachineFunction *MF = MBB.getParent(); 3575 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3576 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3577 MachineRegisterInfo &MRI = MF->getRegInfo(); 3578 const DebugLoc &DL = MI.getDebugLoc(); 3579 MachineBasicBlock::iterator I(&MI); 3580 3581 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3582 Register DstReg = MI.getOperand(0).getReg(); 3583 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3584 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3585 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3586 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3587 3588 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3589 3590 // Save the EXEC mask 3591 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3592 .addReg(Exec); 3593 3594 MachineBasicBlock *LoopBB; 3595 MachineBasicBlock *RemainderBB; 3596 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3597 3598 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3599 3600 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3601 InitResultReg, DstReg, PhiReg, TmpExec, 3602 Offset, UseGPRIdxMode, SGPRIdxReg); 3603 3604 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3605 MachineFunction::iterator MBBI(LoopBB); 3606 ++MBBI; 3607 MF->insert(MBBI, LandingPad); 3608 LoopBB->removeSuccessor(RemainderBB); 3609 LandingPad->addSuccessor(RemainderBB); 3610 LoopBB->addSuccessor(LandingPad); 3611 MachineBasicBlock::iterator First = LandingPad->begin(); 3612 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3613 .addReg(SaveExec); 3614 3615 return InsPt; 3616 } 3617 3618 // Returns subreg index, offset 3619 static std::pair<unsigned, int> 3620 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3621 const TargetRegisterClass *SuperRC, 3622 unsigned VecReg, 3623 int Offset) { 3624 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3625 3626 // Skip out of bounds offsets, or else we would end up using an undefined 3627 // register. 3628 if (Offset >= NumElts || Offset < 0) 3629 return std::make_pair(AMDGPU::sub0, Offset); 3630 3631 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3632 } 3633 3634 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3635 MachineRegisterInfo &MRI, MachineInstr &MI, 3636 int Offset) { 3637 MachineBasicBlock *MBB = MI.getParent(); 3638 const DebugLoc &DL = MI.getDebugLoc(); 3639 MachineBasicBlock::iterator I(&MI); 3640 3641 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3642 3643 assert(Idx->getReg() != AMDGPU::NoRegister); 3644 3645 if (Offset == 0) { 3646 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3647 } else { 3648 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3649 .add(*Idx) 3650 .addImm(Offset); 3651 } 3652 } 3653 3654 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3655 MachineRegisterInfo &MRI, MachineInstr &MI, 3656 int Offset) { 3657 MachineBasicBlock *MBB = MI.getParent(); 3658 const DebugLoc &DL = MI.getDebugLoc(); 3659 MachineBasicBlock::iterator I(&MI); 3660 3661 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3662 3663 if (Offset == 0) 3664 return Idx->getReg(); 3665 3666 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3667 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3668 .add(*Idx) 3669 .addImm(Offset); 3670 return Tmp; 3671 } 3672 3673 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3674 MachineBasicBlock &MBB, 3675 const GCNSubtarget &ST) { 3676 const SIInstrInfo *TII = ST.getInstrInfo(); 3677 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3678 MachineFunction *MF = MBB.getParent(); 3679 MachineRegisterInfo &MRI = MF->getRegInfo(); 3680 3681 Register Dst = MI.getOperand(0).getReg(); 3682 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3683 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3684 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3685 3686 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3687 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3688 3689 unsigned SubReg; 3690 std::tie(SubReg, Offset) 3691 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3692 3693 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3694 3695 // Check for a SGPR index. 3696 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3697 MachineBasicBlock::iterator I(&MI); 3698 const DebugLoc &DL = MI.getDebugLoc(); 3699 3700 if (UseGPRIdxMode) { 3701 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3702 // to avoid interfering with other uses, so probably requires a new 3703 // optimization pass. 3704 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3705 3706 const MCInstrDesc &GPRIDXDesc = 3707 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3708 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3709 .addReg(SrcReg) 3710 .addReg(Idx) 3711 .addImm(SubReg); 3712 } else { 3713 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3714 3715 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3716 .addReg(SrcReg, 0, SubReg) 3717 .addReg(SrcReg, RegState::Implicit); 3718 } 3719 3720 MI.eraseFromParent(); 3721 3722 return &MBB; 3723 } 3724 3725 // Control flow needs to be inserted if indexing with a VGPR. 3726 const DebugLoc &DL = MI.getDebugLoc(); 3727 MachineBasicBlock::iterator I(&MI); 3728 3729 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3730 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3731 3732 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3733 3734 Register SGPRIdxReg; 3735 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3736 UseGPRIdxMode, SGPRIdxReg); 3737 3738 MachineBasicBlock *LoopBB = InsPt->getParent(); 3739 3740 if (UseGPRIdxMode) { 3741 const MCInstrDesc &GPRIDXDesc = 3742 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3743 3744 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3745 .addReg(SrcReg) 3746 .addReg(SGPRIdxReg) 3747 .addImm(SubReg); 3748 } else { 3749 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3750 .addReg(SrcReg, 0, SubReg) 3751 .addReg(SrcReg, RegState::Implicit); 3752 } 3753 3754 MI.eraseFromParent(); 3755 3756 return LoopBB; 3757 } 3758 3759 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3760 MachineBasicBlock &MBB, 3761 const GCNSubtarget &ST) { 3762 const SIInstrInfo *TII = ST.getInstrInfo(); 3763 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3764 MachineFunction *MF = MBB.getParent(); 3765 MachineRegisterInfo &MRI = MF->getRegInfo(); 3766 3767 Register Dst = MI.getOperand(0).getReg(); 3768 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3769 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3770 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3771 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3772 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3773 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3774 3775 // This can be an immediate, but will be folded later. 3776 assert(Val->getReg()); 3777 3778 unsigned SubReg; 3779 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3780 SrcVec->getReg(), 3781 Offset); 3782 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3783 3784 if (Idx->getReg() == AMDGPU::NoRegister) { 3785 MachineBasicBlock::iterator I(&MI); 3786 const DebugLoc &DL = MI.getDebugLoc(); 3787 3788 assert(Offset == 0); 3789 3790 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3791 .add(*SrcVec) 3792 .add(*Val) 3793 .addImm(SubReg); 3794 3795 MI.eraseFromParent(); 3796 return &MBB; 3797 } 3798 3799 // Check for a SGPR index. 3800 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3801 MachineBasicBlock::iterator I(&MI); 3802 const DebugLoc &DL = MI.getDebugLoc(); 3803 3804 if (UseGPRIdxMode) { 3805 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3806 3807 const MCInstrDesc &GPRIDXDesc = 3808 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3809 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3810 .addReg(SrcVec->getReg()) 3811 .add(*Val) 3812 .addReg(Idx) 3813 .addImm(SubReg); 3814 } else { 3815 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3816 3817 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3818 TRI.getRegSizeInBits(*VecRC), 32, false); 3819 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3820 .addReg(SrcVec->getReg()) 3821 .add(*Val) 3822 .addImm(SubReg); 3823 } 3824 MI.eraseFromParent(); 3825 return &MBB; 3826 } 3827 3828 // Control flow needs to be inserted if indexing with a VGPR. 3829 if (Val->isReg()) 3830 MRI.clearKillFlags(Val->getReg()); 3831 3832 const DebugLoc &DL = MI.getDebugLoc(); 3833 3834 Register PhiReg = MRI.createVirtualRegister(VecRC); 3835 3836 Register SGPRIdxReg; 3837 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3838 UseGPRIdxMode, SGPRIdxReg); 3839 MachineBasicBlock *LoopBB = InsPt->getParent(); 3840 3841 if (UseGPRIdxMode) { 3842 const MCInstrDesc &GPRIDXDesc = 3843 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3844 3845 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3846 .addReg(PhiReg) 3847 .add(*Val) 3848 .addReg(SGPRIdxReg) 3849 .addImm(AMDGPU::sub0); 3850 } else { 3851 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3852 TRI.getRegSizeInBits(*VecRC), 32, false); 3853 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3854 .addReg(PhiReg) 3855 .add(*Val) 3856 .addImm(AMDGPU::sub0); 3857 } 3858 3859 MI.eraseFromParent(); 3860 return LoopBB; 3861 } 3862 3863 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3864 MachineInstr &MI, MachineBasicBlock *BB) const { 3865 3866 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3867 MachineFunction *MF = BB->getParent(); 3868 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3869 3870 switch (MI.getOpcode()) { 3871 case AMDGPU::S_UADDO_PSEUDO: 3872 case AMDGPU::S_USUBO_PSEUDO: { 3873 const DebugLoc &DL = MI.getDebugLoc(); 3874 MachineOperand &Dest0 = MI.getOperand(0); 3875 MachineOperand &Dest1 = MI.getOperand(1); 3876 MachineOperand &Src0 = MI.getOperand(2); 3877 MachineOperand &Src1 = MI.getOperand(3); 3878 3879 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3880 ? AMDGPU::S_ADD_I32 3881 : AMDGPU::S_SUB_I32; 3882 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3883 3884 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3885 .addImm(1) 3886 .addImm(0); 3887 3888 MI.eraseFromParent(); 3889 return BB; 3890 } 3891 case AMDGPU::S_ADD_U64_PSEUDO: 3892 case AMDGPU::S_SUB_U64_PSEUDO: { 3893 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3894 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3895 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3896 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3897 const DebugLoc &DL = MI.getDebugLoc(); 3898 3899 MachineOperand &Dest = MI.getOperand(0); 3900 MachineOperand &Src0 = MI.getOperand(1); 3901 MachineOperand &Src1 = MI.getOperand(2); 3902 3903 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3904 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3905 3906 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3907 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3908 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3909 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3910 3911 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3912 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3913 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3914 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3915 3916 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3917 3918 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3919 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3920 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3921 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3922 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3923 .addReg(DestSub0) 3924 .addImm(AMDGPU::sub0) 3925 .addReg(DestSub1) 3926 .addImm(AMDGPU::sub1); 3927 MI.eraseFromParent(); 3928 return BB; 3929 } 3930 case AMDGPU::V_ADD_U64_PSEUDO: 3931 case AMDGPU::V_SUB_U64_PSEUDO: { 3932 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3933 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3934 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3935 const DebugLoc &DL = MI.getDebugLoc(); 3936 3937 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3938 3939 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3940 3941 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3942 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3943 3944 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3945 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3946 3947 MachineOperand &Dest = MI.getOperand(0); 3948 MachineOperand &Src0 = MI.getOperand(1); 3949 MachineOperand &Src1 = MI.getOperand(2); 3950 3951 const TargetRegisterClass *Src0RC = Src0.isReg() 3952 ? MRI.getRegClass(Src0.getReg()) 3953 : &AMDGPU::VReg_64RegClass; 3954 const TargetRegisterClass *Src1RC = Src1.isReg() 3955 ? MRI.getRegClass(Src1.getReg()) 3956 : &AMDGPU::VReg_64RegClass; 3957 3958 const TargetRegisterClass *Src0SubRC = 3959 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3960 const TargetRegisterClass *Src1SubRC = 3961 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3962 3963 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3964 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3965 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3966 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3967 3968 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3969 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3970 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3971 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3972 3973 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 3974 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3975 .addReg(CarryReg, RegState::Define) 3976 .add(SrcReg0Sub0) 3977 .add(SrcReg1Sub0) 3978 .addImm(0); // clamp bit 3979 3980 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3981 MachineInstr *HiHalf = 3982 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3983 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3984 .add(SrcReg0Sub1) 3985 .add(SrcReg1Sub1) 3986 .addReg(CarryReg, RegState::Kill) 3987 .addImm(0); // clamp bit 3988 3989 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3990 .addReg(DestSub0) 3991 .addImm(AMDGPU::sub0) 3992 .addReg(DestSub1) 3993 .addImm(AMDGPU::sub1); 3994 TII->legalizeOperands(*LoHalf); 3995 TII->legalizeOperands(*HiHalf); 3996 MI.eraseFromParent(); 3997 return BB; 3998 } 3999 case AMDGPU::S_ADD_CO_PSEUDO: 4000 case AMDGPU::S_SUB_CO_PSEUDO: { 4001 // This pseudo has a chance to be selected 4002 // only from uniform add/subcarry node. All the VGPR operands 4003 // therefore assumed to be splat vectors. 4004 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4005 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4006 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4007 MachineBasicBlock::iterator MII = MI; 4008 const DebugLoc &DL = MI.getDebugLoc(); 4009 MachineOperand &Dest = MI.getOperand(0); 4010 MachineOperand &CarryDest = MI.getOperand(1); 4011 MachineOperand &Src0 = MI.getOperand(2); 4012 MachineOperand &Src1 = MI.getOperand(3); 4013 MachineOperand &Src2 = MI.getOperand(4); 4014 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4015 ? AMDGPU::S_ADDC_U32 4016 : AMDGPU::S_SUBB_U32; 4017 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4018 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4019 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4020 .addReg(Src0.getReg()); 4021 Src0.setReg(RegOp0); 4022 } 4023 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4024 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4025 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4026 .addReg(Src1.getReg()); 4027 Src1.setReg(RegOp1); 4028 } 4029 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4030 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4031 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4032 .addReg(Src2.getReg()); 4033 Src2.setReg(RegOp2); 4034 } 4035 4036 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4037 if (TRI->getRegSizeInBits(*Src2RC) == 64) { 4038 if (ST.hasScalarCompareEq64()) { 4039 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4040 .addReg(Src2.getReg()) 4041 .addImm(0); 4042 } else { 4043 const TargetRegisterClass *SubRC = 4044 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4045 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4046 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4047 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4048 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4049 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4050 4051 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4052 .add(Src2Sub0) 4053 .add(Src2Sub1); 4054 4055 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4056 .addReg(Src2_32, RegState::Kill) 4057 .addImm(0); 4058 } 4059 } else { 4060 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4061 .addReg(Src2.getReg()) 4062 .addImm(0); 4063 } 4064 4065 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4066 4067 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 4068 .addReg(AMDGPU::SCC); 4069 MI.eraseFromParent(); 4070 return BB; 4071 } 4072 case AMDGPU::SI_INIT_M0: { 4073 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4074 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4075 .add(MI.getOperand(0)); 4076 MI.eraseFromParent(); 4077 return BB; 4078 } 4079 case AMDGPU::GET_GROUPSTATICSIZE: { 4080 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4081 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4082 DebugLoc DL = MI.getDebugLoc(); 4083 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4084 .add(MI.getOperand(0)) 4085 .addImm(MFI->getLDSSize()); 4086 MI.eraseFromParent(); 4087 return BB; 4088 } 4089 case AMDGPU::SI_INDIRECT_SRC_V1: 4090 case AMDGPU::SI_INDIRECT_SRC_V2: 4091 case AMDGPU::SI_INDIRECT_SRC_V4: 4092 case AMDGPU::SI_INDIRECT_SRC_V8: 4093 case AMDGPU::SI_INDIRECT_SRC_V16: 4094 case AMDGPU::SI_INDIRECT_SRC_V32: 4095 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4096 case AMDGPU::SI_INDIRECT_DST_V1: 4097 case AMDGPU::SI_INDIRECT_DST_V2: 4098 case AMDGPU::SI_INDIRECT_DST_V4: 4099 case AMDGPU::SI_INDIRECT_DST_V8: 4100 case AMDGPU::SI_INDIRECT_DST_V16: 4101 case AMDGPU::SI_INDIRECT_DST_V32: 4102 return emitIndirectDst(MI, *BB, *getSubtarget()); 4103 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4104 case AMDGPU::SI_KILL_I1_PSEUDO: 4105 return splitKillBlock(MI, BB); 4106 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4107 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4108 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4109 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4110 4111 Register Dst = MI.getOperand(0).getReg(); 4112 Register Src0 = MI.getOperand(1).getReg(); 4113 Register Src1 = MI.getOperand(2).getReg(); 4114 const DebugLoc &DL = MI.getDebugLoc(); 4115 Register SrcCond = MI.getOperand(3).getReg(); 4116 4117 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4118 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4119 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4120 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4121 4122 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4123 .addReg(SrcCond); 4124 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4125 .addImm(0) 4126 .addReg(Src0, 0, AMDGPU::sub0) 4127 .addImm(0) 4128 .addReg(Src1, 0, AMDGPU::sub0) 4129 .addReg(SrcCondCopy); 4130 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4131 .addImm(0) 4132 .addReg(Src0, 0, AMDGPU::sub1) 4133 .addImm(0) 4134 .addReg(Src1, 0, AMDGPU::sub1) 4135 .addReg(SrcCondCopy); 4136 4137 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4138 .addReg(DstLo) 4139 .addImm(AMDGPU::sub0) 4140 .addReg(DstHi) 4141 .addImm(AMDGPU::sub1); 4142 MI.eraseFromParent(); 4143 return BB; 4144 } 4145 case AMDGPU::SI_BR_UNDEF: { 4146 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4147 const DebugLoc &DL = MI.getDebugLoc(); 4148 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4149 .add(MI.getOperand(0)); 4150 Br->getOperand(1).setIsUndef(true); // read undef SCC 4151 MI.eraseFromParent(); 4152 return BB; 4153 } 4154 case AMDGPU::ADJCALLSTACKUP: 4155 case AMDGPU::ADJCALLSTACKDOWN: { 4156 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4157 MachineInstrBuilder MIB(*MF, &MI); 4158 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4159 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4160 return BB; 4161 } 4162 case AMDGPU::SI_CALL_ISEL: { 4163 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4164 const DebugLoc &DL = MI.getDebugLoc(); 4165 4166 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4167 4168 MachineInstrBuilder MIB; 4169 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4170 4171 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4172 MIB.add(MI.getOperand(I)); 4173 4174 MIB.cloneMemRefs(MI); 4175 MI.eraseFromParent(); 4176 return BB; 4177 } 4178 case AMDGPU::V_ADD_CO_U32_e32: 4179 case AMDGPU::V_SUB_CO_U32_e32: 4180 case AMDGPU::V_SUBREV_CO_U32_e32: { 4181 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4182 const DebugLoc &DL = MI.getDebugLoc(); 4183 unsigned Opc = MI.getOpcode(); 4184 4185 bool NeedClampOperand = false; 4186 if (TII->pseudoToMCOpcode(Opc) == -1) { 4187 Opc = AMDGPU::getVOPe64(Opc); 4188 NeedClampOperand = true; 4189 } 4190 4191 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4192 if (TII->isVOP3(*I)) { 4193 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4194 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4195 I.addReg(TRI->getVCC(), RegState::Define); 4196 } 4197 I.add(MI.getOperand(1)) 4198 .add(MI.getOperand(2)); 4199 if (NeedClampOperand) 4200 I.addImm(0); // clamp bit for e64 encoding 4201 4202 TII->legalizeOperands(*I); 4203 4204 MI.eraseFromParent(); 4205 return BB; 4206 } 4207 case AMDGPU::DS_GWS_INIT: 4208 case AMDGPU::DS_GWS_SEMA_V: 4209 case AMDGPU::DS_GWS_SEMA_BR: 4210 case AMDGPU::DS_GWS_SEMA_P: 4211 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4212 case AMDGPU::DS_GWS_BARRIER: 4213 // A s_waitcnt 0 is required to be the instruction immediately following. 4214 if (getSubtarget()->hasGWSAutoReplay()) { 4215 bundleInstWithWaitcnt(MI); 4216 return BB; 4217 } 4218 4219 return emitGWSMemViolTestLoop(MI, BB); 4220 case AMDGPU::S_SETREG_B32: { 4221 // Try to optimize cases that only set the denormal mode or rounding mode. 4222 // 4223 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4224 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4225 // instead. 4226 // 4227 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4228 // allow you to have a no side effect instruction in the output of a 4229 // sideeffecting pattern. 4230 unsigned ID, Offset, Width; 4231 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4232 if (ID != AMDGPU::Hwreg::ID_MODE) 4233 return BB; 4234 4235 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4236 const unsigned SetMask = WidthMask << Offset; 4237 4238 if (getSubtarget()->hasDenormModeInst()) { 4239 unsigned SetDenormOp = 0; 4240 unsigned SetRoundOp = 0; 4241 4242 // The dedicated instructions can only set the whole denorm or round mode 4243 // at once, not a subset of bits in either. 4244 if (SetMask == 4245 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4246 // If this fully sets both the round and denorm mode, emit the two 4247 // dedicated instructions for these. 4248 SetRoundOp = AMDGPU::S_ROUND_MODE; 4249 SetDenormOp = AMDGPU::S_DENORM_MODE; 4250 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4251 SetRoundOp = AMDGPU::S_ROUND_MODE; 4252 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4253 SetDenormOp = AMDGPU::S_DENORM_MODE; 4254 } 4255 4256 if (SetRoundOp || SetDenormOp) { 4257 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4258 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4259 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4260 unsigned ImmVal = Def->getOperand(1).getImm(); 4261 if (SetRoundOp) { 4262 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4263 .addImm(ImmVal & 0xf); 4264 4265 // If we also have the denorm mode, get just the denorm mode bits. 4266 ImmVal >>= 4; 4267 } 4268 4269 if (SetDenormOp) { 4270 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4271 .addImm(ImmVal & 0xf); 4272 } 4273 4274 MI.eraseFromParent(); 4275 return BB; 4276 } 4277 } 4278 } 4279 4280 // If only FP bits are touched, used the no side effects pseudo. 4281 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4282 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4283 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4284 4285 return BB; 4286 } 4287 default: 4288 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4289 } 4290 } 4291 4292 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4293 return isTypeLegal(VT.getScalarType()); 4294 } 4295 4296 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4297 // This currently forces unfolding various combinations of fsub into fma with 4298 // free fneg'd operands. As long as we have fast FMA (controlled by 4299 // isFMAFasterThanFMulAndFAdd), we should perform these. 4300 4301 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4302 // most of these combines appear to be cycle neutral but save on instruction 4303 // count / code size. 4304 return true; 4305 } 4306 4307 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4308 EVT VT) const { 4309 if (!VT.isVector()) { 4310 return MVT::i1; 4311 } 4312 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4313 } 4314 4315 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4316 // TODO: Should i16 be used always if legal? For now it would force VALU 4317 // shifts. 4318 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4319 } 4320 4321 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4322 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4323 ? Ty.changeElementSize(16) 4324 : Ty.changeElementSize(32); 4325 } 4326 4327 // Answering this is somewhat tricky and depends on the specific device which 4328 // have different rates for fma or all f64 operations. 4329 // 4330 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4331 // regardless of which device (although the number of cycles differs between 4332 // devices), so it is always profitable for f64. 4333 // 4334 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4335 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4336 // which we can always do even without fused FP ops since it returns the same 4337 // result as the separate operations and since it is always full 4338 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4339 // however does not support denormals, so we do report fma as faster if we have 4340 // a fast fma device and require denormals. 4341 // 4342 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4343 EVT VT) const { 4344 VT = VT.getScalarType(); 4345 4346 switch (VT.getSimpleVT().SimpleTy) { 4347 case MVT::f32: { 4348 // If mad is not available this depends only on if f32 fma is full rate. 4349 if (!Subtarget->hasMadMacF32Insts()) 4350 return Subtarget->hasFastFMAF32(); 4351 4352 // Otherwise f32 mad is always full rate and returns the same result as 4353 // the separate operations so should be preferred over fma. 4354 // However does not support denomals. 4355 if (hasFP32Denormals(MF)) 4356 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4357 4358 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4359 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4360 } 4361 case MVT::f64: 4362 return true; 4363 case MVT::f16: 4364 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4365 default: 4366 break; 4367 } 4368 4369 return false; 4370 } 4371 4372 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4373 const SDNode *N) const { 4374 // TODO: Check future ftz flag 4375 // v_mad_f32/v_mac_f32 do not support denormals. 4376 EVT VT = N->getValueType(0); 4377 if (VT == MVT::f32) 4378 return Subtarget->hasMadMacF32Insts() && 4379 !hasFP32Denormals(DAG.getMachineFunction()); 4380 if (VT == MVT::f16) { 4381 return Subtarget->hasMadF16() && 4382 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4383 } 4384 4385 return false; 4386 } 4387 4388 //===----------------------------------------------------------------------===// 4389 // Custom DAG Lowering Operations 4390 //===----------------------------------------------------------------------===// 4391 4392 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4393 // wider vector type is legal. 4394 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4395 SelectionDAG &DAG) const { 4396 unsigned Opc = Op.getOpcode(); 4397 EVT VT = Op.getValueType(); 4398 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4399 4400 SDValue Lo, Hi; 4401 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4402 4403 SDLoc SL(Op); 4404 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4405 Op->getFlags()); 4406 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4407 Op->getFlags()); 4408 4409 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4410 } 4411 4412 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4413 // wider vector type is legal. 4414 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4415 SelectionDAG &DAG) const { 4416 unsigned Opc = Op.getOpcode(); 4417 EVT VT = Op.getValueType(); 4418 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4419 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4420 4421 SDValue Lo0, Hi0; 4422 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4423 SDValue Lo1, Hi1; 4424 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4425 4426 SDLoc SL(Op); 4427 4428 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4429 Op->getFlags()); 4430 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4431 Op->getFlags()); 4432 4433 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4434 } 4435 4436 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4437 SelectionDAG &DAG) const { 4438 unsigned Opc = Op.getOpcode(); 4439 EVT VT = Op.getValueType(); 4440 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4441 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4442 4443 SDValue Lo0, Hi0; 4444 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4445 SDValue Lo1, Hi1; 4446 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4447 SDValue Lo2, Hi2; 4448 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4449 4450 SDLoc SL(Op); 4451 4452 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4453 Op->getFlags()); 4454 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4455 Op->getFlags()); 4456 4457 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4458 } 4459 4460 4461 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4462 switch (Op.getOpcode()) { 4463 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4464 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4465 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4466 case ISD::LOAD: { 4467 SDValue Result = LowerLOAD(Op, DAG); 4468 assert((!Result.getNode() || 4469 Result.getNode()->getNumValues() == 2) && 4470 "Load should return a value and a chain"); 4471 return Result; 4472 } 4473 4474 case ISD::FSIN: 4475 case ISD::FCOS: 4476 return LowerTrig(Op, DAG); 4477 case ISD::SELECT: return LowerSELECT(Op, DAG); 4478 case ISD::FDIV: return LowerFDIV(Op, DAG); 4479 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4480 case ISD::STORE: return LowerSTORE(Op, DAG); 4481 case ISD::GlobalAddress: { 4482 MachineFunction &MF = DAG.getMachineFunction(); 4483 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4484 return LowerGlobalAddress(MFI, Op, DAG); 4485 } 4486 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4487 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4488 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4489 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4490 case ISD::INSERT_SUBVECTOR: 4491 return lowerINSERT_SUBVECTOR(Op, DAG); 4492 case ISD::INSERT_VECTOR_ELT: 4493 return lowerINSERT_VECTOR_ELT(Op, DAG); 4494 case ISD::EXTRACT_VECTOR_ELT: 4495 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4496 case ISD::VECTOR_SHUFFLE: 4497 return lowerVECTOR_SHUFFLE(Op, DAG); 4498 case ISD::BUILD_VECTOR: 4499 return lowerBUILD_VECTOR(Op, DAG); 4500 case ISD::FP_ROUND: 4501 return lowerFP_ROUND(Op, DAG); 4502 case ISD::TRAP: 4503 return lowerTRAP(Op, DAG); 4504 case ISD::DEBUGTRAP: 4505 return lowerDEBUGTRAP(Op, DAG); 4506 case ISD::FABS: 4507 case ISD::FNEG: 4508 case ISD::FCANONICALIZE: 4509 case ISD::BSWAP: 4510 return splitUnaryVectorOp(Op, DAG); 4511 case ISD::FMINNUM: 4512 case ISD::FMAXNUM: 4513 return lowerFMINNUM_FMAXNUM(Op, DAG); 4514 case ISD::FMA: 4515 return splitTernaryVectorOp(Op, DAG); 4516 case ISD::SHL: 4517 case ISD::SRA: 4518 case ISD::SRL: 4519 case ISD::ADD: 4520 case ISD::SUB: 4521 case ISD::MUL: 4522 case ISD::SMIN: 4523 case ISD::SMAX: 4524 case ISD::UMIN: 4525 case ISD::UMAX: 4526 case ISD::FADD: 4527 case ISD::FMUL: 4528 case ISD::FMINNUM_IEEE: 4529 case ISD::FMAXNUM_IEEE: 4530 case ISD::UADDSAT: 4531 case ISD::USUBSAT: 4532 case ISD::SADDSAT: 4533 case ISD::SSUBSAT: 4534 return splitBinaryVectorOp(Op, DAG); 4535 case ISD::SMULO: 4536 case ISD::UMULO: 4537 return lowerXMULO(Op, DAG); 4538 case ISD::DYNAMIC_STACKALLOC: 4539 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4540 } 4541 return SDValue(); 4542 } 4543 4544 // Used for D16: Casts the result of an instruction into the right vector, 4545 // packs values if loads return unpacked values. 4546 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4547 const SDLoc &DL, 4548 SelectionDAG &DAG, bool Unpacked) { 4549 if (!LoadVT.isVector()) 4550 return Result; 4551 4552 // Cast back to the original packed type or to a larger type that is a 4553 // multiple of 32 bit for D16. Widening the return type is a required for 4554 // legalization. 4555 EVT FittingLoadVT = LoadVT; 4556 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4557 FittingLoadVT = 4558 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4559 LoadVT.getVectorNumElements() + 1); 4560 } 4561 4562 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4563 // Truncate to v2i16/v4i16. 4564 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4565 4566 // Workaround legalizer not scalarizing truncate after vector op 4567 // legalization but not creating intermediate vector trunc. 4568 SmallVector<SDValue, 4> Elts; 4569 DAG.ExtractVectorElements(Result, Elts); 4570 for (SDValue &Elt : Elts) 4571 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4572 4573 // Pad illegal v1i16/v3fi6 to v4i16 4574 if ((LoadVT.getVectorNumElements() % 2) == 1) 4575 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4576 4577 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4578 4579 // Bitcast to original type (v2f16/v4f16). 4580 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4581 } 4582 4583 // Cast back to the original packed type. 4584 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4585 } 4586 4587 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4588 MemSDNode *M, 4589 SelectionDAG &DAG, 4590 ArrayRef<SDValue> Ops, 4591 bool IsIntrinsic) const { 4592 SDLoc DL(M); 4593 4594 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4595 EVT LoadVT = M->getValueType(0); 4596 4597 EVT EquivLoadVT = LoadVT; 4598 if (LoadVT.isVector()) { 4599 if (Unpacked) { 4600 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4601 LoadVT.getVectorNumElements()); 4602 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4603 // Widen v3f16 to legal type 4604 EquivLoadVT = 4605 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4606 LoadVT.getVectorNumElements() + 1); 4607 } 4608 } 4609 4610 // Change from v4f16/v2f16 to EquivLoadVT. 4611 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4612 4613 SDValue Load 4614 = DAG.getMemIntrinsicNode( 4615 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4616 VTList, Ops, M->getMemoryVT(), 4617 M->getMemOperand()); 4618 4619 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4620 4621 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4622 } 4623 4624 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4625 SelectionDAG &DAG, 4626 ArrayRef<SDValue> Ops) const { 4627 SDLoc DL(M); 4628 EVT LoadVT = M->getValueType(0); 4629 EVT EltType = LoadVT.getScalarType(); 4630 EVT IntVT = LoadVT.changeTypeToInteger(); 4631 4632 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4633 4634 unsigned Opc = 4635 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4636 4637 if (IsD16) { 4638 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4639 } 4640 4641 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4642 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4643 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4644 4645 if (isTypeLegal(LoadVT)) { 4646 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4647 M->getMemOperand(), DAG); 4648 } 4649 4650 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4651 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4652 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4653 M->getMemOperand(), DAG); 4654 return DAG.getMergeValues( 4655 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4656 DL); 4657 } 4658 4659 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4660 SDNode *N, SelectionDAG &DAG) { 4661 EVT VT = N->getValueType(0); 4662 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4663 unsigned CondCode = CD->getZExtValue(); 4664 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4665 return DAG.getUNDEF(VT); 4666 4667 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4668 4669 SDValue LHS = N->getOperand(1); 4670 SDValue RHS = N->getOperand(2); 4671 4672 SDLoc DL(N); 4673 4674 EVT CmpVT = LHS.getValueType(); 4675 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4676 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4677 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4678 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4679 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4680 } 4681 4682 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4683 4684 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4685 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4686 4687 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4688 DAG.getCondCode(CCOpcode)); 4689 if (VT.bitsEq(CCVT)) 4690 return SetCC; 4691 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4692 } 4693 4694 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4695 SDNode *N, SelectionDAG &DAG) { 4696 EVT VT = N->getValueType(0); 4697 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4698 4699 unsigned CondCode = CD->getZExtValue(); 4700 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4701 return DAG.getUNDEF(VT); 4702 4703 SDValue Src0 = N->getOperand(1); 4704 SDValue Src1 = N->getOperand(2); 4705 EVT CmpVT = Src0.getValueType(); 4706 SDLoc SL(N); 4707 4708 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4709 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4710 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4711 } 4712 4713 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4714 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4715 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4716 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4717 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4718 Src1, DAG.getCondCode(CCOpcode)); 4719 if (VT.bitsEq(CCVT)) 4720 return SetCC; 4721 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4722 } 4723 4724 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4725 SelectionDAG &DAG) { 4726 EVT VT = N->getValueType(0); 4727 SDValue Src = N->getOperand(1); 4728 SDLoc SL(N); 4729 4730 if (Src.getOpcode() == ISD::SETCC) { 4731 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4732 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4733 Src.getOperand(1), Src.getOperand(2)); 4734 } 4735 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4736 // (ballot 0) -> 0 4737 if (Arg->isNullValue()) 4738 return DAG.getConstant(0, SL, VT); 4739 4740 // (ballot 1) -> EXEC/EXEC_LO 4741 if (Arg->isOne()) { 4742 Register Exec; 4743 if (VT.getScalarSizeInBits() == 32) 4744 Exec = AMDGPU::EXEC_LO; 4745 else if (VT.getScalarSizeInBits() == 64) 4746 Exec = AMDGPU::EXEC; 4747 else 4748 return SDValue(); 4749 4750 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4751 } 4752 } 4753 4754 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4755 // ISD::SETNE) 4756 return DAG.getNode( 4757 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4758 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4759 } 4760 4761 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4762 SmallVectorImpl<SDValue> &Results, 4763 SelectionDAG &DAG) const { 4764 switch (N->getOpcode()) { 4765 case ISD::INSERT_VECTOR_ELT: { 4766 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4767 Results.push_back(Res); 4768 return; 4769 } 4770 case ISD::EXTRACT_VECTOR_ELT: { 4771 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4772 Results.push_back(Res); 4773 return; 4774 } 4775 case ISD::INTRINSIC_WO_CHAIN: { 4776 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4777 switch (IID) { 4778 case Intrinsic::amdgcn_cvt_pkrtz: { 4779 SDValue Src0 = N->getOperand(1); 4780 SDValue Src1 = N->getOperand(2); 4781 SDLoc SL(N); 4782 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4783 Src0, Src1); 4784 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4785 return; 4786 } 4787 case Intrinsic::amdgcn_cvt_pknorm_i16: 4788 case Intrinsic::amdgcn_cvt_pknorm_u16: 4789 case Intrinsic::amdgcn_cvt_pk_i16: 4790 case Intrinsic::amdgcn_cvt_pk_u16: { 4791 SDValue Src0 = N->getOperand(1); 4792 SDValue Src1 = N->getOperand(2); 4793 SDLoc SL(N); 4794 unsigned Opcode; 4795 4796 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4797 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4798 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4799 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4800 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4801 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4802 else 4803 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4804 4805 EVT VT = N->getValueType(0); 4806 if (isTypeLegal(VT)) 4807 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4808 else { 4809 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4810 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4811 } 4812 return; 4813 } 4814 } 4815 break; 4816 } 4817 case ISD::INTRINSIC_W_CHAIN: { 4818 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4819 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4820 // FIXME: Hacky 4821 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4822 Results.push_back(Res.getOperand(I)); 4823 } 4824 } else { 4825 Results.push_back(Res); 4826 Results.push_back(Res.getValue(1)); 4827 } 4828 return; 4829 } 4830 4831 break; 4832 } 4833 case ISD::SELECT: { 4834 SDLoc SL(N); 4835 EVT VT = N->getValueType(0); 4836 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4837 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4838 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4839 4840 EVT SelectVT = NewVT; 4841 if (NewVT.bitsLT(MVT::i32)) { 4842 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4843 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4844 SelectVT = MVT::i32; 4845 } 4846 4847 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4848 N->getOperand(0), LHS, RHS); 4849 4850 if (NewVT != SelectVT) 4851 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4852 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4853 return; 4854 } 4855 case ISD::FNEG: { 4856 if (N->getValueType(0) != MVT::v2f16) 4857 break; 4858 4859 SDLoc SL(N); 4860 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4861 4862 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4863 BC, 4864 DAG.getConstant(0x80008000, SL, MVT::i32)); 4865 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4866 return; 4867 } 4868 case ISD::FABS: { 4869 if (N->getValueType(0) != MVT::v2f16) 4870 break; 4871 4872 SDLoc SL(N); 4873 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4874 4875 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4876 BC, 4877 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4878 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4879 return; 4880 } 4881 default: 4882 break; 4883 } 4884 } 4885 4886 /// Helper function for LowerBRCOND 4887 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4888 4889 SDNode *Parent = Value.getNode(); 4890 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4891 I != E; ++I) { 4892 4893 if (I.getUse().get() != Value) 4894 continue; 4895 4896 if (I->getOpcode() == Opcode) 4897 return *I; 4898 } 4899 return nullptr; 4900 } 4901 4902 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4903 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4904 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4905 case Intrinsic::amdgcn_if: 4906 return AMDGPUISD::IF; 4907 case Intrinsic::amdgcn_else: 4908 return AMDGPUISD::ELSE; 4909 case Intrinsic::amdgcn_loop: 4910 return AMDGPUISD::LOOP; 4911 case Intrinsic::amdgcn_end_cf: 4912 llvm_unreachable("should not occur"); 4913 default: 4914 return 0; 4915 } 4916 } 4917 4918 // break, if_break, else_break are all only used as inputs to loop, not 4919 // directly as branch conditions. 4920 return 0; 4921 } 4922 4923 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4924 const Triple &TT = getTargetMachine().getTargetTriple(); 4925 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4926 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4927 AMDGPU::shouldEmitConstantsToTextSection(TT); 4928 } 4929 4930 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4931 // FIXME: Either avoid relying on address space here or change the default 4932 // address space for functions to avoid the explicit check. 4933 return (GV->getValueType()->isFunctionTy() || 4934 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4935 !shouldEmitFixup(GV) && 4936 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4937 } 4938 4939 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4940 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4941 } 4942 4943 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4944 if (!GV->hasExternalLinkage()) 4945 return true; 4946 4947 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4948 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4949 } 4950 4951 /// This transforms the control flow intrinsics to get the branch destination as 4952 /// last parameter, also switches branch target with BR if the need arise 4953 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4954 SelectionDAG &DAG) const { 4955 SDLoc DL(BRCOND); 4956 4957 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4958 SDValue Target = BRCOND.getOperand(2); 4959 SDNode *BR = nullptr; 4960 SDNode *SetCC = nullptr; 4961 4962 if (Intr->getOpcode() == ISD::SETCC) { 4963 // As long as we negate the condition everything is fine 4964 SetCC = Intr; 4965 Intr = SetCC->getOperand(0).getNode(); 4966 4967 } else { 4968 // Get the target from BR if we don't negate the condition 4969 BR = findUser(BRCOND, ISD::BR); 4970 assert(BR && "brcond missing unconditional branch user"); 4971 Target = BR->getOperand(1); 4972 } 4973 4974 unsigned CFNode = isCFIntrinsic(Intr); 4975 if (CFNode == 0) { 4976 // This is a uniform branch so we don't need to legalize. 4977 return BRCOND; 4978 } 4979 4980 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4981 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4982 4983 assert(!SetCC || 4984 (SetCC->getConstantOperandVal(1) == 1 && 4985 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4986 ISD::SETNE)); 4987 4988 // operands of the new intrinsic call 4989 SmallVector<SDValue, 4> Ops; 4990 if (HaveChain) 4991 Ops.push_back(BRCOND.getOperand(0)); 4992 4993 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4994 Ops.push_back(Target); 4995 4996 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4997 4998 // build the new intrinsic call 4999 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5000 5001 if (!HaveChain) { 5002 SDValue Ops[] = { 5003 SDValue(Result, 0), 5004 BRCOND.getOperand(0) 5005 }; 5006 5007 Result = DAG.getMergeValues(Ops, DL).getNode(); 5008 } 5009 5010 if (BR) { 5011 // Give the branch instruction our target 5012 SDValue Ops[] = { 5013 BR->getOperand(0), 5014 BRCOND.getOperand(2) 5015 }; 5016 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5017 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5018 } 5019 5020 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5021 5022 // Copy the intrinsic results to registers 5023 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5024 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5025 if (!CopyToReg) 5026 continue; 5027 5028 Chain = DAG.getCopyToReg( 5029 Chain, DL, 5030 CopyToReg->getOperand(1), 5031 SDValue(Result, i - 1), 5032 SDValue()); 5033 5034 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5035 } 5036 5037 // Remove the old intrinsic from the chain 5038 DAG.ReplaceAllUsesOfValueWith( 5039 SDValue(Intr, Intr->getNumValues() - 1), 5040 Intr->getOperand(0)); 5041 5042 return Chain; 5043 } 5044 5045 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5046 SelectionDAG &DAG) const { 5047 MVT VT = Op.getSimpleValueType(); 5048 SDLoc DL(Op); 5049 // Checking the depth 5050 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5051 return DAG.getConstant(0, DL, VT); 5052 5053 MachineFunction &MF = DAG.getMachineFunction(); 5054 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5055 // Check for kernel and shader functions 5056 if (Info->isEntryFunction()) 5057 return DAG.getConstant(0, DL, VT); 5058 5059 MachineFrameInfo &MFI = MF.getFrameInfo(); 5060 // There is a call to @llvm.returnaddress in this function 5061 MFI.setReturnAddressIsTaken(true); 5062 5063 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5064 // Get the return address reg and mark it as an implicit live-in 5065 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5066 5067 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5068 } 5069 5070 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5071 SDValue Op, 5072 const SDLoc &DL, 5073 EVT VT) const { 5074 return Op.getValueType().bitsLE(VT) ? 5075 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5076 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5077 DAG.getTargetConstant(0, DL, MVT::i32)); 5078 } 5079 5080 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5081 assert(Op.getValueType() == MVT::f16 && 5082 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5083 5084 SDValue Src = Op.getOperand(0); 5085 EVT SrcVT = Src.getValueType(); 5086 if (SrcVT != MVT::f64) 5087 return Op; 5088 5089 SDLoc DL(Op); 5090 5091 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5092 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5093 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5094 } 5095 5096 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5097 SelectionDAG &DAG) const { 5098 EVT VT = Op.getValueType(); 5099 const MachineFunction &MF = DAG.getMachineFunction(); 5100 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5101 bool IsIEEEMode = Info->getMode().IEEE; 5102 5103 // FIXME: Assert during selection that this is only selected for 5104 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5105 // mode functions, but this happens to be OK since it's only done in cases 5106 // where there is known no sNaN. 5107 if (IsIEEEMode) 5108 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5109 5110 if (VT == MVT::v4f16) 5111 return splitBinaryVectorOp(Op, DAG); 5112 return Op; 5113 } 5114 5115 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5116 EVT VT = Op.getValueType(); 5117 SDLoc SL(Op); 5118 SDValue LHS = Op.getOperand(0); 5119 SDValue RHS = Op.getOperand(1); 5120 bool isSigned = Op.getOpcode() == ISD::SMULO; 5121 5122 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5123 const APInt &C = RHSC->getAPIntValue(); 5124 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5125 if (C.isPowerOf2()) { 5126 // smulo(x, signed_min) is same as umulo(x, signed_min). 5127 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5128 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5129 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5130 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5131 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5132 SL, VT, Result, ShiftAmt), 5133 LHS, ISD::SETNE); 5134 return DAG.getMergeValues({ Result, Overflow }, SL); 5135 } 5136 } 5137 5138 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5139 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5140 SL, VT, LHS, RHS); 5141 5142 SDValue Sign = isSigned 5143 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5144 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5145 : DAG.getConstant(0, SL, VT); 5146 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5147 5148 return DAG.getMergeValues({ Result, Overflow }, SL); 5149 } 5150 5151 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5152 SDLoc SL(Op); 5153 SDValue Chain = Op.getOperand(0); 5154 5155 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5156 !Subtarget->isTrapHandlerEnabled()) 5157 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5158 5159 MachineFunction &MF = DAG.getMachineFunction(); 5160 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5161 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5162 assert(UserSGPR != AMDGPU::NoRegister); 5163 SDValue QueuePtr = CreateLiveInRegister( 5164 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5165 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5166 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5167 QueuePtr, SDValue()); 5168 SDValue Ops[] = { 5169 ToReg, 5170 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 5171 SGPR01, 5172 ToReg.getValue(1) 5173 }; 5174 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5175 } 5176 5177 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5178 SDLoc SL(Op); 5179 SDValue Chain = Op.getOperand(0); 5180 MachineFunction &MF = DAG.getMachineFunction(); 5181 5182 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5183 !Subtarget->isTrapHandlerEnabled()) { 5184 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5185 "debugtrap handler not supported", 5186 Op.getDebugLoc(), 5187 DS_Warning); 5188 LLVMContext &Ctx = MF.getFunction().getContext(); 5189 Ctx.diagnose(NoTrap); 5190 return Chain; 5191 } 5192 5193 SDValue Ops[] = { 5194 Chain, 5195 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 5196 }; 5197 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5198 } 5199 5200 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5201 SelectionDAG &DAG) const { 5202 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5203 if (Subtarget->hasApertureRegs()) { 5204 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5205 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5206 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5207 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5208 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5209 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5210 unsigned Encoding = 5211 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5212 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5213 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5214 5215 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5216 SDValue ApertureReg = SDValue( 5217 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5218 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5219 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5220 } 5221 5222 MachineFunction &MF = DAG.getMachineFunction(); 5223 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5224 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5225 assert(UserSGPR != AMDGPU::NoRegister); 5226 5227 SDValue QueuePtr = CreateLiveInRegister( 5228 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5229 5230 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5231 // private_segment_aperture_base_hi. 5232 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5233 5234 SDValue Ptr = 5235 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5236 5237 // TODO: Use custom target PseudoSourceValue. 5238 // TODO: We should use the value from the IR intrinsic call, but it might not 5239 // be available and how do we get it? 5240 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5241 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5242 commonAlignment(Align(64), StructOffset), 5243 MachineMemOperand::MODereferenceable | 5244 MachineMemOperand::MOInvariant); 5245 } 5246 5247 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5248 SelectionDAG &DAG) const { 5249 SDLoc SL(Op); 5250 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5251 5252 SDValue Src = ASC->getOperand(0); 5253 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5254 5255 const AMDGPUTargetMachine &TM = 5256 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5257 5258 // flat -> local/private 5259 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5260 unsigned DestAS = ASC->getDestAddressSpace(); 5261 5262 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5263 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5264 unsigned NullVal = TM.getNullPointerValue(DestAS); 5265 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5266 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5267 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5268 5269 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5270 NonNull, Ptr, SegmentNullPtr); 5271 } 5272 } 5273 5274 // local/private -> flat 5275 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5276 unsigned SrcAS = ASC->getSrcAddressSpace(); 5277 5278 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5279 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5280 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5281 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5282 5283 SDValue NonNull 5284 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5285 5286 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5287 SDValue CvtPtr 5288 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5289 5290 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5291 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5292 FlatNullPtr); 5293 } 5294 } 5295 5296 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5297 Src.getValueType() == MVT::i64) 5298 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5299 5300 // global <-> flat are no-ops and never emitted. 5301 5302 const MachineFunction &MF = DAG.getMachineFunction(); 5303 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5304 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5305 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5306 5307 return DAG.getUNDEF(ASC->getValueType(0)); 5308 } 5309 5310 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5311 // the small vector and inserting them into the big vector. That is better than 5312 // the default expansion of doing it via a stack slot. Even though the use of 5313 // the stack slot would be optimized away afterwards, the stack slot itself 5314 // remains. 5315 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5316 SelectionDAG &DAG) const { 5317 SDValue Vec = Op.getOperand(0); 5318 SDValue Ins = Op.getOperand(1); 5319 SDValue Idx = Op.getOperand(2); 5320 EVT VecVT = Vec.getValueType(); 5321 EVT InsVT = Ins.getValueType(); 5322 EVT EltVT = VecVT.getVectorElementType(); 5323 unsigned InsNumElts = InsVT.getVectorNumElements(); 5324 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5325 SDLoc SL(Op); 5326 5327 for (unsigned I = 0; I != InsNumElts; ++I) { 5328 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5329 DAG.getConstant(I, SL, MVT::i32)); 5330 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5331 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5332 } 5333 return Vec; 5334 } 5335 5336 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5337 SelectionDAG &DAG) const { 5338 SDValue Vec = Op.getOperand(0); 5339 SDValue InsVal = Op.getOperand(1); 5340 SDValue Idx = Op.getOperand(2); 5341 EVT VecVT = Vec.getValueType(); 5342 EVT EltVT = VecVT.getVectorElementType(); 5343 unsigned VecSize = VecVT.getSizeInBits(); 5344 unsigned EltSize = EltVT.getSizeInBits(); 5345 5346 5347 assert(VecSize <= 64); 5348 5349 unsigned NumElts = VecVT.getVectorNumElements(); 5350 SDLoc SL(Op); 5351 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5352 5353 if (NumElts == 4 && EltSize == 16 && KIdx) { 5354 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5355 5356 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5357 DAG.getConstant(0, SL, MVT::i32)); 5358 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5359 DAG.getConstant(1, SL, MVT::i32)); 5360 5361 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5362 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5363 5364 unsigned Idx = KIdx->getZExtValue(); 5365 bool InsertLo = Idx < 2; 5366 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5367 InsertLo ? LoVec : HiVec, 5368 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5369 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5370 5371 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5372 5373 SDValue Concat = InsertLo ? 5374 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5375 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5376 5377 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5378 } 5379 5380 if (isa<ConstantSDNode>(Idx)) 5381 return SDValue(); 5382 5383 MVT IntVT = MVT::getIntegerVT(VecSize); 5384 5385 // Avoid stack access for dynamic indexing. 5386 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5387 5388 // Create a congruent vector with the target value in each element so that 5389 // the required element can be masked and ORed into the target vector. 5390 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5391 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5392 5393 assert(isPowerOf2_32(EltSize)); 5394 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5395 5396 // Convert vector index to bit-index. 5397 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5398 5399 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5400 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5401 DAG.getConstant(0xffff, SL, IntVT), 5402 ScaledIdx); 5403 5404 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5405 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5406 DAG.getNOT(SL, BFM, IntVT), BCVec); 5407 5408 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5409 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5410 } 5411 5412 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5413 SelectionDAG &DAG) const { 5414 SDLoc SL(Op); 5415 5416 EVT ResultVT = Op.getValueType(); 5417 SDValue Vec = Op.getOperand(0); 5418 SDValue Idx = Op.getOperand(1); 5419 EVT VecVT = Vec.getValueType(); 5420 unsigned VecSize = VecVT.getSizeInBits(); 5421 EVT EltVT = VecVT.getVectorElementType(); 5422 assert(VecSize <= 64); 5423 5424 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5425 5426 // Make sure we do any optimizations that will make it easier to fold 5427 // source modifiers before obscuring it with bit operations. 5428 5429 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5430 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5431 return Combined; 5432 5433 unsigned EltSize = EltVT.getSizeInBits(); 5434 assert(isPowerOf2_32(EltSize)); 5435 5436 MVT IntVT = MVT::getIntegerVT(VecSize); 5437 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5438 5439 // Convert vector index to bit-index (* EltSize) 5440 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5441 5442 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5443 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5444 5445 if (ResultVT == MVT::f16) { 5446 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5447 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5448 } 5449 5450 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5451 } 5452 5453 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5454 assert(Elt % 2 == 0); 5455 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5456 } 5457 5458 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5459 SelectionDAG &DAG) const { 5460 SDLoc SL(Op); 5461 EVT ResultVT = Op.getValueType(); 5462 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5463 5464 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5465 EVT EltVT = PackVT.getVectorElementType(); 5466 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5467 5468 // vector_shuffle <0,1,6,7> lhs, rhs 5469 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5470 // 5471 // vector_shuffle <6,7,2,3> lhs, rhs 5472 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5473 // 5474 // vector_shuffle <6,7,0,1> lhs, rhs 5475 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5476 5477 // Avoid scalarizing when both halves are reading from consecutive elements. 5478 SmallVector<SDValue, 4> Pieces; 5479 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5480 if (elementPairIsContiguous(SVN->getMask(), I)) { 5481 const int Idx = SVN->getMaskElt(I); 5482 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5483 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5484 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5485 PackVT, SVN->getOperand(VecIdx), 5486 DAG.getConstant(EltIdx, SL, MVT::i32)); 5487 Pieces.push_back(SubVec); 5488 } else { 5489 const int Idx0 = SVN->getMaskElt(I); 5490 const int Idx1 = SVN->getMaskElt(I + 1); 5491 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5492 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5493 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5494 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5495 5496 SDValue Vec0 = SVN->getOperand(VecIdx0); 5497 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5498 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5499 5500 SDValue Vec1 = SVN->getOperand(VecIdx1); 5501 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5502 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5503 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5504 } 5505 } 5506 5507 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5508 } 5509 5510 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5511 SelectionDAG &DAG) const { 5512 SDLoc SL(Op); 5513 EVT VT = Op.getValueType(); 5514 5515 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5516 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5517 5518 // Turn into pair of packed build_vectors. 5519 // TODO: Special case for constants that can be materialized with s_mov_b64. 5520 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5521 { Op.getOperand(0), Op.getOperand(1) }); 5522 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5523 { Op.getOperand(2), Op.getOperand(3) }); 5524 5525 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5526 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5527 5528 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5529 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5530 } 5531 5532 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5533 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5534 5535 SDValue Lo = Op.getOperand(0); 5536 SDValue Hi = Op.getOperand(1); 5537 5538 // Avoid adding defined bits with the zero_extend. 5539 if (Hi.isUndef()) { 5540 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5541 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5542 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5543 } 5544 5545 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5546 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5547 5548 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5549 DAG.getConstant(16, SL, MVT::i32)); 5550 if (Lo.isUndef()) 5551 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5552 5553 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5554 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5555 5556 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5557 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5558 } 5559 5560 bool 5561 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5562 // We can fold offsets for anything that doesn't require a GOT relocation. 5563 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5564 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5565 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5566 !shouldEmitGOTReloc(GA->getGlobal()); 5567 } 5568 5569 static SDValue 5570 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5571 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5572 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5573 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5574 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5575 // lowered to the following code sequence: 5576 // 5577 // For constant address space: 5578 // s_getpc_b64 s[0:1] 5579 // s_add_u32 s0, s0, $symbol 5580 // s_addc_u32 s1, s1, 0 5581 // 5582 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5583 // a fixup or relocation is emitted to replace $symbol with a literal 5584 // constant, which is a pc-relative offset from the encoding of the $symbol 5585 // operand to the global variable. 5586 // 5587 // For global address space: 5588 // s_getpc_b64 s[0:1] 5589 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5590 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5591 // 5592 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5593 // fixups or relocations are emitted to replace $symbol@*@lo and 5594 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5595 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5596 // operand to the global variable. 5597 // 5598 // What we want here is an offset from the value returned by s_getpc 5599 // (which is the address of the s_add_u32 instruction) to the global 5600 // variable, but since the encoding of $symbol starts 4 bytes after the start 5601 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5602 // small. This requires us to add 4 to the global variable offset in order to 5603 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5604 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5605 // instruction. 5606 SDValue PtrLo = 5607 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5608 SDValue PtrHi; 5609 if (GAFlags == SIInstrInfo::MO_NONE) { 5610 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5611 } else { 5612 PtrHi = 5613 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5614 } 5615 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5616 } 5617 5618 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5619 SDValue Op, 5620 SelectionDAG &DAG) const { 5621 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5622 SDLoc DL(GSD); 5623 EVT PtrVT = Op.getValueType(); 5624 5625 const GlobalValue *GV = GSD->getGlobal(); 5626 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5627 shouldUseLDSConstAddress(GV)) || 5628 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5629 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5630 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5631 GV->hasExternalLinkage()) { 5632 Type *Ty = GV->getValueType(); 5633 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5634 // zero-sized type in other languages to declare the dynamic shared 5635 // memory which size is not known at the compile time. They will be 5636 // allocated by the runtime and placed directly after the static 5637 // allocated ones. They all share the same offset. 5638 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5639 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5640 // Adjust alignment for that dynamic shared memory array. 5641 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5642 return SDValue( 5643 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5644 } 5645 } 5646 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5647 } 5648 5649 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5650 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5651 SIInstrInfo::MO_ABS32_LO); 5652 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5653 } 5654 5655 if (shouldEmitFixup(GV)) 5656 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5657 else if (shouldEmitPCReloc(GV)) 5658 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5659 SIInstrInfo::MO_REL32); 5660 5661 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5662 SIInstrInfo::MO_GOTPCREL32); 5663 5664 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5665 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5666 const DataLayout &DataLayout = DAG.getDataLayout(); 5667 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5668 MachinePointerInfo PtrInfo 5669 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5670 5671 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5672 MachineMemOperand::MODereferenceable | 5673 MachineMemOperand::MOInvariant); 5674 } 5675 5676 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5677 const SDLoc &DL, SDValue V) const { 5678 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5679 // the destination register. 5680 // 5681 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5682 // so we will end up with redundant moves to m0. 5683 // 5684 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5685 5686 // A Null SDValue creates a glue result. 5687 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5688 V, Chain); 5689 return SDValue(M0, 0); 5690 } 5691 5692 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5693 SDValue Op, 5694 MVT VT, 5695 unsigned Offset) const { 5696 SDLoc SL(Op); 5697 SDValue Param = lowerKernargMemParameter( 5698 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5699 // The local size values will have the hi 16-bits as zero. 5700 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5701 DAG.getValueType(VT)); 5702 } 5703 5704 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5705 EVT VT) { 5706 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5707 "non-hsa intrinsic with hsa target", 5708 DL.getDebugLoc()); 5709 DAG.getContext()->diagnose(BadIntrin); 5710 return DAG.getUNDEF(VT); 5711 } 5712 5713 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5714 EVT VT) { 5715 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5716 "intrinsic not supported on subtarget", 5717 DL.getDebugLoc()); 5718 DAG.getContext()->diagnose(BadIntrin); 5719 return DAG.getUNDEF(VT); 5720 } 5721 5722 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5723 ArrayRef<SDValue> Elts) { 5724 assert(!Elts.empty()); 5725 MVT Type; 5726 unsigned NumElts; 5727 5728 if (Elts.size() == 1) { 5729 Type = MVT::f32; 5730 NumElts = 1; 5731 } else if (Elts.size() == 2) { 5732 Type = MVT::v2f32; 5733 NumElts = 2; 5734 } else if (Elts.size() == 3) { 5735 Type = MVT::v3f32; 5736 NumElts = 3; 5737 } else if (Elts.size() <= 4) { 5738 Type = MVT::v4f32; 5739 NumElts = 4; 5740 } else if (Elts.size() <= 8) { 5741 Type = MVT::v8f32; 5742 NumElts = 8; 5743 } else { 5744 assert(Elts.size() <= 16); 5745 Type = MVT::v16f32; 5746 NumElts = 16; 5747 } 5748 5749 SmallVector<SDValue, 16> VecElts(NumElts); 5750 for (unsigned i = 0; i < Elts.size(); ++i) { 5751 SDValue Elt = Elts[i]; 5752 if (Elt.getValueType() != MVT::f32) 5753 Elt = DAG.getBitcast(MVT::f32, Elt); 5754 VecElts[i] = Elt; 5755 } 5756 for (unsigned i = Elts.size(); i < NumElts; ++i) 5757 VecElts[i] = DAG.getUNDEF(MVT::f32); 5758 5759 if (NumElts == 1) 5760 return VecElts[0]; 5761 return DAG.getBuildVector(Type, DL, VecElts); 5762 } 5763 5764 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5765 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5766 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5767 5768 uint64_t Value = CachePolicyConst->getZExtValue(); 5769 SDLoc DL(CachePolicy); 5770 if (GLC) { 5771 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5772 Value &= ~(uint64_t)0x1; 5773 } 5774 if (SLC) { 5775 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5776 Value &= ~(uint64_t)0x2; 5777 } 5778 if (DLC) { 5779 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5780 Value &= ~(uint64_t)0x4; 5781 } 5782 5783 return Value == 0; 5784 } 5785 5786 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5787 SDValue Src, int ExtraElts) { 5788 EVT SrcVT = Src.getValueType(); 5789 5790 SmallVector<SDValue, 8> Elts; 5791 5792 if (SrcVT.isVector()) 5793 DAG.ExtractVectorElements(Src, Elts); 5794 else 5795 Elts.push_back(Src); 5796 5797 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5798 while (ExtraElts--) 5799 Elts.push_back(Undef); 5800 5801 return DAG.getBuildVector(CastVT, DL, Elts); 5802 } 5803 5804 // Re-construct the required return value for a image load intrinsic. 5805 // This is more complicated due to the optional use TexFailCtrl which means the required 5806 // return type is an aggregate 5807 static SDValue constructRetValue(SelectionDAG &DAG, 5808 MachineSDNode *Result, 5809 ArrayRef<EVT> ResultTypes, 5810 bool IsTexFail, bool Unpacked, bool IsD16, 5811 int DMaskPop, int NumVDataDwords, 5812 const SDLoc &DL, LLVMContext &Context) { 5813 // Determine the required return type. This is the same regardless of IsTexFail flag 5814 EVT ReqRetVT = ResultTypes[0]; 5815 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5816 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5817 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5818 5819 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5820 DMaskPop : (DMaskPop + 1) / 2; 5821 5822 MVT DataDwordVT = NumDataDwords == 1 ? 5823 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5824 5825 MVT MaskPopVT = MaskPopDwords == 1 ? 5826 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5827 5828 SDValue Data(Result, 0); 5829 SDValue TexFail; 5830 5831 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 5832 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5833 if (MaskPopVT.isVector()) { 5834 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5835 SDValue(Result, 0), ZeroIdx); 5836 } else { 5837 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5838 SDValue(Result, 0), ZeroIdx); 5839 } 5840 } 5841 5842 if (DataDwordVT.isVector()) 5843 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5844 NumDataDwords - MaskPopDwords); 5845 5846 if (IsD16) 5847 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5848 5849 EVT LegalReqRetVT = ReqRetVT; 5850 if (!ReqRetVT.isVector()) { 5851 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5852 } else { 5853 // We need to widen the return vector to a legal type 5854 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 5855 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 5856 LegalReqRetVT = 5857 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 5858 ReqRetVT.getVectorNumElements() + 1); 5859 } 5860 } 5861 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 5862 5863 if (IsTexFail) { 5864 TexFail = 5865 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 5866 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5867 5868 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5869 } 5870 5871 if (Result->getNumValues() == 1) 5872 return Data; 5873 5874 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5875 } 5876 5877 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5878 SDValue *LWE, bool &IsTexFail) { 5879 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5880 5881 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5882 if (Value) { 5883 IsTexFail = true; 5884 } 5885 5886 SDLoc DL(TexFailCtrlConst); 5887 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5888 Value &= ~(uint64_t)0x1; 5889 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5890 Value &= ~(uint64_t)0x2; 5891 5892 return Value == 0; 5893 } 5894 5895 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5896 MVT PackVectorVT, 5897 SmallVectorImpl<SDValue> &PackedAddrs, 5898 unsigned DimIdx, unsigned EndIdx, 5899 unsigned NumGradients) { 5900 SDLoc DL(Op); 5901 for (unsigned I = DimIdx; I < EndIdx; I++) { 5902 SDValue Addr = Op.getOperand(I); 5903 5904 // Gradients are packed with undef for each coordinate. 5905 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5906 // 1D: undef,dx/dh; undef,dx/dv 5907 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5908 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5909 if (((I + 1) >= EndIdx) || 5910 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5911 I == DimIdx + NumGradients - 1))) { 5912 if (Addr.getValueType() != MVT::i16) 5913 Addr = DAG.getBitcast(MVT::i16, Addr); 5914 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5915 } else { 5916 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5917 I++; 5918 } 5919 Addr = DAG.getBitcast(MVT::f32, Addr); 5920 PackedAddrs.push_back(Addr); 5921 } 5922 } 5923 5924 SDValue SITargetLowering::lowerImage(SDValue Op, 5925 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5926 SelectionDAG &DAG, bool WithChain) const { 5927 SDLoc DL(Op); 5928 MachineFunction &MF = DAG.getMachineFunction(); 5929 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5930 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5931 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5932 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5933 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5934 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5935 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5936 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5937 unsigned IntrOpcode = Intr->BaseOpcode; 5938 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 5939 5940 SmallVector<EVT, 3> ResultTypes(Op->values()); 5941 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 5942 bool IsD16 = false; 5943 bool IsG16 = false; 5944 bool IsA16 = false; 5945 SDValue VData; 5946 int NumVDataDwords; 5947 bool AdjustRetType = false; 5948 5949 // Offset of intrinsic arguments 5950 const unsigned ArgOffset = WithChain ? 2 : 1; 5951 5952 unsigned DMask; 5953 unsigned DMaskLanes = 0; 5954 5955 if (BaseOpcode->Atomic) { 5956 VData = Op.getOperand(2); 5957 5958 bool Is64Bit = VData.getValueType() == MVT::i64; 5959 if (BaseOpcode->AtomicX2) { 5960 SDValue VData2 = Op.getOperand(3); 5961 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5962 {VData, VData2}); 5963 if (Is64Bit) 5964 VData = DAG.getBitcast(MVT::v4i32, VData); 5965 5966 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5967 DMask = Is64Bit ? 0xf : 0x3; 5968 NumVDataDwords = Is64Bit ? 4 : 2; 5969 } else { 5970 DMask = Is64Bit ? 0x3 : 0x1; 5971 NumVDataDwords = Is64Bit ? 2 : 1; 5972 } 5973 } else { 5974 auto *DMaskConst = 5975 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 5976 DMask = DMaskConst->getZExtValue(); 5977 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5978 5979 if (BaseOpcode->Store) { 5980 VData = Op.getOperand(2); 5981 5982 MVT StoreVT = VData.getSimpleValueType(); 5983 if (StoreVT.getScalarType() == MVT::f16) { 5984 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5985 return Op; // D16 is unsupported for this instruction 5986 5987 IsD16 = true; 5988 VData = handleD16VData(VData, DAG, true); 5989 } 5990 5991 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5992 } else { 5993 // Work out the num dwords based on the dmask popcount and underlying type 5994 // and whether packing is supported. 5995 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5996 if (LoadVT.getScalarType() == MVT::f16) { 5997 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5998 return Op; // D16 is unsupported for this instruction 5999 6000 IsD16 = true; 6001 } 6002 6003 // Confirm that the return type is large enough for the dmask specified 6004 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6005 (!LoadVT.isVector() && DMaskLanes > 1)) 6006 return Op; 6007 6008 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6009 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6010 // instructions. 6011 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6012 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6013 NumVDataDwords = (DMaskLanes + 1) / 2; 6014 else 6015 NumVDataDwords = DMaskLanes; 6016 6017 AdjustRetType = true; 6018 } 6019 } 6020 6021 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6022 SmallVector<SDValue, 4> VAddrs; 6023 6024 // Optimize _L to _LZ when _L is zero 6025 if (LZMappingInfo) { 6026 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6027 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6028 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6029 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6030 VAddrEnd--; // remove 'lod' 6031 } 6032 } 6033 } 6034 6035 // Optimize _mip away, when 'lod' is zero 6036 if (MIPMappingInfo) { 6037 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6038 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6039 if (ConstantLod->isNullValue()) { 6040 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6041 VAddrEnd--; // remove 'mip' 6042 } 6043 } 6044 } 6045 6046 // Push back extra arguments. 6047 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) 6048 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6049 6050 // Check for 16 bit addresses or derivatives and pack if true. 6051 MVT VAddrVT = 6052 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6053 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6054 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6055 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6056 6057 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6058 VAddrScalarVT = VAddrVT.getScalarType(); 6059 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6060 if (IsA16 || IsG16) { 6061 if (IsA16) { 6062 if (!ST->hasA16()) { 6063 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6064 "support 16 bit addresses\n"); 6065 return Op; 6066 } 6067 if (!IsG16) { 6068 LLVM_DEBUG( 6069 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6070 "need 16 bit derivatives but got 32 bit derivatives\n"); 6071 return Op; 6072 } 6073 } else if (!ST->hasG16()) { 6074 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6075 "support 16 bit derivatives\n"); 6076 return Op; 6077 } 6078 6079 if (BaseOpcode->Gradients && !IsA16) { 6080 if (!ST->hasG16()) { 6081 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6082 "support 16 bit derivatives\n"); 6083 return Op; 6084 } 6085 // Activate g16 6086 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6087 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6088 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6089 } 6090 6091 // Don't compress addresses for G16 6092 const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6093 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, 6094 ArgOffset + Intr->GradientStart, PackEndIdx, 6095 Intr->NumGradients); 6096 6097 if (!IsA16) { 6098 // Add uncompressed address 6099 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6100 VAddrs.push_back(Op.getOperand(I)); 6101 } 6102 } else { 6103 for (unsigned I = ArgOffset + Intr->GradientStart; I < VAddrEnd; I++) 6104 VAddrs.push_back(Op.getOperand(I)); 6105 } 6106 6107 // If the register allocator cannot place the address registers contiguously 6108 // without introducing moves, then using the non-sequential address encoding 6109 // is always preferable, since it saves VALU instructions and is usually a 6110 // wash in terms of code size or even better. 6111 // 6112 // However, we currently have no way of hinting to the register allocator that 6113 // MIMG addresses should be placed contiguously when it is possible to do so, 6114 // so force non-NSA for the common 2-address case as a heuristic. 6115 // 6116 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6117 // allocation when possible. 6118 bool UseNSA = 6119 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 6120 SDValue VAddr; 6121 if (!UseNSA) 6122 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6123 6124 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6125 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6126 SDValue Unorm; 6127 if (!BaseOpcode->Sampler) { 6128 Unorm = True; 6129 } else { 6130 auto UnormConst = 6131 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6132 6133 Unorm = UnormConst->getZExtValue() ? True : False; 6134 } 6135 6136 SDValue TFE; 6137 SDValue LWE; 6138 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6139 bool IsTexFail = false; 6140 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6141 return Op; 6142 6143 if (IsTexFail) { 6144 if (!DMaskLanes) { 6145 // Expecting to get an error flag since TFC is on - and dmask is 0 6146 // Force dmask to be at least 1 otherwise the instruction will fail 6147 DMask = 0x1; 6148 DMaskLanes = 1; 6149 NumVDataDwords = 1; 6150 } 6151 NumVDataDwords += 1; 6152 AdjustRetType = true; 6153 } 6154 6155 // Has something earlier tagged that the return type needs adjusting 6156 // This happens if the instruction is a load or has set TexFailCtrl flags 6157 if (AdjustRetType) { 6158 // NumVDataDwords reflects the true number of dwords required in the return type 6159 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6160 // This is a no-op load. This can be eliminated 6161 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6162 if (isa<MemSDNode>(Op)) 6163 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6164 return Undef; 6165 } 6166 6167 EVT NewVT = NumVDataDwords > 1 ? 6168 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6169 : MVT::i32; 6170 6171 ResultTypes[0] = NewVT; 6172 if (ResultTypes.size() == 3) { 6173 // Original result was aggregate type used for TexFailCtrl results 6174 // The actual instruction returns as a vector type which has now been 6175 // created. Remove the aggregate result. 6176 ResultTypes.erase(&ResultTypes[1]); 6177 } 6178 } 6179 6180 SDValue GLC; 6181 SDValue SLC; 6182 SDValue DLC; 6183 if (BaseOpcode->Atomic) { 6184 GLC = True; // TODO no-return optimization 6185 if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex), 6186 DAG, nullptr, &SLC, IsGFX10Plus ? &DLC : nullptr)) 6187 return Op; 6188 } else { 6189 if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex), 6190 DAG, &GLC, &SLC, IsGFX10Plus ? &DLC : nullptr)) 6191 return Op; 6192 } 6193 6194 SmallVector<SDValue, 26> Ops; 6195 if (BaseOpcode->Store || BaseOpcode->Atomic) 6196 Ops.push_back(VData); // vdata 6197 if (UseNSA) 6198 append_range(Ops, VAddrs); 6199 else 6200 Ops.push_back(VAddr); 6201 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6202 if (BaseOpcode->Sampler) 6203 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6204 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6205 if (IsGFX10Plus) 6206 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6207 Ops.push_back(Unorm); 6208 if (!IsGFX10Plus) 6209 Ops.push_back(DAG.getTargetConstant(0, SDLoc(), MVT::i1)); 6210 if (IsGFX10Plus) 6211 Ops.push_back(DLC); 6212 Ops.push_back(GLC); 6213 Ops.push_back(SLC); 6214 Ops.push_back(IsA16 && // r128, a16 for gfx9 6215 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6216 if (IsGFX10Plus) 6217 Ops.push_back(IsA16 ? True : False); 6218 if (!Subtarget->hasGFX90AInsts()) { 6219 Ops.push_back(TFE); //tfe 6220 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6221 report_fatal_error("TFE is not supported on this GPU"); 6222 } 6223 Ops.push_back(LWE); // lwe 6224 if (!IsGFX10Plus) 6225 Ops.push_back(DimInfo->DA ? True : False); 6226 if (BaseOpcode->HasD16) 6227 Ops.push_back(IsD16 ? True : False); 6228 if (isa<MemSDNode>(Op)) 6229 Ops.push_back(Op.getOperand(0)); // chain 6230 6231 int NumVAddrDwords = 6232 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6233 int Opcode = -1; 6234 6235 if (IsGFX10Plus) { 6236 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6237 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6238 : AMDGPU::MIMGEncGfx10Default, 6239 NumVDataDwords, NumVAddrDwords); 6240 } else { 6241 if (Subtarget->hasGFX90AInsts()) { 6242 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6243 NumVDataDwords, NumVAddrDwords); 6244 if (Opcode == -1) 6245 report_fatal_error( 6246 "requested image instruction is not supported on this GPU"); 6247 } 6248 if (Opcode == -1 && 6249 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6250 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6251 NumVDataDwords, NumVAddrDwords); 6252 if (Opcode == -1) 6253 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6254 NumVDataDwords, NumVAddrDwords); 6255 } 6256 assert(Opcode != -1); 6257 6258 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6259 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6260 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6261 DAG.setNodeMemRefs(NewNode, {MemRef}); 6262 } 6263 6264 if (BaseOpcode->AtomicX2) { 6265 SmallVector<SDValue, 1> Elt; 6266 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6267 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6268 } else if (!BaseOpcode->Store) { 6269 return constructRetValue(DAG, NewNode, 6270 OrigResultTypes, IsTexFail, 6271 Subtarget->hasUnpackedD16VMem(), IsD16, 6272 DMaskLanes, NumVDataDwords, DL, 6273 *DAG.getContext()); 6274 } 6275 6276 return SDValue(NewNode, 0); 6277 } 6278 6279 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6280 SDValue Offset, SDValue CachePolicy, 6281 SelectionDAG &DAG) const { 6282 MachineFunction &MF = DAG.getMachineFunction(); 6283 6284 const DataLayout &DataLayout = DAG.getDataLayout(); 6285 Align Alignment = 6286 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6287 6288 MachineMemOperand *MMO = MF.getMachineMemOperand( 6289 MachinePointerInfo(), 6290 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6291 MachineMemOperand::MOInvariant, 6292 VT.getStoreSize(), Alignment); 6293 6294 if (!Offset->isDivergent()) { 6295 SDValue Ops[] = { 6296 Rsrc, 6297 Offset, // Offset 6298 CachePolicy 6299 }; 6300 6301 // Widen vec3 load to vec4. 6302 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6303 EVT WidenedVT = 6304 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6305 auto WidenedOp = DAG.getMemIntrinsicNode( 6306 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6307 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6308 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6309 DAG.getVectorIdxConstant(0, DL)); 6310 return Subvector; 6311 } 6312 6313 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6314 DAG.getVTList(VT), Ops, VT, MMO); 6315 } 6316 6317 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6318 // assume that the buffer is unswizzled. 6319 SmallVector<SDValue, 4> Loads; 6320 unsigned NumLoads = 1; 6321 MVT LoadVT = VT.getSimpleVT(); 6322 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6323 assert((LoadVT.getScalarType() == MVT::i32 || 6324 LoadVT.getScalarType() == MVT::f32)); 6325 6326 if (NumElts == 8 || NumElts == 16) { 6327 NumLoads = NumElts / 4; 6328 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6329 } 6330 6331 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6332 SDValue Ops[] = { 6333 DAG.getEntryNode(), // Chain 6334 Rsrc, // rsrc 6335 DAG.getConstant(0, DL, MVT::i32), // vindex 6336 {}, // voffset 6337 {}, // soffset 6338 {}, // offset 6339 CachePolicy, // cachepolicy 6340 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6341 }; 6342 6343 // Use the alignment to ensure that the required offsets will fit into the 6344 // immediate offsets. 6345 setBufferOffsets(Offset, DAG, &Ops[3], 6346 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6347 6348 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6349 for (unsigned i = 0; i < NumLoads; ++i) { 6350 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6351 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6352 LoadVT, MMO, DAG)); 6353 } 6354 6355 if (NumElts == 8 || NumElts == 16) 6356 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6357 6358 return Loads[0]; 6359 } 6360 6361 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6362 SelectionDAG &DAG) const { 6363 MachineFunction &MF = DAG.getMachineFunction(); 6364 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6365 6366 EVT VT = Op.getValueType(); 6367 SDLoc DL(Op); 6368 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6369 6370 // TODO: Should this propagate fast-math-flags? 6371 6372 switch (IntrinsicID) { 6373 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6374 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6375 return emitNonHSAIntrinsicError(DAG, DL, VT); 6376 return getPreloadedValue(DAG, *MFI, VT, 6377 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6378 } 6379 case Intrinsic::amdgcn_dispatch_ptr: 6380 case Intrinsic::amdgcn_queue_ptr: { 6381 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6382 DiagnosticInfoUnsupported BadIntrin( 6383 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6384 DL.getDebugLoc()); 6385 DAG.getContext()->diagnose(BadIntrin); 6386 return DAG.getUNDEF(VT); 6387 } 6388 6389 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6390 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6391 return getPreloadedValue(DAG, *MFI, VT, RegID); 6392 } 6393 case Intrinsic::amdgcn_implicitarg_ptr: { 6394 if (MFI->isEntryFunction()) 6395 return getImplicitArgPtr(DAG, DL); 6396 return getPreloadedValue(DAG, *MFI, VT, 6397 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6398 } 6399 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6400 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6401 // This only makes sense to call in a kernel, so just lower to null. 6402 return DAG.getConstant(0, DL, VT); 6403 } 6404 6405 return getPreloadedValue(DAG, *MFI, VT, 6406 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6407 } 6408 case Intrinsic::amdgcn_dispatch_id: { 6409 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6410 } 6411 case Intrinsic::amdgcn_rcp: 6412 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6413 case Intrinsic::amdgcn_rsq: 6414 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6415 case Intrinsic::amdgcn_rsq_legacy: 6416 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6417 return emitRemovedIntrinsicError(DAG, DL, VT); 6418 return SDValue(); 6419 case Intrinsic::amdgcn_rcp_legacy: 6420 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6421 return emitRemovedIntrinsicError(DAG, DL, VT); 6422 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6423 case Intrinsic::amdgcn_rsq_clamp: { 6424 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6425 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6426 6427 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6428 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6429 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6430 6431 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6432 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6433 DAG.getConstantFP(Max, DL, VT)); 6434 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6435 DAG.getConstantFP(Min, DL, VT)); 6436 } 6437 case Intrinsic::r600_read_ngroups_x: 6438 if (Subtarget->isAmdHsaOS()) 6439 return emitNonHSAIntrinsicError(DAG, DL, VT); 6440 6441 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6442 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6443 false); 6444 case Intrinsic::r600_read_ngroups_y: 6445 if (Subtarget->isAmdHsaOS()) 6446 return emitNonHSAIntrinsicError(DAG, DL, VT); 6447 6448 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6449 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6450 false); 6451 case Intrinsic::r600_read_ngroups_z: 6452 if (Subtarget->isAmdHsaOS()) 6453 return emitNonHSAIntrinsicError(DAG, DL, VT); 6454 6455 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6456 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6457 false); 6458 case Intrinsic::r600_read_global_size_x: 6459 if (Subtarget->isAmdHsaOS()) 6460 return emitNonHSAIntrinsicError(DAG, DL, VT); 6461 6462 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6463 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6464 Align(4), false); 6465 case Intrinsic::r600_read_global_size_y: 6466 if (Subtarget->isAmdHsaOS()) 6467 return emitNonHSAIntrinsicError(DAG, DL, VT); 6468 6469 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6470 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6471 Align(4), false); 6472 case Intrinsic::r600_read_global_size_z: 6473 if (Subtarget->isAmdHsaOS()) 6474 return emitNonHSAIntrinsicError(DAG, DL, VT); 6475 6476 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6477 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6478 Align(4), false); 6479 case Intrinsic::r600_read_local_size_x: 6480 if (Subtarget->isAmdHsaOS()) 6481 return emitNonHSAIntrinsicError(DAG, DL, VT); 6482 6483 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6484 SI::KernelInputOffsets::LOCAL_SIZE_X); 6485 case Intrinsic::r600_read_local_size_y: 6486 if (Subtarget->isAmdHsaOS()) 6487 return emitNonHSAIntrinsicError(DAG, DL, VT); 6488 6489 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6490 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6491 case Intrinsic::r600_read_local_size_z: 6492 if (Subtarget->isAmdHsaOS()) 6493 return emitNonHSAIntrinsicError(DAG, DL, VT); 6494 6495 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6496 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6497 case Intrinsic::amdgcn_workgroup_id_x: 6498 return getPreloadedValue(DAG, *MFI, VT, 6499 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6500 case Intrinsic::amdgcn_workgroup_id_y: 6501 return getPreloadedValue(DAG, *MFI, VT, 6502 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6503 case Intrinsic::amdgcn_workgroup_id_z: 6504 return getPreloadedValue(DAG, *MFI, VT, 6505 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6506 case Intrinsic::amdgcn_workitem_id_x: 6507 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6508 SDLoc(DAG.getEntryNode()), 6509 MFI->getArgInfo().WorkItemIDX); 6510 case Intrinsic::amdgcn_workitem_id_y: 6511 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6512 SDLoc(DAG.getEntryNode()), 6513 MFI->getArgInfo().WorkItemIDY); 6514 case Intrinsic::amdgcn_workitem_id_z: 6515 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6516 SDLoc(DAG.getEntryNode()), 6517 MFI->getArgInfo().WorkItemIDZ); 6518 case Intrinsic::amdgcn_wavefrontsize: 6519 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6520 SDLoc(Op), MVT::i32); 6521 case Intrinsic::amdgcn_s_buffer_load: { 6522 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6523 SDValue GLC; 6524 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6525 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6526 IsGFX10Plus ? &DLC : nullptr)) 6527 return Op; 6528 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6529 DAG); 6530 } 6531 case Intrinsic::amdgcn_fdiv_fast: 6532 return lowerFDIV_FAST(Op, DAG); 6533 case Intrinsic::amdgcn_sin: 6534 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6535 6536 case Intrinsic::amdgcn_cos: 6537 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6538 6539 case Intrinsic::amdgcn_mul_u24: 6540 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6541 case Intrinsic::amdgcn_mul_i24: 6542 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6543 6544 case Intrinsic::amdgcn_log_clamp: { 6545 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6546 return SDValue(); 6547 6548 return emitRemovedIntrinsicError(DAG, DL, VT); 6549 } 6550 case Intrinsic::amdgcn_ldexp: 6551 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6552 Op.getOperand(1), Op.getOperand(2)); 6553 6554 case Intrinsic::amdgcn_fract: 6555 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6556 6557 case Intrinsic::amdgcn_class: 6558 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6559 Op.getOperand(1), Op.getOperand(2)); 6560 case Intrinsic::amdgcn_div_fmas: 6561 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6562 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6563 Op.getOperand(4)); 6564 6565 case Intrinsic::amdgcn_div_fixup: 6566 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6567 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6568 6569 case Intrinsic::amdgcn_div_scale: { 6570 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6571 6572 // Translate to the operands expected by the machine instruction. The 6573 // first parameter must be the same as the first instruction. 6574 SDValue Numerator = Op.getOperand(1); 6575 SDValue Denominator = Op.getOperand(2); 6576 6577 // Note this order is opposite of the machine instruction's operations, 6578 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6579 // intrinsic has the numerator as the first operand to match a normal 6580 // division operation. 6581 6582 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6583 6584 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6585 Denominator, Numerator); 6586 } 6587 case Intrinsic::amdgcn_icmp: { 6588 // There is a Pat that handles this variant, so return it as-is. 6589 if (Op.getOperand(1).getValueType() == MVT::i1 && 6590 Op.getConstantOperandVal(2) == 0 && 6591 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6592 return Op; 6593 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6594 } 6595 case Intrinsic::amdgcn_fcmp: { 6596 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6597 } 6598 case Intrinsic::amdgcn_ballot: 6599 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6600 case Intrinsic::amdgcn_fmed3: 6601 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6602 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6603 case Intrinsic::amdgcn_fdot2: 6604 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6605 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6606 Op.getOperand(4)); 6607 case Intrinsic::amdgcn_fmul_legacy: 6608 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6609 Op.getOperand(1), Op.getOperand(2)); 6610 case Intrinsic::amdgcn_sffbh: 6611 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6612 case Intrinsic::amdgcn_sbfe: 6613 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6614 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6615 case Intrinsic::amdgcn_ubfe: 6616 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6617 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6618 case Intrinsic::amdgcn_cvt_pkrtz: 6619 case Intrinsic::amdgcn_cvt_pknorm_i16: 6620 case Intrinsic::amdgcn_cvt_pknorm_u16: 6621 case Intrinsic::amdgcn_cvt_pk_i16: 6622 case Intrinsic::amdgcn_cvt_pk_u16: { 6623 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6624 EVT VT = Op.getValueType(); 6625 unsigned Opcode; 6626 6627 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6628 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6629 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6630 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6631 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6632 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6633 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6634 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6635 else 6636 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6637 6638 if (isTypeLegal(VT)) 6639 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6640 6641 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6642 Op.getOperand(1), Op.getOperand(2)); 6643 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6644 } 6645 case Intrinsic::amdgcn_fmad_ftz: 6646 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6647 Op.getOperand(2), Op.getOperand(3)); 6648 6649 case Intrinsic::amdgcn_if_break: 6650 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6651 Op->getOperand(1), Op->getOperand(2)), 0); 6652 6653 case Intrinsic::amdgcn_groupstaticsize: { 6654 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6655 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6656 return Op; 6657 6658 const Module *M = MF.getFunction().getParent(); 6659 const GlobalValue *GV = 6660 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6661 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6662 SIInstrInfo::MO_ABS32_LO); 6663 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6664 } 6665 case Intrinsic::amdgcn_is_shared: 6666 case Intrinsic::amdgcn_is_private: { 6667 SDLoc SL(Op); 6668 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6669 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6670 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6671 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6672 Op.getOperand(1)); 6673 6674 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6675 DAG.getConstant(1, SL, MVT::i32)); 6676 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6677 } 6678 case Intrinsic::amdgcn_alignbit: 6679 return DAG.getNode(ISD::FSHR, DL, VT, 6680 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6681 case Intrinsic::amdgcn_reloc_constant: { 6682 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6683 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6684 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6685 auto RelocSymbol = cast<GlobalVariable>( 6686 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6687 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6688 SIInstrInfo::MO_ABS32_LO); 6689 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6690 } 6691 default: 6692 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6693 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6694 return lowerImage(Op, ImageDimIntr, DAG, false); 6695 6696 return Op; 6697 } 6698 } 6699 6700 // This function computes an appropriate offset to pass to 6701 // MachineMemOperand::setOffset() based on the offset inputs to 6702 // an intrinsic. If any of the offsets are non-contstant or 6703 // if VIndex is non-zero then this function returns 0. Otherwise, 6704 // it returns the sum of VOffset, SOffset, and Offset. 6705 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6706 SDValue SOffset, 6707 SDValue Offset, 6708 SDValue VIndex = SDValue()) { 6709 6710 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6711 !isa<ConstantSDNode>(Offset)) 6712 return 0; 6713 6714 if (VIndex) { 6715 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6716 return 0; 6717 } 6718 6719 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6720 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6721 cast<ConstantSDNode>(Offset)->getSExtValue(); 6722 } 6723 6724 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6725 SelectionDAG &DAG, 6726 unsigned NewOpcode) const { 6727 SDLoc DL(Op); 6728 6729 SDValue VData = Op.getOperand(2); 6730 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6731 SDValue Ops[] = { 6732 Op.getOperand(0), // Chain 6733 VData, // vdata 6734 Op.getOperand(3), // rsrc 6735 DAG.getConstant(0, DL, MVT::i32), // vindex 6736 Offsets.first, // voffset 6737 Op.getOperand(5), // soffset 6738 Offsets.second, // offset 6739 Op.getOperand(6), // cachepolicy 6740 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6741 }; 6742 6743 auto *M = cast<MemSDNode>(Op); 6744 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6745 6746 EVT MemVT = VData.getValueType(); 6747 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6748 M->getMemOperand()); 6749 } 6750 6751 SDValue 6752 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6753 unsigned NewOpcode) const { 6754 SDLoc DL(Op); 6755 6756 SDValue VData = Op.getOperand(2); 6757 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6758 SDValue Ops[] = { 6759 Op.getOperand(0), // Chain 6760 VData, // vdata 6761 Op.getOperand(3), // rsrc 6762 Op.getOperand(4), // vindex 6763 Offsets.first, // voffset 6764 Op.getOperand(6), // soffset 6765 Offsets.second, // offset 6766 Op.getOperand(7), // cachepolicy 6767 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6768 }; 6769 6770 auto *M = cast<MemSDNode>(Op); 6771 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6772 Ops[3])); 6773 6774 EVT MemVT = VData.getValueType(); 6775 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6776 M->getMemOperand()); 6777 } 6778 6779 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6780 SelectionDAG &DAG) const { 6781 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6782 SDLoc DL(Op); 6783 6784 switch (IntrID) { 6785 case Intrinsic::amdgcn_ds_ordered_add: 6786 case Intrinsic::amdgcn_ds_ordered_swap: { 6787 MemSDNode *M = cast<MemSDNode>(Op); 6788 SDValue Chain = M->getOperand(0); 6789 SDValue M0 = M->getOperand(2); 6790 SDValue Value = M->getOperand(3); 6791 unsigned IndexOperand = M->getConstantOperandVal(7); 6792 unsigned WaveRelease = M->getConstantOperandVal(8); 6793 unsigned WaveDone = M->getConstantOperandVal(9); 6794 6795 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6796 IndexOperand &= ~0x3f; 6797 unsigned CountDw = 0; 6798 6799 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6800 CountDw = (IndexOperand >> 24) & 0xf; 6801 IndexOperand &= ~(0xf << 24); 6802 6803 if (CountDw < 1 || CountDw > 4) { 6804 report_fatal_error( 6805 "ds_ordered_count: dword count must be between 1 and 4"); 6806 } 6807 } 6808 6809 if (IndexOperand) 6810 report_fatal_error("ds_ordered_count: bad index operand"); 6811 6812 if (WaveDone && !WaveRelease) 6813 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6814 6815 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6816 unsigned ShaderType = 6817 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6818 unsigned Offset0 = OrderedCountIndex << 2; 6819 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6820 (Instruction << 4); 6821 6822 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6823 Offset1 |= (CountDw - 1) << 6; 6824 6825 unsigned Offset = Offset0 | (Offset1 << 8); 6826 6827 SDValue Ops[] = { 6828 Chain, 6829 Value, 6830 DAG.getTargetConstant(Offset, DL, MVT::i16), 6831 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6832 }; 6833 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6834 M->getVTList(), Ops, M->getMemoryVT(), 6835 M->getMemOperand()); 6836 } 6837 case Intrinsic::amdgcn_ds_fadd: { 6838 MemSDNode *M = cast<MemSDNode>(Op); 6839 unsigned Opc; 6840 switch (IntrID) { 6841 case Intrinsic::amdgcn_ds_fadd: 6842 Opc = ISD::ATOMIC_LOAD_FADD; 6843 break; 6844 } 6845 6846 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6847 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6848 M->getMemOperand()); 6849 } 6850 case Intrinsic::amdgcn_atomic_inc: 6851 case Intrinsic::amdgcn_atomic_dec: 6852 case Intrinsic::amdgcn_ds_fmin: 6853 case Intrinsic::amdgcn_ds_fmax: { 6854 MemSDNode *M = cast<MemSDNode>(Op); 6855 unsigned Opc; 6856 switch (IntrID) { 6857 case Intrinsic::amdgcn_atomic_inc: 6858 Opc = AMDGPUISD::ATOMIC_INC; 6859 break; 6860 case Intrinsic::amdgcn_atomic_dec: 6861 Opc = AMDGPUISD::ATOMIC_DEC; 6862 break; 6863 case Intrinsic::amdgcn_ds_fmin: 6864 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6865 break; 6866 case Intrinsic::amdgcn_ds_fmax: 6867 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6868 break; 6869 default: 6870 llvm_unreachable("Unknown intrinsic!"); 6871 } 6872 SDValue Ops[] = { 6873 M->getOperand(0), // Chain 6874 M->getOperand(2), // Ptr 6875 M->getOperand(3) // Value 6876 }; 6877 6878 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6879 M->getMemoryVT(), M->getMemOperand()); 6880 } 6881 case Intrinsic::amdgcn_buffer_load: 6882 case Intrinsic::amdgcn_buffer_load_format: { 6883 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6884 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6885 unsigned IdxEn = 1; 6886 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6887 IdxEn = Idx->getZExtValue() != 0; 6888 SDValue Ops[] = { 6889 Op.getOperand(0), // Chain 6890 Op.getOperand(2), // rsrc 6891 Op.getOperand(3), // vindex 6892 SDValue(), // voffset -- will be set by setBufferOffsets 6893 SDValue(), // soffset -- will be set by setBufferOffsets 6894 SDValue(), // offset -- will be set by setBufferOffsets 6895 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6896 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6897 }; 6898 6899 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6900 // We don't know the offset if vindex is non-zero, so clear it. 6901 if (IdxEn) 6902 Offset = 0; 6903 6904 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6905 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6906 6907 EVT VT = Op.getValueType(); 6908 EVT IntVT = VT.changeTypeToInteger(); 6909 auto *M = cast<MemSDNode>(Op); 6910 M->getMemOperand()->setOffset(Offset); 6911 EVT LoadVT = Op.getValueType(); 6912 6913 if (LoadVT.getScalarType() == MVT::f16) 6914 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6915 M, DAG, Ops); 6916 6917 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6918 if (LoadVT.getScalarType() == MVT::i8 || 6919 LoadVT.getScalarType() == MVT::i16) 6920 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6921 6922 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6923 M->getMemOperand(), DAG); 6924 } 6925 case Intrinsic::amdgcn_raw_buffer_load: 6926 case Intrinsic::amdgcn_raw_buffer_load_format: { 6927 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6928 6929 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6930 SDValue Ops[] = { 6931 Op.getOperand(0), // Chain 6932 Op.getOperand(2), // rsrc 6933 DAG.getConstant(0, DL, MVT::i32), // vindex 6934 Offsets.first, // voffset 6935 Op.getOperand(4), // soffset 6936 Offsets.second, // offset 6937 Op.getOperand(5), // cachepolicy, swizzled buffer 6938 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6939 }; 6940 6941 auto *M = cast<MemSDNode>(Op); 6942 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6943 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6944 } 6945 case Intrinsic::amdgcn_struct_buffer_load: 6946 case Intrinsic::amdgcn_struct_buffer_load_format: { 6947 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6948 6949 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6950 SDValue Ops[] = { 6951 Op.getOperand(0), // Chain 6952 Op.getOperand(2), // rsrc 6953 Op.getOperand(3), // vindex 6954 Offsets.first, // voffset 6955 Op.getOperand(5), // soffset 6956 Offsets.second, // offset 6957 Op.getOperand(6), // cachepolicy, swizzled buffer 6958 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6959 }; 6960 6961 auto *M = cast<MemSDNode>(Op); 6962 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6963 Ops[2])); 6964 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6965 } 6966 case Intrinsic::amdgcn_tbuffer_load: { 6967 MemSDNode *M = cast<MemSDNode>(Op); 6968 EVT LoadVT = Op.getValueType(); 6969 6970 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6971 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6972 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6973 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6974 unsigned IdxEn = 1; 6975 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6976 IdxEn = Idx->getZExtValue() != 0; 6977 SDValue Ops[] = { 6978 Op.getOperand(0), // Chain 6979 Op.getOperand(2), // rsrc 6980 Op.getOperand(3), // vindex 6981 Op.getOperand(4), // voffset 6982 Op.getOperand(5), // soffset 6983 Op.getOperand(6), // offset 6984 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6985 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6986 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6987 }; 6988 6989 if (LoadVT.getScalarType() == MVT::f16) 6990 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6991 M, DAG, Ops); 6992 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6993 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6994 DAG); 6995 } 6996 case Intrinsic::amdgcn_raw_tbuffer_load: { 6997 MemSDNode *M = cast<MemSDNode>(Op); 6998 EVT LoadVT = Op.getValueType(); 6999 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7000 7001 SDValue Ops[] = { 7002 Op.getOperand(0), // Chain 7003 Op.getOperand(2), // rsrc 7004 DAG.getConstant(0, DL, MVT::i32), // vindex 7005 Offsets.first, // voffset 7006 Op.getOperand(4), // soffset 7007 Offsets.second, // offset 7008 Op.getOperand(5), // format 7009 Op.getOperand(6), // cachepolicy, swizzled buffer 7010 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7011 }; 7012 7013 if (LoadVT.getScalarType() == MVT::f16) 7014 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7015 M, DAG, Ops); 7016 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7017 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7018 DAG); 7019 } 7020 case Intrinsic::amdgcn_struct_tbuffer_load: { 7021 MemSDNode *M = cast<MemSDNode>(Op); 7022 EVT LoadVT = Op.getValueType(); 7023 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7024 7025 SDValue Ops[] = { 7026 Op.getOperand(0), // Chain 7027 Op.getOperand(2), // rsrc 7028 Op.getOperand(3), // vindex 7029 Offsets.first, // voffset 7030 Op.getOperand(5), // soffset 7031 Offsets.second, // offset 7032 Op.getOperand(6), // format 7033 Op.getOperand(7), // cachepolicy, swizzled buffer 7034 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7035 }; 7036 7037 if (LoadVT.getScalarType() == MVT::f16) 7038 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7039 M, DAG, Ops); 7040 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7041 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7042 DAG); 7043 } 7044 case Intrinsic::amdgcn_buffer_atomic_swap: 7045 case Intrinsic::amdgcn_buffer_atomic_add: 7046 case Intrinsic::amdgcn_buffer_atomic_sub: 7047 case Intrinsic::amdgcn_buffer_atomic_csub: 7048 case Intrinsic::amdgcn_buffer_atomic_smin: 7049 case Intrinsic::amdgcn_buffer_atomic_umin: 7050 case Intrinsic::amdgcn_buffer_atomic_smax: 7051 case Intrinsic::amdgcn_buffer_atomic_umax: 7052 case Intrinsic::amdgcn_buffer_atomic_and: 7053 case Intrinsic::amdgcn_buffer_atomic_or: 7054 case Intrinsic::amdgcn_buffer_atomic_xor: 7055 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7056 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7057 unsigned IdxEn = 1; 7058 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7059 IdxEn = Idx->getZExtValue() != 0; 7060 SDValue Ops[] = { 7061 Op.getOperand(0), // Chain 7062 Op.getOperand(2), // vdata 7063 Op.getOperand(3), // rsrc 7064 Op.getOperand(4), // vindex 7065 SDValue(), // voffset -- will be set by setBufferOffsets 7066 SDValue(), // soffset -- will be set by setBufferOffsets 7067 SDValue(), // offset -- will be set by setBufferOffsets 7068 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7069 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7070 }; 7071 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7072 // We don't know the offset if vindex is non-zero, so clear it. 7073 if (IdxEn) 7074 Offset = 0; 7075 EVT VT = Op.getValueType(); 7076 7077 auto *M = cast<MemSDNode>(Op); 7078 M->getMemOperand()->setOffset(Offset); 7079 unsigned Opcode = 0; 7080 7081 switch (IntrID) { 7082 case Intrinsic::amdgcn_buffer_atomic_swap: 7083 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7084 break; 7085 case Intrinsic::amdgcn_buffer_atomic_add: 7086 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7087 break; 7088 case Intrinsic::amdgcn_buffer_atomic_sub: 7089 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7090 break; 7091 case Intrinsic::amdgcn_buffer_atomic_csub: 7092 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7093 break; 7094 case Intrinsic::amdgcn_buffer_atomic_smin: 7095 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7096 break; 7097 case Intrinsic::amdgcn_buffer_atomic_umin: 7098 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7099 break; 7100 case Intrinsic::amdgcn_buffer_atomic_smax: 7101 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7102 break; 7103 case Intrinsic::amdgcn_buffer_atomic_umax: 7104 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7105 break; 7106 case Intrinsic::amdgcn_buffer_atomic_and: 7107 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7108 break; 7109 case Intrinsic::amdgcn_buffer_atomic_or: 7110 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7111 break; 7112 case Intrinsic::amdgcn_buffer_atomic_xor: 7113 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7114 break; 7115 case Intrinsic::amdgcn_buffer_atomic_fadd: 7116 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7117 DiagnosticInfoUnsupported 7118 NoFpRet(DAG.getMachineFunction().getFunction(), 7119 "return versions of fp atomics not supported", 7120 DL.getDebugLoc(), DS_Error); 7121 DAG.getContext()->diagnose(NoFpRet); 7122 return SDValue(); 7123 } 7124 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7125 break; 7126 default: 7127 llvm_unreachable("unhandled atomic opcode"); 7128 } 7129 7130 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7131 M->getMemOperand()); 7132 } 7133 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7134 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7135 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7136 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7137 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7138 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7139 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7140 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7141 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7142 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7143 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7144 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7145 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7146 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7147 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7148 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7149 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7150 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7151 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7152 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7153 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7154 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7155 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7156 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7157 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7158 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7159 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7160 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7161 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7162 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7163 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7164 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7165 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7166 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7167 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7168 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7169 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7170 return lowerStructBufferAtomicIntrin(Op, DAG, 7171 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7172 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7173 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7174 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7175 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7176 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7177 return lowerStructBufferAtomicIntrin(Op, DAG, 7178 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7179 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7180 return lowerStructBufferAtomicIntrin(Op, DAG, 7181 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7182 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7183 return lowerStructBufferAtomicIntrin(Op, DAG, 7184 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7185 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7186 return lowerStructBufferAtomicIntrin(Op, DAG, 7187 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7188 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7189 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7190 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7191 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7192 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7193 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7194 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7195 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7196 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7197 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7198 7199 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7200 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7201 unsigned IdxEn = 1; 7202 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7203 IdxEn = Idx->getZExtValue() != 0; 7204 SDValue Ops[] = { 7205 Op.getOperand(0), // Chain 7206 Op.getOperand(2), // src 7207 Op.getOperand(3), // cmp 7208 Op.getOperand(4), // rsrc 7209 Op.getOperand(5), // vindex 7210 SDValue(), // voffset -- will be set by setBufferOffsets 7211 SDValue(), // soffset -- will be set by setBufferOffsets 7212 SDValue(), // offset -- will be set by setBufferOffsets 7213 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7214 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7215 }; 7216 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7217 // We don't know the offset if vindex is non-zero, so clear it. 7218 if (IdxEn) 7219 Offset = 0; 7220 EVT VT = Op.getValueType(); 7221 auto *M = cast<MemSDNode>(Op); 7222 M->getMemOperand()->setOffset(Offset); 7223 7224 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7225 Op->getVTList(), Ops, VT, M->getMemOperand()); 7226 } 7227 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7228 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7229 SDValue Ops[] = { 7230 Op.getOperand(0), // Chain 7231 Op.getOperand(2), // src 7232 Op.getOperand(3), // cmp 7233 Op.getOperand(4), // rsrc 7234 DAG.getConstant(0, DL, MVT::i32), // vindex 7235 Offsets.first, // voffset 7236 Op.getOperand(6), // soffset 7237 Offsets.second, // offset 7238 Op.getOperand(7), // cachepolicy 7239 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7240 }; 7241 EVT VT = Op.getValueType(); 7242 auto *M = cast<MemSDNode>(Op); 7243 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7244 7245 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7246 Op->getVTList(), Ops, VT, M->getMemOperand()); 7247 } 7248 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7249 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7250 SDValue Ops[] = { 7251 Op.getOperand(0), // Chain 7252 Op.getOperand(2), // src 7253 Op.getOperand(3), // cmp 7254 Op.getOperand(4), // rsrc 7255 Op.getOperand(5), // vindex 7256 Offsets.first, // voffset 7257 Op.getOperand(7), // soffset 7258 Offsets.second, // offset 7259 Op.getOperand(8), // cachepolicy 7260 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7261 }; 7262 EVT VT = Op.getValueType(); 7263 auto *M = cast<MemSDNode>(Op); 7264 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7265 Ops[4])); 7266 7267 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7268 Op->getVTList(), Ops, VT, M->getMemOperand()); 7269 } 7270 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7271 SDLoc DL(Op); 7272 MemSDNode *M = cast<MemSDNode>(Op); 7273 SDValue NodePtr = M->getOperand(2); 7274 SDValue RayExtent = M->getOperand(3); 7275 SDValue RayOrigin = M->getOperand(4); 7276 SDValue RayDir = M->getOperand(5); 7277 SDValue RayInvDir = M->getOperand(6); 7278 SDValue TDescr = M->getOperand(7); 7279 7280 assert(NodePtr.getValueType() == MVT::i32 || 7281 NodePtr.getValueType() == MVT::i64); 7282 assert(RayDir.getValueType() == MVT::v4f16 || 7283 RayDir.getValueType() == MVT::v4f32); 7284 7285 bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7286 bool Is64 = NodePtr.getValueType() == MVT::i64; 7287 unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa 7288 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa 7289 : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa 7290 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa; 7291 7292 SmallVector<SDValue, 16> Ops; 7293 7294 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7295 SmallVector<SDValue, 3> Lanes; 7296 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7297 if (Lanes[0].getValueSizeInBits() == 32) { 7298 for (unsigned I = 0; I < 3; ++I) 7299 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7300 } else { 7301 if (IsAligned) { 7302 Ops.push_back( 7303 DAG.getBitcast(MVT::i32, 7304 DAG.getBuildVector(MVT::v2f16, DL, 7305 { Lanes[0], Lanes[1] }))); 7306 Ops.push_back(Lanes[2]); 7307 } else { 7308 SDValue Elt0 = Ops.pop_back_val(); 7309 Ops.push_back( 7310 DAG.getBitcast(MVT::i32, 7311 DAG.getBuildVector(MVT::v2f16, DL, 7312 { Elt0, Lanes[0] }))); 7313 Ops.push_back( 7314 DAG.getBitcast(MVT::i32, 7315 DAG.getBuildVector(MVT::v2f16, DL, 7316 { Lanes[1], Lanes[2] }))); 7317 } 7318 } 7319 }; 7320 7321 if (Is64) 7322 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7323 else 7324 Ops.push_back(NodePtr); 7325 7326 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7327 packLanes(RayOrigin, true); 7328 packLanes(RayDir, true); 7329 packLanes(RayInvDir, false); 7330 Ops.push_back(TDescr); 7331 if (IsA16) 7332 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7333 Ops.push_back(M->getChain()); 7334 7335 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7336 MachineMemOperand *MemRef = M->getMemOperand(); 7337 DAG.setNodeMemRefs(NewNode, {MemRef}); 7338 return SDValue(NewNode, 0); 7339 } 7340 case Intrinsic::amdgcn_global_atomic_fadd: 7341 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7342 DiagnosticInfoUnsupported 7343 NoFpRet(DAG.getMachineFunction().getFunction(), 7344 "return versions of fp atomics not supported", 7345 DL.getDebugLoc(), DS_Error); 7346 DAG.getContext()->diagnose(NoFpRet); 7347 return SDValue(); 7348 } 7349 LLVM_FALLTHROUGH; 7350 case Intrinsic::amdgcn_global_atomic_fmin: 7351 case Intrinsic::amdgcn_global_atomic_fmax: 7352 case Intrinsic::amdgcn_flat_atomic_fadd: 7353 case Intrinsic::amdgcn_flat_atomic_fmin: 7354 case Intrinsic::amdgcn_flat_atomic_fmax: { 7355 MemSDNode *M = cast<MemSDNode>(Op); 7356 SDValue Ops[] = { 7357 M->getOperand(0), // Chain 7358 M->getOperand(2), // Ptr 7359 M->getOperand(3) // Value 7360 }; 7361 unsigned Opcode = 0; 7362 switch (IntrID) { 7363 case Intrinsic::amdgcn_global_atomic_fadd: 7364 case Intrinsic::amdgcn_flat_atomic_fadd: { 7365 EVT VT = Op.getOperand(3).getValueType(); 7366 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7367 DAG.getVTList(VT, MVT::Other), Ops, 7368 M->getMemOperand()); 7369 } 7370 case Intrinsic::amdgcn_global_atomic_fmin: 7371 case Intrinsic::amdgcn_flat_atomic_fmin: { 7372 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7373 break; 7374 } 7375 case Intrinsic::amdgcn_global_atomic_fmax: 7376 case Intrinsic::amdgcn_flat_atomic_fmax: { 7377 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7378 break; 7379 } 7380 default: 7381 llvm_unreachable("unhandled atomic opcode"); 7382 } 7383 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7384 M->getVTList(), Ops, M->getMemoryVT(), 7385 M->getMemOperand()); 7386 } 7387 default: 7388 7389 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7390 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7391 return lowerImage(Op, ImageDimIntr, DAG, true); 7392 7393 return SDValue(); 7394 } 7395 } 7396 7397 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7398 // dwordx4 if on SI. 7399 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7400 SDVTList VTList, 7401 ArrayRef<SDValue> Ops, EVT MemVT, 7402 MachineMemOperand *MMO, 7403 SelectionDAG &DAG) const { 7404 EVT VT = VTList.VTs[0]; 7405 EVT WidenedVT = VT; 7406 EVT WidenedMemVT = MemVT; 7407 if (!Subtarget->hasDwordx3LoadStores() && 7408 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7409 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7410 WidenedVT.getVectorElementType(), 4); 7411 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7412 WidenedMemVT.getVectorElementType(), 4); 7413 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7414 } 7415 7416 assert(VTList.NumVTs == 2); 7417 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7418 7419 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7420 WidenedMemVT, MMO); 7421 if (WidenedVT != VT) { 7422 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7423 DAG.getVectorIdxConstant(0, DL)); 7424 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7425 } 7426 return NewOp; 7427 } 7428 7429 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7430 bool ImageStore) const { 7431 EVT StoreVT = VData.getValueType(); 7432 7433 // No change for f16 and legal vector D16 types. 7434 if (!StoreVT.isVector()) 7435 return VData; 7436 7437 SDLoc DL(VData); 7438 unsigned NumElements = StoreVT.getVectorNumElements(); 7439 7440 if (Subtarget->hasUnpackedD16VMem()) { 7441 // We need to unpack the packed data to store. 7442 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7443 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7444 7445 EVT EquivStoreVT = 7446 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7447 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7448 return DAG.UnrollVectorOp(ZExt.getNode()); 7449 } 7450 7451 // The sq block of gfx8.1 does not estimate register use correctly for d16 7452 // image store instructions. The data operand is computed as if it were not a 7453 // d16 image instruction. 7454 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7455 // Bitcast to i16 7456 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7457 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7458 7459 // Decompose into scalars 7460 SmallVector<SDValue, 4> Elts; 7461 DAG.ExtractVectorElements(IntVData, Elts); 7462 7463 // Group pairs of i16 into v2i16 and bitcast to i32 7464 SmallVector<SDValue, 4> PackedElts; 7465 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7466 SDValue Pair = 7467 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7468 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7469 PackedElts.push_back(IntPair); 7470 } 7471 if ((NumElements % 2) == 1) { 7472 // Handle v3i16 7473 unsigned I = Elts.size() / 2; 7474 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7475 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7476 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7477 PackedElts.push_back(IntPair); 7478 } 7479 7480 // Pad using UNDEF 7481 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7482 7483 // Build final vector 7484 EVT VecVT = 7485 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7486 return DAG.getBuildVector(VecVT, DL, PackedElts); 7487 } 7488 7489 if (NumElements == 3) { 7490 EVT IntStoreVT = 7491 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7492 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7493 7494 EVT WidenedStoreVT = EVT::getVectorVT( 7495 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7496 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7497 WidenedStoreVT.getStoreSizeInBits()); 7498 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7499 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7500 } 7501 7502 assert(isTypeLegal(StoreVT)); 7503 return VData; 7504 } 7505 7506 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7507 SelectionDAG &DAG) const { 7508 SDLoc DL(Op); 7509 SDValue Chain = Op.getOperand(0); 7510 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7511 MachineFunction &MF = DAG.getMachineFunction(); 7512 7513 switch (IntrinsicID) { 7514 case Intrinsic::amdgcn_exp_compr: { 7515 SDValue Src0 = Op.getOperand(4); 7516 SDValue Src1 = Op.getOperand(5); 7517 // Hack around illegal type on SI by directly selecting it. 7518 if (isTypeLegal(Src0.getValueType())) 7519 return SDValue(); 7520 7521 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7522 SDValue Undef = DAG.getUNDEF(MVT::f32); 7523 const SDValue Ops[] = { 7524 Op.getOperand(2), // tgt 7525 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7526 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7527 Undef, // src2 7528 Undef, // src3 7529 Op.getOperand(7), // vm 7530 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7531 Op.getOperand(3), // en 7532 Op.getOperand(0) // Chain 7533 }; 7534 7535 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7536 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7537 } 7538 case Intrinsic::amdgcn_s_barrier: { 7539 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7540 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7541 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7542 if (WGSize <= ST.getWavefrontSize()) 7543 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7544 Op.getOperand(0)), 0); 7545 } 7546 return SDValue(); 7547 }; 7548 case Intrinsic::amdgcn_tbuffer_store: { 7549 SDValue VData = Op.getOperand(2); 7550 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7551 if (IsD16) 7552 VData = handleD16VData(VData, DAG); 7553 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7554 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7555 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7556 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7557 unsigned IdxEn = 1; 7558 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7559 IdxEn = Idx->getZExtValue() != 0; 7560 SDValue Ops[] = { 7561 Chain, 7562 VData, // vdata 7563 Op.getOperand(3), // rsrc 7564 Op.getOperand(4), // vindex 7565 Op.getOperand(5), // voffset 7566 Op.getOperand(6), // soffset 7567 Op.getOperand(7), // offset 7568 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7569 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7570 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7571 }; 7572 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7573 AMDGPUISD::TBUFFER_STORE_FORMAT; 7574 MemSDNode *M = cast<MemSDNode>(Op); 7575 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7576 M->getMemoryVT(), M->getMemOperand()); 7577 } 7578 7579 case Intrinsic::amdgcn_struct_tbuffer_store: { 7580 SDValue VData = Op.getOperand(2); 7581 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7582 if (IsD16) 7583 VData = handleD16VData(VData, DAG); 7584 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7585 SDValue Ops[] = { 7586 Chain, 7587 VData, // vdata 7588 Op.getOperand(3), // rsrc 7589 Op.getOperand(4), // vindex 7590 Offsets.first, // voffset 7591 Op.getOperand(6), // soffset 7592 Offsets.second, // offset 7593 Op.getOperand(7), // format 7594 Op.getOperand(8), // cachepolicy, swizzled buffer 7595 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7596 }; 7597 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7598 AMDGPUISD::TBUFFER_STORE_FORMAT; 7599 MemSDNode *M = cast<MemSDNode>(Op); 7600 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7601 M->getMemoryVT(), M->getMemOperand()); 7602 } 7603 7604 case Intrinsic::amdgcn_raw_tbuffer_store: { 7605 SDValue VData = Op.getOperand(2); 7606 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7607 if (IsD16) 7608 VData = handleD16VData(VData, DAG); 7609 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7610 SDValue Ops[] = { 7611 Chain, 7612 VData, // vdata 7613 Op.getOperand(3), // rsrc 7614 DAG.getConstant(0, DL, MVT::i32), // vindex 7615 Offsets.first, // voffset 7616 Op.getOperand(5), // soffset 7617 Offsets.second, // offset 7618 Op.getOperand(6), // format 7619 Op.getOperand(7), // cachepolicy, swizzled buffer 7620 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7621 }; 7622 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7623 AMDGPUISD::TBUFFER_STORE_FORMAT; 7624 MemSDNode *M = cast<MemSDNode>(Op); 7625 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7626 M->getMemoryVT(), M->getMemOperand()); 7627 } 7628 7629 case Intrinsic::amdgcn_buffer_store: 7630 case Intrinsic::amdgcn_buffer_store_format: { 7631 SDValue VData = Op.getOperand(2); 7632 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7633 if (IsD16) 7634 VData = handleD16VData(VData, DAG); 7635 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7636 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7637 unsigned IdxEn = 1; 7638 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7639 IdxEn = Idx->getZExtValue() != 0; 7640 SDValue Ops[] = { 7641 Chain, 7642 VData, 7643 Op.getOperand(3), // rsrc 7644 Op.getOperand(4), // vindex 7645 SDValue(), // voffset -- will be set by setBufferOffsets 7646 SDValue(), // soffset -- will be set by setBufferOffsets 7647 SDValue(), // offset -- will be set by setBufferOffsets 7648 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7649 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7650 }; 7651 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7652 // We don't know the offset if vindex is non-zero, so clear it. 7653 if (IdxEn) 7654 Offset = 0; 7655 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7656 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7657 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7658 MemSDNode *M = cast<MemSDNode>(Op); 7659 M->getMemOperand()->setOffset(Offset); 7660 7661 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7662 EVT VDataType = VData.getValueType().getScalarType(); 7663 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7664 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7665 7666 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7667 M->getMemoryVT(), M->getMemOperand()); 7668 } 7669 7670 case Intrinsic::amdgcn_raw_buffer_store: 7671 case Intrinsic::amdgcn_raw_buffer_store_format: { 7672 const bool IsFormat = 7673 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7674 7675 SDValue VData = Op.getOperand(2); 7676 EVT VDataVT = VData.getValueType(); 7677 EVT EltType = VDataVT.getScalarType(); 7678 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7679 if (IsD16) { 7680 VData = handleD16VData(VData, DAG); 7681 VDataVT = VData.getValueType(); 7682 } 7683 7684 if (!isTypeLegal(VDataVT)) { 7685 VData = 7686 DAG.getNode(ISD::BITCAST, DL, 7687 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7688 } 7689 7690 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7691 SDValue Ops[] = { 7692 Chain, 7693 VData, 7694 Op.getOperand(3), // rsrc 7695 DAG.getConstant(0, DL, MVT::i32), // vindex 7696 Offsets.first, // voffset 7697 Op.getOperand(5), // soffset 7698 Offsets.second, // offset 7699 Op.getOperand(6), // cachepolicy, swizzled buffer 7700 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7701 }; 7702 unsigned Opc = 7703 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7704 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7705 MemSDNode *M = cast<MemSDNode>(Op); 7706 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7707 7708 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7709 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7710 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7711 7712 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7713 M->getMemoryVT(), M->getMemOperand()); 7714 } 7715 7716 case Intrinsic::amdgcn_struct_buffer_store: 7717 case Intrinsic::amdgcn_struct_buffer_store_format: { 7718 const bool IsFormat = 7719 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7720 7721 SDValue VData = Op.getOperand(2); 7722 EVT VDataVT = VData.getValueType(); 7723 EVT EltType = VDataVT.getScalarType(); 7724 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7725 7726 if (IsD16) { 7727 VData = handleD16VData(VData, DAG); 7728 VDataVT = VData.getValueType(); 7729 } 7730 7731 if (!isTypeLegal(VDataVT)) { 7732 VData = 7733 DAG.getNode(ISD::BITCAST, DL, 7734 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7735 } 7736 7737 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7738 SDValue Ops[] = { 7739 Chain, 7740 VData, 7741 Op.getOperand(3), // rsrc 7742 Op.getOperand(4), // vindex 7743 Offsets.first, // voffset 7744 Op.getOperand(6), // soffset 7745 Offsets.second, // offset 7746 Op.getOperand(7), // cachepolicy, swizzled buffer 7747 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7748 }; 7749 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7750 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7751 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7752 MemSDNode *M = cast<MemSDNode>(Op); 7753 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7754 Ops[3])); 7755 7756 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7757 EVT VDataType = VData.getValueType().getScalarType(); 7758 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7759 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7760 7761 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7762 M->getMemoryVT(), M->getMemOperand()); 7763 } 7764 case Intrinsic::amdgcn_end_cf: 7765 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7766 Op->getOperand(2), Chain), 0); 7767 7768 default: { 7769 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7770 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7771 return lowerImage(Op, ImageDimIntr, DAG, true); 7772 7773 return Op; 7774 } 7775 } 7776 } 7777 7778 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7779 // offset (the offset that is included in bounds checking and swizzling, to be 7780 // split between the instruction's voffset and immoffset fields) and soffset 7781 // (the offset that is excluded from bounds checking and swizzling, to go in 7782 // the instruction's soffset field). This function takes the first kind of 7783 // offset and figures out how to split it between voffset and immoffset. 7784 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7785 SDValue Offset, SelectionDAG &DAG) const { 7786 SDLoc DL(Offset); 7787 const unsigned MaxImm = 4095; 7788 SDValue N0 = Offset; 7789 ConstantSDNode *C1 = nullptr; 7790 7791 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7792 N0 = SDValue(); 7793 else if (DAG.isBaseWithConstantOffset(N0)) { 7794 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7795 N0 = N0.getOperand(0); 7796 } 7797 7798 if (C1) { 7799 unsigned ImmOffset = C1->getZExtValue(); 7800 // If the immediate value is too big for the immoffset field, put the value 7801 // and -4096 into the immoffset field so that the value that is copied/added 7802 // for the voffset field is a multiple of 4096, and it stands more chance 7803 // of being CSEd with the copy/add for another similar load/store. 7804 // However, do not do that rounding down to a multiple of 4096 if that is a 7805 // negative number, as it appears to be illegal to have a negative offset 7806 // in the vgpr, even if adding the immediate offset makes it positive. 7807 unsigned Overflow = ImmOffset & ~MaxImm; 7808 ImmOffset -= Overflow; 7809 if ((int32_t)Overflow < 0) { 7810 Overflow += ImmOffset; 7811 ImmOffset = 0; 7812 } 7813 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7814 if (Overflow) { 7815 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7816 if (!N0) 7817 N0 = OverflowVal; 7818 else { 7819 SDValue Ops[] = { N0, OverflowVal }; 7820 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7821 } 7822 } 7823 } 7824 if (!N0) 7825 N0 = DAG.getConstant(0, DL, MVT::i32); 7826 if (!C1) 7827 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7828 return {N0, SDValue(C1, 0)}; 7829 } 7830 7831 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7832 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7833 // pointed to by Offsets. 7834 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7835 SelectionDAG &DAG, SDValue *Offsets, 7836 Align Alignment) const { 7837 SDLoc DL(CombinedOffset); 7838 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7839 uint32_t Imm = C->getZExtValue(); 7840 uint32_t SOffset, ImmOffset; 7841 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7842 Alignment)) { 7843 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7844 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7845 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7846 return SOffset + ImmOffset; 7847 } 7848 } 7849 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7850 SDValue N0 = CombinedOffset.getOperand(0); 7851 SDValue N1 = CombinedOffset.getOperand(1); 7852 uint32_t SOffset, ImmOffset; 7853 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7854 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7855 Subtarget, Alignment)) { 7856 Offsets[0] = N0; 7857 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7858 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7859 return 0; 7860 } 7861 } 7862 Offsets[0] = CombinedOffset; 7863 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7864 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7865 return 0; 7866 } 7867 7868 // Handle 8 bit and 16 bit buffer loads 7869 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7870 EVT LoadVT, SDLoc DL, 7871 ArrayRef<SDValue> Ops, 7872 MemSDNode *M) const { 7873 EVT IntVT = LoadVT.changeTypeToInteger(); 7874 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7875 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7876 7877 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7878 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7879 Ops, IntVT, 7880 M->getMemOperand()); 7881 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7882 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7883 7884 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7885 } 7886 7887 // Handle 8 bit and 16 bit buffer stores 7888 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7889 EVT VDataType, SDLoc DL, 7890 SDValue Ops[], 7891 MemSDNode *M) const { 7892 if (VDataType == MVT::f16) 7893 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7894 7895 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7896 Ops[1] = BufferStoreExt; 7897 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7898 AMDGPUISD::BUFFER_STORE_SHORT; 7899 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7900 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7901 M->getMemOperand()); 7902 } 7903 7904 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7905 ISD::LoadExtType ExtType, SDValue Op, 7906 const SDLoc &SL, EVT VT) { 7907 if (VT.bitsLT(Op.getValueType())) 7908 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7909 7910 switch (ExtType) { 7911 case ISD::SEXTLOAD: 7912 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7913 case ISD::ZEXTLOAD: 7914 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7915 case ISD::EXTLOAD: 7916 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7917 case ISD::NON_EXTLOAD: 7918 return Op; 7919 } 7920 7921 llvm_unreachable("invalid ext type"); 7922 } 7923 7924 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7925 SelectionDAG &DAG = DCI.DAG; 7926 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7927 return SDValue(); 7928 7929 // FIXME: Constant loads should all be marked invariant. 7930 unsigned AS = Ld->getAddressSpace(); 7931 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7932 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7933 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7934 return SDValue(); 7935 7936 // Don't do this early, since it may interfere with adjacent load merging for 7937 // illegal types. We can avoid losing alignment information for exotic types 7938 // pre-legalize. 7939 EVT MemVT = Ld->getMemoryVT(); 7940 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7941 MemVT.getSizeInBits() >= 32) 7942 return SDValue(); 7943 7944 SDLoc SL(Ld); 7945 7946 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7947 "unexpected vector extload"); 7948 7949 // TODO: Drop only high part of range. 7950 SDValue Ptr = Ld->getBasePtr(); 7951 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7952 MVT::i32, SL, Ld->getChain(), Ptr, 7953 Ld->getOffset(), 7954 Ld->getPointerInfo(), MVT::i32, 7955 Ld->getAlignment(), 7956 Ld->getMemOperand()->getFlags(), 7957 Ld->getAAInfo(), 7958 nullptr); // Drop ranges 7959 7960 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7961 if (MemVT.isFloatingPoint()) { 7962 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7963 "unexpected fp extload"); 7964 TruncVT = MemVT.changeTypeToInteger(); 7965 } 7966 7967 SDValue Cvt = NewLoad; 7968 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7969 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7970 DAG.getValueType(TruncVT)); 7971 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7972 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7973 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7974 } else { 7975 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7976 } 7977 7978 EVT VT = Ld->getValueType(0); 7979 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7980 7981 DCI.AddToWorklist(Cvt.getNode()); 7982 7983 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7984 // the appropriate extension from the 32-bit load. 7985 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7986 DCI.AddToWorklist(Cvt.getNode()); 7987 7988 // Handle conversion back to floating point if necessary. 7989 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7990 7991 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7992 } 7993 7994 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7995 SDLoc DL(Op); 7996 LoadSDNode *Load = cast<LoadSDNode>(Op); 7997 ISD::LoadExtType ExtType = Load->getExtensionType(); 7998 EVT MemVT = Load->getMemoryVT(); 7999 8000 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8001 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8002 return SDValue(); 8003 8004 // FIXME: Copied from PPC 8005 // First, load into 32 bits, then truncate to 1 bit. 8006 8007 SDValue Chain = Load->getChain(); 8008 SDValue BasePtr = Load->getBasePtr(); 8009 MachineMemOperand *MMO = Load->getMemOperand(); 8010 8011 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8012 8013 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8014 BasePtr, RealMemVT, MMO); 8015 8016 if (!MemVT.isVector()) { 8017 SDValue Ops[] = { 8018 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8019 NewLD.getValue(1) 8020 }; 8021 8022 return DAG.getMergeValues(Ops, DL); 8023 } 8024 8025 SmallVector<SDValue, 3> Elts; 8026 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8027 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8028 DAG.getConstant(I, DL, MVT::i32)); 8029 8030 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8031 } 8032 8033 SDValue Ops[] = { 8034 DAG.getBuildVector(MemVT, DL, Elts), 8035 NewLD.getValue(1) 8036 }; 8037 8038 return DAG.getMergeValues(Ops, DL); 8039 } 8040 8041 if (!MemVT.isVector()) 8042 return SDValue(); 8043 8044 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8045 "Custom lowering for non-i32 vectors hasn't been implemented."); 8046 8047 unsigned Alignment = Load->getAlignment(); 8048 unsigned AS = Load->getAddressSpace(); 8049 if (Subtarget->hasLDSMisalignedBug() && 8050 AS == AMDGPUAS::FLAT_ADDRESS && 8051 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8052 return SplitVectorLoad(Op, DAG); 8053 } 8054 8055 MachineFunction &MF = DAG.getMachineFunction(); 8056 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8057 // If there is a possibilty that flat instruction access scratch memory 8058 // then we need to use the same legalization rules we use for private. 8059 if (AS == AMDGPUAS::FLAT_ADDRESS && 8060 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8061 AS = MFI->hasFlatScratchInit() ? 8062 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8063 8064 unsigned NumElements = MemVT.getVectorNumElements(); 8065 8066 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8067 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8068 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8069 if (MemVT.isPow2VectorType()) 8070 return SDValue(); 8071 return WidenOrSplitVectorLoad(Op, DAG); 8072 } 8073 // Non-uniform loads will be selected to MUBUF instructions, so they 8074 // have the same legalization requirements as global and private 8075 // loads. 8076 // 8077 } 8078 8079 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8080 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8081 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8082 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8083 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8084 Alignment >= 4 && NumElements < 32) { 8085 if (MemVT.isPow2VectorType()) 8086 return SDValue(); 8087 return WidenOrSplitVectorLoad(Op, DAG); 8088 } 8089 // Non-uniform loads will be selected to MUBUF instructions, so they 8090 // have the same legalization requirements as global and private 8091 // loads. 8092 // 8093 } 8094 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8095 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8096 AS == AMDGPUAS::GLOBAL_ADDRESS || 8097 AS == AMDGPUAS::FLAT_ADDRESS) { 8098 if (NumElements > 4) 8099 return SplitVectorLoad(Op, DAG); 8100 // v3 loads not supported on SI. 8101 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8102 return WidenOrSplitVectorLoad(Op, DAG); 8103 8104 // v3 and v4 loads are supported for private and global memory. 8105 return SDValue(); 8106 } 8107 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8108 // Depending on the setting of the private_element_size field in the 8109 // resource descriptor, we can only make private accesses up to a certain 8110 // size. 8111 switch (Subtarget->getMaxPrivateElementSize()) { 8112 case 4: { 8113 SDValue Ops[2]; 8114 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8115 return DAG.getMergeValues(Ops, DL); 8116 } 8117 case 8: 8118 if (NumElements > 2) 8119 return SplitVectorLoad(Op, DAG); 8120 return SDValue(); 8121 case 16: 8122 // Same as global/flat 8123 if (NumElements > 4) 8124 return SplitVectorLoad(Op, DAG); 8125 // v3 loads not supported on SI. 8126 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8127 return WidenOrSplitVectorLoad(Op, DAG); 8128 8129 return SDValue(); 8130 default: 8131 llvm_unreachable("unsupported private_element_size"); 8132 } 8133 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8134 // Use ds_read_b128 or ds_read_b96 when possible. 8135 if (Subtarget->hasDS96AndDS128() && 8136 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8137 MemVT.getStoreSize() == 12) && 8138 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8139 Load->getAlign())) 8140 return SDValue(); 8141 8142 if (NumElements > 2) 8143 return SplitVectorLoad(Op, DAG); 8144 8145 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8146 // address is negative, then the instruction is incorrectly treated as 8147 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8148 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8149 // load later in the SILoadStoreOptimizer. 8150 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8151 NumElements == 2 && MemVT.getStoreSize() == 8 && 8152 Load->getAlignment() < 8) { 8153 return SplitVectorLoad(Op, DAG); 8154 } 8155 } 8156 8157 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8158 MemVT, *Load->getMemOperand())) { 8159 SDValue Ops[2]; 8160 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8161 return DAG.getMergeValues(Ops, DL); 8162 } 8163 8164 return SDValue(); 8165 } 8166 8167 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8168 EVT VT = Op.getValueType(); 8169 assert(VT.getSizeInBits() == 64); 8170 8171 SDLoc DL(Op); 8172 SDValue Cond = Op.getOperand(0); 8173 8174 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8175 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8176 8177 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8178 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8179 8180 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8181 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8182 8183 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8184 8185 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8186 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8187 8188 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8189 8190 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8191 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8192 } 8193 8194 // Catch division cases where we can use shortcuts with rcp and rsq 8195 // instructions. 8196 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8197 SelectionDAG &DAG) const { 8198 SDLoc SL(Op); 8199 SDValue LHS = Op.getOperand(0); 8200 SDValue RHS = Op.getOperand(1); 8201 EVT VT = Op.getValueType(); 8202 const SDNodeFlags Flags = Op->getFlags(); 8203 8204 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8205 8206 // Without !fpmath accuracy information, we can't do more because we don't 8207 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8208 if (!AllowInaccurateRcp) 8209 return SDValue(); 8210 8211 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8212 if (CLHS->isExactlyValue(1.0)) { 8213 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8214 // the CI documentation has a worst case error of 1 ulp. 8215 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8216 // use it as long as we aren't trying to use denormals. 8217 // 8218 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8219 8220 // 1.0 / sqrt(x) -> rsq(x) 8221 8222 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8223 // error seems really high at 2^29 ULP. 8224 if (RHS.getOpcode() == ISD::FSQRT) 8225 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8226 8227 // 1.0 / x -> rcp(x) 8228 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8229 } 8230 8231 // Same as for 1.0, but expand the sign out of the constant. 8232 if (CLHS->isExactlyValue(-1.0)) { 8233 // -1.0 / x -> rcp (fneg x) 8234 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8235 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8236 } 8237 } 8238 8239 // Turn into multiply by the reciprocal. 8240 // x / y -> x * (1.0 / y) 8241 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8242 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8243 } 8244 8245 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8246 SelectionDAG &DAG) const { 8247 SDLoc SL(Op); 8248 SDValue X = Op.getOperand(0); 8249 SDValue Y = Op.getOperand(1); 8250 EVT VT = Op.getValueType(); 8251 const SDNodeFlags Flags = Op->getFlags(); 8252 8253 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8254 DAG.getTarget().Options.UnsafeFPMath; 8255 if (!AllowInaccurateDiv) 8256 return SDValue(); 8257 8258 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8259 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8260 8261 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8262 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8263 8264 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8265 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8266 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8267 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8268 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8269 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8270 } 8271 8272 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8273 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8274 SDNodeFlags Flags) { 8275 if (GlueChain->getNumValues() <= 1) { 8276 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8277 } 8278 8279 assert(GlueChain->getNumValues() == 3); 8280 8281 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8282 switch (Opcode) { 8283 default: llvm_unreachable("no chain equivalent for opcode"); 8284 case ISD::FMUL: 8285 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8286 break; 8287 } 8288 8289 return DAG.getNode(Opcode, SL, VTList, 8290 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8291 Flags); 8292 } 8293 8294 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8295 EVT VT, SDValue A, SDValue B, SDValue C, 8296 SDValue GlueChain, SDNodeFlags Flags) { 8297 if (GlueChain->getNumValues() <= 1) { 8298 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8299 } 8300 8301 assert(GlueChain->getNumValues() == 3); 8302 8303 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8304 switch (Opcode) { 8305 default: llvm_unreachable("no chain equivalent for opcode"); 8306 case ISD::FMA: 8307 Opcode = AMDGPUISD::FMA_W_CHAIN; 8308 break; 8309 } 8310 8311 return DAG.getNode(Opcode, SL, VTList, 8312 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8313 Flags); 8314 } 8315 8316 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8317 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8318 return FastLowered; 8319 8320 SDLoc SL(Op); 8321 SDValue Src0 = Op.getOperand(0); 8322 SDValue Src1 = Op.getOperand(1); 8323 8324 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8325 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8326 8327 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8328 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8329 8330 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8331 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8332 8333 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8334 } 8335 8336 // Faster 2.5 ULP division that does not support denormals. 8337 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8338 SDLoc SL(Op); 8339 SDValue LHS = Op.getOperand(1); 8340 SDValue RHS = Op.getOperand(2); 8341 8342 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8343 8344 const APFloat K0Val(BitsToFloat(0x6f800000)); 8345 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8346 8347 const APFloat K1Val(BitsToFloat(0x2f800000)); 8348 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8349 8350 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8351 8352 EVT SetCCVT = 8353 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8354 8355 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8356 8357 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8358 8359 // TODO: Should this propagate fast-math-flags? 8360 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8361 8362 // rcp does not support denormals. 8363 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8364 8365 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8366 8367 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8368 } 8369 8370 // Returns immediate value for setting the F32 denorm mode when using the 8371 // S_DENORM_MODE instruction. 8372 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8373 const SDLoc &SL, const GCNSubtarget *ST) { 8374 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8375 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8376 ? FP_DENORM_FLUSH_NONE 8377 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8378 8379 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8380 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8381 } 8382 8383 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8384 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8385 return FastLowered; 8386 8387 // The selection matcher assumes anything with a chain selecting to a 8388 // mayRaiseFPException machine instruction. Since we're introducing a chain 8389 // here, we need to explicitly report nofpexcept for the regular fdiv 8390 // lowering. 8391 SDNodeFlags Flags = Op->getFlags(); 8392 Flags.setNoFPExcept(true); 8393 8394 SDLoc SL(Op); 8395 SDValue LHS = Op.getOperand(0); 8396 SDValue RHS = Op.getOperand(1); 8397 8398 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8399 8400 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8401 8402 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8403 {RHS, RHS, LHS}, Flags); 8404 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8405 {LHS, RHS, LHS}, Flags); 8406 8407 // Denominator is scaled to not be denormal, so using rcp is ok. 8408 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8409 DenominatorScaled, Flags); 8410 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8411 DenominatorScaled, Flags); 8412 8413 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8414 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8415 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8416 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8417 8418 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8419 8420 if (!HasFP32Denormals) { 8421 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8422 // lowering. The chain dependence is insufficient, and we need glue. We do 8423 // not need the glue variants in a strictfp function. 8424 8425 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8426 8427 SDNode *EnableDenorm; 8428 if (Subtarget->hasDenormModeInst()) { 8429 const SDValue EnableDenormValue = 8430 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8431 8432 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8433 DAG.getEntryNode(), EnableDenormValue).getNode(); 8434 } else { 8435 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8436 SL, MVT::i32); 8437 EnableDenorm = 8438 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8439 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8440 } 8441 8442 SDValue Ops[3] = { 8443 NegDivScale0, 8444 SDValue(EnableDenorm, 0), 8445 SDValue(EnableDenorm, 1) 8446 }; 8447 8448 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8449 } 8450 8451 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8452 ApproxRcp, One, NegDivScale0, Flags); 8453 8454 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8455 ApproxRcp, Fma0, Flags); 8456 8457 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8458 Fma1, Fma1, Flags); 8459 8460 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8461 NumeratorScaled, Mul, Flags); 8462 8463 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8464 Fma2, Fma1, Mul, Fma2, Flags); 8465 8466 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8467 NumeratorScaled, Fma3, Flags); 8468 8469 if (!HasFP32Denormals) { 8470 SDNode *DisableDenorm; 8471 if (Subtarget->hasDenormModeInst()) { 8472 const SDValue DisableDenormValue = 8473 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8474 8475 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8476 Fma4.getValue(1), DisableDenormValue, 8477 Fma4.getValue(2)).getNode(); 8478 } else { 8479 const SDValue DisableDenormValue = 8480 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8481 8482 DisableDenorm = DAG.getMachineNode( 8483 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8484 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8485 } 8486 8487 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8488 SDValue(DisableDenorm, 0), DAG.getRoot()); 8489 DAG.setRoot(OutputChain); 8490 } 8491 8492 SDValue Scale = NumeratorScaled.getValue(1); 8493 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8494 {Fma4, Fma1, Fma3, Scale}, Flags); 8495 8496 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8497 } 8498 8499 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8500 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8501 return FastLowered; 8502 8503 SDLoc SL(Op); 8504 SDValue X = Op.getOperand(0); 8505 SDValue Y = Op.getOperand(1); 8506 8507 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8508 8509 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8510 8511 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8512 8513 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8514 8515 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8516 8517 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8518 8519 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8520 8521 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8522 8523 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8524 8525 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8526 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8527 8528 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8529 NegDivScale0, Mul, DivScale1); 8530 8531 SDValue Scale; 8532 8533 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8534 // Workaround a hardware bug on SI where the condition output from div_scale 8535 // is not usable. 8536 8537 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8538 8539 // Figure out if the scale to use for div_fmas. 8540 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8541 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8542 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8543 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8544 8545 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8546 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8547 8548 SDValue Scale0Hi 8549 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8550 SDValue Scale1Hi 8551 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8552 8553 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8554 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8555 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8556 } else { 8557 Scale = DivScale1.getValue(1); 8558 } 8559 8560 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8561 Fma4, Fma3, Mul, Scale); 8562 8563 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8564 } 8565 8566 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8567 EVT VT = Op.getValueType(); 8568 8569 if (VT == MVT::f32) 8570 return LowerFDIV32(Op, DAG); 8571 8572 if (VT == MVT::f64) 8573 return LowerFDIV64(Op, DAG); 8574 8575 if (VT == MVT::f16) 8576 return LowerFDIV16(Op, DAG); 8577 8578 llvm_unreachable("Unexpected type for fdiv"); 8579 } 8580 8581 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8582 SDLoc DL(Op); 8583 StoreSDNode *Store = cast<StoreSDNode>(Op); 8584 EVT VT = Store->getMemoryVT(); 8585 8586 if (VT == MVT::i1) { 8587 return DAG.getTruncStore(Store->getChain(), DL, 8588 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8589 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8590 } 8591 8592 assert(VT.isVector() && 8593 Store->getValue().getValueType().getScalarType() == MVT::i32); 8594 8595 unsigned AS = Store->getAddressSpace(); 8596 if (Subtarget->hasLDSMisalignedBug() && 8597 AS == AMDGPUAS::FLAT_ADDRESS && 8598 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8599 return SplitVectorStore(Op, DAG); 8600 } 8601 8602 MachineFunction &MF = DAG.getMachineFunction(); 8603 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8604 // If there is a possibilty that flat instruction access scratch memory 8605 // then we need to use the same legalization rules we use for private. 8606 if (AS == AMDGPUAS::FLAT_ADDRESS && 8607 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8608 AS = MFI->hasFlatScratchInit() ? 8609 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8610 8611 unsigned NumElements = VT.getVectorNumElements(); 8612 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8613 AS == AMDGPUAS::FLAT_ADDRESS) { 8614 if (NumElements > 4) 8615 return SplitVectorStore(Op, DAG); 8616 // v3 stores not supported on SI. 8617 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8618 return SplitVectorStore(Op, DAG); 8619 8620 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8621 VT, *Store->getMemOperand())) 8622 return expandUnalignedStore(Store, DAG); 8623 8624 return SDValue(); 8625 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8626 switch (Subtarget->getMaxPrivateElementSize()) { 8627 case 4: 8628 return scalarizeVectorStore(Store, DAG); 8629 case 8: 8630 if (NumElements > 2) 8631 return SplitVectorStore(Op, DAG); 8632 return SDValue(); 8633 case 16: 8634 if (NumElements > 4 || 8635 (NumElements == 3 && !Subtarget->enableFlatScratch())) 8636 return SplitVectorStore(Op, DAG); 8637 return SDValue(); 8638 default: 8639 llvm_unreachable("unsupported private_element_size"); 8640 } 8641 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8642 // Use ds_write_b128 or ds_write_b96 when possible. 8643 if (Subtarget->hasDS96AndDS128() && 8644 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8645 (VT.getStoreSize() == 12)) && 8646 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8647 Store->getAlign())) 8648 return SDValue(); 8649 8650 if (NumElements > 2) 8651 return SplitVectorStore(Op, DAG); 8652 8653 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8654 // address is negative, then the instruction is incorrectly treated as 8655 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8656 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8657 // store later in the SILoadStoreOptimizer. 8658 if (!Subtarget->hasUsableDSOffset() && 8659 NumElements == 2 && VT.getStoreSize() == 8 && 8660 Store->getAlignment() < 8) { 8661 return SplitVectorStore(Op, DAG); 8662 } 8663 8664 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8665 VT, *Store->getMemOperand())) { 8666 if (VT.isVector()) 8667 return SplitVectorStore(Op, DAG); 8668 return expandUnalignedStore(Store, DAG); 8669 } 8670 8671 return SDValue(); 8672 } else { 8673 llvm_unreachable("unhandled address space"); 8674 } 8675 } 8676 8677 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8678 SDLoc DL(Op); 8679 EVT VT = Op.getValueType(); 8680 SDValue Arg = Op.getOperand(0); 8681 SDValue TrigVal; 8682 8683 // Propagate fast-math flags so that the multiply we introduce can be folded 8684 // if Arg is already the result of a multiply by constant. 8685 auto Flags = Op->getFlags(); 8686 8687 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8688 8689 if (Subtarget->hasTrigReducedRange()) { 8690 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8691 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8692 } else { 8693 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8694 } 8695 8696 switch (Op.getOpcode()) { 8697 case ISD::FCOS: 8698 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8699 case ISD::FSIN: 8700 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8701 default: 8702 llvm_unreachable("Wrong trig opcode"); 8703 } 8704 } 8705 8706 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8707 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8708 assert(AtomicNode->isCompareAndSwap()); 8709 unsigned AS = AtomicNode->getAddressSpace(); 8710 8711 // No custom lowering required for local address space 8712 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8713 return Op; 8714 8715 // Non-local address space requires custom lowering for atomic compare 8716 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8717 SDLoc DL(Op); 8718 SDValue ChainIn = Op.getOperand(0); 8719 SDValue Addr = Op.getOperand(1); 8720 SDValue Old = Op.getOperand(2); 8721 SDValue New = Op.getOperand(3); 8722 EVT VT = Op.getValueType(); 8723 MVT SimpleVT = VT.getSimpleVT(); 8724 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8725 8726 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8727 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8728 8729 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8730 Ops, VT, AtomicNode->getMemOperand()); 8731 } 8732 8733 //===----------------------------------------------------------------------===// 8734 // Custom DAG optimizations 8735 //===----------------------------------------------------------------------===// 8736 8737 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8738 DAGCombinerInfo &DCI) const { 8739 EVT VT = N->getValueType(0); 8740 EVT ScalarVT = VT.getScalarType(); 8741 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8742 return SDValue(); 8743 8744 SelectionDAG &DAG = DCI.DAG; 8745 SDLoc DL(N); 8746 8747 SDValue Src = N->getOperand(0); 8748 EVT SrcVT = Src.getValueType(); 8749 8750 // TODO: We could try to match extracting the higher bytes, which would be 8751 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8752 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8753 // about in practice. 8754 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8755 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8756 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8757 DCI.AddToWorklist(Cvt.getNode()); 8758 8759 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8760 if (ScalarVT != MVT::f32) { 8761 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8762 DAG.getTargetConstant(0, DL, MVT::i32)); 8763 } 8764 return Cvt; 8765 } 8766 } 8767 8768 return SDValue(); 8769 } 8770 8771 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8772 8773 // This is a variant of 8774 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8775 // 8776 // The normal DAG combiner will do this, but only if the add has one use since 8777 // that would increase the number of instructions. 8778 // 8779 // This prevents us from seeing a constant offset that can be folded into a 8780 // memory instruction's addressing mode. If we know the resulting add offset of 8781 // a pointer can be folded into an addressing offset, we can replace the pointer 8782 // operand with the add of new constant offset. This eliminates one of the uses, 8783 // and may allow the remaining use to also be simplified. 8784 // 8785 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8786 unsigned AddrSpace, 8787 EVT MemVT, 8788 DAGCombinerInfo &DCI) const { 8789 SDValue N0 = N->getOperand(0); 8790 SDValue N1 = N->getOperand(1); 8791 8792 // We only do this to handle cases where it's profitable when there are 8793 // multiple uses of the add, so defer to the standard combine. 8794 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8795 N0->hasOneUse()) 8796 return SDValue(); 8797 8798 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8799 if (!CN1) 8800 return SDValue(); 8801 8802 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8803 if (!CAdd) 8804 return SDValue(); 8805 8806 // If the resulting offset is too large, we can't fold it into the addressing 8807 // mode offset. 8808 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8809 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8810 8811 AddrMode AM; 8812 AM.HasBaseReg = true; 8813 AM.BaseOffs = Offset.getSExtValue(); 8814 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8815 return SDValue(); 8816 8817 SelectionDAG &DAG = DCI.DAG; 8818 SDLoc SL(N); 8819 EVT VT = N->getValueType(0); 8820 8821 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8822 SDValue COffset = DAG.getConstant(Offset, SL, VT); 8823 8824 SDNodeFlags Flags; 8825 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8826 (N0.getOpcode() == ISD::OR || 8827 N0->getFlags().hasNoUnsignedWrap())); 8828 8829 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8830 } 8831 8832 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 8833 /// by the chain and intrinsic ID. Theoretically we would also need to check the 8834 /// specific intrinsic, but they all place the pointer operand first. 8835 static unsigned getBasePtrIndex(const MemSDNode *N) { 8836 switch (N->getOpcode()) { 8837 case ISD::STORE: 8838 case ISD::INTRINSIC_W_CHAIN: 8839 case ISD::INTRINSIC_VOID: 8840 return 2; 8841 default: 8842 return 1; 8843 } 8844 } 8845 8846 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8847 DAGCombinerInfo &DCI) const { 8848 SelectionDAG &DAG = DCI.DAG; 8849 SDLoc SL(N); 8850 8851 unsigned PtrIdx = getBasePtrIndex(N); 8852 SDValue Ptr = N->getOperand(PtrIdx); 8853 8854 // TODO: We could also do this for multiplies. 8855 if (Ptr.getOpcode() == ISD::SHL) { 8856 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8857 N->getMemoryVT(), DCI); 8858 if (NewPtr) { 8859 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8860 8861 NewOps[PtrIdx] = NewPtr; 8862 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8863 } 8864 } 8865 8866 return SDValue(); 8867 } 8868 8869 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8870 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8871 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8872 (Opc == ISD::XOR && Val == 0); 8873 } 8874 8875 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8876 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8877 // integer combine opportunities since most 64-bit operations are decomposed 8878 // this way. TODO: We won't want this for SALU especially if it is an inline 8879 // immediate. 8880 SDValue SITargetLowering::splitBinaryBitConstantOp( 8881 DAGCombinerInfo &DCI, 8882 const SDLoc &SL, 8883 unsigned Opc, SDValue LHS, 8884 const ConstantSDNode *CRHS) const { 8885 uint64_t Val = CRHS->getZExtValue(); 8886 uint32_t ValLo = Lo_32(Val); 8887 uint32_t ValHi = Hi_32(Val); 8888 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8889 8890 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8891 bitOpWithConstantIsReducible(Opc, ValHi)) || 8892 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8893 // If we need to materialize a 64-bit immediate, it will be split up later 8894 // anyway. Avoid creating the harder to understand 64-bit immediate 8895 // materialization. 8896 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8897 } 8898 8899 return SDValue(); 8900 } 8901 8902 // Returns true if argument is a boolean value which is not serialized into 8903 // memory or argument and does not require v_cndmask_b32 to be deserialized. 8904 static bool isBoolSGPR(SDValue V) { 8905 if (V.getValueType() != MVT::i1) 8906 return false; 8907 switch (V.getOpcode()) { 8908 default: 8909 break; 8910 case ISD::SETCC: 8911 case AMDGPUISD::FP_CLASS: 8912 return true; 8913 case ISD::AND: 8914 case ISD::OR: 8915 case ISD::XOR: 8916 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 8917 } 8918 return false; 8919 } 8920 8921 // If a constant has all zeroes or all ones within each byte return it. 8922 // Otherwise return 0. 8923 static uint32_t getConstantPermuteMask(uint32_t C) { 8924 // 0xff for any zero byte in the mask 8925 uint32_t ZeroByteMask = 0; 8926 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8927 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8928 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8929 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8930 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8931 if ((NonZeroByteMask & C) != NonZeroByteMask) 8932 return 0; // Partial bytes selected. 8933 return C; 8934 } 8935 8936 // Check if a node selects whole bytes from its operand 0 starting at a byte 8937 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8938 // or -1 if not succeeded. 8939 // Note byte select encoding: 8940 // value 0-3 selects corresponding source byte; 8941 // value 0xc selects zero; 8942 // value 0xff selects 0xff. 8943 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8944 assert(V.getValueSizeInBits() == 32); 8945 8946 if (V.getNumOperands() != 2) 8947 return ~0; 8948 8949 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8950 if (!N1) 8951 return ~0; 8952 8953 uint32_t C = N1->getZExtValue(); 8954 8955 switch (V.getOpcode()) { 8956 default: 8957 break; 8958 case ISD::AND: 8959 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8960 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8961 } 8962 break; 8963 8964 case ISD::OR: 8965 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8966 return (0x03020100 & ~ConstMask) | ConstMask; 8967 } 8968 break; 8969 8970 case ISD::SHL: 8971 if (C % 8) 8972 return ~0; 8973 8974 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8975 8976 case ISD::SRL: 8977 if (C % 8) 8978 return ~0; 8979 8980 return uint32_t(0x0c0c0c0c03020100ull >> C); 8981 } 8982 8983 return ~0; 8984 } 8985 8986 SDValue SITargetLowering::performAndCombine(SDNode *N, 8987 DAGCombinerInfo &DCI) const { 8988 if (DCI.isBeforeLegalize()) 8989 return SDValue(); 8990 8991 SelectionDAG &DAG = DCI.DAG; 8992 EVT VT = N->getValueType(0); 8993 SDValue LHS = N->getOperand(0); 8994 SDValue RHS = N->getOperand(1); 8995 8996 8997 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8998 if (VT == MVT::i64 && CRHS) { 8999 if (SDValue Split 9000 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9001 return Split; 9002 } 9003 9004 if (CRHS && VT == MVT::i32) { 9005 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9006 // nb = number of trailing zeroes in mask 9007 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9008 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9009 uint64_t Mask = CRHS->getZExtValue(); 9010 unsigned Bits = countPopulation(Mask); 9011 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9012 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9013 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9014 unsigned Shift = CShift->getZExtValue(); 9015 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9016 unsigned Offset = NB + Shift; 9017 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9018 SDLoc SL(N); 9019 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9020 LHS->getOperand(0), 9021 DAG.getConstant(Offset, SL, MVT::i32), 9022 DAG.getConstant(Bits, SL, MVT::i32)); 9023 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9024 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9025 DAG.getValueType(NarrowVT)); 9026 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9027 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9028 return Shl; 9029 } 9030 } 9031 } 9032 9033 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9034 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9035 isa<ConstantSDNode>(LHS.getOperand(2))) { 9036 uint32_t Sel = getConstantPermuteMask(Mask); 9037 if (!Sel) 9038 return SDValue(); 9039 9040 // Select 0xc for all zero bytes 9041 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9042 SDLoc DL(N); 9043 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9044 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9045 } 9046 } 9047 9048 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9049 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9050 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9051 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9052 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9053 9054 SDValue X = LHS.getOperand(0); 9055 SDValue Y = RHS.getOperand(0); 9056 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9057 return SDValue(); 9058 9059 if (LCC == ISD::SETO) { 9060 if (X != LHS.getOperand(1)) 9061 return SDValue(); 9062 9063 if (RCC == ISD::SETUNE) { 9064 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9065 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9066 return SDValue(); 9067 9068 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9069 SIInstrFlags::N_SUBNORMAL | 9070 SIInstrFlags::N_ZERO | 9071 SIInstrFlags::P_ZERO | 9072 SIInstrFlags::P_SUBNORMAL | 9073 SIInstrFlags::P_NORMAL; 9074 9075 static_assert(((~(SIInstrFlags::S_NAN | 9076 SIInstrFlags::Q_NAN | 9077 SIInstrFlags::N_INFINITY | 9078 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9079 "mask not equal"); 9080 9081 SDLoc DL(N); 9082 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9083 X, DAG.getConstant(Mask, DL, MVT::i32)); 9084 } 9085 } 9086 } 9087 9088 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9089 std::swap(LHS, RHS); 9090 9091 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9092 RHS.hasOneUse()) { 9093 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9094 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9095 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9096 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9097 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9098 (RHS.getOperand(0) == LHS.getOperand(0) && 9099 LHS.getOperand(0) == LHS.getOperand(1))) { 9100 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9101 unsigned NewMask = LCC == ISD::SETO ? 9102 Mask->getZExtValue() & ~OrdMask : 9103 Mask->getZExtValue() & OrdMask; 9104 9105 SDLoc DL(N); 9106 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9107 DAG.getConstant(NewMask, DL, MVT::i32)); 9108 } 9109 } 9110 9111 if (VT == MVT::i32 && 9112 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9113 // and x, (sext cc from i1) => select cc, x, 0 9114 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9115 std::swap(LHS, RHS); 9116 if (isBoolSGPR(RHS.getOperand(0))) 9117 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9118 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9119 } 9120 9121 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9122 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9123 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9124 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9125 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9126 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9127 if (LHSMask != ~0u && RHSMask != ~0u) { 9128 // Canonicalize the expression in an attempt to have fewer unique masks 9129 // and therefore fewer registers used to hold the masks. 9130 if (LHSMask > RHSMask) { 9131 std::swap(LHSMask, RHSMask); 9132 std::swap(LHS, RHS); 9133 } 9134 9135 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9136 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9137 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9138 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9139 9140 // Check of we need to combine values from two sources within a byte. 9141 if (!(LHSUsedLanes & RHSUsedLanes) && 9142 // If we select high and lower word keep it for SDWA. 9143 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9144 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9145 // Each byte in each mask is either selector mask 0-3, or has higher 9146 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9147 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9148 // mask which is not 0xff wins. By anding both masks we have a correct 9149 // result except that 0x0c shall be corrected to give 0x0c only. 9150 uint32_t Mask = LHSMask & RHSMask; 9151 for (unsigned I = 0; I < 32; I += 8) { 9152 uint32_t ByteSel = 0xff << I; 9153 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9154 Mask &= (0x0c << I) & 0xffffffff; 9155 } 9156 9157 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9158 // or 0x0c. 9159 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9160 SDLoc DL(N); 9161 9162 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9163 LHS.getOperand(0), RHS.getOperand(0), 9164 DAG.getConstant(Sel, DL, MVT::i32)); 9165 } 9166 } 9167 } 9168 9169 return SDValue(); 9170 } 9171 9172 SDValue SITargetLowering::performOrCombine(SDNode *N, 9173 DAGCombinerInfo &DCI) const { 9174 SelectionDAG &DAG = DCI.DAG; 9175 SDValue LHS = N->getOperand(0); 9176 SDValue RHS = N->getOperand(1); 9177 9178 EVT VT = N->getValueType(0); 9179 if (VT == MVT::i1) { 9180 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9181 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9182 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9183 SDValue Src = LHS.getOperand(0); 9184 if (Src != RHS.getOperand(0)) 9185 return SDValue(); 9186 9187 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9188 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9189 if (!CLHS || !CRHS) 9190 return SDValue(); 9191 9192 // Only 10 bits are used. 9193 static const uint32_t MaxMask = 0x3ff; 9194 9195 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9196 SDLoc DL(N); 9197 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9198 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9199 } 9200 9201 return SDValue(); 9202 } 9203 9204 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9205 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9206 LHS.getOpcode() == AMDGPUISD::PERM && 9207 isa<ConstantSDNode>(LHS.getOperand(2))) { 9208 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9209 if (!Sel) 9210 return SDValue(); 9211 9212 Sel |= LHS.getConstantOperandVal(2); 9213 SDLoc DL(N); 9214 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9215 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9216 } 9217 9218 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9219 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9220 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9221 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9222 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9223 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9224 if (LHSMask != ~0u && RHSMask != ~0u) { 9225 // Canonicalize the expression in an attempt to have fewer unique masks 9226 // and therefore fewer registers used to hold the masks. 9227 if (LHSMask > RHSMask) { 9228 std::swap(LHSMask, RHSMask); 9229 std::swap(LHS, RHS); 9230 } 9231 9232 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9233 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9234 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9235 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9236 9237 // Check of we need to combine values from two sources within a byte. 9238 if (!(LHSUsedLanes & RHSUsedLanes) && 9239 // If we select high and lower word keep it for SDWA. 9240 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9241 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9242 // Kill zero bytes selected by other mask. Zero value is 0xc. 9243 LHSMask &= ~RHSUsedLanes; 9244 RHSMask &= ~LHSUsedLanes; 9245 // Add 4 to each active LHS lane 9246 LHSMask |= LHSUsedLanes & 0x04040404; 9247 // Combine masks 9248 uint32_t Sel = LHSMask | RHSMask; 9249 SDLoc DL(N); 9250 9251 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9252 LHS.getOperand(0), RHS.getOperand(0), 9253 DAG.getConstant(Sel, DL, MVT::i32)); 9254 } 9255 } 9256 } 9257 9258 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9259 return SDValue(); 9260 9261 // TODO: This could be a generic combine with a predicate for extracting the 9262 // high half of an integer being free. 9263 9264 // (or i64:x, (zero_extend i32:y)) -> 9265 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9266 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9267 RHS.getOpcode() != ISD::ZERO_EXTEND) 9268 std::swap(LHS, RHS); 9269 9270 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9271 SDValue ExtSrc = RHS.getOperand(0); 9272 EVT SrcVT = ExtSrc.getValueType(); 9273 if (SrcVT == MVT::i32) { 9274 SDLoc SL(N); 9275 SDValue LowLHS, HiBits; 9276 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9277 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9278 9279 DCI.AddToWorklist(LowOr.getNode()); 9280 DCI.AddToWorklist(HiBits.getNode()); 9281 9282 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9283 LowOr, HiBits); 9284 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9285 } 9286 } 9287 9288 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9289 if (CRHS) { 9290 if (SDValue Split 9291 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9292 return Split; 9293 } 9294 9295 return SDValue(); 9296 } 9297 9298 SDValue SITargetLowering::performXorCombine(SDNode *N, 9299 DAGCombinerInfo &DCI) const { 9300 EVT VT = N->getValueType(0); 9301 if (VT != MVT::i64) 9302 return SDValue(); 9303 9304 SDValue LHS = N->getOperand(0); 9305 SDValue RHS = N->getOperand(1); 9306 9307 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9308 if (CRHS) { 9309 if (SDValue Split 9310 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9311 return Split; 9312 } 9313 9314 return SDValue(); 9315 } 9316 9317 // Instructions that will be lowered with a final instruction that zeros the 9318 // high result bits. 9319 // XXX - probably only need to list legal operations. 9320 static bool fp16SrcZerosHighBits(unsigned Opc) { 9321 switch (Opc) { 9322 case ISD::FADD: 9323 case ISD::FSUB: 9324 case ISD::FMUL: 9325 case ISD::FDIV: 9326 case ISD::FREM: 9327 case ISD::FMA: 9328 case ISD::FMAD: 9329 case ISD::FCANONICALIZE: 9330 case ISD::FP_ROUND: 9331 case ISD::UINT_TO_FP: 9332 case ISD::SINT_TO_FP: 9333 case ISD::FABS: 9334 // Fabs is lowered to a bit operation, but it's an and which will clear the 9335 // high bits anyway. 9336 case ISD::FSQRT: 9337 case ISD::FSIN: 9338 case ISD::FCOS: 9339 case ISD::FPOWI: 9340 case ISD::FPOW: 9341 case ISD::FLOG: 9342 case ISD::FLOG2: 9343 case ISD::FLOG10: 9344 case ISD::FEXP: 9345 case ISD::FEXP2: 9346 case ISD::FCEIL: 9347 case ISD::FTRUNC: 9348 case ISD::FRINT: 9349 case ISD::FNEARBYINT: 9350 case ISD::FROUND: 9351 case ISD::FFLOOR: 9352 case ISD::FMINNUM: 9353 case ISD::FMAXNUM: 9354 case AMDGPUISD::FRACT: 9355 case AMDGPUISD::CLAMP: 9356 case AMDGPUISD::COS_HW: 9357 case AMDGPUISD::SIN_HW: 9358 case AMDGPUISD::FMIN3: 9359 case AMDGPUISD::FMAX3: 9360 case AMDGPUISD::FMED3: 9361 case AMDGPUISD::FMAD_FTZ: 9362 case AMDGPUISD::RCP: 9363 case AMDGPUISD::RSQ: 9364 case AMDGPUISD::RCP_IFLAG: 9365 case AMDGPUISD::LDEXP: 9366 return true; 9367 default: 9368 // fcopysign, select and others may be lowered to 32-bit bit operations 9369 // which don't zero the high bits. 9370 return false; 9371 } 9372 } 9373 9374 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9375 DAGCombinerInfo &DCI) const { 9376 if (!Subtarget->has16BitInsts() || 9377 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9378 return SDValue(); 9379 9380 EVT VT = N->getValueType(0); 9381 if (VT != MVT::i32) 9382 return SDValue(); 9383 9384 SDValue Src = N->getOperand(0); 9385 if (Src.getValueType() != MVT::i16) 9386 return SDValue(); 9387 9388 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9389 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9390 if (Src.getOpcode() == ISD::BITCAST) { 9391 SDValue BCSrc = Src.getOperand(0); 9392 if (BCSrc.getValueType() == MVT::f16 && 9393 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9394 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9395 } 9396 9397 return SDValue(); 9398 } 9399 9400 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9401 DAGCombinerInfo &DCI) 9402 const { 9403 SDValue Src = N->getOperand(0); 9404 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9405 9406 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9407 VTSign->getVT() == MVT::i8) || 9408 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9409 VTSign->getVT() == MVT::i16)) && 9410 Src.hasOneUse()) { 9411 auto *M = cast<MemSDNode>(Src); 9412 SDValue Ops[] = { 9413 Src.getOperand(0), // Chain 9414 Src.getOperand(1), // rsrc 9415 Src.getOperand(2), // vindex 9416 Src.getOperand(3), // voffset 9417 Src.getOperand(4), // soffset 9418 Src.getOperand(5), // offset 9419 Src.getOperand(6), 9420 Src.getOperand(7) 9421 }; 9422 // replace with BUFFER_LOAD_BYTE/SHORT 9423 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9424 Src.getOperand(0).getValueType()); 9425 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9426 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9427 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9428 ResList, 9429 Ops, M->getMemoryVT(), 9430 M->getMemOperand()); 9431 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9432 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9433 } 9434 return SDValue(); 9435 } 9436 9437 SDValue SITargetLowering::performClassCombine(SDNode *N, 9438 DAGCombinerInfo &DCI) const { 9439 SelectionDAG &DAG = DCI.DAG; 9440 SDValue Mask = N->getOperand(1); 9441 9442 // fp_class x, 0 -> false 9443 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9444 if (CMask->isNullValue()) 9445 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9446 } 9447 9448 if (N->getOperand(0).isUndef()) 9449 return DAG.getUNDEF(MVT::i1); 9450 9451 return SDValue(); 9452 } 9453 9454 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9455 DAGCombinerInfo &DCI) const { 9456 EVT VT = N->getValueType(0); 9457 SDValue N0 = N->getOperand(0); 9458 9459 if (N0.isUndef()) 9460 return N0; 9461 9462 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9463 N0.getOpcode() == ISD::SINT_TO_FP)) { 9464 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9465 N->getFlags()); 9466 } 9467 9468 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9469 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9470 N0.getOperand(0), N->getFlags()); 9471 } 9472 9473 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9474 } 9475 9476 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9477 unsigned MaxDepth) const { 9478 unsigned Opcode = Op.getOpcode(); 9479 if (Opcode == ISD::FCANONICALIZE) 9480 return true; 9481 9482 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9483 auto F = CFP->getValueAPF(); 9484 if (F.isNaN() && F.isSignaling()) 9485 return false; 9486 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9487 } 9488 9489 // If source is a result of another standard FP operation it is already in 9490 // canonical form. 9491 if (MaxDepth == 0) 9492 return false; 9493 9494 switch (Opcode) { 9495 // These will flush denorms if required. 9496 case ISD::FADD: 9497 case ISD::FSUB: 9498 case ISD::FMUL: 9499 case ISD::FCEIL: 9500 case ISD::FFLOOR: 9501 case ISD::FMA: 9502 case ISD::FMAD: 9503 case ISD::FSQRT: 9504 case ISD::FDIV: 9505 case ISD::FREM: 9506 case ISD::FP_ROUND: 9507 case ISD::FP_EXTEND: 9508 case AMDGPUISD::FMUL_LEGACY: 9509 case AMDGPUISD::FMAD_FTZ: 9510 case AMDGPUISD::RCP: 9511 case AMDGPUISD::RSQ: 9512 case AMDGPUISD::RSQ_CLAMP: 9513 case AMDGPUISD::RCP_LEGACY: 9514 case AMDGPUISD::RCP_IFLAG: 9515 case AMDGPUISD::DIV_SCALE: 9516 case AMDGPUISD::DIV_FMAS: 9517 case AMDGPUISD::DIV_FIXUP: 9518 case AMDGPUISD::FRACT: 9519 case AMDGPUISD::LDEXP: 9520 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9521 case AMDGPUISD::CVT_F32_UBYTE0: 9522 case AMDGPUISD::CVT_F32_UBYTE1: 9523 case AMDGPUISD::CVT_F32_UBYTE2: 9524 case AMDGPUISD::CVT_F32_UBYTE3: 9525 return true; 9526 9527 // It can/will be lowered or combined as a bit operation. 9528 // Need to check their input recursively to handle. 9529 case ISD::FNEG: 9530 case ISD::FABS: 9531 case ISD::FCOPYSIGN: 9532 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9533 9534 case ISD::FSIN: 9535 case ISD::FCOS: 9536 case ISD::FSINCOS: 9537 return Op.getValueType().getScalarType() != MVT::f16; 9538 9539 case ISD::FMINNUM: 9540 case ISD::FMAXNUM: 9541 case ISD::FMINNUM_IEEE: 9542 case ISD::FMAXNUM_IEEE: 9543 case AMDGPUISD::CLAMP: 9544 case AMDGPUISD::FMED3: 9545 case AMDGPUISD::FMAX3: 9546 case AMDGPUISD::FMIN3: { 9547 // FIXME: Shouldn't treat the generic operations different based these. 9548 // However, we aren't really required to flush the result from 9549 // minnum/maxnum.. 9550 9551 // snans will be quieted, so we only need to worry about denormals. 9552 if (Subtarget->supportsMinMaxDenormModes() || 9553 denormalsEnabledForType(DAG, Op.getValueType())) 9554 return true; 9555 9556 // Flushing may be required. 9557 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9558 // targets need to check their input recursively. 9559 9560 // FIXME: Does this apply with clamp? It's implemented with max. 9561 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9562 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9563 return false; 9564 } 9565 9566 return true; 9567 } 9568 case ISD::SELECT: { 9569 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9570 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9571 } 9572 case ISD::BUILD_VECTOR: { 9573 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9574 SDValue SrcOp = Op.getOperand(i); 9575 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9576 return false; 9577 } 9578 9579 return true; 9580 } 9581 case ISD::EXTRACT_VECTOR_ELT: 9582 case ISD::EXTRACT_SUBVECTOR: { 9583 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9584 } 9585 case ISD::INSERT_VECTOR_ELT: { 9586 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9587 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9588 } 9589 case ISD::UNDEF: 9590 // Could be anything. 9591 return false; 9592 9593 case ISD::BITCAST: { 9594 // Hack round the mess we make when legalizing extract_vector_elt 9595 SDValue Src = Op.getOperand(0); 9596 if (Src.getValueType() == MVT::i16 && 9597 Src.getOpcode() == ISD::TRUNCATE) { 9598 SDValue TruncSrc = Src.getOperand(0); 9599 if (TruncSrc.getValueType() == MVT::i32 && 9600 TruncSrc.getOpcode() == ISD::BITCAST && 9601 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9602 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9603 } 9604 } 9605 9606 return false; 9607 } 9608 case ISD::INTRINSIC_WO_CHAIN: { 9609 unsigned IntrinsicID 9610 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9611 // TODO: Handle more intrinsics 9612 switch (IntrinsicID) { 9613 case Intrinsic::amdgcn_cvt_pkrtz: 9614 case Intrinsic::amdgcn_cubeid: 9615 case Intrinsic::amdgcn_frexp_mant: 9616 case Intrinsic::amdgcn_fdot2: 9617 case Intrinsic::amdgcn_rcp: 9618 case Intrinsic::amdgcn_rsq: 9619 case Intrinsic::amdgcn_rsq_clamp: 9620 case Intrinsic::amdgcn_rcp_legacy: 9621 case Intrinsic::amdgcn_rsq_legacy: 9622 case Intrinsic::amdgcn_trig_preop: 9623 return true; 9624 default: 9625 break; 9626 } 9627 9628 LLVM_FALLTHROUGH; 9629 } 9630 default: 9631 return denormalsEnabledForType(DAG, Op.getValueType()) && 9632 DAG.isKnownNeverSNaN(Op); 9633 } 9634 9635 llvm_unreachable("invalid operation"); 9636 } 9637 9638 // Constant fold canonicalize. 9639 SDValue SITargetLowering::getCanonicalConstantFP( 9640 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9641 // Flush denormals to 0 if not enabled. 9642 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9643 return DAG.getConstantFP(0.0, SL, VT); 9644 9645 if (C.isNaN()) { 9646 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9647 if (C.isSignaling()) { 9648 // Quiet a signaling NaN. 9649 // FIXME: Is this supposed to preserve payload bits? 9650 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9651 } 9652 9653 // Make sure it is the canonical NaN bitpattern. 9654 // 9655 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9656 // immediate? 9657 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9658 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9659 } 9660 9661 // Already canonical. 9662 return DAG.getConstantFP(C, SL, VT); 9663 } 9664 9665 static bool vectorEltWillFoldAway(SDValue Op) { 9666 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9667 } 9668 9669 SDValue SITargetLowering::performFCanonicalizeCombine( 9670 SDNode *N, 9671 DAGCombinerInfo &DCI) const { 9672 SelectionDAG &DAG = DCI.DAG; 9673 SDValue N0 = N->getOperand(0); 9674 EVT VT = N->getValueType(0); 9675 9676 // fcanonicalize undef -> qnan 9677 if (N0.isUndef()) { 9678 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9679 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9680 } 9681 9682 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9683 EVT VT = N->getValueType(0); 9684 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9685 } 9686 9687 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9688 // (fcanonicalize k) 9689 // 9690 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9691 9692 // TODO: This could be better with wider vectors that will be split to v2f16, 9693 // and to consider uses since there aren't that many packed operations. 9694 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9695 isTypeLegal(MVT::v2f16)) { 9696 SDLoc SL(N); 9697 SDValue NewElts[2]; 9698 SDValue Lo = N0.getOperand(0); 9699 SDValue Hi = N0.getOperand(1); 9700 EVT EltVT = Lo.getValueType(); 9701 9702 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9703 for (unsigned I = 0; I != 2; ++I) { 9704 SDValue Op = N0.getOperand(I); 9705 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9706 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9707 CFP->getValueAPF()); 9708 } else if (Op.isUndef()) { 9709 // Handled below based on what the other operand is. 9710 NewElts[I] = Op; 9711 } else { 9712 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9713 } 9714 } 9715 9716 // If one half is undef, and one is constant, perfer a splat vector rather 9717 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9718 // cheaper to use and may be free with a packed operation. 9719 if (NewElts[0].isUndef()) { 9720 if (isa<ConstantFPSDNode>(NewElts[1])) 9721 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9722 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9723 } 9724 9725 if (NewElts[1].isUndef()) { 9726 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9727 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9728 } 9729 9730 return DAG.getBuildVector(VT, SL, NewElts); 9731 } 9732 } 9733 9734 unsigned SrcOpc = N0.getOpcode(); 9735 9736 // If it's free to do so, push canonicalizes further up the source, which may 9737 // find a canonical source. 9738 // 9739 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9740 // sNaNs. 9741 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9742 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9743 if (CRHS && N0.hasOneUse()) { 9744 SDLoc SL(N); 9745 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9746 N0.getOperand(0)); 9747 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9748 DCI.AddToWorklist(Canon0.getNode()); 9749 9750 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9751 } 9752 } 9753 9754 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9755 } 9756 9757 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9758 switch (Opc) { 9759 case ISD::FMAXNUM: 9760 case ISD::FMAXNUM_IEEE: 9761 return AMDGPUISD::FMAX3; 9762 case ISD::SMAX: 9763 return AMDGPUISD::SMAX3; 9764 case ISD::UMAX: 9765 return AMDGPUISD::UMAX3; 9766 case ISD::FMINNUM: 9767 case ISD::FMINNUM_IEEE: 9768 return AMDGPUISD::FMIN3; 9769 case ISD::SMIN: 9770 return AMDGPUISD::SMIN3; 9771 case ISD::UMIN: 9772 return AMDGPUISD::UMIN3; 9773 default: 9774 llvm_unreachable("Not a min/max opcode"); 9775 } 9776 } 9777 9778 SDValue SITargetLowering::performIntMed3ImmCombine( 9779 SelectionDAG &DAG, const SDLoc &SL, 9780 SDValue Op0, SDValue Op1, bool Signed) const { 9781 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9782 if (!K1) 9783 return SDValue(); 9784 9785 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9786 if (!K0) 9787 return SDValue(); 9788 9789 if (Signed) { 9790 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9791 return SDValue(); 9792 } else { 9793 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9794 return SDValue(); 9795 } 9796 9797 EVT VT = K0->getValueType(0); 9798 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9799 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9800 return DAG.getNode(Med3Opc, SL, VT, 9801 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9802 } 9803 9804 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9805 MVT NVT = MVT::i32; 9806 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9807 9808 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9809 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9810 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9811 9812 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9813 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9814 } 9815 9816 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9817 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9818 return C; 9819 9820 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9821 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9822 return C; 9823 } 9824 9825 return nullptr; 9826 } 9827 9828 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9829 const SDLoc &SL, 9830 SDValue Op0, 9831 SDValue Op1) const { 9832 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9833 if (!K1) 9834 return SDValue(); 9835 9836 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9837 if (!K0) 9838 return SDValue(); 9839 9840 // Ordered >= (although NaN inputs should have folded away by now). 9841 if (K0->getValueAPF() > K1->getValueAPF()) 9842 return SDValue(); 9843 9844 const MachineFunction &MF = DAG.getMachineFunction(); 9845 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9846 9847 // TODO: Check IEEE bit enabled? 9848 EVT VT = Op0.getValueType(); 9849 if (Info->getMode().DX10Clamp) { 9850 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9851 // hardware fmed3 behavior converting to a min. 9852 // FIXME: Should this be allowing -0.0? 9853 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9854 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9855 } 9856 9857 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9858 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9859 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9860 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9861 // then give the other result, which is different from med3 with a NaN 9862 // input. 9863 SDValue Var = Op0.getOperand(0); 9864 if (!DAG.isKnownNeverSNaN(Var)) 9865 return SDValue(); 9866 9867 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9868 9869 if ((!K0->hasOneUse() || 9870 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9871 (!K1->hasOneUse() || 9872 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9873 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9874 Var, SDValue(K0, 0), SDValue(K1, 0)); 9875 } 9876 } 9877 9878 return SDValue(); 9879 } 9880 9881 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9882 DAGCombinerInfo &DCI) const { 9883 SelectionDAG &DAG = DCI.DAG; 9884 9885 EVT VT = N->getValueType(0); 9886 unsigned Opc = N->getOpcode(); 9887 SDValue Op0 = N->getOperand(0); 9888 SDValue Op1 = N->getOperand(1); 9889 9890 // Only do this if the inner op has one use since this will just increases 9891 // register pressure for no benefit. 9892 9893 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9894 !VT.isVector() && 9895 (VT == MVT::i32 || VT == MVT::f32 || 9896 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9897 // max(max(a, b), c) -> max3(a, b, c) 9898 // min(min(a, b), c) -> min3(a, b, c) 9899 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9900 SDLoc DL(N); 9901 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9902 DL, 9903 N->getValueType(0), 9904 Op0.getOperand(0), 9905 Op0.getOperand(1), 9906 Op1); 9907 } 9908 9909 // Try commuted. 9910 // max(a, max(b, c)) -> max3(a, b, c) 9911 // min(a, min(b, c)) -> min3(a, b, c) 9912 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9913 SDLoc DL(N); 9914 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9915 DL, 9916 N->getValueType(0), 9917 Op0, 9918 Op1.getOperand(0), 9919 Op1.getOperand(1)); 9920 } 9921 } 9922 9923 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9924 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9925 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9926 return Med3; 9927 } 9928 9929 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9930 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9931 return Med3; 9932 } 9933 9934 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9935 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9936 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9937 (Opc == AMDGPUISD::FMIN_LEGACY && 9938 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9939 (VT == MVT::f32 || VT == MVT::f64 || 9940 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9941 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9942 Op0.hasOneUse()) { 9943 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9944 return Res; 9945 } 9946 9947 return SDValue(); 9948 } 9949 9950 static bool isClampZeroToOne(SDValue A, SDValue B) { 9951 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9952 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9953 // FIXME: Should this be allowing -0.0? 9954 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9955 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9956 } 9957 } 9958 9959 return false; 9960 } 9961 9962 // FIXME: Should only worry about snans for version with chain. 9963 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9964 DAGCombinerInfo &DCI) const { 9965 EVT VT = N->getValueType(0); 9966 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9967 // NaNs. With a NaN input, the order of the operands may change the result. 9968 9969 SelectionDAG &DAG = DCI.DAG; 9970 SDLoc SL(N); 9971 9972 SDValue Src0 = N->getOperand(0); 9973 SDValue Src1 = N->getOperand(1); 9974 SDValue Src2 = N->getOperand(2); 9975 9976 if (isClampZeroToOne(Src0, Src1)) { 9977 // const_a, const_b, x -> clamp is safe in all cases including signaling 9978 // nans. 9979 // FIXME: Should this be allowing -0.0? 9980 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9981 } 9982 9983 const MachineFunction &MF = DAG.getMachineFunction(); 9984 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9985 9986 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9987 // handling no dx10-clamp? 9988 if (Info->getMode().DX10Clamp) { 9989 // If NaNs is clamped to 0, we are free to reorder the inputs. 9990 9991 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9992 std::swap(Src0, Src1); 9993 9994 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9995 std::swap(Src1, Src2); 9996 9997 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9998 std::swap(Src0, Src1); 9999 10000 if (isClampZeroToOne(Src1, Src2)) 10001 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10002 } 10003 10004 return SDValue(); 10005 } 10006 10007 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10008 DAGCombinerInfo &DCI) const { 10009 SDValue Src0 = N->getOperand(0); 10010 SDValue Src1 = N->getOperand(1); 10011 if (Src0.isUndef() && Src1.isUndef()) 10012 return DCI.DAG.getUNDEF(N->getValueType(0)); 10013 return SDValue(); 10014 } 10015 10016 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10017 // expanded into a set of cmp/select instructions. 10018 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10019 unsigned NumElem, 10020 bool IsDivergentIdx) { 10021 if (UseDivergentRegisterIndexing) 10022 return false; 10023 10024 unsigned VecSize = EltSize * NumElem; 10025 10026 // Sub-dword vectors of size 2 dword or less have better implementation. 10027 if (VecSize <= 64 && EltSize < 32) 10028 return false; 10029 10030 // Always expand the rest of sub-dword instructions, otherwise it will be 10031 // lowered via memory. 10032 if (EltSize < 32) 10033 return true; 10034 10035 // Always do this if var-idx is divergent, otherwise it will become a loop. 10036 if (IsDivergentIdx) 10037 return true; 10038 10039 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10040 unsigned NumInsts = NumElem /* Number of compares */ + 10041 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10042 return NumInsts <= 16; 10043 } 10044 10045 static bool shouldExpandVectorDynExt(SDNode *N) { 10046 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10047 if (isa<ConstantSDNode>(Idx)) 10048 return false; 10049 10050 SDValue Vec = N->getOperand(0); 10051 EVT VecVT = Vec.getValueType(); 10052 EVT EltVT = VecVT.getVectorElementType(); 10053 unsigned EltSize = EltVT.getSizeInBits(); 10054 unsigned NumElem = VecVT.getVectorNumElements(); 10055 10056 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10057 Idx->isDivergent()); 10058 } 10059 10060 SDValue SITargetLowering::performExtractVectorEltCombine( 10061 SDNode *N, DAGCombinerInfo &DCI) const { 10062 SDValue Vec = N->getOperand(0); 10063 SelectionDAG &DAG = DCI.DAG; 10064 10065 EVT VecVT = Vec.getValueType(); 10066 EVT EltVT = VecVT.getVectorElementType(); 10067 10068 if ((Vec.getOpcode() == ISD::FNEG || 10069 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10070 SDLoc SL(N); 10071 EVT EltVT = N->getValueType(0); 10072 SDValue Idx = N->getOperand(1); 10073 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10074 Vec.getOperand(0), Idx); 10075 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10076 } 10077 10078 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10079 // => 10080 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10081 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10082 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10083 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10084 SDLoc SL(N); 10085 EVT EltVT = N->getValueType(0); 10086 SDValue Idx = N->getOperand(1); 10087 unsigned Opc = Vec.getOpcode(); 10088 10089 switch(Opc) { 10090 default: 10091 break; 10092 // TODO: Support other binary operations. 10093 case ISD::FADD: 10094 case ISD::FSUB: 10095 case ISD::FMUL: 10096 case ISD::ADD: 10097 case ISD::UMIN: 10098 case ISD::UMAX: 10099 case ISD::SMIN: 10100 case ISD::SMAX: 10101 case ISD::FMAXNUM: 10102 case ISD::FMINNUM: 10103 case ISD::FMAXNUM_IEEE: 10104 case ISD::FMINNUM_IEEE: { 10105 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10106 Vec.getOperand(0), Idx); 10107 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10108 Vec.getOperand(1), Idx); 10109 10110 DCI.AddToWorklist(Elt0.getNode()); 10111 DCI.AddToWorklist(Elt1.getNode()); 10112 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10113 } 10114 } 10115 } 10116 10117 unsigned VecSize = VecVT.getSizeInBits(); 10118 unsigned EltSize = EltVT.getSizeInBits(); 10119 10120 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10121 if (::shouldExpandVectorDynExt(N)) { 10122 SDLoc SL(N); 10123 SDValue Idx = N->getOperand(1); 10124 SDValue V; 10125 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10126 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10127 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10128 if (I == 0) 10129 V = Elt; 10130 else 10131 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10132 } 10133 return V; 10134 } 10135 10136 if (!DCI.isBeforeLegalize()) 10137 return SDValue(); 10138 10139 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10140 // elements. This exposes more load reduction opportunities by replacing 10141 // multiple small extract_vector_elements with a single 32-bit extract. 10142 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10143 if (isa<MemSDNode>(Vec) && 10144 EltSize <= 16 && 10145 EltVT.isByteSized() && 10146 VecSize > 32 && 10147 VecSize % 32 == 0 && 10148 Idx) { 10149 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10150 10151 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10152 unsigned EltIdx = BitIndex / 32; 10153 unsigned LeftoverBitIdx = BitIndex % 32; 10154 SDLoc SL(N); 10155 10156 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10157 DCI.AddToWorklist(Cast.getNode()); 10158 10159 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10160 DAG.getConstant(EltIdx, SL, MVT::i32)); 10161 DCI.AddToWorklist(Elt.getNode()); 10162 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10163 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10164 DCI.AddToWorklist(Srl.getNode()); 10165 10166 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10167 DCI.AddToWorklist(Trunc.getNode()); 10168 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10169 } 10170 10171 return SDValue(); 10172 } 10173 10174 SDValue 10175 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10176 DAGCombinerInfo &DCI) const { 10177 SDValue Vec = N->getOperand(0); 10178 SDValue Idx = N->getOperand(2); 10179 EVT VecVT = Vec.getValueType(); 10180 EVT EltVT = VecVT.getVectorElementType(); 10181 10182 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10183 // => BUILD_VECTOR n x select (e, const-idx) 10184 if (!::shouldExpandVectorDynExt(N)) 10185 return SDValue(); 10186 10187 SelectionDAG &DAG = DCI.DAG; 10188 SDLoc SL(N); 10189 SDValue Ins = N->getOperand(1); 10190 EVT IdxVT = Idx.getValueType(); 10191 10192 SmallVector<SDValue, 16> Ops; 10193 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10194 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10195 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10196 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10197 Ops.push_back(V); 10198 } 10199 10200 return DAG.getBuildVector(VecVT, SL, Ops); 10201 } 10202 10203 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10204 const SDNode *N0, 10205 const SDNode *N1) const { 10206 EVT VT = N0->getValueType(0); 10207 10208 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10209 // support denormals ever. 10210 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10211 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10212 getSubtarget()->hasMadF16())) && 10213 isOperationLegal(ISD::FMAD, VT)) 10214 return ISD::FMAD; 10215 10216 const TargetOptions &Options = DAG.getTarget().Options; 10217 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10218 (N0->getFlags().hasAllowContract() && 10219 N1->getFlags().hasAllowContract())) && 10220 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10221 return ISD::FMA; 10222 } 10223 10224 return 0; 10225 } 10226 10227 // For a reassociatable opcode perform: 10228 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10229 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10230 SelectionDAG &DAG) const { 10231 EVT VT = N->getValueType(0); 10232 if (VT != MVT::i32 && VT != MVT::i64) 10233 return SDValue(); 10234 10235 unsigned Opc = N->getOpcode(); 10236 SDValue Op0 = N->getOperand(0); 10237 SDValue Op1 = N->getOperand(1); 10238 10239 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10240 return SDValue(); 10241 10242 if (Op0->isDivergent()) 10243 std::swap(Op0, Op1); 10244 10245 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10246 return SDValue(); 10247 10248 SDValue Op2 = Op1.getOperand(1); 10249 Op1 = Op1.getOperand(0); 10250 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10251 return SDValue(); 10252 10253 if (Op1->isDivergent()) 10254 std::swap(Op1, Op2); 10255 10256 // If either operand is constant this will conflict with 10257 // DAGCombiner::ReassociateOps(). 10258 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10259 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10260 return SDValue(); 10261 10262 SDLoc SL(N); 10263 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10264 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10265 } 10266 10267 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10268 EVT VT, 10269 SDValue N0, SDValue N1, SDValue N2, 10270 bool Signed) { 10271 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10272 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10273 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10274 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10275 } 10276 10277 SDValue SITargetLowering::performAddCombine(SDNode *N, 10278 DAGCombinerInfo &DCI) const { 10279 SelectionDAG &DAG = DCI.DAG; 10280 EVT VT = N->getValueType(0); 10281 SDLoc SL(N); 10282 SDValue LHS = N->getOperand(0); 10283 SDValue RHS = N->getOperand(1); 10284 10285 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10286 && Subtarget->hasMad64_32() && 10287 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10288 VT.getScalarSizeInBits() <= 64) { 10289 if (LHS.getOpcode() != ISD::MUL) 10290 std::swap(LHS, RHS); 10291 10292 SDValue MulLHS = LHS.getOperand(0); 10293 SDValue MulRHS = LHS.getOperand(1); 10294 SDValue AddRHS = RHS; 10295 10296 // TODO: Maybe restrict if SGPR inputs. 10297 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10298 numBitsUnsigned(MulRHS, DAG) <= 32) { 10299 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10300 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10301 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10302 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10303 } 10304 10305 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10306 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10307 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10308 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10309 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10310 } 10311 10312 return SDValue(); 10313 } 10314 10315 if (SDValue V = reassociateScalarOps(N, DAG)) { 10316 return V; 10317 } 10318 10319 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10320 return SDValue(); 10321 10322 // add x, zext (setcc) => addcarry x, 0, setcc 10323 // add x, sext (setcc) => subcarry x, 0, setcc 10324 unsigned Opc = LHS.getOpcode(); 10325 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10326 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10327 std::swap(RHS, LHS); 10328 10329 Opc = RHS.getOpcode(); 10330 switch (Opc) { 10331 default: break; 10332 case ISD::ZERO_EXTEND: 10333 case ISD::SIGN_EXTEND: 10334 case ISD::ANY_EXTEND: { 10335 auto Cond = RHS.getOperand(0); 10336 // If this won't be a real VOPC output, we would still need to insert an 10337 // extra instruction anyway. 10338 if (!isBoolSGPR(Cond)) 10339 break; 10340 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10341 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10342 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10343 return DAG.getNode(Opc, SL, VTList, Args); 10344 } 10345 case ISD::ADDCARRY: { 10346 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10347 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10348 if (!C || C->getZExtValue() != 0) break; 10349 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10350 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10351 } 10352 } 10353 return SDValue(); 10354 } 10355 10356 SDValue SITargetLowering::performSubCombine(SDNode *N, 10357 DAGCombinerInfo &DCI) const { 10358 SelectionDAG &DAG = DCI.DAG; 10359 EVT VT = N->getValueType(0); 10360 10361 if (VT != MVT::i32) 10362 return SDValue(); 10363 10364 SDLoc SL(N); 10365 SDValue LHS = N->getOperand(0); 10366 SDValue RHS = N->getOperand(1); 10367 10368 // sub x, zext (setcc) => subcarry x, 0, setcc 10369 // sub x, sext (setcc) => addcarry x, 0, setcc 10370 unsigned Opc = RHS.getOpcode(); 10371 switch (Opc) { 10372 default: break; 10373 case ISD::ZERO_EXTEND: 10374 case ISD::SIGN_EXTEND: 10375 case ISD::ANY_EXTEND: { 10376 auto Cond = RHS.getOperand(0); 10377 // If this won't be a real VOPC output, we would still need to insert an 10378 // extra instruction anyway. 10379 if (!isBoolSGPR(Cond)) 10380 break; 10381 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10382 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10383 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10384 return DAG.getNode(Opc, SL, VTList, Args); 10385 } 10386 } 10387 10388 if (LHS.getOpcode() == ISD::SUBCARRY) { 10389 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10390 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10391 if (!C || !C->isNullValue()) 10392 return SDValue(); 10393 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10394 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10395 } 10396 return SDValue(); 10397 } 10398 10399 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10400 DAGCombinerInfo &DCI) const { 10401 10402 if (N->getValueType(0) != MVT::i32) 10403 return SDValue(); 10404 10405 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10406 if (!C || C->getZExtValue() != 0) 10407 return SDValue(); 10408 10409 SelectionDAG &DAG = DCI.DAG; 10410 SDValue LHS = N->getOperand(0); 10411 10412 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10413 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10414 unsigned LHSOpc = LHS.getOpcode(); 10415 unsigned Opc = N->getOpcode(); 10416 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10417 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10418 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10419 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10420 } 10421 return SDValue(); 10422 } 10423 10424 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10425 DAGCombinerInfo &DCI) const { 10426 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10427 return SDValue(); 10428 10429 SelectionDAG &DAG = DCI.DAG; 10430 EVT VT = N->getValueType(0); 10431 10432 SDLoc SL(N); 10433 SDValue LHS = N->getOperand(0); 10434 SDValue RHS = N->getOperand(1); 10435 10436 // These should really be instruction patterns, but writing patterns with 10437 // source modiifiers is a pain. 10438 10439 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10440 if (LHS.getOpcode() == ISD::FADD) { 10441 SDValue A = LHS.getOperand(0); 10442 if (A == LHS.getOperand(1)) { 10443 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10444 if (FusedOp != 0) { 10445 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10446 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10447 } 10448 } 10449 } 10450 10451 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10452 if (RHS.getOpcode() == ISD::FADD) { 10453 SDValue A = RHS.getOperand(0); 10454 if (A == RHS.getOperand(1)) { 10455 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10456 if (FusedOp != 0) { 10457 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10458 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10459 } 10460 } 10461 } 10462 10463 return SDValue(); 10464 } 10465 10466 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10467 DAGCombinerInfo &DCI) const { 10468 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10469 return SDValue(); 10470 10471 SelectionDAG &DAG = DCI.DAG; 10472 SDLoc SL(N); 10473 EVT VT = N->getValueType(0); 10474 assert(!VT.isVector()); 10475 10476 // Try to get the fneg to fold into the source modifier. This undoes generic 10477 // DAG combines and folds them into the mad. 10478 // 10479 // Only do this if we are not trying to support denormals. v_mad_f32 does 10480 // not support denormals ever. 10481 SDValue LHS = N->getOperand(0); 10482 SDValue RHS = N->getOperand(1); 10483 if (LHS.getOpcode() == ISD::FADD) { 10484 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10485 SDValue A = LHS.getOperand(0); 10486 if (A == LHS.getOperand(1)) { 10487 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10488 if (FusedOp != 0){ 10489 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10490 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10491 10492 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10493 } 10494 } 10495 } 10496 10497 if (RHS.getOpcode() == ISD::FADD) { 10498 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10499 10500 SDValue A = RHS.getOperand(0); 10501 if (A == RHS.getOperand(1)) { 10502 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10503 if (FusedOp != 0){ 10504 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10505 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10506 } 10507 } 10508 } 10509 10510 return SDValue(); 10511 } 10512 10513 SDValue SITargetLowering::performFMACombine(SDNode *N, 10514 DAGCombinerInfo &DCI) const { 10515 SelectionDAG &DAG = DCI.DAG; 10516 EVT VT = N->getValueType(0); 10517 SDLoc SL(N); 10518 10519 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 10520 return SDValue(); 10521 10522 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10523 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10524 SDValue Op1 = N->getOperand(0); 10525 SDValue Op2 = N->getOperand(1); 10526 SDValue FMA = N->getOperand(2); 10527 10528 if (FMA.getOpcode() != ISD::FMA || 10529 Op1.getOpcode() != ISD::FP_EXTEND || 10530 Op2.getOpcode() != ISD::FP_EXTEND) 10531 return SDValue(); 10532 10533 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10534 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10535 // is sufficient to allow generaing fdot2. 10536 const TargetOptions &Options = DAG.getTarget().Options; 10537 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10538 (N->getFlags().hasAllowContract() && 10539 FMA->getFlags().hasAllowContract())) { 10540 Op1 = Op1.getOperand(0); 10541 Op2 = Op2.getOperand(0); 10542 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10543 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10544 return SDValue(); 10545 10546 SDValue Vec1 = Op1.getOperand(0); 10547 SDValue Idx1 = Op1.getOperand(1); 10548 SDValue Vec2 = Op2.getOperand(0); 10549 10550 SDValue FMAOp1 = FMA.getOperand(0); 10551 SDValue FMAOp2 = FMA.getOperand(1); 10552 SDValue FMAAcc = FMA.getOperand(2); 10553 10554 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10555 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10556 return SDValue(); 10557 10558 FMAOp1 = FMAOp1.getOperand(0); 10559 FMAOp2 = FMAOp2.getOperand(0); 10560 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10561 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10562 return SDValue(); 10563 10564 SDValue Vec3 = FMAOp1.getOperand(0); 10565 SDValue Vec4 = FMAOp2.getOperand(0); 10566 SDValue Idx2 = FMAOp1.getOperand(1); 10567 10568 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10569 // Idx1 and Idx2 cannot be the same. 10570 Idx1 == Idx2) 10571 return SDValue(); 10572 10573 if (Vec1 == Vec2 || Vec3 == Vec4) 10574 return SDValue(); 10575 10576 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10577 return SDValue(); 10578 10579 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10580 (Vec1 == Vec4 && Vec2 == Vec3)) { 10581 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10582 DAG.getTargetConstant(0, SL, MVT::i1)); 10583 } 10584 } 10585 return SDValue(); 10586 } 10587 10588 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10589 DAGCombinerInfo &DCI) const { 10590 SelectionDAG &DAG = DCI.DAG; 10591 SDLoc SL(N); 10592 10593 SDValue LHS = N->getOperand(0); 10594 SDValue RHS = N->getOperand(1); 10595 EVT VT = LHS.getValueType(); 10596 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10597 10598 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10599 if (!CRHS) { 10600 CRHS = dyn_cast<ConstantSDNode>(LHS); 10601 if (CRHS) { 10602 std::swap(LHS, RHS); 10603 CC = getSetCCSwappedOperands(CC); 10604 } 10605 } 10606 10607 if (CRHS) { 10608 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10609 isBoolSGPR(LHS.getOperand(0))) { 10610 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10611 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10612 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10613 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10614 if ((CRHS->isAllOnesValue() && 10615 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10616 (CRHS->isNullValue() && 10617 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10618 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10619 DAG.getConstant(-1, SL, MVT::i1)); 10620 if ((CRHS->isAllOnesValue() && 10621 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10622 (CRHS->isNullValue() && 10623 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10624 return LHS.getOperand(0); 10625 } 10626 10627 uint64_t CRHSVal = CRHS->getZExtValue(); 10628 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10629 LHS.getOpcode() == ISD::SELECT && 10630 isa<ConstantSDNode>(LHS.getOperand(1)) && 10631 isa<ConstantSDNode>(LHS.getOperand(2)) && 10632 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10633 isBoolSGPR(LHS.getOperand(0))) { 10634 // Given CT != FT: 10635 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10636 // setcc (select cc, CT, CF), CF, ne => cc 10637 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10638 // setcc (select cc, CT, CF), CT, eq => cc 10639 uint64_t CT = LHS.getConstantOperandVal(1); 10640 uint64_t CF = LHS.getConstantOperandVal(2); 10641 10642 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10643 (CT == CRHSVal && CC == ISD::SETNE)) 10644 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10645 DAG.getConstant(-1, SL, MVT::i1)); 10646 if ((CF == CRHSVal && CC == ISD::SETNE) || 10647 (CT == CRHSVal && CC == ISD::SETEQ)) 10648 return LHS.getOperand(0); 10649 } 10650 } 10651 10652 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10653 VT != MVT::f16)) 10654 return SDValue(); 10655 10656 // Match isinf/isfinite pattern 10657 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10658 // (fcmp one (fabs x), inf) -> (fp_class x, 10659 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10660 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10661 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10662 if (!CRHS) 10663 return SDValue(); 10664 10665 const APFloat &APF = CRHS->getValueAPF(); 10666 if (APF.isInfinity() && !APF.isNegative()) { 10667 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10668 SIInstrFlags::N_INFINITY; 10669 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10670 SIInstrFlags::P_ZERO | 10671 SIInstrFlags::N_NORMAL | 10672 SIInstrFlags::P_NORMAL | 10673 SIInstrFlags::N_SUBNORMAL | 10674 SIInstrFlags::P_SUBNORMAL; 10675 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10676 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10677 DAG.getConstant(Mask, SL, MVT::i32)); 10678 } 10679 } 10680 10681 return SDValue(); 10682 } 10683 10684 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10685 DAGCombinerInfo &DCI) const { 10686 SelectionDAG &DAG = DCI.DAG; 10687 SDLoc SL(N); 10688 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10689 10690 SDValue Src = N->getOperand(0); 10691 SDValue Shift = N->getOperand(0); 10692 10693 // TODO: Extend type shouldn't matter (assuming legal types). 10694 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10695 Shift = Shift.getOperand(0); 10696 10697 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10698 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10699 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10700 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10701 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10702 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10703 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10704 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10705 SDLoc(Shift.getOperand(0)), MVT::i32); 10706 10707 unsigned ShiftOffset = 8 * Offset; 10708 if (Shift.getOpcode() == ISD::SHL) 10709 ShiftOffset -= C->getZExtValue(); 10710 else 10711 ShiftOffset += C->getZExtValue(); 10712 10713 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10714 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10715 MVT::f32, Shift); 10716 } 10717 } 10718 } 10719 10720 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10721 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10722 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10723 // We simplified Src. If this node is not dead, visit it again so it is 10724 // folded properly. 10725 if (N->getOpcode() != ISD::DELETED_NODE) 10726 DCI.AddToWorklist(N); 10727 return SDValue(N, 0); 10728 } 10729 10730 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10731 if (SDValue DemandedSrc = 10732 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10733 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10734 10735 return SDValue(); 10736 } 10737 10738 SDValue SITargetLowering::performClampCombine(SDNode *N, 10739 DAGCombinerInfo &DCI) const { 10740 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10741 if (!CSrc) 10742 return SDValue(); 10743 10744 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10745 const APFloat &F = CSrc->getValueAPF(); 10746 APFloat Zero = APFloat::getZero(F.getSemantics()); 10747 if (F < Zero || 10748 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10749 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10750 } 10751 10752 APFloat One(F.getSemantics(), "1.0"); 10753 if (F > One) 10754 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10755 10756 return SDValue(CSrc, 0); 10757 } 10758 10759 10760 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10761 DAGCombinerInfo &DCI) const { 10762 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10763 return SDValue(); 10764 switch (N->getOpcode()) { 10765 case ISD::ADD: 10766 return performAddCombine(N, DCI); 10767 case ISD::SUB: 10768 return performSubCombine(N, DCI); 10769 case ISD::ADDCARRY: 10770 case ISD::SUBCARRY: 10771 return performAddCarrySubCarryCombine(N, DCI); 10772 case ISD::FADD: 10773 return performFAddCombine(N, DCI); 10774 case ISD::FSUB: 10775 return performFSubCombine(N, DCI); 10776 case ISD::SETCC: 10777 return performSetCCCombine(N, DCI); 10778 case ISD::FMAXNUM: 10779 case ISD::FMINNUM: 10780 case ISD::FMAXNUM_IEEE: 10781 case ISD::FMINNUM_IEEE: 10782 case ISD::SMAX: 10783 case ISD::SMIN: 10784 case ISD::UMAX: 10785 case ISD::UMIN: 10786 case AMDGPUISD::FMIN_LEGACY: 10787 case AMDGPUISD::FMAX_LEGACY: 10788 return performMinMaxCombine(N, DCI); 10789 case ISD::FMA: 10790 return performFMACombine(N, DCI); 10791 case ISD::AND: 10792 return performAndCombine(N, DCI); 10793 case ISD::OR: 10794 return performOrCombine(N, DCI); 10795 case ISD::XOR: 10796 return performXorCombine(N, DCI); 10797 case ISD::ZERO_EXTEND: 10798 return performZeroExtendCombine(N, DCI); 10799 case ISD::SIGN_EXTEND_INREG: 10800 return performSignExtendInRegCombine(N , DCI); 10801 case AMDGPUISD::FP_CLASS: 10802 return performClassCombine(N, DCI); 10803 case ISD::FCANONICALIZE: 10804 return performFCanonicalizeCombine(N, DCI); 10805 case AMDGPUISD::RCP: 10806 return performRcpCombine(N, DCI); 10807 case AMDGPUISD::FRACT: 10808 case AMDGPUISD::RSQ: 10809 case AMDGPUISD::RCP_LEGACY: 10810 case AMDGPUISD::RCP_IFLAG: 10811 case AMDGPUISD::RSQ_CLAMP: 10812 case AMDGPUISD::LDEXP: { 10813 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10814 SDValue Src = N->getOperand(0); 10815 if (Src.isUndef()) 10816 return Src; 10817 break; 10818 } 10819 case ISD::SINT_TO_FP: 10820 case ISD::UINT_TO_FP: 10821 return performUCharToFloatCombine(N, DCI); 10822 case AMDGPUISD::CVT_F32_UBYTE0: 10823 case AMDGPUISD::CVT_F32_UBYTE1: 10824 case AMDGPUISD::CVT_F32_UBYTE2: 10825 case AMDGPUISD::CVT_F32_UBYTE3: 10826 return performCvtF32UByteNCombine(N, DCI); 10827 case AMDGPUISD::FMED3: 10828 return performFMed3Combine(N, DCI); 10829 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10830 return performCvtPkRTZCombine(N, DCI); 10831 case AMDGPUISD::CLAMP: 10832 return performClampCombine(N, DCI); 10833 case ISD::SCALAR_TO_VECTOR: { 10834 SelectionDAG &DAG = DCI.DAG; 10835 EVT VT = N->getValueType(0); 10836 10837 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10838 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10839 SDLoc SL(N); 10840 SDValue Src = N->getOperand(0); 10841 EVT EltVT = Src.getValueType(); 10842 if (EltVT == MVT::f16) 10843 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10844 10845 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10846 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10847 } 10848 10849 break; 10850 } 10851 case ISD::EXTRACT_VECTOR_ELT: 10852 return performExtractVectorEltCombine(N, DCI); 10853 case ISD::INSERT_VECTOR_ELT: 10854 return performInsertVectorEltCombine(N, DCI); 10855 case ISD::LOAD: { 10856 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10857 return Widended; 10858 LLVM_FALLTHROUGH; 10859 } 10860 default: { 10861 if (!DCI.isBeforeLegalize()) { 10862 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 10863 return performMemSDNodeCombine(MemNode, DCI); 10864 } 10865 10866 break; 10867 } 10868 } 10869 10870 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10871 } 10872 10873 /// Helper function for adjustWritemask 10874 static unsigned SubIdx2Lane(unsigned Idx) { 10875 switch (Idx) { 10876 default: return ~0u; 10877 case AMDGPU::sub0: return 0; 10878 case AMDGPU::sub1: return 1; 10879 case AMDGPU::sub2: return 2; 10880 case AMDGPU::sub3: return 3; 10881 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10882 } 10883 } 10884 10885 /// Adjust the writemask of MIMG instructions 10886 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10887 SelectionDAG &DAG) const { 10888 unsigned Opcode = Node->getMachineOpcode(); 10889 10890 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10891 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10892 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10893 return Node; // not implemented for D16 10894 10895 SDNode *Users[5] = { nullptr }; 10896 unsigned Lane = 0; 10897 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10898 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10899 unsigned NewDmask = 0; 10900 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10901 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10902 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 10903 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10904 unsigned TFCLane = 0; 10905 bool HasChain = Node->getNumValues() > 1; 10906 10907 if (OldDmask == 0) { 10908 // These are folded out, but on the chance it happens don't assert. 10909 return Node; 10910 } 10911 10912 unsigned OldBitsSet = countPopulation(OldDmask); 10913 // Work out which is the TFE/LWE lane if that is enabled. 10914 if (UsesTFC) { 10915 TFCLane = OldBitsSet; 10916 } 10917 10918 // Try to figure out the used register components 10919 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10920 I != E; ++I) { 10921 10922 // Don't look at users of the chain. 10923 if (I.getUse().getResNo() != 0) 10924 continue; 10925 10926 // Abort if we can't understand the usage 10927 if (!I->isMachineOpcode() || 10928 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10929 return Node; 10930 10931 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10932 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10933 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10934 // set, etc. 10935 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10936 if (Lane == ~0u) 10937 return Node; 10938 10939 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10940 if (UsesTFC && Lane == TFCLane) { 10941 Users[Lane] = *I; 10942 } else { 10943 // Set which texture component corresponds to the lane. 10944 unsigned Comp; 10945 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10946 Comp = countTrailingZeros(Dmask); 10947 Dmask &= ~(1 << Comp); 10948 } 10949 10950 // Abort if we have more than one user per component. 10951 if (Users[Lane]) 10952 return Node; 10953 10954 Users[Lane] = *I; 10955 NewDmask |= 1 << Comp; 10956 } 10957 } 10958 10959 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10960 bool NoChannels = !NewDmask; 10961 if (NoChannels) { 10962 if (!UsesTFC) { 10963 // No uses of the result and not using TFC. Then do nothing. 10964 return Node; 10965 } 10966 // If the original dmask has one channel - then nothing to do 10967 if (OldBitsSet == 1) 10968 return Node; 10969 // Use an arbitrary dmask - required for the instruction to work 10970 NewDmask = 1; 10971 } 10972 // Abort if there's no change 10973 if (NewDmask == OldDmask) 10974 return Node; 10975 10976 unsigned BitsSet = countPopulation(NewDmask); 10977 10978 // Check for TFE or LWE - increase the number of channels by one to account 10979 // for the extra return value 10980 // This will need adjustment for D16 if this is also included in 10981 // adjustWriteMask (this function) but at present D16 are excluded. 10982 unsigned NewChannels = BitsSet + UsesTFC; 10983 10984 int NewOpcode = 10985 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10986 assert(NewOpcode != -1 && 10987 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10988 "failed to find equivalent MIMG op"); 10989 10990 // Adjust the writemask in the node 10991 SmallVector<SDValue, 12> Ops; 10992 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10993 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10994 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10995 10996 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10997 10998 MVT ResultVT = NewChannels == 1 ? 10999 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11000 NewChannels == 5 ? 8 : NewChannels); 11001 SDVTList NewVTList = HasChain ? 11002 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11003 11004 11005 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11006 NewVTList, Ops); 11007 11008 if (HasChain) { 11009 // Update chain. 11010 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11011 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11012 } 11013 11014 if (NewChannels == 1) { 11015 assert(Node->hasNUsesOfValue(1, 0)); 11016 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11017 SDLoc(Node), Users[Lane]->getValueType(0), 11018 SDValue(NewNode, 0)); 11019 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11020 return nullptr; 11021 } 11022 11023 // Update the users of the node with the new indices 11024 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11025 SDNode *User = Users[i]; 11026 if (!User) { 11027 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11028 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11029 if (i || !NoChannels) 11030 continue; 11031 } else { 11032 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11033 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11034 } 11035 11036 switch (Idx) { 11037 default: break; 11038 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11039 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11040 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11041 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11042 } 11043 } 11044 11045 DAG.RemoveDeadNode(Node); 11046 return nullptr; 11047 } 11048 11049 static bool isFrameIndexOp(SDValue Op) { 11050 if (Op.getOpcode() == ISD::AssertZext) 11051 Op = Op.getOperand(0); 11052 11053 return isa<FrameIndexSDNode>(Op); 11054 } 11055 11056 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11057 /// with frame index operands. 11058 /// LLVM assumes that inputs are to these instructions are registers. 11059 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11060 SelectionDAG &DAG) const { 11061 if (Node->getOpcode() == ISD::CopyToReg) { 11062 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11063 SDValue SrcVal = Node->getOperand(2); 11064 11065 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11066 // to try understanding copies to physical registers. 11067 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11068 SDLoc SL(Node); 11069 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11070 SDValue VReg = DAG.getRegister( 11071 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11072 11073 SDNode *Glued = Node->getGluedNode(); 11074 SDValue ToVReg 11075 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11076 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11077 SDValue ToResultReg 11078 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11079 VReg, ToVReg.getValue(1)); 11080 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11081 DAG.RemoveDeadNode(Node); 11082 return ToResultReg.getNode(); 11083 } 11084 } 11085 11086 SmallVector<SDValue, 8> Ops; 11087 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11088 if (!isFrameIndexOp(Node->getOperand(i))) { 11089 Ops.push_back(Node->getOperand(i)); 11090 continue; 11091 } 11092 11093 SDLoc DL(Node); 11094 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11095 Node->getOperand(i).getValueType(), 11096 Node->getOperand(i)), 0)); 11097 } 11098 11099 return DAG.UpdateNodeOperands(Node, Ops); 11100 } 11101 11102 /// Fold the instructions after selecting them. 11103 /// Returns null if users were already updated. 11104 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11105 SelectionDAG &DAG) const { 11106 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11107 unsigned Opcode = Node->getMachineOpcode(); 11108 11109 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11110 !TII->isGather4(Opcode) && 11111 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11112 return adjustWritemask(Node, DAG); 11113 } 11114 11115 if (Opcode == AMDGPU::INSERT_SUBREG || 11116 Opcode == AMDGPU::REG_SEQUENCE) { 11117 legalizeTargetIndependentNode(Node, DAG); 11118 return Node; 11119 } 11120 11121 switch (Opcode) { 11122 case AMDGPU::V_DIV_SCALE_F32_e64: 11123 case AMDGPU::V_DIV_SCALE_F64_e64: { 11124 // Satisfy the operand register constraint when one of the inputs is 11125 // undefined. Ordinarily each undef value will have its own implicit_def of 11126 // a vreg, so force these to use a single register. 11127 SDValue Src0 = Node->getOperand(1); 11128 SDValue Src1 = Node->getOperand(3); 11129 SDValue Src2 = Node->getOperand(5); 11130 11131 if ((Src0.isMachineOpcode() && 11132 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11133 (Src0 == Src1 || Src0 == Src2)) 11134 break; 11135 11136 MVT VT = Src0.getValueType().getSimpleVT(); 11137 const TargetRegisterClass *RC = 11138 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11139 11140 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11141 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11142 11143 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11144 UndefReg, Src0, SDValue()); 11145 11146 // src0 must be the same register as src1 or src2, even if the value is 11147 // undefined, so make sure we don't violate this constraint. 11148 if (Src0.isMachineOpcode() && 11149 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11150 if (Src1.isMachineOpcode() && 11151 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11152 Src0 = Src1; 11153 else if (Src2.isMachineOpcode() && 11154 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11155 Src0 = Src2; 11156 else { 11157 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11158 Src0 = UndefReg; 11159 Src1 = UndefReg; 11160 } 11161 } else 11162 break; 11163 11164 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11165 Ops[1] = Src0; 11166 Ops[3] = Src1; 11167 Ops[5] = Src2; 11168 Ops.push_back(ImpDef.getValue(1)); 11169 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11170 } 11171 default: 11172 break; 11173 } 11174 11175 return Node; 11176 } 11177 11178 /// Assign the register class depending on the number of 11179 /// bits set in the writemask 11180 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11181 SDNode *Node) const { 11182 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11183 11184 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11185 11186 if (TII->isVOP3(MI.getOpcode())) { 11187 // Make sure constant bus requirements are respected. 11188 TII->legalizeOperandsVOP3(MRI, MI); 11189 11190 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11191 // This saves a chain-copy of registers and better ballance register 11192 // use between vgpr and agpr as agpr tuples tend to be big. 11193 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 11194 unsigned Opc = MI.getOpcode(); 11195 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11196 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11197 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11198 if (I == -1) 11199 break; 11200 MachineOperand &Op = MI.getOperand(I); 11201 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 11202 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 11203 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 11204 continue; 11205 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11206 if (!Src || !Src->isCopy() || 11207 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11208 continue; 11209 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11210 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11211 // All uses of agpr64 and agpr32 can also accept vgpr except for 11212 // v_accvgpr_read, but we do not produce agpr reads during selection, 11213 // so no use checks are needed. 11214 MRI.setRegClass(Op.getReg(), NewRC); 11215 } 11216 } 11217 11218 return; 11219 } 11220 11221 // Replace unused atomics with the no return version. 11222 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11223 if (NoRetAtomicOp != -1) { 11224 if (!Node->hasAnyUseOfValue(0)) { 11225 int Glc1Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11226 AMDGPU::OpName::glc1); 11227 if (Glc1Idx != -1) 11228 MI.RemoveOperand(Glc1Idx); 11229 MI.RemoveOperand(0); 11230 MI.setDesc(TII->get(NoRetAtomicOp)); 11231 return; 11232 } 11233 11234 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11235 // instruction, because the return type of these instructions is a vec2 of 11236 // the memory type, so it can be tied to the input operand. 11237 // This means these instructions always have a use, so we need to add a 11238 // special case to check if the atomic has only one extract_subreg use, 11239 // which itself has no uses. 11240 if ((Node->hasNUsesOfValue(1, 0) && 11241 Node->use_begin()->isMachineOpcode() && 11242 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11243 !Node->use_begin()->hasAnyUseOfValue(0))) { 11244 Register Def = MI.getOperand(0).getReg(); 11245 11246 // Change this into a noret atomic. 11247 MI.setDesc(TII->get(NoRetAtomicOp)); 11248 MI.RemoveOperand(0); 11249 11250 // If we only remove the def operand from the atomic instruction, the 11251 // extract_subreg will be left with a use of a vreg without a def. 11252 // So we need to insert an implicit_def to avoid machine verifier 11253 // errors. 11254 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11255 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11256 } 11257 return; 11258 } 11259 } 11260 11261 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11262 uint64_t Val) { 11263 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11264 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11265 } 11266 11267 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11268 const SDLoc &DL, 11269 SDValue Ptr) const { 11270 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11271 11272 // Build the half of the subregister with the constants before building the 11273 // full 128-bit register. If we are building multiple resource descriptors, 11274 // this will allow CSEing of the 2-component register. 11275 const SDValue Ops0[] = { 11276 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11277 buildSMovImm32(DAG, DL, 0), 11278 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11279 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11280 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11281 }; 11282 11283 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11284 MVT::v2i32, Ops0), 0); 11285 11286 // Combine the constants and the pointer. 11287 const SDValue Ops1[] = { 11288 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11289 Ptr, 11290 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11291 SubRegHi, 11292 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11293 }; 11294 11295 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11296 } 11297 11298 /// Return a resource descriptor with the 'Add TID' bit enabled 11299 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11300 /// of the resource descriptor) to create an offset, which is added to 11301 /// the resource pointer. 11302 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11303 SDValue Ptr, uint32_t RsrcDword1, 11304 uint64_t RsrcDword2And3) const { 11305 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11306 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11307 if (RsrcDword1) { 11308 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11309 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11310 0); 11311 } 11312 11313 SDValue DataLo = buildSMovImm32(DAG, DL, 11314 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11315 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11316 11317 const SDValue Ops[] = { 11318 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11319 PtrLo, 11320 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11321 PtrHi, 11322 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11323 DataLo, 11324 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11325 DataHi, 11326 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11327 }; 11328 11329 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11330 } 11331 11332 //===----------------------------------------------------------------------===// 11333 // SI Inline Assembly Support 11334 //===----------------------------------------------------------------------===// 11335 11336 std::pair<unsigned, const TargetRegisterClass *> 11337 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11338 StringRef Constraint, 11339 MVT VT) const { 11340 const TargetRegisterClass *RC = nullptr; 11341 if (Constraint.size() == 1) { 11342 const unsigned BitWidth = VT.getSizeInBits(); 11343 switch (Constraint[0]) { 11344 default: 11345 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11346 case 's': 11347 case 'r': 11348 switch (BitWidth) { 11349 case 16: 11350 RC = &AMDGPU::SReg_32RegClass; 11351 break; 11352 case 64: 11353 RC = &AMDGPU::SGPR_64RegClass; 11354 break; 11355 default: 11356 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11357 if (!RC) 11358 return std::make_pair(0U, nullptr); 11359 break; 11360 } 11361 break; 11362 case 'v': 11363 switch (BitWidth) { 11364 case 16: 11365 RC = &AMDGPU::VGPR_32RegClass; 11366 break; 11367 default: 11368 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 11369 if (!RC) 11370 return std::make_pair(0U, nullptr); 11371 break; 11372 } 11373 break; 11374 case 'a': 11375 if (!Subtarget->hasMAIInsts()) 11376 break; 11377 switch (BitWidth) { 11378 case 16: 11379 RC = &AMDGPU::AGPR_32RegClass; 11380 break; 11381 default: 11382 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 11383 if (!RC) 11384 return std::make_pair(0U, nullptr); 11385 break; 11386 } 11387 break; 11388 } 11389 // We actually support i128, i16 and f16 as inline parameters 11390 // even if they are not reported as legal 11391 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11392 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11393 return std::make_pair(0U, RC); 11394 } 11395 11396 if (Constraint.size() > 1) { 11397 if (Constraint[1] == 'v') { 11398 RC = &AMDGPU::VGPR_32RegClass; 11399 } else if (Constraint[1] == 's') { 11400 RC = &AMDGPU::SGPR_32RegClass; 11401 } else if (Constraint[1] == 'a') { 11402 RC = &AMDGPU::AGPR_32RegClass; 11403 } 11404 11405 if (RC) { 11406 uint32_t Idx; 11407 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11408 if (!Failed && Idx < RC->getNumRegs()) 11409 return std::make_pair(RC->getRegister(Idx), RC); 11410 } 11411 } 11412 11413 // FIXME: Returns VS_32 for physical SGPR constraints 11414 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11415 } 11416 11417 static bool isImmConstraint(StringRef Constraint) { 11418 if (Constraint.size() == 1) { 11419 switch (Constraint[0]) { 11420 default: break; 11421 case 'I': 11422 case 'J': 11423 case 'A': 11424 case 'B': 11425 case 'C': 11426 return true; 11427 } 11428 } else if (Constraint == "DA" || 11429 Constraint == "DB") { 11430 return true; 11431 } 11432 return false; 11433 } 11434 11435 SITargetLowering::ConstraintType 11436 SITargetLowering::getConstraintType(StringRef Constraint) const { 11437 if (Constraint.size() == 1) { 11438 switch (Constraint[0]) { 11439 default: break; 11440 case 's': 11441 case 'v': 11442 case 'a': 11443 return C_RegisterClass; 11444 } 11445 } 11446 if (isImmConstraint(Constraint)) { 11447 return C_Other; 11448 } 11449 return TargetLowering::getConstraintType(Constraint); 11450 } 11451 11452 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11453 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11454 Val = Val & maskTrailingOnes<uint64_t>(Size); 11455 } 11456 return Val; 11457 } 11458 11459 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11460 std::string &Constraint, 11461 std::vector<SDValue> &Ops, 11462 SelectionDAG &DAG) const { 11463 if (isImmConstraint(Constraint)) { 11464 uint64_t Val; 11465 if (getAsmOperandConstVal(Op, Val) && 11466 checkAsmConstraintVal(Op, Constraint, Val)) { 11467 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11468 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11469 } 11470 } else { 11471 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11472 } 11473 } 11474 11475 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11476 unsigned Size = Op.getScalarValueSizeInBits(); 11477 if (Size > 64) 11478 return false; 11479 11480 if (Size == 16 && !Subtarget->has16BitInsts()) 11481 return false; 11482 11483 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11484 Val = C->getSExtValue(); 11485 return true; 11486 } 11487 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11488 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11489 return true; 11490 } 11491 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11492 if (Size != 16 || Op.getNumOperands() != 2) 11493 return false; 11494 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11495 return false; 11496 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11497 Val = C->getSExtValue(); 11498 return true; 11499 } 11500 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11501 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11502 return true; 11503 } 11504 } 11505 11506 return false; 11507 } 11508 11509 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11510 const std::string &Constraint, 11511 uint64_t Val) const { 11512 if (Constraint.size() == 1) { 11513 switch (Constraint[0]) { 11514 case 'I': 11515 return AMDGPU::isInlinableIntLiteral(Val); 11516 case 'J': 11517 return isInt<16>(Val); 11518 case 'A': 11519 return checkAsmConstraintValA(Op, Val); 11520 case 'B': 11521 return isInt<32>(Val); 11522 case 'C': 11523 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11524 AMDGPU::isInlinableIntLiteral(Val); 11525 default: 11526 break; 11527 } 11528 } else if (Constraint.size() == 2) { 11529 if (Constraint == "DA") { 11530 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11531 int64_t LoBits = static_cast<int32_t>(Val); 11532 return checkAsmConstraintValA(Op, HiBits, 32) && 11533 checkAsmConstraintValA(Op, LoBits, 32); 11534 } 11535 if (Constraint == "DB") { 11536 return true; 11537 } 11538 } 11539 llvm_unreachable("Invalid asm constraint"); 11540 } 11541 11542 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11543 uint64_t Val, 11544 unsigned MaxSize) const { 11545 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11546 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11547 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11548 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11549 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11550 return true; 11551 } 11552 return false; 11553 } 11554 11555 // Figure out which registers should be reserved for stack access. Only after 11556 // the function is legalized do we know all of the non-spill stack objects or if 11557 // calls are present. 11558 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11559 MachineRegisterInfo &MRI = MF.getRegInfo(); 11560 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11561 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11562 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11563 11564 if (Info->isEntryFunction()) { 11565 // Callable functions have fixed registers used for stack access. 11566 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11567 } 11568 11569 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11570 Info->getStackPtrOffsetReg())); 11571 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11572 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11573 11574 // We need to worry about replacing the default register with itself in case 11575 // of MIR testcases missing the MFI. 11576 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11577 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11578 11579 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11580 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11581 11582 Info->limitOccupancy(MF); 11583 11584 if (ST.isWave32() && !MF.empty()) { 11585 const SIInstrInfo *TII = ST.getInstrInfo(); 11586 for (auto &MBB : MF) { 11587 for (auto &MI : MBB) { 11588 TII->fixImplicitOperands(MI); 11589 } 11590 } 11591 } 11592 11593 TargetLoweringBase::finalizeLowering(MF); 11594 11595 // Allocate a VGPR for future SGPR Spill if 11596 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11597 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11598 if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() && 11599 !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction() && 11600 MF.getFrameInfo().hasStackObjects()) 11601 Info->reserveVGPRforSGPRSpills(MF); 11602 } 11603 11604 void SITargetLowering::computeKnownBitsForFrameIndex( 11605 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11606 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11607 11608 // Set the high bits to zero based on the maximum allowed scratch size per 11609 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11610 // calculation won't overflow, so assume the sign bit is never set. 11611 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11612 } 11613 11614 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11615 KnownBits &Known, unsigned Dim) { 11616 unsigned MaxValue = 11617 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11618 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11619 } 11620 11621 void SITargetLowering::computeKnownBitsForTargetInstr( 11622 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11623 const MachineRegisterInfo &MRI, unsigned Depth) const { 11624 const MachineInstr *MI = MRI.getVRegDef(R); 11625 switch (MI->getOpcode()) { 11626 case AMDGPU::G_INTRINSIC: { 11627 switch (MI->getIntrinsicID()) { 11628 case Intrinsic::amdgcn_workitem_id_x: 11629 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11630 break; 11631 case Intrinsic::amdgcn_workitem_id_y: 11632 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11633 break; 11634 case Intrinsic::amdgcn_workitem_id_z: 11635 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11636 break; 11637 case Intrinsic::amdgcn_mbcnt_lo: 11638 case Intrinsic::amdgcn_mbcnt_hi: { 11639 // These return at most the wavefront size - 1. 11640 unsigned Size = MRI.getType(R).getSizeInBits(); 11641 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11642 break; 11643 } 11644 case Intrinsic::amdgcn_groupstaticsize: { 11645 // We can report everything over the maximum size as 0. We can't report 11646 // based on the actual size because we don't know if it's accurate or not 11647 // at any given point. 11648 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11649 break; 11650 } 11651 } 11652 break; 11653 } 11654 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 11655 Known.Zero.setHighBits(24); 11656 break; 11657 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 11658 Known.Zero.setHighBits(16); 11659 break; 11660 } 11661 } 11662 11663 Align SITargetLowering::computeKnownAlignForTargetInstr( 11664 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11665 unsigned Depth) const { 11666 const MachineInstr *MI = MRI.getVRegDef(R); 11667 switch (MI->getOpcode()) { 11668 case AMDGPU::G_INTRINSIC: 11669 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11670 // FIXME: Can this move to generic code? What about the case where the call 11671 // site specifies a lower alignment? 11672 Intrinsic::ID IID = MI->getIntrinsicID(); 11673 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11674 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11675 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11676 return *RetAlign; 11677 return Align(1); 11678 } 11679 default: 11680 return Align(1); 11681 } 11682 } 11683 11684 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11685 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11686 const Align CacheLineAlign = Align(64); 11687 11688 // Pre-GFX10 target did not benefit from loop alignment 11689 if (!ML || DisableLoopAlignment || 11690 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11691 getSubtarget()->hasInstFwdPrefetchBug()) 11692 return PrefAlign; 11693 11694 // On GFX10 I$ is 4 x 64 bytes cache lines. 11695 // By default prefetcher keeps one cache line behind and reads two ahead. 11696 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11697 // behind and one ahead. 11698 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11699 // If loop fits 64 bytes it always spans no more than two cache lines and 11700 // does not need an alignment. 11701 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11702 // Else if loop is less or equal 192 bytes we need two lines behind. 11703 11704 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11705 const MachineBasicBlock *Header = ML->getHeader(); 11706 if (Header->getAlignment() != PrefAlign) 11707 return Header->getAlignment(); // Already processed. 11708 11709 unsigned LoopSize = 0; 11710 for (const MachineBasicBlock *MBB : ML->blocks()) { 11711 // If inner loop block is aligned assume in average half of the alignment 11712 // size to be added as nops. 11713 if (MBB != Header) 11714 LoopSize += MBB->getAlignment().value() / 2; 11715 11716 for (const MachineInstr &MI : *MBB) { 11717 LoopSize += TII->getInstSizeInBytes(MI); 11718 if (LoopSize > 192) 11719 return PrefAlign; 11720 } 11721 } 11722 11723 if (LoopSize <= 64) 11724 return PrefAlign; 11725 11726 if (LoopSize <= 128) 11727 return CacheLineAlign; 11728 11729 // If any of parent loops is surrounded by prefetch instructions do not 11730 // insert new for inner loop, which would reset parent's settings. 11731 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11732 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11733 auto I = Exit->getFirstNonDebugInstr(); 11734 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11735 return CacheLineAlign; 11736 } 11737 } 11738 11739 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11740 MachineBasicBlock *Exit = ML->getExitBlock(); 11741 11742 if (Pre && Exit) { 11743 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11744 TII->get(AMDGPU::S_INST_PREFETCH)) 11745 .addImm(1); // prefetch 2 lines behind PC 11746 11747 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11748 TII->get(AMDGPU::S_INST_PREFETCH)) 11749 .addImm(2); // prefetch 1 line behind PC 11750 } 11751 11752 return CacheLineAlign; 11753 } 11754 11755 LLVM_ATTRIBUTE_UNUSED 11756 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11757 assert(N->getOpcode() == ISD::CopyFromReg); 11758 do { 11759 // Follow the chain until we find an INLINEASM node. 11760 N = N->getOperand(0).getNode(); 11761 if (N->getOpcode() == ISD::INLINEASM || 11762 N->getOpcode() == ISD::INLINEASM_BR) 11763 return true; 11764 } while (N->getOpcode() == ISD::CopyFromReg); 11765 return false; 11766 } 11767 11768 bool SITargetLowering::isSDNodeSourceOfDivergence( 11769 const SDNode *N, FunctionLoweringInfo *FLI, 11770 LegacyDivergenceAnalysis *KDA) const { 11771 switch (N->getOpcode()) { 11772 case ISD::CopyFromReg: { 11773 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11774 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11775 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11776 Register Reg = R->getReg(); 11777 11778 // FIXME: Why does this need to consider isLiveIn? 11779 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11780 return !TRI->isSGPRReg(MRI, Reg); 11781 11782 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11783 return KDA->isDivergent(V); 11784 11785 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11786 return !TRI->isSGPRReg(MRI, Reg); 11787 } 11788 case ISD::LOAD: { 11789 const LoadSDNode *L = cast<LoadSDNode>(N); 11790 unsigned AS = L->getAddressSpace(); 11791 // A flat load may access private memory. 11792 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11793 } 11794 case ISD::CALLSEQ_END: 11795 return true; 11796 case ISD::INTRINSIC_WO_CHAIN: 11797 return AMDGPU::isIntrinsicSourceOfDivergence( 11798 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11799 case ISD::INTRINSIC_W_CHAIN: 11800 return AMDGPU::isIntrinsicSourceOfDivergence( 11801 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11802 } 11803 return false; 11804 } 11805 11806 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11807 EVT VT) const { 11808 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11809 case MVT::f32: 11810 return hasFP32Denormals(DAG.getMachineFunction()); 11811 case MVT::f64: 11812 case MVT::f16: 11813 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11814 default: 11815 return false; 11816 } 11817 } 11818 11819 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11820 const SelectionDAG &DAG, 11821 bool SNaN, 11822 unsigned Depth) const { 11823 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11824 const MachineFunction &MF = DAG.getMachineFunction(); 11825 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11826 11827 if (Info->getMode().DX10Clamp) 11828 return true; // Clamped to 0. 11829 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11830 } 11831 11832 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11833 SNaN, Depth); 11834 } 11835 11836 // Global FP atomic instructions have a hardcoded FP mode and do not support 11837 // FP32 denormals, and only support v2f16 denormals. 11838 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 11839 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 11840 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 11841 if (&Flt == &APFloat::IEEEsingle()) 11842 return DenormMode == DenormalMode::getPreserveSign(); 11843 return DenormMode == DenormalMode::getIEEE(); 11844 } 11845 11846 TargetLowering::AtomicExpansionKind 11847 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11848 switch (RMW->getOperation()) { 11849 case AtomicRMWInst::FAdd: { 11850 Type *Ty = RMW->getType(); 11851 11852 // We don't have a way to support 16-bit atomics now, so just leave them 11853 // as-is. 11854 if (Ty->isHalfTy()) 11855 return AtomicExpansionKind::None; 11856 11857 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 11858 return AtomicExpansionKind::CmpXChg; 11859 11860 // TODO: Do have these for flat. Older targets also had them for buffers. 11861 unsigned AS = RMW->getPointerAddressSpace(); 11862 11863 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 11864 Subtarget->hasAtomicFaddInsts()) { 11865 if (!fpModeMatchesGlobalFPAtomicMode(RMW) || 11866 RMW->getFunction()->getFnAttribute("amdgpu-unsafe-fp-atomics") 11867 .getValueAsString() != "true") 11868 return AtomicExpansionKind::CmpXChg; 11869 11870 if (Subtarget->hasGFX90AInsts()) 11871 return (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) ? 11872 AtomicExpansionKind::CmpXChg : AtomicExpansionKind::None; 11873 11874 if (!Subtarget->hasGFX90AInsts() && AS != AMDGPUAS::GLOBAL_ADDRESS) 11875 return AtomicExpansionKind::CmpXChg; 11876 11877 return RMW->use_empty() ? AtomicExpansionKind::None : 11878 AtomicExpansionKind::CmpXChg; 11879 } 11880 11881 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 11882 // to round-to-nearest-even. 11883 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 11884 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) { 11885 return (Ty->isDoubleTy() && !fpModeMatchesGlobalFPAtomicMode(RMW)) ? 11886 AtomicExpansionKind::CmpXChg : AtomicExpansionKind::None; 11887 } 11888 11889 return AtomicExpansionKind::CmpXChg; 11890 } 11891 default: 11892 break; 11893 } 11894 11895 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11896 } 11897 11898 const TargetRegisterClass * 11899 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11900 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11901 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11902 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11903 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11904 : &AMDGPU::SReg_32RegClass; 11905 if (!TRI->isSGPRClass(RC) && !isDivergent) 11906 return TRI->getEquivalentSGPRClass(RC); 11907 else if (TRI->isSGPRClass(RC) && isDivergent) 11908 return TRI->getEquivalentVGPRClass(RC); 11909 11910 return RC; 11911 } 11912 11913 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11914 // uniform values (as produced by the mask results of control flow intrinsics) 11915 // used outside of divergent blocks. The phi users need to also be treated as 11916 // always uniform. 11917 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11918 unsigned WaveSize) { 11919 // FIXME: We asssume we never cast the mask results of a control flow 11920 // intrinsic. 11921 // Early exit if the type won't be consistent as a compile time hack. 11922 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11923 if (!IT || IT->getBitWidth() != WaveSize) 11924 return false; 11925 11926 if (!isa<Instruction>(V)) 11927 return false; 11928 if (!Visited.insert(V).second) 11929 return false; 11930 bool Result = false; 11931 for (auto U : V->users()) { 11932 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11933 if (V == U->getOperand(1)) { 11934 switch (Intrinsic->getIntrinsicID()) { 11935 default: 11936 Result = false; 11937 break; 11938 case Intrinsic::amdgcn_if_break: 11939 case Intrinsic::amdgcn_if: 11940 case Intrinsic::amdgcn_else: 11941 Result = true; 11942 break; 11943 } 11944 } 11945 if (V == U->getOperand(0)) { 11946 switch (Intrinsic->getIntrinsicID()) { 11947 default: 11948 Result = false; 11949 break; 11950 case Intrinsic::amdgcn_end_cf: 11951 case Intrinsic::amdgcn_loop: 11952 Result = true; 11953 break; 11954 } 11955 } 11956 } else { 11957 Result = hasCFUser(U, Visited, WaveSize); 11958 } 11959 if (Result) 11960 break; 11961 } 11962 return Result; 11963 } 11964 11965 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11966 const Value *V) const { 11967 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11968 if (CI->isInlineAsm()) { 11969 // FIXME: This cannot give a correct answer. This should only trigger in 11970 // the case where inline asm returns mixed SGPR and VGPR results, used 11971 // outside the defining block. We don't have a specific result to 11972 // consider, so this assumes if any value is SGPR, the overall register 11973 // also needs to be SGPR. 11974 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11975 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11976 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11977 for (auto &TC : TargetConstraints) { 11978 if (TC.Type == InlineAsm::isOutput) { 11979 ComputeConstraintToUse(TC, SDValue()); 11980 unsigned AssignedReg; 11981 const TargetRegisterClass *RC; 11982 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11983 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11984 if (RC) { 11985 MachineRegisterInfo &MRI = MF.getRegInfo(); 11986 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11987 return true; 11988 else if (SIRI->isSGPRClass(RC)) 11989 return true; 11990 } 11991 } 11992 } 11993 } 11994 } 11995 SmallPtrSet<const Value *, 16> Visited; 11996 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11997 } 11998 11999 std::pair<int, MVT> 12000 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12001 Type *Ty) const { 12002 auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12003 auto Size = DL.getTypeSizeInBits(Ty); 12004 // Maximum load or store can handle 8 dwords for scalar and 4 for 12005 // vector ALU. Let's assume anything above 8 dwords is expensive 12006 // even if legal. 12007 if (Size <= 256) 12008 return Cost; 12009 12010 Cost.first = (Size + 255) / 256; 12011 return Cost; 12012 } 12013