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 #if defined(_MSC_VER) || defined(__MINGW32__) 15 // Provide M_PI. 16 #define _USE_MATH_DEFINES 17 #endif 18 19 #include "SIISelLowering.h" 20 #include "AMDGPU.h" 21 #include "AMDGPUSubtarget.h" 22 #include "AMDGPUTargetMachine.h" 23 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 24 #include "SIDefines.h" 25 #include "SIInstrInfo.h" 26 #include "SIMachineFunctionInfo.h" 27 #include "SIRegisterInfo.h" 28 #include "Utils/AMDGPUBaseInfo.h" 29 #include "llvm/ADT/APFloat.h" 30 #include "llvm/ADT/APInt.h" 31 #include "llvm/ADT/ArrayRef.h" 32 #include "llvm/ADT/BitVector.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/ADT/Twine.h" 38 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 39 #include "llvm/CodeGen/Analysis.h" 40 #include "llvm/CodeGen/CallingConvLower.h" 41 #include "llvm/CodeGen/DAGCombine.h" 42 #include "llvm/CodeGen/ISDOpcodes.h" 43 #include "llvm/CodeGen/MachineBasicBlock.h" 44 #include "llvm/CodeGen/MachineFrameInfo.h" 45 #include "llvm/CodeGen/MachineFunction.h" 46 #include "llvm/CodeGen/MachineInstr.h" 47 #include "llvm/CodeGen/MachineInstrBuilder.h" 48 #include "llvm/CodeGen/MachineLoopInfo.h" 49 #include "llvm/CodeGen/MachineMemOperand.h" 50 #include "llvm/CodeGen/MachineModuleInfo.h" 51 #include "llvm/CodeGen/MachineOperand.h" 52 #include "llvm/CodeGen/MachineRegisterInfo.h" 53 #include "llvm/CodeGen/SelectionDAG.h" 54 #include "llvm/CodeGen/SelectionDAGNodes.h" 55 #include "llvm/CodeGen/TargetCallingConv.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/Constants.h" 59 #include "llvm/IR/DataLayout.h" 60 #include "llvm/IR/DebugLoc.h" 61 #include "llvm/IR/DerivedTypes.h" 62 #include "llvm/IR/DiagnosticInfo.h" 63 #include "llvm/IR/Function.h" 64 #include "llvm/IR/GlobalValue.h" 65 #include "llvm/IR/InstrTypes.h" 66 #include "llvm/IR/Instruction.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/IntrinsicInst.h" 69 #include "llvm/IR/Type.h" 70 #include "llvm/Support/Casting.h" 71 #include "llvm/Support/CodeGen.h" 72 #include "llvm/Support/CommandLine.h" 73 #include "llvm/Support/Compiler.h" 74 #include "llvm/Support/ErrorHandling.h" 75 #include "llvm/Support/KnownBits.h" 76 #include "llvm/Support/MachineValueType.h" 77 #include "llvm/Support/MathExtras.h" 78 #include "llvm/Target/TargetOptions.h" 79 #include <cassert> 80 #include <cmath> 81 #include <cstdint> 82 #include <iterator> 83 #include <tuple> 84 #include <utility> 85 #include <vector> 86 87 using namespace llvm; 88 89 #define DEBUG_TYPE "si-lower" 90 91 STATISTIC(NumTailCalls, "Number of tail calls"); 92 93 static cl::opt<bool> DisableLoopAlignment( 94 "amdgpu-disable-loop-alignment", 95 cl::desc("Do not align and prefetch loops"), 96 cl::init(false)); 97 98 static cl::opt<bool> VGPRReserveforSGPRSpill( 99 "amdgpu-reserve-vgpr-for-sgpr-spill", 100 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 101 102 static bool hasFP32Denormals(const MachineFunction &MF) { 103 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 104 return Info->getMode().allFP32Denormals(); 105 } 106 107 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 108 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 109 return Info->getMode().allFP64FP16Denormals(); 110 } 111 112 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 113 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 114 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 115 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 116 return AMDGPU::SGPR0 + Reg; 117 } 118 } 119 llvm_unreachable("Cannot allocate sgpr"); 120 } 121 122 SITargetLowering::SITargetLowering(const TargetMachine &TM, 123 const GCNSubtarget &STI) 124 : AMDGPUTargetLowering(TM, STI), 125 Subtarget(&STI) { 126 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 127 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 128 129 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 130 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 131 132 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 133 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 134 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 135 136 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 137 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 138 139 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 140 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 141 142 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 143 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 144 145 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 146 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 147 148 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 149 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 150 151 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 152 addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass); 153 154 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 155 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 156 157 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 158 addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass); 159 160 if (Subtarget->has16BitInsts()) { 161 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 162 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 163 164 // Unless there are also VOP3P operations, not operations are really legal. 165 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 166 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 167 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 168 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 169 } 170 171 if (Subtarget->hasMAIInsts()) { 172 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 173 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 174 } 175 176 computeRegisterProperties(Subtarget->getRegisterInfo()); 177 178 // The boolean content concept here is too inflexible. Compares only ever 179 // really produce a 1-bit result. Any copy/extend from these will turn into a 180 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 181 // it's what most targets use. 182 setBooleanContents(ZeroOrOneBooleanContent); 183 setBooleanVectorContents(ZeroOrOneBooleanContent); 184 185 // We need to custom lower vector stores from local memory 186 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 187 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 188 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 189 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 190 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 191 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 192 setOperationAction(ISD::LOAD, MVT::i1, Custom); 193 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 194 195 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 196 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 197 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 198 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 199 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 200 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 201 setOperationAction(ISD::STORE, MVT::i1, Custom); 202 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 203 204 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 205 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 206 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 207 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 208 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 209 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 210 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 211 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 212 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 213 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 214 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 215 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 216 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 217 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 218 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 219 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 220 221 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 222 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 223 224 setOperationAction(ISD::SELECT, MVT::i1, Promote); 225 setOperationAction(ISD::SELECT, MVT::i64, Custom); 226 setOperationAction(ISD::SELECT, MVT::f64, Promote); 227 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 228 229 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 230 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 231 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 232 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 233 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 234 235 setOperationAction(ISD::SETCC, MVT::i1, Promote); 236 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 237 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 238 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 239 240 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 241 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 242 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 243 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 244 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 245 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 246 247 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 248 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 249 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 250 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 251 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 252 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 253 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 254 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 255 256 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 257 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 258 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 259 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 260 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 261 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 262 263 setOperationAction(ISD::UADDO, MVT::i32, Legal); 264 setOperationAction(ISD::USUBO, MVT::i32, Legal); 265 266 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 267 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 268 269 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 270 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 271 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 272 273 #if 0 274 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 275 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 276 #endif 277 278 // We only support LOAD/STORE and vector manipulation ops for vectors 279 // with > 4 elements. 280 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 281 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 282 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 283 MVT::v32i32, MVT::v32f32 }) { 284 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 285 switch (Op) { 286 case ISD::LOAD: 287 case ISD::STORE: 288 case ISD::BUILD_VECTOR: 289 case ISD::BITCAST: 290 case ISD::EXTRACT_VECTOR_ELT: 291 case ISD::INSERT_VECTOR_ELT: 292 case ISD::INSERT_SUBVECTOR: 293 case ISD::EXTRACT_SUBVECTOR: 294 case ISD::SCALAR_TO_VECTOR: 295 break; 296 case ISD::CONCAT_VECTORS: 297 setOperationAction(Op, VT, Custom); 298 break; 299 default: 300 setOperationAction(Op, VT, Expand); 301 break; 302 } 303 } 304 } 305 306 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 307 308 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 309 // is expanded to avoid having two separate loops in case the index is a VGPR. 310 311 // Most operations are naturally 32-bit vector operations. We only support 312 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 313 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 314 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 315 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 316 317 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 318 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 319 320 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 321 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 322 323 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 324 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 325 } 326 327 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 328 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 329 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 330 331 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 332 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 333 334 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 335 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 336 337 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 338 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 339 } 340 341 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 342 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 343 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 344 345 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 346 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 347 348 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 349 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 350 351 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 352 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 353 } 354 355 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 356 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 357 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 358 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 359 360 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 361 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 362 363 // Avoid stack access for these. 364 // TODO: Generalize to more vector types. 365 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 366 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 367 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 368 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 369 370 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 371 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 372 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 373 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 374 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 375 376 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 377 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 378 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 379 380 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 381 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 382 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 383 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 384 385 // Deal with vec3 vector operations when widened to vec4. 386 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 387 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 388 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 389 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 390 391 // Deal with vec5 vector operations when widened to vec8. 392 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 393 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 394 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 395 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 396 397 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 398 // and output demarshalling 399 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 400 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 401 402 // We can't return success/failure, only the old value, 403 // let LLVM add the comparison 404 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 405 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 406 407 if (Subtarget->hasFlatAddressSpace()) { 408 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 409 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 410 } 411 412 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 413 414 // FIXME: This should be narrowed to i32, but that only happens if i64 is 415 // illegal. 416 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 417 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 418 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 419 420 // On SI this is s_memtime and s_memrealtime on VI. 421 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 422 setOperationAction(ISD::TRAP, MVT::Other, Custom); 423 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 424 425 if (Subtarget->has16BitInsts()) { 426 setOperationAction(ISD::FPOW, MVT::f16, Promote); 427 setOperationAction(ISD::FLOG, MVT::f16, Custom); 428 setOperationAction(ISD::FEXP, MVT::f16, Custom); 429 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 430 } 431 432 // v_mad_f32 does not support denormals. We report it as unconditionally 433 // legal, and the context where it is formed will disallow it when fp32 434 // denormals are enabled. 435 setOperationAction(ISD::FMAD, MVT::f32, Legal); 436 437 if (!Subtarget->hasBFI()) { 438 // fcopysign can be done in a single instruction with BFI. 439 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 440 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 441 } 442 443 if (!Subtarget->hasBCNT(32)) 444 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 445 446 if (!Subtarget->hasBCNT(64)) 447 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 448 449 if (Subtarget->hasFFBH()) 450 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 451 452 if (Subtarget->hasFFBL()) 453 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 454 455 // We only really have 32-bit BFE instructions (and 16-bit on VI). 456 // 457 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 458 // effort to match them now. We want this to be false for i64 cases when the 459 // extraction isn't restricted to the upper or lower half. Ideally we would 460 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 461 // span the midpoint are probably relatively rare, so don't worry about them 462 // for now. 463 if (Subtarget->hasBFE()) 464 setHasExtractBitsInsn(true); 465 466 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 467 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 468 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 469 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 470 471 472 // These are really only legal for ieee_mode functions. We should be avoiding 473 // them for functions that don't have ieee_mode enabled, so just say they are 474 // legal. 475 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 476 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 477 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 478 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 479 480 481 if (Subtarget->haveRoundOpsF64()) { 482 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 483 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 484 setOperationAction(ISD::FRINT, MVT::f64, Legal); 485 } else { 486 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 487 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 488 setOperationAction(ISD::FRINT, MVT::f64, Custom); 489 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 490 } 491 492 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 493 494 setOperationAction(ISD::FSIN, MVT::f32, Custom); 495 setOperationAction(ISD::FCOS, MVT::f32, Custom); 496 setOperationAction(ISD::FDIV, MVT::f32, Custom); 497 setOperationAction(ISD::FDIV, MVT::f64, Custom); 498 499 if (Subtarget->has16BitInsts()) { 500 setOperationAction(ISD::Constant, MVT::i16, Legal); 501 502 setOperationAction(ISD::SMIN, MVT::i16, Legal); 503 setOperationAction(ISD::SMAX, MVT::i16, Legal); 504 505 setOperationAction(ISD::UMIN, MVT::i16, Legal); 506 setOperationAction(ISD::UMAX, MVT::i16, Legal); 507 508 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 509 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 510 511 setOperationAction(ISD::ROTR, MVT::i16, Promote); 512 setOperationAction(ISD::ROTL, MVT::i16, Promote); 513 514 setOperationAction(ISD::SDIV, MVT::i16, Promote); 515 setOperationAction(ISD::UDIV, MVT::i16, Promote); 516 setOperationAction(ISD::SREM, MVT::i16, Promote); 517 setOperationAction(ISD::UREM, MVT::i16, Promote); 518 519 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 520 521 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 522 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 523 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 524 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 525 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 526 527 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 528 529 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 530 531 setOperationAction(ISD::LOAD, MVT::i16, Custom); 532 533 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 534 535 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 536 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 537 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 538 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 539 540 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 541 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 542 543 // F16 - Constant Actions. 544 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 545 546 // F16 - Load/Store Actions. 547 setOperationAction(ISD::LOAD, MVT::f16, Promote); 548 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 549 setOperationAction(ISD::STORE, MVT::f16, Promote); 550 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 551 552 // F16 - VOP1 Actions. 553 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 554 setOperationAction(ISD::FCOS, MVT::f16, Custom); 555 setOperationAction(ISD::FSIN, MVT::f16, Custom); 556 557 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 558 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 559 560 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 561 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 562 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 563 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 564 setOperationAction(ISD::FROUND, MVT::f16, Custom); 565 566 // F16 - VOP2 Actions. 567 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 568 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 569 570 setOperationAction(ISD::FDIV, MVT::f16, Custom); 571 572 // F16 - VOP3 Actions. 573 setOperationAction(ISD::FMA, MVT::f16, Legal); 574 if (STI.hasMadF16()) 575 setOperationAction(ISD::FMAD, MVT::f16, Legal); 576 577 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 578 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 579 switch (Op) { 580 case ISD::LOAD: 581 case ISD::STORE: 582 case ISD::BUILD_VECTOR: 583 case ISD::BITCAST: 584 case ISD::EXTRACT_VECTOR_ELT: 585 case ISD::INSERT_VECTOR_ELT: 586 case ISD::INSERT_SUBVECTOR: 587 case ISD::EXTRACT_SUBVECTOR: 588 case ISD::SCALAR_TO_VECTOR: 589 break; 590 case ISD::CONCAT_VECTORS: 591 setOperationAction(Op, VT, Custom); 592 break; 593 default: 594 setOperationAction(Op, VT, Expand); 595 break; 596 } 597 } 598 } 599 600 // v_perm_b32 can handle either of these. 601 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 602 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 603 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 604 605 // XXX - Do these do anything? Vector constants turn into build_vector. 606 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 607 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 608 609 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 610 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 611 612 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 613 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 614 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 615 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 616 617 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 618 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 619 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 620 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 621 622 setOperationAction(ISD::AND, MVT::v2i16, Promote); 623 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 624 setOperationAction(ISD::OR, MVT::v2i16, Promote); 625 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 626 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 627 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 628 629 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 630 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 631 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 632 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 633 634 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 635 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 636 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 637 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 638 639 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 640 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 641 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 642 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 643 644 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 645 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 646 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 647 648 if (!Subtarget->hasVOP3PInsts()) { 649 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 650 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 651 } 652 653 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 654 // This isn't really legal, but this avoids the legalizer unrolling it (and 655 // allows matching fneg (fabs x) patterns) 656 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 657 658 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 659 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 660 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 661 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 662 663 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 664 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 665 666 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 667 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 668 } 669 670 if (Subtarget->hasVOP3PInsts()) { 671 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 672 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 673 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 674 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 675 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 676 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 677 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 678 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 679 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 680 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 681 682 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 683 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 684 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 685 686 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 687 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 688 689 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 690 691 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 692 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 693 694 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 695 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 696 697 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 698 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 699 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 700 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 701 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 702 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 703 704 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 705 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 706 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 707 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 708 709 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 710 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 711 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 712 713 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 714 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 715 716 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 717 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 718 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 719 720 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 721 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 722 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 723 } 724 725 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 726 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 727 728 if (Subtarget->has16BitInsts()) { 729 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 730 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 731 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 732 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 733 } else { 734 // Legalization hack. 735 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 736 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 737 738 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 739 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 740 } 741 742 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 743 setOperationAction(ISD::SELECT, VT, Custom); 744 } 745 746 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 747 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 748 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 749 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 750 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 751 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 752 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 753 754 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 755 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 756 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 757 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 758 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 759 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 760 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 761 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 762 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 763 764 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 765 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 766 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 767 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 768 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 769 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 770 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 771 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 772 773 setTargetDAGCombine(ISD::ADD); 774 setTargetDAGCombine(ISD::ADDCARRY); 775 setTargetDAGCombine(ISD::SUB); 776 setTargetDAGCombine(ISD::SUBCARRY); 777 setTargetDAGCombine(ISD::FADD); 778 setTargetDAGCombine(ISD::FSUB); 779 setTargetDAGCombine(ISD::FMINNUM); 780 setTargetDAGCombine(ISD::FMAXNUM); 781 setTargetDAGCombine(ISD::FMINNUM_IEEE); 782 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 783 setTargetDAGCombine(ISD::FMA); 784 setTargetDAGCombine(ISD::SMIN); 785 setTargetDAGCombine(ISD::SMAX); 786 setTargetDAGCombine(ISD::UMIN); 787 setTargetDAGCombine(ISD::UMAX); 788 setTargetDAGCombine(ISD::SETCC); 789 setTargetDAGCombine(ISD::AND); 790 setTargetDAGCombine(ISD::OR); 791 setTargetDAGCombine(ISD::XOR); 792 setTargetDAGCombine(ISD::SINT_TO_FP); 793 setTargetDAGCombine(ISD::UINT_TO_FP); 794 setTargetDAGCombine(ISD::FCANONICALIZE); 795 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 796 setTargetDAGCombine(ISD::ZERO_EXTEND); 797 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 798 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 799 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 800 801 // All memory operations. Some folding on the pointer operand is done to help 802 // matching the constant offsets in the addressing modes. 803 setTargetDAGCombine(ISD::LOAD); 804 setTargetDAGCombine(ISD::STORE); 805 setTargetDAGCombine(ISD::ATOMIC_LOAD); 806 setTargetDAGCombine(ISD::ATOMIC_STORE); 807 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 808 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 809 setTargetDAGCombine(ISD::ATOMIC_SWAP); 810 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 811 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 812 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 813 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 814 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 815 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 816 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 817 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 818 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 819 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 820 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 821 822 setSchedulingPreference(Sched::RegPressure); 823 } 824 825 const GCNSubtarget *SITargetLowering::getSubtarget() const { 826 return Subtarget; 827 } 828 829 //===----------------------------------------------------------------------===// 830 // TargetLowering queries 831 //===----------------------------------------------------------------------===// 832 833 // v_mad_mix* support a conversion from f16 to f32. 834 // 835 // There is only one special case when denormals are enabled we don't currently, 836 // where this is OK to use. 837 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 838 EVT DestVT, EVT SrcVT) const { 839 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 840 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 841 DestVT.getScalarType() == MVT::f32 && 842 SrcVT.getScalarType() == MVT::f16 && 843 // TODO: This probably only requires no input flushing? 844 !hasFP32Denormals(DAG.getMachineFunction()); 845 } 846 847 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 848 // SI has some legal vector types, but no legal vector operations. Say no 849 // shuffles are legal in order to prefer scalarizing some vector operations. 850 return false; 851 } 852 853 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 854 CallingConv::ID CC, 855 EVT VT) const { 856 if (CC == CallingConv::AMDGPU_KERNEL) 857 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 858 859 if (VT.isVector()) { 860 EVT ScalarVT = VT.getScalarType(); 861 unsigned Size = ScalarVT.getSizeInBits(); 862 if (Size == 32) 863 return ScalarVT.getSimpleVT(); 864 865 if (Size > 32) 866 return MVT::i32; 867 868 if (Size == 16 && Subtarget->has16BitInsts()) 869 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 870 } else if (VT.getSizeInBits() > 32) 871 return MVT::i32; 872 873 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 874 } 875 876 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 877 CallingConv::ID CC, 878 EVT VT) const { 879 if (CC == CallingConv::AMDGPU_KERNEL) 880 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 881 882 if (VT.isVector()) { 883 unsigned NumElts = VT.getVectorNumElements(); 884 EVT ScalarVT = VT.getScalarType(); 885 unsigned Size = ScalarVT.getSizeInBits(); 886 887 if (Size == 32) 888 return NumElts; 889 890 if (Size > 32) 891 return NumElts * ((Size + 31) / 32); 892 893 if (Size == 16 && Subtarget->has16BitInsts()) 894 return (NumElts + 1) / 2; 895 } else if (VT.getSizeInBits() > 32) 896 return (VT.getSizeInBits() + 31) / 32; 897 898 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 899 } 900 901 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 902 LLVMContext &Context, CallingConv::ID CC, 903 EVT VT, EVT &IntermediateVT, 904 unsigned &NumIntermediates, MVT &RegisterVT) const { 905 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 906 unsigned NumElts = VT.getVectorNumElements(); 907 EVT ScalarVT = VT.getScalarType(); 908 unsigned Size = ScalarVT.getSizeInBits(); 909 if (Size == 32) { 910 RegisterVT = ScalarVT.getSimpleVT(); 911 IntermediateVT = RegisterVT; 912 NumIntermediates = NumElts; 913 return NumIntermediates; 914 } 915 916 if (Size > 32) { 917 RegisterVT = MVT::i32; 918 IntermediateVT = RegisterVT; 919 NumIntermediates = NumElts * ((Size + 31) / 32); 920 return NumIntermediates; 921 } 922 923 // FIXME: We should fix the ABI to be the same on targets without 16-bit 924 // support, but unless we can properly handle 3-vectors, it will be still be 925 // inconsistent. 926 if (Size == 16 && Subtarget->has16BitInsts()) { 927 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 928 IntermediateVT = RegisterVT; 929 NumIntermediates = (NumElts + 1) / 2; 930 return NumIntermediates; 931 } 932 } 933 934 return TargetLowering::getVectorTypeBreakdownForCallingConv( 935 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 936 } 937 938 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 939 assert(DMaskLanes != 0); 940 941 if (auto *VT = dyn_cast<VectorType>(Ty)) { 942 unsigned NumElts = std::min(DMaskLanes, 943 static_cast<unsigned>(VT->getNumElements())); 944 return EVT::getVectorVT(Ty->getContext(), 945 EVT::getEVT(VT->getElementType()), 946 NumElts); 947 } 948 949 return EVT::getEVT(Ty); 950 } 951 952 // Peek through TFE struct returns to only use the data size. 953 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 954 auto *ST = dyn_cast<StructType>(Ty); 955 if (!ST) 956 return memVTFromImageData(Ty, DMaskLanes); 957 958 // Some intrinsics return an aggregate type - special case to work out the 959 // correct memVT. 960 // 961 // Only limited forms of aggregate type currently expected. 962 if (ST->getNumContainedTypes() != 2 || 963 !ST->getContainedType(1)->isIntegerTy(32)) 964 return EVT(); 965 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 966 } 967 968 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 969 const CallInst &CI, 970 MachineFunction &MF, 971 unsigned IntrID) const { 972 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 973 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 974 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 975 (Intrinsic::ID)IntrID); 976 if (Attr.hasFnAttribute(Attribute::ReadNone)) 977 return false; 978 979 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 980 981 if (RsrcIntr->IsImage) { 982 Info.ptrVal = MFI->getImagePSV( 983 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 984 CI.getArgOperand(RsrcIntr->RsrcArg)); 985 Info.align.reset(); 986 } else { 987 Info.ptrVal = MFI->getBufferPSV( 988 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 989 CI.getArgOperand(RsrcIntr->RsrcArg)); 990 } 991 992 Info.flags = MachineMemOperand::MODereferenceable; 993 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 994 unsigned DMaskLanes = 4; 995 996 if (RsrcIntr->IsImage) { 997 const AMDGPU::ImageDimIntrinsicInfo *Intr 998 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 999 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1000 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1001 1002 if (!BaseOpcode->Gather4) { 1003 // If this isn't a gather, we may have excess loaded elements in the 1004 // IR type. Check the dmask for the real number of elements loaded. 1005 unsigned DMask 1006 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1007 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1008 } 1009 1010 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1011 } else 1012 Info.memVT = EVT::getEVT(CI.getType()); 1013 1014 // FIXME: What does alignment mean for an image? 1015 Info.opc = ISD::INTRINSIC_W_CHAIN; 1016 Info.flags |= MachineMemOperand::MOLoad; 1017 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1018 Info.opc = ISD::INTRINSIC_VOID; 1019 1020 Type *DataTy = CI.getArgOperand(0)->getType(); 1021 if (RsrcIntr->IsImage) { 1022 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1023 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1024 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1025 } else 1026 Info.memVT = EVT::getEVT(DataTy); 1027 1028 Info.flags |= MachineMemOperand::MOStore; 1029 } else { 1030 // Atomic 1031 Info.opc = ISD::INTRINSIC_W_CHAIN; 1032 Info.memVT = MVT::getVT(CI.getType()); 1033 Info.flags = MachineMemOperand::MOLoad | 1034 MachineMemOperand::MOStore | 1035 MachineMemOperand::MODereferenceable; 1036 1037 // XXX - Should this be volatile without known ordering? 1038 Info.flags |= MachineMemOperand::MOVolatile; 1039 } 1040 return true; 1041 } 1042 1043 switch (IntrID) { 1044 case Intrinsic::amdgcn_atomic_inc: 1045 case Intrinsic::amdgcn_atomic_dec: 1046 case Intrinsic::amdgcn_ds_ordered_add: 1047 case Intrinsic::amdgcn_ds_ordered_swap: 1048 case Intrinsic::amdgcn_ds_fadd: 1049 case Intrinsic::amdgcn_ds_fmin: 1050 case Intrinsic::amdgcn_ds_fmax: { 1051 Info.opc = ISD::INTRINSIC_W_CHAIN; 1052 Info.memVT = MVT::getVT(CI.getType()); 1053 Info.ptrVal = CI.getOperand(0); 1054 Info.align.reset(); 1055 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1056 1057 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1058 if (!Vol->isZero()) 1059 Info.flags |= MachineMemOperand::MOVolatile; 1060 1061 return true; 1062 } 1063 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1064 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1065 1066 Info.opc = ISD::INTRINSIC_VOID; 1067 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1068 Info.ptrVal = MFI->getBufferPSV( 1069 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1070 CI.getArgOperand(1)); 1071 Info.align.reset(); 1072 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1073 1074 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1075 if (!Vol || !Vol->isZero()) 1076 Info.flags |= MachineMemOperand::MOVolatile; 1077 1078 return true; 1079 } 1080 case Intrinsic::amdgcn_global_atomic_fadd: { 1081 Info.opc = ISD::INTRINSIC_VOID; 1082 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 1083 ->getPointerElementType()); 1084 Info.ptrVal = CI.getOperand(0); 1085 Info.align.reset(); 1086 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1087 1088 return true; 1089 } 1090 case Intrinsic::amdgcn_ds_append: 1091 case Intrinsic::amdgcn_ds_consume: { 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(1)); 1099 if (!Vol->isZero()) 1100 Info.flags |= MachineMemOperand::MOVolatile; 1101 1102 return true; 1103 } 1104 case Intrinsic::amdgcn_ds_gws_init: 1105 case Intrinsic::amdgcn_ds_gws_barrier: 1106 case Intrinsic::amdgcn_ds_gws_sema_v: 1107 case Intrinsic::amdgcn_ds_gws_sema_br: 1108 case Intrinsic::amdgcn_ds_gws_sema_p: 1109 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1110 Info.opc = ISD::INTRINSIC_VOID; 1111 1112 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1113 Info.ptrVal = 1114 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1115 1116 // This is an abstract access, but we need to specify a type and size. 1117 Info.memVT = MVT::i32; 1118 Info.size = 4; 1119 Info.align = Align(4); 1120 1121 Info.flags = MachineMemOperand::MOStore; 1122 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1123 Info.flags = MachineMemOperand::MOLoad; 1124 return true; 1125 } 1126 default: 1127 return false; 1128 } 1129 } 1130 1131 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1132 SmallVectorImpl<Value*> &Ops, 1133 Type *&AccessTy) const { 1134 switch (II->getIntrinsicID()) { 1135 case Intrinsic::amdgcn_atomic_inc: 1136 case Intrinsic::amdgcn_atomic_dec: 1137 case Intrinsic::amdgcn_ds_ordered_add: 1138 case Intrinsic::amdgcn_ds_ordered_swap: 1139 case Intrinsic::amdgcn_ds_fadd: 1140 case Intrinsic::amdgcn_ds_fmin: 1141 case Intrinsic::amdgcn_ds_fmax: { 1142 Value *Ptr = II->getArgOperand(0); 1143 AccessTy = II->getType(); 1144 Ops.push_back(Ptr); 1145 return true; 1146 } 1147 default: 1148 return false; 1149 } 1150 } 1151 1152 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1153 if (!Subtarget->hasFlatInstOffsets()) { 1154 // Flat instructions do not have offsets, and only have the register 1155 // address. 1156 return AM.BaseOffs == 0 && AM.Scale == 0; 1157 } 1158 1159 return AM.Scale == 0 && 1160 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1161 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1162 /*Signed=*/false)); 1163 } 1164 1165 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1166 if (Subtarget->hasFlatGlobalInsts()) 1167 return AM.Scale == 0 && 1168 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1169 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1170 /*Signed=*/true)); 1171 1172 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1173 // Assume the we will use FLAT for all global memory accesses 1174 // on VI. 1175 // FIXME: This assumption is currently wrong. On VI we still use 1176 // MUBUF instructions for the r + i addressing mode. As currently 1177 // implemented, the MUBUF instructions only work on buffer < 4GB. 1178 // It may be possible to support > 4GB buffers with MUBUF instructions, 1179 // by setting the stride value in the resource descriptor which would 1180 // increase the size limit to (stride * 4GB). However, this is risky, 1181 // because it has never been validated. 1182 return isLegalFlatAddressingMode(AM); 1183 } 1184 1185 return isLegalMUBUFAddressingMode(AM); 1186 } 1187 1188 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1189 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1190 // additionally can do r + r + i with addr64. 32-bit has more addressing 1191 // mode options. Depending on the resource constant, it can also do 1192 // (i64 r0) + (i32 r1) * (i14 i). 1193 // 1194 // Private arrays end up using a scratch buffer most of the time, so also 1195 // assume those use MUBUF instructions. Scratch loads / stores are currently 1196 // implemented as mubuf instructions with offen bit set, so slightly 1197 // different than the normal addr64. 1198 if (!isUInt<12>(AM.BaseOffs)) 1199 return false; 1200 1201 // FIXME: Since we can split immediate into soffset and immediate offset, 1202 // would it make sense to allow any immediate? 1203 1204 switch (AM.Scale) { 1205 case 0: // r + i or just i, depending on HasBaseReg. 1206 return true; 1207 case 1: 1208 return true; // We have r + r or r + i. 1209 case 2: 1210 if (AM.HasBaseReg) { 1211 // Reject 2 * r + r. 1212 return false; 1213 } 1214 1215 // Allow 2 * r as r + r 1216 // Or 2 * r + i is allowed as r + r + i. 1217 return true; 1218 default: // Don't allow n * r 1219 return false; 1220 } 1221 } 1222 1223 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1224 const AddrMode &AM, Type *Ty, 1225 unsigned AS, Instruction *I) const { 1226 // No global is ever allowed as a base. 1227 if (AM.BaseGV) 1228 return false; 1229 1230 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1231 return isLegalGlobalAddressingMode(AM); 1232 1233 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1234 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1235 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1236 // If the offset isn't a multiple of 4, it probably isn't going to be 1237 // correctly aligned. 1238 // FIXME: Can we get the real alignment here? 1239 if (AM.BaseOffs % 4 != 0) 1240 return isLegalMUBUFAddressingMode(AM); 1241 1242 // There are no SMRD extloads, so if we have to do a small type access we 1243 // will use a MUBUF load. 1244 // FIXME?: We also need to do this if unaligned, but we don't know the 1245 // alignment here. 1246 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1247 return isLegalGlobalAddressingMode(AM); 1248 1249 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1250 // SMRD instructions have an 8-bit, dword offset on SI. 1251 if (!isUInt<8>(AM.BaseOffs / 4)) 1252 return false; 1253 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1254 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1255 // in 8-bits, it can use a smaller encoding. 1256 if (!isUInt<32>(AM.BaseOffs / 4)) 1257 return false; 1258 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1259 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1260 if (!isUInt<20>(AM.BaseOffs)) 1261 return false; 1262 } else 1263 llvm_unreachable("unhandled generation"); 1264 1265 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1266 return true; 1267 1268 if (AM.Scale == 1 && AM.HasBaseReg) 1269 return true; 1270 1271 return false; 1272 1273 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1274 return isLegalMUBUFAddressingMode(AM); 1275 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1276 AS == AMDGPUAS::REGION_ADDRESS) { 1277 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1278 // field. 1279 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1280 // an 8-bit dword offset but we don't know the alignment here. 1281 if (!isUInt<16>(AM.BaseOffs)) 1282 return false; 1283 1284 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1285 return true; 1286 1287 if (AM.Scale == 1 && AM.HasBaseReg) 1288 return true; 1289 1290 return false; 1291 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1292 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1293 // For an unknown address space, this usually means that this is for some 1294 // reason being used for pure arithmetic, and not based on some addressing 1295 // computation. We don't have instructions that compute pointers with any 1296 // addressing modes, so treat them as having no offset like flat 1297 // instructions. 1298 return isLegalFlatAddressingMode(AM); 1299 } 1300 1301 // Assume a user alias of global for unknown address spaces. 1302 return isLegalGlobalAddressingMode(AM); 1303 } 1304 1305 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1306 const SelectionDAG &DAG) const { 1307 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1308 return (MemVT.getSizeInBits() <= 4 * 32); 1309 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1310 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1311 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1312 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1313 return (MemVT.getSizeInBits() <= 2 * 32); 1314 } 1315 return true; 1316 } 1317 1318 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1319 unsigned Size, unsigned AddrSpace, unsigned Align, 1320 MachineMemOperand::Flags Flags, bool *IsFast) const { 1321 if (IsFast) 1322 *IsFast = false; 1323 1324 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1325 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1326 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1327 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1328 // with adjacent offsets. 1329 bool AlignedBy4 = (Align % 4 == 0); 1330 if (IsFast) 1331 *IsFast = AlignedBy4; 1332 1333 return AlignedBy4; 1334 } 1335 1336 // FIXME: We have to be conservative here and assume that flat operations 1337 // will access scratch. If we had access to the IR function, then we 1338 // could determine if any private memory was used in the function. 1339 if (!Subtarget->hasUnalignedScratchAccess() && 1340 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1341 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1342 bool AlignedBy4 = Align >= 4; 1343 if (IsFast) 1344 *IsFast = AlignedBy4; 1345 1346 return AlignedBy4; 1347 } 1348 1349 if (Subtarget->hasUnalignedBufferAccess()) { 1350 // If we have an uniform constant load, it still requires using a slow 1351 // buffer instruction if unaligned. 1352 if (IsFast) { 1353 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1354 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1355 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1356 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1357 Align >= 4 : Align != 2; 1358 } 1359 1360 return true; 1361 } 1362 1363 // Smaller than dword value must be aligned. 1364 if (Size < 32) 1365 return false; 1366 1367 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1368 // byte-address are ignored, thus forcing Dword alignment. 1369 // This applies to private, global, and constant memory. 1370 if (IsFast) 1371 *IsFast = true; 1372 1373 return Size >= 32 && Align >= 4; 1374 } 1375 1376 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1377 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1378 bool *IsFast) const { 1379 if (IsFast) 1380 *IsFast = false; 1381 1382 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1383 // which isn't a simple VT. 1384 // Until MVT is extended to handle this, simply check for the size and 1385 // rely on the condition below: allow accesses if the size is a multiple of 4. 1386 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1387 VT.getStoreSize() > 16)) { 1388 return false; 1389 } 1390 1391 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1392 Align, Flags, IsFast); 1393 } 1394 1395 EVT SITargetLowering::getOptimalMemOpType( 1396 const MemOp &Op, const AttributeList &FuncAttributes) const { 1397 // FIXME: Should account for address space here. 1398 1399 // The default fallback uses the private pointer size as a guess for a type to 1400 // use. Make sure we switch these to 64-bit accesses. 1401 1402 if (Op.size() >= 16 && 1403 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1404 return MVT::v4i32; 1405 1406 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1407 return MVT::v2i32; 1408 1409 // Use the default. 1410 return MVT::Other; 1411 } 1412 1413 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1414 unsigned DestAS) const { 1415 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1416 } 1417 1418 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1419 const MemSDNode *MemNode = cast<MemSDNode>(N); 1420 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1421 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1422 return I && I->getMetadata("amdgpu.noclobber"); 1423 } 1424 1425 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1426 unsigned DestAS) const { 1427 // Flat -> private/local is a simple truncate. 1428 // Flat -> global is no-op 1429 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1430 return true; 1431 1432 return isNoopAddrSpaceCast(SrcAS, DestAS); 1433 } 1434 1435 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1436 const MemSDNode *MemNode = cast<MemSDNode>(N); 1437 1438 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1439 } 1440 1441 TargetLoweringBase::LegalizeTypeAction 1442 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1443 int NumElts = VT.getVectorNumElements(); 1444 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1445 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1446 return TargetLoweringBase::getPreferredVectorAction(VT); 1447 } 1448 1449 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1450 Type *Ty) const { 1451 // FIXME: Could be smarter if called for vector constants. 1452 return true; 1453 } 1454 1455 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1456 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1457 switch (Op) { 1458 case ISD::LOAD: 1459 case ISD::STORE: 1460 1461 // These operations are done with 32-bit instructions anyway. 1462 case ISD::AND: 1463 case ISD::OR: 1464 case ISD::XOR: 1465 case ISD::SELECT: 1466 // TODO: Extensions? 1467 return true; 1468 default: 1469 return false; 1470 } 1471 } 1472 1473 // SimplifySetCC uses this function to determine whether or not it should 1474 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1475 if (VT == MVT::i1 && Op == ISD::SETCC) 1476 return false; 1477 1478 return TargetLowering::isTypeDesirableForOp(Op, VT); 1479 } 1480 1481 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1482 const SDLoc &SL, 1483 SDValue Chain, 1484 uint64_t Offset) const { 1485 const DataLayout &DL = DAG.getDataLayout(); 1486 MachineFunction &MF = DAG.getMachineFunction(); 1487 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1488 1489 const ArgDescriptor *InputPtrReg; 1490 const TargetRegisterClass *RC; 1491 1492 std::tie(InputPtrReg, RC) 1493 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1494 1495 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1496 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1497 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1498 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1499 1500 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1501 } 1502 1503 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1504 const SDLoc &SL) const { 1505 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1506 FIRST_IMPLICIT); 1507 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1508 } 1509 1510 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1511 const SDLoc &SL, SDValue Val, 1512 bool Signed, 1513 const ISD::InputArg *Arg) const { 1514 // First, if it is a widened vector, narrow it. 1515 if (VT.isVector() && 1516 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1517 EVT NarrowedVT = 1518 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1519 VT.getVectorNumElements()); 1520 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1521 DAG.getConstant(0, SL, MVT::i32)); 1522 } 1523 1524 // Then convert the vector elements or scalar value. 1525 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1526 VT.bitsLT(MemVT)) { 1527 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1528 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1529 } 1530 1531 if (MemVT.isFloatingPoint()) 1532 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1533 else if (Signed) 1534 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1535 else 1536 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1537 1538 return Val; 1539 } 1540 1541 SDValue SITargetLowering::lowerKernargMemParameter( 1542 SelectionDAG &DAG, EVT VT, EVT MemVT, 1543 const SDLoc &SL, SDValue Chain, 1544 uint64_t Offset, unsigned Align, bool Signed, 1545 const ISD::InputArg *Arg) const { 1546 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1547 1548 // Try to avoid using an extload by loading earlier than the argument address, 1549 // and extracting the relevant bits. The load should hopefully be merged with 1550 // the previous argument. 1551 if (MemVT.getStoreSize() < 4 && Align < 4) { 1552 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1553 int64_t AlignDownOffset = alignDown(Offset, 4); 1554 int64_t OffsetDiff = Offset - AlignDownOffset; 1555 1556 EVT IntVT = MemVT.changeTypeToInteger(); 1557 1558 // TODO: If we passed in the base kernel offset we could have a better 1559 // alignment than 4, but we don't really need it. 1560 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1561 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1562 MachineMemOperand::MODereferenceable | 1563 MachineMemOperand::MOInvariant); 1564 1565 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1566 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1567 1568 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1569 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1570 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1571 1572 1573 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1574 } 1575 1576 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1577 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1578 MachineMemOperand::MODereferenceable | 1579 MachineMemOperand::MOInvariant); 1580 1581 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1582 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1583 } 1584 1585 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1586 const SDLoc &SL, SDValue Chain, 1587 const ISD::InputArg &Arg) const { 1588 MachineFunction &MF = DAG.getMachineFunction(); 1589 MachineFrameInfo &MFI = MF.getFrameInfo(); 1590 1591 if (Arg.Flags.isByVal()) { 1592 unsigned Size = Arg.Flags.getByValSize(); 1593 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1594 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1595 } 1596 1597 unsigned ArgOffset = VA.getLocMemOffset(); 1598 unsigned ArgSize = VA.getValVT().getStoreSize(); 1599 1600 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1601 1602 // Create load nodes to retrieve arguments from the stack. 1603 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1604 SDValue ArgValue; 1605 1606 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1607 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1608 MVT MemVT = VA.getValVT(); 1609 1610 switch (VA.getLocInfo()) { 1611 default: 1612 break; 1613 case CCValAssign::BCvt: 1614 MemVT = VA.getLocVT(); 1615 break; 1616 case CCValAssign::SExt: 1617 ExtType = ISD::SEXTLOAD; 1618 break; 1619 case CCValAssign::ZExt: 1620 ExtType = ISD::ZEXTLOAD; 1621 break; 1622 case CCValAssign::AExt: 1623 ExtType = ISD::EXTLOAD; 1624 break; 1625 } 1626 1627 ArgValue = DAG.getExtLoad( 1628 ExtType, SL, VA.getLocVT(), Chain, FIN, 1629 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1630 MemVT); 1631 return ArgValue; 1632 } 1633 1634 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1635 const SIMachineFunctionInfo &MFI, 1636 EVT VT, 1637 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1638 const ArgDescriptor *Reg; 1639 const TargetRegisterClass *RC; 1640 1641 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1642 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1643 } 1644 1645 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1646 CallingConv::ID CallConv, 1647 ArrayRef<ISD::InputArg> Ins, 1648 BitVector &Skipped, 1649 FunctionType *FType, 1650 SIMachineFunctionInfo *Info) { 1651 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1652 const ISD::InputArg *Arg = &Ins[I]; 1653 1654 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1655 "vector type argument should have been split"); 1656 1657 // First check if it's a PS input addr. 1658 if (CallConv == CallingConv::AMDGPU_PS && 1659 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1660 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1661 1662 // Inconveniently only the first part of the split is marked as isSplit, 1663 // so skip to the end. We only want to increment PSInputNum once for the 1664 // entire split argument. 1665 if (Arg->Flags.isSplit()) { 1666 while (!Arg->Flags.isSplitEnd()) { 1667 assert((!Arg->VT.isVector() || 1668 Arg->VT.getScalarSizeInBits() == 16) && 1669 "unexpected vector split in ps argument type"); 1670 if (!SkipArg) 1671 Splits.push_back(*Arg); 1672 Arg = &Ins[++I]; 1673 } 1674 } 1675 1676 if (SkipArg) { 1677 // We can safely skip PS inputs. 1678 Skipped.set(Arg->getOrigArgIndex()); 1679 ++PSInputNum; 1680 continue; 1681 } 1682 1683 Info->markPSInputAllocated(PSInputNum); 1684 if (Arg->Used) 1685 Info->markPSInputEnabled(PSInputNum); 1686 1687 ++PSInputNum; 1688 } 1689 1690 Splits.push_back(*Arg); 1691 } 1692 } 1693 1694 // Allocate special inputs passed in VGPRs. 1695 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1696 MachineFunction &MF, 1697 const SIRegisterInfo &TRI, 1698 SIMachineFunctionInfo &Info) const { 1699 const LLT S32 = LLT::scalar(32); 1700 MachineRegisterInfo &MRI = MF.getRegInfo(); 1701 1702 if (Info.hasWorkItemIDX()) { 1703 Register Reg = AMDGPU::VGPR0; 1704 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1705 1706 CCInfo.AllocateReg(Reg); 1707 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1708 } 1709 1710 if (Info.hasWorkItemIDY()) { 1711 Register Reg = AMDGPU::VGPR1; 1712 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1713 1714 CCInfo.AllocateReg(Reg); 1715 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1716 } 1717 1718 if (Info.hasWorkItemIDZ()) { 1719 Register Reg = AMDGPU::VGPR2; 1720 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1721 1722 CCInfo.AllocateReg(Reg); 1723 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1724 } 1725 } 1726 1727 // Try to allocate a VGPR at the end of the argument list, or if no argument 1728 // VGPRs are left allocating a stack slot. 1729 // If \p Mask is is given it indicates bitfield position in the register. 1730 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1731 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1732 ArgDescriptor Arg = ArgDescriptor()) { 1733 if (Arg.isSet()) 1734 return ArgDescriptor::createArg(Arg, Mask); 1735 1736 ArrayRef<MCPhysReg> ArgVGPRs 1737 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1738 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1739 if (RegIdx == ArgVGPRs.size()) { 1740 // Spill to stack required. 1741 int64_t Offset = CCInfo.AllocateStack(4, 4); 1742 1743 return ArgDescriptor::createStack(Offset, Mask); 1744 } 1745 1746 unsigned Reg = ArgVGPRs[RegIdx]; 1747 Reg = CCInfo.AllocateReg(Reg); 1748 assert(Reg != AMDGPU::NoRegister); 1749 1750 MachineFunction &MF = CCInfo.getMachineFunction(); 1751 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1752 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1753 return ArgDescriptor::createRegister(Reg, Mask); 1754 } 1755 1756 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1757 const TargetRegisterClass *RC, 1758 unsigned NumArgRegs) { 1759 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1760 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1761 if (RegIdx == ArgSGPRs.size()) 1762 report_fatal_error("ran out of SGPRs for arguments"); 1763 1764 unsigned Reg = ArgSGPRs[RegIdx]; 1765 Reg = CCInfo.AllocateReg(Reg); 1766 assert(Reg != AMDGPU::NoRegister); 1767 1768 MachineFunction &MF = CCInfo.getMachineFunction(); 1769 MF.addLiveIn(Reg, RC); 1770 return ArgDescriptor::createRegister(Reg); 1771 } 1772 1773 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1774 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1775 } 1776 1777 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1778 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1779 } 1780 1781 /// Allocate implicit function VGPR arguments at the end of allocated user 1782 /// arguments. 1783 void SITargetLowering::allocateSpecialInputVGPRs( 1784 CCState &CCInfo, MachineFunction &MF, 1785 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1786 const unsigned Mask = 0x3ff; 1787 ArgDescriptor Arg; 1788 1789 if (Info.hasWorkItemIDX()) { 1790 Arg = allocateVGPR32Input(CCInfo, Mask); 1791 Info.setWorkItemIDX(Arg); 1792 } 1793 1794 if (Info.hasWorkItemIDY()) { 1795 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1796 Info.setWorkItemIDY(Arg); 1797 } 1798 1799 if (Info.hasWorkItemIDZ()) 1800 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1801 } 1802 1803 /// Allocate implicit function VGPR arguments in fixed registers. 1804 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1805 CCState &CCInfo, MachineFunction &MF, 1806 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1807 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1808 if (!Reg) 1809 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1810 1811 const unsigned Mask = 0x3ff; 1812 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1813 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1814 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1815 } 1816 1817 void SITargetLowering::allocateSpecialInputSGPRs( 1818 CCState &CCInfo, 1819 MachineFunction &MF, 1820 const SIRegisterInfo &TRI, 1821 SIMachineFunctionInfo &Info) const { 1822 auto &ArgInfo = Info.getArgInfo(); 1823 1824 // TODO: Unify handling with private memory pointers. 1825 1826 if (Info.hasDispatchPtr()) 1827 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1828 1829 if (Info.hasQueuePtr()) 1830 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1831 1832 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1833 // constant offset from the kernarg segment. 1834 if (Info.hasImplicitArgPtr()) 1835 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1836 1837 if (Info.hasDispatchID()) 1838 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1839 1840 // flat_scratch_init is not applicable for non-kernel functions. 1841 1842 if (Info.hasWorkGroupIDX()) 1843 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1844 1845 if (Info.hasWorkGroupIDY()) 1846 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1847 1848 if (Info.hasWorkGroupIDZ()) 1849 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1850 } 1851 1852 // Allocate special inputs passed in user SGPRs. 1853 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1854 MachineFunction &MF, 1855 const SIRegisterInfo &TRI, 1856 SIMachineFunctionInfo &Info) const { 1857 if (Info.hasImplicitBufferPtr()) { 1858 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1859 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1860 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1861 } 1862 1863 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1864 if (Info.hasPrivateSegmentBuffer()) { 1865 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1866 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1867 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1868 } 1869 1870 if (Info.hasDispatchPtr()) { 1871 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1872 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1873 CCInfo.AllocateReg(DispatchPtrReg); 1874 } 1875 1876 if (Info.hasQueuePtr()) { 1877 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1878 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1879 CCInfo.AllocateReg(QueuePtrReg); 1880 } 1881 1882 if (Info.hasKernargSegmentPtr()) { 1883 MachineRegisterInfo &MRI = MF.getRegInfo(); 1884 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1885 CCInfo.AllocateReg(InputPtrReg); 1886 1887 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1888 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1889 } 1890 1891 if (Info.hasDispatchID()) { 1892 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1893 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1894 CCInfo.AllocateReg(DispatchIDReg); 1895 } 1896 1897 if (Info.hasFlatScratchInit()) { 1898 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1899 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1900 CCInfo.AllocateReg(FlatScratchInitReg); 1901 } 1902 1903 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1904 // these from the dispatch pointer. 1905 } 1906 1907 // Allocate special input registers that are initialized per-wave. 1908 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1909 MachineFunction &MF, 1910 SIMachineFunctionInfo &Info, 1911 CallingConv::ID CallConv, 1912 bool IsShader) const { 1913 if (Info.hasWorkGroupIDX()) { 1914 unsigned Reg = Info.addWorkGroupIDX(); 1915 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1916 CCInfo.AllocateReg(Reg); 1917 } 1918 1919 if (Info.hasWorkGroupIDY()) { 1920 unsigned Reg = Info.addWorkGroupIDY(); 1921 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1922 CCInfo.AllocateReg(Reg); 1923 } 1924 1925 if (Info.hasWorkGroupIDZ()) { 1926 unsigned Reg = Info.addWorkGroupIDZ(); 1927 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1928 CCInfo.AllocateReg(Reg); 1929 } 1930 1931 if (Info.hasWorkGroupInfo()) { 1932 unsigned Reg = Info.addWorkGroupInfo(); 1933 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1934 CCInfo.AllocateReg(Reg); 1935 } 1936 1937 if (Info.hasPrivateSegmentWaveByteOffset()) { 1938 // Scratch wave offset passed in system SGPR. 1939 unsigned PrivateSegmentWaveByteOffsetReg; 1940 1941 if (IsShader) { 1942 PrivateSegmentWaveByteOffsetReg = 1943 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1944 1945 // This is true if the scratch wave byte offset doesn't have a fixed 1946 // location. 1947 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1948 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1949 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1950 } 1951 } else 1952 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1953 1954 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1955 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1956 } 1957 } 1958 1959 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1960 MachineFunction &MF, 1961 const SIRegisterInfo &TRI, 1962 SIMachineFunctionInfo &Info) { 1963 // Now that we've figured out where the scratch register inputs are, see if 1964 // should reserve the arguments and use them directly. 1965 MachineFrameInfo &MFI = MF.getFrameInfo(); 1966 bool HasStackObjects = MFI.hasStackObjects(); 1967 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 1968 1969 // Record that we know we have non-spill stack objects so we don't need to 1970 // check all stack objects later. 1971 if (HasStackObjects) 1972 Info.setHasNonSpillStackObjects(true); 1973 1974 // Everything live out of a block is spilled with fast regalloc, so it's 1975 // almost certain that spilling will be required. 1976 if (TM.getOptLevel() == CodeGenOpt::None) 1977 HasStackObjects = true; 1978 1979 // For now assume stack access is needed in any callee functions, so we need 1980 // the scratch registers to pass in. 1981 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1982 1983 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 1984 // If we have stack objects, we unquestionably need the private buffer 1985 // resource. For the Code Object V2 ABI, this will be the first 4 user 1986 // SGPR inputs. We can reserve those and use them directly. 1987 1988 Register PrivateSegmentBufferReg = 1989 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 1990 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1991 } else { 1992 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1993 // We tentatively reserve the last registers (skipping the last registers 1994 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 1995 // we'll replace these with the ones immediately after those which were 1996 // really allocated. In the prologue copies will be inserted from the 1997 // argument to these reserved registers. 1998 1999 // Without HSA, relocations are used for the scratch pointer and the 2000 // buffer resource setup is always inserted in the prologue. Scratch wave 2001 // offset is still in an input SGPR. 2002 Info.setScratchRSrcReg(ReservedBufferReg); 2003 } 2004 2005 MachineRegisterInfo &MRI = MF.getRegInfo(); 2006 2007 // For entry functions we have to set up the stack pointer if we use it, 2008 // whereas non-entry functions get this "for free". This means there is no 2009 // intrinsic advantage to using S32 over S34 in cases where we do not have 2010 // calls but do need a frame pointer (i.e. if we are requested to have one 2011 // because frame pointer elimination is disabled). To keep things simple we 2012 // only ever use S32 as the call ABI stack pointer, and so using it does not 2013 // imply we need a separate frame pointer. 2014 // 2015 // Try to use s32 as the SP, but move it if it would interfere with input 2016 // arguments. This won't work with calls though. 2017 // 2018 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2019 // registers. 2020 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2021 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2022 } else { 2023 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2024 2025 if (MFI.hasCalls()) 2026 report_fatal_error("call in graphics shader with too many input SGPRs"); 2027 2028 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2029 if (!MRI.isLiveIn(Reg)) { 2030 Info.setStackPtrOffsetReg(Reg); 2031 break; 2032 } 2033 } 2034 2035 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2036 report_fatal_error("failed to find register for SP"); 2037 } 2038 2039 // hasFP should be accurate for entry functions even before the frame is 2040 // finalized, because it does not rely on the known stack size, only 2041 // properties like whether variable sized objects are present. 2042 if (ST.getFrameLowering()->hasFP(MF)) { 2043 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2044 } 2045 } 2046 2047 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2048 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2049 return !Info->isEntryFunction(); 2050 } 2051 2052 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2053 2054 } 2055 2056 void SITargetLowering::insertCopiesSplitCSR( 2057 MachineBasicBlock *Entry, 2058 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2059 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2060 2061 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2062 if (!IStart) 2063 return; 2064 2065 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2066 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2067 MachineBasicBlock::iterator MBBI = Entry->begin(); 2068 for (const MCPhysReg *I = IStart; *I; ++I) { 2069 const TargetRegisterClass *RC = nullptr; 2070 if (AMDGPU::SReg_64RegClass.contains(*I)) 2071 RC = &AMDGPU::SGPR_64RegClass; 2072 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2073 RC = &AMDGPU::SGPR_32RegClass; 2074 else 2075 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2076 2077 Register NewVR = MRI->createVirtualRegister(RC); 2078 // Create copy from CSR to a virtual register. 2079 Entry->addLiveIn(*I); 2080 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2081 .addReg(*I); 2082 2083 // Insert the copy-back instructions right before the terminator. 2084 for (auto *Exit : Exits) 2085 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2086 TII->get(TargetOpcode::COPY), *I) 2087 .addReg(NewVR); 2088 } 2089 } 2090 2091 SDValue SITargetLowering::LowerFormalArguments( 2092 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2093 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2094 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2095 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2096 2097 MachineFunction &MF = DAG.getMachineFunction(); 2098 const Function &Fn = MF.getFunction(); 2099 FunctionType *FType = MF.getFunction().getFunctionType(); 2100 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2101 2102 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2103 DiagnosticInfoUnsupported NoGraphicsHSA( 2104 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2105 DAG.getContext()->diagnose(NoGraphicsHSA); 2106 return DAG.getEntryNode(); 2107 } 2108 2109 SmallVector<ISD::InputArg, 16> Splits; 2110 SmallVector<CCValAssign, 16> ArgLocs; 2111 BitVector Skipped(Ins.size()); 2112 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2113 *DAG.getContext()); 2114 2115 bool IsShader = AMDGPU::isShader(CallConv); 2116 bool IsKernel = AMDGPU::isKernel(CallConv); 2117 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2118 2119 if (IsShader) { 2120 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2121 2122 // At least one interpolation mode must be enabled or else the GPU will 2123 // hang. 2124 // 2125 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2126 // set PSInputAddr, the user wants to enable some bits after the compilation 2127 // based on run-time states. Since we can't know what the final PSInputEna 2128 // will look like, so we shouldn't do anything here and the user should take 2129 // responsibility for the correct programming. 2130 // 2131 // Otherwise, the following restrictions apply: 2132 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2133 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2134 // enabled too. 2135 if (CallConv == CallingConv::AMDGPU_PS) { 2136 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2137 ((Info->getPSInputAddr() & 0xF) == 0 && 2138 Info->isPSInputAllocated(11))) { 2139 CCInfo.AllocateReg(AMDGPU::VGPR0); 2140 CCInfo.AllocateReg(AMDGPU::VGPR1); 2141 Info->markPSInputAllocated(0); 2142 Info->markPSInputEnabled(0); 2143 } 2144 if (Subtarget->isAmdPalOS()) { 2145 // For isAmdPalOS, the user does not enable some bits after compilation 2146 // based on run-time states; the register values being generated here are 2147 // the final ones set in hardware. Therefore we need to apply the 2148 // workaround to PSInputAddr and PSInputEnable together. (The case where 2149 // a bit is set in PSInputAddr but not PSInputEnable is where the 2150 // frontend set up an input arg for a particular interpolation mode, but 2151 // nothing uses that input arg. Really we should have an earlier pass 2152 // that removes such an arg.) 2153 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2154 if ((PsInputBits & 0x7F) == 0 || 2155 ((PsInputBits & 0xF) == 0 && 2156 (PsInputBits >> 11 & 1))) 2157 Info->markPSInputEnabled( 2158 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2159 } 2160 } 2161 2162 assert(!Info->hasDispatchPtr() && 2163 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2164 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2165 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2166 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2167 !Info->hasWorkItemIDZ()); 2168 } else if (IsKernel) { 2169 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2170 } else { 2171 Splits.append(Ins.begin(), Ins.end()); 2172 } 2173 2174 if (IsEntryFunc) { 2175 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2176 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2177 } else { 2178 // For the fixed ABI, pass workitem IDs in the last argument register. 2179 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2180 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2181 } 2182 2183 if (IsKernel) { 2184 analyzeFormalArgumentsCompute(CCInfo, Ins); 2185 } else { 2186 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2187 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2188 } 2189 2190 SmallVector<SDValue, 16> Chains; 2191 2192 // FIXME: This is the minimum kernel argument alignment. We should improve 2193 // this to the maximum alignment of the arguments. 2194 // 2195 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2196 // kern arg offset. 2197 const unsigned KernelArgBaseAlign = 16; 2198 2199 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2200 const ISD::InputArg &Arg = Ins[i]; 2201 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2202 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2203 continue; 2204 } 2205 2206 CCValAssign &VA = ArgLocs[ArgIdx++]; 2207 MVT VT = VA.getLocVT(); 2208 2209 if (IsEntryFunc && VA.isMemLoc()) { 2210 VT = Ins[i].VT; 2211 EVT MemVT = VA.getLocVT(); 2212 2213 const uint64_t Offset = VA.getLocMemOffset(); 2214 unsigned Align = MinAlign(KernelArgBaseAlign, Offset); 2215 2216 SDValue Arg = lowerKernargMemParameter( 2217 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]); 2218 Chains.push_back(Arg.getValue(1)); 2219 2220 auto *ParamTy = 2221 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2222 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2223 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2224 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2225 // On SI local pointers are just offsets into LDS, so they are always 2226 // less than 16-bits. On CI and newer they could potentially be 2227 // real pointers, so we can't guarantee their size. 2228 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2229 DAG.getValueType(MVT::i16)); 2230 } 2231 2232 InVals.push_back(Arg); 2233 continue; 2234 } else if (!IsEntryFunc && VA.isMemLoc()) { 2235 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2236 InVals.push_back(Val); 2237 if (!Arg.Flags.isByVal()) 2238 Chains.push_back(Val.getValue(1)); 2239 continue; 2240 } 2241 2242 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2243 2244 Register Reg = VA.getLocReg(); 2245 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2246 EVT ValVT = VA.getValVT(); 2247 2248 Reg = MF.addLiveIn(Reg, RC); 2249 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2250 2251 if (Arg.Flags.isSRet()) { 2252 // The return object should be reasonably addressable. 2253 2254 // FIXME: This helps when the return is a real sret. If it is a 2255 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2256 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2257 unsigned NumBits 2258 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2259 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2260 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2261 } 2262 2263 // If this is an 8 or 16-bit value, it is really passed promoted 2264 // to 32 bits. Insert an assert[sz]ext to capture this, then 2265 // truncate to the right size. 2266 switch (VA.getLocInfo()) { 2267 case CCValAssign::Full: 2268 break; 2269 case CCValAssign::BCvt: 2270 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2271 break; 2272 case CCValAssign::SExt: 2273 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2274 DAG.getValueType(ValVT)); 2275 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2276 break; 2277 case CCValAssign::ZExt: 2278 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2279 DAG.getValueType(ValVT)); 2280 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2281 break; 2282 case CCValAssign::AExt: 2283 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2284 break; 2285 default: 2286 llvm_unreachable("Unknown loc info!"); 2287 } 2288 2289 InVals.push_back(Val); 2290 } 2291 2292 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2293 // Special inputs come after user arguments. 2294 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2295 } 2296 2297 // Start adding system SGPRs. 2298 if (IsEntryFunc) { 2299 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2300 } else { 2301 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2302 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2303 } 2304 2305 auto &ArgUsageInfo = 2306 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2307 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2308 2309 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2310 Info->setBytesInStackArgArea(StackArgSize); 2311 2312 return Chains.empty() ? Chain : 2313 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2314 } 2315 2316 // TODO: If return values can't fit in registers, we should return as many as 2317 // possible in registers before passing on stack. 2318 bool SITargetLowering::CanLowerReturn( 2319 CallingConv::ID CallConv, 2320 MachineFunction &MF, bool IsVarArg, 2321 const SmallVectorImpl<ISD::OutputArg> &Outs, 2322 LLVMContext &Context) const { 2323 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2324 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2325 // for shaders. Vector types should be explicitly handled by CC. 2326 if (AMDGPU::isEntryFunctionCC(CallConv)) 2327 return true; 2328 2329 SmallVector<CCValAssign, 16> RVLocs; 2330 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2331 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2332 } 2333 2334 SDValue 2335 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2336 bool isVarArg, 2337 const SmallVectorImpl<ISD::OutputArg> &Outs, 2338 const SmallVectorImpl<SDValue> &OutVals, 2339 const SDLoc &DL, SelectionDAG &DAG) const { 2340 MachineFunction &MF = DAG.getMachineFunction(); 2341 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2342 2343 if (AMDGPU::isKernel(CallConv)) { 2344 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2345 OutVals, DL, DAG); 2346 } 2347 2348 bool IsShader = AMDGPU::isShader(CallConv); 2349 2350 Info->setIfReturnsVoid(Outs.empty()); 2351 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2352 2353 // CCValAssign - represent the assignment of the return value to a location. 2354 SmallVector<CCValAssign, 48> RVLocs; 2355 SmallVector<ISD::OutputArg, 48> Splits; 2356 2357 // CCState - Info about the registers and stack slots. 2358 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2359 *DAG.getContext()); 2360 2361 // Analyze outgoing return values. 2362 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2363 2364 SDValue Flag; 2365 SmallVector<SDValue, 48> RetOps; 2366 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2367 2368 // Add return address for callable functions. 2369 if (!Info->isEntryFunction()) { 2370 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2371 SDValue ReturnAddrReg = CreateLiveInRegister( 2372 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2373 2374 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2375 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2376 MVT::i64); 2377 Chain = 2378 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2379 Flag = Chain.getValue(1); 2380 RetOps.push_back(ReturnAddrVirtualReg); 2381 } 2382 2383 // Copy the result values into the output registers. 2384 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2385 ++I, ++RealRVLocIdx) { 2386 CCValAssign &VA = RVLocs[I]; 2387 assert(VA.isRegLoc() && "Can only return in registers!"); 2388 // TODO: Partially return in registers if return values don't fit. 2389 SDValue Arg = OutVals[RealRVLocIdx]; 2390 2391 // Copied from other backends. 2392 switch (VA.getLocInfo()) { 2393 case CCValAssign::Full: 2394 break; 2395 case CCValAssign::BCvt: 2396 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2397 break; 2398 case CCValAssign::SExt: 2399 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2400 break; 2401 case CCValAssign::ZExt: 2402 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2403 break; 2404 case CCValAssign::AExt: 2405 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2406 break; 2407 default: 2408 llvm_unreachable("Unknown loc info!"); 2409 } 2410 2411 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2412 Flag = Chain.getValue(1); 2413 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2414 } 2415 2416 // FIXME: Does sret work properly? 2417 if (!Info->isEntryFunction()) { 2418 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2419 const MCPhysReg *I = 2420 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2421 if (I) { 2422 for (; *I; ++I) { 2423 if (AMDGPU::SReg_64RegClass.contains(*I)) 2424 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2425 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2426 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2427 else 2428 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2429 } 2430 } 2431 } 2432 2433 // Update chain and glue. 2434 RetOps[0] = Chain; 2435 if (Flag.getNode()) 2436 RetOps.push_back(Flag); 2437 2438 unsigned Opc = AMDGPUISD::ENDPGM; 2439 if (!IsWaveEnd) 2440 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2441 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2442 } 2443 2444 SDValue SITargetLowering::LowerCallResult( 2445 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2446 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2447 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2448 SDValue ThisVal) const { 2449 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2450 2451 // Assign locations to each value returned by this call. 2452 SmallVector<CCValAssign, 16> RVLocs; 2453 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2454 *DAG.getContext()); 2455 CCInfo.AnalyzeCallResult(Ins, RetCC); 2456 2457 // Copy all of the result registers out of their specified physreg. 2458 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2459 CCValAssign VA = RVLocs[i]; 2460 SDValue Val; 2461 2462 if (VA.isRegLoc()) { 2463 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2464 Chain = Val.getValue(1); 2465 InFlag = Val.getValue(2); 2466 } else if (VA.isMemLoc()) { 2467 report_fatal_error("TODO: return values in memory"); 2468 } else 2469 llvm_unreachable("unknown argument location type"); 2470 2471 switch (VA.getLocInfo()) { 2472 case CCValAssign::Full: 2473 break; 2474 case CCValAssign::BCvt: 2475 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2476 break; 2477 case CCValAssign::ZExt: 2478 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2479 DAG.getValueType(VA.getValVT())); 2480 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2481 break; 2482 case CCValAssign::SExt: 2483 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2484 DAG.getValueType(VA.getValVT())); 2485 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2486 break; 2487 case CCValAssign::AExt: 2488 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2489 break; 2490 default: 2491 llvm_unreachable("Unknown loc info!"); 2492 } 2493 2494 InVals.push_back(Val); 2495 } 2496 2497 return Chain; 2498 } 2499 2500 // Add code to pass special inputs required depending on used features separate 2501 // from the explicit user arguments present in the IR. 2502 void SITargetLowering::passSpecialInputs( 2503 CallLoweringInfo &CLI, 2504 CCState &CCInfo, 2505 const SIMachineFunctionInfo &Info, 2506 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2507 SmallVectorImpl<SDValue> &MemOpChains, 2508 SDValue Chain) const { 2509 // If we don't have a call site, this was a call inserted by 2510 // legalization. These can never use special inputs. 2511 if (!CLI.CB) 2512 return; 2513 2514 SelectionDAG &DAG = CLI.DAG; 2515 const SDLoc &DL = CLI.DL; 2516 2517 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2518 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2519 2520 const AMDGPUFunctionArgInfo *CalleeArgInfo 2521 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2522 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2523 auto &ArgUsageInfo = 2524 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2525 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2526 } 2527 2528 // TODO: Unify with private memory register handling. This is complicated by 2529 // the fact that at least in kernels, the input argument is not necessarily 2530 // in the same location as the input. 2531 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2532 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2533 AMDGPUFunctionArgInfo::QUEUE_PTR, 2534 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2535 AMDGPUFunctionArgInfo::DISPATCH_ID, 2536 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2537 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2538 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2539 }; 2540 2541 for (auto InputID : InputRegs) { 2542 const ArgDescriptor *OutgoingArg; 2543 const TargetRegisterClass *ArgRC; 2544 2545 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID); 2546 if (!OutgoingArg) 2547 continue; 2548 2549 const ArgDescriptor *IncomingArg; 2550 const TargetRegisterClass *IncomingArgRC; 2551 std::tie(IncomingArg, IncomingArgRC) 2552 = CallerArgInfo.getPreloadedValue(InputID); 2553 assert(IncomingArgRC == ArgRC); 2554 2555 // All special arguments are ints for now. 2556 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2557 SDValue InputReg; 2558 2559 if (IncomingArg) { 2560 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2561 } else { 2562 // The implicit arg ptr is special because it doesn't have a corresponding 2563 // input for kernels, and is computed from the kernarg segment pointer. 2564 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2565 InputReg = getImplicitArgPtr(DAG, DL); 2566 } 2567 2568 if (OutgoingArg->isRegister()) { 2569 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2570 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2571 report_fatal_error("failed to allocate implicit input argument"); 2572 } else { 2573 unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4); 2574 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2575 SpecialArgOffset); 2576 MemOpChains.push_back(ArgStore); 2577 } 2578 } 2579 2580 // Pack workitem IDs into a single register or pass it as is if already 2581 // packed. 2582 const ArgDescriptor *OutgoingArg; 2583 const TargetRegisterClass *ArgRC; 2584 2585 std::tie(OutgoingArg, ArgRC) = 2586 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2587 if (!OutgoingArg) 2588 std::tie(OutgoingArg, ArgRC) = 2589 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2590 if (!OutgoingArg) 2591 std::tie(OutgoingArg, ArgRC) = 2592 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2593 if (!OutgoingArg) 2594 return; 2595 2596 const ArgDescriptor *IncomingArgX 2597 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first; 2598 const ArgDescriptor *IncomingArgY 2599 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first; 2600 const ArgDescriptor *IncomingArgZ 2601 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first; 2602 2603 SDValue InputReg; 2604 SDLoc SL; 2605 2606 // If incoming ids are not packed we need to pack them. 2607 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2608 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2609 2610 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2611 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2612 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2613 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2614 InputReg = InputReg.getNode() ? 2615 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2616 } 2617 2618 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2619 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2620 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2621 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2622 InputReg = InputReg.getNode() ? 2623 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2624 } 2625 2626 if (!InputReg.getNode()) { 2627 // Workitem ids are already packed, any of present incoming arguments 2628 // will carry all required fields. 2629 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2630 IncomingArgX ? *IncomingArgX : 2631 IncomingArgY ? *IncomingArgY : 2632 *IncomingArgZ, ~0u); 2633 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2634 } 2635 2636 if (OutgoingArg->isRegister()) { 2637 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2638 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2639 } else { 2640 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4); 2641 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2642 SpecialArgOffset); 2643 MemOpChains.push_back(ArgStore); 2644 } 2645 } 2646 2647 static bool canGuaranteeTCO(CallingConv::ID CC) { 2648 return CC == CallingConv::Fast; 2649 } 2650 2651 /// Return true if we might ever do TCO for calls with this calling convention. 2652 static bool mayTailCallThisCC(CallingConv::ID CC) { 2653 switch (CC) { 2654 case CallingConv::C: 2655 return true; 2656 default: 2657 return canGuaranteeTCO(CC); 2658 } 2659 } 2660 2661 bool SITargetLowering::isEligibleForTailCallOptimization( 2662 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2663 const SmallVectorImpl<ISD::OutputArg> &Outs, 2664 const SmallVectorImpl<SDValue> &OutVals, 2665 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2666 if (!mayTailCallThisCC(CalleeCC)) 2667 return false; 2668 2669 MachineFunction &MF = DAG.getMachineFunction(); 2670 const Function &CallerF = MF.getFunction(); 2671 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2672 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2673 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2674 2675 // Kernels aren't callable, and don't have a live in return address so it 2676 // doesn't make sense to do a tail call with entry functions. 2677 if (!CallerPreserved) 2678 return false; 2679 2680 bool CCMatch = CallerCC == CalleeCC; 2681 2682 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2683 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2684 return true; 2685 return false; 2686 } 2687 2688 // TODO: Can we handle var args? 2689 if (IsVarArg) 2690 return false; 2691 2692 for (const Argument &Arg : CallerF.args()) { 2693 if (Arg.hasByValAttr()) 2694 return false; 2695 } 2696 2697 LLVMContext &Ctx = *DAG.getContext(); 2698 2699 // Check that the call results are passed in the same way. 2700 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2701 CCAssignFnForCall(CalleeCC, IsVarArg), 2702 CCAssignFnForCall(CallerCC, IsVarArg))) 2703 return false; 2704 2705 // The callee has to preserve all registers the caller needs to preserve. 2706 if (!CCMatch) { 2707 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2708 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2709 return false; 2710 } 2711 2712 // Nothing more to check if the callee is taking no arguments. 2713 if (Outs.empty()) 2714 return true; 2715 2716 SmallVector<CCValAssign, 16> ArgLocs; 2717 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2718 2719 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2720 2721 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2722 // If the stack arguments for this call do not fit into our own save area then 2723 // the call cannot be made tail. 2724 // TODO: Is this really necessary? 2725 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2726 return false; 2727 2728 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2729 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2730 } 2731 2732 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2733 if (!CI->isTailCall()) 2734 return false; 2735 2736 const Function *ParentFn = CI->getParent()->getParent(); 2737 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2738 return false; 2739 return true; 2740 } 2741 2742 // The wave scratch offset register is used as the global base pointer. 2743 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2744 SmallVectorImpl<SDValue> &InVals) const { 2745 SelectionDAG &DAG = CLI.DAG; 2746 const SDLoc &DL = CLI.DL; 2747 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2748 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2749 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2750 SDValue Chain = CLI.Chain; 2751 SDValue Callee = CLI.Callee; 2752 bool &IsTailCall = CLI.IsTailCall; 2753 CallingConv::ID CallConv = CLI.CallConv; 2754 bool IsVarArg = CLI.IsVarArg; 2755 bool IsSibCall = false; 2756 bool IsThisReturn = false; 2757 MachineFunction &MF = DAG.getMachineFunction(); 2758 2759 if (Callee.isUndef() || isNullConstant(Callee)) { 2760 if (!CLI.IsTailCall) { 2761 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2762 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2763 } 2764 2765 return Chain; 2766 } 2767 2768 if (IsVarArg) { 2769 return lowerUnhandledCall(CLI, InVals, 2770 "unsupported call to variadic function "); 2771 } 2772 2773 if (!CLI.CB) 2774 report_fatal_error("unsupported libcall legalization"); 2775 2776 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2777 !CLI.CB->getCalledFunction()) { 2778 return lowerUnhandledCall(CLI, InVals, 2779 "unsupported indirect call to function "); 2780 } 2781 2782 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2783 return lowerUnhandledCall(CLI, InVals, 2784 "unsupported required tail call to function "); 2785 } 2786 2787 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2788 // Note the issue is with the CC of the calling function, not of the call 2789 // itself. 2790 return lowerUnhandledCall(CLI, InVals, 2791 "unsupported call from graphics shader of function "); 2792 } 2793 2794 if (IsTailCall) { 2795 IsTailCall = isEligibleForTailCallOptimization( 2796 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2797 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2798 report_fatal_error("failed to perform tail call elimination on a call " 2799 "site marked musttail"); 2800 } 2801 2802 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2803 2804 // A sibling call is one where we're under the usual C ABI and not planning 2805 // to change that but can still do a tail call: 2806 if (!TailCallOpt && IsTailCall) 2807 IsSibCall = true; 2808 2809 if (IsTailCall) 2810 ++NumTailCalls; 2811 } 2812 2813 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2814 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2815 SmallVector<SDValue, 8> MemOpChains; 2816 2817 // Analyze operands of the call, assigning locations to each operand. 2818 SmallVector<CCValAssign, 16> ArgLocs; 2819 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2820 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2821 2822 if (AMDGPUTargetMachine::EnableFixedFunctionABI) { 2823 // With a fixed ABI, allocate fixed registers before user arguments. 2824 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2825 } 2826 2827 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2828 2829 // Get a count of how many bytes are to be pushed on the stack. 2830 unsigned NumBytes = CCInfo.getNextStackOffset(); 2831 2832 if (IsSibCall) { 2833 // Since we're not changing the ABI to make this a tail call, the memory 2834 // operands are already available in the caller's incoming argument space. 2835 NumBytes = 0; 2836 } 2837 2838 // FPDiff is the byte offset of the call's argument area from the callee's. 2839 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2840 // by this amount for a tail call. In a sibling call it must be 0 because the 2841 // caller will deallocate the entire stack and the callee still expects its 2842 // arguments to begin at SP+0. Completely unused for non-tail calls. 2843 int32_t FPDiff = 0; 2844 MachineFrameInfo &MFI = MF.getFrameInfo(); 2845 2846 // Adjust the stack pointer for the new arguments... 2847 // These operations are automatically eliminated by the prolog/epilog pass 2848 if (!IsSibCall) { 2849 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2850 2851 SmallVector<SDValue, 4> CopyFromChains; 2852 2853 // In the HSA case, this should be an identity copy. 2854 SDValue ScratchRSrcReg 2855 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2856 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2857 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2858 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2859 } 2860 2861 MVT PtrVT = MVT::i32; 2862 2863 // Walk the register/memloc assignments, inserting copies/loads. 2864 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2865 CCValAssign &VA = ArgLocs[i]; 2866 SDValue Arg = OutVals[i]; 2867 2868 // Promote the value if needed. 2869 switch (VA.getLocInfo()) { 2870 case CCValAssign::Full: 2871 break; 2872 case CCValAssign::BCvt: 2873 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2874 break; 2875 case CCValAssign::ZExt: 2876 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2877 break; 2878 case CCValAssign::SExt: 2879 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2880 break; 2881 case CCValAssign::AExt: 2882 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2883 break; 2884 case CCValAssign::FPExt: 2885 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2886 break; 2887 default: 2888 llvm_unreachable("Unknown loc info!"); 2889 } 2890 2891 if (VA.isRegLoc()) { 2892 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2893 } else { 2894 assert(VA.isMemLoc()); 2895 2896 SDValue DstAddr; 2897 MachinePointerInfo DstInfo; 2898 2899 unsigned LocMemOffset = VA.getLocMemOffset(); 2900 int32_t Offset = LocMemOffset; 2901 2902 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2903 MaybeAlign Alignment; 2904 2905 if (IsTailCall) { 2906 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2907 unsigned OpSize = Flags.isByVal() ? 2908 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2909 2910 // FIXME: We can have better than the minimum byval required alignment. 2911 Alignment = 2912 Flags.isByVal() 2913 ? Flags.getNonZeroByValAlign() 2914 : commonAlignment(Subtarget->getStackAlignment(), Offset); 2915 2916 Offset = Offset + FPDiff; 2917 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2918 2919 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2920 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2921 2922 // Make sure any stack arguments overlapping with where we're storing 2923 // are loaded before this eventual operation. Otherwise they'll be 2924 // clobbered. 2925 2926 // FIXME: Why is this really necessary? This seems to just result in a 2927 // lot of code to copy the stack and write them back to the same 2928 // locations, which are supposed to be immutable? 2929 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2930 } else { 2931 DstAddr = PtrOff; 2932 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2933 Alignment = 2934 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 2935 } 2936 2937 if (Outs[i].Flags.isByVal()) { 2938 SDValue SizeNode = 2939 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2940 SDValue Cpy = 2941 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 2942 Outs[i].Flags.getNonZeroByValAlign(), 2943 /*isVol = */ false, /*AlwaysInline = */ true, 2944 /*isTailCall = */ false, DstInfo, 2945 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 2946 2947 MemOpChains.push_back(Cpy); 2948 } else { 2949 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 2950 Alignment ? Alignment->value() : 0); 2951 MemOpChains.push_back(Store); 2952 } 2953 } 2954 } 2955 2956 if (!AMDGPUTargetMachine::EnableFixedFunctionABI) { 2957 // Copy special input registers after user input arguments. 2958 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2959 } 2960 2961 if (!MemOpChains.empty()) 2962 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2963 2964 // Build a sequence of copy-to-reg nodes chained together with token chain 2965 // and flag operands which copy the outgoing args into the appropriate regs. 2966 SDValue InFlag; 2967 for (auto &RegToPass : RegsToPass) { 2968 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2969 RegToPass.second, InFlag); 2970 InFlag = Chain.getValue(1); 2971 } 2972 2973 2974 SDValue PhysReturnAddrReg; 2975 if (IsTailCall) { 2976 // Since the return is being combined with the call, we need to pass on the 2977 // return address. 2978 2979 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2980 SDValue ReturnAddrReg = CreateLiveInRegister( 2981 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2982 2983 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2984 MVT::i64); 2985 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2986 InFlag = Chain.getValue(1); 2987 } 2988 2989 // We don't usually want to end the call-sequence here because we would tidy 2990 // the frame up *after* the call, however in the ABI-changing tail-call case 2991 // we've carefully laid out the parameters so that when sp is reset they'll be 2992 // in the correct location. 2993 if (IsTailCall && !IsSibCall) { 2994 Chain = DAG.getCALLSEQ_END(Chain, 2995 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2996 DAG.getTargetConstant(0, DL, MVT::i32), 2997 InFlag, DL); 2998 InFlag = Chain.getValue(1); 2999 } 3000 3001 std::vector<SDValue> Ops; 3002 Ops.push_back(Chain); 3003 Ops.push_back(Callee); 3004 // Add a redundant copy of the callee global which will not be legalized, as 3005 // we need direct access to the callee later. 3006 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3007 const GlobalValue *GV = GSD->getGlobal(); 3008 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3009 } else { 3010 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3011 } 3012 3013 if (IsTailCall) { 3014 // Each tail call may have to adjust the stack by a different amount, so 3015 // this information must travel along with the operation for eventual 3016 // consumption by emitEpilogue. 3017 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3018 3019 Ops.push_back(PhysReturnAddrReg); 3020 } 3021 3022 // Add argument registers to the end of the list so that they are known live 3023 // into the call. 3024 for (auto &RegToPass : RegsToPass) { 3025 Ops.push_back(DAG.getRegister(RegToPass.first, 3026 RegToPass.second.getValueType())); 3027 } 3028 3029 // Add a register mask operand representing the call-preserved registers. 3030 3031 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3032 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3033 assert(Mask && "Missing call preserved mask for calling convention"); 3034 Ops.push_back(DAG.getRegisterMask(Mask)); 3035 3036 if (InFlag.getNode()) 3037 Ops.push_back(InFlag); 3038 3039 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3040 3041 // If we're doing a tall call, use a TC_RETURN here rather than an 3042 // actual call instruction. 3043 if (IsTailCall) { 3044 MFI.setHasTailCall(); 3045 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3046 } 3047 3048 // Returns a chain and a flag for retval copy to use. 3049 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3050 Chain = Call.getValue(0); 3051 InFlag = Call.getValue(1); 3052 3053 uint64_t CalleePopBytes = NumBytes; 3054 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3055 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3056 InFlag, DL); 3057 if (!Ins.empty()) 3058 InFlag = Chain.getValue(1); 3059 3060 // Handle result values, copying them out of physregs into vregs that we 3061 // return. 3062 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3063 InVals, IsThisReturn, 3064 IsThisReturn ? OutVals[0] : SDValue()); 3065 } 3066 3067 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3068 const MachineFunction &MF) const { 3069 Register Reg = StringSwitch<Register>(RegName) 3070 .Case("m0", AMDGPU::M0) 3071 .Case("exec", AMDGPU::EXEC) 3072 .Case("exec_lo", AMDGPU::EXEC_LO) 3073 .Case("exec_hi", AMDGPU::EXEC_HI) 3074 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3075 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3076 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3077 .Default(Register()); 3078 3079 if (Reg == AMDGPU::NoRegister) { 3080 report_fatal_error(Twine("invalid register name \"" 3081 + StringRef(RegName) + "\".")); 3082 3083 } 3084 3085 if (!Subtarget->hasFlatScrRegister() && 3086 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3087 report_fatal_error(Twine("invalid register \"" 3088 + StringRef(RegName) + "\" for subtarget.")); 3089 } 3090 3091 switch (Reg) { 3092 case AMDGPU::M0: 3093 case AMDGPU::EXEC_LO: 3094 case AMDGPU::EXEC_HI: 3095 case AMDGPU::FLAT_SCR_LO: 3096 case AMDGPU::FLAT_SCR_HI: 3097 if (VT.getSizeInBits() == 32) 3098 return Reg; 3099 break; 3100 case AMDGPU::EXEC: 3101 case AMDGPU::FLAT_SCR: 3102 if (VT.getSizeInBits() == 64) 3103 return Reg; 3104 break; 3105 default: 3106 llvm_unreachable("missing register type checking"); 3107 } 3108 3109 report_fatal_error(Twine("invalid type for register \"" 3110 + StringRef(RegName) + "\".")); 3111 } 3112 3113 // If kill is not the last instruction, split the block so kill is always a 3114 // proper terminator. 3115 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3116 MachineBasicBlock *BB) const { 3117 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3118 3119 MachineBasicBlock::iterator SplitPoint(&MI); 3120 ++SplitPoint; 3121 3122 if (SplitPoint == BB->end()) { 3123 // Don't bother with a new block. 3124 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3125 return BB; 3126 } 3127 3128 MachineFunction *MF = BB->getParent(); 3129 MachineBasicBlock *SplitBB 3130 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3131 3132 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3133 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3134 3135 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3136 BB->addSuccessor(SplitBB); 3137 3138 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3139 return SplitBB; 3140 } 3141 3142 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3143 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3144 // be the first instruction in the remainder block. 3145 // 3146 /// \returns { LoopBody, Remainder } 3147 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3148 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3149 MachineFunction *MF = MBB.getParent(); 3150 MachineBasicBlock::iterator I(&MI); 3151 3152 // To insert the loop we need to split the block. Move everything after this 3153 // point to a new block, and insert a new empty block between the two. 3154 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3155 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3156 MachineFunction::iterator MBBI(MBB); 3157 ++MBBI; 3158 3159 MF->insert(MBBI, LoopBB); 3160 MF->insert(MBBI, RemainderBB); 3161 3162 LoopBB->addSuccessor(LoopBB); 3163 LoopBB->addSuccessor(RemainderBB); 3164 3165 // Move the rest of the block into a new block. 3166 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3167 3168 if (InstInLoop) { 3169 auto Next = std::next(I); 3170 3171 // Move instruction to loop body. 3172 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3173 3174 // Move the rest of the block. 3175 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3176 } else { 3177 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3178 } 3179 3180 MBB.addSuccessor(LoopBB); 3181 3182 return std::make_pair(LoopBB, RemainderBB); 3183 } 3184 3185 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3186 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3187 MachineBasicBlock *MBB = MI.getParent(); 3188 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3189 auto I = MI.getIterator(); 3190 auto E = std::next(I); 3191 3192 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3193 .addImm(0); 3194 3195 MIBundleBuilder Bundler(*MBB, I, E); 3196 finalizeBundle(*MBB, Bundler.begin()); 3197 } 3198 3199 MachineBasicBlock * 3200 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3201 MachineBasicBlock *BB) const { 3202 const DebugLoc &DL = MI.getDebugLoc(); 3203 3204 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3205 3206 MachineBasicBlock *LoopBB; 3207 MachineBasicBlock *RemainderBB; 3208 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3209 3210 // Apparently kill flags are only valid if the def is in the same block? 3211 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3212 Src->setIsKill(false); 3213 3214 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3215 3216 MachineBasicBlock::iterator I = LoopBB->end(); 3217 3218 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3219 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3220 3221 // Clear TRAP_STS.MEM_VIOL 3222 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3223 .addImm(0) 3224 .addImm(EncodedReg); 3225 3226 bundleInstWithWaitcnt(MI); 3227 3228 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3229 3230 // Load and check TRAP_STS.MEM_VIOL 3231 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3232 .addImm(EncodedReg); 3233 3234 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3235 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3236 .addReg(Reg, RegState::Kill) 3237 .addImm(0); 3238 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3239 .addMBB(LoopBB); 3240 3241 return RemainderBB; 3242 } 3243 3244 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3245 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3246 // will only do one iteration. In the worst case, this will loop 64 times. 3247 // 3248 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3249 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3250 const SIInstrInfo *TII, 3251 MachineRegisterInfo &MRI, 3252 MachineBasicBlock &OrigBB, 3253 MachineBasicBlock &LoopBB, 3254 const DebugLoc &DL, 3255 const MachineOperand &IdxReg, 3256 unsigned InitReg, 3257 unsigned ResultReg, 3258 unsigned PhiReg, 3259 unsigned InitSaveExecReg, 3260 int Offset, 3261 bool UseGPRIdxMode, 3262 bool IsIndirectSrc) { 3263 MachineFunction *MF = OrigBB.getParent(); 3264 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3265 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3266 MachineBasicBlock::iterator I = LoopBB.begin(); 3267 3268 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3269 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3270 Register NewExec = MRI.createVirtualRegister(BoolRC); 3271 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3272 Register CondReg = MRI.createVirtualRegister(BoolRC); 3273 3274 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3275 .addReg(InitReg) 3276 .addMBB(&OrigBB) 3277 .addReg(ResultReg) 3278 .addMBB(&LoopBB); 3279 3280 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3281 .addReg(InitSaveExecReg) 3282 .addMBB(&OrigBB) 3283 .addReg(NewExec) 3284 .addMBB(&LoopBB); 3285 3286 // Read the next variant <- also loop target. 3287 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3288 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3289 3290 // Compare the just read M0 value to all possible Idx values. 3291 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3292 .addReg(CurrentIdxReg) 3293 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3294 3295 // Update EXEC, save the original EXEC value to VCC. 3296 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3297 : AMDGPU::S_AND_SAVEEXEC_B64), 3298 NewExec) 3299 .addReg(CondReg, RegState::Kill); 3300 3301 MRI.setSimpleHint(NewExec, CondReg); 3302 3303 if (UseGPRIdxMode) { 3304 unsigned IdxReg; 3305 if (Offset == 0) { 3306 IdxReg = CurrentIdxReg; 3307 } else { 3308 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3309 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3310 .addReg(CurrentIdxReg, RegState::Kill) 3311 .addImm(Offset); 3312 } 3313 unsigned IdxMode = IsIndirectSrc ? 3314 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3315 MachineInstr *SetOn = 3316 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3317 .addReg(IdxReg, RegState::Kill) 3318 .addImm(IdxMode); 3319 SetOn->getOperand(3).setIsUndef(); 3320 } else { 3321 // Move index from VCC into M0 3322 if (Offset == 0) { 3323 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3324 .addReg(CurrentIdxReg, RegState::Kill); 3325 } else { 3326 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3327 .addReg(CurrentIdxReg, RegState::Kill) 3328 .addImm(Offset); 3329 } 3330 } 3331 3332 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3333 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3334 MachineInstr *InsertPt = 3335 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3336 : AMDGPU::S_XOR_B64_term), Exec) 3337 .addReg(Exec) 3338 .addReg(NewExec); 3339 3340 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3341 // s_cbranch_scc0? 3342 3343 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3344 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3345 .addMBB(&LoopBB); 3346 3347 return InsertPt->getIterator(); 3348 } 3349 3350 // This has slightly sub-optimal regalloc when the source vector is killed by 3351 // the read. The register allocator does not understand that the kill is 3352 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3353 // subregister from it, using 1 more VGPR than necessary. This was saved when 3354 // this was expanded after register allocation. 3355 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3356 MachineBasicBlock &MBB, 3357 MachineInstr &MI, 3358 unsigned InitResultReg, 3359 unsigned PhiReg, 3360 int Offset, 3361 bool UseGPRIdxMode, 3362 bool IsIndirectSrc) { 3363 MachineFunction *MF = MBB.getParent(); 3364 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3365 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3366 MachineRegisterInfo &MRI = MF->getRegInfo(); 3367 const DebugLoc &DL = MI.getDebugLoc(); 3368 MachineBasicBlock::iterator I(&MI); 3369 3370 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3371 Register DstReg = MI.getOperand(0).getReg(); 3372 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3373 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3374 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3375 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3376 3377 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3378 3379 // Save the EXEC mask 3380 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3381 .addReg(Exec); 3382 3383 MachineBasicBlock *LoopBB; 3384 MachineBasicBlock *RemainderBB; 3385 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3386 3387 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3388 3389 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3390 InitResultReg, DstReg, PhiReg, TmpExec, 3391 Offset, UseGPRIdxMode, IsIndirectSrc); 3392 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3393 MachineFunction::iterator MBBI(LoopBB); 3394 ++MBBI; 3395 MF->insert(MBBI, LandingPad); 3396 LoopBB->removeSuccessor(RemainderBB); 3397 LandingPad->addSuccessor(RemainderBB); 3398 LoopBB->addSuccessor(LandingPad); 3399 MachineBasicBlock::iterator First = LandingPad->begin(); 3400 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3401 .addReg(SaveExec); 3402 3403 return InsPt; 3404 } 3405 3406 // Returns subreg index, offset 3407 static std::pair<unsigned, int> 3408 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3409 const TargetRegisterClass *SuperRC, 3410 unsigned VecReg, 3411 int Offset) { 3412 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3413 3414 // Skip out of bounds offsets, or else we would end up using an undefined 3415 // register. 3416 if (Offset >= NumElts || Offset < 0) 3417 return std::make_pair(AMDGPU::sub0, Offset); 3418 3419 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3420 } 3421 3422 // Return true if the index is an SGPR and was set. 3423 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3424 MachineRegisterInfo &MRI, 3425 MachineInstr &MI, 3426 int Offset, 3427 bool UseGPRIdxMode, 3428 bool IsIndirectSrc) { 3429 MachineBasicBlock *MBB = MI.getParent(); 3430 const DebugLoc &DL = MI.getDebugLoc(); 3431 MachineBasicBlock::iterator I(&MI); 3432 3433 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3434 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3435 3436 assert(Idx->getReg() != AMDGPU::NoRegister); 3437 3438 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3439 return false; 3440 3441 if (UseGPRIdxMode) { 3442 unsigned IdxMode = IsIndirectSrc ? 3443 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3444 if (Offset == 0) { 3445 MachineInstr *SetOn = 3446 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3447 .add(*Idx) 3448 .addImm(IdxMode); 3449 3450 SetOn->getOperand(3).setIsUndef(); 3451 } else { 3452 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3453 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3454 .add(*Idx) 3455 .addImm(Offset); 3456 MachineInstr *SetOn = 3457 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3458 .addReg(Tmp, RegState::Kill) 3459 .addImm(IdxMode); 3460 3461 SetOn->getOperand(3).setIsUndef(); 3462 } 3463 3464 return true; 3465 } 3466 3467 if (Offset == 0) { 3468 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3469 .add(*Idx); 3470 } else { 3471 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3472 .add(*Idx) 3473 .addImm(Offset); 3474 } 3475 3476 return true; 3477 } 3478 3479 // Control flow needs to be inserted if indexing with a VGPR. 3480 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3481 MachineBasicBlock &MBB, 3482 const GCNSubtarget &ST) { 3483 const SIInstrInfo *TII = ST.getInstrInfo(); 3484 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3485 MachineFunction *MF = MBB.getParent(); 3486 MachineRegisterInfo &MRI = MF->getRegInfo(); 3487 3488 Register Dst = MI.getOperand(0).getReg(); 3489 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3490 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3491 3492 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3493 3494 unsigned SubReg; 3495 std::tie(SubReg, Offset) 3496 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3497 3498 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3499 3500 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3501 MachineBasicBlock::iterator I(&MI); 3502 const DebugLoc &DL = MI.getDebugLoc(); 3503 3504 if (UseGPRIdxMode) { 3505 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3506 // to avoid interfering with other uses, so probably requires a new 3507 // optimization pass. 3508 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3509 .addReg(SrcReg, RegState::Undef, SubReg) 3510 .addReg(SrcReg, RegState::Implicit) 3511 .addReg(AMDGPU::M0, RegState::Implicit); 3512 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3513 } else { 3514 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3515 .addReg(SrcReg, RegState::Undef, SubReg) 3516 .addReg(SrcReg, RegState::Implicit); 3517 } 3518 3519 MI.eraseFromParent(); 3520 3521 return &MBB; 3522 } 3523 3524 const DebugLoc &DL = MI.getDebugLoc(); 3525 MachineBasicBlock::iterator I(&MI); 3526 3527 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3528 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3529 3530 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3531 3532 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3533 Offset, UseGPRIdxMode, true); 3534 MachineBasicBlock *LoopBB = InsPt->getParent(); 3535 3536 if (UseGPRIdxMode) { 3537 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3538 .addReg(SrcReg, RegState::Undef, SubReg) 3539 .addReg(SrcReg, RegState::Implicit) 3540 .addReg(AMDGPU::M0, RegState::Implicit); 3541 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3542 } else { 3543 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3544 .addReg(SrcReg, RegState::Undef, SubReg) 3545 .addReg(SrcReg, RegState::Implicit); 3546 } 3547 3548 MI.eraseFromParent(); 3549 3550 return LoopBB; 3551 } 3552 3553 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3554 MachineBasicBlock &MBB, 3555 const GCNSubtarget &ST) { 3556 const SIInstrInfo *TII = ST.getInstrInfo(); 3557 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3558 MachineFunction *MF = MBB.getParent(); 3559 MachineRegisterInfo &MRI = MF->getRegInfo(); 3560 3561 Register Dst = MI.getOperand(0).getReg(); 3562 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3563 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3564 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3565 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3566 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3567 3568 // This can be an immediate, but will be folded later. 3569 assert(Val->getReg()); 3570 3571 unsigned SubReg; 3572 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3573 SrcVec->getReg(), 3574 Offset); 3575 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3576 3577 if (Idx->getReg() == AMDGPU::NoRegister) { 3578 MachineBasicBlock::iterator I(&MI); 3579 const DebugLoc &DL = MI.getDebugLoc(); 3580 3581 assert(Offset == 0); 3582 3583 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3584 .add(*SrcVec) 3585 .add(*Val) 3586 .addImm(SubReg); 3587 3588 MI.eraseFromParent(); 3589 return &MBB; 3590 } 3591 3592 const MCInstrDesc &MovRelDesc 3593 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3594 3595 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3596 MachineBasicBlock::iterator I(&MI); 3597 const DebugLoc &DL = MI.getDebugLoc(); 3598 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3599 .addReg(SrcVec->getReg()) 3600 .add(*Val) 3601 .addImm(SubReg); 3602 if (UseGPRIdxMode) 3603 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3604 3605 MI.eraseFromParent(); 3606 return &MBB; 3607 } 3608 3609 if (Val->isReg()) 3610 MRI.clearKillFlags(Val->getReg()); 3611 3612 const DebugLoc &DL = MI.getDebugLoc(); 3613 3614 Register PhiReg = MRI.createVirtualRegister(VecRC); 3615 3616 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3617 Offset, UseGPRIdxMode, false); 3618 MachineBasicBlock *LoopBB = InsPt->getParent(); 3619 3620 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3621 .addReg(PhiReg) 3622 .add(*Val) 3623 .addImm(AMDGPU::sub0); 3624 if (UseGPRIdxMode) 3625 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3626 3627 MI.eraseFromParent(); 3628 return LoopBB; 3629 } 3630 3631 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3632 MachineInstr &MI, MachineBasicBlock *BB) const { 3633 3634 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3635 MachineFunction *MF = BB->getParent(); 3636 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3637 3638 if (TII->isMIMG(MI)) { 3639 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 3640 report_fatal_error("missing mem operand from MIMG instruction"); 3641 } 3642 // Add a memoperand for mimg instructions so that they aren't assumed to 3643 // be ordered memory instuctions. 3644 3645 return BB; 3646 } 3647 3648 switch (MI.getOpcode()) { 3649 case AMDGPU::S_UADDO_PSEUDO: 3650 case AMDGPU::S_USUBO_PSEUDO: { 3651 const DebugLoc &DL = MI.getDebugLoc(); 3652 MachineOperand &Dest0 = MI.getOperand(0); 3653 MachineOperand &Dest1 = MI.getOperand(1); 3654 MachineOperand &Src0 = MI.getOperand(2); 3655 MachineOperand &Src1 = MI.getOperand(3); 3656 3657 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3658 ? AMDGPU::S_ADD_I32 3659 : AMDGPU::S_SUB_I32; 3660 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3661 3662 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3663 .addImm(1) 3664 .addImm(0); 3665 3666 MI.eraseFromParent(); 3667 return BB; 3668 } 3669 case AMDGPU::S_ADD_U64_PSEUDO: 3670 case AMDGPU::S_SUB_U64_PSEUDO: { 3671 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3672 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3673 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3674 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3675 const DebugLoc &DL = MI.getDebugLoc(); 3676 3677 MachineOperand &Dest = MI.getOperand(0); 3678 MachineOperand &Src0 = MI.getOperand(1); 3679 MachineOperand &Src1 = MI.getOperand(2); 3680 3681 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3682 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3683 3684 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3685 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3686 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3687 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3688 3689 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3690 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3691 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3692 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3693 3694 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3695 3696 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3697 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3698 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3699 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3700 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3701 .addReg(DestSub0) 3702 .addImm(AMDGPU::sub0) 3703 .addReg(DestSub1) 3704 .addImm(AMDGPU::sub1); 3705 MI.eraseFromParent(); 3706 return BB; 3707 } 3708 case AMDGPU::V_ADD_U64_PSEUDO: 3709 case AMDGPU::V_SUB_U64_PSEUDO: { 3710 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3711 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3712 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3713 const DebugLoc &DL = MI.getDebugLoc(); 3714 3715 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3716 3717 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3718 3719 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3720 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3721 3722 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3723 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3724 3725 MachineOperand &Dest = MI.getOperand(0); 3726 MachineOperand &Src0 = MI.getOperand(1); 3727 MachineOperand &Src1 = MI.getOperand(2); 3728 3729 const TargetRegisterClass *Src0RC = Src0.isReg() 3730 ? MRI.getRegClass(Src0.getReg()) 3731 : &AMDGPU::VReg_64RegClass; 3732 const TargetRegisterClass *Src1RC = Src1.isReg() 3733 ? MRI.getRegClass(Src1.getReg()) 3734 : &AMDGPU::VReg_64RegClass; 3735 3736 const TargetRegisterClass *Src0SubRC = 3737 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3738 const TargetRegisterClass *Src1SubRC = 3739 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3740 3741 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3742 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3743 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3744 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3745 3746 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3747 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3748 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3749 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3750 3751 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64; 3752 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3753 .addReg(CarryReg, RegState::Define) 3754 .add(SrcReg0Sub0) 3755 .add(SrcReg1Sub0) 3756 .addImm(0); // clamp bit 3757 3758 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3759 MachineInstr *HiHalf = 3760 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3761 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3762 .add(SrcReg0Sub1) 3763 .add(SrcReg1Sub1) 3764 .addReg(CarryReg, RegState::Kill) 3765 .addImm(0); // clamp bit 3766 3767 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3768 .addReg(DestSub0) 3769 .addImm(AMDGPU::sub0) 3770 .addReg(DestSub1) 3771 .addImm(AMDGPU::sub1); 3772 TII->legalizeOperands(*LoHalf); 3773 TII->legalizeOperands(*HiHalf); 3774 MI.eraseFromParent(); 3775 return BB; 3776 } 3777 case AMDGPU::S_ADD_CO_PSEUDO: 3778 case AMDGPU::S_SUB_CO_PSEUDO: { 3779 // This pseudo has a chance to be selected 3780 // only from uniform add/subcarry node. All the VGPR operands 3781 // therefore assumed to be splat vectors. 3782 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3783 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3784 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3785 MachineBasicBlock::iterator MII = MI; 3786 const DebugLoc &DL = MI.getDebugLoc(); 3787 MachineOperand &Dest = MI.getOperand(0); 3788 MachineOperand &Src0 = MI.getOperand(2); 3789 MachineOperand &Src1 = MI.getOperand(3); 3790 MachineOperand &Src2 = MI.getOperand(4); 3791 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 3792 ? AMDGPU::S_ADDC_U32 3793 : AMDGPU::S_SUBB_U32; 3794 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 3795 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3796 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 3797 .addReg(Src0.getReg()); 3798 Src0.setReg(RegOp0); 3799 } 3800 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 3801 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3802 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 3803 .addReg(Src1.getReg()); 3804 Src1.setReg(RegOp1); 3805 } 3806 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3807 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 3808 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 3809 .addReg(Src2.getReg()); 3810 Src2.setReg(RegOp2); 3811 } 3812 3813 if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) { 3814 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 3815 .addReg(Src2.getReg()) 3816 .addImm(0); 3817 } else { 3818 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 3819 .addReg(Src2.getReg()) 3820 .addImm(0); 3821 } 3822 3823 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 3824 MI.eraseFromParent(); 3825 return BB; 3826 } 3827 case AMDGPU::SI_INIT_M0: { 3828 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3829 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3830 .add(MI.getOperand(0)); 3831 MI.eraseFromParent(); 3832 return BB; 3833 } 3834 case AMDGPU::SI_INIT_EXEC: 3835 // This should be before all vector instructions. 3836 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3837 AMDGPU::EXEC) 3838 .addImm(MI.getOperand(0).getImm()); 3839 MI.eraseFromParent(); 3840 return BB; 3841 3842 case AMDGPU::SI_INIT_EXEC_LO: 3843 // This should be before all vector instructions. 3844 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3845 AMDGPU::EXEC_LO) 3846 .addImm(MI.getOperand(0).getImm()); 3847 MI.eraseFromParent(); 3848 return BB; 3849 3850 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3851 // Extract the thread count from an SGPR input and set EXEC accordingly. 3852 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3853 // 3854 // S_BFE_U32 count, input, {shift, 7} 3855 // S_BFM_B64 exec, count, 0 3856 // S_CMP_EQ_U32 count, 64 3857 // S_CMOV_B64 exec, -1 3858 MachineInstr *FirstMI = &*BB->begin(); 3859 MachineRegisterInfo &MRI = MF->getRegInfo(); 3860 Register InputReg = MI.getOperand(0).getReg(); 3861 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3862 bool Found = false; 3863 3864 // Move the COPY of the input reg to the beginning, so that we can use it. 3865 for (auto I = BB->begin(); I != &MI; I++) { 3866 if (I->getOpcode() != TargetOpcode::COPY || 3867 I->getOperand(0).getReg() != InputReg) 3868 continue; 3869 3870 if (I == FirstMI) { 3871 FirstMI = &*++BB->begin(); 3872 } else { 3873 I->removeFromParent(); 3874 BB->insert(FirstMI, &*I); 3875 } 3876 Found = true; 3877 break; 3878 } 3879 assert(Found); 3880 (void)Found; 3881 3882 // This should be before all vector instructions. 3883 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3884 bool isWave32 = getSubtarget()->isWave32(); 3885 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3886 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3887 .addReg(InputReg) 3888 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3889 BuildMI(*BB, FirstMI, DebugLoc(), 3890 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3891 Exec) 3892 .addReg(CountReg) 3893 .addImm(0); 3894 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3895 .addReg(CountReg, RegState::Kill) 3896 .addImm(getSubtarget()->getWavefrontSize()); 3897 BuildMI(*BB, FirstMI, DebugLoc(), 3898 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3899 Exec) 3900 .addImm(-1); 3901 MI.eraseFromParent(); 3902 return BB; 3903 } 3904 3905 case AMDGPU::GET_GROUPSTATICSIZE: { 3906 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 3907 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 3908 DebugLoc DL = MI.getDebugLoc(); 3909 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3910 .add(MI.getOperand(0)) 3911 .addImm(MFI->getLDSSize()); 3912 MI.eraseFromParent(); 3913 return BB; 3914 } 3915 case AMDGPU::SI_INDIRECT_SRC_V1: 3916 case AMDGPU::SI_INDIRECT_SRC_V2: 3917 case AMDGPU::SI_INDIRECT_SRC_V4: 3918 case AMDGPU::SI_INDIRECT_SRC_V8: 3919 case AMDGPU::SI_INDIRECT_SRC_V16: 3920 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3921 case AMDGPU::SI_INDIRECT_DST_V1: 3922 case AMDGPU::SI_INDIRECT_DST_V2: 3923 case AMDGPU::SI_INDIRECT_DST_V4: 3924 case AMDGPU::SI_INDIRECT_DST_V8: 3925 case AMDGPU::SI_INDIRECT_DST_V16: 3926 return emitIndirectDst(MI, *BB, *getSubtarget()); 3927 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3928 case AMDGPU::SI_KILL_I1_PSEUDO: 3929 return splitKillBlock(MI, BB); 3930 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3931 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3932 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3933 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3934 3935 Register Dst = MI.getOperand(0).getReg(); 3936 Register Src0 = MI.getOperand(1).getReg(); 3937 Register Src1 = MI.getOperand(2).getReg(); 3938 const DebugLoc &DL = MI.getDebugLoc(); 3939 Register SrcCond = MI.getOperand(3).getReg(); 3940 3941 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3942 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3943 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3944 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 3945 3946 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3947 .addReg(SrcCond); 3948 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3949 .addImm(0) 3950 .addReg(Src0, 0, AMDGPU::sub0) 3951 .addImm(0) 3952 .addReg(Src1, 0, AMDGPU::sub0) 3953 .addReg(SrcCondCopy); 3954 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3955 .addImm(0) 3956 .addReg(Src0, 0, AMDGPU::sub1) 3957 .addImm(0) 3958 .addReg(Src1, 0, AMDGPU::sub1) 3959 .addReg(SrcCondCopy); 3960 3961 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3962 .addReg(DstLo) 3963 .addImm(AMDGPU::sub0) 3964 .addReg(DstHi) 3965 .addImm(AMDGPU::sub1); 3966 MI.eraseFromParent(); 3967 return BB; 3968 } 3969 case AMDGPU::SI_BR_UNDEF: { 3970 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3971 const DebugLoc &DL = MI.getDebugLoc(); 3972 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3973 .add(MI.getOperand(0)); 3974 Br->getOperand(1).setIsUndef(true); // read undef SCC 3975 MI.eraseFromParent(); 3976 return BB; 3977 } 3978 case AMDGPU::ADJCALLSTACKUP: 3979 case AMDGPU::ADJCALLSTACKDOWN: { 3980 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3981 MachineInstrBuilder MIB(*MF, &MI); 3982 3983 // Add an implicit use of the frame offset reg to prevent the restore copy 3984 // inserted after the call from being reorderd after stack operations in the 3985 // the caller's frame. 3986 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3987 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 3988 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 3989 return BB; 3990 } 3991 case AMDGPU::SI_CALL_ISEL: { 3992 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3993 const DebugLoc &DL = MI.getDebugLoc(); 3994 3995 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3996 3997 MachineInstrBuilder MIB; 3998 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 3999 4000 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4001 MIB.add(MI.getOperand(I)); 4002 4003 MIB.cloneMemRefs(MI); 4004 MI.eraseFromParent(); 4005 return BB; 4006 } 4007 case AMDGPU::V_ADD_I32_e32: 4008 case AMDGPU::V_SUB_I32_e32: 4009 case AMDGPU::V_SUBREV_I32_e32: { 4010 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4011 const DebugLoc &DL = MI.getDebugLoc(); 4012 unsigned Opc = MI.getOpcode(); 4013 4014 bool NeedClampOperand = false; 4015 if (TII->pseudoToMCOpcode(Opc) == -1) { 4016 Opc = AMDGPU::getVOPe64(Opc); 4017 NeedClampOperand = true; 4018 } 4019 4020 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4021 if (TII->isVOP3(*I)) { 4022 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4023 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4024 I.addReg(TRI->getVCC(), RegState::Define); 4025 } 4026 I.add(MI.getOperand(1)) 4027 .add(MI.getOperand(2)); 4028 if (NeedClampOperand) 4029 I.addImm(0); // clamp bit for e64 encoding 4030 4031 TII->legalizeOperands(*I); 4032 4033 MI.eraseFromParent(); 4034 return BB; 4035 } 4036 case AMDGPU::DS_GWS_INIT: 4037 case AMDGPU::DS_GWS_SEMA_V: 4038 case AMDGPU::DS_GWS_SEMA_BR: 4039 case AMDGPU::DS_GWS_SEMA_P: 4040 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4041 case AMDGPU::DS_GWS_BARRIER: 4042 // A s_waitcnt 0 is required to be the instruction immediately following. 4043 if (getSubtarget()->hasGWSAutoReplay()) { 4044 bundleInstWithWaitcnt(MI); 4045 return BB; 4046 } 4047 4048 return emitGWSMemViolTestLoop(MI, BB); 4049 default: 4050 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4051 } 4052 } 4053 4054 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4055 return isTypeLegal(VT.getScalarType()); 4056 } 4057 4058 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4059 // This currently forces unfolding various combinations of fsub into fma with 4060 // free fneg'd operands. As long as we have fast FMA (controlled by 4061 // isFMAFasterThanFMulAndFAdd), we should perform these. 4062 4063 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4064 // most of these combines appear to be cycle neutral but save on instruction 4065 // count / code size. 4066 return true; 4067 } 4068 4069 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4070 EVT VT) const { 4071 if (!VT.isVector()) { 4072 return MVT::i1; 4073 } 4074 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4075 } 4076 4077 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4078 // TODO: Should i16 be used always if legal? For now it would force VALU 4079 // shifts. 4080 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4081 } 4082 4083 // Answering this is somewhat tricky and depends on the specific device which 4084 // have different rates for fma or all f64 operations. 4085 // 4086 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4087 // regardless of which device (although the number of cycles differs between 4088 // devices), so it is always profitable for f64. 4089 // 4090 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4091 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4092 // which we can always do even without fused FP ops since it returns the same 4093 // result as the separate operations and since it is always full 4094 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4095 // however does not support denormals, so we do report fma as faster if we have 4096 // a fast fma device and require denormals. 4097 // 4098 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4099 EVT VT) const { 4100 VT = VT.getScalarType(); 4101 4102 switch (VT.getSimpleVT().SimpleTy) { 4103 case MVT::f32: { 4104 // This is as fast on some subtargets. However, we always have full rate f32 4105 // mad available which returns the same result as the separate operations 4106 // which we should prefer over fma. We can't use this if we want to support 4107 // denormals, so only report this in these cases. 4108 if (hasFP32Denormals(MF)) 4109 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4110 4111 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4112 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4113 } 4114 case MVT::f64: 4115 return true; 4116 case MVT::f16: 4117 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4118 default: 4119 break; 4120 } 4121 4122 return false; 4123 } 4124 4125 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4126 const SDNode *N) const { 4127 // TODO: Check future ftz flag 4128 // v_mad_f32/v_mac_f32 do not support denormals. 4129 EVT VT = N->getValueType(0); 4130 if (VT == MVT::f32) 4131 return !hasFP32Denormals(DAG.getMachineFunction()); 4132 if (VT == MVT::f16) { 4133 return Subtarget->hasMadF16() && 4134 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4135 } 4136 4137 return false; 4138 } 4139 4140 //===----------------------------------------------------------------------===// 4141 // Custom DAG Lowering Operations 4142 //===----------------------------------------------------------------------===// 4143 4144 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4145 // wider vector type is legal. 4146 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4147 SelectionDAG &DAG) const { 4148 unsigned Opc = Op.getOpcode(); 4149 EVT VT = Op.getValueType(); 4150 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4151 4152 SDValue Lo, Hi; 4153 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4154 4155 SDLoc SL(Op); 4156 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4157 Op->getFlags()); 4158 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4159 Op->getFlags()); 4160 4161 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4162 } 4163 4164 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4165 // wider vector type is legal. 4166 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4167 SelectionDAG &DAG) const { 4168 unsigned Opc = Op.getOpcode(); 4169 EVT VT = Op.getValueType(); 4170 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4171 4172 SDValue Lo0, Hi0; 4173 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4174 SDValue Lo1, Hi1; 4175 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4176 4177 SDLoc SL(Op); 4178 4179 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4180 Op->getFlags()); 4181 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4182 Op->getFlags()); 4183 4184 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4185 } 4186 4187 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4188 SelectionDAG &DAG) const { 4189 unsigned Opc = Op.getOpcode(); 4190 EVT VT = Op.getValueType(); 4191 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4192 4193 SDValue Lo0, Hi0; 4194 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4195 SDValue Lo1, Hi1; 4196 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4197 SDValue Lo2, Hi2; 4198 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4199 4200 SDLoc SL(Op); 4201 4202 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4203 Op->getFlags()); 4204 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4205 Op->getFlags()); 4206 4207 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4208 } 4209 4210 4211 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4212 switch (Op.getOpcode()) { 4213 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4214 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4215 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4216 case ISD::LOAD: { 4217 SDValue Result = LowerLOAD(Op, DAG); 4218 assert((!Result.getNode() || 4219 Result.getNode()->getNumValues() == 2) && 4220 "Load should return a value and a chain"); 4221 return Result; 4222 } 4223 4224 case ISD::FSIN: 4225 case ISD::FCOS: 4226 return LowerTrig(Op, DAG); 4227 case ISD::SELECT: return LowerSELECT(Op, DAG); 4228 case ISD::FDIV: return LowerFDIV(Op, DAG); 4229 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4230 case ISD::STORE: return LowerSTORE(Op, DAG); 4231 case ISD::GlobalAddress: { 4232 MachineFunction &MF = DAG.getMachineFunction(); 4233 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4234 return LowerGlobalAddress(MFI, Op, DAG); 4235 } 4236 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4237 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4238 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4239 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4240 case ISD::INSERT_SUBVECTOR: 4241 return lowerINSERT_SUBVECTOR(Op, DAG); 4242 case ISD::INSERT_VECTOR_ELT: 4243 return lowerINSERT_VECTOR_ELT(Op, DAG); 4244 case ISD::EXTRACT_VECTOR_ELT: 4245 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4246 case ISD::VECTOR_SHUFFLE: 4247 return lowerVECTOR_SHUFFLE(Op, DAG); 4248 case ISD::BUILD_VECTOR: 4249 return lowerBUILD_VECTOR(Op, DAG); 4250 case ISD::FP_ROUND: 4251 return lowerFP_ROUND(Op, DAG); 4252 case ISD::TRAP: 4253 return lowerTRAP(Op, DAG); 4254 case ISD::DEBUGTRAP: 4255 return lowerDEBUGTRAP(Op, DAG); 4256 case ISD::FABS: 4257 case ISD::FNEG: 4258 case ISD::FCANONICALIZE: 4259 case ISD::BSWAP: 4260 return splitUnaryVectorOp(Op, DAG); 4261 case ISD::FMINNUM: 4262 case ISD::FMAXNUM: 4263 return lowerFMINNUM_FMAXNUM(Op, DAG); 4264 case ISD::FMA: 4265 return splitTernaryVectorOp(Op, DAG); 4266 case ISD::SHL: 4267 case ISD::SRA: 4268 case ISD::SRL: 4269 case ISD::ADD: 4270 case ISD::SUB: 4271 case ISD::MUL: 4272 case ISD::SMIN: 4273 case ISD::SMAX: 4274 case ISD::UMIN: 4275 case ISD::UMAX: 4276 case ISD::FADD: 4277 case ISD::FMUL: 4278 case ISD::FMINNUM_IEEE: 4279 case ISD::FMAXNUM_IEEE: 4280 return splitBinaryVectorOp(Op, DAG); 4281 } 4282 return SDValue(); 4283 } 4284 4285 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4286 const SDLoc &DL, 4287 SelectionDAG &DAG, bool Unpacked) { 4288 if (!LoadVT.isVector()) 4289 return Result; 4290 4291 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4292 // Truncate to v2i16/v4i16. 4293 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4294 4295 // Workaround legalizer not scalarizing truncate after vector op 4296 // legalization byt not creating intermediate vector trunc. 4297 SmallVector<SDValue, 4> Elts; 4298 DAG.ExtractVectorElements(Result, Elts); 4299 for (SDValue &Elt : Elts) 4300 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4301 4302 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4303 4304 // Bitcast to original type (v2f16/v4f16). 4305 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4306 } 4307 4308 // Cast back to the original packed type. 4309 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4310 } 4311 4312 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4313 MemSDNode *M, 4314 SelectionDAG &DAG, 4315 ArrayRef<SDValue> Ops, 4316 bool IsIntrinsic) const { 4317 SDLoc DL(M); 4318 4319 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4320 EVT LoadVT = M->getValueType(0); 4321 4322 EVT EquivLoadVT = LoadVT; 4323 if (Unpacked && LoadVT.isVector()) { 4324 EquivLoadVT = LoadVT.isVector() ? 4325 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4326 LoadVT.getVectorNumElements()) : LoadVT; 4327 } 4328 4329 // Change from v4f16/v2f16 to EquivLoadVT. 4330 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4331 4332 SDValue Load 4333 = DAG.getMemIntrinsicNode( 4334 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4335 VTList, Ops, M->getMemoryVT(), 4336 M->getMemOperand()); 4337 if (!Unpacked) // Just adjusted the opcode. 4338 return Load; 4339 4340 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4341 4342 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4343 } 4344 4345 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4346 SelectionDAG &DAG, 4347 ArrayRef<SDValue> Ops) const { 4348 SDLoc DL(M); 4349 EVT LoadVT = M->getValueType(0); 4350 EVT EltType = LoadVT.getScalarType(); 4351 EVT IntVT = LoadVT.changeTypeToInteger(); 4352 4353 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4354 4355 unsigned Opc = 4356 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4357 4358 if (IsD16) { 4359 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4360 } 4361 4362 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4363 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4364 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4365 4366 if (isTypeLegal(LoadVT)) { 4367 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4368 M->getMemOperand(), DAG); 4369 } 4370 4371 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4372 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4373 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4374 M->getMemOperand(), DAG); 4375 return DAG.getMergeValues( 4376 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4377 DL); 4378 } 4379 4380 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4381 SDNode *N, SelectionDAG &DAG) { 4382 EVT VT = N->getValueType(0); 4383 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4384 int CondCode = CD->getSExtValue(); 4385 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4386 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4387 return DAG.getUNDEF(VT); 4388 4389 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4390 4391 SDValue LHS = N->getOperand(1); 4392 SDValue RHS = N->getOperand(2); 4393 4394 SDLoc DL(N); 4395 4396 EVT CmpVT = LHS.getValueType(); 4397 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4398 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4399 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4400 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4401 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4402 } 4403 4404 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4405 4406 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4407 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4408 4409 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4410 DAG.getCondCode(CCOpcode)); 4411 if (VT.bitsEq(CCVT)) 4412 return SetCC; 4413 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4414 } 4415 4416 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4417 SDNode *N, SelectionDAG &DAG) { 4418 EVT VT = N->getValueType(0); 4419 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4420 4421 int CondCode = CD->getSExtValue(); 4422 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4423 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4424 return DAG.getUNDEF(VT); 4425 } 4426 4427 SDValue Src0 = N->getOperand(1); 4428 SDValue Src1 = N->getOperand(2); 4429 EVT CmpVT = Src0.getValueType(); 4430 SDLoc SL(N); 4431 4432 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4433 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4434 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4435 } 4436 4437 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4438 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4439 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4440 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4441 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4442 Src1, DAG.getCondCode(CCOpcode)); 4443 if (VT.bitsEq(CCVT)) 4444 return SetCC; 4445 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4446 } 4447 4448 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4449 SelectionDAG &DAG) { 4450 EVT VT = N->getValueType(0); 4451 SDValue Src = N->getOperand(1); 4452 SDLoc SL(N); 4453 4454 if (Src.getOpcode() == ISD::SETCC) { 4455 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4456 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4457 Src.getOperand(1), Src.getOperand(2)); 4458 } 4459 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4460 // (ballot 0) -> 0 4461 if (Arg->isNullValue()) 4462 return DAG.getConstant(0, SL, VT); 4463 4464 // (ballot 1) -> EXEC/EXEC_LO 4465 if (Arg->isOne()) { 4466 Register Exec; 4467 if (VT.getScalarSizeInBits() == 32) 4468 Exec = AMDGPU::EXEC_LO; 4469 else if (VT.getScalarSizeInBits() == 64) 4470 Exec = AMDGPU::EXEC; 4471 else 4472 return SDValue(); 4473 4474 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4475 } 4476 } 4477 4478 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4479 // ISD::SETNE) 4480 return DAG.getNode( 4481 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4482 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4483 } 4484 4485 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4486 SmallVectorImpl<SDValue> &Results, 4487 SelectionDAG &DAG) const { 4488 switch (N->getOpcode()) { 4489 case ISD::INSERT_VECTOR_ELT: { 4490 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4491 Results.push_back(Res); 4492 return; 4493 } 4494 case ISD::EXTRACT_VECTOR_ELT: { 4495 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4496 Results.push_back(Res); 4497 return; 4498 } 4499 case ISD::INTRINSIC_WO_CHAIN: { 4500 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4501 switch (IID) { 4502 case Intrinsic::amdgcn_cvt_pkrtz: { 4503 SDValue Src0 = N->getOperand(1); 4504 SDValue Src1 = N->getOperand(2); 4505 SDLoc SL(N); 4506 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4507 Src0, Src1); 4508 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4509 return; 4510 } 4511 case Intrinsic::amdgcn_cvt_pknorm_i16: 4512 case Intrinsic::amdgcn_cvt_pknorm_u16: 4513 case Intrinsic::amdgcn_cvt_pk_i16: 4514 case Intrinsic::amdgcn_cvt_pk_u16: { 4515 SDValue Src0 = N->getOperand(1); 4516 SDValue Src1 = N->getOperand(2); 4517 SDLoc SL(N); 4518 unsigned Opcode; 4519 4520 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4521 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4522 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4523 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4524 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4525 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4526 else 4527 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4528 4529 EVT VT = N->getValueType(0); 4530 if (isTypeLegal(VT)) 4531 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4532 else { 4533 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4534 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4535 } 4536 return; 4537 } 4538 } 4539 break; 4540 } 4541 case ISD::INTRINSIC_W_CHAIN: { 4542 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4543 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4544 // FIXME: Hacky 4545 Results.push_back(Res.getOperand(0)); 4546 Results.push_back(Res.getOperand(1)); 4547 } else { 4548 Results.push_back(Res); 4549 Results.push_back(Res.getValue(1)); 4550 } 4551 return; 4552 } 4553 4554 break; 4555 } 4556 case ISD::SELECT: { 4557 SDLoc SL(N); 4558 EVT VT = N->getValueType(0); 4559 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4560 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4561 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4562 4563 EVT SelectVT = NewVT; 4564 if (NewVT.bitsLT(MVT::i32)) { 4565 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4566 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4567 SelectVT = MVT::i32; 4568 } 4569 4570 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4571 N->getOperand(0), LHS, RHS); 4572 4573 if (NewVT != SelectVT) 4574 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4575 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4576 return; 4577 } 4578 case ISD::FNEG: { 4579 if (N->getValueType(0) != MVT::v2f16) 4580 break; 4581 4582 SDLoc SL(N); 4583 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4584 4585 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4586 BC, 4587 DAG.getConstant(0x80008000, SL, MVT::i32)); 4588 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4589 return; 4590 } 4591 case ISD::FABS: { 4592 if (N->getValueType(0) != MVT::v2f16) 4593 break; 4594 4595 SDLoc SL(N); 4596 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4597 4598 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4599 BC, 4600 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4601 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4602 return; 4603 } 4604 default: 4605 break; 4606 } 4607 } 4608 4609 /// Helper function for LowerBRCOND 4610 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4611 4612 SDNode *Parent = Value.getNode(); 4613 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4614 I != E; ++I) { 4615 4616 if (I.getUse().get() != Value) 4617 continue; 4618 4619 if (I->getOpcode() == Opcode) 4620 return *I; 4621 } 4622 return nullptr; 4623 } 4624 4625 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4626 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4627 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4628 case Intrinsic::amdgcn_if: 4629 return AMDGPUISD::IF; 4630 case Intrinsic::amdgcn_else: 4631 return AMDGPUISD::ELSE; 4632 case Intrinsic::amdgcn_loop: 4633 return AMDGPUISD::LOOP; 4634 case Intrinsic::amdgcn_end_cf: 4635 llvm_unreachable("should not occur"); 4636 default: 4637 return 0; 4638 } 4639 } 4640 4641 // break, if_break, else_break are all only used as inputs to loop, not 4642 // directly as branch conditions. 4643 return 0; 4644 } 4645 4646 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4647 const Triple &TT = getTargetMachine().getTargetTriple(); 4648 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4649 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4650 AMDGPU::shouldEmitConstantsToTextSection(TT); 4651 } 4652 4653 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4654 // FIXME: Either avoid relying on address space here or change the default 4655 // address space for functions to avoid the explicit check. 4656 return (GV->getValueType()->isFunctionTy() || 4657 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4658 !shouldEmitFixup(GV) && 4659 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4660 } 4661 4662 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4663 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4664 } 4665 4666 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4667 if (!GV->hasExternalLinkage()) 4668 return true; 4669 4670 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4671 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4672 } 4673 4674 /// This transforms the control flow intrinsics to get the branch destination as 4675 /// last parameter, also switches branch target with BR if the need arise 4676 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4677 SelectionDAG &DAG) const { 4678 SDLoc DL(BRCOND); 4679 4680 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4681 SDValue Target = BRCOND.getOperand(2); 4682 SDNode *BR = nullptr; 4683 SDNode *SetCC = nullptr; 4684 4685 if (Intr->getOpcode() == ISD::SETCC) { 4686 // As long as we negate the condition everything is fine 4687 SetCC = Intr; 4688 Intr = SetCC->getOperand(0).getNode(); 4689 4690 } else { 4691 // Get the target from BR if we don't negate the condition 4692 BR = findUser(BRCOND, ISD::BR); 4693 Target = BR->getOperand(1); 4694 } 4695 4696 // FIXME: This changes the types of the intrinsics instead of introducing new 4697 // nodes with the correct types. 4698 // e.g. llvm.amdgcn.loop 4699 4700 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 4701 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 4702 4703 unsigned CFNode = isCFIntrinsic(Intr); 4704 if (CFNode == 0) { 4705 // This is a uniform branch so we don't need to legalize. 4706 return BRCOND; 4707 } 4708 4709 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4710 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4711 4712 assert(!SetCC || 4713 (SetCC->getConstantOperandVal(1) == 1 && 4714 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4715 ISD::SETNE)); 4716 4717 // operands of the new intrinsic call 4718 SmallVector<SDValue, 4> Ops; 4719 if (HaveChain) 4720 Ops.push_back(BRCOND.getOperand(0)); 4721 4722 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4723 Ops.push_back(Target); 4724 4725 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4726 4727 // build the new intrinsic call 4728 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4729 4730 if (!HaveChain) { 4731 SDValue Ops[] = { 4732 SDValue(Result, 0), 4733 BRCOND.getOperand(0) 4734 }; 4735 4736 Result = DAG.getMergeValues(Ops, DL).getNode(); 4737 } 4738 4739 if (BR) { 4740 // Give the branch instruction our target 4741 SDValue Ops[] = { 4742 BR->getOperand(0), 4743 BRCOND.getOperand(2) 4744 }; 4745 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4746 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4747 } 4748 4749 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4750 4751 // Copy the intrinsic results to registers 4752 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4753 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4754 if (!CopyToReg) 4755 continue; 4756 4757 Chain = DAG.getCopyToReg( 4758 Chain, DL, 4759 CopyToReg->getOperand(1), 4760 SDValue(Result, i - 1), 4761 SDValue()); 4762 4763 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4764 } 4765 4766 // Remove the old intrinsic from the chain 4767 DAG.ReplaceAllUsesOfValueWith( 4768 SDValue(Intr, Intr->getNumValues() - 1), 4769 Intr->getOperand(0)); 4770 4771 return Chain; 4772 } 4773 4774 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4775 SelectionDAG &DAG) const { 4776 MVT VT = Op.getSimpleValueType(); 4777 SDLoc DL(Op); 4778 // Checking the depth 4779 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4780 return DAG.getConstant(0, DL, VT); 4781 4782 MachineFunction &MF = DAG.getMachineFunction(); 4783 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4784 // Check for kernel and shader functions 4785 if (Info->isEntryFunction()) 4786 return DAG.getConstant(0, DL, VT); 4787 4788 MachineFrameInfo &MFI = MF.getFrameInfo(); 4789 // There is a call to @llvm.returnaddress in this function 4790 MFI.setReturnAddressIsTaken(true); 4791 4792 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4793 // Get the return address reg and mark it as an implicit live-in 4794 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4795 4796 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4797 } 4798 4799 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 4800 SDValue Op, 4801 const SDLoc &DL, 4802 EVT VT) const { 4803 return Op.getValueType().bitsLE(VT) ? 4804 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4805 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 4806 DAG.getTargetConstant(0, DL, MVT::i32)); 4807 } 4808 4809 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4810 assert(Op.getValueType() == MVT::f16 && 4811 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4812 4813 SDValue Src = Op.getOperand(0); 4814 EVT SrcVT = Src.getValueType(); 4815 if (SrcVT != MVT::f64) 4816 return Op; 4817 4818 SDLoc DL(Op); 4819 4820 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4821 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4822 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4823 } 4824 4825 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4826 SelectionDAG &DAG) const { 4827 EVT VT = Op.getValueType(); 4828 const MachineFunction &MF = DAG.getMachineFunction(); 4829 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4830 bool IsIEEEMode = Info->getMode().IEEE; 4831 4832 // FIXME: Assert during selection that this is only selected for 4833 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4834 // mode functions, but this happens to be OK since it's only done in cases 4835 // where there is known no sNaN. 4836 if (IsIEEEMode) 4837 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 4838 4839 if (VT == MVT::v4f16) 4840 return splitBinaryVectorOp(Op, DAG); 4841 return Op; 4842 } 4843 4844 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4845 SDLoc SL(Op); 4846 SDValue Chain = Op.getOperand(0); 4847 4848 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4849 !Subtarget->isTrapHandlerEnabled()) 4850 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4851 4852 MachineFunction &MF = DAG.getMachineFunction(); 4853 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4854 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4855 assert(UserSGPR != AMDGPU::NoRegister); 4856 SDValue QueuePtr = CreateLiveInRegister( 4857 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4858 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4859 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4860 QueuePtr, SDValue()); 4861 SDValue Ops[] = { 4862 ToReg, 4863 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 4864 SGPR01, 4865 ToReg.getValue(1) 4866 }; 4867 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4868 } 4869 4870 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 4871 SDLoc SL(Op); 4872 SDValue Chain = Op.getOperand(0); 4873 MachineFunction &MF = DAG.getMachineFunction(); 4874 4875 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4876 !Subtarget->isTrapHandlerEnabled()) { 4877 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4878 "debugtrap handler not supported", 4879 Op.getDebugLoc(), 4880 DS_Warning); 4881 LLVMContext &Ctx = MF.getFunction().getContext(); 4882 Ctx.diagnose(NoTrap); 4883 return Chain; 4884 } 4885 4886 SDValue Ops[] = { 4887 Chain, 4888 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 4889 }; 4890 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4891 } 4892 4893 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4894 SelectionDAG &DAG) const { 4895 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4896 if (Subtarget->hasApertureRegs()) { 4897 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 4898 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4899 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4900 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 4901 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4902 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4903 unsigned Encoding = 4904 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4905 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4906 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4907 4908 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4909 SDValue ApertureReg = SDValue( 4910 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4911 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4912 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4913 } 4914 4915 MachineFunction &MF = DAG.getMachineFunction(); 4916 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4917 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4918 assert(UserSGPR != AMDGPU::NoRegister); 4919 4920 SDValue QueuePtr = CreateLiveInRegister( 4921 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4922 4923 // Offset into amd_queue_t for group_segment_aperture_base_hi / 4924 // private_segment_aperture_base_hi. 4925 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 4926 4927 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 4928 4929 // TODO: Use custom target PseudoSourceValue. 4930 // TODO: We should use the value from the IR intrinsic call, but it might not 4931 // be available and how do we get it? 4932 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 4933 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4934 MinAlign(64, StructOffset), 4935 MachineMemOperand::MODereferenceable | 4936 MachineMemOperand::MOInvariant); 4937 } 4938 4939 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4940 SelectionDAG &DAG) const { 4941 SDLoc SL(Op); 4942 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4943 4944 SDValue Src = ASC->getOperand(0); 4945 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4946 4947 const AMDGPUTargetMachine &TM = 4948 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4949 4950 // flat -> local/private 4951 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4952 unsigned DestAS = ASC->getDestAddressSpace(); 4953 4954 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 4955 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 4956 unsigned NullVal = TM.getNullPointerValue(DestAS); 4957 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4958 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4959 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4960 4961 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4962 NonNull, Ptr, SegmentNullPtr); 4963 } 4964 } 4965 4966 // local/private -> flat 4967 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4968 unsigned SrcAS = ASC->getSrcAddressSpace(); 4969 4970 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 4971 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 4972 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4973 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4974 4975 SDValue NonNull 4976 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4977 4978 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4979 SDValue CvtPtr 4980 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4981 4982 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4983 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4984 FlatNullPtr); 4985 } 4986 } 4987 4988 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 4989 Src.getValueType() == MVT::i64) 4990 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4991 4992 // global <-> flat are no-ops and never emitted. 4993 4994 const MachineFunction &MF = DAG.getMachineFunction(); 4995 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 4996 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 4997 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 4998 4999 return DAG.getUNDEF(ASC->getValueType(0)); 5000 } 5001 5002 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5003 // the small vector and inserting them into the big vector. That is better than 5004 // the default expansion of doing it via a stack slot. Even though the use of 5005 // the stack slot would be optimized away afterwards, the stack slot itself 5006 // remains. 5007 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5008 SelectionDAG &DAG) const { 5009 SDValue Vec = Op.getOperand(0); 5010 SDValue Ins = Op.getOperand(1); 5011 SDValue Idx = Op.getOperand(2); 5012 EVT VecVT = Vec.getValueType(); 5013 EVT InsVT = Ins.getValueType(); 5014 EVT EltVT = VecVT.getVectorElementType(); 5015 unsigned InsNumElts = InsVT.getVectorNumElements(); 5016 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5017 SDLoc SL(Op); 5018 5019 for (unsigned I = 0; I != InsNumElts; ++I) { 5020 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5021 DAG.getConstant(I, SL, MVT::i32)); 5022 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5023 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5024 } 5025 return Vec; 5026 } 5027 5028 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5029 SelectionDAG &DAG) const { 5030 SDValue Vec = Op.getOperand(0); 5031 SDValue InsVal = Op.getOperand(1); 5032 SDValue Idx = Op.getOperand(2); 5033 EVT VecVT = Vec.getValueType(); 5034 EVT EltVT = VecVT.getVectorElementType(); 5035 unsigned VecSize = VecVT.getSizeInBits(); 5036 unsigned EltSize = EltVT.getSizeInBits(); 5037 5038 5039 assert(VecSize <= 64); 5040 5041 unsigned NumElts = VecVT.getVectorNumElements(); 5042 SDLoc SL(Op); 5043 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5044 5045 if (NumElts == 4 && EltSize == 16 && KIdx) { 5046 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5047 5048 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5049 DAG.getConstant(0, SL, MVT::i32)); 5050 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5051 DAG.getConstant(1, SL, MVT::i32)); 5052 5053 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5054 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5055 5056 unsigned Idx = KIdx->getZExtValue(); 5057 bool InsertLo = Idx < 2; 5058 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5059 InsertLo ? LoVec : HiVec, 5060 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5061 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5062 5063 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5064 5065 SDValue Concat = InsertLo ? 5066 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5067 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5068 5069 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5070 } 5071 5072 if (isa<ConstantSDNode>(Idx)) 5073 return SDValue(); 5074 5075 MVT IntVT = MVT::getIntegerVT(VecSize); 5076 5077 // Avoid stack access for dynamic indexing. 5078 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5079 5080 // Create a congruent vector with the target value in each element so that 5081 // the required element can be masked and ORed into the target vector. 5082 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5083 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5084 5085 assert(isPowerOf2_32(EltSize)); 5086 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5087 5088 // Convert vector index to bit-index. 5089 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5090 5091 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5092 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5093 DAG.getConstant(0xffff, SL, IntVT), 5094 ScaledIdx); 5095 5096 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5097 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5098 DAG.getNOT(SL, BFM, IntVT), BCVec); 5099 5100 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5101 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5102 } 5103 5104 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5105 SelectionDAG &DAG) const { 5106 SDLoc SL(Op); 5107 5108 EVT ResultVT = Op.getValueType(); 5109 SDValue Vec = Op.getOperand(0); 5110 SDValue Idx = Op.getOperand(1); 5111 EVT VecVT = Vec.getValueType(); 5112 unsigned VecSize = VecVT.getSizeInBits(); 5113 EVT EltVT = VecVT.getVectorElementType(); 5114 assert(VecSize <= 64); 5115 5116 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5117 5118 // Make sure we do any optimizations that will make it easier to fold 5119 // source modifiers before obscuring it with bit operations. 5120 5121 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5122 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5123 return Combined; 5124 5125 unsigned EltSize = EltVT.getSizeInBits(); 5126 assert(isPowerOf2_32(EltSize)); 5127 5128 MVT IntVT = MVT::getIntegerVT(VecSize); 5129 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5130 5131 // Convert vector index to bit-index (* EltSize) 5132 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5133 5134 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5135 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5136 5137 if (ResultVT == MVT::f16) { 5138 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5139 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5140 } 5141 5142 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5143 } 5144 5145 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5146 assert(Elt % 2 == 0); 5147 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5148 } 5149 5150 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5151 SelectionDAG &DAG) const { 5152 SDLoc SL(Op); 5153 EVT ResultVT = Op.getValueType(); 5154 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5155 5156 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5157 EVT EltVT = PackVT.getVectorElementType(); 5158 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5159 5160 // vector_shuffle <0,1,6,7> lhs, rhs 5161 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5162 // 5163 // vector_shuffle <6,7,2,3> lhs, rhs 5164 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5165 // 5166 // vector_shuffle <6,7,0,1> lhs, rhs 5167 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5168 5169 // Avoid scalarizing when both halves are reading from consecutive elements. 5170 SmallVector<SDValue, 4> Pieces; 5171 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5172 if (elementPairIsContiguous(SVN->getMask(), I)) { 5173 const int Idx = SVN->getMaskElt(I); 5174 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5175 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5176 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5177 PackVT, SVN->getOperand(VecIdx), 5178 DAG.getConstant(EltIdx, SL, MVT::i32)); 5179 Pieces.push_back(SubVec); 5180 } else { 5181 const int Idx0 = SVN->getMaskElt(I); 5182 const int Idx1 = SVN->getMaskElt(I + 1); 5183 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5184 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5185 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5186 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5187 5188 SDValue Vec0 = SVN->getOperand(VecIdx0); 5189 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5190 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5191 5192 SDValue Vec1 = SVN->getOperand(VecIdx1); 5193 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5194 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5195 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5196 } 5197 } 5198 5199 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5200 } 5201 5202 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5203 SelectionDAG &DAG) const { 5204 SDLoc SL(Op); 5205 EVT VT = Op.getValueType(); 5206 5207 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5208 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5209 5210 // Turn into pair of packed build_vectors. 5211 // TODO: Special case for constants that can be materialized with s_mov_b64. 5212 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5213 { Op.getOperand(0), Op.getOperand(1) }); 5214 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5215 { Op.getOperand(2), Op.getOperand(3) }); 5216 5217 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5218 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5219 5220 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5221 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5222 } 5223 5224 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5225 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5226 5227 SDValue Lo = Op.getOperand(0); 5228 SDValue Hi = Op.getOperand(1); 5229 5230 // Avoid adding defined bits with the zero_extend. 5231 if (Hi.isUndef()) { 5232 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5233 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5234 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5235 } 5236 5237 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5238 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5239 5240 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5241 DAG.getConstant(16, SL, MVT::i32)); 5242 if (Lo.isUndef()) 5243 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5244 5245 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5246 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5247 5248 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5249 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5250 } 5251 5252 bool 5253 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5254 // We can fold offsets for anything that doesn't require a GOT relocation. 5255 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5256 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5257 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5258 !shouldEmitGOTReloc(GA->getGlobal()); 5259 } 5260 5261 static SDValue 5262 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5263 const SDLoc &DL, unsigned Offset, EVT PtrVT, 5264 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5265 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5266 // lowered to the following code sequence: 5267 // 5268 // For constant address space: 5269 // s_getpc_b64 s[0:1] 5270 // s_add_u32 s0, s0, $symbol 5271 // s_addc_u32 s1, s1, 0 5272 // 5273 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5274 // a fixup or relocation is emitted to replace $symbol with a literal 5275 // constant, which is a pc-relative offset from the encoding of the $symbol 5276 // operand to the global variable. 5277 // 5278 // For global address space: 5279 // s_getpc_b64 s[0:1] 5280 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5281 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5282 // 5283 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5284 // fixups or relocations are emitted to replace $symbol@*@lo and 5285 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5286 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5287 // operand to the global variable. 5288 // 5289 // What we want here is an offset from the value returned by s_getpc 5290 // (which is the address of the s_add_u32 instruction) to the global 5291 // variable, but since the encoding of $symbol starts 4 bytes after the start 5292 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5293 // small. This requires us to add 4 to the global variable offset in order to 5294 // compute the correct address. 5295 SDValue PtrLo = 5296 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5297 SDValue PtrHi; 5298 if (GAFlags == SIInstrInfo::MO_NONE) { 5299 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5300 } else { 5301 PtrHi = 5302 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5303 } 5304 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5305 } 5306 5307 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5308 SDValue Op, 5309 SelectionDAG &DAG) const { 5310 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5311 const GlobalValue *GV = GSD->getGlobal(); 5312 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5313 shouldUseLDSConstAddress(GV)) || 5314 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5315 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5316 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5317 5318 SDLoc DL(GSD); 5319 EVT PtrVT = Op.getValueType(); 5320 5321 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5322 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5323 SIInstrInfo::MO_ABS32_LO); 5324 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5325 } 5326 5327 if (shouldEmitFixup(GV)) 5328 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5329 else if (shouldEmitPCReloc(GV)) 5330 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5331 SIInstrInfo::MO_REL32); 5332 5333 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5334 SIInstrInfo::MO_GOTPCREL32); 5335 5336 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5337 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5338 const DataLayout &DataLayout = DAG.getDataLayout(); 5339 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 5340 MachinePointerInfo PtrInfo 5341 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5342 5343 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 5344 MachineMemOperand::MODereferenceable | 5345 MachineMemOperand::MOInvariant); 5346 } 5347 5348 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5349 const SDLoc &DL, SDValue V) const { 5350 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5351 // the destination register. 5352 // 5353 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5354 // so we will end up with redundant moves to m0. 5355 // 5356 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5357 5358 // A Null SDValue creates a glue result. 5359 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5360 V, Chain); 5361 return SDValue(M0, 0); 5362 } 5363 5364 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5365 SDValue Op, 5366 MVT VT, 5367 unsigned Offset) const { 5368 SDLoc SL(Op); 5369 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 5370 DAG.getEntryNode(), Offset, 4, false); 5371 // The local size values will have the hi 16-bits as zero. 5372 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5373 DAG.getValueType(VT)); 5374 } 5375 5376 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5377 EVT VT) { 5378 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5379 "non-hsa intrinsic with hsa target", 5380 DL.getDebugLoc()); 5381 DAG.getContext()->diagnose(BadIntrin); 5382 return DAG.getUNDEF(VT); 5383 } 5384 5385 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5386 EVT VT) { 5387 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5388 "intrinsic not supported on subtarget", 5389 DL.getDebugLoc()); 5390 DAG.getContext()->diagnose(BadIntrin); 5391 return DAG.getUNDEF(VT); 5392 } 5393 5394 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5395 ArrayRef<SDValue> Elts) { 5396 assert(!Elts.empty()); 5397 MVT Type; 5398 unsigned NumElts; 5399 5400 if (Elts.size() == 1) { 5401 Type = MVT::f32; 5402 NumElts = 1; 5403 } else if (Elts.size() == 2) { 5404 Type = MVT::v2f32; 5405 NumElts = 2; 5406 } else if (Elts.size() == 3) { 5407 Type = MVT::v3f32; 5408 NumElts = 3; 5409 } else if (Elts.size() <= 4) { 5410 Type = MVT::v4f32; 5411 NumElts = 4; 5412 } else if (Elts.size() <= 8) { 5413 Type = MVT::v8f32; 5414 NumElts = 8; 5415 } else { 5416 assert(Elts.size() <= 16); 5417 Type = MVT::v16f32; 5418 NumElts = 16; 5419 } 5420 5421 SmallVector<SDValue, 16> VecElts(NumElts); 5422 for (unsigned i = 0; i < Elts.size(); ++i) { 5423 SDValue Elt = Elts[i]; 5424 if (Elt.getValueType() != MVT::f32) 5425 Elt = DAG.getBitcast(MVT::f32, Elt); 5426 VecElts[i] = Elt; 5427 } 5428 for (unsigned i = Elts.size(); i < NumElts; ++i) 5429 VecElts[i] = DAG.getUNDEF(MVT::f32); 5430 5431 if (NumElts == 1) 5432 return VecElts[0]; 5433 return DAG.getBuildVector(Type, DL, VecElts); 5434 } 5435 5436 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5437 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5438 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5439 5440 uint64_t Value = CachePolicyConst->getZExtValue(); 5441 SDLoc DL(CachePolicy); 5442 if (GLC) { 5443 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5444 Value &= ~(uint64_t)0x1; 5445 } 5446 if (SLC) { 5447 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5448 Value &= ~(uint64_t)0x2; 5449 } 5450 if (DLC) { 5451 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5452 Value &= ~(uint64_t)0x4; 5453 } 5454 5455 return Value == 0; 5456 } 5457 5458 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5459 SDValue Src, int ExtraElts) { 5460 EVT SrcVT = Src.getValueType(); 5461 5462 SmallVector<SDValue, 8> Elts; 5463 5464 if (SrcVT.isVector()) 5465 DAG.ExtractVectorElements(Src, Elts); 5466 else 5467 Elts.push_back(Src); 5468 5469 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5470 while (ExtraElts--) 5471 Elts.push_back(Undef); 5472 5473 return DAG.getBuildVector(CastVT, DL, Elts); 5474 } 5475 5476 // Re-construct the required return value for a image load intrinsic. 5477 // This is more complicated due to the optional use TexFailCtrl which means the required 5478 // return type is an aggregate 5479 static SDValue constructRetValue(SelectionDAG &DAG, 5480 MachineSDNode *Result, 5481 ArrayRef<EVT> ResultTypes, 5482 bool IsTexFail, bool Unpacked, bool IsD16, 5483 int DMaskPop, int NumVDataDwords, 5484 const SDLoc &DL, LLVMContext &Context) { 5485 // Determine the required return type. This is the same regardless of IsTexFail flag 5486 EVT ReqRetVT = ResultTypes[0]; 5487 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5488 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5489 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5490 5491 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5492 DMaskPop : (DMaskPop + 1) / 2; 5493 5494 MVT DataDwordVT = NumDataDwords == 1 ? 5495 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5496 5497 MVT MaskPopVT = MaskPopDwords == 1 ? 5498 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5499 5500 SDValue Data(Result, 0); 5501 SDValue TexFail; 5502 5503 if (IsTexFail) { 5504 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5505 if (MaskPopVT.isVector()) { 5506 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5507 SDValue(Result, 0), ZeroIdx); 5508 } else { 5509 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5510 SDValue(Result, 0), ZeroIdx); 5511 } 5512 5513 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5514 SDValue(Result, 0), 5515 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5516 } 5517 5518 if (DataDwordVT.isVector()) 5519 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5520 NumDataDwords - MaskPopDwords); 5521 5522 if (IsD16) 5523 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5524 5525 if (!ReqRetVT.isVector()) 5526 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5527 5528 Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data); 5529 5530 if (TexFail) 5531 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5532 5533 if (Result->getNumValues() == 1) 5534 return Data; 5535 5536 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5537 } 5538 5539 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5540 SDValue *LWE, bool &IsTexFail) { 5541 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5542 5543 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5544 if (Value) { 5545 IsTexFail = true; 5546 } 5547 5548 SDLoc DL(TexFailCtrlConst); 5549 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5550 Value &= ~(uint64_t)0x1; 5551 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5552 Value &= ~(uint64_t)0x2; 5553 5554 return Value == 0; 5555 } 5556 5557 SDValue SITargetLowering::lowerImage(SDValue Op, 5558 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5559 SelectionDAG &DAG) const { 5560 SDLoc DL(Op); 5561 MachineFunction &MF = DAG.getMachineFunction(); 5562 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5563 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5564 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5565 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5566 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5567 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5568 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5569 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5570 unsigned IntrOpcode = Intr->BaseOpcode; 5571 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5572 5573 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5574 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5575 bool IsD16 = false; 5576 bool IsA16 = false; 5577 SDValue VData; 5578 int NumVDataDwords; 5579 bool AdjustRetType = false; 5580 5581 unsigned AddrIdx; // Index of first address argument 5582 unsigned DMask; 5583 unsigned DMaskLanes = 0; 5584 5585 if (BaseOpcode->Atomic) { 5586 VData = Op.getOperand(2); 5587 5588 bool Is64Bit = VData.getValueType() == MVT::i64; 5589 if (BaseOpcode->AtomicX2) { 5590 SDValue VData2 = Op.getOperand(3); 5591 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5592 {VData, VData2}); 5593 if (Is64Bit) 5594 VData = DAG.getBitcast(MVT::v4i32, VData); 5595 5596 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5597 DMask = Is64Bit ? 0xf : 0x3; 5598 NumVDataDwords = Is64Bit ? 4 : 2; 5599 AddrIdx = 4; 5600 } else { 5601 DMask = Is64Bit ? 0x3 : 0x1; 5602 NumVDataDwords = Is64Bit ? 2 : 1; 5603 AddrIdx = 3; 5604 } 5605 } else { 5606 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5607 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5608 DMask = DMaskConst->getZExtValue(); 5609 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5610 5611 if (BaseOpcode->Store) { 5612 VData = Op.getOperand(2); 5613 5614 MVT StoreVT = VData.getSimpleValueType(); 5615 if (StoreVT.getScalarType() == MVT::f16) { 5616 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5617 return Op; // D16 is unsupported for this instruction 5618 5619 IsD16 = true; 5620 VData = handleD16VData(VData, DAG); 5621 } 5622 5623 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5624 } else { 5625 // Work out the num dwords based on the dmask popcount and underlying type 5626 // and whether packing is supported. 5627 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5628 if (LoadVT.getScalarType() == MVT::f16) { 5629 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5630 return Op; // D16 is unsupported for this instruction 5631 5632 IsD16 = true; 5633 } 5634 5635 // Confirm that the return type is large enough for the dmask specified 5636 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5637 (!LoadVT.isVector() && DMaskLanes > 1)) 5638 return Op; 5639 5640 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5641 NumVDataDwords = (DMaskLanes + 1) / 2; 5642 else 5643 NumVDataDwords = DMaskLanes; 5644 5645 AdjustRetType = true; 5646 } 5647 5648 AddrIdx = DMaskIdx + 1; 5649 } 5650 5651 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5652 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5653 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5654 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5655 NumCoords + NumLCM; 5656 unsigned NumMIVAddrs = NumVAddrs; 5657 5658 SmallVector<SDValue, 4> VAddrs; 5659 5660 // Optimize _L to _LZ when _L is zero 5661 if (LZMappingInfo) { 5662 if (auto ConstantLod = 5663 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5664 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5665 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5666 NumMIVAddrs--; // remove 'lod' 5667 } 5668 } 5669 } 5670 5671 // Optimize _mip away, when 'lod' is zero 5672 if (MIPMappingInfo) { 5673 if (auto ConstantLod = 5674 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5675 if (ConstantLod->isNullValue()) { 5676 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5677 NumMIVAddrs--; // remove 'lod' 5678 } 5679 } 5680 } 5681 5682 // Check for 16 bit addresses and pack if true. 5683 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5684 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5685 const MVT VAddrScalarVT = VAddrVT.getScalarType(); 5686 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) { 5687 // Illegal to use a16 images 5688 if (!ST->hasFeature(AMDGPU::FeatureR128A16) && !ST->hasFeature(AMDGPU::FeatureGFX10A16)) 5689 return Op; 5690 5691 IsA16 = true; 5692 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5693 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) { 5694 SDValue AddrLo; 5695 // Push back extra arguments. 5696 if (i < DimIdx) { 5697 AddrLo = Op.getOperand(i); 5698 } else { 5699 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, 5700 // in 1D, derivatives dx/dh and dx/dv are packed with undef. 5701 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) || 5702 ((NumGradients / 2) % 2 == 1 && 5703 (i == DimIdx + (NumGradients / 2) - 1 || 5704 i == DimIdx + NumGradients - 1))) { 5705 AddrLo = Op.getOperand(i); 5706 if (AddrLo.getValueType() != MVT::i16) 5707 AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i)); 5708 AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo); 5709 } else { 5710 AddrLo = DAG.getBuildVector(VectorVT, DL, 5711 {Op.getOperand(i), Op.getOperand(i + 1)}); 5712 i++; 5713 } 5714 AddrLo = DAG.getBitcast(MVT::f32, AddrLo); 5715 } 5716 VAddrs.push_back(AddrLo); 5717 } 5718 } else { 5719 for (unsigned i = 0; i < NumMIVAddrs; ++i) 5720 VAddrs.push_back(Op.getOperand(AddrIdx + i)); 5721 } 5722 5723 // If the register allocator cannot place the address registers contiguously 5724 // without introducing moves, then using the non-sequential address encoding 5725 // is always preferable, since it saves VALU instructions and is usually a 5726 // wash in terms of code size or even better. 5727 // 5728 // However, we currently have no way of hinting to the register allocator that 5729 // MIMG addresses should be placed contiguously when it is possible to do so, 5730 // so force non-NSA for the common 2-address case as a heuristic. 5731 // 5732 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5733 // allocation when possible. 5734 bool UseNSA = 5735 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5736 SDValue VAddr; 5737 if (!UseNSA) 5738 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5739 5740 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5741 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5742 unsigned CtrlIdx; // Index of texfailctrl argument 5743 SDValue Unorm; 5744 if (!BaseOpcode->Sampler) { 5745 Unorm = True; 5746 CtrlIdx = AddrIdx + NumVAddrs + 1; 5747 } else { 5748 auto UnormConst = 5749 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 5750 5751 Unorm = UnormConst->getZExtValue() ? True : False; 5752 CtrlIdx = AddrIdx + NumVAddrs + 3; 5753 } 5754 5755 SDValue TFE; 5756 SDValue LWE; 5757 SDValue TexFail = Op.getOperand(CtrlIdx); 5758 bool IsTexFail = false; 5759 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 5760 return Op; 5761 5762 if (IsTexFail) { 5763 if (!DMaskLanes) { 5764 // Expecting to get an error flag since TFC is on - and dmask is 0 5765 // Force dmask to be at least 1 otherwise the instruction will fail 5766 DMask = 0x1; 5767 DMaskLanes = 1; 5768 NumVDataDwords = 1; 5769 } 5770 NumVDataDwords += 1; 5771 AdjustRetType = true; 5772 } 5773 5774 // Has something earlier tagged that the return type needs adjusting 5775 // This happens if the instruction is a load or has set TexFailCtrl flags 5776 if (AdjustRetType) { 5777 // NumVDataDwords reflects the true number of dwords required in the return type 5778 if (DMaskLanes == 0 && !BaseOpcode->Store) { 5779 // This is a no-op load. This can be eliminated 5780 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 5781 if (isa<MemSDNode>(Op)) 5782 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 5783 return Undef; 5784 } 5785 5786 EVT NewVT = NumVDataDwords > 1 ? 5787 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 5788 : MVT::i32; 5789 5790 ResultTypes[0] = NewVT; 5791 if (ResultTypes.size() == 3) { 5792 // Original result was aggregate type used for TexFailCtrl results 5793 // The actual instruction returns as a vector type which has now been 5794 // created. Remove the aggregate result. 5795 ResultTypes.erase(&ResultTypes[1]); 5796 } 5797 } 5798 5799 SDValue GLC; 5800 SDValue SLC; 5801 SDValue DLC; 5802 if (BaseOpcode->Atomic) { 5803 GLC = True; // TODO no-return optimization 5804 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 5805 IsGFX10 ? &DLC : nullptr)) 5806 return Op; 5807 } else { 5808 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 5809 IsGFX10 ? &DLC : nullptr)) 5810 return Op; 5811 } 5812 5813 SmallVector<SDValue, 26> Ops; 5814 if (BaseOpcode->Store || BaseOpcode->Atomic) 5815 Ops.push_back(VData); // vdata 5816 if (UseNSA) { 5817 for (const SDValue &Addr : VAddrs) 5818 Ops.push_back(Addr); 5819 } else { 5820 Ops.push_back(VAddr); 5821 } 5822 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 5823 if (BaseOpcode->Sampler) 5824 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 5825 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 5826 if (IsGFX10) 5827 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 5828 Ops.push_back(Unorm); 5829 if (IsGFX10) 5830 Ops.push_back(DLC); 5831 Ops.push_back(GLC); 5832 Ops.push_back(SLC); 5833 Ops.push_back(IsA16 && // r128, a16 for gfx9 5834 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 5835 if (IsGFX10) 5836 Ops.push_back(IsA16 ? True : False); 5837 Ops.push_back(TFE); 5838 Ops.push_back(LWE); 5839 if (!IsGFX10) 5840 Ops.push_back(DimInfo->DA ? True : False); 5841 if (BaseOpcode->HasD16) 5842 Ops.push_back(IsD16 ? True : False); 5843 if (isa<MemSDNode>(Op)) 5844 Ops.push_back(Op.getOperand(0)); // chain 5845 5846 int NumVAddrDwords = 5847 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 5848 int Opcode = -1; 5849 5850 if (IsGFX10) { 5851 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 5852 UseNSA ? AMDGPU::MIMGEncGfx10NSA 5853 : AMDGPU::MIMGEncGfx10Default, 5854 NumVDataDwords, NumVAddrDwords); 5855 } else { 5856 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5857 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 5858 NumVDataDwords, NumVAddrDwords); 5859 if (Opcode == -1) 5860 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 5861 NumVDataDwords, NumVAddrDwords); 5862 } 5863 assert(Opcode != -1); 5864 5865 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 5866 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 5867 MachineMemOperand *MemRef = MemOp->getMemOperand(); 5868 DAG.setNodeMemRefs(NewNode, {MemRef}); 5869 } 5870 5871 if (BaseOpcode->AtomicX2) { 5872 SmallVector<SDValue, 1> Elt; 5873 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 5874 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 5875 } else if (!BaseOpcode->Store) { 5876 return constructRetValue(DAG, NewNode, 5877 OrigResultTypes, IsTexFail, 5878 Subtarget->hasUnpackedD16VMem(), IsD16, 5879 DMaskLanes, NumVDataDwords, DL, 5880 *DAG.getContext()); 5881 } 5882 5883 return SDValue(NewNode, 0); 5884 } 5885 5886 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 5887 SDValue Offset, SDValue CachePolicy, 5888 SelectionDAG &DAG) const { 5889 MachineFunction &MF = DAG.getMachineFunction(); 5890 5891 const DataLayout &DataLayout = DAG.getDataLayout(); 5892 Align Alignment = 5893 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 5894 5895 MachineMemOperand *MMO = MF.getMachineMemOperand( 5896 MachinePointerInfo(), 5897 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 5898 MachineMemOperand::MOInvariant, 5899 VT.getStoreSize(), Alignment); 5900 5901 if (!Offset->isDivergent()) { 5902 SDValue Ops[] = { 5903 Rsrc, 5904 Offset, // Offset 5905 CachePolicy 5906 }; 5907 5908 // Widen vec3 load to vec4. 5909 if (VT.isVector() && VT.getVectorNumElements() == 3) { 5910 EVT WidenedVT = 5911 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 5912 auto WidenedOp = DAG.getMemIntrinsicNode( 5913 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 5914 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 5915 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 5916 DAG.getVectorIdxConstant(0, DL)); 5917 return Subvector; 5918 } 5919 5920 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 5921 DAG.getVTList(VT), Ops, VT, MMO); 5922 } 5923 5924 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 5925 // assume that the buffer is unswizzled. 5926 SmallVector<SDValue, 4> Loads; 5927 unsigned NumLoads = 1; 5928 MVT LoadVT = VT.getSimpleVT(); 5929 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 5930 assert((LoadVT.getScalarType() == MVT::i32 || 5931 LoadVT.getScalarType() == MVT::f32)); 5932 5933 if (NumElts == 8 || NumElts == 16) { 5934 NumLoads = NumElts / 4; 5935 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 5936 } 5937 5938 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 5939 SDValue Ops[] = { 5940 DAG.getEntryNode(), // Chain 5941 Rsrc, // rsrc 5942 DAG.getConstant(0, DL, MVT::i32), // vindex 5943 {}, // voffset 5944 {}, // soffset 5945 {}, // offset 5946 CachePolicy, // cachepolicy 5947 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 5948 }; 5949 5950 // Use the alignment to ensure that the required offsets will fit into the 5951 // immediate offsets. 5952 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 5953 5954 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 5955 for (unsigned i = 0; i < NumLoads; ++i) { 5956 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 5957 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 5958 LoadVT, MMO, DAG)); 5959 } 5960 5961 if (NumElts == 8 || NumElts == 16) 5962 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 5963 5964 return Loads[0]; 5965 } 5966 5967 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 5968 SelectionDAG &DAG) const { 5969 MachineFunction &MF = DAG.getMachineFunction(); 5970 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 5971 5972 EVT VT = Op.getValueType(); 5973 SDLoc DL(Op); 5974 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5975 5976 // TODO: Should this propagate fast-math-flags? 5977 5978 switch (IntrinsicID) { 5979 case Intrinsic::amdgcn_implicit_buffer_ptr: { 5980 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 5981 return emitNonHSAIntrinsicError(DAG, DL, VT); 5982 return getPreloadedValue(DAG, *MFI, VT, 5983 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 5984 } 5985 case Intrinsic::amdgcn_dispatch_ptr: 5986 case Intrinsic::amdgcn_queue_ptr: { 5987 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 5988 DiagnosticInfoUnsupported BadIntrin( 5989 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 5990 DL.getDebugLoc()); 5991 DAG.getContext()->diagnose(BadIntrin); 5992 return DAG.getUNDEF(VT); 5993 } 5994 5995 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 5996 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 5997 return getPreloadedValue(DAG, *MFI, VT, RegID); 5998 } 5999 case Intrinsic::amdgcn_implicitarg_ptr: { 6000 if (MFI->isEntryFunction()) 6001 return getImplicitArgPtr(DAG, DL); 6002 return getPreloadedValue(DAG, *MFI, VT, 6003 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6004 } 6005 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6006 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6007 // This only makes sense to call in a kernel, so just lower to null. 6008 return DAG.getConstant(0, DL, VT); 6009 } 6010 6011 return getPreloadedValue(DAG, *MFI, VT, 6012 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6013 } 6014 case Intrinsic::amdgcn_dispatch_id: { 6015 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6016 } 6017 case Intrinsic::amdgcn_rcp: 6018 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6019 case Intrinsic::amdgcn_rsq: 6020 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6021 case Intrinsic::amdgcn_rsq_legacy: 6022 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6023 return emitRemovedIntrinsicError(DAG, DL, VT); 6024 return SDValue(); 6025 case Intrinsic::amdgcn_rcp_legacy: 6026 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6027 return emitRemovedIntrinsicError(DAG, DL, VT); 6028 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6029 case Intrinsic::amdgcn_rsq_clamp: { 6030 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6031 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6032 6033 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6034 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6035 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6036 6037 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6038 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6039 DAG.getConstantFP(Max, DL, VT)); 6040 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6041 DAG.getConstantFP(Min, DL, VT)); 6042 } 6043 case Intrinsic::r600_read_ngroups_x: 6044 if (Subtarget->isAmdHsaOS()) 6045 return emitNonHSAIntrinsicError(DAG, DL, VT); 6046 6047 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6048 SI::KernelInputOffsets::NGROUPS_X, 4, false); 6049 case Intrinsic::r600_read_ngroups_y: 6050 if (Subtarget->isAmdHsaOS()) 6051 return emitNonHSAIntrinsicError(DAG, DL, VT); 6052 6053 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6054 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 6055 case Intrinsic::r600_read_ngroups_z: 6056 if (Subtarget->isAmdHsaOS()) 6057 return emitNonHSAIntrinsicError(DAG, DL, VT); 6058 6059 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6060 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 6061 case Intrinsic::r600_read_global_size_x: 6062 if (Subtarget->isAmdHsaOS()) 6063 return emitNonHSAIntrinsicError(DAG, DL, VT); 6064 6065 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6066 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 6067 case Intrinsic::r600_read_global_size_y: 6068 if (Subtarget->isAmdHsaOS()) 6069 return emitNonHSAIntrinsicError(DAG, DL, VT); 6070 6071 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6072 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 6073 case Intrinsic::r600_read_global_size_z: 6074 if (Subtarget->isAmdHsaOS()) 6075 return emitNonHSAIntrinsicError(DAG, DL, VT); 6076 6077 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6078 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 6079 case Intrinsic::r600_read_local_size_x: 6080 if (Subtarget->isAmdHsaOS()) 6081 return emitNonHSAIntrinsicError(DAG, DL, VT); 6082 6083 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6084 SI::KernelInputOffsets::LOCAL_SIZE_X); 6085 case Intrinsic::r600_read_local_size_y: 6086 if (Subtarget->isAmdHsaOS()) 6087 return emitNonHSAIntrinsicError(DAG, DL, VT); 6088 6089 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6090 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6091 case Intrinsic::r600_read_local_size_z: 6092 if (Subtarget->isAmdHsaOS()) 6093 return emitNonHSAIntrinsicError(DAG, DL, VT); 6094 6095 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6096 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6097 case Intrinsic::amdgcn_workgroup_id_x: 6098 return getPreloadedValue(DAG, *MFI, VT, 6099 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6100 case Intrinsic::amdgcn_workgroup_id_y: 6101 return getPreloadedValue(DAG, *MFI, VT, 6102 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6103 case Intrinsic::amdgcn_workgroup_id_z: 6104 return getPreloadedValue(DAG, *MFI, VT, 6105 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6106 case Intrinsic::amdgcn_workitem_id_x: 6107 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6108 SDLoc(DAG.getEntryNode()), 6109 MFI->getArgInfo().WorkItemIDX); 6110 case Intrinsic::amdgcn_workitem_id_y: 6111 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6112 SDLoc(DAG.getEntryNode()), 6113 MFI->getArgInfo().WorkItemIDY); 6114 case Intrinsic::amdgcn_workitem_id_z: 6115 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6116 SDLoc(DAG.getEntryNode()), 6117 MFI->getArgInfo().WorkItemIDZ); 6118 case Intrinsic::amdgcn_wavefrontsize: 6119 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6120 SDLoc(Op), MVT::i32); 6121 case Intrinsic::amdgcn_s_buffer_load: { 6122 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 6123 SDValue GLC; 6124 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6125 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6126 IsGFX10 ? &DLC : nullptr)) 6127 return Op; 6128 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6129 DAG); 6130 } 6131 case Intrinsic::amdgcn_fdiv_fast: 6132 return lowerFDIV_FAST(Op, DAG); 6133 case Intrinsic::amdgcn_sin: 6134 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6135 6136 case Intrinsic::amdgcn_cos: 6137 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6138 6139 case Intrinsic::amdgcn_mul_u24: 6140 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6141 case Intrinsic::amdgcn_mul_i24: 6142 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6143 6144 case Intrinsic::amdgcn_log_clamp: { 6145 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6146 return SDValue(); 6147 6148 DiagnosticInfoUnsupported BadIntrin( 6149 MF.getFunction(), "intrinsic not supported on subtarget", 6150 DL.getDebugLoc()); 6151 DAG.getContext()->diagnose(BadIntrin); 6152 return DAG.getUNDEF(VT); 6153 } 6154 case Intrinsic::amdgcn_ldexp: 6155 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6156 Op.getOperand(1), Op.getOperand(2)); 6157 6158 case Intrinsic::amdgcn_fract: 6159 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6160 6161 case Intrinsic::amdgcn_class: 6162 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6163 Op.getOperand(1), Op.getOperand(2)); 6164 case Intrinsic::amdgcn_div_fmas: 6165 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6166 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6167 Op.getOperand(4)); 6168 6169 case Intrinsic::amdgcn_div_fixup: 6170 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6171 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6172 6173 case Intrinsic::amdgcn_trig_preop: 6174 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 6175 Op.getOperand(1), Op.getOperand(2)); 6176 case Intrinsic::amdgcn_div_scale: { 6177 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6178 6179 // Translate to the operands expected by the machine instruction. The 6180 // first parameter must be the same as the first instruction. 6181 SDValue Numerator = Op.getOperand(1); 6182 SDValue Denominator = Op.getOperand(2); 6183 6184 // Note this order is opposite of the machine instruction's operations, 6185 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6186 // intrinsic has the numerator as the first operand to match a normal 6187 // division operation. 6188 6189 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6190 6191 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6192 Denominator, Numerator); 6193 } 6194 case Intrinsic::amdgcn_icmp: { 6195 // There is a Pat that handles this variant, so return it as-is. 6196 if (Op.getOperand(1).getValueType() == MVT::i1 && 6197 Op.getConstantOperandVal(2) == 0 && 6198 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6199 return Op; 6200 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6201 } 6202 case Intrinsic::amdgcn_fcmp: { 6203 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6204 } 6205 case Intrinsic::amdgcn_ballot: 6206 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6207 case Intrinsic::amdgcn_fmed3: 6208 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6209 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6210 case Intrinsic::amdgcn_fdot2: 6211 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6212 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6213 Op.getOperand(4)); 6214 case Intrinsic::amdgcn_fmul_legacy: 6215 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6216 Op.getOperand(1), Op.getOperand(2)); 6217 case Intrinsic::amdgcn_sffbh: 6218 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6219 case Intrinsic::amdgcn_sbfe: 6220 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6221 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6222 case Intrinsic::amdgcn_ubfe: 6223 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6224 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6225 case Intrinsic::amdgcn_cvt_pkrtz: 6226 case Intrinsic::amdgcn_cvt_pknorm_i16: 6227 case Intrinsic::amdgcn_cvt_pknorm_u16: 6228 case Intrinsic::amdgcn_cvt_pk_i16: 6229 case Intrinsic::amdgcn_cvt_pk_u16: { 6230 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6231 EVT VT = Op.getValueType(); 6232 unsigned Opcode; 6233 6234 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6235 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6236 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6237 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6238 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6239 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6240 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6241 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6242 else 6243 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6244 6245 if (isTypeLegal(VT)) 6246 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6247 6248 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6249 Op.getOperand(1), Op.getOperand(2)); 6250 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6251 } 6252 case Intrinsic::amdgcn_fmad_ftz: 6253 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6254 Op.getOperand(2), Op.getOperand(3)); 6255 6256 case Intrinsic::amdgcn_if_break: 6257 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6258 Op->getOperand(1), Op->getOperand(2)), 0); 6259 6260 case Intrinsic::amdgcn_groupstaticsize: { 6261 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6262 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6263 return Op; 6264 6265 const Module *M = MF.getFunction().getParent(); 6266 const GlobalValue *GV = 6267 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6268 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6269 SIInstrInfo::MO_ABS32_LO); 6270 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6271 } 6272 case Intrinsic::amdgcn_is_shared: 6273 case Intrinsic::amdgcn_is_private: { 6274 SDLoc SL(Op); 6275 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6276 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6277 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6278 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6279 Op.getOperand(1)); 6280 6281 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6282 DAG.getConstant(1, SL, MVT::i32)); 6283 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6284 } 6285 case Intrinsic::amdgcn_alignbit: 6286 return DAG.getNode(ISD::FSHR, DL, VT, 6287 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6288 case Intrinsic::amdgcn_reloc_constant: { 6289 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6290 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6291 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6292 auto RelocSymbol = cast<GlobalVariable>( 6293 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6294 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6295 SIInstrInfo::MO_ABS32_LO); 6296 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6297 } 6298 default: 6299 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6300 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6301 return lowerImage(Op, ImageDimIntr, DAG); 6302 6303 return Op; 6304 } 6305 } 6306 6307 // This function computes an appropriate offset to pass to 6308 // MachineMemOperand::setOffset() based on the offset inputs to 6309 // an intrinsic. If any of the offsets are non-contstant or 6310 // if VIndex is non-zero then this function returns 0. Otherwise, 6311 // it returns the sum of VOffset, SOffset, and Offset. 6312 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6313 SDValue SOffset, 6314 SDValue Offset, 6315 SDValue VIndex = SDValue()) { 6316 6317 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6318 !isa<ConstantSDNode>(Offset)) 6319 return 0; 6320 6321 if (VIndex) { 6322 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6323 return 0; 6324 } 6325 6326 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6327 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6328 cast<ConstantSDNode>(Offset)->getSExtValue(); 6329 } 6330 6331 static unsigned getDSShaderTypeValue(const MachineFunction &MF) { 6332 switch (MF.getFunction().getCallingConv()) { 6333 case CallingConv::AMDGPU_PS: 6334 return 1; 6335 case CallingConv::AMDGPU_VS: 6336 return 2; 6337 case CallingConv::AMDGPU_GS: 6338 return 3; 6339 case CallingConv::AMDGPU_HS: 6340 case CallingConv::AMDGPU_LS: 6341 case CallingConv::AMDGPU_ES: 6342 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6343 case CallingConv::AMDGPU_CS: 6344 case CallingConv::AMDGPU_KERNEL: 6345 case CallingConv::C: 6346 case CallingConv::Fast: 6347 default: 6348 // Assume other calling conventions are various compute callable functions 6349 return 0; 6350 } 6351 } 6352 6353 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6354 SelectionDAG &DAG) const { 6355 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6356 SDLoc DL(Op); 6357 6358 switch (IntrID) { 6359 case Intrinsic::amdgcn_ds_ordered_add: 6360 case Intrinsic::amdgcn_ds_ordered_swap: { 6361 MemSDNode *M = cast<MemSDNode>(Op); 6362 SDValue Chain = M->getOperand(0); 6363 SDValue M0 = M->getOperand(2); 6364 SDValue Value = M->getOperand(3); 6365 unsigned IndexOperand = M->getConstantOperandVal(7); 6366 unsigned WaveRelease = M->getConstantOperandVal(8); 6367 unsigned WaveDone = M->getConstantOperandVal(9); 6368 6369 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6370 IndexOperand &= ~0x3f; 6371 unsigned CountDw = 0; 6372 6373 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6374 CountDw = (IndexOperand >> 24) & 0xf; 6375 IndexOperand &= ~(0xf << 24); 6376 6377 if (CountDw < 1 || CountDw > 4) { 6378 report_fatal_error( 6379 "ds_ordered_count: dword count must be between 1 and 4"); 6380 } 6381 } 6382 6383 if (IndexOperand) 6384 report_fatal_error("ds_ordered_count: bad index operand"); 6385 6386 if (WaveDone && !WaveRelease) 6387 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6388 6389 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6390 unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction()); 6391 unsigned Offset0 = OrderedCountIndex << 2; 6392 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6393 (Instruction << 4); 6394 6395 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6396 Offset1 |= (CountDw - 1) << 6; 6397 6398 unsigned Offset = Offset0 | (Offset1 << 8); 6399 6400 SDValue Ops[] = { 6401 Chain, 6402 Value, 6403 DAG.getTargetConstant(Offset, DL, MVT::i16), 6404 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6405 }; 6406 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6407 M->getVTList(), Ops, M->getMemoryVT(), 6408 M->getMemOperand()); 6409 } 6410 case Intrinsic::amdgcn_ds_fadd: { 6411 MemSDNode *M = cast<MemSDNode>(Op); 6412 unsigned Opc; 6413 switch (IntrID) { 6414 case Intrinsic::amdgcn_ds_fadd: 6415 Opc = ISD::ATOMIC_LOAD_FADD; 6416 break; 6417 } 6418 6419 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6420 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6421 M->getMemOperand()); 6422 } 6423 case Intrinsic::amdgcn_atomic_inc: 6424 case Intrinsic::amdgcn_atomic_dec: 6425 case Intrinsic::amdgcn_ds_fmin: 6426 case Intrinsic::amdgcn_ds_fmax: { 6427 MemSDNode *M = cast<MemSDNode>(Op); 6428 unsigned Opc; 6429 switch (IntrID) { 6430 case Intrinsic::amdgcn_atomic_inc: 6431 Opc = AMDGPUISD::ATOMIC_INC; 6432 break; 6433 case Intrinsic::amdgcn_atomic_dec: 6434 Opc = AMDGPUISD::ATOMIC_DEC; 6435 break; 6436 case Intrinsic::amdgcn_ds_fmin: 6437 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6438 break; 6439 case Intrinsic::amdgcn_ds_fmax: 6440 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6441 break; 6442 default: 6443 llvm_unreachable("Unknown intrinsic!"); 6444 } 6445 SDValue Ops[] = { 6446 M->getOperand(0), // Chain 6447 M->getOperand(2), // Ptr 6448 M->getOperand(3) // Value 6449 }; 6450 6451 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6452 M->getMemoryVT(), M->getMemOperand()); 6453 } 6454 case Intrinsic::amdgcn_buffer_load: 6455 case Intrinsic::amdgcn_buffer_load_format: { 6456 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6457 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6458 unsigned IdxEn = 1; 6459 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6460 IdxEn = Idx->getZExtValue() != 0; 6461 SDValue Ops[] = { 6462 Op.getOperand(0), // Chain 6463 Op.getOperand(2), // rsrc 6464 Op.getOperand(3), // vindex 6465 SDValue(), // voffset -- will be set by setBufferOffsets 6466 SDValue(), // soffset -- will be set by setBufferOffsets 6467 SDValue(), // offset -- will be set by setBufferOffsets 6468 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6469 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6470 }; 6471 6472 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6473 // We don't know the offset if vindex is non-zero, so clear it. 6474 if (IdxEn) 6475 Offset = 0; 6476 6477 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6478 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6479 6480 EVT VT = Op.getValueType(); 6481 EVT IntVT = VT.changeTypeToInteger(); 6482 auto *M = cast<MemSDNode>(Op); 6483 M->getMemOperand()->setOffset(Offset); 6484 EVT LoadVT = Op.getValueType(); 6485 6486 if (LoadVT.getScalarType() == MVT::f16) 6487 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6488 M, DAG, Ops); 6489 6490 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6491 if (LoadVT.getScalarType() == MVT::i8 || 6492 LoadVT.getScalarType() == MVT::i16) 6493 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6494 6495 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6496 M->getMemOperand(), DAG); 6497 } 6498 case Intrinsic::amdgcn_raw_buffer_load: 6499 case Intrinsic::amdgcn_raw_buffer_load_format: { 6500 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6501 6502 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6503 SDValue Ops[] = { 6504 Op.getOperand(0), // Chain 6505 Op.getOperand(2), // rsrc 6506 DAG.getConstant(0, DL, MVT::i32), // vindex 6507 Offsets.first, // voffset 6508 Op.getOperand(4), // soffset 6509 Offsets.second, // offset 6510 Op.getOperand(5), // cachepolicy, swizzled buffer 6511 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6512 }; 6513 6514 auto *M = cast<MemSDNode>(Op); 6515 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6516 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6517 } 6518 case Intrinsic::amdgcn_struct_buffer_load: 6519 case Intrinsic::amdgcn_struct_buffer_load_format: { 6520 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6521 6522 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6523 SDValue Ops[] = { 6524 Op.getOperand(0), // Chain 6525 Op.getOperand(2), // rsrc 6526 Op.getOperand(3), // vindex 6527 Offsets.first, // voffset 6528 Op.getOperand(5), // soffset 6529 Offsets.second, // offset 6530 Op.getOperand(6), // cachepolicy, swizzled buffer 6531 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6532 }; 6533 6534 auto *M = cast<MemSDNode>(Op); 6535 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6536 Ops[2])); 6537 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6538 } 6539 case Intrinsic::amdgcn_tbuffer_load: { 6540 MemSDNode *M = cast<MemSDNode>(Op); 6541 EVT LoadVT = Op.getValueType(); 6542 6543 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6544 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6545 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6546 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6547 unsigned IdxEn = 1; 6548 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6549 IdxEn = Idx->getZExtValue() != 0; 6550 SDValue Ops[] = { 6551 Op.getOperand(0), // Chain 6552 Op.getOperand(2), // rsrc 6553 Op.getOperand(3), // vindex 6554 Op.getOperand(4), // voffset 6555 Op.getOperand(5), // soffset 6556 Op.getOperand(6), // offset 6557 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6558 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6559 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6560 }; 6561 6562 if (LoadVT.getScalarType() == MVT::f16) 6563 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6564 M, DAG, Ops); 6565 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6566 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6567 DAG); 6568 } 6569 case Intrinsic::amdgcn_raw_tbuffer_load: { 6570 MemSDNode *M = cast<MemSDNode>(Op); 6571 EVT LoadVT = Op.getValueType(); 6572 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6573 6574 SDValue Ops[] = { 6575 Op.getOperand(0), // Chain 6576 Op.getOperand(2), // rsrc 6577 DAG.getConstant(0, DL, MVT::i32), // vindex 6578 Offsets.first, // voffset 6579 Op.getOperand(4), // soffset 6580 Offsets.second, // offset 6581 Op.getOperand(5), // format 6582 Op.getOperand(6), // cachepolicy, swizzled buffer 6583 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6584 }; 6585 6586 if (LoadVT.getScalarType() == MVT::f16) 6587 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6588 M, DAG, Ops); 6589 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6590 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6591 DAG); 6592 } 6593 case Intrinsic::amdgcn_struct_tbuffer_load: { 6594 MemSDNode *M = cast<MemSDNode>(Op); 6595 EVT LoadVT = Op.getValueType(); 6596 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6597 6598 SDValue Ops[] = { 6599 Op.getOperand(0), // Chain 6600 Op.getOperand(2), // rsrc 6601 Op.getOperand(3), // vindex 6602 Offsets.first, // voffset 6603 Op.getOperand(5), // soffset 6604 Offsets.second, // offset 6605 Op.getOperand(6), // format 6606 Op.getOperand(7), // cachepolicy, swizzled buffer 6607 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6608 }; 6609 6610 if (LoadVT.getScalarType() == MVT::f16) 6611 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6612 M, DAG, Ops); 6613 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6614 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6615 DAG); 6616 } 6617 case Intrinsic::amdgcn_buffer_atomic_swap: 6618 case Intrinsic::amdgcn_buffer_atomic_add: 6619 case Intrinsic::amdgcn_buffer_atomic_sub: 6620 case Intrinsic::amdgcn_buffer_atomic_smin: 6621 case Intrinsic::amdgcn_buffer_atomic_umin: 6622 case Intrinsic::amdgcn_buffer_atomic_smax: 6623 case Intrinsic::amdgcn_buffer_atomic_umax: 6624 case Intrinsic::amdgcn_buffer_atomic_and: 6625 case Intrinsic::amdgcn_buffer_atomic_or: 6626 case Intrinsic::amdgcn_buffer_atomic_xor: { 6627 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6628 unsigned IdxEn = 1; 6629 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6630 IdxEn = Idx->getZExtValue() != 0; 6631 SDValue Ops[] = { 6632 Op.getOperand(0), // Chain 6633 Op.getOperand(2), // vdata 6634 Op.getOperand(3), // rsrc 6635 Op.getOperand(4), // vindex 6636 SDValue(), // voffset -- will be set by setBufferOffsets 6637 SDValue(), // soffset -- will be set by setBufferOffsets 6638 SDValue(), // offset -- will be set by setBufferOffsets 6639 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6640 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6641 }; 6642 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6643 // We don't know the offset if vindex is non-zero, so clear it. 6644 if (IdxEn) 6645 Offset = 0; 6646 EVT VT = Op.getValueType(); 6647 6648 auto *M = cast<MemSDNode>(Op); 6649 M->getMemOperand()->setOffset(Offset); 6650 unsigned Opcode = 0; 6651 6652 switch (IntrID) { 6653 case Intrinsic::amdgcn_buffer_atomic_swap: 6654 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6655 break; 6656 case Intrinsic::amdgcn_buffer_atomic_add: 6657 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6658 break; 6659 case Intrinsic::amdgcn_buffer_atomic_sub: 6660 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6661 break; 6662 case Intrinsic::amdgcn_buffer_atomic_smin: 6663 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6664 break; 6665 case Intrinsic::amdgcn_buffer_atomic_umin: 6666 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6667 break; 6668 case Intrinsic::amdgcn_buffer_atomic_smax: 6669 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6670 break; 6671 case Intrinsic::amdgcn_buffer_atomic_umax: 6672 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6673 break; 6674 case Intrinsic::amdgcn_buffer_atomic_and: 6675 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6676 break; 6677 case Intrinsic::amdgcn_buffer_atomic_or: 6678 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6679 break; 6680 case Intrinsic::amdgcn_buffer_atomic_xor: 6681 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6682 break; 6683 default: 6684 llvm_unreachable("unhandled atomic opcode"); 6685 } 6686 6687 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6688 M->getMemOperand()); 6689 } 6690 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6691 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6692 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6693 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6694 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6695 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6696 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6697 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6698 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6699 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6700 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6701 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 6702 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6703 SDValue Ops[] = { 6704 Op.getOperand(0), // Chain 6705 Op.getOperand(2), // vdata 6706 Op.getOperand(3), // rsrc 6707 DAG.getConstant(0, DL, MVT::i32), // vindex 6708 Offsets.first, // voffset 6709 Op.getOperand(5), // soffset 6710 Offsets.second, // offset 6711 Op.getOperand(6), // cachepolicy 6712 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6713 }; 6714 EVT VT = Op.getValueType(); 6715 6716 auto *M = cast<MemSDNode>(Op); 6717 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6718 unsigned Opcode = 0; 6719 6720 switch (IntrID) { 6721 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6722 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6723 break; 6724 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6725 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6726 break; 6727 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6728 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6729 break; 6730 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6731 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6732 break; 6733 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6734 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6735 break; 6736 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6737 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6738 break; 6739 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6740 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6741 break; 6742 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6743 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6744 break; 6745 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6746 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6747 break; 6748 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6749 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6750 break; 6751 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6752 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6753 break; 6754 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 6755 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6756 break; 6757 default: 6758 llvm_unreachable("unhandled atomic opcode"); 6759 } 6760 6761 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6762 M->getMemOperand()); 6763 } 6764 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6765 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6766 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6767 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6768 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6769 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6770 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6771 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6772 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6773 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6774 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6775 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 6776 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6777 SDValue Ops[] = { 6778 Op.getOperand(0), // Chain 6779 Op.getOperand(2), // vdata 6780 Op.getOperand(3), // rsrc 6781 Op.getOperand(4), // vindex 6782 Offsets.first, // voffset 6783 Op.getOperand(6), // soffset 6784 Offsets.second, // offset 6785 Op.getOperand(7), // cachepolicy 6786 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6787 }; 6788 EVT VT = Op.getValueType(); 6789 6790 auto *M = cast<MemSDNode>(Op); 6791 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6792 Ops[3])); 6793 unsigned Opcode = 0; 6794 6795 switch (IntrID) { 6796 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6797 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6798 break; 6799 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6800 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6801 break; 6802 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6803 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6804 break; 6805 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6806 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6807 break; 6808 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6809 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6810 break; 6811 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6812 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6813 break; 6814 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6815 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6816 break; 6817 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6818 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6819 break; 6820 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6821 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6822 break; 6823 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6824 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6825 break; 6826 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6827 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6828 break; 6829 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 6830 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6831 break; 6832 default: 6833 llvm_unreachable("unhandled atomic opcode"); 6834 } 6835 6836 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6837 M->getMemOperand()); 6838 } 6839 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 6840 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6841 unsigned IdxEn = 1; 6842 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 6843 IdxEn = Idx->getZExtValue() != 0; 6844 SDValue Ops[] = { 6845 Op.getOperand(0), // Chain 6846 Op.getOperand(2), // src 6847 Op.getOperand(3), // cmp 6848 Op.getOperand(4), // rsrc 6849 Op.getOperand(5), // vindex 6850 SDValue(), // voffset -- will be set by setBufferOffsets 6851 SDValue(), // soffset -- will be set by setBufferOffsets 6852 SDValue(), // offset -- will be set by setBufferOffsets 6853 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6854 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6855 }; 6856 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 6857 // We don't know the offset if vindex is non-zero, so clear it. 6858 if (IdxEn) 6859 Offset = 0; 6860 EVT VT = Op.getValueType(); 6861 auto *M = cast<MemSDNode>(Op); 6862 M->getMemOperand()->setOffset(Offset); 6863 6864 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6865 Op->getVTList(), Ops, VT, M->getMemOperand()); 6866 } 6867 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 6868 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6869 SDValue Ops[] = { 6870 Op.getOperand(0), // Chain 6871 Op.getOperand(2), // src 6872 Op.getOperand(3), // cmp 6873 Op.getOperand(4), // rsrc 6874 DAG.getConstant(0, DL, MVT::i32), // vindex 6875 Offsets.first, // voffset 6876 Op.getOperand(6), // soffset 6877 Offsets.second, // offset 6878 Op.getOperand(7), // cachepolicy 6879 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6880 }; 6881 EVT VT = Op.getValueType(); 6882 auto *M = cast<MemSDNode>(Op); 6883 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 6884 6885 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6886 Op->getVTList(), Ops, VT, M->getMemOperand()); 6887 } 6888 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 6889 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 6890 SDValue Ops[] = { 6891 Op.getOperand(0), // Chain 6892 Op.getOperand(2), // src 6893 Op.getOperand(3), // cmp 6894 Op.getOperand(4), // rsrc 6895 Op.getOperand(5), // vindex 6896 Offsets.first, // voffset 6897 Op.getOperand(7), // soffset 6898 Offsets.second, // offset 6899 Op.getOperand(8), // cachepolicy 6900 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6901 }; 6902 EVT VT = Op.getValueType(); 6903 auto *M = cast<MemSDNode>(Op); 6904 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 6905 Ops[4])); 6906 6907 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6908 Op->getVTList(), Ops, VT, M->getMemOperand()); 6909 } 6910 6911 default: 6912 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6913 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 6914 return lowerImage(Op, ImageDimIntr, DAG); 6915 6916 return SDValue(); 6917 } 6918 } 6919 6920 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 6921 // dwordx4 if on SI. 6922 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 6923 SDVTList VTList, 6924 ArrayRef<SDValue> Ops, EVT MemVT, 6925 MachineMemOperand *MMO, 6926 SelectionDAG &DAG) const { 6927 EVT VT = VTList.VTs[0]; 6928 EVT WidenedVT = VT; 6929 EVT WidenedMemVT = MemVT; 6930 if (!Subtarget->hasDwordx3LoadStores() && 6931 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 6932 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 6933 WidenedVT.getVectorElementType(), 4); 6934 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 6935 WidenedMemVT.getVectorElementType(), 4); 6936 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 6937 } 6938 6939 assert(VTList.NumVTs == 2); 6940 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 6941 6942 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 6943 WidenedMemVT, MMO); 6944 if (WidenedVT != VT) { 6945 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 6946 DAG.getVectorIdxConstant(0, DL)); 6947 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 6948 } 6949 return NewOp; 6950 } 6951 6952 SDValue SITargetLowering::handleD16VData(SDValue VData, 6953 SelectionDAG &DAG) const { 6954 EVT StoreVT = VData.getValueType(); 6955 6956 // No change for f16 and legal vector D16 types. 6957 if (!StoreVT.isVector()) 6958 return VData; 6959 6960 SDLoc DL(VData); 6961 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 6962 6963 if (Subtarget->hasUnpackedD16VMem()) { 6964 // We need to unpack the packed data to store. 6965 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 6966 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 6967 6968 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 6969 StoreVT.getVectorNumElements()); 6970 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 6971 return DAG.UnrollVectorOp(ZExt.getNode()); 6972 } 6973 6974 assert(isTypeLegal(StoreVT)); 6975 return VData; 6976 } 6977 6978 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 6979 SelectionDAG &DAG) const { 6980 SDLoc DL(Op); 6981 SDValue Chain = Op.getOperand(0); 6982 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6983 MachineFunction &MF = DAG.getMachineFunction(); 6984 6985 switch (IntrinsicID) { 6986 case Intrinsic::amdgcn_exp_compr: { 6987 SDValue Src0 = Op.getOperand(4); 6988 SDValue Src1 = Op.getOperand(5); 6989 // Hack around illegal type on SI by directly selecting it. 6990 if (isTypeLegal(Src0.getValueType())) 6991 return SDValue(); 6992 6993 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 6994 SDValue Undef = DAG.getUNDEF(MVT::f32); 6995 const SDValue Ops[] = { 6996 Op.getOperand(2), // tgt 6997 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 6998 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 6999 Undef, // src2 7000 Undef, // src3 7001 Op.getOperand(7), // vm 7002 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7003 Op.getOperand(3), // en 7004 Op.getOperand(0) // Chain 7005 }; 7006 7007 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7008 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7009 } 7010 case Intrinsic::amdgcn_s_barrier: { 7011 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7012 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7013 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7014 if (WGSize <= ST.getWavefrontSize()) 7015 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7016 Op.getOperand(0)), 0); 7017 } 7018 return SDValue(); 7019 }; 7020 case Intrinsic::amdgcn_tbuffer_store: { 7021 SDValue VData = Op.getOperand(2); 7022 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7023 if (IsD16) 7024 VData = handleD16VData(VData, DAG); 7025 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7026 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7027 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7028 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7029 unsigned IdxEn = 1; 7030 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7031 IdxEn = Idx->getZExtValue() != 0; 7032 SDValue Ops[] = { 7033 Chain, 7034 VData, // vdata 7035 Op.getOperand(3), // rsrc 7036 Op.getOperand(4), // vindex 7037 Op.getOperand(5), // voffset 7038 Op.getOperand(6), // soffset 7039 Op.getOperand(7), // offset 7040 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7041 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7042 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7043 }; 7044 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7045 AMDGPUISD::TBUFFER_STORE_FORMAT; 7046 MemSDNode *M = cast<MemSDNode>(Op); 7047 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7048 M->getMemoryVT(), M->getMemOperand()); 7049 } 7050 7051 case Intrinsic::amdgcn_struct_tbuffer_store: { 7052 SDValue VData = Op.getOperand(2); 7053 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7054 if (IsD16) 7055 VData = handleD16VData(VData, DAG); 7056 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7057 SDValue Ops[] = { 7058 Chain, 7059 VData, // vdata 7060 Op.getOperand(3), // rsrc 7061 Op.getOperand(4), // vindex 7062 Offsets.first, // voffset 7063 Op.getOperand(6), // soffset 7064 Offsets.second, // offset 7065 Op.getOperand(7), // format 7066 Op.getOperand(8), // cachepolicy, swizzled buffer 7067 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7068 }; 7069 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7070 AMDGPUISD::TBUFFER_STORE_FORMAT; 7071 MemSDNode *M = cast<MemSDNode>(Op); 7072 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7073 M->getMemoryVT(), M->getMemOperand()); 7074 } 7075 7076 case Intrinsic::amdgcn_raw_tbuffer_store: { 7077 SDValue VData = Op.getOperand(2); 7078 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7079 if (IsD16) 7080 VData = handleD16VData(VData, DAG); 7081 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7082 SDValue Ops[] = { 7083 Chain, 7084 VData, // vdata 7085 Op.getOperand(3), // rsrc 7086 DAG.getConstant(0, DL, MVT::i32), // vindex 7087 Offsets.first, // voffset 7088 Op.getOperand(5), // soffset 7089 Offsets.second, // offset 7090 Op.getOperand(6), // format 7091 Op.getOperand(7), // cachepolicy, swizzled buffer 7092 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7093 }; 7094 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7095 AMDGPUISD::TBUFFER_STORE_FORMAT; 7096 MemSDNode *M = cast<MemSDNode>(Op); 7097 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7098 M->getMemoryVT(), M->getMemOperand()); 7099 } 7100 7101 case Intrinsic::amdgcn_buffer_store: 7102 case Intrinsic::amdgcn_buffer_store_format: { 7103 SDValue VData = Op.getOperand(2); 7104 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7105 if (IsD16) 7106 VData = handleD16VData(VData, DAG); 7107 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7108 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7109 unsigned IdxEn = 1; 7110 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7111 IdxEn = Idx->getZExtValue() != 0; 7112 SDValue Ops[] = { 7113 Chain, 7114 VData, 7115 Op.getOperand(3), // rsrc 7116 Op.getOperand(4), // vindex 7117 SDValue(), // voffset -- will be set by setBufferOffsets 7118 SDValue(), // soffset -- will be set by setBufferOffsets 7119 SDValue(), // offset -- will be set by setBufferOffsets 7120 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7121 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7122 }; 7123 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7124 // We don't know the offset if vindex is non-zero, so clear it. 7125 if (IdxEn) 7126 Offset = 0; 7127 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7128 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7129 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7130 MemSDNode *M = cast<MemSDNode>(Op); 7131 M->getMemOperand()->setOffset(Offset); 7132 7133 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7134 EVT VDataType = VData.getValueType().getScalarType(); 7135 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7136 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7137 7138 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7139 M->getMemoryVT(), M->getMemOperand()); 7140 } 7141 7142 case Intrinsic::amdgcn_raw_buffer_store: 7143 case Intrinsic::amdgcn_raw_buffer_store_format: { 7144 const bool IsFormat = 7145 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7146 7147 SDValue VData = Op.getOperand(2); 7148 EVT VDataVT = VData.getValueType(); 7149 EVT EltType = VDataVT.getScalarType(); 7150 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7151 if (IsD16) 7152 VData = handleD16VData(VData, DAG); 7153 7154 if (!isTypeLegal(VDataVT)) { 7155 VData = 7156 DAG.getNode(ISD::BITCAST, DL, 7157 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7158 } 7159 7160 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7161 SDValue Ops[] = { 7162 Chain, 7163 VData, 7164 Op.getOperand(3), // rsrc 7165 DAG.getConstant(0, DL, MVT::i32), // vindex 7166 Offsets.first, // voffset 7167 Op.getOperand(5), // soffset 7168 Offsets.second, // offset 7169 Op.getOperand(6), // cachepolicy, swizzled buffer 7170 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7171 }; 7172 unsigned Opc = 7173 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7174 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7175 MemSDNode *M = cast<MemSDNode>(Op); 7176 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7177 7178 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7179 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7180 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7181 7182 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7183 M->getMemoryVT(), M->getMemOperand()); 7184 } 7185 7186 case Intrinsic::amdgcn_struct_buffer_store: 7187 case Intrinsic::amdgcn_struct_buffer_store_format: { 7188 const bool IsFormat = 7189 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7190 7191 SDValue VData = Op.getOperand(2); 7192 EVT VDataVT = VData.getValueType(); 7193 EVT EltType = VDataVT.getScalarType(); 7194 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7195 7196 if (IsD16) 7197 VData = handleD16VData(VData, DAG); 7198 7199 if (!isTypeLegal(VDataVT)) { 7200 VData = 7201 DAG.getNode(ISD::BITCAST, DL, 7202 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7203 } 7204 7205 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7206 SDValue Ops[] = { 7207 Chain, 7208 VData, 7209 Op.getOperand(3), // rsrc 7210 Op.getOperand(4), // vindex 7211 Offsets.first, // voffset 7212 Op.getOperand(6), // soffset 7213 Offsets.second, // offset 7214 Op.getOperand(7), // cachepolicy, swizzled buffer 7215 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7216 }; 7217 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7218 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7219 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7220 MemSDNode *M = cast<MemSDNode>(Op); 7221 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7222 Ops[3])); 7223 7224 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7225 EVT VDataType = VData.getValueType().getScalarType(); 7226 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7227 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7228 7229 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7230 M->getMemoryVT(), M->getMemOperand()); 7231 } 7232 7233 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7234 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7235 unsigned IdxEn = 1; 7236 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7237 IdxEn = Idx->getZExtValue() != 0; 7238 SDValue Ops[] = { 7239 Chain, 7240 Op.getOperand(2), // vdata 7241 Op.getOperand(3), // rsrc 7242 Op.getOperand(4), // vindex 7243 SDValue(), // voffset -- will be set by setBufferOffsets 7244 SDValue(), // soffset -- will be set by setBufferOffsets 7245 SDValue(), // offset -- will be set by setBufferOffsets 7246 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7247 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7248 }; 7249 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7250 // We don't know the offset if vindex is non-zero, so clear it. 7251 if (IdxEn) 7252 Offset = 0; 7253 EVT VT = Op.getOperand(2).getValueType(); 7254 7255 auto *M = cast<MemSDNode>(Op); 7256 M->getMemOperand()->setOffset(Offset); 7257 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 7258 : AMDGPUISD::BUFFER_ATOMIC_FADD; 7259 7260 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7261 M->getMemOperand()); 7262 } 7263 7264 case Intrinsic::amdgcn_global_atomic_fadd: { 7265 SDValue Ops[] = { 7266 Chain, 7267 Op.getOperand(2), // ptr 7268 Op.getOperand(3) // vdata 7269 }; 7270 EVT VT = Op.getOperand(3).getValueType(); 7271 7272 auto *M = cast<MemSDNode>(Op); 7273 if (VT.isVector()) { 7274 return DAG.getMemIntrinsicNode( 7275 AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT, 7276 M->getMemOperand()); 7277 } 7278 7279 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7280 DAG.getVTList(VT, MVT::Other), Ops, 7281 M->getMemOperand()).getValue(1); 7282 } 7283 case Intrinsic::amdgcn_end_cf: 7284 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7285 Op->getOperand(2), Chain), 0); 7286 7287 default: { 7288 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7289 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7290 return lowerImage(Op, ImageDimIntr, DAG); 7291 7292 return Op; 7293 } 7294 } 7295 } 7296 7297 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7298 // offset (the offset that is included in bounds checking and swizzling, to be 7299 // split between the instruction's voffset and immoffset fields) and soffset 7300 // (the offset that is excluded from bounds checking and swizzling, to go in 7301 // the instruction's soffset field). This function takes the first kind of 7302 // offset and figures out how to split it between voffset and immoffset. 7303 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7304 SDValue Offset, SelectionDAG &DAG) const { 7305 SDLoc DL(Offset); 7306 const unsigned MaxImm = 4095; 7307 SDValue N0 = Offset; 7308 ConstantSDNode *C1 = nullptr; 7309 7310 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7311 N0 = SDValue(); 7312 else if (DAG.isBaseWithConstantOffset(N0)) { 7313 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7314 N0 = N0.getOperand(0); 7315 } 7316 7317 if (C1) { 7318 unsigned ImmOffset = C1->getZExtValue(); 7319 // If the immediate value is too big for the immoffset field, put the value 7320 // and -4096 into the immoffset field so that the value that is copied/added 7321 // for the voffset field is a multiple of 4096, and it stands more chance 7322 // of being CSEd with the copy/add for another similar load/store. 7323 // However, do not do that rounding down to a multiple of 4096 if that is a 7324 // negative number, as it appears to be illegal to have a negative offset 7325 // in the vgpr, even if adding the immediate offset makes it positive. 7326 unsigned Overflow = ImmOffset & ~MaxImm; 7327 ImmOffset -= Overflow; 7328 if ((int32_t)Overflow < 0) { 7329 Overflow += ImmOffset; 7330 ImmOffset = 0; 7331 } 7332 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7333 if (Overflow) { 7334 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7335 if (!N0) 7336 N0 = OverflowVal; 7337 else { 7338 SDValue Ops[] = { N0, OverflowVal }; 7339 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7340 } 7341 } 7342 } 7343 if (!N0) 7344 N0 = DAG.getConstant(0, DL, MVT::i32); 7345 if (!C1) 7346 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7347 return {N0, SDValue(C1, 0)}; 7348 } 7349 7350 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7351 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7352 // pointed to by Offsets. 7353 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7354 SelectionDAG &DAG, SDValue *Offsets, 7355 unsigned Align) const { 7356 SDLoc DL(CombinedOffset); 7357 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7358 uint32_t Imm = C->getZExtValue(); 7359 uint32_t SOffset, ImmOffset; 7360 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 7361 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7362 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7363 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7364 return SOffset + ImmOffset; 7365 } 7366 } 7367 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7368 SDValue N0 = CombinedOffset.getOperand(0); 7369 SDValue N1 = CombinedOffset.getOperand(1); 7370 uint32_t SOffset, ImmOffset; 7371 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7372 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7373 Subtarget, Align)) { 7374 Offsets[0] = N0; 7375 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7376 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7377 return 0; 7378 } 7379 } 7380 Offsets[0] = CombinedOffset; 7381 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7382 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7383 return 0; 7384 } 7385 7386 // Handle 8 bit and 16 bit buffer loads 7387 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7388 EVT LoadVT, SDLoc DL, 7389 ArrayRef<SDValue> Ops, 7390 MemSDNode *M) const { 7391 EVT IntVT = LoadVT.changeTypeToInteger(); 7392 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7393 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7394 7395 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7396 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7397 Ops, IntVT, 7398 M->getMemOperand()); 7399 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7400 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7401 7402 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7403 } 7404 7405 // Handle 8 bit and 16 bit buffer stores 7406 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7407 EVT VDataType, SDLoc DL, 7408 SDValue Ops[], 7409 MemSDNode *M) const { 7410 if (VDataType == MVT::f16) 7411 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7412 7413 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7414 Ops[1] = BufferStoreExt; 7415 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7416 AMDGPUISD::BUFFER_STORE_SHORT; 7417 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7418 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7419 M->getMemOperand()); 7420 } 7421 7422 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7423 ISD::LoadExtType ExtType, SDValue Op, 7424 const SDLoc &SL, EVT VT) { 7425 if (VT.bitsLT(Op.getValueType())) 7426 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7427 7428 switch (ExtType) { 7429 case ISD::SEXTLOAD: 7430 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7431 case ISD::ZEXTLOAD: 7432 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7433 case ISD::EXTLOAD: 7434 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7435 case ISD::NON_EXTLOAD: 7436 return Op; 7437 } 7438 7439 llvm_unreachable("invalid ext type"); 7440 } 7441 7442 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7443 SelectionDAG &DAG = DCI.DAG; 7444 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7445 return SDValue(); 7446 7447 // FIXME: Constant loads should all be marked invariant. 7448 unsigned AS = Ld->getAddressSpace(); 7449 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7450 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7451 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7452 return SDValue(); 7453 7454 // Don't do this early, since it may interfere with adjacent load merging for 7455 // illegal types. We can avoid losing alignment information for exotic types 7456 // pre-legalize. 7457 EVT MemVT = Ld->getMemoryVT(); 7458 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7459 MemVT.getSizeInBits() >= 32) 7460 return SDValue(); 7461 7462 SDLoc SL(Ld); 7463 7464 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7465 "unexpected vector extload"); 7466 7467 // TODO: Drop only high part of range. 7468 SDValue Ptr = Ld->getBasePtr(); 7469 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7470 MVT::i32, SL, Ld->getChain(), Ptr, 7471 Ld->getOffset(), 7472 Ld->getPointerInfo(), MVT::i32, 7473 Ld->getAlignment(), 7474 Ld->getMemOperand()->getFlags(), 7475 Ld->getAAInfo(), 7476 nullptr); // Drop ranges 7477 7478 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7479 if (MemVT.isFloatingPoint()) { 7480 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7481 "unexpected fp extload"); 7482 TruncVT = MemVT.changeTypeToInteger(); 7483 } 7484 7485 SDValue Cvt = NewLoad; 7486 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7487 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7488 DAG.getValueType(TruncVT)); 7489 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7490 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7491 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7492 } else { 7493 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7494 } 7495 7496 EVT VT = Ld->getValueType(0); 7497 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7498 7499 DCI.AddToWorklist(Cvt.getNode()); 7500 7501 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7502 // the appropriate extension from the 32-bit load. 7503 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7504 DCI.AddToWorklist(Cvt.getNode()); 7505 7506 // Handle conversion back to floating point if necessary. 7507 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7508 7509 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7510 } 7511 7512 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7513 SDLoc DL(Op); 7514 LoadSDNode *Load = cast<LoadSDNode>(Op); 7515 ISD::LoadExtType ExtType = Load->getExtensionType(); 7516 EVT MemVT = Load->getMemoryVT(); 7517 7518 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7519 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7520 return SDValue(); 7521 7522 // FIXME: Copied from PPC 7523 // First, load into 32 bits, then truncate to 1 bit. 7524 7525 SDValue Chain = Load->getChain(); 7526 SDValue BasePtr = Load->getBasePtr(); 7527 MachineMemOperand *MMO = Load->getMemOperand(); 7528 7529 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7530 7531 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7532 BasePtr, RealMemVT, MMO); 7533 7534 if (!MemVT.isVector()) { 7535 SDValue Ops[] = { 7536 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7537 NewLD.getValue(1) 7538 }; 7539 7540 return DAG.getMergeValues(Ops, DL); 7541 } 7542 7543 SmallVector<SDValue, 3> Elts; 7544 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7545 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7546 DAG.getConstant(I, DL, MVT::i32)); 7547 7548 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7549 } 7550 7551 SDValue Ops[] = { 7552 DAG.getBuildVector(MemVT, DL, Elts), 7553 NewLD.getValue(1) 7554 }; 7555 7556 return DAG.getMergeValues(Ops, DL); 7557 } 7558 7559 if (!MemVT.isVector()) 7560 return SDValue(); 7561 7562 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7563 "Custom lowering for non-i32 vectors hasn't been implemented."); 7564 7565 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7566 MemVT, *Load->getMemOperand())) { 7567 SDValue Ops[2]; 7568 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7569 return DAG.getMergeValues(Ops, DL); 7570 } 7571 7572 unsigned Alignment = Load->getAlignment(); 7573 unsigned AS = Load->getAddressSpace(); 7574 if (Subtarget->hasLDSMisalignedBug() && 7575 AS == AMDGPUAS::FLAT_ADDRESS && 7576 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7577 return SplitVectorLoad(Op, DAG); 7578 } 7579 7580 MachineFunction &MF = DAG.getMachineFunction(); 7581 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7582 // If there is a possibilty that flat instruction access scratch memory 7583 // then we need to use the same legalization rules we use for private. 7584 if (AS == AMDGPUAS::FLAT_ADDRESS && 7585 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7586 AS = MFI->hasFlatScratchInit() ? 7587 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7588 7589 unsigned NumElements = MemVT.getVectorNumElements(); 7590 7591 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7592 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7593 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7594 if (MemVT.isPow2VectorType()) 7595 return SDValue(); 7596 if (NumElements == 3) 7597 return WidenVectorLoad(Op, DAG); 7598 return SplitVectorLoad(Op, DAG); 7599 } 7600 // Non-uniform loads will be selected to MUBUF instructions, so they 7601 // have the same legalization requirements as global and private 7602 // loads. 7603 // 7604 } 7605 7606 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7607 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7608 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7609 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7610 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 7611 Alignment >= 4 && NumElements < 32) { 7612 if (MemVT.isPow2VectorType()) 7613 return SDValue(); 7614 if (NumElements == 3) 7615 return WidenVectorLoad(Op, DAG); 7616 return SplitVectorLoad(Op, DAG); 7617 } 7618 // Non-uniform loads will be selected to MUBUF instructions, so they 7619 // have the same legalization requirements as global and private 7620 // loads. 7621 // 7622 } 7623 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7624 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7625 AS == AMDGPUAS::GLOBAL_ADDRESS || 7626 AS == AMDGPUAS::FLAT_ADDRESS) { 7627 if (NumElements > 4) 7628 return SplitVectorLoad(Op, DAG); 7629 // v3 loads not supported on SI. 7630 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7631 return WidenVectorLoad(Op, DAG); 7632 // v3 and v4 loads are supported for private and global memory. 7633 return SDValue(); 7634 } 7635 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7636 // Depending on the setting of the private_element_size field in the 7637 // resource descriptor, we can only make private accesses up to a certain 7638 // size. 7639 switch (Subtarget->getMaxPrivateElementSize()) { 7640 case 4: { 7641 SDValue Ops[2]; 7642 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7643 return DAG.getMergeValues(Ops, DL); 7644 } 7645 case 8: 7646 if (NumElements > 2) 7647 return SplitVectorLoad(Op, DAG); 7648 return SDValue(); 7649 case 16: 7650 // Same as global/flat 7651 if (NumElements > 4) 7652 return SplitVectorLoad(Op, DAG); 7653 // v3 loads not supported on SI. 7654 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7655 return WidenVectorLoad(Op, DAG); 7656 return SDValue(); 7657 default: 7658 llvm_unreachable("unsupported private_element_size"); 7659 } 7660 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7661 // Use ds_read_b128 if possible. 7662 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7663 MemVT.getStoreSize() == 16) 7664 return SDValue(); 7665 7666 if (NumElements > 2) 7667 return SplitVectorLoad(Op, DAG); 7668 7669 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7670 // address is negative, then the instruction is incorrectly treated as 7671 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7672 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7673 // load later in the SILoadStoreOptimizer. 7674 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7675 NumElements == 2 && MemVT.getStoreSize() == 8 && 7676 Load->getAlignment() < 8) { 7677 return SplitVectorLoad(Op, DAG); 7678 } 7679 } 7680 return SDValue(); 7681 } 7682 7683 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7684 EVT VT = Op.getValueType(); 7685 assert(VT.getSizeInBits() == 64); 7686 7687 SDLoc DL(Op); 7688 SDValue Cond = Op.getOperand(0); 7689 7690 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7691 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7692 7693 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7694 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7695 7696 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7697 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7698 7699 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7700 7701 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7702 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7703 7704 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7705 7706 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7707 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7708 } 7709 7710 // Catch division cases where we can use shortcuts with rcp and rsq 7711 // instructions. 7712 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7713 SelectionDAG &DAG) const { 7714 SDLoc SL(Op); 7715 SDValue LHS = Op.getOperand(0); 7716 SDValue RHS = Op.getOperand(1); 7717 EVT VT = Op.getValueType(); 7718 const SDNodeFlags Flags = Op->getFlags(); 7719 7720 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 7721 Flags.hasApproximateFuncs(); 7722 7723 // Without !fpmath accuracy information, we can't do more because we don't 7724 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 7725 if (!AllowInaccurateRcp) 7726 return SDValue(); 7727 7728 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7729 if (CLHS->isExactlyValue(1.0)) { 7730 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7731 // the CI documentation has a worst case error of 1 ulp. 7732 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7733 // use it as long as we aren't trying to use denormals. 7734 // 7735 // v_rcp_f16 and v_rsq_f16 DO support denormals. 7736 7737 // 1.0 / sqrt(x) -> rsq(x) 7738 7739 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 7740 // error seems really high at 2^29 ULP. 7741 if (RHS.getOpcode() == ISD::FSQRT) 7742 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 7743 7744 // 1.0 / x -> rcp(x) 7745 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7746 } 7747 7748 // Same as for 1.0, but expand the sign out of the constant. 7749 if (CLHS->isExactlyValue(-1.0)) { 7750 // -1.0 / x -> rcp (fneg x) 7751 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7752 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 7753 } 7754 } 7755 7756 // Turn into multiply by the reciprocal. 7757 // x / y -> x * (1.0 / y) 7758 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7759 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 7760 } 7761 7762 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7763 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 7764 if (GlueChain->getNumValues() <= 1) { 7765 return DAG.getNode(Opcode, SL, VT, A, B); 7766 } 7767 7768 assert(GlueChain->getNumValues() == 3); 7769 7770 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7771 switch (Opcode) { 7772 default: llvm_unreachable("no chain equivalent for opcode"); 7773 case ISD::FMUL: 7774 Opcode = AMDGPUISD::FMUL_W_CHAIN; 7775 break; 7776 } 7777 7778 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 7779 GlueChain.getValue(2)); 7780 } 7781 7782 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7783 EVT VT, SDValue A, SDValue B, SDValue C, 7784 SDValue GlueChain) { 7785 if (GlueChain->getNumValues() <= 1) { 7786 return DAG.getNode(Opcode, SL, VT, A, B, C); 7787 } 7788 7789 assert(GlueChain->getNumValues() == 3); 7790 7791 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7792 switch (Opcode) { 7793 default: llvm_unreachable("no chain equivalent for opcode"); 7794 case ISD::FMA: 7795 Opcode = AMDGPUISD::FMA_W_CHAIN; 7796 break; 7797 } 7798 7799 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 7800 GlueChain.getValue(2)); 7801 } 7802 7803 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 7804 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7805 return FastLowered; 7806 7807 SDLoc SL(Op); 7808 SDValue Src0 = Op.getOperand(0); 7809 SDValue Src1 = Op.getOperand(1); 7810 7811 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 7812 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 7813 7814 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 7815 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 7816 7817 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 7818 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 7819 7820 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 7821 } 7822 7823 // Faster 2.5 ULP division that does not support denormals. 7824 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 7825 SDLoc SL(Op); 7826 SDValue LHS = Op.getOperand(1); 7827 SDValue RHS = Op.getOperand(2); 7828 7829 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 7830 7831 const APFloat K0Val(BitsToFloat(0x6f800000)); 7832 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 7833 7834 const APFloat K1Val(BitsToFloat(0x2f800000)); 7835 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 7836 7837 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7838 7839 EVT SetCCVT = 7840 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 7841 7842 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 7843 7844 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 7845 7846 // TODO: Should this propagate fast-math-flags? 7847 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 7848 7849 // rcp does not support denormals. 7850 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 7851 7852 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 7853 7854 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 7855 } 7856 7857 // Returns immediate value for setting the F32 denorm mode when using the 7858 // S_DENORM_MODE instruction. 7859 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 7860 const SDLoc &SL, const GCNSubtarget *ST) { 7861 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 7862 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 7863 ? FP_DENORM_FLUSH_NONE 7864 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 7865 7866 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 7867 return DAG.getTargetConstant(Mode, SL, MVT::i32); 7868 } 7869 7870 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 7871 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7872 return FastLowered; 7873 7874 SDLoc SL(Op); 7875 SDValue LHS = Op.getOperand(0); 7876 SDValue RHS = Op.getOperand(1); 7877 7878 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7879 7880 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 7881 7882 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7883 RHS, RHS, LHS); 7884 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7885 LHS, RHS, LHS); 7886 7887 // Denominator is scaled to not be denormal, so using rcp is ok. 7888 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 7889 DenominatorScaled); 7890 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 7891 DenominatorScaled); 7892 7893 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 7894 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 7895 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 7896 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 7897 7898 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 7899 7900 if (!HasFP32Denormals) { 7901 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 7902 7903 SDValue EnableDenorm; 7904 if (Subtarget->hasDenormModeInst()) { 7905 const SDValue EnableDenormValue = 7906 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 7907 7908 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 7909 DAG.getEntryNode(), EnableDenormValue); 7910 } else { 7911 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 7912 SL, MVT::i32); 7913 EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 7914 DAG.getEntryNode(), EnableDenormValue, 7915 BitField); 7916 } 7917 7918 SDValue Ops[3] = { 7919 NegDivScale0, 7920 EnableDenorm.getValue(0), 7921 EnableDenorm.getValue(1) 7922 }; 7923 7924 NegDivScale0 = DAG.getMergeValues(Ops, SL); 7925 } 7926 7927 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 7928 ApproxRcp, One, NegDivScale0); 7929 7930 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 7931 ApproxRcp, Fma0); 7932 7933 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 7934 Fma1, Fma1); 7935 7936 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 7937 NumeratorScaled, Mul); 7938 7939 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 7940 7941 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 7942 NumeratorScaled, Fma3); 7943 7944 if (!HasFP32Denormals) { 7945 SDValue DisableDenorm; 7946 if (Subtarget->hasDenormModeInst()) { 7947 const SDValue DisableDenormValue = 7948 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 7949 7950 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 7951 Fma4.getValue(1), DisableDenormValue, 7952 Fma4.getValue(2)); 7953 } else { 7954 const SDValue DisableDenormValue = 7955 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 7956 7957 DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 7958 Fma4.getValue(1), DisableDenormValue, 7959 BitField, Fma4.getValue(2)); 7960 } 7961 7962 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 7963 DisableDenorm, DAG.getRoot()); 7964 DAG.setRoot(OutputChain); 7965 } 7966 7967 SDValue Scale = NumeratorScaled.getValue(1); 7968 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 7969 Fma4, Fma1, Fma3, Scale); 7970 7971 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 7972 } 7973 7974 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 7975 if (DAG.getTarget().Options.UnsafeFPMath) 7976 return lowerFastUnsafeFDIV(Op, DAG); 7977 7978 SDLoc SL(Op); 7979 SDValue X = Op.getOperand(0); 7980 SDValue Y = Op.getOperand(1); 7981 7982 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 7983 7984 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 7985 7986 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 7987 7988 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 7989 7990 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 7991 7992 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 7993 7994 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 7995 7996 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 7997 7998 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 7999 8000 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8001 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8002 8003 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8004 NegDivScale0, Mul, DivScale1); 8005 8006 SDValue Scale; 8007 8008 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8009 // Workaround a hardware bug on SI where the condition output from div_scale 8010 // is not usable. 8011 8012 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8013 8014 // Figure out if the scale to use for div_fmas. 8015 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8016 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8017 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8018 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8019 8020 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8021 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8022 8023 SDValue Scale0Hi 8024 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8025 SDValue Scale1Hi 8026 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8027 8028 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8029 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8030 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8031 } else { 8032 Scale = DivScale1.getValue(1); 8033 } 8034 8035 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8036 Fma4, Fma3, Mul, Scale); 8037 8038 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8039 } 8040 8041 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8042 EVT VT = Op.getValueType(); 8043 8044 if (VT == MVT::f32) 8045 return LowerFDIV32(Op, DAG); 8046 8047 if (VT == MVT::f64) 8048 return LowerFDIV64(Op, DAG); 8049 8050 if (VT == MVT::f16) 8051 return LowerFDIV16(Op, DAG); 8052 8053 llvm_unreachable("Unexpected type for fdiv"); 8054 } 8055 8056 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8057 SDLoc DL(Op); 8058 StoreSDNode *Store = cast<StoreSDNode>(Op); 8059 EVT VT = Store->getMemoryVT(); 8060 8061 if (VT == MVT::i1) { 8062 return DAG.getTruncStore(Store->getChain(), DL, 8063 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8064 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8065 } 8066 8067 assert(VT.isVector() && 8068 Store->getValue().getValueType().getScalarType() == MVT::i32); 8069 8070 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8071 VT, *Store->getMemOperand())) { 8072 return expandUnalignedStore(Store, DAG); 8073 } 8074 8075 unsigned AS = Store->getAddressSpace(); 8076 if (Subtarget->hasLDSMisalignedBug() && 8077 AS == AMDGPUAS::FLAT_ADDRESS && 8078 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8079 return SplitVectorStore(Op, DAG); 8080 } 8081 8082 MachineFunction &MF = DAG.getMachineFunction(); 8083 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8084 // If there is a possibilty that flat instruction access scratch memory 8085 // then we need to use the same legalization rules we use for private. 8086 if (AS == AMDGPUAS::FLAT_ADDRESS && 8087 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8088 AS = MFI->hasFlatScratchInit() ? 8089 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8090 8091 unsigned NumElements = VT.getVectorNumElements(); 8092 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8093 AS == AMDGPUAS::FLAT_ADDRESS) { 8094 if (NumElements > 4) 8095 return SplitVectorStore(Op, DAG); 8096 // v3 stores not supported on SI. 8097 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8098 return SplitVectorStore(Op, DAG); 8099 return SDValue(); 8100 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8101 switch (Subtarget->getMaxPrivateElementSize()) { 8102 case 4: 8103 return scalarizeVectorStore(Store, DAG); 8104 case 8: 8105 if (NumElements > 2) 8106 return SplitVectorStore(Op, DAG); 8107 return SDValue(); 8108 case 16: 8109 if (NumElements > 4 || NumElements == 3) 8110 return SplitVectorStore(Op, DAG); 8111 return SDValue(); 8112 default: 8113 llvm_unreachable("unsupported private_element_size"); 8114 } 8115 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8116 // Use ds_write_b128 if possible. 8117 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 8118 VT.getStoreSize() == 16 && NumElements != 3) 8119 return SDValue(); 8120 8121 if (NumElements > 2) 8122 return SplitVectorStore(Op, DAG); 8123 8124 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8125 // address is negative, then the instruction is incorrectly treated as 8126 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8127 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8128 // store later in the SILoadStoreOptimizer. 8129 if (!Subtarget->hasUsableDSOffset() && 8130 NumElements == 2 && VT.getStoreSize() == 8 && 8131 Store->getAlignment() < 8) { 8132 return SplitVectorStore(Op, DAG); 8133 } 8134 8135 return SDValue(); 8136 } else { 8137 llvm_unreachable("unhandled address space"); 8138 } 8139 } 8140 8141 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8142 SDLoc DL(Op); 8143 EVT VT = Op.getValueType(); 8144 SDValue Arg = Op.getOperand(0); 8145 SDValue TrigVal; 8146 8147 // TODO: Should this propagate fast-math-flags? 8148 8149 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT); 8150 8151 if (Subtarget->hasTrigReducedRange()) { 8152 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 8153 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal); 8154 } else { 8155 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 8156 } 8157 8158 switch (Op.getOpcode()) { 8159 case ISD::FCOS: 8160 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal); 8161 case ISD::FSIN: 8162 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal); 8163 default: 8164 llvm_unreachable("Wrong trig opcode"); 8165 } 8166 } 8167 8168 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8169 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8170 assert(AtomicNode->isCompareAndSwap()); 8171 unsigned AS = AtomicNode->getAddressSpace(); 8172 8173 // No custom lowering required for local address space 8174 if (!isFlatGlobalAddrSpace(AS)) 8175 return Op; 8176 8177 // Non-local address space requires custom lowering for atomic compare 8178 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8179 SDLoc DL(Op); 8180 SDValue ChainIn = Op.getOperand(0); 8181 SDValue Addr = Op.getOperand(1); 8182 SDValue Old = Op.getOperand(2); 8183 SDValue New = Op.getOperand(3); 8184 EVT VT = Op.getValueType(); 8185 MVT SimpleVT = VT.getSimpleVT(); 8186 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8187 8188 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8189 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8190 8191 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8192 Ops, VT, AtomicNode->getMemOperand()); 8193 } 8194 8195 //===----------------------------------------------------------------------===// 8196 // Custom DAG optimizations 8197 //===----------------------------------------------------------------------===// 8198 8199 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8200 DAGCombinerInfo &DCI) const { 8201 EVT VT = N->getValueType(0); 8202 EVT ScalarVT = VT.getScalarType(); 8203 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8204 return SDValue(); 8205 8206 SelectionDAG &DAG = DCI.DAG; 8207 SDLoc DL(N); 8208 8209 SDValue Src = N->getOperand(0); 8210 EVT SrcVT = Src.getValueType(); 8211 8212 // TODO: We could try to match extracting the higher bytes, which would be 8213 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8214 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8215 // about in practice. 8216 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8217 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8218 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8219 DCI.AddToWorklist(Cvt.getNode()); 8220 8221 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8222 if (ScalarVT != MVT::f32) { 8223 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8224 DAG.getTargetConstant(0, DL, MVT::i32)); 8225 } 8226 return Cvt; 8227 } 8228 } 8229 8230 return SDValue(); 8231 } 8232 8233 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8234 8235 // This is a variant of 8236 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8237 // 8238 // The normal DAG combiner will do this, but only if the add has one use since 8239 // that would increase the number of instructions. 8240 // 8241 // This prevents us from seeing a constant offset that can be folded into a 8242 // memory instruction's addressing mode. If we know the resulting add offset of 8243 // a pointer can be folded into an addressing offset, we can replace the pointer 8244 // operand with the add of new constant offset. This eliminates one of the uses, 8245 // and may allow the remaining use to also be simplified. 8246 // 8247 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8248 unsigned AddrSpace, 8249 EVT MemVT, 8250 DAGCombinerInfo &DCI) const { 8251 SDValue N0 = N->getOperand(0); 8252 SDValue N1 = N->getOperand(1); 8253 8254 // We only do this to handle cases where it's profitable when there are 8255 // multiple uses of the add, so defer to the standard combine. 8256 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8257 N0->hasOneUse()) 8258 return SDValue(); 8259 8260 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8261 if (!CN1) 8262 return SDValue(); 8263 8264 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8265 if (!CAdd) 8266 return SDValue(); 8267 8268 // If the resulting offset is too large, we can't fold it into the addressing 8269 // mode offset. 8270 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8271 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8272 8273 AddrMode AM; 8274 AM.HasBaseReg = true; 8275 AM.BaseOffs = Offset.getSExtValue(); 8276 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8277 return SDValue(); 8278 8279 SelectionDAG &DAG = DCI.DAG; 8280 SDLoc SL(N); 8281 EVT VT = N->getValueType(0); 8282 8283 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8284 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 8285 8286 SDNodeFlags Flags; 8287 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8288 (N0.getOpcode() == ISD::OR || 8289 N0->getFlags().hasNoUnsignedWrap())); 8290 8291 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8292 } 8293 8294 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8295 DAGCombinerInfo &DCI) const { 8296 SDValue Ptr = N->getBasePtr(); 8297 SelectionDAG &DAG = DCI.DAG; 8298 SDLoc SL(N); 8299 8300 // TODO: We could also do this for multiplies. 8301 if (Ptr.getOpcode() == ISD::SHL) { 8302 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8303 N->getMemoryVT(), DCI); 8304 if (NewPtr) { 8305 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8306 8307 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8308 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8309 } 8310 } 8311 8312 return SDValue(); 8313 } 8314 8315 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8316 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8317 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8318 (Opc == ISD::XOR && Val == 0); 8319 } 8320 8321 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8322 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8323 // integer combine opportunities since most 64-bit operations are decomposed 8324 // this way. TODO: We won't want this for SALU especially if it is an inline 8325 // immediate. 8326 SDValue SITargetLowering::splitBinaryBitConstantOp( 8327 DAGCombinerInfo &DCI, 8328 const SDLoc &SL, 8329 unsigned Opc, SDValue LHS, 8330 const ConstantSDNode *CRHS) const { 8331 uint64_t Val = CRHS->getZExtValue(); 8332 uint32_t ValLo = Lo_32(Val); 8333 uint32_t ValHi = Hi_32(Val); 8334 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8335 8336 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8337 bitOpWithConstantIsReducible(Opc, ValHi)) || 8338 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8339 // If we need to materialize a 64-bit immediate, it will be split up later 8340 // anyway. Avoid creating the harder to understand 64-bit immediate 8341 // materialization. 8342 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8343 } 8344 8345 return SDValue(); 8346 } 8347 8348 // Returns true if argument is a boolean value which is not serialized into 8349 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8350 static bool isBoolSGPR(SDValue V) { 8351 if (V.getValueType() != MVT::i1) 8352 return false; 8353 switch (V.getOpcode()) { 8354 default: break; 8355 case ISD::SETCC: 8356 case ISD::AND: 8357 case ISD::OR: 8358 case ISD::XOR: 8359 case AMDGPUISD::FP_CLASS: 8360 return true; 8361 } 8362 return false; 8363 } 8364 8365 // If a constant has all zeroes or all ones within each byte return it. 8366 // Otherwise return 0. 8367 static uint32_t getConstantPermuteMask(uint32_t C) { 8368 // 0xff for any zero byte in the mask 8369 uint32_t ZeroByteMask = 0; 8370 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8371 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8372 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8373 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8374 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8375 if ((NonZeroByteMask & C) != NonZeroByteMask) 8376 return 0; // Partial bytes selected. 8377 return C; 8378 } 8379 8380 // Check if a node selects whole bytes from its operand 0 starting at a byte 8381 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8382 // or -1 if not succeeded. 8383 // Note byte select encoding: 8384 // value 0-3 selects corresponding source byte; 8385 // value 0xc selects zero; 8386 // value 0xff selects 0xff. 8387 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8388 assert(V.getValueSizeInBits() == 32); 8389 8390 if (V.getNumOperands() != 2) 8391 return ~0; 8392 8393 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8394 if (!N1) 8395 return ~0; 8396 8397 uint32_t C = N1->getZExtValue(); 8398 8399 switch (V.getOpcode()) { 8400 default: 8401 break; 8402 case ISD::AND: 8403 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8404 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8405 } 8406 break; 8407 8408 case ISD::OR: 8409 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8410 return (0x03020100 & ~ConstMask) | ConstMask; 8411 } 8412 break; 8413 8414 case ISD::SHL: 8415 if (C % 8) 8416 return ~0; 8417 8418 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8419 8420 case ISD::SRL: 8421 if (C % 8) 8422 return ~0; 8423 8424 return uint32_t(0x0c0c0c0c03020100ull >> C); 8425 } 8426 8427 return ~0; 8428 } 8429 8430 SDValue SITargetLowering::performAndCombine(SDNode *N, 8431 DAGCombinerInfo &DCI) const { 8432 if (DCI.isBeforeLegalize()) 8433 return SDValue(); 8434 8435 SelectionDAG &DAG = DCI.DAG; 8436 EVT VT = N->getValueType(0); 8437 SDValue LHS = N->getOperand(0); 8438 SDValue RHS = N->getOperand(1); 8439 8440 8441 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8442 if (VT == MVT::i64 && CRHS) { 8443 if (SDValue Split 8444 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8445 return Split; 8446 } 8447 8448 if (CRHS && VT == MVT::i32) { 8449 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8450 // nb = number of trailing zeroes in mask 8451 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8452 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8453 uint64_t Mask = CRHS->getZExtValue(); 8454 unsigned Bits = countPopulation(Mask); 8455 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8456 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8457 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8458 unsigned Shift = CShift->getZExtValue(); 8459 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8460 unsigned Offset = NB + Shift; 8461 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8462 SDLoc SL(N); 8463 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8464 LHS->getOperand(0), 8465 DAG.getConstant(Offset, SL, MVT::i32), 8466 DAG.getConstant(Bits, SL, MVT::i32)); 8467 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8468 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8469 DAG.getValueType(NarrowVT)); 8470 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8471 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8472 return Shl; 8473 } 8474 } 8475 } 8476 8477 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8478 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8479 isa<ConstantSDNode>(LHS.getOperand(2))) { 8480 uint32_t Sel = getConstantPermuteMask(Mask); 8481 if (!Sel) 8482 return SDValue(); 8483 8484 // Select 0xc for all zero bytes 8485 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8486 SDLoc DL(N); 8487 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8488 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8489 } 8490 } 8491 8492 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8493 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8494 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8495 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8496 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8497 8498 SDValue X = LHS.getOperand(0); 8499 SDValue Y = RHS.getOperand(0); 8500 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8501 return SDValue(); 8502 8503 if (LCC == ISD::SETO) { 8504 if (X != LHS.getOperand(1)) 8505 return SDValue(); 8506 8507 if (RCC == ISD::SETUNE) { 8508 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8509 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8510 return SDValue(); 8511 8512 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8513 SIInstrFlags::N_SUBNORMAL | 8514 SIInstrFlags::N_ZERO | 8515 SIInstrFlags::P_ZERO | 8516 SIInstrFlags::P_SUBNORMAL | 8517 SIInstrFlags::P_NORMAL; 8518 8519 static_assert(((~(SIInstrFlags::S_NAN | 8520 SIInstrFlags::Q_NAN | 8521 SIInstrFlags::N_INFINITY | 8522 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8523 "mask not equal"); 8524 8525 SDLoc DL(N); 8526 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8527 X, DAG.getConstant(Mask, DL, MVT::i32)); 8528 } 8529 } 8530 } 8531 8532 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8533 std::swap(LHS, RHS); 8534 8535 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8536 RHS.hasOneUse()) { 8537 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8538 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8539 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8540 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8541 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8542 (RHS.getOperand(0) == LHS.getOperand(0) && 8543 LHS.getOperand(0) == LHS.getOperand(1))) { 8544 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8545 unsigned NewMask = LCC == ISD::SETO ? 8546 Mask->getZExtValue() & ~OrdMask : 8547 Mask->getZExtValue() & OrdMask; 8548 8549 SDLoc DL(N); 8550 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8551 DAG.getConstant(NewMask, DL, MVT::i32)); 8552 } 8553 } 8554 8555 if (VT == MVT::i32 && 8556 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8557 // and x, (sext cc from i1) => select cc, x, 0 8558 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8559 std::swap(LHS, RHS); 8560 if (isBoolSGPR(RHS.getOperand(0))) 8561 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8562 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8563 } 8564 8565 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8566 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8567 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8568 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8569 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8570 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8571 if (LHSMask != ~0u && RHSMask != ~0u) { 8572 // Canonicalize the expression in an attempt to have fewer unique masks 8573 // and therefore fewer registers used to hold the masks. 8574 if (LHSMask > RHSMask) { 8575 std::swap(LHSMask, RHSMask); 8576 std::swap(LHS, RHS); 8577 } 8578 8579 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8580 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8581 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8582 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8583 8584 // Check of we need to combine values from two sources within a byte. 8585 if (!(LHSUsedLanes & RHSUsedLanes) && 8586 // If we select high and lower word keep it for SDWA. 8587 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8588 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8589 // Each byte in each mask is either selector mask 0-3, or has higher 8590 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8591 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8592 // mask which is not 0xff wins. By anding both masks we have a correct 8593 // result except that 0x0c shall be corrected to give 0x0c only. 8594 uint32_t Mask = LHSMask & RHSMask; 8595 for (unsigned I = 0; I < 32; I += 8) { 8596 uint32_t ByteSel = 0xff << I; 8597 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8598 Mask &= (0x0c << I) & 0xffffffff; 8599 } 8600 8601 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8602 // or 0x0c. 8603 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8604 SDLoc DL(N); 8605 8606 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8607 LHS.getOperand(0), RHS.getOperand(0), 8608 DAG.getConstant(Sel, DL, MVT::i32)); 8609 } 8610 } 8611 } 8612 8613 return SDValue(); 8614 } 8615 8616 SDValue SITargetLowering::performOrCombine(SDNode *N, 8617 DAGCombinerInfo &DCI) const { 8618 SelectionDAG &DAG = DCI.DAG; 8619 SDValue LHS = N->getOperand(0); 8620 SDValue RHS = N->getOperand(1); 8621 8622 EVT VT = N->getValueType(0); 8623 if (VT == MVT::i1) { 8624 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8625 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8626 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8627 SDValue Src = LHS.getOperand(0); 8628 if (Src != RHS.getOperand(0)) 8629 return SDValue(); 8630 8631 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8632 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8633 if (!CLHS || !CRHS) 8634 return SDValue(); 8635 8636 // Only 10 bits are used. 8637 static const uint32_t MaxMask = 0x3ff; 8638 8639 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8640 SDLoc DL(N); 8641 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8642 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8643 } 8644 8645 return SDValue(); 8646 } 8647 8648 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8649 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8650 LHS.getOpcode() == AMDGPUISD::PERM && 8651 isa<ConstantSDNode>(LHS.getOperand(2))) { 8652 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8653 if (!Sel) 8654 return SDValue(); 8655 8656 Sel |= LHS.getConstantOperandVal(2); 8657 SDLoc DL(N); 8658 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8659 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8660 } 8661 8662 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8663 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8664 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8665 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8666 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8667 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8668 if (LHSMask != ~0u && RHSMask != ~0u) { 8669 // Canonicalize the expression in an attempt to have fewer unique masks 8670 // and therefore fewer registers used to hold the masks. 8671 if (LHSMask > RHSMask) { 8672 std::swap(LHSMask, RHSMask); 8673 std::swap(LHS, RHS); 8674 } 8675 8676 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8677 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8678 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8679 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8680 8681 // Check of we need to combine values from two sources within a byte. 8682 if (!(LHSUsedLanes & RHSUsedLanes) && 8683 // If we select high and lower word keep it for SDWA. 8684 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8685 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8686 // Kill zero bytes selected by other mask. Zero value is 0xc. 8687 LHSMask &= ~RHSUsedLanes; 8688 RHSMask &= ~LHSUsedLanes; 8689 // Add 4 to each active LHS lane 8690 LHSMask |= LHSUsedLanes & 0x04040404; 8691 // Combine masks 8692 uint32_t Sel = LHSMask | RHSMask; 8693 SDLoc DL(N); 8694 8695 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8696 LHS.getOperand(0), RHS.getOperand(0), 8697 DAG.getConstant(Sel, DL, MVT::i32)); 8698 } 8699 } 8700 } 8701 8702 if (VT != MVT::i64) 8703 return SDValue(); 8704 8705 // TODO: This could be a generic combine with a predicate for extracting the 8706 // high half of an integer being free. 8707 8708 // (or i64:x, (zero_extend i32:y)) -> 8709 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8710 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8711 RHS.getOpcode() != ISD::ZERO_EXTEND) 8712 std::swap(LHS, RHS); 8713 8714 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8715 SDValue ExtSrc = RHS.getOperand(0); 8716 EVT SrcVT = ExtSrc.getValueType(); 8717 if (SrcVT == MVT::i32) { 8718 SDLoc SL(N); 8719 SDValue LowLHS, HiBits; 8720 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 8721 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 8722 8723 DCI.AddToWorklist(LowOr.getNode()); 8724 DCI.AddToWorklist(HiBits.getNode()); 8725 8726 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 8727 LowOr, HiBits); 8728 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 8729 } 8730 } 8731 8732 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8733 if (CRHS) { 8734 if (SDValue Split 8735 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 8736 return Split; 8737 } 8738 8739 return SDValue(); 8740 } 8741 8742 SDValue SITargetLowering::performXorCombine(SDNode *N, 8743 DAGCombinerInfo &DCI) const { 8744 EVT VT = N->getValueType(0); 8745 if (VT != MVT::i64) 8746 return SDValue(); 8747 8748 SDValue LHS = N->getOperand(0); 8749 SDValue RHS = N->getOperand(1); 8750 8751 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8752 if (CRHS) { 8753 if (SDValue Split 8754 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 8755 return Split; 8756 } 8757 8758 return SDValue(); 8759 } 8760 8761 // Instructions that will be lowered with a final instruction that zeros the 8762 // high result bits. 8763 // XXX - probably only need to list legal operations. 8764 static bool fp16SrcZerosHighBits(unsigned Opc) { 8765 switch (Opc) { 8766 case ISD::FADD: 8767 case ISD::FSUB: 8768 case ISD::FMUL: 8769 case ISD::FDIV: 8770 case ISD::FREM: 8771 case ISD::FMA: 8772 case ISD::FMAD: 8773 case ISD::FCANONICALIZE: 8774 case ISD::FP_ROUND: 8775 case ISD::UINT_TO_FP: 8776 case ISD::SINT_TO_FP: 8777 case ISD::FABS: 8778 // Fabs is lowered to a bit operation, but it's an and which will clear the 8779 // high bits anyway. 8780 case ISD::FSQRT: 8781 case ISD::FSIN: 8782 case ISD::FCOS: 8783 case ISD::FPOWI: 8784 case ISD::FPOW: 8785 case ISD::FLOG: 8786 case ISD::FLOG2: 8787 case ISD::FLOG10: 8788 case ISD::FEXP: 8789 case ISD::FEXP2: 8790 case ISD::FCEIL: 8791 case ISD::FTRUNC: 8792 case ISD::FRINT: 8793 case ISD::FNEARBYINT: 8794 case ISD::FROUND: 8795 case ISD::FFLOOR: 8796 case ISD::FMINNUM: 8797 case ISD::FMAXNUM: 8798 case AMDGPUISD::FRACT: 8799 case AMDGPUISD::CLAMP: 8800 case AMDGPUISD::COS_HW: 8801 case AMDGPUISD::SIN_HW: 8802 case AMDGPUISD::FMIN3: 8803 case AMDGPUISD::FMAX3: 8804 case AMDGPUISD::FMED3: 8805 case AMDGPUISD::FMAD_FTZ: 8806 case AMDGPUISD::RCP: 8807 case AMDGPUISD::RSQ: 8808 case AMDGPUISD::RCP_IFLAG: 8809 case AMDGPUISD::LDEXP: 8810 return true; 8811 default: 8812 // fcopysign, select and others may be lowered to 32-bit bit operations 8813 // which don't zero the high bits. 8814 return false; 8815 } 8816 } 8817 8818 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 8819 DAGCombinerInfo &DCI) const { 8820 if (!Subtarget->has16BitInsts() || 8821 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8822 return SDValue(); 8823 8824 EVT VT = N->getValueType(0); 8825 if (VT != MVT::i32) 8826 return SDValue(); 8827 8828 SDValue Src = N->getOperand(0); 8829 if (Src.getValueType() != MVT::i16) 8830 return SDValue(); 8831 8832 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 8833 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 8834 if (Src.getOpcode() == ISD::BITCAST) { 8835 SDValue BCSrc = Src.getOperand(0); 8836 if (BCSrc.getValueType() == MVT::f16 && 8837 fp16SrcZerosHighBits(BCSrc.getOpcode())) 8838 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 8839 } 8840 8841 return SDValue(); 8842 } 8843 8844 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 8845 DAGCombinerInfo &DCI) 8846 const { 8847 SDValue Src = N->getOperand(0); 8848 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 8849 8850 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 8851 VTSign->getVT() == MVT::i8) || 8852 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 8853 VTSign->getVT() == MVT::i16)) && 8854 Src.hasOneUse()) { 8855 auto *M = cast<MemSDNode>(Src); 8856 SDValue Ops[] = { 8857 Src.getOperand(0), // Chain 8858 Src.getOperand(1), // rsrc 8859 Src.getOperand(2), // vindex 8860 Src.getOperand(3), // voffset 8861 Src.getOperand(4), // soffset 8862 Src.getOperand(5), // offset 8863 Src.getOperand(6), 8864 Src.getOperand(7) 8865 }; 8866 // replace with BUFFER_LOAD_BYTE/SHORT 8867 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 8868 Src.getOperand(0).getValueType()); 8869 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 8870 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 8871 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 8872 ResList, 8873 Ops, M->getMemoryVT(), 8874 M->getMemOperand()); 8875 return DCI.DAG.getMergeValues({BufferLoadSignExt, 8876 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 8877 } 8878 return SDValue(); 8879 } 8880 8881 SDValue SITargetLowering::performClassCombine(SDNode *N, 8882 DAGCombinerInfo &DCI) const { 8883 SelectionDAG &DAG = DCI.DAG; 8884 SDValue Mask = N->getOperand(1); 8885 8886 // fp_class x, 0 -> false 8887 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 8888 if (CMask->isNullValue()) 8889 return DAG.getConstant(0, SDLoc(N), MVT::i1); 8890 } 8891 8892 if (N->getOperand(0).isUndef()) 8893 return DAG.getUNDEF(MVT::i1); 8894 8895 return SDValue(); 8896 } 8897 8898 SDValue SITargetLowering::performRcpCombine(SDNode *N, 8899 DAGCombinerInfo &DCI) const { 8900 EVT VT = N->getValueType(0); 8901 SDValue N0 = N->getOperand(0); 8902 8903 if (N0.isUndef()) 8904 return N0; 8905 8906 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 8907 N0.getOpcode() == ISD::SINT_TO_FP)) { 8908 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 8909 N->getFlags()); 8910 } 8911 8912 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 8913 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 8914 N0.getOperand(0), N->getFlags()); 8915 } 8916 8917 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 8918 } 8919 8920 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 8921 unsigned MaxDepth) const { 8922 unsigned Opcode = Op.getOpcode(); 8923 if (Opcode == ISD::FCANONICALIZE) 8924 return true; 8925 8926 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8927 auto F = CFP->getValueAPF(); 8928 if (F.isNaN() && F.isSignaling()) 8929 return false; 8930 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 8931 } 8932 8933 // If source is a result of another standard FP operation it is already in 8934 // canonical form. 8935 if (MaxDepth == 0) 8936 return false; 8937 8938 switch (Opcode) { 8939 // These will flush denorms if required. 8940 case ISD::FADD: 8941 case ISD::FSUB: 8942 case ISD::FMUL: 8943 case ISD::FCEIL: 8944 case ISD::FFLOOR: 8945 case ISD::FMA: 8946 case ISD::FMAD: 8947 case ISD::FSQRT: 8948 case ISD::FDIV: 8949 case ISD::FREM: 8950 case ISD::FP_ROUND: 8951 case ISD::FP_EXTEND: 8952 case AMDGPUISD::FMUL_LEGACY: 8953 case AMDGPUISD::FMAD_FTZ: 8954 case AMDGPUISD::RCP: 8955 case AMDGPUISD::RSQ: 8956 case AMDGPUISD::RSQ_CLAMP: 8957 case AMDGPUISD::RCP_LEGACY: 8958 case AMDGPUISD::RCP_IFLAG: 8959 case AMDGPUISD::TRIG_PREOP: 8960 case AMDGPUISD::DIV_SCALE: 8961 case AMDGPUISD::DIV_FMAS: 8962 case AMDGPUISD::DIV_FIXUP: 8963 case AMDGPUISD::FRACT: 8964 case AMDGPUISD::LDEXP: 8965 case AMDGPUISD::CVT_PKRTZ_F16_F32: 8966 case AMDGPUISD::CVT_F32_UBYTE0: 8967 case AMDGPUISD::CVT_F32_UBYTE1: 8968 case AMDGPUISD::CVT_F32_UBYTE2: 8969 case AMDGPUISD::CVT_F32_UBYTE3: 8970 return true; 8971 8972 // It can/will be lowered or combined as a bit operation. 8973 // Need to check their input recursively to handle. 8974 case ISD::FNEG: 8975 case ISD::FABS: 8976 case ISD::FCOPYSIGN: 8977 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8978 8979 case ISD::FSIN: 8980 case ISD::FCOS: 8981 case ISD::FSINCOS: 8982 return Op.getValueType().getScalarType() != MVT::f16; 8983 8984 case ISD::FMINNUM: 8985 case ISD::FMAXNUM: 8986 case ISD::FMINNUM_IEEE: 8987 case ISD::FMAXNUM_IEEE: 8988 case AMDGPUISD::CLAMP: 8989 case AMDGPUISD::FMED3: 8990 case AMDGPUISD::FMAX3: 8991 case AMDGPUISD::FMIN3: { 8992 // FIXME: Shouldn't treat the generic operations different based these. 8993 // However, we aren't really required to flush the result from 8994 // minnum/maxnum.. 8995 8996 // snans will be quieted, so we only need to worry about denormals. 8997 if (Subtarget->supportsMinMaxDenormModes() || 8998 denormalsEnabledForType(DAG, Op.getValueType())) 8999 return true; 9000 9001 // Flushing may be required. 9002 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9003 // targets need to check their input recursively. 9004 9005 // FIXME: Does this apply with clamp? It's implemented with max. 9006 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9007 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9008 return false; 9009 } 9010 9011 return true; 9012 } 9013 case ISD::SELECT: { 9014 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9015 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9016 } 9017 case ISD::BUILD_VECTOR: { 9018 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9019 SDValue SrcOp = Op.getOperand(i); 9020 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9021 return false; 9022 } 9023 9024 return true; 9025 } 9026 case ISD::EXTRACT_VECTOR_ELT: 9027 case ISD::EXTRACT_SUBVECTOR: { 9028 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9029 } 9030 case ISD::INSERT_VECTOR_ELT: { 9031 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9032 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9033 } 9034 case ISD::UNDEF: 9035 // Could be anything. 9036 return false; 9037 9038 case ISD::BITCAST: { 9039 // Hack round the mess we make when legalizing extract_vector_elt 9040 SDValue Src = Op.getOperand(0); 9041 if (Src.getValueType() == MVT::i16 && 9042 Src.getOpcode() == ISD::TRUNCATE) { 9043 SDValue TruncSrc = Src.getOperand(0); 9044 if (TruncSrc.getValueType() == MVT::i32 && 9045 TruncSrc.getOpcode() == ISD::BITCAST && 9046 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9047 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9048 } 9049 } 9050 9051 return false; 9052 } 9053 case ISD::INTRINSIC_WO_CHAIN: { 9054 unsigned IntrinsicID 9055 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9056 // TODO: Handle more intrinsics 9057 switch (IntrinsicID) { 9058 case Intrinsic::amdgcn_cvt_pkrtz: 9059 case Intrinsic::amdgcn_cubeid: 9060 case Intrinsic::amdgcn_frexp_mant: 9061 case Intrinsic::amdgcn_fdot2: 9062 case Intrinsic::amdgcn_rcp: 9063 case Intrinsic::amdgcn_rsq: 9064 case Intrinsic::amdgcn_rsq_clamp: 9065 case Intrinsic::amdgcn_rcp_legacy: 9066 case Intrinsic::amdgcn_rsq_legacy: 9067 return true; 9068 default: 9069 break; 9070 } 9071 9072 LLVM_FALLTHROUGH; 9073 } 9074 default: 9075 return denormalsEnabledForType(DAG, Op.getValueType()) && 9076 DAG.isKnownNeverSNaN(Op); 9077 } 9078 9079 llvm_unreachable("invalid operation"); 9080 } 9081 9082 // Constant fold canonicalize. 9083 SDValue SITargetLowering::getCanonicalConstantFP( 9084 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9085 // Flush denormals to 0 if not enabled. 9086 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9087 return DAG.getConstantFP(0.0, SL, VT); 9088 9089 if (C.isNaN()) { 9090 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9091 if (C.isSignaling()) { 9092 // Quiet a signaling NaN. 9093 // FIXME: Is this supposed to preserve payload bits? 9094 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9095 } 9096 9097 // Make sure it is the canonical NaN bitpattern. 9098 // 9099 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9100 // immediate? 9101 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9102 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9103 } 9104 9105 // Already canonical. 9106 return DAG.getConstantFP(C, SL, VT); 9107 } 9108 9109 static bool vectorEltWillFoldAway(SDValue Op) { 9110 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9111 } 9112 9113 SDValue SITargetLowering::performFCanonicalizeCombine( 9114 SDNode *N, 9115 DAGCombinerInfo &DCI) const { 9116 SelectionDAG &DAG = DCI.DAG; 9117 SDValue N0 = N->getOperand(0); 9118 EVT VT = N->getValueType(0); 9119 9120 // fcanonicalize undef -> qnan 9121 if (N0.isUndef()) { 9122 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9123 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9124 } 9125 9126 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9127 EVT VT = N->getValueType(0); 9128 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9129 } 9130 9131 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9132 // (fcanonicalize k) 9133 // 9134 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9135 9136 // TODO: This could be better with wider vectors that will be split to v2f16, 9137 // and to consider uses since there aren't that many packed operations. 9138 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9139 isTypeLegal(MVT::v2f16)) { 9140 SDLoc SL(N); 9141 SDValue NewElts[2]; 9142 SDValue Lo = N0.getOperand(0); 9143 SDValue Hi = N0.getOperand(1); 9144 EVT EltVT = Lo.getValueType(); 9145 9146 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9147 for (unsigned I = 0; I != 2; ++I) { 9148 SDValue Op = N0.getOperand(I); 9149 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9150 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9151 CFP->getValueAPF()); 9152 } else if (Op.isUndef()) { 9153 // Handled below based on what the other operand is. 9154 NewElts[I] = Op; 9155 } else { 9156 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9157 } 9158 } 9159 9160 // If one half is undef, and one is constant, perfer a splat vector rather 9161 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9162 // cheaper to use and may be free with a packed operation. 9163 if (NewElts[0].isUndef()) { 9164 if (isa<ConstantFPSDNode>(NewElts[1])) 9165 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9166 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9167 } 9168 9169 if (NewElts[1].isUndef()) { 9170 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9171 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9172 } 9173 9174 return DAG.getBuildVector(VT, SL, NewElts); 9175 } 9176 } 9177 9178 unsigned SrcOpc = N0.getOpcode(); 9179 9180 // If it's free to do so, push canonicalizes further up the source, which may 9181 // find a canonical source. 9182 // 9183 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9184 // sNaNs. 9185 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9186 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9187 if (CRHS && N0.hasOneUse()) { 9188 SDLoc SL(N); 9189 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9190 N0.getOperand(0)); 9191 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9192 DCI.AddToWorklist(Canon0.getNode()); 9193 9194 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9195 } 9196 } 9197 9198 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9199 } 9200 9201 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9202 switch (Opc) { 9203 case ISD::FMAXNUM: 9204 case ISD::FMAXNUM_IEEE: 9205 return AMDGPUISD::FMAX3; 9206 case ISD::SMAX: 9207 return AMDGPUISD::SMAX3; 9208 case ISD::UMAX: 9209 return AMDGPUISD::UMAX3; 9210 case ISD::FMINNUM: 9211 case ISD::FMINNUM_IEEE: 9212 return AMDGPUISD::FMIN3; 9213 case ISD::SMIN: 9214 return AMDGPUISD::SMIN3; 9215 case ISD::UMIN: 9216 return AMDGPUISD::UMIN3; 9217 default: 9218 llvm_unreachable("Not a min/max opcode"); 9219 } 9220 } 9221 9222 SDValue SITargetLowering::performIntMed3ImmCombine( 9223 SelectionDAG &DAG, const SDLoc &SL, 9224 SDValue Op0, SDValue Op1, bool Signed) const { 9225 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9226 if (!K1) 9227 return SDValue(); 9228 9229 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9230 if (!K0) 9231 return SDValue(); 9232 9233 if (Signed) { 9234 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9235 return SDValue(); 9236 } else { 9237 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9238 return SDValue(); 9239 } 9240 9241 EVT VT = K0->getValueType(0); 9242 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9243 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9244 return DAG.getNode(Med3Opc, SL, VT, 9245 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9246 } 9247 9248 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9249 MVT NVT = MVT::i32; 9250 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9251 9252 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9253 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9254 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9255 9256 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9257 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9258 } 9259 9260 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9261 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9262 return C; 9263 9264 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9265 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9266 return C; 9267 } 9268 9269 return nullptr; 9270 } 9271 9272 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9273 const SDLoc &SL, 9274 SDValue Op0, 9275 SDValue Op1) const { 9276 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9277 if (!K1) 9278 return SDValue(); 9279 9280 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9281 if (!K0) 9282 return SDValue(); 9283 9284 // Ordered >= (although NaN inputs should have folded away by now). 9285 if (K0->getValueAPF() > K1->getValueAPF()) 9286 return SDValue(); 9287 9288 const MachineFunction &MF = DAG.getMachineFunction(); 9289 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9290 9291 // TODO: Check IEEE bit enabled? 9292 EVT VT = Op0.getValueType(); 9293 if (Info->getMode().DX10Clamp) { 9294 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9295 // hardware fmed3 behavior converting to a min. 9296 // FIXME: Should this be allowing -0.0? 9297 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9298 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9299 } 9300 9301 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9302 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9303 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9304 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9305 // then give the other result, which is different from med3 with a NaN 9306 // input. 9307 SDValue Var = Op0.getOperand(0); 9308 if (!DAG.isKnownNeverSNaN(Var)) 9309 return SDValue(); 9310 9311 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9312 9313 if ((!K0->hasOneUse() || 9314 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9315 (!K1->hasOneUse() || 9316 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9317 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9318 Var, SDValue(K0, 0), SDValue(K1, 0)); 9319 } 9320 } 9321 9322 return SDValue(); 9323 } 9324 9325 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9326 DAGCombinerInfo &DCI) const { 9327 SelectionDAG &DAG = DCI.DAG; 9328 9329 EVT VT = N->getValueType(0); 9330 unsigned Opc = N->getOpcode(); 9331 SDValue Op0 = N->getOperand(0); 9332 SDValue Op1 = N->getOperand(1); 9333 9334 // Only do this if the inner op has one use since this will just increases 9335 // register pressure for no benefit. 9336 9337 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9338 !VT.isVector() && 9339 (VT == MVT::i32 || VT == MVT::f32 || 9340 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9341 // max(max(a, b), c) -> max3(a, b, c) 9342 // min(min(a, b), c) -> min3(a, b, c) 9343 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9344 SDLoc DL(N); 9345 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9346 DL, 9347 N->getValueType(0), 9348 Op0.getOperand(0), 9349 Op0.getOperand(1), 9350 Op1); 9351 } 9352 9353 // Try commuted. 9354 // max(a, max(b, c)) -> max3(a, b, c) 9355 // min(a, min(b, c)) -> min3(a, b, c) 9356 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9357 SDLoc DL(N); 9358 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9359 DL, 9360 N->getValueType(0), 9361 Op0, 9362 Op1.getOperand(0), 9363 Op1.getOperand(1)); 9364 } 9365 } 9366 9367 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9368 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9369 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9370 return Med3; 9371 } 9372 9373 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9374 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9375 return Med3; 9376 } 9377 9378 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9379 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9380 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9381 (Opc == AMDGPUISD::FMIN_LEGACY && 9382 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9383 (VT == MVT::f32 || VT == MVT::f64 || 9384 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9385 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9386 Op0.hasOneUse()) { 9387 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9388 return Res; 9389 } 9390 9391 return SDValue(); 9392 } 9393 9394 static bool isClampZeroToOne(SDValue A, SDValue B) { 9395 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9396 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9397 // FIXME: Should this be allowing -0.0? 9398 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9399 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9400 } 9401 } 9402 9403 return false; 9404 } 9405 9406 // FIXME: Should only worry about snans for version with chain. 9407 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9408 DAGCombinerInfo &DCI) const { 9409 EVT VT = N->getValueType(0); 9410 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9411 // NaNs. With a NaN input, the order of the operands may change the result. 9412 9413 SelectionDAG &DAG = DCI.DAG; 9414 SDLoc SL(N); 9415 9416 SDValue Src0 = N->getOperand(0); 9417 SDValue Src1 = N->getOperand(1); 9418 SDValue Src2 = N->getOperand(2); 9419 9420 if (isClampZeroToOne(Src0, Src1)) { 9421 // const_a, const_b, x -> clamp is safe in all cases including signaling 9422 // nans. 9423 // FIXME: Should this be allowing -0.0? 9424 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9425 } 9426 9427 const MachineFunction &MF = DAG.getMachineFunction(); 9428 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9429 9430 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9431 // handling no dx10-clamp? 9432 if (Info->getMode().DX10Clamp) { 9433 // If NaNs is clamped to 0, we are free to reorder the inputs. 9434 9435 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9436 std::swap(Src0, Src1); 9437 9438 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9439 std::swap(Src1, Src2); 9440 9441 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9442 std::swap(Src0, Src1); 9443 9444 if (isClampZeroToOne(Src1, Src2)) 9445 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9446 } 9447 9448 return SDValue(); 9449 } 9450 9451 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9452 DAGCombinerInfo &DCI) const { 9453 SDValue Src0 = N->getOperand(0); 9454 SDValue Src1 = N->getOperand(1); 9455 if (Src0.isUndef() && Src1.isUndef()) 9456 return DCI.DAG.getUNDEF(N->getValueType(0)); 9457 return SDValue(); 9458 } 9459 9460 SDValue SITargetLowering::performExtractVectorEltCombine( 9461 SDNode *N, DAGCombinerInfo &DCI) const { 9462 SDValue Vec = N->getOperand(0); 9463 SelectionDAG &DAG = DCI.DAG; 9464 9465 EVT VecVT = Vec.getValueType(); 9466 EVT EltVT = VecVT.getVectorElementType(); 9467 9468 if ((Vec.getOpcode() == ISD::FNEG || 9469 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9470 SDLoc SL(N); 9471 EVT EltVT = N->getValueType(0); 9472 SDValue Idx = N->getOperand(1); 9473 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9474 Vec.getOperand(0), Idx); 9475 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9476 } 9477 9478 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9479 // => 9480 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9481 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9482 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9483 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9484 SDLoc SL(N); 9485 EVT EltVT = N->getValueType(0); 9486 SDValue Idx = N->getOperand(1); 9487 unsigned Opc = Vec.getOpcode(); 9488 9489 switch(Opc) { 9490 default: 9491 break; 9492 // TODO: Support other binary operations. 9493 case ISD::FADD: 9494 case ISD::FSUB: 9495 case ISD::FMUL: 9496 case ISD::ADD: 9497 case ISD::UMIN: 9498 case ISD::UMAX: 9499 case ISD::SMIN: 9500 case ISD::SMAX: 9501 case ISD::FMAXNUM: 9502 case ISD::FMINNUM: 9503 case ISD::FMAXNUM_IEEE: 9504 case ISD::FMINNUM_IEEE: { 9505 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9506 Vec.getOperand(0), Idx); 9507 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9508 Vec.getOperand(1), Idx); 9509 9510 DCI.AddToWorklist(Elt0.getNode()); 9511 DCI.AddToWorklist(Elt1.getNode()); 9512 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9513 } 9514 } 9515 } 9516 9517 unsigned VecSize = VecVT.getSizeInBits(); 9518 unsigned EltSize = EltVT.getSizeInBits(); 9519 9520 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9521 // This elminates non-constant index and subsequent movrel or scratch access. 9522 // Sub-dword vectors of size 2 dword or less have better implementation. 9523 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9524 // instructions. 9525 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) && 9526 !isa<ConstantSDNode>(N->getOperand(1))) { 9527 SDLoc SL(N); 9528 SDValue Idx = N->getOperand(1); 9529 SDValue V; 9530 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9531 SDValue IC = DAG.getVectorIdxConstant(I, SL); 9532 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9533 if (I == 0) 9534 V = Elt; 9535 else 9536 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9537 } 9538 return V; 9539 } 9540 9541 if (!DCI.isBeforeLegalize()) 9542 return SDValue(); 9543 9544 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9545 // elements. This exposes more load reduction opportunities by replacing 9546 // multiple small extract_vector_elements with a single 32-bit extract. 9547 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9548 if (isa<MemSDNode>(Vec) && 9549 EltSize <= 16 && 9550 EltVT.isByteSized() && 9551 VecSize > 32 && 9552 VecSize % 32 == 0 && 9553 Idx) { 9554 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9555 9556 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9557 unsigned EltIdx = BitIndex / 32; 9558 unsigned LeftoverBitIdx = BitIndex % 32; 9559 SDLoc SL(N); 9560 9561 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9562 DCI.AddToWorklist(Cast.getNode()); 9563 9564 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9565 DAG.getConstant(EltIdx, SL, MVT::i32)); 9566 DCI.AddToWorklist(Elt.getNode()); 9567 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9568 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9569 DCI.AddToWorklist(Srl.getNode()); 9570 9571 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9572 DCI.AddToWorklist(Trunc.getNode()); 9573 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9574 } 9575 9576 return SDValue(); 9577 } 9578 9579 SDValue 9580 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9581 DAGCombinerInfo &DCI) const { 9582 SDValue Vec = N->getOperand(0); 9583 SDValue Idx = N->getOperand(2); 9584 EVT VecVT = Vec.getValueType(); 9585 EVT EltVT = VecVT.getVectorElementType(); 9586 unsigned VecSize = VecVT.getSizeInBits(); 9587 unsigned EltSize = EltVT.getSizeInBits(); 9588 9589 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9590 // => BUILD_VECTOR n x select (e, const-idx) 9591 // This elminates non-constant index and subsequent movrel or scratch access. 9592 // Sub-dword vectors of size 2 dword or less have better implementation. 9593 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9594 // instructions. 9595 if (isa<ConstantSDNode>(Idx) || 9596 VecSize > 256 || (VecSize <= 64 && EltSize < 32)) 9597 return SDValue(); 9598 9599 SelectionDAG &DAG = DCI.DAG; 9600 SDLoc SL(N); 9601 SDValue Ins = N->getOperand(1); 9602 EVT IdxVT = Idx.getValueType(); 9603 9604 SmallVector<SDValue, 16> Ops; 9605 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9606 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9607 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9608 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9609 Ops.push_back(V); 9610 } 9611 9612 return DAG.getBuildVector(VecVT, SL, Ops); 9613 } 9614 9615 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9616 const SDNode *N0, 9617 const SDNode *N1) const { 9618 EVT VT = N0->getValueType(0); 9619 9620 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9621 // support denormals ever. 9622 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9623 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9624 getSubtarget()->hasMadF16())) && 9625 isOperationLegal(ISD::FMAD, VT)) 9626 return ISD::FMAD; 9627 9628 const TargetOptions &Options = DAG.getTarget().Options; 9629 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9630 (N0->getFlags().hasAllowContract() && 9631 N1->getFlags().hasAllowContract())) && 9632 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 9633 return ISD::FMA; 9634 } 9635 9636 return 0; 9637 } 9638 9639 // For a reassociatable opcode perform: 9640 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9641 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9642 SelectionDAG &DAG) const { 9643 EVT VT = N->getValueType(0); 9644 if (VT != MVT::i32 && VT != MVT::i64) 9645 return SDValue(); 9646 9647 unsigned Opc = N->getOpcode(); 9648 SDValue Op0 = N->getOperand(0); 9649 SDValue Op1 = N->getOperand(1); 9650 9651 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9652 return SDValue(); 9653 9654 if (Op0->isDivergent()) 9655 std::swap(Op0, Op1); 9656 9657 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9658 return SDValue(); 9659 9660 SDValue Op2 = Op1.getOperand(1); 9661 Op1 = Op1.getOperand(0); 9662 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9663 return SDValue(); 9664 9665 if (Op1->isDivergent()) 9666 std::swap(Op1, Op2); 9667 9668 // If either operand is constant this will conflict with 9669 // DAGCombiner::ReassociateOps(). 9670 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9671 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9672 return SDValue(); 9673 9674 SDLoc SL(N); 9675 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9676 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9677 } 9678 9679 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9680 EVT VT, 9681 SDValue N0, SDValue N1, SDValue N2, 9682 bool Signed) { 9683 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9684 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9685 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 9686 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 9687 } 9688 9689 SDValue SITargetLowering::performAddCombine(SDNode *N, 9690 DAGCombinerInfo &DCI) const { 9691 SelectionDAG &DAG = DCI.DAG; 9692 EVT VT = N->getValueType(0); 9693 SDLoc SL(N); 9694 SDValue LHS = N->getOperand(0); 9695 SDValue RHS = N->getOperand(1); 9696 9697 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 9698 && Subtarget->hasMad64_32() && 9699 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 9700 VT.getScalarSizeInBits() <= 64) { 9701 if (LHS.getOpcode() != ISD::MUL) 9702 std::swap(LHS, RHS); 9703 9704 SDValue MulLHS = LHS.getOperand(0); 9705 SDValue MulRHS = LHS.getOperand(1); 9706 SDValue AddRHS = RHS; 9707 9708 // TODO: Maybe restrict if SGPR inputs. 9709 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 9710 numBitsUnsigned(MulRHS, DAG) <= 32) { 9711 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 9712 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 9713 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 9714 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 9715 } 9716 9717 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 9718 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 9719 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 9720 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 9721 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 9722 } 9723 9724 return SDValue(); 9725 } 9726 9727 if (SDValue V = reassociateScalarOps(N, DAG)) { 9728 return V; 9729 } 9730 9731 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 9732 return SDValue(); 9733 9734 // add x, zext (setcc) => addcarry x, 0, setcc 9735 // add x, sext (setcc) => subcarry x, 0, setcc 9736 unsigned Opc = LHS.getOpcode(); 9737 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9738 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 9739 std::swap(RHS, LHS); 9740 9741 Opc = RHS.getOpcode(); 9742 switch (Opc) { 9743 default: break; 9744 case ISD::ZERO_EXTEND: 9745 case ISD::SIGN_EXTEND: 9746 case ISD::ANY_EXTEND: { 9747 auto Cond = RHS.getOperand(0); 9748 // If this won't be a real VOPC output, we would still need to insert an 9749 // extra instruction anyway. 9750 if (!isBoolSGPR(Cond)) 9751 break; 9752 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9753 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9754 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9755 return DAG.getNode(Opc, SL, VTList, Args); 9756 } 9757 case ISD::ADDCARRY: { 9758 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 9759 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9760 if (!C || C->getZExtValue() != 0) break; 9761 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 9762 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 9763 } 9764 } 9765 return SDValue(); 9766 } 9767 9768 SDValue SITargetLowering::performSubCombine(SDNode *N, 9769 DAGCombinerInfo &DCI) const { 9770 SelectionDAG &DAG = DCI.DAG; 9771 EVT VT = N->getValueType(0); 9772 9773 if (VT != MVT::i32) 9774 return SDValue(); 9775 9776 SDLoc SL(N); 9777 SDValue LHS = N->getOperand(0); 9778 SDValue RHS = N->getOperand(1); 9779 9780 // sub x, zext (setcc) => subcarry x, 0, setcc 9781 // sub x, sext (setcc) => addcarry x, 0, setcc 9782 unsigned Opc = RHS.getOpcode(); 9783 switch (Opc) { 9784 default: break; 9785 case ISD::ZERO_EXTEND: 9786 case ISD::SIGN_EXTEND: 9787 case ISD::ANY_EXTEND: { 9788 auto Cond = RHS.getOperand(0); 9789 // If this won't be a real VOPC output, we would still need to insert an 9790 // extra instruction anyway. 9791 if (!isBoolSGPR(Cond)) 9792 break; 9793 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9794 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9795 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 9796 return DAG.getNode(Opc, SL, VTList, Args); 9797 } 9798 } 9799 9800 if (LHS.getOpcode() == ISD::SUBCARRY) { 9801 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 9802 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9803 if (!C || !C->isNullValue()) 9804 return SDValue(); 9805 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 9806 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 9807 } 9808 return SDValue(); 9809 } 9810 9811 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 9812 DAGCombinerInfo &DCI) const { 9813 9814 if (N->getValueType(0) != MVT::i32) 9815 return SDValue(); 9816 9817 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9818 if (!C || C->getZExtValue() != 0) 9819 return SDValue(); 9820 9821 SelectionDAG &DAG = DCI.DAG; 9822 SDValue LHS = N->getOperand(0); 9823 9824 // addcarry (add x, y), 0, cc => addcarry x, y, cc 9825 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 9826 unsigned LHSOpc = LHS.getOpcode(); 9827 unsigned Opc = N->getOpcode(); 9828 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 9829 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 9830 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 9831 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 9832 } 9833 return SDValue(); 9834 } 9835 9836 SDValue SITargetLowering::performFAddCombine(SDNode *N, 9837 DAGCombinerInfo &DCI) const { 9838 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9839 return SDValue(); 9840 9841 SelectionDAG &DAG = DCI.DAG; 9842 EVT VT = N->getValueType(0); 9843 9844 SDLoc SL(N); 9845 SDValue LHS = N->getOperand(0); 9846 SDValue RHS = N->getOperand(1); 9847 9848 // These should really be instruction patterns, but writing patterns with 9849 // source modiifiers is a pain. 9850 9851 // fadd (fadd (a, a), b) -> mad 2.0, a, b 9852 if (LHS.getOpcode() == ISD::FADD) { 9853 SDValue A = LHS.getOperand(0); 9854 if (A == LHS.getOperand(1)) { 9855 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9856 if (FusedOp != 0) { 9857 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9858 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 9859 } 9860 } 9861 } 9862 9863 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 9864 if (RHS.getOpcode() == ISD::FADD) { 9865 SDValue A = RHS.getOperand(0); 9866 if (A == RHS.getOperand(1)) { 9867 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9868 if (FusedOp != 0) { 9869 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9870 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 9871 } 9872 } 9873 } 9874 9875 return SDValue(); 9876 } 9877 9878 SDValue SITargetLowering::performFSubCombine(SDNode *N, 9879 DAGCombinerInfo &DCI) const { 9880 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9881 return SDValue(); 9882 9883 SelectionDAG &DAG = DCI.DAG; 9884 SDLoc SL(N); 9885 EVT VT = N->getValueType(0); 9886 assert(!VT.isVector()); 9887 9888 // Try to get the fneg to fold into the source modifier. This undoes generic 9889 // DAG combines and folds them into the mad. 9890 // 9891 // Only do this if we are not trying to support denormals. v_mad_f32 does 9892 // not support denormals ever. 9893 SDValue LHS = N->getOperand(0); 9894 SDValue RHS = N->getOperand(1); 9895 if (LHS.getOpcode() == ISD::FADD) { 9896 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 9897 SDValue A = LHS.getOperand(0); 9898 if (A == LHS.getOperand(1)) { 9899 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9900 if (FusedOp != 0){ 9901 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9902 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 9903 9904 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 9905 } 9906 } 9907 } 9908 9909 if (RHS.getOpcode() == ISD::FADD) { 9910 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 9911 9912 SDValue A = RHS.getOperand(0); 9913 if (A == RHS.getOperand(1)) { 9914 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9915 if (FusedOp != 0){ 9916 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 9917 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 9918 } 9919 } 9920 } 9921 9922 return SDValue(); 9923 } 9924 9925 SDValue SITargetLowering::performFMACombine(SDNode *N, 9926 DAGCombinerInfo &DCI) const { 9927 SelectionDAG &DAG = DCI.DAG; 9928 EVT VT = N->getValueType(0); 9929 SDLoc SL(N); 9930 9931 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 9932 return SDValue(); 9933 9934 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 9935 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 9936 SDValue Op1 = N->getOperand(0); 9937 SDValue Op2 = N->getOperand(1); 9938 SDValue FMA = N->getOperand(2); 9939 9940 if (FMA.getOpcode() != ISD::FMA || 9941 Op1.getOpcode() != ISD::FP_EXTEND || 9942 Op2.getOpcode() != ISD::FP_EXTEND) 9943 return SDValue(); 9944 9945 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 9946 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 9947 // is sufficient to allow generaing fdot2. 9948 const TargetOptions &Options = DAG.getTarget().Options; 9949 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9950 (N->getFlags().hasAllowContract() && 9951 FMA->getFlags().hasAllowContract())) { 9952 Op1 = Op1.getOperand(0); 9953 Op2 = Op2.getOperand(0); 9954 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9955 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9956 return SDValue(); 9957 9958 SDValue Vec1 = Op1.getOperand(0); 9959 SDValue Idx1 = Op1.getOperand(1); 9960 SDValue Vec2 = Op2.getOperand(0); 9961 9962 SDValue FMAOp1 = FMA.getOperand(0); 9963 SDValue FMAOp2 = FMA.getOperand(1); 9964 SDValue FMAAcc = FMA.getOperand(2); 9965 9966 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 9967 FMAOp2.getOpcode() != ISD::FP_EXTEND) 9968 return SDValue(); 9969 9970 FMAOp1 = FMAOp1.getOperand(0); 9971 FMAOp2 = FMAOp2.getOperand(0); 9972 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9973 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9974 return SDValue(); 9975 9976 SDValue Vec3 = FMAOp1.getOperand(0); 9977 SDValue Vec4 = FMAOp2.getOperand(0); 9978 SDValue Idx2 = FMAOp1.getOperand(1); 9979 9980 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 9981 // Idx1 and Idx2 cannot be the same. 9982 Idx1 == Idx2) 9983 return SDValue(); 9984 9985 if (Vec1 == Vec2 || Vec3 == Vec4) 9986 return SDValue(); 9987 9988 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 9989 return SDValue(); 9990 9991 if ((Vec1 == Vec3 && Vec2 == Vec4) || 9992 (Vec1 == Vec4 && Vec2 == Vec3)) { 9993 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 9994 DAG.getTargetConstant(0, SL, MVT::i1)); 9995 } 9996 } 9997 return SDValue(); 9998 } 9999 10000 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10001 DAGCombinerInfo &DCI) const { 10002 SelectionDAG &DAG = DCI.DAG; 10003 SDLoc SL(N); 10004 10005 SDValue LHS = N->getOperand(0); 10006 SDValue RHS = N->getOperand(1); 10007 EVT VT = LHS.getValueType(); 10008 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10009 10010 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10011 if (!CRHS) { 10012 CRHS = dyn_cast<ConstantSDNode>(LHS); 10013 if (CRHS) { 10014 std::swap(LHS, RHS); 10015 CC = getSetCCSwappedOperands(CC); 10016 } 10017 } 10018 10019 if (CRHS) { 10020 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10021 isBoolSGPR(LHS.getOperand(0))) { 10022 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10023 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10024 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10025 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10026 if ((CRHS->isAllOnesValue() && 10027 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10028 (CRHS->isNullValue() && 10029 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10030 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10031 DAG.getConstant(-1, SL, MVT::i1)); 10032 if ((CRHS->isAllOnesValue() && 10033 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10034 (CRHS->isNullValue() && 10035 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10036 return LHS.getOperand(0); 10037 } 10038 10039 uint64_t CRHSVal = CRHS->getZExtValue(); 10040 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10041 LHS.getOpcode() == ISD::SELECT && 10042 isa<ConstantSDNode>(LHS.getOperand(1)) && 10043 isa<ConstantSDNode>(LHS.getOperand(2)) && 10044 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10045 isBoolSGPR(LHS.getOperand(0))) { 10046 // Given CT != FT: 10047 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10048 // setcc (select cc, CT, CF), CF, ne => cc 10049 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10050 // setcc (select cc, CT, CF), CT, eq => cc 10051 uint64_t CT = LHS.getConstantOperandVal(1); 10052 uint64_t CF = LHS.getConstantOperandVal(2); 10053 10054 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10055 (CT == CRHSVal && CC == ISD::SETNE)) 10056 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10057 DAG.getConstant(-1, SL, MVT::i1)); 10058 if ((CF == CRHSVal && CC == ISD::SETNE) || 10059 (CT == CRHSVal && CC == ISD::SETEQ)) 10060 return LHS.getOperand(0); 10061 } 10062 } 10063 10064 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10065 VT != MVT::f16)) 10066 return SDValue(); 10067 10068 // Match isinf/isfinite pattern 10069 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10070 // (fcmp one (fabs x), inf) -> (fp_class x, 10071 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10072 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10073 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10074 if (!CRHS) 10075 return SDValue(); 10076 10077 const APFloat &APF = CRHS->getValueAPF(); 10078 if (APF.isInfinity() && !APF.isNegative()) { 10079 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10080 SIInstrFlags::N_INFINITY; 10081 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10082 SIInstrFlags::P_ZERO | 10083 SIInstrFlags::N_NORMAL | 10084 SIInstrFlags::P_NORMAL | 10085 SIInstrFlags::N_SUBNORMAL | 10086 SIInstrFlags::P_SUBNORMAL; 10087 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10088 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10089 DAG.getConstant(Mask, SL, MVT::i32)); 10090 } 10091 } 10092 10093 return SDValue(); 10094 } 10095 10096 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10097 DAGCombinerInfo &DCI) const { 10098 SelectionDAG &DAG = DCI.DAG; 10099 SDLoc SL(N); 10100 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10101 10102 SDValue Src = N->getOperand(0); 10103 SDValue Shift = N->getOperand(0); 10104 10105 // TODO: Extend type shouldn't matter (assuming legal types). 10106 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10107 Shift = Shift.getOperand(0); 10108 10109 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10110 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10111 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10112 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10113 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10114 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10115 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10116 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10117 SDLoc(Shift.getOperand(0)), MVT::i32); 10118 10119 unsigned ShiftOffset = 8 * Offset; 10120 if (Shift.getOpcode() == ISD::SHL) 10121 ShiftOffset -= C->getZExtValue(); 10122 else 10123 ShiftOffset += C->getZExtValue(); 10124 10125 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10126 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10127 MVT::f32, Shift); 10128 } 10129 } 10130 } 10131 10132 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10133 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10134 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10135 // We simplified Src. If this node is not dead, visit it again so it is 10136 // folded properly. 10137 if (N->getOpcode() != ISD::DELETED_NODE) 10138 DCI.AddToWorklist(N); 10139 return SDValue(N, 0); 10140 } 10141 10142 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10143 if (SDValue DemandedSrc = 10144 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10145 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10146 10147 return SDValue(); 10148 } 10149 10150 SDValue SITargetLowering::performClampCombine(SDNode *N, 10151 DAGCombinerInfo &DCI) const { 10152 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10153 if (!CSrc) 10154 return SDValue(); 10155 10156 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10157 const APFloat &F = CSrc->getValueAPF(); 10158 APFloat Zero = APFloat::getZero(F.getSemantics()); 10159 if (F < Zero || 10160 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10161 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10162 } 10163 10164 APFloat One(F.getSemantics(), "1.0"); 10165 if (F > One) 10166 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10167 10168 return SDValue(CSrc, 0); 10169 } 10170 10171 10172 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10173 DAGCombinerInfo &DCI) const { 10174 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10175 return SDValue(); 10176 switch (N->getOpcode()) { 10177 default: 10178 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10179 case ISD::ADD: 10180 return performAddCombine(N, DCI); 10181 case ISD::SUB: 10182 return performSubCombine(N, DCI); 10183 case ISD::ADDCARRY: 10184 case ISD::SUBCARRY: 10185 return performAddCarrySubCarryCombine(N, DCI); 10186 case ISD::FADD: 10187 return performFAddCombine(N, DCI); 10188 case ISD::FSUB: 10189 return performFSubCombine(N, DCI); 10190 case ISD::SETCC: 10191 return performSetCCCombine(N, DCI); 10192 case ISD::FMAXNUM: 10193 case ISD::FMINNUM: 10194 case ISD::FMAXNUM_IEEE: 10195 case ISD::FMINNUM_IEEE: 10196 case ISD::SMAX: 10197 case ISD::SMIN: 10198 case ISD::UMAX: 10199 case ISD::UMIN: 10200 case AMDGPUISD::FMIN_LEGACY: 10201 case AMDGPUISD::FMAX_LEGACY: 10202 return performMinMaxCombine(N, DCI); 10203 case ISD::FMA: 10204 return performFMACombine(N, DCI); 10205 case ISD::LOAD: { 10206 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10207 return Widended; 10208 LLVM_FALLTHROUGH; 10209 } 10210 case ISD::STORE: 10211 case ISD::ATOMIC_LOAD: 10212 case ISD::ATOMIC_STORE: 10213 case ISD::ATOMIC_CMP_SWAP: 10214 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 10215 case ISD::ATOMIC_SWAP: 10216 case ISD::ATOMIC_LOAD_ADD: 10217 case ISD::ATOMIC_LOAD_SUB: 10218 case ISD::ATOMIC_LOAD_AND: 10219 case ISD::ATOMIC_LOAD_OR: 10220 case ISD::ATOMIC_LOAD_XOR: 10221 case ISD::ATOMIC_LOAD_NAND: 10222 case ISD::ATOMIC_LOAD_MIN: 10223 case ISD::ATOMIC_LOAD_MAX: 10224 case ISD::ATOMIC_LOAD_UMIN: 10225 case ISD::ATOMIC_LOAD_UMAX: 10226 case ISD::ATOMIC_LOAD_FADD: 10227 case AMDGPUISD::ATOMIC_INC: 10228 case AMDGPUISD::ATOMIC_DEC: 10229 case AMDGPUISD::ATOMIC_LOAD_FMIN: 10230 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 10231 if (DCI.isBeforeLegalize()) 10232 break; 10233 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 10234 case ISD::AND: 10235 return performAndCombine(N, DCI); 10236 case ISD::OR: 10237 return performOrCombine(N, DCI); 10238 case ISD::XOR: 10239 return performXorCombine(N, DCI); 10240 case ISD::ZERO_EXTEND: 10241 return performZeroExtendCombine(N, DCI); 10242 case ISD::SIGN_EXTEND_INREG: 10243 return performSignExtendInRegCombine(N , DCI); 10244 case AMDGPUISD::FP_CLASS: 10245 return performClassCombine(N, DCI); 10246 case ISD::FCANONICALIZE: 10247 return performFCanonicalizeCombine(N, DCI); 10248 case AMDGPUISD::RCP: 10249 return performRcpCombine(N, DCI); 10250 case AMDGPUISD::FRACT: 10251 case AMDGPUISD::RSQ: 10252 case AMDGPUISD::RCP_LEGACY: 10253 case AMDGPUISD::RCP_IFLAG: 10254 case AMDGPUISD::RSQ_CLAMP: 10255 case AMDGPUISD::LDEXP: { 10256 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10257 SDValue Src = N->getOperand(0); 10258 if (Src.isUndef()) 10259 return Src; 10260 break; 10261 } 10262 case ISD::SINT_TO_FP: 10263 case ISD::UINT_TO_FP: 10264 return performUCharToFloatCombine(N, DCI); 10265 case AMDGPUISD::CVT_F32_UBYTE0: 10266 case AMDGPUISD::CVT_F32_UBYTE1: 10267 case AMDGPUISD::CVT_F32_UBYTE2: 10268 case AMDGPUISD::CVT_F32_UBYTE3: 10269 return performCvtF32UByteNCombine(N, DCI); 10270 case AMDGPUISD::FMED3: 10271 return performFMed3Combine(N, DCI); 10272 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10273 return performCvtPkRTZCombine(N, DCI); 10274 case AMDGPUISD::CLAMP: 10275 return performClampCombine(N, DCI); 10276 case ISD::SCALAR_TO_VECTOR: { 10277 SelectionDAG &DAG = DCI.DAG; 10278 EVT VT = N->getValueType(0); 10279 10280 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10281 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10282 SDLoc SL(N); 10283 SDValue Src = N->getOperand(0); 10284 EVT EltVT = Src.getValueType(); 10285 if (EltVT == MVT::f16) 10286 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10287 10288 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10289 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10290 } 10291 10292 break; 10293 } 10294 case ISD::EXTRACT_VECTOR_ELT: 10295 return performExtractVectorEltCombine(N, DCI); 10296 case ISD::INSERT_VECTOR_ELT: 10297 return performInsertVectorEltCombine(N, DCI); 10298 } 10299 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10300 } 10301 10302 /// Helper function for adjustWritemask 10303 static unsigned SubIdx2Lane(unsigned Idx) { 10304 switch (Idx) { 10305 default: return 0; 10306 case AMDGPU::sub0: return 0; 10307 case AMDGPU::sub1: return 1; 10308 case AMDGPU::sub2: return 2; 10309 case AMDGPU::sub3: return 3; 10310 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10311 } 10312 } 10313 10314 /// Adjust the writemask of MIMG instructions 10315 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10316 SelectionDAG &DAG) const { 10317 unsigned Opcode = Node->getMachineOpcode(); 10318 10319 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10320 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10321 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10322 return Node; // not implemented for D16 10323 10324 SDNode *Users[5] = { nullptr }; 10325 unsigned Lane = 0; 10326 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10327 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10328 unsigned NewDmask = 0; 10329 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10330 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10331 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10332 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10333 unsigned TFCLane = 0; 10334 bool HasChain = Node->getNumValues() > 1; 10335 10336 if (OldDmask == 0) { 10337 // These are folded out, but on the chance it happens don't assert. 10338 return Node; 10339 } 10340 10341 unsigned OldBitsSet = countPopulation(OldDmask); 10342 // Work out which is the TFE/LWE lane if that is enabled. 10343 if (UsesTFC) { 10344 TFCLane = OldBitsSet; 10345 } 10346 10347 // Try to figure out the used register components 10348 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10349 I != E; ++I) { 10350 10351 // Don't look at users of the chain. 10352 if (I.getUse().getResNo() != 0) 10353 continue; 10354 10355 // Abort if we can't understand the usage 10356 if (!I->isMachineOpcode() || 10357 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10358 return Node; 10359 10360 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10361 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10362 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10363 // set, etc. 10364 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10365 10366 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10367 if (UsesTFC && Lane == TFCLane) { 10368 Users[Lane] = *I; 10369 } else { 10370 // Set which texture component corresponds to the lane. 10371 unsigned Comp; 10372 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10373 Comp = countTrailingZeros(Dmask); 10374 Dmask &= ~(1 << Comp); 10375 } 10376 10377 // Abort if we have more than one user per component. 10378 if (Users[Lane]) 10379 return Node; 10380 10381 Users[Lane] = *I; 10382 NewDmask |= 1 << Comp; 10383 } 10384 } 10385 10386 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10387 bool NoChannels = !NewDmask; 10388 if (NoChannels) { 10389 if (!UsesTFC) { 10390 // No uses of the result and not using TFC. Then do nothing. 10391 return Node; 10392 } 10393 // If the original dmask has one channel - then nothing to do 10394 if (OldBitsSet == 1) 10395 return Node; 10396 // Use an arbitrary dmask - required for the instruction to work 10397 NewDmask = 1; 10398 } 10399 // Abort if there's no change 10400 if (NewDmask == OldDmask) 10401 return Node; 10402 10403 unsigned BitsSet = countPopulation(NewDmask); 10404 10405 // Check for TFE or LWE - increase the number of channels by one to account 10406 // for the extra return value 10407 // This will need adjustment for D16 if this is also included in 10408 // adjustWriteMask (this function) but at present D16 are excluded. 10409 unsigned NewChannels = BitsSet + UsesTFC; 10410 10411 int NewOpcode = 10412 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10413 assert(NewOpcode != -1 && 10414 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10415 "failed to find equivalent MIMG op"); 10416 10417 // Adjust the writemask in the node 10418 SmallVector<SDValue, 12> Ops; 10419 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10420 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10421 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10422 10423 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10424 10425 MVT ResultVT = NewChannels == 1 ? 10426 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10427 NewChannels == 5 ? 8 : NewChannels); 10428 SDVTList NewVTList = HasChain ? 10429 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10430 10431 10432 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10433 NewVTList, Ops); 10434 10435 if (HasChain) { 10436 // Update chain. 10437 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10438 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10439 } 10440 10441 if (NewChannels == 1) { 10442 assert(Node->hasNUsesOfValue(1, 0)); 10443 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10444 SDLoc(Node), Users[Lane]->getValueType(0), 10445 SDValue(NewNode, 0)); 10446 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10447 return nullptr; 10448 } 10449 10450 // Update the users of the node with the new indices 10451 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10452 SDNode *User = Users[i]; 10453 if (!User) { 10454 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10455 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10456 if (i || !NoChannels) 10457 continue; 10458 } else { 10459 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10460 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10461 } 10462 10463 switch (Idx) { 10464 default: break; 10465 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10466 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10467 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10468 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10469 } 10470 } 10471 10472 DAG.RemoveDeadNode(Node); 10473 return nullptr; 10474 } 10475 10476 static bool isFrameIndexOp(SDValue Op) { 10477 if (Op.getOpcode() == ISD::AssertZext) 10478 Op = Op.getOperand(0); 10479 10480 return isa<FrameIndexSDNode>(Op); 10481 } 10482 10483 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10484 /// with frame index operands. 10485 /// LLVM assumes that inputs are to these instructions are registers. 10486 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10487 SelectionDAG &DAG) const { 10488 if (Node->getOpcode() == ISD::CopyToReg) { 10489 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10490 SDValue SrcVal = Node->getOperand(2); 10491 10492 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10493 // to try understanding copies to physical registers. 10494 if (SrcVal.getValueType() == MVT::i1 && 10495 Register::isPhysicalRegister(DestReg->getReg())) { 10496 SDLoc SL(Node); 10497 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10498 SDValue VReg = DAG.getRegister( 10499 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10500 10501 SDNode *Glued = Node->getGluedNode(); 10502 SDValue ToVReg 10503 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10504 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10505 SDValue ToResultReg 10506 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10507 VReg, ToVReg.getValue(1)); 10508 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10509 DAG.RemoveDeadNode(Node); 10510 return ToResultReg.getNode(); 10511 } 10512 } 10513 10514 SmallVector<SDValue, 8> Ops; 10515 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10516 if (!isFrameIndexOp(Node->getOperand(i))) { 10517 Ops.push_back(Node->getOperand(i)); 10518 continue; 10519 } 10520 10521 SDLoc DL(Node); 10522 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10523 Node->getOperand(i).getValueType(), 10524 Node->getOperand(i)), 0)); 10525 } 10526 10527 return DAG.UpdateNodeOperands(Node, Ops); 10528 } 10529 10530 /// Fold the instructions after selecting them. 10531 /// Returns null if users were already updated. 10532 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10533 SelectionDAG &DAG) const { 10534 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10535 unsigned Opcode = Node->getMachineOpcode(); 10536 10537 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10538 !TII->isGather4(Opcode)) { 10539 return adjustWritemask(Node, DAG); 10540 } 10541 10542 if (Opcode == AMDGPU::INSERT_SUBREG || 10543 Opcode == AMDGPU::REG_SEQUENCE) { 10544 legalizeTargetIndependentNode(Node, DAG); 10545 return Node; 10546 } 10547 10548 switch (Opcode) { 10549 case AMDGPU::V_DIV_SCALE_F32: 10550 case AMDGPU::V_DIV_SCALE_F64: { 10551 // Satisfy the operand register constraint when one of the inputs is 10552 // undefined. Ordinarily each undef value will have its own implicit_def of 10553 // a vreg, so force these to use a single register. 10554 SDValue Src0 = Node->getOperand(0); 10555 SDValue Src1 = Node->getOperand(1); 10556 SDValue Src2 = Node->getOperand(2); 10557 10558 if ((Src0.isMachineOpcode() && 10559 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10560 (Src0 == Src1 || Src0 == Src2)) 10561 break; 10562 10563 MVT VT = Src0.getValueType().getSimpleVT(); 10564 const TargetRegisterClass *RC = 10565 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10566 10567 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10568 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10569 10570 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10571 UndefReg, Src0, SDValue()); 10572 10573 // src0 must be the same register as src1 or src2, even if the value is 10574 // undefined, so make sure we don't violate this constraint. 10575 if (Src0.isMachineOpcode() && 10576 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10577 if (Src1.isMachineOpcode() && 10578 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10579 Src0 = Src1; 10580 else if (Src2.isMachineOpcode() && 10581 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10582 Src0 = Src2; 10583 else { 10584 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10585 Src0 = UndefReg; 10586 Src1 = UndefReg; 10587 } 10588 } else 10589 break; 10590 10591 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10592 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10593 Ops.push_back(Node->getOperand(I)); 10594 10595 Ops.push_back(ImpDef.getValue(1)); 10596 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10597 } 10598 default: 10599 break; 10600 } 10601 10602 return Node; 10603 } 10604 10605 /// Assign the register class depending on the number of 10606 /// bits set in the writemask 10607 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10608 SDNode *Node) const { 10609 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10610 10611 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10612 10613 if (TII->isVOP3(MI.getOpcode())) { 10614 // Make sure constant bus requirements are respected. 10615 TII->legalizeOperandsVOP3(MRI, MI); 10616 10617 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10618 // This saves a chain-copy of registers and better ballance register 10619 // use between vgpr and agpr as agpr tuples tend to be big. 10620 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10621 unsigned Opc = MI.getOpcode(); 10622 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10623 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10624 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10625 if (I == -1) 10626 break; 10627 MachineOperand &Op = MI.getOperand(I); 10628 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10629 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10630 !Register::isVirtualRegister(Op.getReg()) || 10631 !TRI->isAGPR(MRI, Op.getReg())) 10632 continue; 10633 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10634 if (!Src || !Src->isCopy() || 10635 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10636 continue; 10637 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10638 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10639 // All uses of agpr64 and agpr32 can also accept vgpr except for 10640 // v_accvgpr_read, but we do not produce agpr reads during selection, 10641 // so no use checks are needed. 10642 MRI.setRegClass(Op.getReg(), NewRC); 10643 } 10644 } 10645 10646 return; 10647 } 10648 10649 // Replace unused atomics with the no return version. 10650 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10651 if (NoRetAtomicOp != -1) { 10652 if (!Node->hasAnyUseOfValue(0)) { 10653 MI.setDesc(TII->get(NoRetAtomicOp)); 10654 MI.RemoveOperand(0); 10655 return; 10656 } 10657 10658 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10659 // instruction, because the return type of these instructions is a vec2 of 10660 // the memory type, so it can be tied to the input operand. 10661 // This means these instructions always have a use, so we need to add a 10662 // special case to check if the atomic has only one extract_subreg use, 10663 // which itself has no uses. 10664 if ((Node->hasNUsesOfValue(1, 0) && 10665 Node->use_begin()->isMachineOpcode() && 10666 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10667 !Node->use_begin()->hasAnyUseOfValue(0))) { 10668 Register Def = MI.getOperand(0).getReg(); 10669 10670 // Change this into a noret atomic. 10671 MI.setDesc(TII->get(NoRetAtomicOp)); 10672 MI.RemoveOperand(0); 10673 10674 // If we only remove the def operand from the atomic instruction, the 10675 // extract_subreg will be left with a use of a vreg without a def. 10676 // So we need to insert an implicit_def to avoid machine verifier 10677 // errors. 10678 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10679 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10680 } 10681 return; 10682 } 10683 } 10684 10685 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 10686 uint64_t Val) { 10687 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 10688 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 10689 } 10690 10691 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 10692 const SDLoc &DL, 10693 SDValue Ptr) const { 10694 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10695 10696 // Build the half of the subregister with the constants before building the 10697 // full 128-bit register. If we are building multiple resource descriptors, 10698 // this will allow CSEing of the 2-component register. 10699 const SDValue Ops0[] = { 10700 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 10701 buildSMovImm32(DAG, DL, 0), 10702 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10703 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 10704 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 10705 }; 10706 10707 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 10708 MVT::v2i32, Ops0), 0); 10709 10710 // Combine the constants and the pointer. 10711 const SDValue Ops1[] = { 10712 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10713 Ptr, 10714 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 10715 SubRegHi, 10716 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 10717 }; 10718 10719 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 10720 } 10721 10722 /// Return a resource descriptor with the 'Add TID' bit enabled 10723 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 10724 /// of the resource descriptor) to create an offset, which is added to 10725 /// the resource pointer. 10726 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 10727 SDValue Ptr, uint32_t RsrcDword1, 10728 uint64_t RsrcDword2And3) const { 10729 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 10730 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 10731 if (RsrcDword1) { 10732 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 10733 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 10734 0); 10735 } 10736 10737 SDValue DataLo = buildSMovImm32(DAG, DL, 10738 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 10739 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 10740 10741 const SDValue Ops[] = { 10742 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10743 PtrLo, 10744 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10745 PtrHi, 10746 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 10747 DataLo, 10748 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 10749 DataHi, 10750 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 10751 }; 10752 10753 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 10754 } 10755 10756 //===----------------------------------------------------------------------===// 10757 // SI Inline Assembly Support 10758 //===----------------------------------------------------------------------===// 10759 10760 std::pair<unsigned, const TargetRegisterClass *> 10761 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10762 StringRef Constraint, 10763 MVT VT) const { 10764 const TargetRegisterClass *RC = nullptr; 10765 if (Constraint.size() == 1) { 10766 const unsigned BitWidth = VT.getSizeInBits(); 10767 switch (Constraint[0]) { 10768 default: 10769 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10770 case 's': 10771 case 'r': 10772 switch (BitWidth) { 10773 case 16: 10774 RC = &AMDGPU::SReg_32RegClass; 10775 break; 10776 case 64: 10777 RC = &AMDGPU::SGPR_64RegClass; 10778 break; 10779 default: 10780 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 10781 if (!RC) 10782 return std::make_pair(0U, nullptr); 10783 break; 10784 } 10785 break; 10786 case 'v': 10787 switch (BitWidth) { 10788 case 16: 10789 RC = &AMDGPU::VGPR_32RegClass; 10790 break; 10791 default: 10792 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 10793 if (!RC) 10794 return std::make_pair(0U, nullptr); 10795 break; 10796 } 10797 break; 10798 case 'a': 10799 if (!Subtarget->hasMAIInsts()) 10800 break; 10801 switch (BitWidth) { 10802 case 16: 10803 RC = &AMDGPU::AGPR_32RegClass; 10804 break; 10805 default: 10806 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 10807 if (!RC) 10808 return std::make_pair(0U, nullptr); 10809 break; 10810 } 10811 break; 10812 } 10813 // We actually support i128, i16 and f16 as inline parameters 10814 // even if they are not reported as legal 10815 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 10816 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 10817 return std::make_pair(0U, RC); 10818 } 10819 10820 if (Constraint.size() > 1) { 10821 if (Constraint[1] == 'v') { 10822 RC = &AMDGPU::VGPR_32RegClass; 10823 } else if (Constraint[1] == 's') { 10824 RC = &AMDGPU::SGPR_32RegClass; 10825 } else if (Constraint[1] == 'a') { 10826 RC = &AMDGPU::AGPR_32RegClass; 10827 } 10828 10829 if (RC) { 10830 uint32_t Idx; 10831 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 10832 if (!Failed && Idx < RC->getNumRegs()) 10833 return std::make_pair(RC->getRegister(Idx), RC); 10834 } 10835 } 10836 10837 // FIXME: Returns VS_32 for physical SGPR constraints 10838 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10839 } 10840 10841 SITargetLowering::ConstraintType 10842 SITargetLowering::getConstraintType(StringRef Constraint) const { 10843 if (Constraint.size() == 1) { 10844 switch (Constraint[0]) { 10845 default: break; 10846 case 's': 10847 case 'v': 10848 case 'a': 10849 return C_RegisterClass; 10850 } 10851 } 10852 return TargetLowering::getConstraintType(Constraint); 10853 } 10854 10855 // Figure out which registers should be reserved for stack access. Only after 10856 // the function is legalized do we know all of the non-spill stack objects or if 10857 // calls are present. 10858 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 10859 MachineRegisterInfo &MRI = MF.getRegInfo(); 10860 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10861 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 10862 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10863 10864 if (Info->isEntryFunction()) { 10865 // Callable functions have fixed registers used for stack access. 10866 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 10867 } 10868 10869 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 10870 Info->getStackPtrOffsetReg())); 10871 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 10872 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 10873 10874 // We need to worry about replacing the default register with itself in case 10875 // of MIR testcases missing the MFI. 10876 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 10877 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 10878 10879 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 10880 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 10881 10882 Info->limitOccupancy(MF); 10883 10884 if (ST.isWave32() && !MF.empty()) { 10885 // Add VCC_HI def because many instructions marked as imp-use VCC where 10886 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 10887 // having a use of undef. 10888 10889 const SIInstrInfo *TII = ST.getInstrInfo(); 10890 DebugLoc DL; 10891 10892 MachineBasicBlock &MBB = MF.front(); 10893 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 10894 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 10895 10896 for (auto &MBB : MF) { 10897 for (auto &MI : MBB) { 10898 TII->fixImplicitOperands(MI); 10899 } 10900 } 10901 } 10902 10903 TargetLoweringBase::finalizeLowering(MF); 10904 10905 // Allocate a VGPR for future SGPR Spill if 10906 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 10907 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 10908 if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill && 10909 !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects()) 10910 Info->reserveVGPRforSGPRSpills(MF); 10911 } 10912 10913 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 10914 KnownBits &Known, 10915 const APInt &DemandedElts, 10916 const SelectionDAG &DAG, 10917 unsigned Depth) const { 10918 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 10919 DAG, Depth); 10920 10921 // Set the high bits to zero based on the maximum allowed scratch size per 10922 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 10923 // calculation won't overflow, so assume the sign bit is never set. 10924 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 10925 } 10926 10927 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 10928 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 10929 const Align CacheLineAlign = Align(64); 10930 10931 // Pre-GFX10 target did not benefit from loop alignment 10932 if (!ML || DisableLoopAlignment || 10933 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 10934 getSubtarget()->hasInstFwdPrefetchBug()) 10935 return PrefAlign; 10936 10937 // On GFX10 I$ is 4 x 64 bytes cache lines. 10938 // By default prefetcher keeps one cache line behind and reads two ahead. 10939 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 10940 // behind and one ahead. 10941 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 10942 // If loop fits 64 bytes it always spans no more than two cache lines and 10943 // does not need an alignment. 10944 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 10945 // Else if loop is less or equal 192 bytes we need two lines behind. 10946 10947 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10948 const MachineBasicBlock *Header = ML->getHeader(); 10949 if (Header->getAlignment() != PrefAlign) 10950 return Header->getAlignment(); // Already processed. 10951 10952 unsigned LoopSize = 0; 10953 for (const MachineBasicBlock *MBB : ML->blocks()) { 10954 // If inner loop block is aligned assume in average half of the alignment 10955 // size to be added as nops. 10956 if (MBB != Header) 10957 LoopSize += MBB->getAlignment().value() / 2; 10958 10959 for (const MachineInstr &MI : *MBB) { 10960 LoopSize += TII->getInstSizeInBytes(MI); 10961 if (LoopSize > 192) 10962 return PrefAlign; 10963 } 10964 } 10965 10966 if (LoopSize <= 64) 10967 return PrefAlign; 10968 10969 if (LoopSize <= 128) 10970 return CacheLineAlign; 10971 10972 // If any of parent loops is surrounded by prefetch instructions do not 10973 // insert new for inner loop, which would reset parent's settings. 10974 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 10975 if (MachineBasicBlock *Exit = P->getExitBlock()) { 10976 auto I = Exit->getFirstNonDebugInstr(); 10977 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 10978 return CacheLineAlign; 10979 } 10980 } 10981 10982 MachineBasicBlock *Pre = ML->getLoopPreheader(); 10983 MachineBasicBlock *Exit = ML->getExitBlock(); 10984 10985 if (Pre && Exit) { 10986 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 10987 TII->get(AMDGPU::S_INST_PREFETCH)) 10988 .addImm(1); // prefetch 2 lines behind PC 10989 10990 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 10991 TII->get(AMDGPU::S_INST_PREFETCH)) 10992 .addImm(2); // prefetch 1 line behind PC 10993 } 10994 10995 return CacheLineAlign; 10996 } 10997 10998 LLVM_ATTRIBUTE_UNUSED 10999 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11000 assert(N->getOpcode() == ISD::CopyFromReg); 11001 do { 11002 // Follow the chain until we find an INLINEASM node. 11003 N = N->getOperand(0).getNode(); 11004 if (N->getOpcode() == ISD::INLINEASM || 11005 N->getOpcode() == ISD::INLINEASM_BR) 11006 return true; 11007 } while (N->getOpcode() == ISD::CopyFromReg); 11008 return false; 11009 } 11010 11011 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 11012 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 11013 { 11014 switch (N->getOpcode()) { 11015 case ISD::CopyFromReg: 11016 { 11017 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11018 const MachineFunction * MF = FLI->MF; 11019 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 11020 const MachineRegisterInfo &MRI = MF->getRegInfo(); 11021 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo(); 11022 Register Reg = R->getReg(); 11023 if (Reg.isPhysical()) 11024 return !TRI.isSGPRReg(MRI, Reg); 11025 11026 if (MRI.isLiveIn(Reg)) { 11027 // workitem.id.x workitem.id.y workitem.id.z 11028 // Any VGPR formal argument is also considered divergent 11029 if (!TRI.isSGPRReg(MRI, Reg)) 11030 return true; 11031 // Formal arguments of non-entry functions 11032 // are conservatively considered divergent 11033 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv())) 11034 return true; 11035 return false; 11036 } 11037 const Value *V = FLI->getValueFromVirtualReg(Reg); 11038 if (V) 11039 return KDA->isDivergent(V); 11040 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11041 return !TRI.isSGPRReg(MRI, Reg); 11042 } 11043 break; 11044 case ISD::LOAD: { 11045 const LoadSDNode *L = cast<LoadSDNode>(N); 11046 unsigned AS = L->getAddressSpace(); 11047 // A flat load may access private memory. 11048 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11049 } break; 11050 case ISD::CALLSEQ_END: 11051 return true; 11052 break; 11053 case ISD::INTRINSIC_WO_CHAIN: 11054 { 11055 11056 } 11057 return AMDGPU::isIntrinsicSourceOfDivergence( 11058 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11059 case ISD::INTRINSIC_W_CHAIN: 11060 return AMDGPU::isIntrinsicSourceOfDivergence( 11061 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11062 } 11063 return false; 11064 } 11065 11066 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11067 EVT VT) const { 11068 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11069 case MVT::f32: 11070 return hasFP32Denormals(DAG.getMachineFunction()); 11071 case MVT::f64: 11072 case MVT::f16: 11073 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11074 default: 11075 return false; 11076 } 11077 } 11078 11079 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11080 const SelectionDAG &DAG, 11081 bool SNaN, 11082 unsigned Depth) const { 11083 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11084 const MachineFunction &MF = DAG.getMachineFunction(); 11085 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11086 11087 if (Info->getMode().DX10Clamp) 11088 return true; // Clamped to 0. 11089 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11090 } 11091 11092 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11093 SNaN, Depth); 11094 } 11095 11096 TargetLowering::AtomicExpansionKind 11097 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11098 switch (RMW->getOperation()) { 11099 case AtomicRMWInst::FAdd: { 11100 Type *Ty = RMW->getType(); 11101 11102 // We don't have a way to support 16-bit atomics now, so just leave them 11103 // as-is. 11104 if (Ty->isHalfTy()) 11105 return AtomicExpansionKind::None; 11106 11107 if (!Ty->isFloatTy()) 11108 return AtomicExpansionKind::CmpXChg; 11109 11110 // TODO: Do have these for flat. Older targets also had them for buffers. 11111 unsigned AS = RMW->getPointerAddressSpace(); 11112 11113 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11114 return RMW->use_empty() ? AtomicExpansionKind::None : 11115 AtomicExpansionKind::CmpXChg; 11116 } 11117 11118 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11119 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11120 } 11121 default: 11122 break; 11123 } 11124 11125 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11126 } 11127 11128 const TargetRegisterClass * 11129 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11130 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11131 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11132 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11133 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11134 : &AMDGPU::SReg_32RegClass; 11135 if (!TRI->isSGPRClass(RC) && !isDivergent) 11136 return TRI->getEquivalentSGPRClass(RC); 11137 else if (TRI->isSGPRClass(RC) && isDivergent) 11138 return TRI->getEquivalentVGPRClass(RC); 11139 11140 return RC; 11141 } 11142 11143 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11144 // uniform values (as produced by the mask results of control flow intrinsics) 11145 // used outside of divergent blocks. The phi users need to also be treated as 11146 // always uniform. 11147 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11148 unsigned WaveSize) { 11149 // FIXME: We asssume we never cast the mask results of a control flow 11150 // intrinsic. 11151 // Early exit if the type won't be consistent as a compile time hack. 11152 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11153 if (!IT || IT->getBitWidth() != WaveSize) 11154 return false; 11155 11156 if (!isa<Instruction>(V)) 11157 return false; 11158 if (!Visited.insert(V).second) 11159 return false; 11160 bool Result = false; 11161 for (auto U : V->users()) { 11162 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11163 if (V == U->getOperand(1)) { 11164 switch (Intrinsic->getIntrinsicID()) { 11165 default: 11166 Result = false; 11167 break; 11168 case Intrinsic::amdgcn_if_break: 11169 case Intrinsic::amdgcn_if: 11170 case Intrinsic::amdgcn_else: 11171 Result = true; 11172 break; 11173 } 11174 } 11175 if (V == U->getOperand(0)) { 11176 switch (Intrinsic->getIntrinsicID()) { 11177 default: 11178 Result = false; 11179 break; 11180 case Intrinsic::amdgcn_end_cf: 11181 case Intrinsic::amdgcn_loop: 11182 Result = true; 11183 break; 11184 } 11185 } 11186 } else { 11187 Result = hasCFUser(U, Visited, WaveSize); 11188 } 11189 if (Result) 11190 break; 11191 } 11192 return Result; 11193 } 11194 11195 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11196 const Value *V) const { 11197 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11198 if (CI->isInlineAsm()) { 11199 // FIXME: This cannot give a correct answer. This should only trigger in 11200 // the case where inline asm returns mixed SGPR and VGPR results, used 11201 // outside the defining block. We don't have a specific result to 11202 // consider, so this assumes if any value is SGPR, the overall register 11203 // also needs to be SGPR. 11204 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11205 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11206 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11207 for (auto &TC : TargetConstraints) { 11208 if (TC.Type == InlineAsm::isOutput) { 11209 ComputeConstraintToUse(TC, SDValue()); 11210 unsigned AssignedReg; 11211 const TargetRegisterClass *RC; 11212 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11213 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11214 if (RC) { 11215 MachineRegisterInfo &MRI = MF.getRegInfo(); 11216 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11217 return true; 11218 else if (SIRI->isSGPRClass(RC)) 11219 return true; 11220 } 11221 } 11222 } 11223 } 11224 } 11225 SmallPtrSet<const Value *, 16> Visited; 11226 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11227 } 11228