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 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 161 addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass); 162 163 if (Subtarget->has16BitInsts()) { 164 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 165 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 166 167 // Unless there are also VOP3P operations, not operations are really legal. 168 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 169 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 170 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 171 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 172 } 173 174 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 175 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 176 177 computeRegisterProperties(Subtarget->getRegisterInfo()); 178 179 // The boolean content concept here is too inflexible. Compares only ever 180 // really produce a 1-bit result. Any copy/extend from these will turn into a 181 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 182 // it's what most targets use. 183 setBooleanContents(ZeroOrOneBooleanContent); 184 setBooleanVectorContents(ZeroOrOneBooleanContent); 185 186 // We need to custom lower vector stores from local memory 187 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 188 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 189 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 190 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 191 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 192 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 193 setOperationAction(ISD::LOAD, MVT::i1, Custom); 194 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 195 196 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 197 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 198 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 199 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 200 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 201 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 202 setOperationAction(ISD::STORE, MVT::i1, Custom); 203 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 204 205 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 206 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 207 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 208 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 209 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 210 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 211 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 212 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 213 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 214 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 215 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 216 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 217 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 218 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 219 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 220 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 221 222 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 223 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 224 225 setOperationAction(ISD::SELECT, MVT::i1, Promote); 226 setOperationAction(ISD::SELECT, MVT::i64, Custom); 227 setOperationAction(ISD::SELECT, MVT::f64, Promote); 228 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 229 230 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 231 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 232 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 233 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 234 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 235 236 setOperationAction(ISD::SETCC, MVT::i1, Promote); 237 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 238 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 239 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 240 241 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 242 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 243 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 244 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 245 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 246 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 247 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 248 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 249 250 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 251 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 252 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 253 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 254 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 255 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 256 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 257 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 258 259 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 260 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 261 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 262 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 263 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 264 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 265 266 setOperationAction(ISD::UADDO, MVT::i32, Legal); 267 setOperationAction(ISD::USUBO, MVT::i32, Legal); 268 269 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 270 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 271 272 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 273 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 274 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 275 276 #if 0 277 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 278 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 279 #endif 280 281 // We only support LOAD/STORE and vector manipulation ops for vectors 282 // with > 4 elements. 283 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 284 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 285 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 286 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 287 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 288 switch (Op) { 289 case ISD::LOAD: 290 case ISD::STORE: 291 case ISD::BUILD_VECTOR: 292 case ISD::BITCAST: 293 case ISD::EXTRACT_VECTOR_ELT: 294 case ISD::INSERT_VECTOR_ELT: 295 case ISD::INSERT_SUBVECTOR: 296 case ISD::EXTRACT_SUBVECTOR: 297 case ISD::SCALAR_TO_VECTOR: 298 break; 299 case ISD::CONCAT_VECTORS: 300 setOperationAction(Op, VT, Custom); 301 break; 302 default: 303 setOperationAction(Op, VT, Expand); 304 break; 305 } 306 } 307 } 308 309 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 310 311 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 312 // is expanded to avoid having two separate loops in case the index is a VGPR. 313 314 // Most operations are naturally 32-bit vector operations. We only support 315 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 316 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 317 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 318 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 319 320 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 321 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 322 323 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 324 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 325 326 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 327 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 328 } 329 330 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 331 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 332 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 333 334 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 335 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 336 337 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 338 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 339 340 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 341 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 342 } 343 344 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 345 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 346 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 347 348 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 349 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 350 351 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 352 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 353 354 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 355 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 356 } 357 358 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 359 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 360 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 361 362 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 363 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 364 365 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 366 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 367 368 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 369 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 370 } 371 372 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 373 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 374 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 375 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 376 377 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 378 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 379 380 // Avoid stack access for these. 381 // TODO: Generalize to more vector types. 382 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 383 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 384 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 385 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 386 387 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 388 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 389 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 390 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 391 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 392 393 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 394 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 395 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 396 397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 398 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 399 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 400 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 401 402 // Deal with vec3 vector operations when widened to vec4. 403 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 404 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 405 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 406 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 407 408 // Deal with vec5 vector operations when widened to vec8. 409 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 410 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 411 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 413 414 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 415 // and output demarshalling 416 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 417 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 418 419 // We can't return success/failure, only the old value, 420 // let LLVM add the comparison 421 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 422 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 423 424 if (Subtarget->hasFlatAddressSpace()) { 425 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 426 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 427 } 428 429 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 430 431 // FIXME: This should be narrowed to i32, but that only happens if i64 is 432 // illegal. 433 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 434 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 435 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 436 437 // On SI this is s_memtime and s_memrealtime on VI. 438 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 439 setOperationAction(ISD::TRAP, MVT::Other, Custom); 440 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 441 442 if (Subtarget->has16BitInsts()) { 443 setOperationAction(ISD::FPOW, MVT::f16, Promote); 444 setOperationAction(ISD::FLOG, MVT::f16, Custom); 445 setOperationAction(ISD::FEXP, MVT::f16, Custom); 446 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 447 } 448 449 // v_mad_f32 does not support denormals. We report it as unconditionally 450 // legal, and the context where it is formed will disallow it when fp32 451 // denormals are enabled. 452 setOperationAction(ISD::FMAD, MVT::f32, Legal); 453 454 if (!Subtarget->hasBFI()) { 455 // fcopysign can be done in a single instruction with BFI. 456 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 457 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 458 } 459 460 if (!Subtarget->hasBCNT(32)) 461 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 462 463 if (!Subtarget->hasBCNT(64)) 464 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 465 466 if (Subtarget->hasFFBH()) 467 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 468 469 if (Subtarget->hasFFBL()) 470 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 471 472 // We only really have 32-bit BFE instructions (and 16-bit on VI). 473 // 474 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 475 // effort to match them now. We want this to be false for i64 cases when the 476 // extraction isn't restricted to the upper or lower half. Ideally we would 477 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 478 // span the midpoint are probably relatively rare, so don't worry about them 479 // for now. 480 if (Subtarget->hasBFE()) 481 setHasExtractBitsInsn(true); 482 483 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 484 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 485 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 486 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 487 488 489 // These are really only legal for ieee_mode functions. We should be avoiding 490 // them for functions that don't have ieee_mode enabled, so just say they are 491 // legal. 492 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 493 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 494 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 495 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 496 497 498 if (Subtarget->haveRoundOpsF64()) { 499 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 500 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 501 setOperationAction(ISD::FRINT, MVT::f64, Legal); 502 } else { 503 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 504 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 505 setOperationAction(ISD::FRINT, MVT::f64, Custom); 506 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 507 } 508 509 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 510 511 setOperationAction(ISD::FSIN, MVT::f32, Custom); 512 setOperationAction(ISD::FCOS, MVT::f32, Custom); 513 setOperationAction(ISD::FDIV, MVT::f32, Custom); 514 setOperationAction(ISD::FDIV, MVT::f64, Custom); 515 516 if (Subtarget->has16BitInsts()) { 517 setOperationAction(ISD::Constant, MVT::i16, Legal); 518 519 setOperationAction(ISD::SMIN, MVT::i16, Legal); 520 setOperationAction(ISD::SMAX, MVT::i16, Legal); 521 522 setOperationAction(ISD::UMIN, MVT::i16, Legal); 523 setOperationAction(ISD::UMAX, MVT::i16, Legal); 524 525 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 526 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 527 528 setOperationAction(ISD::ROTR, MVT::i16, Promote); 529 setOperationAction(ISD::ROTL, MVT::i16, Promote); 530 531 setOperationAction(ISD::SDIV, MVT::i16, Promote); 532 setOperationAction(ISD::UDIV, MVT::i16, Promote); 533 setOperationAction(ISD::SREM, MVT::i16, Promote); 534 setOperationAction(ISD::UREM, MVT::i16, Promote); 535 536 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 537 538 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 539 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 540 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 541 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 542 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 543 544 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 545 546 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 547 548 setOperationAction(ISD::LOAD, MVT::i16, Custom); 549 550 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 551 552 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 553 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 554 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 555 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 556 557 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 558 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 559 560 // F16 - Constant Actions. 561 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 562 563 // F16 - Load/Store Actions. 564 setOperationAction(ISD::LOAD, MVT::f16, Promote); 565 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 566 setOperationAction(ISD::STORE, MVT::f16, Promote); 567 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 568 569 // F16 - VOP1 Actions. 570 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 571 setOperationAction(ISD::FCOS, MVT::f16, Custom); 572 setOperationAction(ISD::FSIN, MVT::f16, Custom); 573 574 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 575 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 576 577 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 578 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 579 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 580 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 581 setOperationAction(ISD::FROUND, MVT::f16, Custom); 582 583 // F16 - VOP2 Actions. 584 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 585 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 586 587 setOperationAction(ISD::FDIV, MVT::f16, Custom); 588 589 // F16 - VOP3 Actions. 590 setOperationAction(ISD::FMA, MVT::f16, Legal); 591 if (STI.hasMadF16()) 592 setOperationAction(ISD::FMAD, MVT::f16, Legal); 593 594 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 595 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 596 switch (Op) { 597 case ISD::LOAD: 598 case ISD::STORE: 599 case ISD::BUILD_VECTOR: 600 case ISD::BITCAST: 601 case ISD::EXTRACT_VECTOR_ELT: 602 case ISD::INSERT_VECTOR_ELT: 603 case ISD::INSERT_SUBVECTOR: 604 case ISD::EXTRACT_SUBVECTOR: 605 case ISD::SCALAR_TO_VECTOR: 606 break; 607 case ISD::CONCAT_VECTORS: 608 setOperationAction(Op, VT, Custom); 609 break; 610 default: 611 setOperationAction(Op, VT, Expand); 612 break; 613 } 614 } 615 } 616 617 // v_perm_b32 can handle either of these. 618 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 619 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 620 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 621 622 // XXX - Do these do anything? Vector constants turn into build_vector. 623 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 624 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 625 626 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 627 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 628 629 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 630 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 631 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 632 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 633 634 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 635 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 636 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 637 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 638 639 setOperationAction(ISD::AND, MVT::v2i16, Promote); 640 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 641 setOperationAction(ISD::OR, MVT::v2i16, Promote); 642 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 643 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 644 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 645 646 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 647 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 648 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 649 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 650 651 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 652 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 653 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 654 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 655 656 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 657 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 658 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 659 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 660 661 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 662 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 663 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 664 665 if (!Subtarget->hasVOP3PInsts()) { 666 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 667 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 668 } 669 670 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 671 // This isn't really legal, but this avoids the legalizer unrolling it (and 672 // allows matching fneg (fabs x) patterns) 673 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 674 675 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 676 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 677 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 678 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 679 680 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 681 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 682 683 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 684 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 685 } 686 687 if (Subtarget->hasVOP3PInsts()) { 688 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 689 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 690 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 691 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 692 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 693 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 694 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 695 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 696 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 697 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 698 699 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 700 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 701 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 702 703 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 704 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 705 706 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 707 708 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 709 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 710 711 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 712 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 713 714 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 715 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 716 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 717 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 718 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 719 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 720 721 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 722 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 723 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 724 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 725 726 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 727 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 728 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 729 730 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 731 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 732 733 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 734 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 735 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 736 737 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 738 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 739 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 740 } 741 742 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 743 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 744 745 if (Subtarget->has16BitInsts()) { 746 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 747 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 748 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 749 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 750 } else { 751 // Legalization hack. 752 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 753 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 754 755 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 756 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 757 } 758 759 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 760 setOperationAction(ISD::SELECT, VT, Custom); 761 } 762 763 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 764 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 765 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 766 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 767 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 768 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 769 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 770 771 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 772 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 773 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 774 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 775 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 776 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 777 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 778 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 779 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 780 781 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 782 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 783 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 784 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 785 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 786 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 787 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 788 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 789 790 setTargetDAGCombine(ISD::ADD); 791 setTargetDAGCombine(ISD::ADDCARRY); 792 setTargetDAGCombine(ISD::SUB); 793 setTargetDAGCombine(ISD::SUBCARRY); 794 setTargetDAGCombine(ISD::FADD); 795 setTargetDAGCombine(ISD::FSUB); 796 setTargetDAGCombine(ISD::FMINNUM); 797 setTargetDAGCombine(ISD::FMAXNUM); 798 setTargetDAGCombine(ISD::FMINNUM_IEEE); 799 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 800 setTargetDAGCombine(ISD::FMA); 801 setTargetDAGCombine(ISD::SMIN); 802 setTargetDAGCombine(ISD::SMAX); 803 setTargetDAGCombine(ISD::UMIN); 804 setTargetDAGCombine(ISD::UMAX); 805 setTargetDAGCombine(ISD::SETCC); 806 setTargetDAGCombine(ISD::AND); 807 setTargetDAGCombine(ISD::OR); 808 setTargetDAGCombine(ISD::XOR); 809 setTargetDAGCombine(ISD::SINT_TO_FP); 810 setTargetDAGCombine(ISD::UINT_TO_FP); 811 setTargetDAGCombine(ISD::FCANONICALIZE); 812 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 813 setTargetDAGCombine(ISD::ZERO_EXTEND); 814 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 815 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 816 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 817 818 // All memory operations. Some folding on the pointer operand is done to help 819 // matching the constant offsets in the addressing modes. 820 setTargetDAGCombine(ISD::LOAD); 821 setTargetDAGCombine(ISD::STORE); 822 setTargetDAGCombine(ISD::ATOMIC_LOAD); 823 setTargetDAGCombine(ISD::ATOMIC_STORE); 824 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 825 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 826 setTargetDAGCombine(ISD::ATOMIC_SWAP); 827 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 828 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 829 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 830 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 831 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 832 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 833 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 834 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 835 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 836 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 837 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 838 839 setSchedulingPreference(Sched::RegPressure); 840 } 841 842 const GCNSubtarget *SITargetLowering::getSubtarget() const { 843 return Subtarget; 844 } 845 846 //===----------------------------------------------------------------------===// 847 // TargetLowering queries 848 //===----------------------------------------------------------------------===// 849 850 // v_mad_mix* support a conversion from f16 to f32. 851 // 852 // There is only one special case when denormals are enabled we don't currently, 853 // where this is OK to use. 854 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 855 EVT DestVT, EVT SrcVT) const { 856 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 857 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 858 DestVT.getScalarType() == MVT::f32 && 859 SrcVT.getScalarType() == MVT::f16 && 860 // TODO: This probably only requires no input flushing? 861 !hasFP32Denormals(DAG.getMachineFunction()); 862 } 863 864 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 865 // SI has some legal vector types, but no legal vector operations. Say no 866 // shuffles are legal in order to prefer scalarizing some vector operations. 867 return false; 868 } 869 870 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 871 CallingConv::ID CC, 872 EVT VT) const { 873 if (CC == CallingConv::AMDGPU_KERNEL) 874 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 875 876 if (VT.isVector()) { 877 EVT ScalarVT = VT.getScalarType(); 878 unsigned Size = ScalarVT.getSizeInBits(); 879 if (Size == 32) 880 return ScalarVT.getSimpleVT(); 881 882 if (Size > 32) 883 return MVT::i32; 884 885 if (Size == 16 && Subtarget->has16BitInsts()) 886 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 887 } else if (VT.getSizeInBits() > 32) 888 return MVT::i32; 889 890 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 891 } 892 893 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 894 CallingConv::ID CC, 895 EVT VT) const { 896 if (CC == CallingConv::AMDGPU_KERNEL) 897 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 898 899 if (VT.isVector()) { 900 unsigned NumElts = VT.getVectorNumElements(); 901 EVT ScalarVT = VT.getScalarType(); 902 unsigned Size = ScalarVT.getSizeInBits(); 903 904 if (Size == 32) 905 return NumElts; 906 907 if (Size > 32) 908 return NumElts * ((Size + 31) / 32); 909 910 if (Size == 16 && Subtarget->has16BitInsts()) 911 return (NumElts + 1) / 2; 912 } else if (VT.getSizeInBits() > 32) 913 return (VT.getSizeInBits() + 31) / 32; 914 915 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 916 } 917 918 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 919 LLVMContext &Context, CallingConv::ID CC, 920 EVT VT, EVT &IntermediateVT, 921 unsigned &NumIntermediates, MVT &RegisterVT) const { 922 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 923 unsigned NumElts = VT.getVectorNumElements(); 924 EVT ScalarVT = VT.getScalarType(); 925 unsigned Size = ScalarVT.getSizeInBits(); 926 if (Size == 32) { 927 RegisterVT = ScalarVT.getSimpleVT(); 928 IntermediateVT = RegisterVT; 929 NumIntermediates = NumElts; 930 return NumIntermediates; 931 } 932 933 if (Size > 32) { 934 RegisterVT = MVT::i32; 935 IntermediateVT = RegisterVT; 936 NumIntermediates = NumElts * ((Size + 31) / 32); 937 return NumIntermediates; 938 } 939 940 // FIXME: We should fix the ABI to be the same on targets without 16-bit 941 // support, but unless we can properly handle 3-vectors, it will be still be 942 // inconsistent. 943 if (Size == 16 && Subtarget->has16BitInsts()) { 944 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 945 IntermediateVT = RegisterVT; 946 NumIntermediates = (NumElts + 1) / 2; 947 return NumIntermediates; 948 } 949 } 950 951 return TargetLowering::getVectorTypeBreakdownForCallingConv( 952 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 953 } 954 955 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 956 assert(DMaskLanes != 0); 957 958 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 959 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 960 return EVT::getVectorVT(Ty->getContext(), 961 EVT::getEVT(VT->getElementType()), 962 NumElts); 963 } 964 965 return EVT::getEVT(Ty); 966 } 967 968 // Peek through TFE struct returns to only use the data size. 969 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 970 auto *ST = dyn_cast<StructType>(Ty); 971 if (!ST) 972 return memVTFromImageData(Ty, DMaskLanes); 973 974 // Some intrinsics return an aggregate type - special case to work out the 975 // correct memVT. 976 // 977 // Only limited forms of aggregate type currently expected. 978 if (ST->getNumContainedTypes() != 2 || 979 !ST->getContainedType(1)->isIntegerTy(32)) 980 return EVT(); 981 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 982 } 983 984 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 985 const CallInst &CI, 986 MachineFunction &MF, 987 unsigned IntrID) const { 988 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 989 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 990 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 991 (Intrinsic::ID)IntrID); 992 if (Attr.hasFnAttribute(Attribute::ReadNone)) 993 return false; 994 995 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 996 997 if (RsrcIntr->IsImage) { 998 Info.ptrVal = MFI->getImagePSV( 999 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1000 CI.getArgOperand(RsrcIntr->RsrcArg)); 1001 Info.align.reset(); 1002 } else { 1003 Info.ptrVal = MFI->getBufferPSV( 1004 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1005 CI.getArgOperand(RsrcIntr->RsrcArg)); 1006 } 1007 1008 Info.flags = MachineMemOperand::MODereferenceable; 1009 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 1010 unsigned DMaskLanes = 4; 1011 1012 if (RsrcIntr->IsImage) { 1013 const AMDGPU::ImageDimIntrinsicInfo *Intr 1014 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1015 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1016 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1017 1018 if (!BaseOpcode->Gather4) { 1019 // If this isn't a gather, we may have excess loaded elements in the 1020 // IR type. Check the dmask for the real number of elements loaded. 1021 unsigned DMask 1022 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1023 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1024 } 1025 1026 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1027 } else 1028 Info.memVT = EVT::getEVT(CI.getType()); 1029 1030 // FIXME: What does alignment mean for an image? 1031 Info.opc = ISD::INTRINSIC_W_CHAIN; 1032 Info.flags |= MachineMemOperand::MOLoad; 1033 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1034 Info.opc = ISD::INTRINSIC_VOID; 1035 1036 Type *DataTy = CI.getArgOperand(0)->getType(); 1037 if (RsrcIntr->IsImage) { 1038 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1039 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1040 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1041 } else 1042 Info.memVT = EVT::getEVT(DataTy); 1043 1044 Info.flags |= MachineMemOperand::MOStore; 1045 } else { 1046 // Atomic 1047 Info.opc = ISD::INTRINSIC_W_CHAIN; 1048 Info.memVT = MVT::getVT(CI.getType()); 1049 Info.flags = MachineMemOperand::MOLoad | 1050 MachineMemOperand::MOStore | 1051 MachineMemOperand::MODereferenceable; 1052 1053 // XXX - Should this be volatile without known ordering? 1054 Info.flags |= MachineMemOperand::MOVolatile; 1055 } 1056 return true; 1057 } 1058 1059 switch (IntrID) { 1060 case Intrinsic::amdgcn_atomic_inc: 1061 case Intrinsic::amdgcn_atomic_dec: 1062 case Intrinsic::amdgcn_ds_ordered_add: 1063 case Intrinsic::amdgcn_ds_ordered_swap: 1064 case Intrinsic::amdgcn_ds_fadd: 1065 case Intrinsic::amdgcn_ds_fmin: 1066 case Intrinsic::amdgcn_ds_fmax: { 1067 Info.opc = ISD::INTRINSIC_W_CHAIN; 1068 Info.memVT = MVT::getVT(CI.getType()); 1069 Info.ptrVal = CI.getOperand(0); 1070 Info.align.reset(); 1071 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1072 1073 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1074 if (!Vol->isZero()) 1075 Info.flags |= MachineMemOperand::MOVolatile; 1076 1077 return true; 1078 } 1079 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1080 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1081 1082 Info.opc = ISD::INTRINSIC_VOID; 1083 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1084 Info.ptrVal = MFI->getBufferPSV( 1085 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1086 CI.getArgOperand(1)); 1087 Info.align.reset(); 1088 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1089 1090 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1091 if (!Vol || !Vol->isZero()) 1092 Info.flags |= MachineMemOperand::MOVolatile; 1093 1094 return true; 1095 } 1096 case Intrinsic::amdgcn_global_atomic_fadd: { 1097 Info.opc = ISD::INTRINSIC_VOID; 1098 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 1099 ->getPointerElementType()); 1100 Info.ptrVal = CI.getOperand(0); 1101 Info.align.reset(); 1102 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1103 1104 return true; 1105 } 1106 case Intrinsic::amdgcn_ds_append: 1107 case Intrinsic::amdgcn_ds_consume: { 1108 Info.opc = ISD::INTRINSIC_W_CHAIN; 1109 Info.memVT = MVT::getVT(CI.getType()); 1110 Info.ptrVal = CI.getOperand(0); 1111 Info.align.reset(); 1112 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1113 1114 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1115 if (!Vol->isZero()) 1116 Info.flags |= MachineMemOperand::MOVolatile; 1117 1118 return true; 1119 } 1120 case Intrinsic::amdgcn_ds_gws_init: 1121 case Intrinsic::amdgcn_ds_gws_barrier: 1122 case Intrinsic::amdgcn_ds_gws_sema_v: 1123 case Intrinsic::amdgcn_ds_gws_sema_br: 1124 case Intrinsic::amdgcn_ds_gws_sema_p: 1125 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1126 Info.opc = ISD::INTRINSIC_VOID; 1127 1128 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1129 Info.ptrVal = 1130 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1131 1132 // This is an abstract access, but we need to specify a type and size. 1133 Info.memVT = MVT::i32; 1134 Info.size = 4; 1135 Info.align = Align(4); 1136 1137 Info.flags = MachineMemOperand::MOStore; 1138 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1139 Info.flags = MachineMemOperand::MOLoad; 1140 return true; 1141 } 1142 default: 1143 return false; 1144 } 1145 } 1146 1147 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1148 SmallVectorImpl<Value*> &Ops, 1149 Type *&AccessTy) const { 1150 switch (II->getIntrinsicID()) { 1151 case Intrinsic::amdgcn_atomic_inc: 1152 case Intrinsic::amdgcn_atomic_dec: 1153 case Intrinsic::amdgcn_ds_ordered_add: 1154 case Intrinsic::amdgcn_ds_ordered_swap: 1155 case Intrinsic::amdgcn_ds_fadd: 1156 case Intrinsic::amdgcn_ds_fmin: 1157 case Intrinsic::amdgcn_ds_fmax: { 1158 Value *Ptr = II->getArgOperand(0); 1159 AccessTy = II->getType(); 1160 Ops.push_back(Ptr); 1161 return true; 1162 } 1163 default: 1164 return false; 1165 } 1166 } 1167 1168 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1169 if (!Subtarget->hasFlatInstOffsets()) { 1170 // Flat instructions do not have offsets, and only have the register 1171 // address. 1172 return AM.BaseOffs == 0 && AM.Scale == 0; 1173 } 1174 1175 return AM.Scale == 0 && 1176 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1177 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1178 /*Signed=*/false)); 1179 } 1180 1181 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1182 if (Subtarget->hasFlatGlobalInsts()) 1183 return AM.Scale == 0 && 1184 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1185 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1186 /*Signed=*/true)); 1187 1188 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1189 // Assume the we will use FLAT for all global memory accesses 1190 // on VI. 1191 // FIXME: This assumption is currently wrong. On VI we still use 1192 // MUBUF instructions for the r + i addressing mode. As currently 1193 // implemented, the MUBUF instructions only work on buffer < 4GB. 1194 // It may be possible to support > 4GB buffers with MUBUF instructions, 1195 // by setting the stride value in the resource descriptor which would 1196 // increase the size limit to (stride * 4GB). However, this is risky, 1197 // because it has never been validated. 1198 return isLegalFlatAddressingMode(AM); 1199 } 1200 1201 return isLegalMUBUFAddressingMode(AM); 1202 } 1203 1204 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1205 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1206 // additionally can do r + r + i with addr64. 32-bit has more addressing 1207 // mode options. Depending on the resource constant, it can also do 1208 // (i64 r0) + (i32 r1) * (i14 i). 1209 // 1210 // Private arrays end up using a scratch buffer most of the time, so also 1211 // assume those use MUBUF instructions. Scratch loads / stores are currently 1212 // implemented as mubuf instructions with offen bit set, so slightly 1213 // different than the normal addr64. 1214 if (!isUInt<12>(AM.BaseOffs)) 1215 return false; 1216 1217 // FIXME: Since we can split immediate into soffset and immediate offset, 1218 // would it make sense to allow any immediate? 1219 1220 switch (AM.Scale) { 1221 case 0: // r + i or just i, depending on HasBaseReg. 1222 return true; 1223 case 1: 1224 return true; // We have r + r or r + i. 1225 case 2: 1226 if (AM.HasBaseReg) { 1227 // Reject 2 * r + r. 1228 return false; 1229 } 1230 1231 // Allow 2 * r as r + r 1232 // Or 2 * r + i is allowed as r + r + i. 1233 return true; 1234 default: // Don't allow n * r 1235 return false; 1236 } 1237 } 1238 1239 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1240 const AddrMode &AM, Type *Ty, 1241 unsigned AS, Instruction *I) const { 1242 // No global is ever allowed as a base. 1243 if (AM.BaseGV) 1244 return false; 1245 1246 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1247 return isLegalGlobalAddressingMode(AM); 1248 1249 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1250 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1251 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1252 // If the offset isn't a multiple of 4, it probably isn't going to be 1253 // correctly aligned. 1254 // FIXME: Can we get the real alignment here? 1255 if (AM.BaseOffs % 4 != 0) 1256 return isLegalMUBUFAddressingMode(AM); 1257 1258 // There are no SMRD extloads, so if we have to do a small type access we 1259 // will use a MUBUF load. 1260 // FIXME?: We also need to do this if unaligned, but we don't know the 1261 // alignment here. 1262 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1263 return isLegalGlobalAddressingMode(AM); 1264 1265 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1266 // SMRD instructions have an 8-bit, dword offset on SI. 1267 if (!isUInt<8>(AM.BaseOffs / 4)) 1268 return false; 1269 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1270 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1271 // in 8-bits, it can use a smaller encoding. 1272 if (!isUInt<32>(AM.BaseOffs / 4)) 1273 return false; 1274 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1275 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1276 if (!isUInt<20>(AM.BaseOffs)) 1277 return false; 1278 } else 1279 llvm_unreachable("unhandled generation"); 1280 1281 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1282 return true; 1283 1284 if (AM.Scale == 1 && AM.HasBaseReg) 1285 return true; 1286 1287 return false; 1288 1289 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1290 return isLegalMUBUFAddressingMode(AM); 1291 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1292 AS == AMDGPUAS::REGION_ADDRESS) { 1293 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1294 // field. 1295 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1296 // an 8-bit dword offset but we don't know the alignment here. 1297 if (!isUInt<16>(AM.BaseOffs)) 1298 return false; 1299 1300 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1301 return true; 1302 1303 if (AM.Scale == 1 && AM.HasBaseReg) 1304 return true; 1305 1306 return false; 1307 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1308 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1309 // For an unknown address space, this usually means that this is for some 1310 // reason being used for pure arithmetic, and not based on some addressing 1311 // computation. We don't have instructions that compute pointers with any 1312 // addressing modes, so treat them as having no offset like flat 1313 // instructions. 1314 return isLegalFlatAddressingMode(AM); 1315 } 1316 1317 // Assume a user alias of global for unknown address spaces. 1318 return isLegalGlobalAddressingMode(AM); 1319 } 1320 1321 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1322 const SelectionDAG &DAG) const { 1323 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1324 return (MemVT.getSizeInBits() <= 4 * 32); 1325 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1326 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1327 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1328 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1329 return (MemVT.getSizeInBits() <= 2 * 32); 1330 } 1331 return true; 1332 } 1333 1334 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1335 unsigned Size, unsigned AddrSpace, unsigned Align, 1336 MachineMemOperand::Flags Flags, bool *IsFast) const { 1337 if (IsFast) 1338 *IsFast = false; 1339 1340 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1341 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1342 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1343 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1344 // with adjacent offsets. 1345 bool AlignedBy4 = (Align % 4 == 0); 1346 if (IsFast) 1347 *IsFast = AlignedBy4; 1348 1349 return AlignedBy4; 1350 } 1351 1352 // FIXME: We have to be conservative here and assume that flat operations 1353 // will access scratch. If we had access to the IR function, then we 1354 // could determine if any private memory was used in the function. 1355 if (!Subtarget->hasUnalignedScratchAccess() && 1356 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1357 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1358 bool AlignedBy4 = Align >= 4; 1359 if (IsFast) 1360 *IsFast = AlignedBy4; 1361 1362 return AlignedBy4; 1363 } 1364 1365 if (Subtarget->hasUnalignedBufferAccess()) { 1366 // If we have an uniform constant load, it still requires using a slow 1367 // buffer instruction if unaligned. 1368 if (IsFast) { 1369 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1370 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1371 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1372 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1373 Align >= 4 : Align != 2; 1374 } 1375 1376 return true; 1377 } 1378 1379 // Smaller than dword value must be aligned. 1380 if (Size < 32) 1381 return false; 1382 1383 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1384 // byte-address are ignored, thus forcing Dword alignment. 1385 // This applies to private, global, and constant memory. 1386 if (IsFast) 1387 *IsFast = true; 1388 1389 return Size >= 32 && Align >= 4; 1390 } 1391 1392 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1393 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1394 bool *IsFast) const { 1395 if (IsFast) 1396 *IsFast = false; 1397 1398 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1399 // which isn't a simple VT. 1400 // Until MVT is extended to handle this, simply check for the size and 1401 // rely on the condition below: allow accesses if the size is a multiple of 4. 1402 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1403 VT.getStoreSize() > 16)) { 1404 return false; 1405 } 1406 1407 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1408 Align, Flags, IsFast); 1409 } 1410 1411 EVT SITargetLowering::getOptimalMemOpType( 1412 const MemOp &Op, const AttributeList &FuncAttributes) const { 1413 // FIXME: Should account for address space here. 1414 1415 // The default fallback uses the private pointer size as a guess for a type to 1416 // use. Make sure we switch these to 64-bit accesses. 1417 1418 if (Op.size() >= 16 && 1419 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1420 return MVT::v4i32; 1421 1422 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1423 return MVT::v2i32; 1424 1425 // Use the default. 1426 return MVT::Other; 1427 } 1428 1429 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1430 unsigned DestAS) const { 1431 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1432 } 1433 1434 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1435 const MemSDNode *MemNode = cast<MemSDNode>(N); 1436 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1437 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1438 return I && I->getMetadata("amdgpu.noclobber"); 1439 } 1440 1441 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1442 unsigned DestAS) const { 1443 // Flat -> private/local is a simple truncate. 1444 // Flat -> global is no-op 1445 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1446 return true; 1447 1448 return isNoopAddrSpaceCast(SrcAS, DestAS); 1449 } 1450 1451 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1452 const MemSDNode *MemNode = cast<MemSDNode>(N); 1453 1454 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1455 } 1456 1457 TargetLoweringBase::LegalizeTypeAction 1458 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1459 int NumElts = VT.getVectorNumElements(); 1460 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1461 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1462 return TargetLoweringBase::getPreferredVectorAction(VT); 1463 } 1464 1465 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1466 Type *Ty) const { 1467 // FIXME: Could be smarter if called for vector constants. 1468 return true; 1469 } 1470 1471 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1472 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1473 switch (Op) { 1474 case ISD::LOAD: 1475 case ISD::STORE: 1476 1477 // These operations are done with 32-bit instructions anyway. 1478 case ISD::AND: 1479 case ISD::OR: 1480 case ISD::XOR: 1481 case ISD::SELECT: 1482 // TODO: Extensions? 1483 return true; 1484 default: 1485 return false; 1486 } 1487 } 1488 1489 // SimplifySetCC uses this function to determine whether or not it should 1490 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1491 if (VT == MVT::i1 && Op == ISD::SETCC) 1492 return false; 1493 1494 return TargetLowering::isTypeDesirableForOp(Op, VT); 1495 } 1496 1497 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1498 const SDLoc &SL, 1499 SDValue Chain, 1500 uint64_t Offset) const { 1501 const DataLayout &DL = DAG.getDataLayout(); 1502 MachineFunction &MF = DAG.getMachineFunction(); 1503 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1504 1505 const ArgDescriptor *InputPtrReg; 1506 const TargetRegisterClass *RC; 1507 1508 std::tie(InputPtrReg, RC) 1509 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1510 1511 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1512 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1513 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1514 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1515 1516 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1517 } 1518 1519 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1520 const SDLoc &SL) const { 1521 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1522 FIRST_IMPLICIT); 1523 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1524 } 1525 1526 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1527 const SDLoc &SL, SDValue Val, 1528 bool Signed, 1529 const ISD::InputArg *Arg) const { 1530 // First, if it is a widened vector, narrow it. 1531 if (VT.isVector() && 1532 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1533 EVT NarrowedVT = 1534 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1535 VT.getVectorNumElements()); 1536 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1537 DAG.getConstant(0, SL, MVT::i32)); 1538 } 1539 1540 // Then convert the vector elements or scalar value. 1541 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1542 VT.bitsLT(MemVT)) { 1543 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1544 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1545 } 1546 1547 if (MemVT.isFloatingPoint()) 1548 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1549 else if (Signed) 1550 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1551 else 1552 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1553 1554 return Val; 1555 } 1556 1557 SDValue SITargetLowering::lowerKernargMemParameter( 1558 SelectionDAG &DAG, EVT VT, EVT MemVT, 1559 const SDLoc &SL, SDValue Chain, 1560 uint64_t Offset, unsigned Align, bool Signed, 1561 const ISD::InputArg *Arg) const { 1562 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1563 1564 // Try to avoid using an extload by loading earlier than the argument address, 1565 // and extracting the relevant bits. The load should hopefully be merged with 1566 // the previous argument. 1567 if (MemVT.getStoreSize() < 4 && Align < 4) { 1568 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1569 int64_t AlignDownOffset = alignDown(Offset, 4); 1570 int64_t OffsetDiff = Offset - AlignDownOffset; 1571 1572 EVT IntVT = MemVT.changeTypeToInteger(); 1573 1574 // TODO: If we passed in the base kernel offset we could have a better 1575 // alignment than 4, but we don't really need it. 1576 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1577 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1578 MachineMemOperand::MODereferenceable | 1579 MachineMemOperand::MOInvariant); 1580 1581 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1582 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1583 1584 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1585 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1586 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1587 1588 1589 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1590 } 1591 1592 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1593 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1594 MachineMemOperand::MODereferenceable | 1595 MachineMemOperand::MOInvariant); 1596 1597 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1598 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1599 } 1600 1601 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1602 const SDLoc &SL, SDValue Chain, 1603 const ISD::InputArg &Arg) const { 1604 MachineFunction &MF = DAG.getMachineFunction(); 1605 MachineFrameInfo &MFI = MF.getFrameInfo(); 1606 1607 if (Arg.Flags.isByVal()) { 1608 unsigned Size = Arg.Flags.getByValSize(); 1609 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1610 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1611 } 1612 1613 unsigned ArgOffset = VA.getLocMemOffset(); 1614 unsigned ArgSize = VA.getValVT().getStoreSize(); 1615 1616 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1617 1618 // Create load nodes to retrieve arguments from the stack. 1619 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1620 SDValue ArgValue; 1621 1622 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1623 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1624 MVT MemVT = VA.getValVT(); 1625 1626 switch (VA.getLocInfo()) { 1627 default: 1628 break; 1629 case CCValAssign::BCvt: 1630 MemVT = VA.getLocVT(); 1631 break; 1632 case CCValAssign::SExt: 1633 ExtType = ISD::SEXTLOAD; 1634 break; 1635 case CCValAssign::ZExt: 1636 ExtType = ISD::ZEXTLOAD; 1637 break; 1638 case CCValAssign::AExt: 1639 ExtType = ISD::EXTLOAD; 1640 break; 1641 } 1642 1643 ArgValue = DAG.getExtLoad( 1644 ExtType, SL, VA.getLocVT(), Chain, FIN, 1645 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1646 MemVT); 1647 return ArgValue; 1648 } 1649 1650 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1651 const SIMachineFunctionInfo &MFI, 1652 EVT VT, 1653 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1654 const ArgDescriptor *Reg; 1655 const TargetRegisterClass *RC; 1656 1657 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1658 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1659 } 1660 1661 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1662 CallingConv::ID CallConv, 1663 ArrayRef<ISD::InputArg> Ins, 1664 BitVector &Skipped, 1665 FunctionType *FType, 1666 SIMachineFunctionInfo *Info) { 1667 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1668 const ISD::InputArg *Arg = &Ins[I]; 1669 1670 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1671 "vector type argument should have been split"); 1672 1673 // First check if it's a PS input addr. 1674 if (CallConv == CallingConv::AMDGPU_PS && 1675 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1676 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1677 1678 // Inconveniently only the first part of the split is marked as isSplit, 1679 // so skip to the end. We only want to increment PSInputNum once for the 1680 // entire split argument. 1681 if (Arg->Flags.isSplit()) { 1682 while (!Arg->Flags.isSplitEnd()) { 1683 assert((!Arg->VT.isVector() || 1684 Arg->VT.getScalarSizeInBits() == 16) && 1685 "unexpected vector split in ps argument type"); 1686 if (!SkipArg) 1687 Splits.push_back(*Arg); 1688 Arg = &Ins[++I]; 1689 } 1690 } 1691 1692 if (SkipArg) { 1693 // We can safely skip PS inputs. 1694 Skipped.set(Arg->getOrigArgIndex()); 1695 ++PSInputNum; 1696 continue; 1697 } 1698 1699 Info->markPSInputAllocated(PSInputNum); 1700 if (Arg->Used) 1701 Info->markPSInputEnabled(PSInputNum); 1702 1703 ++PSInputNum; 1704 } 1705 1706 Splits.push_back(*Arg); 1707 } 1708 } 1709 1710 // Allocate special inputs passed in VGPRs. 1711 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1712 MachineFunction &MF, 1713 const SIRegisterInfo &TRI, 1714 SIMachineFunctionInfo &Info) const { 1715 const LLT S32 = LLT::scalar(32); 1716 MachineRegisterInfo &MRI = MF.getRegInfo(); 1717 1718 if (Info.hasWorkItemIDX()) { 1719 Register Reg = AMDGPU::VGPR0; 1720 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1721 1722 CCInfo.AllocateReg(Reg); 1723 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1724 } 1725 1726 if (Info.hasWorkItemIDY()) { 1727 Register Reg = AMDGPU::VGPR1; 1728 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1729 1730 CCInfo.AllocateReg(Reg); 1731 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1732 } 1733 1734 if (Info.hasWorkItemIDZ()) { 1735 Register Reg = AMDGPU::VGPR2; 1736 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1737 1738 CCInfo.AllocateReg(Reg); 1739 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1740 } 1741 } 1742 1743 // Try to allocate a VGPR at the end of the argument list, or if no argument 1744 // VGPRs are left allocating a stack slot. 1745 // If \p Mask is is given it indicates bitfield position in the register. 1746 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1747 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1748 ArgDescriptor Arg = ArgDescriptor()) { 1749 if (Arg.isSet()) 1750 return ArgDescriptor::createArg(Arg, Mask); 1751 1752 ArrayRef<MCPhysReg> ArgVGPRs 1753 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1754 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1755 if (RegIdx == ArgVGPRs.size()) { 1756 // Spill to stack required. 1757 int64_t Offset = CCInfo.AllocateStack(4, 4); 1758 1759 return ArgDescriptor::createStack(Offset, Mask); 1760 } 1761 1762 unsigned Reg = ArgVGPRs[RegIdx]; 1763 Reg = CCInfo.AllocateReg(Reg); 1764 assert(Reg != AMDGPU::NoRegister); 1765 1766 MachineFunction &MF = CCInfo.getMachineFunction(); 1767 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1768 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1769 return ArgDescriptor::createRegister(Reg, Mask); 1770 } 1771 1772 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1773 const TargetRegisterClass *RC, 1774 unsigned NumArgRegs) { 1775 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1776 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1777 if (RegIdx == ArgSGPRs.size()) 1778 report_fatal_error("ran out of SGPRs for arguments"); 1779 1780 unsigned Reg = ArgSGPRs[RegIdx]; 1781 Reg = CCInfo.AllocateReg(Reg); 1782 assert(Reg != AMDGPU::NoRegister); 1783 1784 MachineFunction &MF = CCInfo.getMachineFunction(); 1785 MF.addLiveIn(Reg, RC); 1786 return ArgDescriptor::createRegister(Reg); 1787 } 1788 1789 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1790 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1791 } 1792 1793 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1794 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1795 } 1796 1797 /// Allocate implicit function VGPR arguments at the end of allocated user 1798 /// arguments. 1799 void SITargetLowering::allocateSpecialInputVGPRs( 1800 CCState &CCInfo, MachineFunction &MF, 1801 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1802 const unsigned Mask = 0x3ff; 1803 ArgDescriptor Arg; 1804 1805 if (Info.hasWorkItemIDX()) { 1806 Arg = allocateVGPR32Input(CCInfo, Mask); 1807 Info.setWorkItemIDX(Arg); 1808 } 1809 1810 if (Info.hasWorkItemIDY()) { 1811 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1812 Info.setWorkItemIDY(Arg); 1813 } 1814 1815 if (Info.hasWorkItemIDZ()) 1816 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1817 } 1818 1819 /// Allocate implicit function VGPR arguments in fixed registers. 1820 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1821 CCState &CCInfo, MachineFunction &MF, 1822 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1823 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1824 if (!Reg) 1825 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1826 1827 const unsigned Mask = 0x3ff; 1828 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1829 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1830 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1831 } 1832 1833 void SITargetLowering::allocateSpecialInputSGPRs( 1834 CCState &CCInfo, 1835 MachineFunction &MF, 1836 const SIRegisterInfo &TRI, 1837 SIMachineFunctionInfo &Info) const { 1838 auto &ArgInfo = Info.getArgInfo(); 1839 1840 // TODO: Unify handling with private memory pointers. 1841 1842 if (Info.hasDispatchPtr()) 1843 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1844 1845 if (Info.hasQueuePtr()) 1846 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1847 1848 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1849 // constant offset from the kernarg segment. 1850 if (Info.hasImplicitArgPtr()) 1851 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1852 1853 if (Info.hasDispatchID()) 1854 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1855 1856 // flat_scratch_init is not applicable for non-kernel functions. 1857 1858 if (Info.hasWorkGroupIDX()) 1859 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1860 1861 if (Info.hasWorkGroupIDY()) 1862 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1863 1864 if (Info.hasWorkGroupIDZ()) 1865 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1866 } 1867 1868 // Allocate special inputs passed in user SGPRs. 1869 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1870 MachineFunction &MF, 1871 const SIRegisterInfo &TRI, 1872 SIMachineFunctionInfo &Info) const { 1873 if (Info.hasImplicitBufferPtr()) { 1874 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1875 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1876 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1877 } 1878 1879 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1880 if (Info.hasPrivateSegmentBuffer()) { 1881 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1882 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1883 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1884 } 1885 1886 if (Info.hasDispatchPtr()) { 1887 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1888 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1889 CCInfo.AllocateReg(DispatchPtrReg); 1890 } 1891 1892 if (Info.hasQueuePtr()) { 1893 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1894 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1895 CCInfo.AllocateReg(QueuePtrReg); 1896 } 1897 1898 if (Info.hasKernargSegmentPtr()) { 1899 MachineRegisterInfo &MRI = MF.getRegInfo(); 1900 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1901 CCInfo.AllocateReg(InputPtrReg); 1902 1903 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1904 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1905 } 1906 1907 if (Info.hasDispatchID()) { 1908 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1909 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1910 CCInfo.AllocateReg(DispatchIDReg); 1911 } 1912 1913 if (Info.hasFlatScratchInit()) { 1914 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1915 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1916 CCInfo.AllocateReg(FlatScratchInitReg); 1917 } 1918 1919 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1920 // these from the dispatch pointer. 1921 } 1922 1923 // Allocate special input registers that are initialized per-wave. 1924 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1925 MachineFunction &MF, 1926 SIMachineFunctionInfo &Info, 1927 CallingConv::ID CallConv, 1928 bool IsShader) const { 1929 if (Info.hasWorkGroupIDX()) { 1930 unsigned Reg = Info.addWorkGroupIDX(); 1931 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1932 CCInfo.AllocateReg(Reg); 1933 } 1934 1935 if (Info.hasWorkGroupIDY()) { 1936 unsigned Reg = Info.addWorkGroupIDY(); 1937 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1938 CCInfo.AllocateReg(Reg); 1939 } 1940 1941 if (Info.hasWorkGroupIDZ()) { 1942 unsigned Reg = Info.addWorkGroupIDZ(); 1943 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1944 CCInfo.AllocateReg(Reg); 1945 } 1946 1947 if (Info.hasWorkGroupInfo()) { 1948 unsigned Reg = Info.addWorkGroupInfo(); 1949 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1950 CCInfo.AllocateReg(Reg); 1951 } 1952 1953 if (Info.hasPrivateSegmentWaveByteOffset()) { 1954 // Scratch wave offset passed in system SGPR. 1955 unsigned PrivateSegmentWaveByteOffsetReg; 1956 1957 if (IsShader) { 1958 PrivateSegmentWaveByteOffsetReg = 1959 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1960 1961 // This is true if the scratch wave byte offset doesn't have a fixed 1962 // location. 1963 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1964 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1965 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1966 } 1967 } else 1968 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1969 1970 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1971 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1972 } 1973 } 1974 1975 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1976 MachineFunction &MF, 1977 const SIRegisterInfo &TRI, 1978 SIMachineFunctionInfo &Info) { 1979 // Now that we've figured out where the scratch register inputs are, see if 1980 // should reserve the arguments and use them directly. 1981 MachineFrameInfo &MFI = MF.getFrameInfo(); 1982 bool HasStackObjects = MFI.hasStackObjects(); 1983 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 1984 1985 // Record that we know we have non-spill stack objects so we don't need to 1986 // check all stack objects later. 1987 if (HasStackObjects) 1988 Info.setHasNonSpillStackObjects(true); 1989 1990 // Everything live out of a block is spilled with fast regalloc, so it's 1991 // almost certain that spilling will be required. 1992 if (TM.getOptLevel() == CodeGenOpt::None) 1993 HasStackObjects = true; 1994 1995 // For now assume stack access is needed in any callee functions, so we need 1996 // the scratch registers to pass in. 1997 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1998 1999 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2000 // If we have stack objects, we unquestionably need the private buffer 2001 // resource. For the Code Object V2 ABI, this will be the first 4 user 2002 // SGPR inputs. We can reserve those and use them directly. 2003 2004 Register PrivateSegmentBufferReg = 2005 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2006 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2007 } else { 2008 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2009 // We tentatively reserve the last registers (skipping the last registers 2010 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2011 // we'll replace these with the ones immediately after those which were 2012 // really allocated. In the prologue copies will be inserted from the 2013 // argument to these reserved registers. 2014 2015 // Without HSA, relocations are used for the scratch pointer and the 2016 // buffer resource setup is always inserted in the prologue. Scratch wave 2017 // offset is still in an input SGPR. 2018 Info.setScratchRSrcReg(ReservedBufferReg); 2019 } 2020 2021 MachineRegisterInfo &MRI = MF.getRegInfo(); 2022 2023 // For entry functions we have to set up the stack pointer if we use it, 2024 // whereas non-entry functions get this "for free". This means there is no 2025 // intrinsic advantage to using S32 over S34 in cases where we do not have 2026 // calls but do need a frame pointer (i.e. if we are requested to have one 2027 // because frame pointer elimination is disabled). To keep things simple we 2028 // only ever use S32 as the call ABI stack pointer, and so using it does not 2029 // imply we need a separate frame pointer. 2030 // 2031 // Try to use s32 as the SP, but move it if it would interfere with input 2032 // arguments. This won't work with calls though. 2033 // 2034 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2035 // registers. 2036 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2037 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2038 } else { 2039 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2040 2041 if (MFI.hasCalls()) 2042 report_fatal_error("call in graphics shader with too many input SGPRs"); 2043 2044 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2045 if (!MRI.isLiveIn(Reg)) { 2046 Info.setStackPtrOffsetReg(Reg); 2047 break; 2048 } 2049 } 2050 2051 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2052 report_fatal_error("failed to find register for SP"); 2053 } 2054 2055 // hasFP should be accurate for entry functions even before the frame is 2056 // finalized, because it does not rely on the known stack size, only 2057 // properties like whether variable sized objects are present. 2058 if (ST.getFrameLowering()->hasFP(MF)) { 2059 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2060 } 2061 } 2062 2063 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2064 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2065 return !Info->isEntryFunction(); 2066 } 2067 2068 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2069 2070 } 2071 2072 void SITargetLowering::insertCopiesSplitCSR( 2073 MachineBasicBlock *Entry, 2074 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2075 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2076 2077 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2078 if (!IStart) 2079 return; 2080 2081 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2082 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2083 MachineBasicBlock::iterator MBBI = Entry->begin(); 2084 for (const MCPhysReg *I = IStart; *I; ++I) { 2085 const TargetRegisterClass *RC = nullptr; 2086 if (AMDGPU::SReg_64RegClass.contains(*I)) 2087 RC = &AMDGPU::SGPR_64RegClass; 2088 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2089 RC = &AMDGPU::SGPR_32RegClass; 2090 else 2091 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2092 2093 Register NewVR = MRI->createVirtualRegister(RC); 2094 // Create copy from CSR to a virtual register. 2095 Entry->addLiveIn(*I); 2096 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2097 .addReg(*I); 2098 2099 // Insert the copy-back instructions right before the terminator. 2100 for (auto *Exit : Exits) 2101 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2102 TII->get(TargetOpcode::COPY), *I) 2103 .addReg(NewVR); 2104 } 2105 } 2106 2107 SDValue SITargetLowering::LowerFormalArguments( 2108 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2109 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2110 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2111 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2112 2113 MachineFunction &MF = DAG.getMachineFunction(); 2114 const Function &Fn = MF.getFunction(); 2115 FunctionType *FType = MF.getFunction().getFunctionType(); 2116 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2117 2118 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2119 DiagnosticInfoUnsupported NoGraphicsHSA( 2120 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2121 DAG.getContext()->diagnose(NoGraphicsHSA); 2122 return DAG.getEntryNode(); 2123 } 2124 2125 SmallVector<ISD::InputArg, 16> Splits; 2126 SmallVector<CCValAssign, 16> ArgLocs; 2127 BitVector Skipped(Ins.size()); 2128 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2129 *DAG.getContext()); 2130 2131 bool IsShader = AMDGPU::isShader(CallConv); 2132 bool IsKernel = AMDGPU::isKernel(CallConv); 2133 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2134 2135 if (IsShader) { 2136 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2137 2138 // At least one interpolation mode must be enabled or else the GPU will 2139 // hang. 2140 // 2141 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2142 // set PSInputAddr, the user wants to enable some bits after the compilation 2143 // based on run-time states. Since we can't know what the final PSInputEna 2144 // will look like, so we shouldn't do anything here and the user should take 2145 // responsibility for the correct programming. 2146 // 2147 // Otherwise, the following restrictions apply: 2148 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2149 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2150 // enabled too. 2151 if (CallConv == CallingConv::AMDGPU_PS) { 2152 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2153 ((Info->getPSInputAddr() & 0xF) == 0 && 2154 Info->isPSInputAllocated(11))) { 2155 CCInfo.AllocateReg(AMDGPU::VGPR0); 2156 CCInfo.AllocateReg(AMDGPU::VGPR1); 2157 Info->markPSInputAllocated(0); 2158 Info->markPSInputEnabled(0); 2159 } 2160 if (Subtarget->isAmdPalOS()) { 2161 // For isAmdPalOS, the user does not enable some bits after compilation 2162 // based on run-time states; the register values being generated here are 2163 // the final ones set in hardware. Therefore we need to apply the 2164 // workaround to PSInputAddr and PSInputEnable together. (The case where 2165 // a bit is set in PSInputAddr but not PSInputEnable is where the 2166 // frontend set up an input arg for a particular interpolation mode, but 2167 // nothing uses that input arg. Really we should have an earlier pass 2168 // that removes such an arg.) 2169 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2170 if ((PsInputBits & 0x7F) == 0 || 2171 ((PsInputBits & 0xF) == 0 && 2172 (PsInputBits >> 11 & 1))) 2173 Info->markPSInputEnabled( 2174 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2175 } 2176 } 2177 2178 assert(!Info->hasDispatchPtr() && 2179 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2180 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2181 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2182 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2183 !Info->hasWorkItemIDZ()); 2184 } else if (IsKernel) { 2185 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2186 } else { 2187 Splits.append(Ins.begin(), Ins.end()); 2188 } 2189 2190 if (IsEntryFunc) { 2191 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2192 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2193 } else { 2194 // For the fixed ABI, pass workitem IDs in the last argument register. 2195 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2196 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2197 } 2198 2199 if (IsKernel) { 2200 analyzeFormalArgumentsCompute(CCInfo, Ins); 2201 } else { 2202 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2203 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2204 } 2205 2206 SmallVector<SDValue, 16> Chains; 2207 2208 // FIXME: This is the minimum kernel argument alignment. We should improve 2209 // this to the maximum alignment of the arguments. 2210 // 2211 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2212 // kern arg offset. 2213 const unsigned KernelArgBaseAlign = 16; 2214 2215 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2216 const ISD::InputArg &Arg = Ins[i]; 2217 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2218 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2219 continue; 2220 } 2221 2222 CCValAssign &VA = ArgLocs[ArgIdx++]; 2223 MVT VT = VA.getLocVT(); 2224 2225 if (IsEntryFunc && VA.isMemLoc()) { 2226 VT = Ins[i].VT; 2227 EVT MemVT = VA.getLocVT(); 2228 2229 const uint64_t Offset = VA.getLocMemOffset(); 2230 unsigned Align = MinAlign(KernelArgBaseAlign, Offset); 2231 2232 SDValue Arg = lowerKernargMemParameter( 2233 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]); 2234 Chains.push_back(Arg.getValue(1)); 2235 2236 auto *ParamTy = 2237 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2238 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2239 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2240 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2241 // On SI local pointers are just offsets into LDS, so they are always 2242 // less than 16-bits. On CI and newer they could potentially be 2243 // real pointers, so we can't guarantee their size. 2244 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2245 DAG.getValueType(MVT::i16)); 2246 } 2247 2248 InVals.push_back(Arg); 2249 continue; 2250 } else if (!IsEntryFunc && VA.isMemLoc()) { 2251 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2252 InVals.push_back(Val); 2253 if (!Arg.Flags.isByVal()) 2254 Chains.push_back(Val.getValue(1)); 2255 continue; 2256 } 2257 2258 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2259 2260 Register Reg = VA.getLocReg(); 2261 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2262 EVT ValVT = VA.getValVT(); 2263 2264 Reg = MF.addLiveIn(Reg, RC); 2265 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2266 2267 if (Arg.Flags.isSRet()) { 2268 // The return object should be reasonably addressable. 2269 2270 // FIXME: This helps when the return is a real sret. If it is a 2271 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2272 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2273 unsigned NumBits 2274 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2275 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2276 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2277 } 2278 2279 // If this is an 8 or 16-bit value, it is really passed promoted 2280 // to 32 bits. Insert an assert[sz]ext to capture this, then 2281 // truncate to the right size. 2282 switch (VA.getLocInfo()) { 2283 case CCValAssign::Full: 2284 break; 2285 case CCValAssign::BCvt: 2286 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2287 break; 2288 case CCValAssign::SExt: 2289 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2290 DAG.getValueType(ValVT)); 2291 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2292 break; 2293 case CCValAssign::ZExt: 2294 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2295 DAG.getValueType(ValVT)); 2296 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2297 break; 2298 case CCValAssign::AExt: 2299 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2300 break; 2301 default: 2302 llvm_unreachable("Unknown loc info!"); 2303 } 2304 2305 InVals.push_back(Val); 2306 } 2307 2308 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2309 // Special inputs come after user arguments. 2310 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2311 } 2312 2313 // Start adding system SGPRs. 2314 if (IsEntryFunc) { 2315 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2316 } else { 2317 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2318 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2319 } 2320 2321 auto &ArgUsageInfo = 2322 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2323 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2324 2325 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2326 Info->setBytesInStackArgArea(StackArgSize); 2327 2328 return Chains.empty() ? Chain : 2329 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2330 } 2331 2332 // TODO: If return values can't fit in registers, we should return as many as 2333 // possible in registers before passing on stack. 2334 bool SITargetLowering::CanLowerReturn( 2335 CallingConv::ID CallConv, 2336 MachineFunction &MF, bool IsVarArg, 2337 const SmallVectorImpl<ISD::OutputArg> &Outs, 2338 LLVMContext &Context) const { 2339 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2340 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2341 // for shaders. Vector types should be explicitly handled by CC. 2342 if (AMDGPU::isEntryFunctionCC(CallConv)) 2343 return true; 2344 2345 SmallVector<CCValAssign, 16> RVLocs; 2346 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2347 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2348 } 2349 2350 SDValue 2351 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2352 bool isVarArg, 2353 const SmallVectorImpl<ISD::OutputArg> &Outs, 2354 const SmallVectorImpl<SDValue> &OutVals, 2355 const SDLoc &DL, SelectionDAG &DAG) const { 2356 MachineFunction &MF = DAG.getMachineFunction(); 2357 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2358 2359 if (AMDGPU::isKernel(CallConv)) { 2360 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2361 OutVals, DL, DAG); 2362 } 2363 2364 bool IsShader = AMDGPU::isShader(CallConv); 2365 2366 Info->setIfReturnsVoid(Outs.empty()); 2367 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2368 2369 // CCValAssign - represent the assignment of the return value to a location. 2370 SmallVector<CCValAssign, 48> RVLocs; 2371 SmallVector<ISD::OutputArg, 48> Splits; 2372 2373 // CCState - Info about the registers and stack slots. 2374 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2375 *DAG.getContext()); 2376 2377 // Analyze outgoing return values. 2378 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2379 2380 SDValue Flag; 2381 SmallVector<SDValue, 48> RetOps; 2382 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2383 2384 // Add return address for callable functions. 2385 if (!Info->isEntryFunction()) { 2386 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2387 SDValue ReturnAddrReg = CreateLiveInRegister( 2388 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2389 2390 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2391 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2392 MVT::i64); 2393 Chain = 2394 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2395 Flag = Chain.getValue(1); 2396 RetOps.push_back(ReturnAddrVirtualReg); 2397 } 2398 2399 // Copy the result values into the output registers. 2400 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2401 ++I, ++RealRVLocIdx) { 2402 CCValAssign &VA = RVLocs[I]; 2403 assert(VA.isRegLoc() && "Can only return in registers!"); 2404 // TODO: Partially return in registers if return values don't fit. 2405 SDValue Arg = OutVals[RealRVLocIdx]; 2406 2407 // Copied from other backends. 2408 switch (VA.getLocInfo()) { 2409 case CCValAssign::Full: 2410 break; 2411 case CCValAssign::BCvt: 2412 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2413 break; 2414 case CCValAssign::SExt: 2415 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2416 break; 2417 case CCValAssign::ZExt: 2418 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2419 break; 2420 case CCValAssign::AExt: 2421 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2422 break; 2423 default: 2424 llvm_unreachable("Unknown loc info!"); 2425 } 2426 2427 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2428 Flag = Chain.getValue(1); 2429 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2430 } 2431 2432 // FIXME: Does sret work properly? 2433 if (!Info->isEntryFunction()) { 2434 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2435 const MCPhysReg *I = 2436 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2437 if (I) { 2438 for (; *I; ++I) { 2439 if (AMDGPU::SReg_64RegClass.contains(*I)) 2440 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2441 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2442 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2443 else 2444 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2445 } 2446 } 2447 } 2448 2449 // Update chain and glue. 2450 RetOps[0] = Chain; 2451 if (Flag.getNode()) 2452 RetOps.push_back(Flag); 2453 2454 unsigned Opc = AMDGPUISD::ENDPGM; 2455 if (!IsWaveEnd) 2456 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2457 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2458 } 2459 2460 SDValue SITargetLowering::LowerCallResult( 2461 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2462 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2463 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2464 SDValue ThisVal) const { 2465 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2466 2467 // Assign locations to each value returned by this call. 2468 SmallVector<CCValAssign, 16> RVLocs; 2469 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2470 *DAG.getContext()); 2471 CCInfo.AnalyzeCallResult(Ins, RetCC); 2472 2473 // Copy all of the result registers out of their specified physreg. 2474 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2475 CCValAssign VA = RVLocs[i]; 2476 SDValue Val; 2477 2478 if (VA.isRegLoc()) { 2479 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2480 Chain = Val.getValue(1); 2481 InFlag = Val.getValue(2); 2482 } else if (VA.isMemLoc()) { 2483 report_fatal_error("TODO: return values in memory"); 2484 } else 2485 llvm_unreachable("unknown argument location type"); 2486 2487 switch (VA.getLocInfo()) { 2488 case CCValAssign::Full: 2489 break; 2490 case CCValAssign::BCvt: 2491 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2492 break; 2493 case CCValAssign::ZExt: 2494 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2495 DAG.getValueType(VA.getValVT())); 2496 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2497 break; 2498 case CCValAssign::SExt: 2499 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2500 DAG.getValueType(VA.getValVT())); 2501 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2502 break; 2503 case CCValAssign::AExt: 2504 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2505 break; 2506 default: 2507 llvm_unreachable("Unknown loc info!"); 2508 } 2509 2510 InVals.push_back(Val); 2511 } 2512 2513 return Chain; 2514 } 2515 2516 // Add code to pass special inputs required depending on used features separate 2517 // from the explicit user arguments present in the IR. 2518 void SITargetLowering::passSpecialInputs( 2519 CallLoweringInfo &CLI, 2520 CCState &CCInfo, 2521 const SIMachineFunctionInfo &Info, 2522 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2523 SmallVectorImpl<SDValue> &MemOpChains, 2524 SDValue Chain) const { 2525 // If we don't have a call site, this was a call inserted by 2526 // legalization. These can never use special inputs. 2527 if (!CLI.CB) 2528 return; 2529 2530 SelectionDAG &DAG = CLI.DAG; 2531 const SDLoc &DL = CLI.DL; 2532 2533 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2534 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2535 2536 const AMDGPUFunctionArgInfo *CalleeArgInfo 2537 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2538 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2539 auto &ArgUsageInfo = 2540 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2541 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2542 } 2543 2544 // TODO: Unify with private memory register handling. This is complicated by 2545 // the fact that at least in kernels, the input argument is not necessarily 2546 // in the same location as the input. 2547 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2548 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2549 AMDGPUFunctionArgInfo::QUEUE_PTR, 2550 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2551 AMDGPUFunctionArgInfo::DISPATCH_ID, 2552 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2553 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2554 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2555 }; 2556 2557 for (auto InputID : InputRegs) { 2558 const ArgDescriptor *OutgoingArg; 2559 const TargetRegisterClass *ArgRC; 2560 2561 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID); 2562 if (!OutgoingArg) 2563 continue; 2564 2565 const ArgDescriptor *IncomingArg; 2566 const TargetRegisterClass *IncomingArgRC; 2567 std::tie(IncomingArg, IncomingArgRC) 2568 = CallerArgInfo.getPreloadedValue(InputID); 2569 assert(IncomingArgRC == ArgRC); 2570 2571 // All special arguments are ints for now. 2572 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2573 SDValue InputReg; 2574 2575 if (IncomingArg) { 2576 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2577 } else { 2578 // The implicit arg ptr is special because it doesn't have a corresponding 2579 // input for kernels, and is computed from the kernarg segment pointer. 2580 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2581 InputReg = getImplicitArgPtr(DAG, DL); 2582 } 2583 2584 if (OutgoingArg->isRegister()) { 2585 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2586 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2587 report_fatal_error("failed to allocate implicit input argument"); 2588 } else { 2589 unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4); 2590 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2591 SpecialArgOffset); 2592 MemOpChains.push_back(ArgStore); 2593 } 2594 } 2595 2596 // Pack workitem IDs into a single register or pass it as is if already 2597 // packed. 2598 const ArgDescriptor *OutgoingArg; 2599 const TargetRegisterClass *ArgRC; 2600 2601 std::tie(OutgoingArg, ArgRC) = 2602 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2603 if (!OutgoingArg) 2604 std::tie(OutgoingArg, ArgRC) = 2605 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2606 if (!OutgoingArg) 2607 std::tie(OutgoingArg, ArgRC) = 2608 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2609 if (!OutgoingArg) 2610 return; 2611 2612 const ArgDescriptor *IncomingArgX 2613 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first; 2614 const ArgDescriptor *IncomingArgY 2615 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first; 2616 const ArgDescriptor *IncomingArgZ 2617 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first; 2618 2619 SDValue InputReg; 2620 SDLoc SL; 2621 2622 // If incoming ids are not packed we need to pack them. 2623 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2624 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2625 2626 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2627 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2628 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2629 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2630 InputReg = InputReg.getNode() ? 2631 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2632 } 2633 2634 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2635 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2636 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2637 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2638 InputReg = InputReg.getNode() ? 2639 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2640 } 2641 2642 if (!InputReg.getNode()) { 2643 // Workitem ids are already packed, any of present incoming arguments 2644 // will carry all required fields. 2645 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2646 IncomingArgX ? *IncomingArgX : 2647 IncomingArgY ? *IncomingArgY : 2648 *IncomingArgZ, ~0u); 2649 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2650 } 2651 2652 if (OutgoingArg->isRegister()) { 2653 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2654 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2655 } else { 2656 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4); 2657 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2658 SpecialArgOffset); 2659 MemOpChains.push_back(ArgStore); 2660 } 2661 } 2662 2663 static bool canGuaranteeTCO(CallingConv::ID CC) { 2664 return CC == CallingConv::Fast; 2665 } 2666 2667 /// Return true if we might ever do TCO for calls with this calling convention. 2668 static bool mayTailCallThisCC(CallingConv::ID CC) { 2669 switch (CC) { 2670 case CallingConv::C: 2671 return true; 2672 default: 2673 return canGuaranteeTCO(CC); 2674 } 2675 } 2676 2677 bool SITargetLowering::isEligibleForTailCallOptimization( 2678 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2679 const SmallVectorImpl<ISD::OutputArg> &Outs, 2680 const SmallVectorImpl<SDValue> &OutVals, 2681 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2682 if (!mayTailCallThisCC(CalleeCC)) 2683 return false; 2684 2685 MachineFunction &MF = DAG.getMachineFunction(); 2686 const Function &CallerF = MF.getFunction(); 2687 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2688 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2689 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2690 2691 // Kernels aren't callable, and don't have a live in return address so it 2692 // doesn't make sense to do a tail call with entry functions. 2693 if (!CallerPreserved) 2694 return false; 2695 2696 bool CCMatch = CallerCC == CalleeCC; 2697 2698 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2699 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2700 return true; 2701 return false; 2702 } 2703 2704 // TODO: Can we handle var args? 2705 if (IsVarArg) 2706 return false; 2707 2708 for (const Argument &Arg : CallerF.args()) { 2709 if (Arg.hasByValAttr()) 2710 return false; 2711 } 2712 2713 LLVMContext &Ctx = *DAG.getContext(); 2714 2715 // Check that the call results are passed in the same way. 2716 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2717 CCAssignFnForCall(CalleeCC, IsVarArg), 2718 CCAssignFnForCall(CallerCC, IsVarArg))) 2719 return false; 2720 2721 // The callee has to preserve all registers the caller needs to preserve. 2722 if (!CCMatch) { 2723 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2724 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2725 return false; 2726 } 2727 2728 // Nothing more to check if the callee is taking no arguments. 2729 if (Outs.empty()) 2730 return true; 2731 2732 SmallVector<CCValAssign, 16> ArgLocs; 2733 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2734 2735 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2736 2737 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2738 // If the stack arguments for this call do not fit into our own save area then 2739 // the call cannot be made tail. 2740 // TODO: Is this really necessary? 2741 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2742 return false; 2743 2744 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2745 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2746 } 2747 2748 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2749 if (!CI->isTailCall()) 2750 return false; 2751 2752 const Function *ParentFn = CI->getParent()->getParent(); 2753 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2754 return false; 2755 return true; 2756 } 2757 2758 // The wave scratch offset register is used as the global base pointer. 2759 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2760 SmallVectorImpl<SDValue> &InVals) const { 2761 SelectionDAG &DAG = CLI.DAG; 2762 const SDLoc &DL = CLI.DL; 2763 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2764 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2765 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2766 SDValue Chain = CLI.Chain; 2767 SDValue Callee = CLI.Callee; 2768 bool &IsTailCall = CLI.IsTailCall; 2769 CallingConv::ID CallConv = CLI.CallConv; 2770 bool IsVarArg = CLI.IsVarArg; 2771 bool IsSibCall = false; 2772 bool IsThisReturn = false; 2773 MachineFunction &MF = DAG.getMachineFunction(); 2774 2775 if (Callee.isUndef() || isNullConstant(Callee)) { 2776 if (!CLI.IsTailCall) { 2777 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2778 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2779 } 2780 2781 return Chain; 2782 } 2783 2784 if (IsVarArg) { 2785 return lowerUnhandledCall(CLI, InVals, 2786 "unsupported call to variadic function "); 2787 } 2788 2789 if (!CLI.CB) 2790 report_fatal_error("unsupported libcall legalization"); 2791 2792 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2793 !CLI.CB->getCalledFunction()) { 2794 return lowerUnhandledCall(CLI, InVals, 2795 "unsupported indirect call to function "); 2796 } 2797 2798 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2799 return lowerUnhandledCall(CLI, InVals, 2800 "unsupported required tail call to function "); 2801 } 2802 2803 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2804 // Note the issue is with the CC of the calling function, not of the call 2805 // itself. 2806 return lowerUnhandledCall(CLI, InVals, 2807 "unsupported call from graphics shader of function "); 2808 } 2809 2810 if (IsTailCall) { 2811 IsTailCall = isEligibleForTailCallOptimization( 2812 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2813 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2814 report_fatal_error("failed to perform tail call elimination on a call " 2815 "site marked musttail"); 2816 } 2817 2818 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2819 2820 // A sibling call is one where we're under the usual C ABI and not planning 2821 // to change that but can still do a tail call: 2822 if (!TailCallOpt && IsTailCall) 2823 IsSibCall = true; 2824 2825 if (IsTailCall) 2826 ++NumTailCalls; 2827 } 2828 2829 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2830 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2831 SmallVector<SDValue, 8> MemOpChains; 2832 2833 // Analyze operands of the call, assigning locations to each operand. 2834 SmallVector<CCValAssign, 16> ArgLocs; 2835 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2836 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2837 2838 if (AMDGPUTargetMachine::EnableFixedFunctionABI) { 2839 // With a fixed ABI, allocate fixed registers before user arguments. 2840 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2841 } 2842 2843 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2844 2845 // Get a count of how many bytes are to be pushed on the stack. 2846 unsigned NumBytes = CCInfo.getNextStackOffset(); 2847 2848 if (IsSibCall) { 2849 // Since we're not changing the ABI to make this a tail call, the memory 2850 // operands are already available in the caller's incoming argument space. 2851 NumBytes = 0; 2852 } 2853 2854 // FPDiff is the byte offset of the call's argument area from the callee's. 2855 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2856 // by this amount for a tail call. In a sibling call it must be 0 because the 2857 // caller will deallocate the entire stack and the callee still expects its 2858 // arguments to begin at SP+0. Completely unused for non-tail calls. 2859 int32_t FPDiff = 0; 2860 MachineFrameInfo &MFI = MF.getFrameInfo(); 2861 2862 // Adjust the stack pointer for the new arguments... 2863 // These operations are automatically eliminated by the prolog/epilog pass 2864 if (!IsSibCall) { 2865 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2866 2867 SmallVector<SDValue, 4> CopyFromChains; 2868 2869 // In the HSA case, this should be an identity copy. 2870 SDValue ScratchRSrcReg 2871 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2872 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2873 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2874 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2875 } 2876 2877 MVT PtrVT = MVT::i32; 2878 2879 // Walk the register/memloc assignments, inserting copies/loads. 2880 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2881 CCValAssign &VA = ArgLocs[i]; 2882 SDValue Arg = OutVals[i]; 2883 2884 // Promote the value if needed. 2885 switch (VA.getLocInfo()) { 2886 case CCValAssign::Full: 2887 break; 2888 case CCValAssign::BCvt: 2889 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2890 break; 2891 case CCValAssign::ZExt: 2892 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2893 break; 2894 case CCValAssign::SExt: 2895 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2896 break; 2897 case CCValAssign::AExt: 2898 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2899 break; 2900 case CCValAssign::FPExt: 2901 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2902 break; 2903 default: 2904 llvm_unreachable("Unknown loc info!"); 2905 } 2906 2907 if (VA.isRegLoc()) { 2908 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2909 } else { 2910 assert(VA.isMemLoc()); 2911 2912 SDValue DstAddr; 2913 MachinePointerInfo DstInfo; 2914 2915 unsigned LocMemOffset = VA.getLocMemOffset(); 2916 int32_t Offset = LocMemOffset; 2917 2918 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2919 MaybeAlign Alignment; 2920 2921 if (IsTailCall) { 2922 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2923 unsigned OpSize = Flags.isByVal() ? 2924 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2925 2926 // FIXME: We can have better than the minimum byval required alignment. 2927 Alignment = 2928 Flags.isByVal() 2929 ? Flags.getNonZeroByValAlign() 2930 : commonAlignment(Subtarget->getStackAlignment(), Offset); 2931 2932 Offset = Offset + FPDiff; 2933 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2934 2935 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2936 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2937 2938 // Make sure any stack arguments overlapping with where we're storing 2939 // are loaded before this eventual operation. Otherwise they'll be 2940 // clobbered. 2941 2942 // FIXME: Why is this really necessary? This seems to just result in a 2943 // lot of code to copy the stack and write them back to the same 2944 // locations, which are supposed to be immutable? 2945 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2946 } else { 2947 DstAddr = PtrOff; 2948 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2949 Alignment = 2950 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 2951 } 2952 2953 if (Outs[i].Flags.isByVal()) { 2954 SDValue SizeNode = 2955 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2956 SDValue Cpy = 2957 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 2958 Outs[i].Flags.getNonZeroByValAlign(), 2959 /*isVol = */ false, /*AlwaysInline = */ true, 2960 /*isTailCall = */ false, DstInfo, 2961 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 2962 2963 MemOpChains.push_back(Cpy); 2964 } else { 2965 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 2966 Alignment ? Alignment->value() : 0); 2967 MemOpChains.push_back(Store); 2968 } 2969 } 2970 } 2971 2972 if (!AMDGPUTargetMachine::EnableFixedFunctionABI) { 2973 // Copy special input registers after user input arguments. 2974 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2975 } 2976 2977 if (!MemOpChains.empty()) 2978 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2979 2980 // Build a sequence of copy-to-reg nodes chained together with token chain 2981 // and flag operands which copy the outgoing args into the appropriate regs. 2982 SDValue InFlag; 2983 for (auto &RegToPass : RegsToPass) { 2984 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2985 RegToPass.second, InFlag); 2986 InFlag = Chain.getValue(1); 2987 } 2988 2989 2990 SDValue PhysReturnAddrReg; 2991 if (IsTailCall) { 2992 // Since the return is being combined with the call, we need to pass on the 2993 // return address. 2994 2995 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2996 SDValue ReturnAddrReg = CreateLiveInRegister( 2997 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2998 2999 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3000 MVT::i64); 3001 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3002 InFlag = Chain.getValue(1); 3003 } 3004 3005 // We don't usually want to end the call-sequence here because we would tidy 3006 // the frame up *after* the call, however in the ABI-changing tail-call case 3007 // we've carefully laid out the parameters so that when sp is reset they'll be 3008 // in the correct location. 3009 if (IsTailCall && !IsSibCall) { 3010 Chain = DAG.getCALLSEQ_END(Chain, 3011 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3012 DAG.getTargetConstant(0, DL, MVT::i32), 3013 InFlag, DL); 3014 InFlag = Chain.getValue(1); 3015 } 3016 3017 std::vector<SDValue> Ops; 3018 Ops.push_back(Chain); 3019 Ops.push_back(Callee); 3020 // Add a redundant copy of the callee global which will not be legalized, as 3021 // we need direct access to the callee later. 3022 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3023 const GlobalValue *GV = GSD->getGlobal(); 3024 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3025 } else { 3026 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3027 } 3028 3029 if (IsTailCall) { 3030 // Each tail call may have to adjust the stack by a different amount, so 3031 // this information must travel along with the operation for eventual 3032 // consumption by emitEpilogue. 3033 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3034 3035 Ops.push_back(PhysReturnAddrReg); 3036 } 3037 3038 // Add argument registers to the end of the list so that they are known live 3039 // into the call. 3040 for (auto &RegToPass : RegsToPass) { 3041 Ops.push_back(DAG.getRegister(RegToPass.first, 3042 RegToPass.second.getValueType())); 3043 } 3044 3045 // Add a register mask operand representing the call-preserved registers. 3046 3047 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3048 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3049 assert(Mask && "Missing call preserved mask for calling convention"); 3050 Ops.push_back(DAG.getRegisterMask(Mask)); 3051 3052 if (InFlag.getNode()) 3053 Ops.push_back(InFlag); 3054 3055 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3056 3057 // If we're doing a tall call, use a TC_RETURN here rather than an 3058 // actual call instruction. 3059 if (IsTailCall) { 3060 MFI.setHasTailCall(); 3061 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3062 } 3063 3064 // Returns a chain and a flag for retval copy to use. 3065 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3066 Chain = Call.getValue(0); 3067 InFlag = Call.getValue(1); 3068 3069 uint64_t CalleePopBytes = NumBytes; 3070 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3071 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3072 InFlag, DL); 3073 if (!Ins.empty()) 3074 InFlag = Chain.getValue(1); 3075 3076 // Handle result values, copying them out of physregs into vregs that we 3077 // return. 3078 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3079 InVals, IsThisReturn, 3080 IsThisReturn ? OutVals[0] : SDValue()); 3081 } 3082 3083 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3084 const MachineFunction &MF) const { 3085 Register Reg = StringSwitch<Register>(RegName) 3086 .Case("m0", AMDGPU::M0) 3087 .Case("exec", AMDGPU::EXEC) 3088 .Case("exec_lo", AMDGPU::EXEC_LO) 3089 .Case("exec_hi", AMDGPU::EXEC_HI) 3090 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3091 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3092 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3093 .Default(Register()); 3094 3095 if (Reg == AMDGPU::NoRegister) { 3096 report_fatal_error(Twine("invalid register name \"" 3097 + StringRef(RegName) + "\".")); 3098 3099 } 3100 3101 if (!Subtarget->hasFlatScrRegister() && 3102 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3103 report_fatal_error(Twine("invalid register \"" 3104 + StringRef(RegName) + "\" for subtarget.")); 3105 } 3106 3107 switch (Reg) { 3108 case AMDGPU::M0: 3109 case AMDGPU::EXEC_LO: 3110 case AMDGPU::EXEC_HI: 3111 case AMDGPU::FLAT_SCR_LO: 3112 case AMDGPU::FLAT_SCR_HI: 3113 if (VT.getSizeInBits() == 32) 3114 return Reg; 3115 break; 3116 case AMDGPU::EXEC: 3117 case AMDGPU::FLAT_SCR: 3118 if (VT.getSizeInBits() == 64) 3119 return Reg; 3120 break; 3121 default: 3122 llvm_unreachable("missing register type checking"); 3123 } 3124 3125 report_fatal_error(Twine("invalid type for register \"" 3126 + StringRef(RegName) + "\".")); 3127 } 3128 3129 // If kill is not the last instruction, split the block so kill is always a 3130 // proper terminator. 3131 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3132 MachineBasicBlock *BB) const { 3133 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3134 3135 MachineBasicBlock::iterator SplitPoint(&MI); 3136 ++SplitPoint; 3137 3138 if (SplitPoint == BB->end()) { 3139 // Don't bother with a new block. 3140 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3141 return BB; 3142 } 3143 3144 MachineFunction *MF = BB->getParent(); 3145 MachineBasicBlock *SplitBB 3146 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3147 3148 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3149 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3150 3151 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3152 BB->addSuccessor(SplitBB); 3153 3154 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3155 return SplitBB; 3156 } 3157 3158 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3159 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3160 // be the first instruction in the remainder block. 3161 // 3162 /// \returns { LoopBody, Remainder } 3163 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3164 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3165 MachineFunction *MF = MBB.getParent(); 3166 MachineBasicBlock::iterator I(&MI); 3167 3168 // To insert the loop we need to split the block. Move everything after this 3169 // point to a new block, and insert a new empty block between the two. 3170 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3171 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3172 MachineFunction::iterator MBBI(MBB); 3173 ++MBBI; 3174 3175 MF->insert(MBBI, LoopBB); 3176 MF->insert(MBBI, RemainderBB); 3177 3178 LoopBB->addSuccessor(LoopBB); 3179 LoopBB->addSuccessor(RemainderBB); 3180 3181 // Move the rest of the block into a new block. 3182 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3183 3184 if (InstInLoop) { 3185 auto Next = std::next(I); 3186 3187 // Move instruction to loop body. 3188 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3189 3190 // Move the rest of the block. 3191 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3192 } else { 3193 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3194 } 3195 3196 MBB.addSuccessor(LoopBB); 3197 3198 return std::make_pair(LoopBB, RemainderBB); 3199 } 3200 3201 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3202 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3203 MachineBasicBlock *MBB = MI.getParent(); 3204 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3205 auto I = MI.getIterator(); 3206 auto E = std::next(I); 3207 3208 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3209 .addImm(0); 3210 3211 MIBundleBuilder Bundler(*MBB, I, E); 3212 finalizeBundle(*MBB, Bundler.begin()); 3213 } 3214 3215 MachineBasicBlock * 3216 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3217 MachineBasicBlock *BB) const { 3218 const DebugLoc &DL = MI.getDebugLoc(); 3219 3220 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3221 3222 MachineBasicBlock *LoopBB; 3223 MachineBasicBlock *RemainderBB; 3224 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3225 3226 // Apparently kill flags are only valid if the def is in the same block? 3227 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3228 Src->setIsKill(false); 3229 3230 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3231 3232 MachineBasicBlock::iterator I = LoopBB->end(); 3233 3234 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3235 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3236 3237 // Clear TRAP_STS.MEM_VIOL 3238 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3239 .addImm(0) 3240 .addImm(EncodedReg); 3241 3242 bundleInstWithWaitcnt(MI); 3243 3244 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3245 3246 // Load and check TRAP_STS.MEM_VIOL 3247 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3248 .addImm(EncodedReg); 3249 3250 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3251 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3252 .addReg(Reg, RegState::Kill) 3253 .addImm(0); 3254 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3255 .addMBB(LoopBB); 3256 3257 return RemainderBB; 3258 } 3259 3260 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3261 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3262 // will only do one iteration. In the worst case, this will loop 64 times. 3263 // 3264 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3265 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3266 const SIInstrInfo *TII, 3267 MachineRegisterInfo &MRI, 3268 MachineBasicBlock &OrigBB, 3269 MachineBasicBlock &LoopBB, 3270 const DebugLoc &DL, 3271 const MachineOperand &IdxReg, 3272 unsigned InitReg, 3273 unsigned ResultReg, 3274 unsigned PhiReg, 3275 unsigned InitSaveExecReg, 3276 int Offset, 3277 bool UseGPRIdxMode, 3278 bool IsIndirectSrc) { 3279 MachineFunction *MF = OrigBB.getParent(); 3280 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3281 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3282 MachineBasicBlock::iterator I = LoopBB.begin(); 3283 3284 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3285 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3286 Register NewExec = MRI.createVirtualRegister(BoolRC); 3287 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3288 Register CondReg = MRI.createVirtualRegister(BoolRC); 3289 3290 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3291 .addReg(InitReg) 3292 .addMBB(&OrigBB) 3293 .addReg(ResultReg) 3294 .addMBB(&LoopBB); 3295 3296 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3297 .addReg(InitSaveExecReg) 3298 .addMBB(&OrigBB) 3299 .addReg(NewExec) 3300 .addMBB(&LoopBB); 3301 3302 // Read the next variant <- also loop target. 3303 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3304 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3305 3306 // Compare the just read M0 value to all possible Idx values. 3307 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3308 .addReg(CurrentIdxReg) 3309 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3310 3311 // Update EXEC, save the original EXEC value to VCC. 3312 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3313 : AMDGPU::S_AND_SAVEEXEC_B64), 3314 NewExec) 3315 .addReg(CondReg, RegState::Kill); 3316 3317 MRI.setSimpleHint(NewExec, CondReg); 3318 3319 if (UseGPRIdxMode) { 3320 unsigned IdxReg; 3321 if (Offset == 0) { 3322 IdxReg = CurrentIdxReg; 3323 } else { 3324 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3325 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3326 .addReg(CurrentIdxReg, RegState::Kill) 3327 .addImm(Offset); 3328 } 3329 unsigned IdxMode = IsIndirectSrc ? 3330 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3331 MachineInstr *SetOn = 3332 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3333 .addReg(IdxReg, RegState::Kill) 3334 .addImm(IdxMode); 3335 SetOn->getOperand(3).setIsUndef(); 3336 } else { 3337 // Move index from VCC into M0 3338 if (Offset == 0) { 3339 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3340 .addReg(CurrentIdxReg, RegState::Kill); 3341 } else { 3342 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3343 .addReg(CurrentIdxReg, RegState::Kill) 3344 .addImm(Offset); 3345 } 3346 } 3347 3348 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3349 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3350 MachineInstr *InsertPt = 3351 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3352 : AMDGPU::S_XOR_B64_term), Exec) 3353 .addReg(Exec) 3354 .addReg(NewExec); 3355 3356 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3357 // s_cbranch_scc0? 3358 3359 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3360 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3361 .addMBB(&LoopBB); 3362 3363 return InsertPt->getIterator(); 3364 } 3365 3366 // This has slightly sub-optimal regalloc when the source vector is killed by 3367 // the read. The register allocator does not understand that the kill is 3368 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3369 // subregister from it, using 1 more VGPR than necessary. This was saved when 3370 // this was expanded after register allocation. 3371 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3372 MachineBasicBlock &MBB, 3373 MachineInstr &MI, 3374 unsigned InitResultReg, 3375 unsigned PhiReg, 3376 int Offset, 3377 bool UseGPRIdxMode, 3378 bool IsIndirectSrc) { 3379 MachineFunction *MF = MBB.getParent(); 3380 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3381 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3382 MachineRegisterInfo &MRI = MF->getRegInfo(); 3383 const DebugLoc &DL = MI.getDebugLoc(); 3384 MachineBasicBlock::iterator I(&MI); 3385 3386 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3387 Register DstReg = MI.getOperand(0).getReg(); 3388 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3389 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3390 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3391 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3392 3393 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3394 3395 // Save the EXEC mask 3396 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3397 .addReg(Exec); 3398 3399 MachineBasicBlock *LoopBB; 3400 MachineBasicBlock *RemainderBB; 3401 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3402 3403 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3404 3405 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3406 InitResultReg, DstReg, PhiReg, TmpExec, 3407 Offset, UseGPRIdxMode, IsIndirectSrc); 3408 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3409 MachineFunction::iterator MBBI(LoopBB); 3410 ++MBBI; 3411 MF->insert(MBBI, LandingPad); 3412 LoopBB->removeSuccessor(RemainderBB); 3413 LandingPad->addSuccessor(RemainderBB); 3414 LoopBB->addSuccessor(LandingPad); 3415 MachineBasicBlock::iterator First = LandingPad->begin(); 3416 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3417 .addReg(SaveExec); 3418 3419 return InsPt; 3420 } 3421 3422 // Returns subreg index, offset 3423 static std::pair<unsigned, int> 3424 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3425 const TargetRegisterClass *SuperRC, 3426 unsigned VecReg, 3427 int Offset) { 3428 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3429 3430 // Skip out of bounds offsets, or else we would end up using an undefined 3431 // register. 3432 if (Offset >= NumElts || Offset < 0) 3433 return std::make_pair(AMDGPU::sub0, Offset); 3434 3435 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3436 } 3437 3438 // Return true if the index is an SGPR and was set. 3439 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3440 MachineRegisterInfo &MRI, 3441 MachineInstr &MI, 3442 int Offset, 3443 bool UseGPRIdxMode, 3444 bool IsIndirectSrc) { 3445 MachineBasicBlock *MBB = MI.getParent(); 3446 const DebugLoc &DL = MI.getDebugLoc(); 3447 MachineBasicBlock::iterator I(&MI); 3448 3449 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3450 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3451 3452 assert(Idx->getReg() != AMDGPU::NoRegister); 3453 3454 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3455 return false; 3456 3457 if (UseGPRIdxMode) { 3458 unsigned IdxMode = IsIndirectSrc ? 3459 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3460 if (Offset == 0) { 3461 MachineInstr *SetOn = 3462 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3463 .add(*Idx) 3464 .addImm(IdxMode); 3465 3466 SetOn->getOperand(3).setIsUndef(); 3467 } else { 3468 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3469 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3470 .add(*Idx) 3471 .addImm(Offset); 3472 MachineInstr *SetOn = 3473 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3474 .addReg(Tmp, RegState::Kill) 3475 .addImm(IdxMode); 3476 3477 SetOn->getOperand(3).setIsUndef(); 3478 } 3479 3480 return true; 3481 } 3482 3483 if (Offset == 0) { 3484 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3485 .add(*Idx); 3486 } else { 3487 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3488 .add(*Idx) 3489 .addImm(Offset); 3490 } 3491 3492 return true; 3493 } 3494 3495 // Control flow needs to be inserted if indexing with a VGPR. 3496 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3497 MachineBasicBlock &MBB, 3498 const GCNSubtarget &ST) { 3499 const SIInstrInfo *TII = ST.getInstrInfo(); 3500 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3501 MachineFunction *MF = MBB.getParent(); 3502 MachineRegisterInfo &MRI = MF->getRegInfo(); 3503 3504 Register Dst = MI.getOperand(0).getReg(); 3505 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3506 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3507 3508 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3509 3510 unsigned SubReg; 3511 std::tie(SubReg, Offset) 3512 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3513 3514 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3515 3516 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3517 MachineBasicBlock::iterator I(&MI); 3518 const DebugLoc &DL = MI.getDebugLoc(); 3519 3520 if (UseGPRIdxMode) { 3521 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3522 // to avoid interfering with other uses, so probably requires a new 3523 // optimization pass. 3524 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3525 .addReg(SrcReg, RegState::Undef, SubReg) 3526 .addReg(SrcReg, RegState::Implicit) 3527 .addReg(AMDGPU::M0, RegState::Implicit); 3528 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3529 } else { 3530 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3531 .addReg(SrcReg, RegState::Undef, SubReg) 3532 .addReg(SrcReg, RegState::Implicit); 3533 } 3534 3535 MI.eraseFromParent(); 3536 3537 return &MBB; 3538 } 3539 3540 const DebugLoc &DL = MI.getDebugLoc(); 3541 MachineBasicBlock::iterator I(&MI); 3542 3543 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3544 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3545 3546 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3547 3548 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3549 Offset, UseGPRIdxMode, true); 3550 MachineBasicBlock *LoopBB = InsPt->getParent(); 3551 3552 if (UseGPRIdxMode) { 3553 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3554 .addReg(SrcReg, RegState::Undef, SubReg) 3555 .addReg(SrcReg, RegState::Implicit) 3556 .addReg(AMDGPU::M0, RegState::Implicit); 3557 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3558 } else { 3559 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3560 .addReg(SrcReg, RegState::Undef, SubReg) 3561 .addReg(SrcReg, RegState::Implicit); 3562 } 3563 3564 MI.eraseFromParent(); 3565 3566 return LoopBB; 3567 } 3568 3569 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3570 MachineBasicBlock &MBB, 3571 const GCNSubtarget &ST) { 3572 const SIInstrInfo *TII = ST.getInstrInfo(); 3573 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3574 MachineFunction *MF = MBB.getParent(); 3575 MachineRegisterInfo &MRI = MF->getRegInfo(); 3576 3577 Register Dst = MI.getOperand(0).getReg(); 3578 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3579 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3580 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3581 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3582 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3583 3584 // This can be an immediate, but will be folded later. 3585 assert(Val->getReg()); 3586 3587 unsigned SubReg; 3588 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3589 SrcVec->getReg(), 3590 Offset); 3591 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3592 3593 if (Idx->getReg() == AMDGPU::NoRegister) { 3594 MachineBasicBlock::iterator I(&MI); 3595 const DebugLoc &DL = MI.getDebugLoc(); 3596 3597 assert(Offset == 0); 3598 3599 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3600 .add(*SrcVec) 3601 .add(*Val) 3602 .addImm(SubReg); 3603 3604 MI.eraseFromParent(); 3605 return &MBB; 3606 } 3607 3608 const MCInstrDesc &MovRelDesc 3609 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3610 3611 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3612 MachineBasicBlock::iterator I(&MI); 3613 const DebugLoc &DL = MI.getDebugLoc(); 3614 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3615 .addReg(SrcVec->getReg()) 3616 .add(*Val) 3617 .addImm(SubReg); 3618 if (UseGPRIdxMode) 3619 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3620 3621 MI.eraseFromParent(); 3622 return &MBB; 3623 } 3624 3625 if (Val->isReg()) 3626 MRI.clearKillFlags(Val->getReg()); 3627 3628 const DebugLoc &DL = MI.getDebugLoc(); 3629 3630 Register PhiReg = MRI.createVirtualRegister(VecRC); 3631 3632 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3633 Offset, UseGPRIdxMode, false); 3634 MachineBasicBlock *LoopBB = InsPt->getParent(); 3635 3636 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3637 .addReg(PhiReg) 3638 .add(*Val) 3639 .addImm(AMDGPU::sub0); 3640 if (UseGPRIdxMode) 3641 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3642 3643 MI.eraseFromParent(); 3644 return LoopBB; 3645 } 3646 3647 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3648 MachineInstr &MI, MachineBasicBlock *BB) const { 3649 3650 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3651 MachineFunction *MF = BB->getParent(); 3652 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3653 3654 if (TII->isMIMG(MI)) { 3655 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 3656 report_fatal_error("missing mem operand from MIMG instruction"); 3657 } 3658 // Add a memoperand for mimg instructions so that they aren't assumed to 3659 // be ordered memory instuctions. 3660 3661 return BB; 3662 } 3663 3664 switch (MI.getOpcode()) { 3665 case AMDGPU::S_UADDO_PSEUDO: 3666 case AMDGPU::S_USUBO_PSEUDO: { 3667 const DebugLoc &DL = MI.getDebugLoc(); 3668 MachineOperand &Dest0 = MI.getOperand(0); 3669 MachineOperand &Dest1 = MI.getOperand(1); 3670 MachineOperand &Src0 = MI.getOperand(2); 3671 MachineOperand &Src1 = MI.getOperand(3); 3672 3673 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3674 ? AMDGPU::S_ADD_I32 3675 : AMDGPU::S_SUB_I32; 3676 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3677 3678 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3679 .addImm(1) 3680 .addImm(0); 3681 3682 MI.eraseFromParent(); 3683 return BB; 3684 } 3685 case AMDGPU::S_ADD_U64_PSEUDO: 3686 case AMDGPU::S_SUB_U64_PSEUDO: { 3687 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3688 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3689 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3690 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3691 const DebugLoc &DL = MI.getDebugLoc(); 3692 3693 MachineOperand &Dest = MI.getOperand(0); 3694 MachineOperand &Src0 = MI.getOperand(1); 3695 MachineOperand &Src1 = MI.getOperand(2); 3696 3697 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3698 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3699 3700 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3701 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3702 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3703 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3704 3705 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3706 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3707 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3708 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3709 3710 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3711 3712 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3713 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3714 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3715 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3716 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3717 .addReg(DestSub0) 3718 .addImm(AMDGPU::sub0) 3719 .addReg(DestSub1) 3720 .addImm(AMDGPU::sub1); 3721 MI.eraseFromParent(); 3722 return BB; 3723 } 3724 case AMDGPU::V_ADD_U64_PSEUDO: 3725 case AMDGPU::V_SUB_U64_PSEUDO: { 3726 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3727 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3728 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3729 const DebugLoc &DL = MI.getDebugLoc(); 3730 3731 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3732 3733 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3734 3735 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3736 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3737 3738 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3739 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3740 3741 MachineOperand &Dest = MI.getOperand(0); 3742 MachineOperand &Src0 = MI.getOperand(1); 3743 MachineOperand &Src1 = MI.getOperand(2); 3744 3745 const TargetRegisterClass *Src0RC = Src0.isReg() 3746 ? MRI.getRegClass(Src0.getReg()) 3747 : &AMDGPU::VReg_64RegClass; 3748 const TargetRegisterClass *Src1RC = Src1.isReg() 3749 ? MRI.getRegClass(Src1.getReg()) 3750 : &AMDGPU::VReg_64RegClass; 3751 3752 const TargetRegisterClass *Src0SubRC = 3753 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3754 const TargetRegisterClass *Src1SubRC = 3755 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3756 3757 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3758 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3759 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3760 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3761 3762 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3763 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3764 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3765 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3766 3767 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64; 3768 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3769 .addReg(CarryReg, RegState::Define) 3770 .add(SrcReg0Sub0) 3771 .add(SrcReg1Sub0) 3772 .addImm(0); // clamp bit 3773 3774 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3775 MachineInstr *HiHalf = 3776 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3777 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3778 .add(SrcReg0Sub1) 3779 .add(SrcReg1Sub1) 3780 .addReg(CarryReg, RegState::Kill) 3781 .addImm(0); // clamp bit 3782 3783 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3784 .addReg(DestSub0) 3785 .addImm(AMDGPU::sub0) 3786 .addReg(DestSub1) 3787 .addImm(AMDGPU::sub1); 3788 TII->legalizeOperands(*LoHalf); 3789 TII->legalizeOperands(*HiHalf); 3790 MI.eraseFromParent(); 3791 return BB; 3792 } 3793 case AMDGPU::S_ADD_CO_PSEUDO: 3794 case AMDGPU::S_SUB_CO_PSEUDO: { 3795 // This pseudo has a chance to be selected 3796 // only from uniform add/subcarry node. All the VGPR operands 3797 // therefore assumed to be splat vectors. 3798 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3799 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3800 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3801 MachineBasicBlock::iterator MII = MI; 3802 const DebugLoc &DL = MI.getDebugLoc(); 3803 MachineOperand &Dest = MI.getOperand(0); 3804 MachineOperand &Src0 = MI.getOperand(2); 3805 MachineOperand &Src1 = MI.getOperand(3); 3806 MachineOperand &Src2 = MI.getOperand(4); 3807 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 3808 ? AMDGPU::S_ADDC_U32 3809 : AMDGPU::S_SUBB_U32; 3810 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 3811 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3812 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 3813 .addReg(Src0.getReg()); 3814 Src0.setReg(RegOp0); 3815 } 3816 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 3817 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3818 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 3819 .addReg(Src1.getReg()); 3820 Src1.setReg(RegOp1); 3821 } 3822 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3823 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 3824 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 3825 .addReg(Src2.getReg()); 3826 Src2.setReg(RegOp2); 3827 } 3828 3829 if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) { 3830 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 3831 .addReg(Src2.getReg()) 3832 .addImm(0); 3833 } else { 3834 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 3835 .addReg(Src2.getReg()) 3836 .addImm(0); 3837 } 3838 3839 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 3840 MI.eraseFromParent(); 3841 return BB; 3842 } 3843 case AMDGPU::SI_INIT_M0: { 3844 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3845 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3846 .add(MI.getOperand(0)); 3847 MI.eraseFromParent(); 3848 return BB; 3849 } 3850 case AMDGPU::SI_INIT_EXEC: 3851 // This should be before all vector instructions. 3852 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3853 AMDGPU::EXEC) 3854 .addImm(MI.getOperand(0).getImm()); 3855 MI.eraseFromParent(); 3856 return BB; 3857 3858 case AMDGPU::SI_INIT_EXEC_LO: 3859 // This should be before all vector instructions. 3860 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3861 AMDGPU::EXEC_LO) 3862 .addImm(MI.getOperand(0).getImm()); 3863 MI.eraseFromParent(); 3864 return BB; 3865 3866 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3867 // Extract the thread count from an SGPR input and set EXEC accordingly. 3868 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3869 // 3870 // S_BFE_U32 count, input, {shift, 7} 3871 // S_BFM_B64 exec, count, 0 3872 // S_CMP_EQ_U32 count, 64 3873 // S_CMOV_B64 exec, -1 3874 MachineInstr *FirstMI = &*BB->begin(); 3875 MachineRegisterInfo &MRI = MF->getRegInfo(); 3876 Register InputReg = MI.getOperand(0).getReg(); 3877 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3878 bool Found = false; 3879 3880 // Move the COPY of the input reg to the beginning, so that we can use it. 3881 for (auto I = BB->begin(); I != &MI; I++) { 3882 if (I->getOpcode() != TargetOpcode::COPY || 3883 I->getOperand(0).getReg() != InputReg) 3884 continue; 3885 3886 if (I == FirstMI) { 3887 FirstMI = &*++BB->begin(); 3888 } else { 3889 I->removeFromParent(); 3890 BB->insert(FirstMI, &*I); 3891 } 3892 Found = true; 3893 break; 3894 } 3895 assert(Found); 3896 (void)Found; 3897 3898 // This should be before all vector instructions. 3899 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3900 bool isWave32 = getSubtarget()->isWave32(); 3901 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3902 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3903 .addReg(InputReg) 3904 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3905 BuildMI(*BB, FirstMI, DebugLoc(), 3906 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3907 Exec) 3908 .addReg(CountReg) 3909 .addImm(0); 3910 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3911 .addReg(CountReg, RegState::Kill) 3912 .addImm(getSubtarget()->getWavefrontSize()); 3913 BuildMI(*BB, FirstMI, DebugLoc(), 3914 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3915 Exec) 3916 .addImm(-1); 3917 MI.eraseFromParent(); 3918 return BB; 3919 } 3920 3921 case AMDGPU::GET_GROUPSTATICSIZE: { 3922 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 3923 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 3924 DebugLoc DL = MI.getDebugLoc(); 3925 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3926 .add(MI.getOperand(0)) 3927 .addImm(MFI->getLDSSize()); 3928 MI.eraseFromParent(); 3929 return BB; 3930 } 3931 case AMDGPU::SI_INDIRECT_SRC_V1: 3932 case AMDGPU::SI_INDIRECT_SRC_V2: 3933 case AMDGPU::SI_INDIRECT_SRC_V4: 3934 case AMDGPU::SI_INDIRECT_SRC_V8: 3935 case AMDGPU::SI_INDIRECT_SRC_V16: 3936 case AMDGPU::SI_INDIRECT_SRC_V32: 3937 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3938 case AMDGPU::SI_INDIRECT_DST_V1: 3939 case AMDGPU::SI_INDIRECT_DST_V2: 3940 case AMDGPU::SI_INDIRECT_DST_V4: 3941 case AMDGPU::SI_INDIRECT_DST_V8: 3942 case AMDGPU::SI_INDIRECT_DST_V16: 3943 case AMDGPU::SI_INDIRECT_DST_V32: 3944 return emitIndirectDst(MI, *BB, *getSubtarget()); 3945 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3946 case AMDGPU::SI_KILL_I1_PSEUDO: 3947 return splitKillBlock(MI, BB); 3948 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3949 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3950 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3951 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3952 3953 Register Dst = MI.getOperand(0).getReg(); 3954 Register Src0 = MI.getOperand(1).getReg(); 3955 Register Src1 = MI.getOperand(2).getReg(); 3956 const DebugLoc &DL = MI.getDebugLoc(); 3957 Register SrcCond = MI.getOperand(3).getReg(); 3958 3959 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3960 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3961 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3962 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 3963 3964 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3965 .addReg(SrcCond); 3966 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3967 .addImm(0) 3968 .addReg(Src0, 0, AMDGPU::sub0) 3969 .addImm(0) 3970 .addReg(Src1, 0, AMDGPU::sub0) 3971 .addReg(SrcCondCopy); 3972 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3973 .addImm(0) 3974 .addReg(Src0, 0, AMDGPU::sub1) 3975 .addImm(0) 3976 .addReg(Src1, 0, AMDGPU::sub1) 3977 .addReg(SrcCondCopy); 3978 3979 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3980 .addReg(DstLo) 3981 .addImm(AMDGPU::sub0) 3982 .addReg(DstHi) 3983 .addImm(AMDGPU::sub1); 3984 MI.eraseFromParent(); 3985 return BB; 3986 } 3987 case AMDGPU::SI_BR_UNDEF: { 3988 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3989 const DebugLoc &DL = MI.getDebugLoc(); 3990 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3991 .add(MI.getOperand(0)); 3992 Br->getOperand(1).setIsUndef(true); // read undef SCC 3993 MI.eraseFromParent(); 3994 return BB; 3995 } 3996 case AMDGPU::ADJCALLSTACKUP: 3997 case AMDGPU::ADJCALLSTACKDOWN: { 3998 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3999 MachineInstrBuilder MIB(*MF, &MI); 4000 4001 // Add an implicit use of the frame offset reg to prevent the restore copy 4002 // inserted after the call from being reorderd after stack operations in the 4003 // the caller's frame. 4004 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4005 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 4006 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 4007 return BB; 4008 } 4009 case AMDGPU::SI_CALL_ISEL: { 4010 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4011 const DebugLoc &DL = MI.getDebugLoc(); 4012 4013 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4014 4015 MachineInstrBuilder MIB; 4016 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4017 4018 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4019 MIB.add(MI.getOperand(I)); 4020 4021 MIB.cloneMemRefs(MI); 4022 MI.eraseFromParent(); 4023 return BB; 4024 } 4025 case AMDGPU::V_ADD_I32_e32: 4026 case AMDGPU::V_SUB_I32_e32: 4027 case AMDGPU::V_SUBREV_I32_e32: { 4028 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4029 const DebugLoc &DL = MI.getDebugLoc(); 4030 unsigned Opc = MI.getOpcode(); 4031 4032 bool NeedClampOperand = false; 4033 if (TII->pseudoToMCOpcode(Opc) == -1) { 4034 Opc = AMDGPU::getVOPe64(Opc); 4035 NeedClampOperand = true; 4036 } 4037 4038 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4039 if (TII->isVOP3(*I)) { 4040 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4041 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4042 I.addReg(TRI->getVCC(), RegState::Define); 4043 } 4044 I.add(MI.getOperand(1)) 4045 .add(MI.getOperand(2)); 4046 if (NeedClampOperand) 4047 I.addImm(0); // clamp bit for e64 encoding 4048 4049 TII->legalizeOperands(*I); 4050 4051 MI.eraseFromParent(); 4052 return BB; 4053 } 4054 case AMDGPU::DS_GWS_INIT: 4055 case AMDGPU::DS_GWS_SEMA_V: 4056 case AMDGPU::DS_GWS_SEMA_BR: 4057 case AMDGPU::DS_GWS_SEMA_P: 4058 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4059 case AMDGPU::DS_GWS_BARRIER: 4060 // A s_waitcnt 0 is required to be the instruction immediately following. 4061 if (getSubtarget()->hasGWSAutoReplay()) { 4062 bundleInstWithWaitcnt(MI); 4063 return BB; 4064 } 4065 4066 return emitGWSMemViolTestLoop(MI, BB); 4067 default: 4068 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4069 } 4070 } 4071 4072 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4073 return isTypeLegal(VT.getScalarType()); 4074 } 4075 4076 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4077 // This currently forces unfolding various combinations of fsub into fma with 4078 // free fneg'd operands. As long as we have fast FMA (controlled by 4079 // isFMAFasterThanFMulAndFAdd), we should perform these. 4080 4081 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4082 // most of these combines appear to be cycle neutral but save on instruction 4083 // count / code size. 4084 return true; 4085 } 4086 4087 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4088 EVT VT) const { 4089 if (!VT.isVector()) { 4090 return MVT::i1; 4091 } 4092 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4093 } 4094 4095 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4096 // TODO: Should i16 be used always if legal? For now it would force VALU 4097 // shifts. 4098 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4099 } 4100 4101 // Answering this is somewhat tricky and depends on the specific device which 4102 // have different rates for fma or all f64 operations. 4103 // 4104 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4105 // regardless of which device (although the number of cycles differs between 4106 // devices), so it is always profitable for f64. 4107 // 4108 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4109 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4110 // which we can always do even without fused FP ops since it returns the same 4111 // result as the separate operations and since it is always full 4112 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4113 // however does not support denormals, so we do report fma as faster if we have 4114 // a fast fma device and require denormals. 4115 // 4116 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4117 EVT VT) const { 4118 VT = VT.getScalarType(); 4119 4120 switch (VT.getSimpleVT().SimpleTy) { 4121 case MVT::f32: { 4122 // This is as fast on some subtargets. However, we always have full rate f32 4123 // mad available which returns the same result as the separate operations 4124 // which we should prefer over fma. We can't use this if we want to support 4125 // denormals, so only report this in these cases. 4126 if (hasFP32Denormals(MF)) 4127 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4128 4129 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4130 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4131 } 4132 case MVT::f64: 4133 return true; 4134 case MVT::f16: 4135 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4136 default: 4137 break; 4138 } 4139 4140 return false; 4141 } 4142 4143 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4144 const SDNode *N) const { 4145 // TODO: Check future ftz flag 4146 // v_mad_f32/v_mac_f32 do not support denormals. 4147 EVT VT = N->getValueType(0); 4148 if (VT == MVT::f32) 4149 return !hasFP32Denormals(DAG.getMachineFunction()); 4150 if (VT == MVT::f16) { 4151 return Subtarget->hasMadF16() && 4152 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4153 } 4154 4155 return false; 4156 } 4157 4158 //===----------------------------------------------------------------------===// 4159 // Custom DAG Lowering Operations 4160 //===----------------------------------------------------------------------===// 4161 4162 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4163 // wider vector type is legal. 4164 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4165 SelectionDAG &DAG) const { 4166 unsigned Opc = Op.getOpcode(); 4167 EVT VT = Op.getValueType(); 4168 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4169 4170 SDValue Lo, Hi; 4171 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4172 4173 SDLoc SL(Op); 4174 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4175 Op->getFlags()); 4176 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4177 Op->getFlags()); 4178 4179 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4180 } 4181 4182 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4183 // wider vector type is legal. 4184 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4185 SelectionDAG &DAG) const { 4186 unsigned Opc = Op.getOpcode(); 4187 EVT VT = Op.getValueType(); 4188 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4189 4190 SDValue Lo0, Hi0; 4191 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4192 SDValue Lo1, Hi1; 4193 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4194 4195 SDLoc SL(Op); 4196 4197 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4198 Op->getFlags()); 4199 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4200 Op->getFlags()); 4201 4202 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4203 } 4204 4205 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4206 SelectionDAG &DAG) const { 4207 unsigned Opc = Op.getOpcode(); 4208 EVT VT = Op.getValueType(); 4209 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4210 4211 SDValue Lo0, Hi0; 4212 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4213 SDValue Lo1, Hi1; 4214 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4215 SDValue Lo2, Hi2; 4216 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4217 4218 SDLoc SL(Op); 4219 4220 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4221 Op->getFlags()); 4222 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4223 Op->getFlags()); 4224 4225 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4226 } 4227 4228 4229 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4230 switch (Op.getOpcode()) { 4231 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4232 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4233 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4234 case ISD::LOAD: { 4235 SDValue Result = LowerLOAD(Op, DAG); 4236 assert((!Result.getNode() || 4237 Result.getNode()->getNumValues() == 2) && 4238 "Load should return a value and a chain"); 4239 return Result; 4240 } 4241 4242 case ISD::FSIN: 4243 case ISD::FCOS: 4244 return LowerTrig(Op, DAG); 4245 case ISD::SELECT: return LowerSELECT(Op, DAG); 4246 case ISD::FDIV: return LowerFDIV(Op, DAG); 4247 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4248 case ISD::STORE: return LowerSTORE(Op, DAG); 4249 case ISD::GlobalAddress: { 4250 MachineFunction &MF = DAG.getMachineFunction(); 4251 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4252 return LowerGlobalAddress(MFI, Op, DAG); 4253 } 4254 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4255 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4256 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4257 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4258 case ISD::INSERT_SUBVECTOR: 4259 return lowerINSERT_SUBVECTOR(Op, DAG); 4260 case ISD::INSERT_VECTOR_ELT: 4261 return lowerINSERT_VECTOR_ELT(Op, DAG); 4262 case ISD::EXTRACT_VECTOR_ELT: 4263 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4264 case ISD::VECTOR_SHUFFLE: 4265 return lowerVECTOR_SHUFFLE(Op, DAG); 4266 case ISD::BUILD_VECTOR: 4267 return lowerBUILD_VECTOR(Op, DAG); 4268 case ISD::FP_ROUND: 4269 return lowerFP_ROUND(Op, DAG); 4270 case ISD::TRAP: 4271 return lowerTRAP(Op, DAG); 4272 case ISD::DEBUGTRAP: 4273 return lowerDEBUGTRAP(Op, DAG); 4274 case ISD::FABS: 4275 case ISD::FNEG: 4276 case ISD::FCANONICALIZE: 4277 case ISD::BSWAP: 4278 return splitUnaryVectorOp(Op, DAG); 4279 case ISD::FMINNUM: 4280 case ISD::FMAXNUM: 4281 return lowerFMINNUM_FMAXNUM(Op, DAG); 4282 case ISD::FMA: 4283 return splitTernaryVectorOp(Op, DAG); 4284 case ISD::SHL: 4285 case ISD::SRA: 4286 case ISD::SRL: 4287 case ISD::ADD: 4288 case ISD::SUB: 4289 case ISD::MUL: 4290 case ISD::SMIN: 4291 case ISD::SMAX: 4292 case ISD::UMIN: 4293 case ISD::UMAX: 4294 case ISD::FADD: 4295 case ISD::FMUL: 4296 case ISD::FMINNUM_IEEE: 4297 case ISD::FMAXNUM_IEEE: 4298 return splitBinaryVectorOp(Op, DAG); 4299 } 4300 return SDValue(); 4301 } 4302 4303 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4304 const SDLoc &DL, 4305 SelectionDAG &DAG, bool Unpacked) { 4306 if (!LoadVT.isVector()) 4307 return Result; 4308 4309 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4310 // Truncate to v2i16/v4i16. 4311 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4312 4313 // Workaround legalizer not scalarizing truncate after vector op 4314 // legalization byt not creating intermediate vector trunc. 4315 SmallVector<SDValue, 4> Elts; 4316 DAG.ExtractVectorElements(Result, Elts); 4317 for (SDValue &Elt : Elts) 4318 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4319 4320 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4321 4322 // Bitcast to original type (v2f16/v4f16). 4323 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4324 } 4325 4326 // Cast back to the original packed type. 4327 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4328 } 4329 4330 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4331 MemSDNode *M, 4332 SelectionDAG &DAG, 4333 ArrayRef<SDValue> Ops, 4334 bool IsIntrinsic) const { 4335 SDLoc DL(M); 4336 4337 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4338 EVT LoadVT = M->getValueType(0); 4339 4340 EVT EquivLoadVT = LoadVT; 4341 if (Unpacked && LoadVT.isVector()) { 4342 EquivLoadVT = LoadVT.isVector() ? 4343 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4344 LoadVT.getVectorNumElements()) : LoadVT; 4345 } 4346 4347 // Change from v4f16/v2f16 to EquivLoadVT. 4348 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4349 4350 SDValue Load 4351 = DAG.getMemIntrinsicNode( 4352 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4353 VTList, Ops, M->getMemoryVT(), 4354 M->getMemOperand()); 4355 if (!Unpacked) // Just adjusted the opcode. 4356 return Load; 4357 4358 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4359 4360 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4361 } 4362 4363 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4364 SelectionDAG &DAG, 4365 ArrayRef<SDValue> Ops) const { 4366 SDLoc DL(M); 4367 EVT LoadVT = M->getValueType(0); 4368 EVT EltType = LoadVT.getScalarType(); 4369 EVT IntVT = LoadVT.changeTypeToInteger(); 4370 4371 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4372 4373 unsigned Opc = 4374 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4375 4376 if (IsD16) { 4377 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4378 } 4379 4380 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4381 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4382 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4383 4384 if (isTypeLegal(LoadVT)) { 4385 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4386 M->getMemOperand(), DAG); 4387 } 4388 4389 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4390 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4391 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4392 M->getMemOperand(), DAG); 4393 return DAG.getMergeValues( 4394 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4395 DL); 4396 } 4397 4398 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4399 SDNode *N, SelectionDAG &DAG) { 4400 EVT VT = N->getValueType(0); 4401 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4402 int CondCode = CD->getSExtValue(); 4403 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4404 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4405 return DAG.getUNDEF(VT); 4406 4407 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4408 4409 SDValue LHS = N->getOperand(1); 4410 SDValue RHS = N->getOperand(2); 4411 4412 SDLoc DL(N); 4413 4414 EVT CmpVT = LHS.getValueType(); 4415 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4416 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4417 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4418 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4419 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4420 } 4421 4422 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4423 4424 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4425 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4426 4427 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4428 DAG.getCondCode(CCOpcode)); 4429 if (VT.bitsEq(CCVT)) 4430 return SetCC; 4431 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4432 } 4433 4434 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4435 SDNode *N, SelectionDAG &DAG) { 4436 EVT VT = N->getValueType(0); 4437 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4438 4439 int CondCode = CD->getSExtValue(); 4440 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4441 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4442 return DAG.getUNDEF(VT); 4443 } 4444 4445 SDValue Src0 = N->getOperand(1); 4446 SDValue Src1 = N->getOperand(2); 4447 EVT CmpVT = Src0.getValueType(); 4448 SDLoc SL(N); 4449 4450 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4451 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4452 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4453 } 4454 4455 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4456 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4457 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4458 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4459 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4460 Src1, DAG.getCondCode(CCOpcode)); 4461 if (VT.bitsEq(CCVT)) 4462 return SetCC; 4463 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4464 } 4465 4466 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4467 SelectionDAG &DAG) { 4468 EVT VT = N->getValueType(0); 4469 SDValue Src = N->getOperand(1); 4470 SDLoc SL(N); 4471 4472 if (Src.getOpcode() == ISD::SETCC) { 4473 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4474 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4475 Src.getOperand(1), Src.getOperand(2)); 4476 } 4477 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4478 // (ballot 0) -> 0 4479 if (Arg->isNullValue()) 4480 return DAG.getConstant(0, SL, VT); 4481 4482 // (ballot 1) -> EXEC/EXEC_LO 4483 if (Arg->isOne()) { 4484 Register Exec; 4485 if (VT.getScalarSizeInBits() == 32) 4486 Exec = AMDGPU::EXEC_LO; 4487 else if (VT.getScalarSizeInBits() == 64) 4488 Exec = AMDGPU::EXEC; 4489 else 4490 return SDValue(); 4491 4492 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4493 } 4494 } 4495 4496 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4497 // ISD::SETNE) 4498 return DAG.getNode( 4499 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4500 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4501 } 4502 4503 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4504 SmallVectorImpl<SDValue> &Results, 4505 SelectionDAG &DAG) const { 4506 switch (N->getOpcode()) { 4507 case ISD::INSERT_VECTOR_ELT: { 4508 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4509 Results.push_back(Res); 4510 return; 4511 } 4512 case ISD::EXTRACT_VECTOR_ELT: { 4513 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4514 Results.push_back(Res); 4515 return; 4516 } 4517 case ISD::INTRINSIC_WO_CHAIN: { 4518 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4519 switch (IID) { 4520 case Intrinsic::amdgcn_cvt_pkrtz: { 4521 SDValue Src0 = N->getOperand(1); 4522 SDValue Src1 = N->getOperand(2); 4523 SDLoc SL(N); 4524 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4525 Src0, Src1); 4526 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4527 return; 4528 } 4529 case Intrinsic::amdgcn_cvt_pknorm_i16: 4530 case Intrinsic::amdgcn_cvt_pknorm_u16: 4531 case Intrinsic::amdgcn_cvt_pk_i16: 4532 case Intrinsic::amdgcn_cvt_pk_u16: { 4533 SDValue Src0 = N->getOperand(1); 4534 SDValue Src1 = N->getOperand(2); 4535 SDLoc SL(N); 4536 unsigned Opcode; 4537 4538 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4539 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4540 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4541 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4542 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4543 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4544 else 4545 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4546 4547 EVT VT = N->getValueType(0); 4548 if (isTypeLegal(VT)) 4549 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4550 else { 4551 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4552 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4553 } 4554 return; 4555 } 4556 } 4557 break; 4558 } 4559 case ISD::INTRINSIC_W_CHAIN: { 4560 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4561 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4562 // FIXME: Hacky 4563 Results.push_back(Res.getOperand(0)); 4564 Results.push_back(Res.getOperand(1)); 4565 } else { 4566 Results.push_back(Res); 4567 Results.push_back(Res.getValue(1)); 4568 } 4569 return; 4570 } 4571 4572 break; 4573 } 4574 case ISD::SELECT: { 4575 SDLoc SL(N); 4576 EVT VT = N->getValueType(0); 4577 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4578 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4579 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4580 4581 EVT SelectVT = NewVT; 4582 if (NewVT.bitsLT(MVT::i32)) { 4583 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4584 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4585 SelectVT = MVT::i32; 4586 } 4587 4588 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4589 N->getOperand(0), LHS, RHS); 4590 4591 if (NewVT != SelectVT) 4592 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4593 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4594 return; 4595 } 4596 case ISD::FNEG: { 4597 if (N->getValueType(0) != MVT::v2f16) 4598 break; 4599 4600 SDLoc SL(N); 4601 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4602 4603 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4604 BC, 4605 DAG.getConstant(0x80008000, SL, MVT::i32)); 4606 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4607 return; 4608 } 4609 case ISD::FABS: { 4610 if (N->getValueType(0) != MVT::v2f16) 4611 break; 4612 4613 SDLoc SL(N); 4614 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4615 4616 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4617 BC, 4618 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4619 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4620 return; 4621 } 4622 default: 4623 break; 4624 } 4625 } 4626 4627 /// Helper function for LowerBRCOND 4628 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4629 4630 SDNode *Parent = Value.getNode(); 4631 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4632 I != E; ++I) { 4633 4634 if (I.getUse().get() != Value) 4635 continue; 4636 4637 if (I->getOpcode() == Opcode) 4638 return *I; 4639 } 4640 return nullptr; 4641 } 4642 4643 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4644 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4645 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4646 case Intrinsic::amdgcn_if: 4647 return AMDGPUISD::IF; 4648 case Intrinsic::amdgcn_else: 4649 return AMDGPUISD::ELSE; 4650 case Intrinsic::amdgcn_loop: 4651 return AMDGPUISD::LOOP; 4652 case Intrinsic::amdgcn_end_cf: 4653 llvm_unreachable("should not occur"); 4654 default: 4655 return 0; 4656 } 4657 } 4658 4659 // break, if_break, else_break are all only used as inputs to loop, not 4660 // directly as branch conditions. 4661 return 0; 4662 } 4663 4664 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4665 const Triple &TT = getTargetMachine().getTargetTriple(); 4666 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4667 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4668 AMDGPU::shouldEmitConstantsToTextSection(TT); 4669 } 4670 4671 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4672 // FIXME: Either avoid relying on address space here or change the default 4673 // address space for functions to avoid the explicit check. 4674 return (GV->getValueType()->isFunctionTy() || 4675 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4676 !shouldEmitFixup(GV) && 4677 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4678 } 4679 4680 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4681 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4682 } 4683 4684 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4685 if (!GV->hasExternalLinkage()) 4686 return true; 4687 4688 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4689 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4690 } 4691 4692 /// This transforms the control flow intrinsics to get the branch destination as 4693 /// last parameter, also switches branch target with BR if the need arise 4694 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4695 SelectionDAG &DAG) const { 4696 SDLoc DL(BRCOND); 4697 4698 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4699 SDValue Target = BRCOND.getOperand(2); 4700 SDNode *BR = nullptr; 4701 SDNode *SetCC = nullptr; 4702 4703 if (Intr->getOpcode() == ISD::SETCC) { 4704 // As long as we negate the condition everything is fine 4705 SetCC = Intr; 4706 Intr = SetCC->getOperand(0).getNode(); 4707 4708 } else { 4709 // Get the target from BR if we don't negate the condition 4710 BR = findUser(BRCOND, ISD::BR); 4711 Target = BR->getOperand(1); 4712 } 4713 4714 unsigned CFNode = isCFIntrinsic(Intr); 4715 if (CFNode == 0) { 4716 // This is a uniform branch so we don't need to legalize. 4717 return BRCOND; 4718 } 4719 4720 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4721 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4722 4723 assert(!SetCC || 4724 (SetCC->getConstantOperandVal(1) == 1 && 4725 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4726 ISD::SETNE)); 4727 4728 // operands of the new intrinsic call 4729 SmallVector<SDValue, 4> Ops; 4730 if (HaveChain) 4731 Ops.push_back(BRCOND.getOperand(0)); 4732 4733 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4734 Ops.push_back(Target); 4735 4736 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4737 4738 // build the new intrinsic call 4739 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4740 4741 if (!HaveChain) { 4742 SDValue Ops[] = { 4743 SDValue(Result, 0), 4744 BRCOND.getOperand(0) 4745 }; 4746 4747 Result = DAG.getMergeValues(Ops, DL).getNode(); 4748 } 4749 4750 if (BR) { 4751 // Give the branch instruction our target 4752 SDValue Ops[] = { 4753 BR->getOperand(0), 4754 BRCOND.getOperand(2) 4755 }; 4756 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4757 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4758 } 4759 4760 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4761 4762 // Copy the intrinsic results to registers 4763 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4764 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4765 if (!CopyToReg) 4766 continue; 4767 4768 Chain = DAG.getCopyToReg( 4769 Chain, DL, 4770 CopyToReg->getOperand(1), 4771 SDValue(Result, i - 1), 4772 SDValue()); 4773 4774 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4775 } 4776 4777 // Remove the old intrinsic from the chain 4778 DAG.ReplaceAllUsesOfValueWith( 4779 SDValue(Intr, Intr->getNumValues() - 1), 4780 Intr->getOperand(0)); 4781 4782 return Chain; 4783 } 4784 4785 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4786 SelectionDAG &DAG) const { 4787 MVT VT = Op.getSimpleValueType(); 4788 SDLoc DL(Op); 4789 // Checking the depth 4790 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4791 return DAG.getConstant(0, DL, VT); 4792 4793 MachineFunction &MF = DAG.getMachineFunction(); 4794 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4795 // Check for kernel and shader functions 4796 if (Info->isEntryFunction()) 4797 return DAG.getConstant(0, DL, VT); 4798 4799 MachineFrameInfo &MFI = MF.getFrameInfo(); 4800 // There is a call to @llvm.returnaddress in this function 4801 MFI.setReturnAddressIsTaken(true); 4802 4803 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4804 // Get the return address reg and mark it as an implicit live-in 4805 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4806 4807 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4808 } 4809 4810 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 4811 SDValue Op, 4812 const SDLoc &DL, 4813 EVT VT) const { 4814 return Op.getValueType().bitsLE(VT) ? 4815 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4816 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 4817 DAG.getTargetConstant(0, DL, MVT::i32)); 4818 } 4819 4820 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4821 assert(Op.getValueType() == MVT::f16 && 4822 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4823 4824 SDValue Src = Op.getOperand(0); 4825 EVT SrcVT = Src.getValueType(); 4826 if (SrcVT != MVT::f64) 4827 return Op; 4828 4829 SDLoc DL(Op); 4830 4831 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4832 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4833 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4834 } 4835 4836 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4837 SelectionDAG &DAG) const { 4838 EVT VT = Op.getValueType(); 4839 const MachineFunction &MF = DAG.getMachineFunction(); 4840 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4841 bool IsIEEEMode = Info->getMode().IEEE; 4842 4843 // FIXME: Assert during selection that this is only selected for 4844 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4845 // mode functions, but this happens to be OK since it's only done in cases 4846 // where there is known no sNaN. 4847 if (IsIEEEMode) 4848 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 4849 4850 if (VT == MVT::v4f16) 4851 return splitBinaryVectorOp(Op, DAG); 4852 return Op; 4853 } 4854 4855 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4856 SDLoc SL(Op); 4857 SDValue Chain = Op.getOperand(0); 4858 4859 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4860 !Subtarget->isTrapHandlerEnabled()) 4861 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4862 4863 MachineFunction &MF = DAG.getMachineFunction(); 4864 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4865 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4866 assert(UserSGPR != AMDGPU::NoRegister); 4867 SDValue QueuePtr = CreateLiveInRegister( 4868 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4869 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4870 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4871 QueuePtr, SDValue()); 4872 SDValue Ops[] = { 4873 ToReg, 4874 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 4875 SGPR01, 4876 ToReg.getValue(1) 4877 }; 4878 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4879 } 4880 4881 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 4882 SDLoc SL(Op); 4883 SDValue Chain = Op.getOperand(0); 4884 MachineFunction &MF = DAG.getMachineFunction(); 4885 4886 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4887 !Subtarget->isTrapHandlerEnabled()) { 4888 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4889 "debugtrap handler not supported", 4890 Op.getDebugLoc(), 4891 DS_Warning); 4892 LLVMContext &Ctx = MF.getFunction().getContext(); 4893 Ctx.diagnose(NoTrap); 4894 return Chain; 4895 } 4896 4897 SDValue Ops[] = { 4898 Chain, 4899 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 4900 }; 4901 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4902 } 4903 4904 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4905 SelectionDAG &DAG) const { 4906 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4907 if (Subtarget->hasApertureRegs()) { 4908 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 4909 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4910 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4911 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 4912 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4913 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4914 unsigned Encoding = 4915 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4916 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4917 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4918 4919 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4920 SDValue ApertureReg = SDValue( 4921 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4922 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4923 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4924 } 4925 4926 MachineFunction &MF = DAG.getMachineFunction(); 4927 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4928 Register UserSGPR = Info->getQueuePtrUserSGPR(); 4929 assert(UserSGPR != AMDGPU::NoRegister); 4930 4931 SDValue QueuePtr = CreateLiveInRegister( 4932 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4933 4934 // Offset into amd_queue_t for group_segment_aperture_base_hi / 4935 // private_segment_aperture_base_hi. 4936 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 4937 4938 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 4939 4940 // TODO: Use custom target PseudoSourceValue. 4941 // TODO: We should use the value from the IR intrinsic call, but it might not 4942 // be available and how do we get it? 4943 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 4944 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4945 MinAlign(64, StructOffset), 4946 MachineMemOperand::MODereferenceable | 4947 MachineMemOperand::MOInvariant); 4948 } 4949 4950 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4951 SelectionDAG &DAG) const { 4952 SDLoc SL(Op); 4953 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4954 4955 SDValue Src = ASC->getOperand(0); 4956 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4957 4958 const AMDGPUTargetMachine &TM = 4959 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4960 4961 // flat -> local/private 4962 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4963 unsigned DestAS = ASC->getDestAddressSpace(); 4964 4965 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 4966 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 4967 unsigned NullVal = TM.getNullPointerValue(DestAS); 4968 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4969 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4970 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4971 4972 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4973 NonNull, Ptr, SegmentNullPtr); 4974 } 4975 } 4976 4977 // local/private -> flat 4978 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4979 unsigned SrcAS = ASC->getSrcAddressSpace(); 4980 4981 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 4982 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 4983 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4984 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4985 4986 SDValue NonNull 4987 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4988 4989 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4990 SDValue CvtPtr 4991 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4992 4993 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4994 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4995 FlatNullPtr); 4996 } 4997 } 4998 4999 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5000 Src.getValueType() == MVT::i64) 5001 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5002 5003 // global <-> flat are no-ops and never emitted. 5004 5005 const MachineFunction &MF = DAG.getMachineFunction(); 5006 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5007 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5008 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5009 5010 return DAG.getUNDEF(ASC->getValueType(0)); 5011 } 5012 5013 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5014 // the small vector and inserting them into the big vector. That is better than 5015 // the default expansion of doing it via a stack slot. Even though the use of 5016 // the stack slot would be optimized away afterwards, the stack slot itself 5017 // remains. 5018 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5019 SelectionDAG &DAG) const { 5020 SDValue Vec = Op.getOperand(0); 5021 SDValue Ins = Op.getOperand(1); 5022 SDValue Idx = Op.getOperand(2); 5023 EVT VecVT = Vec.getValueType(); 5024 EVT InsVT = Ins.getValueType(); 5025 EVT EltVT = VecVT.getVectorElementType(); 5026 unsigned InsNumElts = InsVT.getVectorNumElements(); 5027 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5028 SDLoc SL(Op); 5029 5030 for (unsigned I = 0; I != InsNumElts; ++I) { 5031 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5032 DAG.getConstant(I, SL, MVT::i32)); 5033 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5034 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5035 } 5036 return Vec; 5037 } 5038 5039 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5040 SelectionDAG &DAG) const { 5041 SDValue Vec = Op.getOperand(0); 5042 SDValue InsVal = Op.getOperand(1); 5043 SDValue Idx = Op.getOperand(2); 5044 EVT VecVT = Vec.getValueType(); 5045 EVT EltVT = VecVT.getVectorElementType(); 5046 unsigned VecSize = VecVT.getSizeInBits(); 5047 unsigned EltSize = EltVT.getSizeInBits(); 5048 5049 5050 assert(VecSize <= 64); 5051 5052 unsigned NumElts = VecVT.getVectorNumElements(); 5053 SDLoc SL(Op); 5054 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5055 5056 if (NumElts == 4 && EltSize == 16 && KIdx) { 5057 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5058 5059 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5060 DAG.getConstant(0, SL, MVT::i32)); 5061 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5062 DAG.getConstant(1, SL, MVT::i32)); 5063 5064 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5065 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5066 5067 unsigned Idx = KIdx->getZExtValue(); 5068 bool InsertLo = Idx < 2; 5069 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5070 InsertLo ? LoVec : HiVec, 5071 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5072 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5073 5074 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5075 5076 SDValue Concat = InsertLo ? 5077 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5078 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5079 5080 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5081 } 5082 5083 if (isa<ConstantSDNode>(Idx)) 5084 return SDValue(); 5085 5086 MVT IntVT = MVT::getIntegerVT(VecSize); 5087 5088 // Avoid stack access for dynamic indexing. 5089 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5090 5091 // Create a congruent vector with the target value in each element so that 5092 // the required element can be masked and ORed into the target vector. 5093 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5094 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5095 5096 assert(isPowerOf2_32(EltSize)); 5097 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5098 5099 // Convert vector index to bit-index. 5100 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5101 5102 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5103 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5104 DAG.getConstant(0xffff, SL, IntVT), 5105 ScaledIdx); 5106 5107 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5108 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5109 DAG.getNOT(SL, BFM, IntVT), BCVec); 5110 5111 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5112 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5113 } 5114 5115 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5116 SelectionDAG &DAG) const { 5117 SDLoc SL(Op); 5118 5119 EVT ResultVT = Op.getValueType(); 5120 SDValue Vec = Op.getOperand(0); 5121 SDValue Idx = Op.getOperand(1); 5122 EVT VecVT = Vec.getValueType(); 5123 unsigned VecSize = VecVT.getSizeInBits(); 5124 EVT EltVT = VecVT.getVectorElementType(); 5125 assert(VecSize <= 64); 5126 5127 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5128 5129 // Make sure we do any optimizations that will make it easier to fold 5130 // source modifiers before obscuring it with bit operations. 5131 5132 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5133 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5134 return Combined; 5135 5136 unsigned EltSize = EltVT.getSizeInBits(); 5137 assert(isPowerOf2_32(EltSize)); 5138 5139 MVT IntVT = MVT::getIntegerVT(VecSize); 5140 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5141 5142 // Convert vector index to bit-index (* EltSize) 5143 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5144 5145 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5146 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5147 5148 if (ResultVT == MVT::f16) { 5149 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5150 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5151 } 5152 5153 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5154 } 5155 5156 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5157 assert(Elt % 2 == 0); 5158 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5159 } 5160 5161 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5162 SelectionDAG &DAG) const { 5163 SDLoc SL(Op); 5164 EVT ResultVT = Op.getValueType(); 5165 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5166 5167 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5168 EVT EltVT = PackVT.getVectorElementType(); 5169 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5170 5171 // vector_shuffle <0,1,6,7> lhs, rhs 5172 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5173 // 5174 // vector_shuffle <6,7,2,3> lhs, rhs 5175 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5176 // 5177 // vector_shuffle <6,7,0,1> lhs, rhs 5178 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5179 5180 // Avoid scalarizing when both halves are reading from consecutive elements. 5181 SmallVector<SDValue, 4> Pieces; 5182 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5183 if (elementPairIsContiguous(SVN->getMask(), I)) { 5184 const int Idx = SVN->getMaskElt(I); 5185 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5186 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5187 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5188 PackVT, SVN->getOperand(VecIdx), 5189 DAG.getConstant(EltIdx, SL, MVT::i32)); 5190 Pieces.push_back(SubVec); 5191 } else { 5192 const int Idx0 = SVN->getMaskElt(I); 5193 const int Idx1 = SVN->getMaskElt(I + 1); 5194 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5195 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5196 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5197 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5198 5199 SDValue Vec0 = SVN->getOperand(VecIdx0); 5200 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5201 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5202 5203 SDValue Vec1 = SVN->getOperand(VecIdx1); 5204 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5205 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5206 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5207 } 5208 } 5209 5210 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5211 } 5212 5213 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5214 SelectionDAG &DAG) const { 5215 SDLoc SL(Op); 5216 EVT VT = Op.getValueType(); 5217 5218 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5219 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5220 5221 // Turn into pair of packed build_vectors. 5222 // TODO: Special case for constants that can be materialized with s_mov_b64. 5223 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5224 { Op.getOperand(0), Op.getOperand(1) }); 5225 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5226 { Op.getOperand(2), Op.getOperand(3) }); 5227 5228 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5229 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5230 5231 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5232 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5233 } 5234 5235 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5236 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5237 5238 SDValue Lo = Op.getOperand(0); 5239 SDValue Hi = Op.getOperand(1); 5240 5241 // Avoid adding defined bits with the zero_extend. 5242 if (Hi.isUndef()) { 5243 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5244 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5245 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5246 } 5247 5248 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5249 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5250 5251 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5252 DAG.getConstant(16, SL, MVT::i32)); 5253 if (Lo.isUndef()) 5254 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5255 5256 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5257 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5258 5259 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5260 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5261 } 5262 5263 bool 5264 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5265 // We can fold offsets for anything that doesn't require a GOT relocation. 5266 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5267 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5268 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5269 !shouldEmitGOTReloc(GA->getGlobal()); 5270 } 5271 5272 static SDValue 5273 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5274 const SDLoc &DL, unsigned Offset, EVT PtrVT, 5275 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5276 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5277 // lowered to the following code sequence: 5278 // 5279 // For constant address space: 5280 // s_getpc_b64 s[0:1] 5281 // s_add_u32 s0, s0, $symbol 5282 // s_addc_u32 s1, s1, 0 5283 // 5284 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5285 // a fixup or relocation is emitted to replace $symbol with a literal 5286 // constant, which is a pc-relative offset from the encoding of the $symbol 5287 // operand to the global variable. 5288 // 5289 // For global address space: 5290 // s_getpc_b64 s[0:1] 5291 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5292 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5293 // 5294 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5295 // fixups or relocations are emitted to replace $symbol@*@lo and 5296 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5297 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5298 // operand to the global variable. 5299 // 5300 // What we want here is an offset from the value returned by s_getpc 5301 // (which is the address of the s_add_u32 instruction) to the global 5302 // variable, but since the encoding of $symbol starts 4 bytes after the start 5303 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5304 // small. This requires us to add 4 to the global variable offset in order to 5305 // compute the correct address. 5306 SDValue PtrLo = 5307 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5308 SDValue PtrHi; 5309 if (GAFlags == SIInstrInfo::MO_NONE) { 5310 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5311 } else { 5312 PtrHi = 5313 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5314 } 5315 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5316 } 5317 5318 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5319 SDValue Op, 5320 SelectionDAG &DAG) const { 5321 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5322 const GlobalValue *GV = GSD->getGlobal(); 5323 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5324 shouldUseLDSConstAddress(GV)) || 5325 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5326 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5327 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5328 5329 SDLoc DL(GSD); 5330 EVT PtrVT = Op.getValueType(); 5331 5332 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5333 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5334 SIInstrInfo::MO_ABS32_LO); 5335 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5336 } 5337 5338 if (shouldEmitFixup(GV)) 5339 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5340 else if (shouldEmitPCReloc(GV)) 5341 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5342 SIInstrInfo::MO_REL32); 5343 5344 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5345 SIInstrInfo::MO_GOTPCREL32); 5346 5347 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5348 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5349 const DataLayout &DataLayout = DAG.getDataLayout(); 5350 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 5351 MachinePointerInfo PtrInfo 5352 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5353 5354 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 5355 MachineMemOperand::MODereferenceable | 5356 MachineMemOperand::MOInvariant); 5357 } 5358 5359 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5360 const SDLoc &DL, SDValue V) const { 5361 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5362 // the destination register. 5363 // 5364 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5365 // so we will end up with redundant moves to m0. 5366 // 5367 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5368 5369 // A Null SDValue creates a glue result. 5370 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5371 V, Chain); 5372 return SDValue(M0, 0); 5373 } 5374 5375 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5376 SDValue Op, 5377 MVT VT, 5378 unsigned Offset) const { 5379 SDLoc SL(Op); 5380 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 5381 DAG.getEntryNode(), Offset, 4, false); 5382 // The local size values will have the hi 16-bits as zero. 5383 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5384 DAG.getValueType(VT)); 5385 } 5386 5387 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5388 EVT VT) { 5389 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5390 "non-hsa intrinsic with hsa target", 5391 DL.getDebugLoc()); 5392 DAG.getContext()->diagnose(BadIntrin); 5393 return DAG.getUNDEF(VT); 5394 } 5395 5396 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5397 EVT VT) { 5398 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5399 "intrinsic not supported on subtarget", 5400 DL.getDebugLoc()); 5401 DAG.getContext()->diagnose(BadIntrin); 5402 return DAG.getUNDEF(VT); 5403 } 5404 5405 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5406 ArrayRef<SDValue> Elts) { 5407 assert(!Elts.empty()); 5408 MVT Type; 5409 unsigned NumElts; 5410 5411 if (Elts.size() == 1) { 5412 Type = MVT::f32; 5413 NumElts = 1; 5414 } else if (Elts.size() == 2) { 5415 Type = MVT::v2f32; 5416 NumElts = 2; 5417 } else if (Elts.size() == 3) { 5418 Type = MVT::v3f32; 5419 NumElts = 3; 5420 } else if (Elts.size() <= 4) { 5421 Type = MVT::v4f32; 5422 NumElts = 4; 5423 } else if (Elts.size() <= 8) { 5424 Type = MVT::v8f32; 5425 NumElts = 8; 5426 } else { 5427 assert(Elts.size() <= 16); 5428 Type = MVT::v16f32; 5429 NumElts = 16; 5430 } 5431 5432 SmallVector<SDValue, 16> VecElts(NumElts); 5433 for (unsigned i = 0; i < Elts.size(); ++i) { 5434 SDValue Elt = Elts[i]; 5435 if (Elt.getValueType() != MVT::f32) 5436 Elt = DAG.getBitcast(MVT::f32, Elt); 5437 VecElts[i] = Elt; 5438 } 5439 for (unsigned i = Elts.size(); i < NumElts; ++i) 5440 VecElts[i] = DAG.getUNDEF(MVT::f32); 5441 5442 if (NumElts == 1) 5443 return VecElts[0]; 5444 return DAG.getBuildVector(Type, DL, VecElts); 5445 } 5446 5447 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5448 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5449 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5450 5451 uint64_t Value = CachePolicyConst->getZExtValue(); 5452 SDLoc DL(CachePolicy); 5453 if (GLC) { 5454 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5455 Value &= ~(uint64_t)0x1; 5456 } 5457 if (SLC) { 5458 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5459 Value &= ~(uint64_t)0x2; 5460 } 5461 if (DLC) { 5462 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5463 Value &= ~(uint64_t)0x4; 5464 } 5465 5466 return Value == 0; 5467 } 5468 5469 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5470 SDValue Src, int ExtraElts) { 5471 EVT SrcVT = Src.getValueType(); 5472 5473 SmallVector<SDValue, 8> Elts; 5474 5475 if (SrcVT.isVector()) 5476 DAG.ExtractVectorElements(Src, Elts); 5477 else 5478 Elts.push_back(Src); 5479 5480 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5481 while (ExtraElts--) 5482 Elts.push_back(Undef); 5483 5484 return DAG.getBuildVector(CastVT, DL, Elts); 5485 } 5486 5487 // Re-construct the required return value for a image load intrinsic. 5488 // This is more complicated due to the optional use TexFailCtrl which means the required 5489 // return type is an aggregate 5490 static SDValue constructRetValue(SelectionDAG &DAG, 5491 MachineSDNode *Result, 5492 ArrayRef<EVT> ResultTypes, 5493 bool IsTexFail, bool Unpacked, bool IsD16, 5494 int DMaskPop, int NumVDataDwords, 5495 const SDLoc &DL, LLVMContext &Context) { 5496 // Determine the required return type. This is the same regardless of IsTexFail flag 5497 EVT ReqRetVT = ResultTypes[0]; 5498 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5499 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5500 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5501 5502 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5503 DMaskPop : (DMaskPop + 1) / 2; 5504 5505 MVT DataDwordVT = NumDataDwords == 1 ? 5506 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5507 5508 MVT MaskPopVT = MaskPopDwords == 1 ? 5509 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5510 5511 SDValue Data(Result, 0); 5512 SDValue TexFail; 5513 5514 if (IsTexFail) { 5515 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5516 if (MaskPopVT.isVector()) { 5517 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5518 SDValue(Result, 0), ZeroIdx); 5519 } else { 5520 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5521 SDValue(Result, 0), ZeroIdx); 5522 } 5523 5524 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5525 SDValue(Result, 0), 5526 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5527 } 5528 5529 if (DataDwordVT.isVector()) 5530 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5531 NumDataDwords - MaskPopDwords); 5532 5533 if (IsD16) 5534 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5535 5536 if (!ReqRetVT.isVector()) 5537 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5538 5539 Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data); 5540 5541 if (TexFail) 5542 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5543 5544 if (Result->getNumValues() == 1) 5545 return Data; 5546 5547 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5548 } 5549 5550 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5551 SDValue *LWE, bool &IsTexFail) { 5552 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5553 5554 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5555 if (Value) { 5556 IsTexFail = true; 5557 } 5558 5559 SDLoc DL(TexFailCtrlConst); 5560 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5561 Value &= ~(uint64_t)0x1; 5562 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5563 Value &= ~(uint64_t)0x2; 5564 5565 return Value == 0; 5566 } 5567 5568 SDValue SITargetLowering::lowerImage(SDValue Op, 5569 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5570 SelectionDAG &DAG) const { 5571 SDLoc DL(Op); 5572 MachineFunction &MF = DAG.getMachineFunction(); 5573 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5574 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5575 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5576 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5577 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5578 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5579 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5580 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5581 unsigned IntrOpcode = Intr->BaseOpcode; 5582 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5583 5584 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5585 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5586 bool IsD16 = false; 5587 bool IsA16 = false; 5588 SDValue VData; 5589 int NumVDataDwords; 5590 bool AdjustRetType = false; 5591 5592 unsigned AddrIdx; // Index of first address argument 5593 unsigned DMask; 5594 unsigned DMaskLanes = 0; 5595 5596 if (BaseOpcode->Atomic) { 5597 VData = Op.getOperand(2); 5598 5599 bool Is64Bit = VData.getValueType() == MVT::i64; 5600 if (BaseOpcode->AtomicX2) { 5601 SDValue VData2 = Op.getOperand(3); 5602 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5603 {VData, VData2}); 5604 if (Is64Bit) 5605 VData = DAG.getBitcast(MVT::v4i32, VData); 5606 5607 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5608 DMask = Is64Bit ? 0xf : 0x3; 5609 NumVDataDwords = Is64Bit ? 4 : 2; 5610 AddrIdx = 4; 5611 } else { 5612 DMask = Is64Bit ? 0x3 : 0x1; 5613 NumVDataDwords = Is64Bit ? 2 : 1; 5614 AddrIdx = 3; 5615 } 5616 } else { 5617 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5618 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5619 DMask = DMaskConst->getZExtValue(); 5620 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5621 5622 if (BaseOpcode->Store) { 5623 VData = Op.getOperand(2); 5624 5625 MVT StoreVT = VData.getSimpleValueType(); 5626 if (StoreVT.getScalarType() == MVT::f16) { 5627 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5628 return Op; // D16 is unsupported for this instruction 5629 5630 IsD16 = true; 5631 VData = handleD16VData(VData, DAG); 5632 } 5633 5634 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5635 } else { 5636 // Work out the num dwords based on the dmask popcount and underlying type 5637 // and whether packing is supported. 5638 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5639 if (LoadVT.getScalarType() == MVT::f16) { 5640 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5641 return Op; // D16 is unsupported for this instruction 5642 5643 IsD16 = true; 5644 } 5645 5646 // Confirm that the return type is large enough for the dmask specified 5647 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5648 (!LoadVT.isVector() && DMaskLanes > 1)) 5649 return Op; 5650 5651 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5652 NumVDataDwords = (DMaskLanes + 1) / 2; 5653 else 5654 NumVDataDwords = DMaskLanes; 5655 5656 AdjustRetType = true; 5657 } 5658 5659 AddrIdx = DMaskIdx + 1; 5660 } 5661 5662 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5663 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5664 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5665 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5666 NumCoords + NumLCM; 5667 unsigned NumMIVAddrs = NumVAddrs; 5668 5669 SmallVector<SDValue, 4> VAddrs; 5670 5671 // Optimize _L to _LZ when _L is zero 5672 if (LZMappingInfo) { 5673 if (auto ConstantLod = 5674 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5675 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5676 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5677 NumMIVAddrs--; // remove 'lod' 5678 } 5679 } 5680 } 5681 5682 // Optimize _mip away, when 'lod' is zero 5683 if (MIPMappingInfo) { 5684 if (auto ConstantLod = 5685 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5686 if (ConstantLod->isNullValue()) { 5687 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5688 NumMIVAddrs--; // remove 'lod' 5689 } 5690 } 5691 } 5692 5693 // Check for 16 bit addresses and pack if true. 5694 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5695 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5696 const MVT VAddrScalarVT = VAddrVT.getScalarType(); 5697 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) { 5698 // Illegal to use a16 images 5699 if (!ST->hasFeature(AMDGPU::FeatureR128A16) && !ST->hasFeature(AMDGPU::FeatureGFX10A16)) 5700 return Op; 5701 5702 IsA16 = true; 5703 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5704 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) { 5705 SDValue AddrLo; 5706 // Push back extra arguments. 5707 if (i < DimIdx) { 5708 AddrLo = Op.getOperand(i); 5709 } else { 5710 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, 5711 // in 1D, derivatives dx/dh and dx/dv are packed with undef. 5712 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) || 5713 ((NumGradients / 2) % 2 == 1 && 5714 (i == DimIdx + (NumGradients / 2) - 1 || 5715 i == DimIdx + NumGradients - 1))) { 5716 AddrLo = Op.getOperand(i); 5717 if (AddrLo.getValueType() != MVT::i16) 5718 AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i)); 5719 AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo); 5720 } else { 5721 AddrLo = DAG.getBuildVector(VectorVT, DL, 5722 {Op.getOperand(i), Op.getOperand(i + 1)}); 5723 i++; 5724 } 5725 AddrLo = DAG.getBitcast(MVT::f32, AddrLo); 5726 } 5727 VAddrs.push_back(AddrLo); 5728 } 5729 } else { 5730 for (unsigned i = 0; i < NumMIVAddrs; ++i) 5731 VAddrs.push_back(Op.getOperand(AddrIdx + i)); 5732 } 5733 5734 // If the register allocator cannot place the address registers contiguously 5735 // without introducing moves, then using the non-sequential address encoding 5736 // is always preferable, since it saves VALU instructions and is usually a 5737 // wash in terms of code size or even better. 5738 // 5739 // However, we currently have no way of hinting to the register allocator that 5740 // MIMG addresses should be placed contiguously when it is possible to do so, 5741 // so force non-NSA for the common 2-address case as a heuristic. 5742 // 5743 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5744 // allocation when possible. 5745 bool UseNSA = 5746 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5747 SDValue VAddr; 5748 if (!UseNSA) 5749 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5750 5751 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5752 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5753 unsigned CtrlIdx; // Index of texfailctrl argument 5754 SDValue Unorm; 5755 if (!BaseOpcode->Sampler) { 5756 Unorm = True; 5757 CtrlIdx = AddrIdx + NumVAddrs + 1; 5758 } else { 5759 auto UnormConst = 5760 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 5761 5762 Unorm = UnormConst->getZExtValue() ? True : False; 5763 CtrlIdx = AddrIdx + NumVAddrs + 3; 5764 } 5765 5766 SDValue TFE; 5767 SDValue LWE; 5768 SDValue TexFail = Op.getOperand(CtrlIdx); 5769 bool IsTexFail = false; 5770 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 5771 return Op; 5772 5773 if (IsTexFail) { 5774 if (!DMaskLanes) { 5775 // Expecting to get an error flag since TFC is on - and dmask is 0 5776 // Force dmask to be at least 1 otherwise the instruction will fail 5777 DMask = 0x1; 5778 DMaskLanes = 1; 5779 NumVDataDwords = 1; 5780 } 5781 NumVDataDwords += 1; 5782 AdjustRetType = true; 5783 } 5784 5785 // Has something earlier tagged that the return type needs adjusting 5786 // This happens if the instruction is a load or has set TexFailCtrl flags 5787 if (AdjustRetType) { 5788 // NumVDataDwords reflects the true number of dwords required in the return type 5789 if (DMaskLanes == 0 && !BaseOpcode->Store) { 5790 // This is a no-op load. This can be eliminated 5791 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 5792 if (isa<MemSDNode>(Op)) 5793 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 5794 return Undef; 5795 } 5796 5797 EVT NewVT = NumVDataDwords > 1 ? 5798 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 5799 : MVT::i32; 5800 5801 ResultTypes[0] = NewVT; 5802 if (ResultTypes.size() == 3) { 5803 // Original result was aggregate type used for TexFailCtrl results 5804 // The actual instruction returns as a vector type which has now been 5805 // created. Remove the aggregate result. 5806 ResultTypes.erase(&ResultTypes[1]); 5807 } 5808 } 5809 5810 SDValue GLC; 5811 SDValue SLC; 5812 SDValue DLC; 5813 if (BaseOpcode->Atomic) { 5814 GLC = True; // TODO no-return optimization 5815 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 5816 IsGFX10 ? &DLC : nullptr)) 5817 return Op; 5818 } else { 5819 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 5820 IsGFX10 ? &DLC : nullptr)) 5821 return Op; 5822 } 5823 5824 SmallVector<SDValue, 26> Ops; 5825 if (BaseOpcode->Store || BaseOpcode->Atomic) 5826 Ops.push_back(VData); // vdata 5827 if (UseNSA) { 5828 for (const SDValue &Addr : VAddrs) 5829 Ops.push_back(Addr); 5830 } else { 5831 Ops.push_back(VAddr); 5832 } 5833 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 5834 if (BaseOpcode->Sampler) 5835 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 5836 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 5837 if (IsGFX10) 5838 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 5839 Ops.push_back(Unorm); 5840 if (IsGFX10) 5841 Ops.push_back(DLC); 5842 Ops.push_back(GLC); 5843 Ops.push_back(SLC); 5844 Ops.push_back(IsA16 && // r128, a16 for gfx9 5845 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 5846 if (IsGFX10) 5847 Ops.push_back(IsA16 ? True : False); 5848 Ops.push_back(TFE); 5849 Ops.push_back(LWE); 5850 if (!IsGFX10) 5851 Ops.push_back(DimInfo->DA ? True : False); 5852 if (BaseOpcode->HasD16) 5853 Ops.push_back(IsD16 ? True : False); 5854 if (isa<MemSDNode>(Op)) 5855 Ops.push_back(Op.getOperand(0)); // chain 5856 5857 int NumVAddrDwords = 5858 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 5859 int Opcode = -1; 5860 5861 if (IsGFX10) { 5862 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 5863 UseNSA ? AMDGPU::MIMGEncGfx10NSA 5864 : AMDGPU::MIMGEncGfx10Default, 5865 NumVDataDwords, NumVAddrDwords); 5866 } else { 5867 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5868 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 5869 NumVDataDwords, NumVAddrDwords); 5870 if (Opcode == -1) 5871 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 5872 NumVDataDwords, NumVAddrDwords); 5873 } 5874 assert(Opcode != -1); 5875 5876 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 5877 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 5878 MachineMemOperand *MemRef = MemOp->getMemOperand(); 5879 DAG.setNodeMemRefs(NewNode, {MemRef}); 5880 } 5881 5882 if (BaseOpcode->AtomicX2) { 5883 SmallVector<SDValue, 1> Elt; 5884 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 5885 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 5886 } else if (!BaseOpcode->Store) { 5887 return constructRetValue(DAG, NewNode, 5888 OrigResultTypes, IsTexFail, 5889 Subtarget->hasUnpackedD16VMem(), IsD16, 5890 DMaskLanes, NumVDataDwords, DL, 5891 *DAG.getContext()); 5892 } 5893 5894 return SDValue(NewNode, 0); 5895 } 5896 5897 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 5898 SDValue Offset, SDValue CachePolicy, 5899 SelectionDAG &DAG) const { 5900 MachineFunction &MF = DAG.getMachineFunction(); 5901 5902 const DataLayout &DataLayout = DAG.getDataLayout(); 5903 Align Alignment = 5904 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 5905 5906 MachineMemOperand *MMO = MF.getMachineMemOperand( 5907 MachinePointerInfo(), 5908 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 5909 MachineMemOperand::MOInvariant, 5910 VT.getStoreSize(), Alignment); 5911 5912 if (!Offset->isDivergent()) { 5913 SDValue Ops[] = { 5914 Rsrc, 5915 Offset, // Offset 5916 CachePolicy 5917 }; 5918 5919 // Widen vec3 load to vec4. 5920 if (VT.isVector() && VT.getVectorNumElements() == 3) { 5921 EVT WidenedVT = 5922 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 5923 auto WidenedOp = DAG.getMemIntrinsicNode( 5924 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 5925 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 5926 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 5927 DAG.getVectorIdxConstant(0, DL)); 5928 return Subvector; 5929 } 5930 5931 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 5932 DAG.getVTList(VT), Ops, VT, MMO); 5933 } 5934 5935 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 5936 // assume that the buffer is unswizzled. 5937 SmallVector<SDValue, 4> Loads; 5938 unsigned NumLoads = 1; 5939 MVT LoadVT = VT.getSimpleVT(); 5940 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 5941 assert((LoadVT.getScalarType() == MVT::i32 || 5942 LoadVT.getScalarType() == MVT::f32)); 5943 5944 if (NumElts == 8 || NumElts == 16) { 5945 NumLoads = NumElts / 4; 5946 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 5947 } 5948 5949 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 5950 SDValue Ops[] = { 5951 DAG.getEntryNode(), // Chain 5952 Rsrc, // rsrc 5953 DAG.getConstant(0, DL, MVT::i32), // vindex 5954 {}, // voffset 5955 {}, // soffset 5956 {}, // offset 5957 CachePolicy, // cachepolicy 5958 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 5959 }; 5960 5961 // Use the alignment to ensure that the required offsets will fit into the 5962 // immediate offsets. 5963 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 5964 5965 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 5966 for (unsigned i = 0; i < NumLoads; ++i) { 5967 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 5968 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 5969 LoadVT, MMO, DAG)); 5970 } 5971 5972 if (NumElts == 8 || NumElts == 16) 5973 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 5974 5975 return Loads[0]; 5976 } 5977 5978 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 5979 SelectionDAG &DAG) const { 5980 MachineFunction &MF = DAG.getMachineFunction(); 5981 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 5982 5983 EVT VT = Op.getValueType(); 5984 SDLoc DL(Op); 5985 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5986 5987 // TODO: Should this propagate fast-math-flags? 5988 5989 switch (IntrinsicID) { 5990 case Intrinsic::amdgcn_implicit_buffer_ptr: { 5991 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 5992 return emitNonHSAIntrinsicError(DAG, DL, VT); 5993 return getPreloadedValue(DAG, *MFI, VT, 5994 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 5995 } 5996 case Intrinsic::amdgcn_dispatch_ptr: 5997 case Intrinsic::amdgcn_queue_ptr: { 5998 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 5999 DiagnosticInfoUnsupported BadIntrin( 6000 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6001 DL.getDebugLoc()); 6002 DAG.getContext()->diagnose(BadIntrin); 6003 return DAG.getUNDEF(VT); 6004 } 6005 6006 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6007 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6008 return getPreloadedValue(DAG, *MFI, VT, RegID); 6009 } 6010 case Intrinsic::amdgcn_implicitarg_ptr: { 6011 if (MFI->isEntryFunction()) 6012 return getImplicitArgPtr(DAG, DL); 6013 return getPreloadedValue(DAG, *MFI, VT, 6014 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6015 } 6016 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6017 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6018 // This only makes sense to call in a kernel, so just lower to null. 6019 return DAG.getConstant(0, DL, VT); 6020 } 6021 6022 return getPreloadedValue(DAG, *MFI, VT, 6023 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6024 } 6025 case Intrinsic::amdgcn_dispatch_id: { 6026 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6027 } 6028 case Intrinsic::amdgcn_rcp: 6029 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6030 case Intrinsic::amdgcn_rsq: 6031 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6032 case Intrinsic::amdgcn_rsq_legacy: 6033 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6034 return emitRemovedIntrinsicError(DAG, DL, VT); 6035 return SDValue(); 6036 case Intrinsic::amdgcn_rcp_legacy: 6037 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6038 return emitRemovedIntrinsicError(DAG, DL, VT); 6039 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6040 case Intrinsic::amdgcn_rsq_clamp: { 6041 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6042 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6043 6044 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6045 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6046 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6047 6048 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6049 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6050 DAG.getConstantFP(Max, DL, VT)); 6051 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6052 DAG.getConstantFP(Min, DL, VT)); 6053 } 6054 case Intrinsic::r600_read_ngroups_x: 6055 if (Subtarget->isAmdHsaOS()) 6056 return emitNonHSAIntrinsicError(DAG, DL, VT); 6057 6058 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6059 SI::KernelInputOffsets::NGROUPS_X, 4, false); 6060 case Intrinsic::r600_read_ngroups_y: 6061 if (Subtarget->isAmdHsaOS()) 6062 return emitNonHSAIntrinsicError(DAG, DL, VT); 6063 6064 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6065 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 6066 case Intrinsic::r600_read_ngroups_z: 6067 if (Subtarget->isAmdHsaOS()) 6068 return emitNonHSAIntrinsicError(DAG, DL, VT); 6069 6070 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6071 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 6072 case Intrinsic::r600_read_global_size_x: 6073 if (Subtarget->isAmdHsaOS()) 6074 return emitNonHSAIntrinsicError(DAG, DL, VT); 6075 6076 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6077 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 6078 case Intrinsic::r600_read_global_size_y: 6079 if (Subtarget->isAmdHsaOS()) 6080 return emitNonHSAIntrinsicError(DAG, DL, VT); 6081 6082 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6083 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 6084 case Intrinsic::r600_read_global_size_z: 6085 if (Subtarget->isAmdHsaOS()) 6086 return emitNonHSAIntrinsicError(DAG, DL, VT); 6087 6088 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6089 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 6090 case Intrinsic::r600_read_local_size_x: 6091 if (Subtarget->isAmdHsaOS()) 6092 return emitNonHSAIntrinsicError(DAG, DL, VT); 6093 6094 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6095 SI::KernelInputOffsets::LOCAL_SIZE_X); 6096 case Intrinsic::r600_read_local_size_y: 6097 if (Subtarget->isAmdHsaOS()) 6098 return emitNonHSAIntrinsicError(DAG, DL, VT); 6099 6100 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6101 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6102 case Intrinsic::r600_read_local_size_z: 6103 if (Subtarget->isAmdHsaOS()) 6104 return emitNonHSAIntrinsicError(DAG, DL, VT); 6105 6106 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6107 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6108 case Intrinsic::amdgcn_workgroup_id_x: 6109 return getPreloadedValue(DAG, *MFI, VT, 6110 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6111 case Intrinsic::amdgcn_workgroup_id_y: 6112 return getPreloadedValue(DAG, *MFI, VT, 6113 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6114 case Intrinsic::amdgcn_workgroup_id_z: 6115 return getPreloadedValue(DAG, *MFI, VT, 6116 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6117 case Intrinsic::amdgcn_workitem_id_x: 6118 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6119 SDLoc(DAG.getEntryNode()), 6120 MFI->getArgInfo().WorkItemIDX); 6121 case Intrinsic::amdgcn_workitem_id_y: 6122 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6123 SDLoc(DAG.getEntryNode()), 6124 MFI->getArgInfo().WorkItemIDY); 6125 case Intrinsic::amdgcn_workitem_id_z: 6126 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6127 SDLoc(DAG.getEntryNode()), 6128 MFI->getArgInfo().WorkItemIDZ); 6129 case Intrinsic::amdgcn_wavefrontsize: 6130 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6131 SDLoc(Op), MVT::i32); 6132 case Intrinsic::amdgcn_s_buffer_load: { 6133 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 6134 SDValue GLC; 6135 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6136 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6137 IsGFX10 ? &DLC : nullptr)) 6138 return Op; 6139 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6140 DAG); 6141 } 6142 case Intrinsic::amdgcn_fdiv_fast: 6143 return lowerFDIV_FAST(Op, DAG); 6144 case Intrinsic::amdgcn_sin: 6145 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6146 6147 case Intrinsic::amdgcn_cos: 6148 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6149 6150 case Intrinsic::amdgcn_mul_u24: 6151 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6152 case Intrinsic::amdgcn_mul_i24: 6153 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6154 6155 case Intrinsic::amdgcn_log_clamp: { 6156 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6157 return SDValue(); 6158 6159 DiagnosticInfoUnsupported BadIntrin( 6160 MF.getFunction(), "intrinsic not supported on subtarget", 6161 DL.getDebugLoc()); 6162 DAG.getContext()->diagnose(BadIntrin); 6163 return DAG.getUNDEF(VT); 6164 } 6165 case Intrinsic::amdgcn_ldexp: 6166 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6167 Op.getOperand(1), Op.getOperand(2)); 6168 6169 case Intrinsic::amdgcn_fract: 6170 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6171 6172 case Intrinsic::amdgcn_class: 6173 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6174 Op.getOperand(1), Op.getOperand(2)); 6175 case Intrinsic::amdgcn_div_fmas: 6176 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6177 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6178 Op.getOperand(4)); 6179 6180 case Intrinsic::amdgcn_div_fixup: 6181 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6182 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6183 6184 case Intrinsic::amdgcn_trig_preop: 6185 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 6186 Op.getOperand(1), Op.getOperand(2)); 6187 case Intrinsic::amdgcn_div_scale: { 6188 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6189 6190 // Translate to the operands expected by the machine instruction. The 6191 // first parameter must be the same as the first instruction. 6192 SDValue Numerator = Op.getOperand(1); 6193 SDValue Denominator = Op.getOperand(2); 6194 6195 // Note this order is opposite of the machine instruction's operations, 6196 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6197 // intrinsic has the numerator as the first operand to match a normal 6198 // division operation. 6199 6200 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6201 6202 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6203 Denominator, Numerator); 6204 } 6205 case Intrinsic::amdgcn_icmp: { 6206 // There is a Pat that handles this variant, so return it as-is. 6207 if (Op.getOperand(1).getValueType() == MVT::i1 && 6208 Op.getConstantOperandVal(2) == 0 && 6209 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6210 return Op; 6211 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6212 } 6213 case Intrinsic::amdgcn_fcmp: { 6214 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6215 } 6216 case Intrinsic::amdgcn_ballot: 6217 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6218 case Intrinsic::amdgcn_fmed3: 6219 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6220 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6221 case Intrinsic::amdgcn_fdot2: 6222 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6223 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6224 Op.getOperand(4)); 6225 case Intrinsic::amdgcn_fmul_legacy: 6226 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6227 Op.getOperand(1), Op.getOperand(2)); 6228 case Intrinsic::amdgcn_sffbh: 6229 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6230 case Intrinsic::amdgcn_sbfe: 6231 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6232 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6233 case Intrinsic::amdgcn_ubfe: 6234 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6235 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6236 case Intrinsic::amdgcn_cvt_pkrtz: 6237 case Intrinsic::amdgcn_cvt_pknorm_i16: 6238 case Intrinsic::amdgcn_cvt_pknorm_u16: 6239 case Intrinsic::amdgcn_cvt_pk_i16: 6240 case Intrinsic::amdgcn_cvt_pk_u16: { 6241 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6242 EVT VT = Op.getValueType(); 6243 unsigned Opcode; 6244 6245 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6246 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6247 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6248 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6249 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6250 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6251 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6252 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6253 else 6254 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6255 6256 if (isTypeLegal(VT)) 6257 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6258 6259 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6260 Op.getOperand(1), Op.getOperand(2)); 6261 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6262 } 6263 case Intrinsic::amdgcn_fmad_ftz: 6264 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6265 Op.getOperand(2), Op.getOperand(3)); 6266 6267 case Intrinsic::amdgcn_if_break: 6268 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6269 Op->getOperand(1), Op->getOperand(2)), 0); 6270 6271 case Intrinsic::amdgcn_groupstaticsize: { 6272 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6273 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6274 return Op; 6275 6276 const Module *M = MF.getFunction().getParent(); 6277 const GlobalValue *GV = 6278 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6279 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6280 SIInstrInfo::MO_ABS32_LO); 6281 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6282 } 6283 case Intrinsic::amdgcn_is_shared: 6284 case Intrinsic::amdgcn_is_private: { 6285 SDLoc SL(Op); 6286 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6287 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6288 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6289 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6290 Op.getOperand(1)); 6291 6292 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6293 DAG.getConstant(1, SL, MVT::i32)); 6294 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6295 } 6296 case Intrinsic::amdgcn_alignbit: 6297 return DAG.getNode(ISD::FSHR, DL, VT, 6298 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6299 case Intrinsic::amdgcn_reloc_constant: { 6300 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6301 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6302 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6303 auto RelocSymbol = cast<GlobalVariable>( 6304 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6305 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6306 SIInstrInfo::MO_ABS32_LO); 6307 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6308 } 6309 default: 6310 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6311 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6312 return lowerImage(Op, ImageDimIntr, DAG); 6313 6314 return Op; 6315 } 6316 } 6317 6318 // This function computes an appropriate offset to pass to 6319 // MachineMemOperand::setOffset() based on the offset inputs to 6320 // an intrinsic. If any of the offsets are non-contstant or 6321 // if VIndex is non-zero then this function returns 0. Otherwise, 6322 // it returns the sum of VOffset, SOffset, and Offset. 6323 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6324 SDValue SOffset, 6325 SDValue Offset, 6326 SDValue VIndex = SDValue()) { 6327 6328 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6329 !isa<ConstantSDNode>(Offset)) 6330 return 0; 6331 6332 if (VIndex) { 6333 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6334 return 0; 6335 } 6336 6337 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6338 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6339 cast<ConstantSDNode>(Offset)->getSExtValue(); 6340 } 6341 6342 static unsigned getDSShaderTypeValue(const MachineFunction &MF) { 6343 switch (MF.getFunction().getCallingConv()) { 6344 case CallingConv::AMDGPU_PS: 6345 return 1; 6346 case CallingConv::AMDGPU_VS: 6347 return 2; 6348 case CallingConv::AMDGPU_GS: 6349 return 3; 6350 case CallingConv::AMDGPU_HS: 6351 case CallingConv::AMDGPU_LS: 6352 case CallingConv::AMDGPU_ES: 6353 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6354 case CallingConv::AMDGPU_CS: 6355 case CallingConv::AMDGPU_KERNEL: 6356 case CallingConv::C: 6357 case CallingConv::Fast: 6358 default: 6359 // Assume other calling conventions are various compute callable functions 6360 return 0; 6361 } 6362 } 6363 6364 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6365 SelectionDAG &DAG) const { 6366 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6367 SDLoc DL(Op); 6368 6369 switch (IntrID) { 6370 case Intrinsic::amdgcn_ds_ordered_add: 6371 case Intrinsic::amdgcn_ds_ordered_swap: { 6372 MemSDNode *M = cast<MemSDNode>(Op); 6373 SDValue Chain = M->getOperand(0); 6374 SDValue M0 = M->getOperand(2); 6375 SDValue Value = M->getOperand(3); 6376 unsigned IndexOperand = M->getConstantOperandVal(7); 6377 unsigned WaveRelease = M->getConstantOperandVal(8); 6378 unsigned WaveDone = M->getConstantOperandVal(9); 6379 6380 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6381 IndexOperand &= ~0x3f; 6382 unsigned CountDw = 0; 6383 6384 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6385 CountDw = (IndexOperand >> 24) & 0xf; 6386 IndexOperand &= ~(0xf << 24); 6387 6388 if (CountDw < 1 || CountDw > 4) { 6389 report_fatal_error( 6390 "ds_ordered_count: dword count must be between 1 and 4"); 6391 } 6392 } 6393 6394 if (IndexOperand) 6395 report_fatal_error("ds_ordered_count: bad index operand"); 6396 6397 if (WaveDone && !WaveRelease) 6398 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6399 6400 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6401 unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction()); 6402 unsigned Offset0 = OrderedCountIndex << 2; 6403 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6404 (Instruction << 4); 6405 6406 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6407 Offset1 |= (CountDw - 1) << 6; 6408 6409 unsigned Offset = Offset0 | (Offset1 << 8); 6410 6411 SDValue Ops[] = { 6412 Chain, 6413 Value, 6414 DAG.getTargetConstant(Offset, DL, MVT::i16), 6415 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6416 }; 6417 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6418 M->getVTList(), Ops, M->getMemoryVT(), 6419 M->getMemOperand()); 6420 } 6421 case Intrinsic::amdgcn_ds_fadd: { 6422 MemSDNode *M = cast<MemSDNode>(Op); 6423 unsigned Opc; 6424 switch (IntrID) { 6425 case Intrinsic::amdgcn_ds_fadd: 6426 Opc = ISD::ATOMIC_LOAD_FADD; 6427 break; 6428 } 6429 6430 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6431 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6432 M->getMemOperand()); 6433 } 6434 case Intrinsic::amdgcn_atomic_inc: 6435 case Intrinsic::amdgcn_atomic_dec: 6436 case Intrinsic::amdgcn_ds_fmin: 6437 case Intrinsic::amdgcn_ds_fmax: { 6438 MemSDNode *M = cast<MemSDNode>(Op); 6439 unsigned Opc; 6440 switch (IntrID) { 6441 case Intrinsic::amdgcn_atomic_inc: 6442 Opc = AMDGPUISD::ATOMIC_INC; 6443 break; 6444 case Intrinsic::amdgcn_atomic_dec: 6445 Opc = AMDGPUISD::ATOMIC_DEC; 6446 break; 6447 case Intrinsic::amdgcn_ds_fmin: 6448 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6449 break; 6450 case Intrinsic::amdgcn_ds_fmax: 6451 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6452 break; 6453 default: 6454 llvm_unreachable("Unknown intrinsic!"); 6455 } 6456 SDValue Ops[] = { 6457 M->getOperand(0), // Chain 6458 M->getOperand(2), // Ptr 6459 M->getOperand(3) // Value 6460 }; 6461 6462 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6463 M->getMemoryVT(), M->getMemOperand()); 6464 } 6465 case Intrinsic::amdgcn_buffer_load: 6466 case Intrinsic::amdgcn_buffer_load_format: { 6467 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6468 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6469 unsigned IdxEn = 1; 6470 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6471 IdxEn = Idx->getZExtValue() != 0; 6472 SDValue Ops[] = { 6473 Op.getOperand(0), // Chain 6474 Op.getOperand(2), // rsrc 6475 Op.getOperand(3), // vindex 6476 SDValue(), // voffset -- will be set by setBufferOffsets 6477 SDValue(), // soffset -- will be set by setBufferOffsets 6478 SDValue(), // offset -- will be set by setBufferOffsets 6479 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6480 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6481 }; 6482 6483 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6484 // We don't know the offset if vindex is non-zero, so clear it. 6485 if (IdxEn) 6486 Offset = 0; 6487 6488 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6489 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6490 6491 EVT VT = Op.getValueType(); 6492 EVT IntVT = VT.changeTypeToInteger(); 6493 auto *M = cast<MemSDNode>(Op); 6494 M->getMemOperand()->setOffset(Offset); 6495 EVT LoadVT = Op.getValueType(); 6496 6497 if (LoadVT.getScalarType() == MVT::f16) 6498 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6499 M, DAG, Ops); 6500 6501 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6502 if (LoadVT.getScalarType() == MVT::i8 || 6503 LoadVT.getScalarType() == MVT::i16) 6504 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6505 6506 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6507 M->getMemOperand(), DAG); 6508 } 6509 case Intrinsic::amdgcn_raw_buffer_load: 6510 case Intrinsic::amdgcn_raw_buffer_load_format: { 6511 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6512 6513 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6514 SDValue Ops[] = { 6515 Op.getOperand(0), // Chain 6516 Op.getOperand(2), // rsrc 6517 DAG.getConstant(0, DL, MVT::i32), // vindex 6518 Offsets.first, // voffset 6519 Op.getOperand(4), // soffset 6520 Offsets.second, // offset 6521 Op.getOperand(5), // cachepolicy, swizzled buffer 6522 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6523 }; 6524 6525 auto *M = cast<MemSDNode>(Op); 6526 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6527 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6528 } 6529 case Intrinsic::amdgcn_struct_buffer_load: 6530 case Intrinsic::amdgcn_struct_buffer_load_format: { 6531 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6532 6533 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6534 SDValue Ops[] = { 6535 Op.getOperand(0), // Chain 6536 Op.getOperand(2), // rsrc 6537 Op.getOperand(3), // vindex 6538 Offsets.first, // voffset 6539 Op.getOperand(5), // soffset 6540 Offsets.second, // offset 6541 Op.getOperand(6), // cachepolicy, swizzled buffer 6542 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6543 }; 6544 6545 auto *M = cast<MemSDNode>(Op); 6546 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6547 Ops[2])); 6548 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6549 } 6550 case Intrinsic::amdgcn_tbuffer_load: { 6551 MemSDNode *M = cast<MemSDNode>(Op); 6552 EVT LoadVT = Op.getValueType(); 6553 6554 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6555 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6556 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6557 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6558 unsigned IdxEn = 1; 6559 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6560 IdxEn = Idx->getZExtValue() != 0; 6561 SDValue Ops[] = { 6562 Op.getOperand(0), // Chain 6563 Op.getOperand(2), // rsrc 6564 Op.getOperand(3), // vindex 6565 Op.getOperand(4), // voffset 6566 Op.getOperand(5), // soffset 6567 Op.getOperand(6), // offset 6568 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6569 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6570 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6571 }; 6572 6573 if (LoadVT.getScalarType() == MVT::f16) 6574 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6575 M, DAG, Ops); 6576 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6577 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6578 DAG); 6579 } 6580 case Intrinsic::amdgcn_raw_tbuffer_load: { 6581 MemSDNode *M = cast<MemSDNode>(Op); 6582 EVT LoadVT = Op.getValueType(); 6583 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6584 6585 SDValue Ops[] = { 6586 Op.getOperand(0), // Chain 6587 Op.getOperand(2), // rsrc 6588 DAG.getConstant(0, DL, MVT::i32), // vindex 6589 Offsets.first, // voffset 6590 Op.getOperand(4), // soffset 6591 Offsets.second, // offset 6592 Op.getOperand(5), // format 6593 Op.getOperand(6), // cachepolicy, swizzled buffer 6594 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6595 }; 6596 6597 if (LoadVT.getScalarType() == MVT::f16) 6598 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6599 M, DAG, Ops); 6600 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6601 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6602 DAG); 6603 } 6604 case Intrinsic::amdgcn_struct_tbuffer_load: { 6605 MemSDNode *M = cast<MemSDNode>(Op); 6606 EVT LoadVT = Op.getValueType(); 6607 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6608 6609 SDValue Ops[] = { 6610 Op.getOperand(0), // Chain 6611 Op.getOperand(2), // rsrc 6612 Op.getOperand(3), // vindex 6613 Offsets.first, // voffset 6614 Op.getOperand(5), // soffset 6615 Offsets.second, // offset 6616 Op.getOperand(6), // format 6617 Op.getOperand(7), // cachepolicy, swizzled buffer 6618 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6619 }; 6620 6621 if (LoadVT.getScalarType() == MVT::f16) 6622 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6623 M, DAG, Ops); 6624 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6625 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6626 DAG); 6627 } 6628 case Intrinsic::amdgcn_buffer_atomic_swap: 6629 case Intrinsic::amdgcn_buffer_atomic_add: 6630 case Intrinsic::amdgcn_buffer_atomic_sub: 6631 case Intrinsic::amdgcn_buffer_atomic_smin: 6632 case Intrinsic::amdgcn_buffer_atomic_umin: 6633 case Intrinsic::amdgcn_buffer_atomic_smax: 6634 case Intrinsic::amdgcn_buffer_atomic_umax: 6635 case Intrinsic::amdgcn_buffer_atomic_and: 6636 case Intrinsic::amdgcn_buffer_atomic_or: 6637 case Intrinsic::amdgcn_buffer_atomic_xor: { 6638 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6639 unsigned IdxEn = 1; 6640 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6641 IdxEn = Idx->getZExtValue() != 0; 6642 SDValue Ops[] = { 6643 Op.getOperand(0), // Chain 6644 Op.getOperand(2), // vdata 6645 Op.getOperand(3), // rsrc 6646 Op.getOperand(4), // vindex 6647 SDValue(), // voffset -- will be set by setBufferOffsets 6648 SDValue(), // soffset -- will be set by setBufferOffsets 6649 SDValue(), // offset -- will be set by setBufferOffsets 6650 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6651 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6652 }; 6653 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6654 // We don't know the offset if vindex is non-zero, so clear it. 6655 if (IdxEn) 6656 Offset = 0; 6657 EVT VT = Op.getValueType(); 6658 6659 auto *M = cast<MemSDNode>(Op); 6660 M->getMemOperand()->setOffset(Offset); 6661 unsigned Opcode = 0; 6662 6663 switch (IntrID) { 6664 case Intrinsic::amdgcn_buffer_atomic_swap: 6665 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6666 break; 6667 case Intrinsic::amdgcn_buffer_atomic_add: 6668 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6669 break; 6670 case Intrinsic::amdgcn_buffer_atomic_sub: 6671 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6672 break; 6673 case Intrinsic::amdgcn_buffer_atomic_smin: 6674 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6675 break; 6676 case Intrinsic::amdgcn_buffer_atomic_umin: 6677 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6678 break; 6679 case Intrinsic::amdgcn_buffer_atomic_smax: 6680 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6681 break; 6682 case Intrinsic::amdgcn_buffer_atomic_umax: 6683 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6684 break; 6685 case Intrinsic::amdgcn_buffer_atomic_and: 6686 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6687 break; 6688 case Intrinsic::amdgcn_buffer_atomic_or: 6689 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6690 break; 6691 case Intrinsic::amdgcn_buffer_atomic_xor: 6692 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6693 break; 6694 default: 6695 llvm_unreachable("unhandled atomic opcode"); 6696 } 6697 6698 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6699 M->getMemOperand()); 6700 } 6701 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6702 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6703 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6704 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6705 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6706 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6707 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6708 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6709 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6710 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6711 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6712 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 6713 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6714 SDValue Ops[] = { 6715 Op.getOperand(0), // Chain 6716 Op.getOperand(2), // vdata 6717 Op.getOperand(3), // rsrc 6718 DAG.getConstant(0, DL, MVT::i32), // vindex 6719 Offsets.first, // voffset 6720 Op.getOperand(5), // soffset 6721 Offsets.second, // offset 6722 Op.getOperand(6), // cachepolicy 6723 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6724 }; 6725 EVT VT = Op.getValueType(); 6726 6727 auto *M = cast<MemSDNode>(Op); 6728 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6729 unsigned Opcode = 0; 6730 6731 switch (IntrID) { 6732 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6733 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6734 break; 6735 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6736 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6737 break; 6738 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6739 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6740 break; 6741 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6742 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6743 break; 6744 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6745 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6746 break; 6747 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6748 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6749 break; 6750 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6751 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6752 break; 6753 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6754 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6755 break; 6756 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6757 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6758 break; 6759 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6760 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6761 break; 6762 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6763 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6764 break; 6765 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 6766 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6767 break; 6768 default: 6769 llvm_unreachable("unhandled atomic opcode"); 6770 } 6771 6772 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6773 M->getMemOperand()); 6774 } 6775 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6776 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6777 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6778 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6779 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6780 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6781 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6782 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6783 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6784 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6785 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6786 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 6787 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6788 SDValue Ops[] = { 6789 Op.getOperand(0), // Chain 6790 Op.getOperand(2), // vdata 6791 Op.getOperand(3), // rsrc 6792 Op.getOperand(4), // vindex 6793 Offsets.first, // voffset 6794 Op.getOperand(6), // soffset 6795 Offsets.second, // offset 6796 Op.getOperand(7), // cachepolicy 6797 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6798 }; 6799 EVT VT = Op.getValueType(); 6800 6801 auto *M = cast<MemSDNode>(Op); 6802 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6803 Ops[3])); 6804 unsigned Opcode = 0; 6805 6806 switch (IntrID) { 6807 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6808 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6809 break; 6810 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6811 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6812 break; 6813 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6814 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6815 break; 6816 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6817 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6818 break; 6819 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6820 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6821 break; 6822 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6823 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6824 break; 6825 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6826 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6827 break; 6828 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6829 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6830 break; 6831 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6832 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6833 break; 6834 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6835 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6836 break; 6837 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6838 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6839 break; 6840 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 6841 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6842 break; 6843 default: 6844 llvm_unreachable("unhandled atomic opcode"); 6845 } 6846 6847 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6848 M->getMemOperand()); 6849 } 6850 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 6851 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6852 unsigned IdxEn = 1; 6853 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 6854 IdxEn = Idx->getZExtValue() != 0; 6855 SDValue Ops[] = { 6856 Op.getOperand(0), // Chain 6857 Op.getOperand(2), // src 6858 Op.getOperand(3), // cmp 6859 Op.getOperand(4), // rsrc 6860 Op.getOperand(5), // vindex 6861 SDValue(), // voffset -- will be set by setBufferOffsets 6862 SDValue(), // soffset -- will be set by setBufferOffsets 6863 SDValue(), // offset -- will be set by setBufferOffsets 6864 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6865 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6866 }; 6867 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 6868 // We don't know the offset if vindex is non-zero, so clear it. 6869 if (IdxEn) 6870 Offset = 0; 6871 EVT VT = Op.getValueType(); 6872 auto *M = cast<MemSDNode>(Op); 6873 M->getMemOperand()->setOffset(Offset); 6874 6875 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6876 Op->getVTList(), Ops, VT, M->getMemOperand()); 6877 } 6878 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 6879 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6880 SDValue Ops[] = { 6881 Op.getOperand(0), // Chain 6882 Op.getOperand(2), // src 6883 Op.getOperand(3), // cmp 6884 Op.getOperand(4), // rsrc 6885 DAG.getConstant(0, DL, MVT::i32), // vindex 6886 Offsets.first, // voffset 6887 Op.getOperand(6), // soffset 6888 Offsets.second, // offset 6889 Op.getOperand(7), // cachepolicy 6890 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6891 }; 6892 EVT VT = Op.getValueType(); 6893 auto *M = cast<MemSDNode>(Op); 6894 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 6895 6896 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6897 Op->getVTList(), Ops, VT, M->getMemOperand()); 6898 } 6899 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 6900 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 6901 SDValue Ops[] = { 6902 Op.getOperand(0), // Chain 6903 Op.getOperand(2), // src 6904 Op.getOperand(3), // cmp 6905 Op.getOperand(4), // rsrc 6906 Op.getOperand(5), // vindex 6907 Offsets.first, // voffset 6908 Op.getOperand(7), // soffset 6909 Offsets.second, // offset 6910 Op.getOperand(8), // cachepolicy 6911 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6912 }; 6913 EVT VT = Op.getValueType(); 6914 auto *M = cast<MemSDNode>(Op); 6915 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 6916 Ops[4])); 6917 6918 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6919 Op->getVTList(), Ops, VT, M->getMemOperand()); 6920 } 6921 6922 default: 6923 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6924 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 6925 return lowerImage(Op, ImageDimIntr, DAG); 6926 6927 return SDValue(); 6928 } 6929 } 6930 6931 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 6932 // dwordx4 if on SI. 6933 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 6934 SDVTList VTList, 6935 ArrayRef<SDValue> Ops, EVT MemVT, 6936 MachineMemOperand *MMO, 6937 SelectionDAG &DAG) const { 6938 EVT VT = VTList.VTs[0]; 6939 EVT WidenedVT = VT; 6940 EVT WidenedMemVT = MemVT; 6941 if (!Subtarget->hasDwordx3LoadStores() && 6942 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 6943 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 6944 WidenedVT.getVectorElementType(), 4); 6945 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 6946 WidenedMemVT.getVectorElementType(), 4); 6947 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 6948 } 6949 6950 assert(VTList.NumVTs == 2); 6951 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 6952 6953 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 6954 WidenedMemVT, MMO); 6955 if (WidenedVT != VT) { 6956 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 6957 DAG.getVectorIdxConstant(0, DL)); 6958 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 6959 } 6960 return NewOp; 6961 } 6962 6963 SDValue SITargetLowering::handleD16VData(SDValue VData, 6964 SelectionDAG &DAG) const { 6965 EVT StoreVT = VData.getValueType(); 6966 6967 // No change for f16 and legal vector D16 types. 6968 if (!StoreVT.isVector()) 6969 return VData; 6970 6971 SDLoc DL(VData); 6972 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 6973 6974 if (Subtarget->hasUnpackedD16VMem()) { 6975 // We need to unpack the packed data to store. 6976 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 6977 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 6978 6979 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 6980 StoreVT.getVectorNumElements()); 6981 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 6982 return DAG.UnrollVectorOp(ZExt.getNode()); 6983 } 6984 6985 assert(isTypeLegal(StoreVT)); 6986 return VData; 6987 } 6988 6989 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 6990 SelectionDAG &DAG) const { 6991 SDLoc DL(Op); 6992 SDValue Chain = Op.getOperand(0); 6993 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6994 MachineFunction &MF = DAG.getMachineFunction(); 6995 6996 switch (IntrinsicID) { 6997 case Intrinsic::amdgcn_exp_compr: { 6998 SDValue Src0 = Op.getOperand(4); 6999 SDValue Src1 = Op.getOperand(5); 7000 // Hack around illegal type on SI by directly selecting it. 7001 if (isTypeLegal(Src0.getValueType())) 7002 return SDValue(); 7003 7004 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7005 SDValue Undef = DAG.getUNDEF(MVT::f32); 7006 const SDValue Ops[] = { 7007 Op.getOperand(2), // tgt 7008 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7009 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7010 Undef, // src2 7011 Undef, // src3 7012 Op.getOperand(7), // vm 7013 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7014 Op.getOperand(3), // en 7015 Op.getOperand(0) // Chain 7016 }; 7017 7018 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7019 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7020 } 7021 case Intrinsic::amdgcn_s_barrier: { 7022 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7023 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7024 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7025 if (WGSize <= ST.getWavefrontSize()) 7026 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7027 Op.getOperand(0)), 0); 7028 } 7029 return SDValue(); 7030 }; 7031 case Intrinsic::amdgcn_tbuffer_store: { 7032 SDValue VData = Op.getOperand(2); 7033 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7034 if (IsD16) 7035 VData = handleD16VData(VData, DAG); 7036 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7037 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7038 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7039 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7040 unsigned IdxEn = 1; 7041 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7042 IdxEn = Idx->getZExtValue() != 0; 7043 SDValue Ops[] = { 7044 Chain, 7045 VData, // vdata 7046 Op.getOperand(3), // rsrc 7047 Op.getOperand(4), // vindex 7048 Op.getOperand(5), // voffset 7049 Op.getOperand(6), // soffset 7050 Op.getOperand(7), // offset 7051 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7052 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7053 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7054 }; 7055 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7056 AMDGPUISD::TBUFFER_STORE_FORMAT; 7057 MemSDNode *M = cast<MemSDNode>(Op); 7058 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7059 M->getMemoryVT(), M->getMemOperand()); 7060 } 7061 7062 case Intrinsic::amdgcn_struct_tbuffer_store: { 7063 SDValue VData = Op.getOperand(2); 7064 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7065 if (IsD16) 7066 VData = handleD16VData(VData, DAG); 7067 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7068 SDValue Ops[] = { 7069 Chain, 7070 VData, // vdata 7071 Op.getOperand(3), // rsrc 7072 Op.getOperand(4), // vindex 7073 Offsets.first, // voffset 7074 Op.getOperand(6), // soffset 7075 Offsets.second, // offset 7076 Op.getOperand(7), // format 7077 Op.getOperand(8), // cachepolicy, swizzled buffer 7078 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7079 }; 7080 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7081 AMDGPUISD::TBUFFER_STORE_FORMAT; 7082 MemSDNode *M = cast<MemSDNode>(Op); 7083 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7084 M->getMemoryVT(), M->getMemOperand()); 7085 } 7086 7087 case Intrinsic::amdgcn_raw_tbuffer_store: { 7088 SDValue VData = Op.getOperand(2); 7089 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7090 if (IsD16) 7091 VData = handleD16VData(VData, DAG); 7092 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7093 SDValue Ops[] = { 7094 Chain, 7095 VData, // vdata 7096 Op.getOperand(3), // rsrc 7097 DAG.getConstant(0, DL, MVT::i32), // vindex 7098 Offsets.first, // voffset 7099 Op.getOperand(5), // soffset 7100 Offsets.second, // offset 7101 Op.getOperand(6), // format 7102 Op.getOperand(7), // cachepolicy, swizzled buffer 7103 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7104 }; 7105 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7106 AMDGPUISD::TBUFFER_STORE_FORMAT; 7107 MemSDNode *M = cast<MemSDNode>(Op); 7108 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7109 M->getMemoryVT(), M->getMemOperand()); 7110 } 7111 7112 case Intrinsic::amdgcn_buffer_store: 7113 case Intrinsic::amdgcn_buffer_store_format: { 7114 SDValue VData = Op.getOperand(2); 7115 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7116 if (IsD16) 7117 VData = handleD16VData(VData, DAG); 7118 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7119 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7120 unsigned IdxEn = 1; 7121 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7122 IdxEn = Idx->getZExtValue() != 0; 7123 SDValue Ops[] = { 7124 Chain, 7125 VData, 7126 Op.getOperand(3), // rsrc 7127 Op.getOperand(4), // vindex 7128 SDValue(), // voffset -- will be set by setBufferOffsets 7129 SDValue(), // soffset -- will be set by setBufferOffsets 7130 SDValue(), // offset -- will be set by setBufferOffsets 7131 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7132 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7133 }; 7134 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7135 // We don't know the offset if vindex is non-zero, so clear it. 7136 if (IdxEn) 7137 Offset = 0; 7138 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7139 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7140 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7141 MemSDNode *M = cast<MemSDNode>(Op); 7142 M->getMemOperand()->setOffset(Offset); 7143 7144 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7145 EVT VDataType = VData.getValueType().getScalarType(); 7146 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7147 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7148 7149 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7150 M->getMemoryVT(), M->getMemOperand()); 7151 } 7152 7153 case Intrinsic::amdgcn_raw_buffer_store: 7154 case Intrinsic::amdgcn_raw_buffer_store_format: { 7155 const bool IsFormat = 7156 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7157 7158 SDValue VData = Op.getOperand(2); 7159 EVT VDataVT = VData.getValueType(); 7160 EVT EltType = VDataVT.getScalarType(); 7161 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7162 if (IsD16) 7163 VData = handleD16VData(VData, DAG); 7164 7165 if (!isTypeLegal(VDataVT)) { 7166 VData = 7167 DAG.getNode(ISD::BITCAST, DL, 7168 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7169 } 7170 7171 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7172 SDValue Ops[] = { 7173 Chain, 7174 VData, 7175 Op.getOperand(3), // rsrc 7176 DAG.getConstant(0, DL, MVT::i32), // vindex 7177 Offsets.first, // voffset 7178 Op.getOperand(5), // soffset 7179 Offsets.second, // offset 7180 Op.getOperand(6), // cachepolicy, swizzled buffer 7181 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7182 }; 7183 unsigned Opc = 7184 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7185 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7186 MemSDNode *M = cast<MemSDNode>(Op); 7187 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7188 7189 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7190 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7191 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7192 7193 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7194 M->getMemoryVT(), M->getMemOperand()); 7195 } 7196 7197 case Intrinsic::amdgcn_struct_buffer_store: 7198 case Intrinsic::amdgcn_struct_buffer_store_format: { 7199 const bool IsFormat = 7200 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7201 7202 SDValue VData = Op.getOperand(2); 7203 EVT VDataVT = VData.getValueType(); 7204 EVT EltType = VDataVT.getScalarType(); 7205 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7206 7207 if (IsD16) 7208 VData = handleD16VData(VData, DAG); 7209 7210 if (!isTypeLegal(VDataVT)) { 7211 VData = 7212 DAG.getNode(ISD::BITCAST, DL, 7213 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7214 } 7215 7216 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7217 SDValue Ops[] = { 7218 Chain, 7219 VData, 7220 Op.getOperand(3), // rsrc 7221 Op.getOperand(4), // vindex 7222 Offsets.first, // voffset 7223 Op.getOperand(6), // soffset 7224 Offsets.second, // offset 7225 Op.getOperand(7), // cachepolicy, swizzled buffer 7226 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7227 }; 7228 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7229 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7230 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7231 MemSDNode *M = cast<MemSDNode>(Op); 7232 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7233 Ops[3])); 7234 7235 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7236 EVT VDataType = VData.getValueType().getScalarType(); 7237 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7238 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7239 7240 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7241 M->getMemoryVT(), M->getMemOperand()); 7242 } 7243 7244 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7245 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7246 unsigned IdxEn = 1; 7247 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7248 IdxEn = Idx->getZExtValue() != 0; 7249 SDValue Ops[] = { 7250 Chain, 7251 Op.getOperand(2), // vdata 7252 Op.getOperand(3), // rsrc 7253 Op.getOperand(4), // vindex 7254 SDValue(), // voffset -- will be set by setBufferOffsets 7255 SDValue(), // soffset -- will be set by setBufferOffsets 7256 SDValue(), // offset -- will be set by setBufferOffsets 7257 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7258 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7259 }; 7260 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7261 // We don't know the offset if vindex is non-zero, so clear it. 7262 if (IdxEn) 7263 Offset = 0; 7264 EVT VT = Op.getOperand(2).getValueType(); 7265 7266 auto *M = cast<MemSDNode>(Op); 7267 M->getMemOperand()->setOffset(Offset); 7268 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 7269 : AMDGPUISD::BUFFER_ATOMIC_FADD; 7270 7271 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7272 M->getMemOperand()); 7273 } 7274 7275 case Intrinsic::amdgcn_global_atomic_fadd: { 7276 SDValue Ops[] = { 7277 Chain, 7278 Op.getOperand(2), // ptr 7279 Op.getOperand(3) // vdata 7280 }; 7281 EVT VT = Op.getOperand(3).getValueType(); 7282 7283 auto *M = cast<MemSDNode>(Op); 7284 if (VT.isVector()) { 7285 return DAG.getMemIntrinsicNode( 7286 AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT, 7287 M->getMemOperand()); 7288 } 7289 7290 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7291 DAG.getVTList(VT, MVT::Other), Ops, 7292 M->getMemOperand()).getValue(1); 7293 } 7294 case Intrinsic::amdgcn_end_cf: 7295 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7296 Op->getOperand(2), Chain), 0); 7297 7298 default: { 7299 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7300 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7301 return lowerImage(Op, ImageDimIntr, DAG); 7302 7303 return Op; 7304 } 7305 } 7306 } 7307 7308 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7309 // offset (the offset that is included in bounds checking and swizzling, to be 7310 // split between the instruction's voffset and immoffset fields) and soffset 7311 // (the offset that is excluded from bounds checking and swizzling, to go in 7312 // the instruction's soffset field). This function takes the first kind of 7313 // offset and figures out how to split it between voffset and immoffset. 7314 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7315 SDValue Offset, SelectionDAG &DAG) const { 7316 SDLoc DL(Offset); 7317 const unsigned MaxImm = 4095; 7318 SDValue N0 = Offset; 7319 ConstantSDNode *C1 = nullptr; 7320 7321 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7322 N0 = SDValue(); 7323 else if (DAG.isBaseWithConstantOffset(N0)) { 7324 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7325 N0 = N0.getOperand(0); 7326 } 7327 7328 if (C1) { 7329 unsigned ImmOffset = C1->getZExtValue(); 7330 // If the immediate value is too big for the immoffset field, put the value 7331 // and -4096 into the immoffset field so that the value that is copied/added 7332 // for the voffset field is a multiple of 4096, and it stands more chance 7333 // of being CSEd with the copy/add for another similar load/store. 7334 // However, do not do that rounding down to a multiple of 4096 if that is a 7335 // negative number, as it appears to be illegal to have a negative offset 7336 // in the vgpr, even if adding the immediate offset makes it positive. 7337 unsigned Overflow = ImmOffset & ~MaxImm; 7338 ImmOffset -= Overflow; 7339 if ((int32_t)Overflow < 0) { 7340 Overflow += ImmOffset; 7341 ImmOffset = 0; 7342 } 7343 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7344 if (Overflow) { 7345 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7346 if (!N0) 7347 N0 = OverflowVal; 7348 else { 7349 SDValue Ops[] = { N0, OverflowVal }; 7350 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7351 } 7352 } 7353 } 7354 if (!N0) 7355 N0 = DAG.getConstant(0, DL, MVT::i32); 7356 if (!C1) 7357 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7358 return {N0, SDValue(C1, 0)}; 7359 } 7360 7361 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7362 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7363 // pointed to by Offsets. 7364 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7365 SelectionDAG &DAG, SDValue *Offsets, 7366 unsigned Align) const { 7367 SDLoc DL(CombinedOffset); 7368 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7369 uint32_t Imm = C->getZExtValue(); 7370 uint32_t SOffset, ImmOffset; 7371 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 7372 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7373 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7374 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7375 return SOffset + ImmOffset; 7376 } 7377 } 7378 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7379 SDValue N0 = CombinedOffset.getOperand(0); 7380 SDValue N1 = CombinedOffset.getOperand(1); 7381 uint32_t SOffset, ImmOffset; 7382 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7383 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7384 Subtarget, Align)) { 7385 Offsets[0] = N0; 7386 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7387 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7388 return 0; 7389 } 7390 } 7391 Offsets[0] = CombinedOffset; 7392 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7393 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7394 return 0; 7395 } 7396 7397 // Handle 8 bit and 16 bit buffer loads 7398 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7399 EVT LoadVT, SDLoc DL, 7400 ArrayRef<SDValue> Ops, 7401 MemSDNode *M) const { 7402 EVT IntVT = LoadVT.changeTypeToInteger(); 7403 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7404 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7405 7406 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7407 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7408 Ops, IntVT, 7409 M->getMemOperand()); 7410 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7411 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7412 7413 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7414 } 7415 7416 // Handle 8 bit and 16 bit buffer stores 7417 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7418 EVT VDataType, SDLoc DL, 7419 SDValue Ops[], 7420 MemSDNode *M) const { 7421 if (VDataType == MVT::f16) 7422 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7423 7424 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7425 Ops[1] = BufferStoreExt; 7426 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7427 AMDGPUISD::BUFFER_STORE_SHORT; 7428 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7429 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7430 M->getMemOperand()); 7431 } 7432 7433 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7434 ISD::LoadExtType ExtType, SDValue Op, 7435 const SDLoc &SL, EVT VT) { 7436 if (VT.bitsLT(Op.getValueType())) 7437 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7438 7439 switch (ExtType) { 7440 case ISD::SEXTLOAD: 7441 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7442 case ISD::ZEXTLOAD: 7443 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7444 case ISD::EXTLOAD: 7445 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7446 case ISD::NON_EXTLOAD: 7447 return Op; 7448 } 7449 7450 llvm_unreachable("invalid ext type"); 7451 } 7452 7453 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7454 SelectionDAG &DAG = DCI.DAG; 7455 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7456 return SDValue(); 7457 7458 // FIXME: Constant loads should all be marked invariant. 7459 unsigned AS = Ld->getAddressSpace(); 7460 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7461 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7462 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7463 return SDValue(); 7464 7465 // Don't do this early, since it may interfere with adjacent load merging for 7466 // illegal types. We can avoid losing alignment information for exotic types 7467 // pre-legalize. 7468 EVT MemVT = Ld->getMemoryVT(); 7469 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7470 MemVT.getSizeInBits() >= 32) 7471 return SDValue(); 7472 7473 SDLoc SL(Ld); 7474 7475 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7476 "unexpected vector extload"); 7477 7478 // TODO: Drop only high part of range. 7479 SDValue Ptr = Ld->getBasePtr(); 7480 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7481 MVT::i32, SL, Ld->getChain(), Ptr, 7482 Ld->getOffset(), 7483 Ld->getPointerInfo(), MVT::i32, 7484 Ld->getAlignment(), 7485 Ld->getMemOperand()->getFlags(), 7486 Ld->getAAInfo(), 7487 nullptr); // Drop ranges 7488 7489 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7490 if (MemVT.isFloatingPoint()) { 7491 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7492 "unexpected fp extload"); 7493 TruncVT = MemVT.changeTypeToInteger(); 7494 } 7495 7496 SDValue Cvt = NewLoad; 7497 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7498 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7499 DAG.getValueType(TruncVT)); 7500 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7501 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7502 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7503 } else { 7504 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7505 } 7506 7507 EVT VT = Ld->getValueType(0); 7508 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7509 7510 DCI.AddToWorklist(Cvt.getNode()); 7511 7512 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7513 // the appropriate extension from the 32-bit load. 7514 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7515 DCI.AddToWorklist(Cvt.getNode()); 7516 7517 // Handle conversion back to floating point if necessary. 7518 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7519 7520 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7521 } 7522 7523 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7524 SDLoc DL(Op); 7525 LoadSDNode *Load = cast<LoadSDNode>(Op); 7526 ISD::LoadExtType ExtType = Load->getExtensionType(); 7527 EVT MemVT = Load->getMemoryVT(); 7528 7529 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7530 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7531 return SDValue(); 7532 7533 // FIXME: Copied from PPC 7534 // First, load into 32 bits, then truncate to 1 bit. 7535 7536 SDValue Chain = Load->getChain(); 7537 SDValue BasePtr = Load->getBasePtr(); 7538 MachineMemOperand *MMO = Load->getMemOperand(); 7539 7540 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7541 7542 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7543 BasePtr, RealMemVT, MMO); 7544 7545 if (!MemVT.isVector()) { 7546 SDValue Ops[] = { 7547 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7548 NewLD.getValue(1) 7549 }; 7550 7551 return DAG.getMergeValues(Ops, DL); 7552 } 7553 7554 SmallVector<SDValue, 3> Elts; 7555 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7556 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7557 DAG.getConstant(I, DL, MVT::i32)); 7558 7559 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7560 } 7561 7562 SDValue Ops[] = { 7563 DAG.getBuildVector(MemVT, DL, Elts), 7564 NewLD.getValue(1) 7565 }; 7566 7567 return DAG.getMergeValues(Ops, DL); 7568 } 7569 7570 if (!MemVT.isVector()) 7571 return SDValue(); 7572 7573 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7574 "Custom lowering for non-i32 vectors hasn't been implemented."); 7575 7576 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7577 MemVT, *Load->getMemOperand())) { 7578 SDValue Ops[2]; 7579 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7580 return DAG.getMergeValues(Ops, DL); 7581 } 7582 7583 unsigned Alignment = Load->getAlignment(); 7584 unsigned AS = Load->getAddressSpace(); 7585 if (Subtarget->hasLDSMisalignedBug() && 7586 AS == AMDGPUAS::FLAT_ADDRESS && 7587 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7588 return SplitVectorLoad(Op, DAG); 7589 } 7590 7591 MachineFunction &MF = DAG.getMachineFunction(); 7592 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7593 // If there is a possibilty that flat instruction access scratch memory 7594 // then we need to use the same legalization rules we use for private. 7595 if (AS == AMDGPUAS::FLAT_ADDRESS && 7596 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7597 AS = MFI->hasFlatScratchInit() ? 7598 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7599 7600 unsigned NumElements = MemVT.getVectorNumElements(); 7601 7602 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7603 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7604 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7605 if (MemVT.isPow2VectorType()) 7606 return SDValue(); 7607 if (NumElements == 3) 7608 return WidenVectorLoad(Op, DAG); 7609 return SplitVectorLoad(Op, DAG); 7610 } 7611 // Non-uniform loads will be selected to MUBUF instructions, so they 7612 // have the same legalization requirements as global and private 7613 // loads. 7614 // 7615 } 7616 7617 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7618 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7619 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7620 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7621 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 7622 Alignment >= 4 && NumElements < 32) { 7623 if (MemVT.isPow2VectorType()) 7624 return SDValue(); 7625 if (NumElements == 3) 7626 return WidenVectorLoad(Op, DAG); 7627 return SplitVectorLoad(Op, DAG); 7628 } 7629 // Non-uniform loads will be selected to MUBUF instructions, so they 7630 // have the same legalization requirements as global and private 7631 // loads. 7632 // 7633 } 7634 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7635 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7636 AS == AMDGPUAS::GLOBAL_ADDRESS || 7637 AS == AMDGPUAS::FLAT_ADDRESS) { 7638 if (NumElements > 4) 7639 return SplitVectorLoad(Op, DAG); 7640 // v3 loads not supported on SI. 7641 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7642 return WidenVectorLoad(Op, DAG); 7643 // v3 and v4 loads are supported for private and global memory. 7644 return SDValue(); 7645 } 7646 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7647 // Depending on the setting of the private_element_size field in the 7648 // resource descriptor, we can only make private accesses up to a certain 7649 // size. 7650 switch (Subtarget->getMaxPrivateElementSize()) { 7651 case 4: { 7652 SDValue Ops[2]; 7653 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7654 return DAG.getMergeValues(Ops, DL); 7655 } 7656 case 8: 7657 if (NumElements > 2) 7658 return SplitVectorLoad(Op, DAG); 7659 return SDValue(); 7660 case 16: 7661 // Same as global/flat 7662 if (NumElements > 4) 7663 return SplitVectorLoad(Op, DAG); 7664 // v3 loads not supported on SI. 7665 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7666 return WidenVectorLoad(Op, DAG); 7667 return SDValue(); 7668 default: 7669 llvm_unreachable("unsupported private_element_size"); 7670 } 7671 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7672 // Use ds_read_b128 if possible. 7673 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7674 MemVT.getStoreSize() == 16) 7675 return SDValue(); 7676 7677 if (NumElements > 2) 7678 return SplitVectorLoad(Op, DAG); 7679 7680 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7681 // address is negative, then the instruction is incorrectly treated as 7682 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7683 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7684 // load later in the SILoadStoreOptimizer. 7685 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7686 NumElements == 2 && MemVT.getStoreSize() == 8 && 7687 Load->getAlignment() < 8) { 7688 return SplitVectorLoad(Op, DAG); 7689 } 7690 } 7691 return SDValue(); 7692 } 7693 7694 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7695 EVT VT = Op.getValueType(); 7696 assert(VT.getSizeInBits() == 64); 7697 7698 SDLoc DL(Op); 7699 SDValue Cond = Op.getOperand(0); 7700 7701 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7702 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7703 7704 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7705 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7706 7707 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7708 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7709 7710 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7711 7712 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7713 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7714 7715 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7716 7717 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7718 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7719 } 7720 7721 // Catch division cases where we can use shortcuts with rcp and rsq 7722 // instructions. 7723 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7724 SelectionDAG &DAG) const { 7725 SDLoc SL(Op); 7726 SDValue LHS = Op.getOperand(0); 7727 SDValue RHS = Op.getOperand(1); 7728 EVT VT = Op.getValueType(); 7729 const SDNodeFlags Flags = Op->getFlags(); 7730 7731 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 7732 Flags.hasApproximateFuncs(); 7733 7734 // Without !fpmath accuracy information, we can't do more because we don't 7735 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 7736 if (!AllowInaccurateRcp) 7737 return SDValue(); 7738 7739 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7740 if (CLHS->isExactlyValue(1.0)) { 7741 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7742 // the CI documentation has a worst case error of 1 ulp. 7743 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7744 // use it as long as we aren't trying to use denormals. 7745 // 7746 // v_rcp_f16 and v_rsq_f16 DO support denormals. 7747 7748 // 1.0 / sqrt(x) -> rsq(x) 7749 7750 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 7751 // error seems really high at 2^29 ULP. 7752 if (RHS.getOpcode() == ISD::FSQRT) 7753 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 7754 7755 // 1.0 / x -> rcp(x) 7756 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7757 } 7758 7759 // Same as for 1.0, but expand the sign out of the constant. 7760 if (CLHS->isExactlyValue(-1.0)) { 7761 // -1.0 / x -> rcp (fneg x) 7762 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7763 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 7764 } 7765 } 7766 7767 // Turn into multiply by the reciprocal. 7768 // x / y -> x * (1.0 / y) 7769 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7770 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 7771 } 7772 7773 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7774 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 7775 if (GlueChain->getNumValues() <= 1) { 7776 return DAG.getNode(Opcode, SL, VT, A, B); 7777 } 7778 7779 assert(GlueChain->getNumValues() == 3); 7780 7781 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7782 switch (Opcode) { 7783 default: llvm_unreachable("no chain equivalent for opcode"); 7784 case ISD::FMUL: 7785 Opcode = AMDGPUISD::FMUL_W_CHAIN; 7786 break; 7787 } 7788 7789 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 7790 GlueChain.getValue(2)); 7791 } 7792 7793 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7794 EVT VT, SDValue A, SDValue B, SDValue C, 7795 SDValue GlueChain) { 7796 if (GlueChain->getNumValues() <= 1) { 7797 return DAG.getNode(Opcode, SL, VT, A, B, C); 7798 } 7799 7800 assert(GlueChain->getNumValues() == 3); 7801 7802 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7803 switch (Opcode) { 7804 default: llvm_unreachable("no chain equivalent for opcode"); 7805 case ISD::FMA: 7806 Opcode = AMDGPUISD::FMA_W_CHAIN; 7807 break; 7808 } 7809 7810 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 7811 GlueChain.getValue(2)); 7812 } 7813 7814 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 7815 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7816 return FastLowered; 7817 7818 SDLoc SL(Op); 7819 SDValue Src0 = Op.getOperand(0); 7820 SDValue Src1 = Op.getOperand(1); 7821 7822 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 7823 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 7824 7825 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 7826 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 7827 7828 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 7829 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 7830 7831 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 7832 } 7833 7834 // Faster 2.5 ULP division that does not support denormals. 7835 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 7836 SDLoc SL(Op); 7837 SDValue LHS = Op.getOperand(1); 7838 SDValue RHS = Op.getOperand(2); 7839 7840 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 7841 7842 const APFloat K0Val(BitsToFloat(0x6f800000)); 7843 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 7844 7845 const APFloat K1Val(BitsToFloat(0x2f800000)); 7846 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 7847 7848 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7849 7850 EVT SetCCVT = 7851 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 7852 7853 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 7854 7855 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 7856 7857 // TODO: Should this propagate fast-math-flags? 7858 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 7859 7860 // rcp does not support denormals. 7861 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 7862 7863 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 7864 7865 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 7866 } 7867 7868 // Returns immediate value for setting the F32 denorm mode when using the 7869 // S_DENORM_MODE instruction. 7870 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 7871 const SDLoc &SL, const GCNSubtarget *ST) { 7872 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 7873 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 7874 ? FP_DENORM_FLUSH_NONE 7875 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 7876 7877 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 7878 return DAG.getTargetConstant(Mode, SL, MVT::i32); 7879 } 7880 7881 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 7882 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7883 return FastLowered; 7884 7885 SDLoc SL(Op); 7886 SDValue LHS = Op.getOperand(0); 7887 SDValue RHS = Op.getOperand(1); 7888 7889 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7890 7891 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 7892 7893 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7894 RHS, RHS, LHS); 7895 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7896 LHS, RHS, LHS); 7897 7898 // Denominator is scaled to not be denormal, so using rcp is ok. 7899 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 7900 DenominatorScaled); 7901 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 7902 DenominatorScaled); 7903 7904 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 7905 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 7906 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 7907 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 7908 7909 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 7910 7911 if (!HasFP32Denormals) { 7912 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 7913 7914 SDValue EnableDenorm; 7915 if (Subtarget->hasDenormModeInst()) { 7916 const SDValue EnableDenormValue = 7917 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 7918 7919 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 7920 DAG.getEntryNode(), EnableDenormValue); 7921 } else { 7922 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 7923 SL, MVT::i32); 7924 EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 7925 DAG.getEntryNode(), EnableDenormValue, 7926 BitField); 7927 } 7928 7929 SDValue Ops[3] = { 7930 NegDivScale0, 7931 EnableDenorm.getValue(0), 7932 EnableDenorm.getValue(1) 7933 }; 7934 7935 NegDivScale0 = DAG.getMergeValues(Ops, SL); 7936 } 7937 7938 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 7939 ApproxRcp, One, NegDivScale0); 7940 7941 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 7942 ApproxRcp, Fma0); 7943 7944 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 7945 Fma1, Fma1); 7946 7947 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 7948 NumeratorScaled, Mul); 7949 7950 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 7951 7952 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 7953 NumeratorScaled, Fma3); 7954 7955 if (!HasFP32Denormals) { 7956 SDValue DisableDenorm; 7957 if (Subtarget->hasDenormModeInst()) { 7958 const SDValue DisableDenormValue = 7959 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 7960 7961 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 7962 Fma4.getValue(1), DisableDenormValue, 7963 Fma4.getValue(2)); 7964 } else { 7965 const SDValue DisableDenormValue = 7966 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 7967 7968 DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 7969 Fma4.getValue(1), DisableDenormValue, 7970 BitField, Fma4.getValue(2)); 7971 } 7972 7973 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 7974 DisableDenorm, DAG.getRoot()); 7975 DAG.setRoot(OutputChain); 7976 } 7977 7978 SDValue Scale = NumeratorScaled.getValue(1); 7979 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 7980 Fma4, Fma1, Fma3, Scale); 7981 7982 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 7983 } 7984 7985 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 7986 if (DAG.getTarget().Options.UnsafeFPMath) 7987 return lowerFastUnsafeFDIV(Op, DAG); 7988 7989 SDLoc SL(Op); 7990 SDValue X = Op.getOperand(0); 7991 SDValue Y = Op.getOperand(1); 7992 7993 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 7994 7995 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 7996 7997 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 7998 7999 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8000 8001 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8002 8003 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8004 8005 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8006 8007 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8008 8009 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8010 8011 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8012 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8013 8014 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8015 NegDivScale0, Mul, DivScale1); 8016 8017 SDValue Scale; 8018 8019 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8020 // Workaround a hardware bug on SI where the condition output from div_scale 8021 // is not usable. 8022 8023 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8024 8025 // Figure out if the scale to use for div_fmas. 8026 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8027 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8028 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8029 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8030 8031 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8032 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8033 8034 SDValue Scale0Hi 8035 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8036 SDValue Scale1Hi 8037 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8038 8039 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8040 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8041 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8042 } else { 8043 Scale = DivScale1.getValue(1); 8044 } 8045 8046 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8047 Fma4, Fma3, Mul, Scale); 8048 8049 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8050 } 8051 8052 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8053 EVT VT = Op.getValueType(); 8054 8055 if (VT == MVT::f32) 8056 return LowerFDIV32(Op, DAG); 8057 8058 if (VT == MVT::f64) 8059 return LowerFDIV64(Op, DAG); 8060 8061 if (VT == MVT::f16) 8062 return LowerFDIV16(Op, DAG); 8063 8064 llvm_unreachable("Unexpected type for fdiv"); 8065 } 8066 8067 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8068 SDLoc DL(Op); 8069 StoreSDNode *Store = cast<StoreSDNode>(Op); 8070 EVT VT = Store->getMemoryVT(); 8071 8072 if (VT == MVT::i1) { 8073 return DAG.getTruncStore(Store->getChain(), DL, 8074 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8075 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8076 } 8077 8078 assert(VT.isVector() && 8079 Store->getValue().getValueType().getScalarType() == MVT::i32); 8080 8081 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8082 VT, *Store->getMemOperand())) { 8083 return expandUnalignedStore(Store, DAG); 8084 } 8085 8086 unsigned AS = Store->getAddressSpace(); 8087 if (Subtarget->hasLDSMisalignedBug() && 8088 AS == AMDGPUAS::FLAT_ADDRESS && 8089 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8090 return SplitVectorStore(Op, DAG); 8091 } 8092 8093 MachineFunction &MF = DAG.getMachineFunction(); 8094 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8095 // If there is a possibilty that flat instruction access scratch memory 8096 // then we need to use the same legalization rules we use for private. 8097 if (AS == AMDGPUAS::FLAT_ADDRESS && 8098 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8099 AS = MFI->hasFlatScratchInit() ? 8100 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8101 8102 unsigned NumElements = VT.getVectorNumElements(); 8103 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8104 AS == AMDGPUAS::FLAT_ADDRESS) { 8105 if (NumElements > 4) 8106 return SplitVectorStore(Op, DAG); 8107 // v3 stores not supported on SI. 8108 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8109 return SplitVectorStore(Op, DAG); 8110 return SDValue(); 8111 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8112 switch (Subtarget->getMaxPrivateElementSize()) { 8113 case 4: 8114 return scalarizeVectorStore(Store, DAG); 8115 case 8: 8116 if (NumElements > 2) 8117 return SplitVectorStore(Op, DAG); 8118 return SDValue(); 8119 case 16: 8120 if (NumElements > 4 || NumElements == 3) 8121 return SplitVectorStore(Op, DAG); 8122 return SDValue(); 8123 default: 8124 llvm_unreachable("unsupported private_element_size"); 8125 } 8126 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8127 // Use ds_write_b128 if possible. 8128 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 8129 VT.getStoreSize() == 16 && NumElements != 3) 8130 return SDValue(); 8131 8132 if (NumElements > 2) 8133 return SplitVectorStore(Op, DAG); 8134 8135 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8136 // address is negative, then the instruction is incorrectly treated as 8137 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8138 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8139 // store later in the SILoadStoreOptimizer. 8140 if (!Subtarget->hasUsableDSOffset() && 8141 NumElements == 2 && VT.getStoreSize() == 8 && 8142 Store->getAlignment() < 8) { 8143 return SplitVectorStore(Op, DAG); 8144 } 8145 8146 return SDValue(); 8147 } else { 8148 llvm_unreachable("unhandled address space"); 8149 } 8150 } 8151 8152 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8153 SDLoc DL(Op); 8154 EVT VT = Op.getValueType(); 8155 SDValue Arg = Op.getOperand(0); 8156 SDValue TrigVal; 8157 8158 // TODO: Should this propagate fast-math-flags? 8159 8160 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT); 8161 8162 if (Subtarget->hasTrigReducedRange()) { 8163 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 8164 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal); 8165 } else { 8166 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 8167 } 8168 8169 switch (Op.getOpcode()) { 8170 case ISD::FCOS: 8171 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal); 8172 case ISD::FSIN: 8173 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal); 8174 default: 8175 llvm_unreachable("Wrong trig opcode"); 8176 } 8177 } 8178 8179 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8180 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8181 assert(AtomicNode->isCompareAndSwap()); 8182 unsigned AS = AtomicNode->getAddressSpace(); 8183 8184 // No custom lowering required for local address space 8185 if (!isFlatGlobalAddrSpace(AS)) 8186 return Op; 8187 8188 // Non-local address space requires custom lowering for atomic compare 8189 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8190 SDLoc DL(Op); 8191 SDValue ChainIn = Op.getOperand(0); 8192 SDValue Addr = Op.getOperand(1); 8193 SDValue Old = Op.getOperand(2); 8194 SDValue New = Op.getOperand(3); 8195 EVT VT = Op.getValueType(); 8196 MVT SimpleVT = VT.getSimpleVT(); 8197 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8198 8199 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8200 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8201 8202 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8203 Ops, VT, AtomicNode->getMemOperand()); 8204 } 8205 8206 //===----------------------------------------------------------------------===// 8207 // Custom DAG optimizations 8208 //===----------------------------------------------------------------------===// 8209 8210 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8211 DAGCombinerInfo &DCI) const { 8212 EVT VT = N->getValueType(0); 8213 EVT ScalarVT = VT.getScalarType(); 8214 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8215 return SDValue(); 8216 8217 SelectionDAG &DAG = DCI.DAG; 8218 SDLoc DL(N); 8219 8220 SDValue Src = N->getOperand(0); 8221 EVT SrcVT = Src.getValueType(); 8222 8223 // TODO: We could try to match extracting the higher bytes, which would be 8224 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8225 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8226 // about in practice. 8227 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8228 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8229 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8230 DCI.AddToWorklist(Cvt.getNode()); 8231 8232 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8233 if (ScalarVT != MVT::f32) { 8234 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8235 DAG.getTargetConstant(0, DL, MVT::i32)); 8236 } 8237 return Cvt; 8238 } 8239 } 8240 8241 return SDValue(); 8242 } 8243 8244 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8245 8246 // This is a variant of 8247 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8248 // 8249 // The normal DAG combiner will do this, but only if the add has one use since 8250 // that would increase the number of instructions. 8251 // 8252 // This prevents us from seeing a constant offset that can be folded into a 8253 // memory instruction's addressing mode. If we know the resulting add offset of 8254 // a pointer can be folded into an addressing offset, we can replace the pointer 8255 // operand with the add of new constant offset. This eliminates one of the uses, 8256 // and may allow the remaining use to also be simplified. 8257 // 8258 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8259 unsigned AddrSpace, 8260 EVT MemVT, 8261 DAGCombinerInfo &DCI) const { 8262 SDValue N0 = N->getOperand(0); 8263 SDValue N1 = N->getOperand(1); 8264 8265 // We only do this to handle cases where it's profitable when there are 8266 // multiple uses of the add, so defer to the standard combine. 8267 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8268 N0->hasOneUse()) 8269 return SDValue(); 8270 8271 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8272 if (!CN1) 8273 return SDValue(); 8274 8275 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8276 if (!CAdd) 8277 return SDValue(); 8278 8279 // If the resulting offset is too large, we can't fold it into the addressing 8280 // mode offset. 8281 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8282 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8283 8284 AddrMode AM; 8285 AM.HasBaseReg = true; 8286 AM.BaseOffs = Offset.getSExtValue(); 8287 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8288 return SDValue(); 8289 8290 SelectionDAG &DAG = DCI.DAG; 8291 SDLoc SL(N); 8292 EVT VT = N->getValueType(0); 8293 8294 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8295 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 8296 8297 SDNodeFlags Flags; 8298 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8299 (N0.getOpcode() == ISD::OR || 8300 N0->getFlags().hasNoUnsignedWrap())); 8301 8302 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8303 } 8304 8305 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8306 DAGCombinerInfo &DCI) const { 8307 SDValue Ptr = N->getBasePtr(); 8308 SelectionDAG &DAG = DCI.DAG; 8309 SDLoc SL(N); 8310 8311 // TODO: We could also do this for multiplies. 8312 if (Ptr.getOpcode() == ISD::SHL) { 8313 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8314 N->getMemoryVT(), DCI); 8315 if (NewPtr) { 8316 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8317 8318 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8319 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8320 } 8321 } 8322 8323 return SDValue(); 8324 } 8325 8326 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8327 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8328 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8329 (Opc == ISD::XOR && Val == 0); 8330 } 8331 8332 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8333 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8334 // integer combine opportunities since most 64-bit operations are decomposed 8335 // this way. TODO: We won't want this for SALU especially if it is an inline 8336 // immediate. 8337 SDValue SITargetLowering::splitBinaryBitConstantOp( 8338 DAGCombinerInfo &DCI, 8339 const SDLoc &SL, 8340 unsigned Opc, SDValue LHS, 8341 const ConstantSDNode *CRHS) const { 8342 uint64_t Val = CRHS->getZExtValue(); 8343 uint32_t ValLo = Lo_32(Val); 8344 uint32_t ValHi = Hi_32(Val); 8345 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8346 8347 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8348 bitOpWithConstantIsReducible(Opc, ValHi)) || 8349 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8350 // If we need to materialize a 64-bit immediate, it will be split up later 8351 // anyway. Avoid creating the harder to understand 64-bit immediate 8352 // materialization. 8353 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8354 } 8355 8356 return SDValue(); 8357 } 8358 8359 // Returns true if argument is a boolean value which is not serialized into 8360 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8361 static bool isBoolSGPR(SDValue V) { 8362 if (V.getValueType() != MVT::i1) 8363 return false; 8364 switch (V.getOpcode()) { 8365 default: break; 8366 case ISD::SETCC: 8367 case ISD::AND: 8368 case ISD::OR: 8369 case ISD::XOR: 8370 case AMDGPUISD::FP_CLASS: 8371 return true; 8372 } 8373 return false; 8374 } 8375 8376 // If a constant has all zeroes or all ones within each byte return it. 8377 // Otherwise return 0. 8378 static uint32_t getConstantPermuteMask(uint32_t C) { 8379 // 0xff for any zero byte in the mask 8380 uint32_t ZeroByteMask = 0; 8381 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8382 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8383 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8384 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8385 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8386 if ((NonZeroByteMask & C) != NonZeroByteMask) 8387 return 0; // Partial bytes selected. 8388 return C; 8389 } 8390 8391 // Check if a node selects whole bytes from its operand 0 starting at a byte 8392 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8393 // or -1 if not succeeded. 8394 // Note byte select encoding: 8395 // value 0-3 selects corresponding source byte; 8396 // value 0xc selects zero; 8397 // value 0xff selects 0xff. 8398 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8399 assert(V.getValueSizeInBits() == 32); 8400 8401 if (V.getNumOperands() != 2) 8402 return ~0; 8403 8404 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8405 if (!N1) 8406 return ~0; 8407 8408 uint32_t C = N1->getZExtValue(); 8409 8410 switch (V.getOpcode()) { 8411 default: 8412 break; 8413 case ISD::AND: 8414 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8415 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8416 } 8417 break; 8418 8419 case ISD::OR: 8420 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8421 return (0x03020100 & ~ConstMask) | ConstMask; 8422 } 8423 break; 8424 8425 case ISD::SHL: 8426 if (C % 8) 8427 return ~0; 8428 8429 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8430 8431 case ISD::SRL: 8432 if (C % 8) 8433 return ~0; 8434 8435 return uint32_t(0x0c0c0c0c03020100ull >> C); 8436 } 8437 8438 return ~0; 8439 } 8440 8441 SDValue SITargetLowering::performAndCombine(SDNode *N, 8442 DAGCombinerInfo &DCI) const { 8443 if (DCI.isBeforeLegalize()) 8444 return SDValue(); 8445 8446 SelectionDAG &DAG = DCI.DAG; 8447 EVT VT = N->getValueType(0); 8448 SDValue LHS = N->getOperand(0); 8449 SDValue RHS = N->getOperand(1); 8450 8451 8452 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8453 if (VT == MVT::i64 && CRHS) { 8454 if (SDValue Split 8455 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8456 return Split; 8457 } 8458 8459 if (CRHS && VT == MVT::i32) { 8460 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8461 // nb = number of trailing zeroes in mask 8462 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8463 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8464 uint64_t Mask = CRHS->getZExtValue(); 8465 unsigned Bits = countPopulation(Mask); 8466 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8467 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8468 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8469 unsigned Shift = CShift->getZExtValue(); 8470 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8471 unsigned Offset = NB + Shift; 8472 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8473 SDLoc SL(N); 8474 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8475 LHS->getOperand(0), 8476 DAG.getConstant(Offset, SL, MVT::i32), 8477 DAG.getConstant(Bits, SL, MVT::i32)); 8478 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8479 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8480 DAG.getValueType(NarrowVT)); 8481 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8482 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8483 return Shl; 8484 } 8485 } 8486 } 8487 8488 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8489 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8490 isa<ConstantSDNode>(LHS.getOperand(2))) { 8491 uint32_t Sel = getConstantPermuteMask(Mask); 8492 if (!Sel) 8493 return SDValue(); 8494 8495 // Select 0xc for all zero bytes 8496 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8497 SDLoc DL(N); 8498 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8499 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8500 } 8501 } 8502 8503 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8504 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8505 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8506 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8507 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8508 8509 SDValue X = LHS.getOperand(0); 8510 SDValue Y = RHS.getOperand(0); 8511 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8512 return SDValue(); 8513 8514 if (LCC == ISD::SETO) { 8515 if (X != LHS.getOperand(1)) 8516 return SDValue(); 8517 8518 if (RCC == ISD::SETUNE) { 8519 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8520 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8521 return SDValue(); 8522 8523 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8524 SIInstrFlags::N_SUBNORMAL | 8525 SIInstrFlags::N_ZERO | 8526 SIInstrFlags::P_ZERO | 8527 SIInstrFlags::P_SUBNORMAL | 8528 SIInstrFlags::P_NORMAL; 8529 8530 static_assert(((~(SIInstrFlags::S_NAN | 8531 SIInstrFlags::Q_NAN | 8532 SIInstrFlags::N_INFINITY | 8533 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8534 "mask not equal"); 8535 8536 SDLoc DL(N); 8537 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8538 X, DAG.getConstant(Mask, DL, MVT::i32)); 8539 } 8540 } 8541 } 8542 8543 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8544 std::swap(LHS, RHS); 8545 8546 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8547 RHS.hasOneUse()) { 8548 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8549 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8550 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8551 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8552 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8553 (RHS.getOperand(0) == LHS.getOperand(0) && 8554 LHS.getOperand(0) == LHS.getOperand(1))) { 8555 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8556 unsigned NewMask = LCC == ISD::SETO ? 8557 Mask->getZExtValue() & ~OrdMask : 8558 Mask->getZExtValue() & OrdMask; 8559 8560 SDLoc DL(N); 8561 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8562 DAG.getConstant(NewMask, DL, MVT::i32)); 8563 } 8564 } 8565 8566 if (VT == MVT::i32 && 8567 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8568 // and x, (sext cc from i1) => select cc, x, 0 8569 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8570 std::swap(LHS, RHS); 8571 if (isBoolSGPR(RHS.getOperand(0))) 8572 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8573 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8574 } 8575 8576 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8577 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8578 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8579 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8580 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8581 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8582 if (LHSMask != ~0u && RHSMask != ~0u) { 8583 // Canonicalize the expression in an attempt to have fewer unique masks 8584 // and therefore fewer registers used to hold the masks. 8585 if (LHSMask > RHSMask) { 8586 std::swap(LHSMask, RHSMask); 8587 std::swap(LHS, RHS); 8588 } 8589 8590 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8591 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8592 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8593 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8594 8595 // Check of we need to combine values from two sources within a byte. 8596 if (!(LHSUsedLanes & RHSUsedLanes) && 8597 // If we select high and lower word keep it for SDWA. 8598 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8599 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8600 // Each byte in each mask is either selector mask 0-3, or has higher 8601 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8602 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8603 // mask which is not 0xff wins. By anding both masks we have a correct 8604 // result except that 0x0c shall be corrected to give 0x0c only. 8605 uint32_t Mask = LHSMask & RHSMask; 8606 for (unsigned I = 0; I < 32; I += 8) { 8607 uint32_t ByteSel = 0xff << I; 8608 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8609 Mask &= (0x0c << I) & 0xffffffff; 8610 } 8611 8612 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8613 // or 0x0c. 8614 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8615 SDLoc DL(N); 8616 8617 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8618 LHS.getOperand(0), RHS.getOperand(0), 8619 DAG.getConstant(Sel, DL, MVT::i32)); 8620 } 8621 } 8622 } 8623 8624 return SDValue(); 8625 } 8626 8627 SDValue SITargetLowering::performOrCombine(SDNode *N, 8628 DAGCombinerInfo &DCI) const { 8629 SelectionDAG &DAG = DCI.DAG; 8630 SDValue LHS = N->getOperand(0); 8631 SDValue RHS = N->getOperand(1); 8632 8633 EVT VT = N->getValueType(0); 8634 if (VT == MVT::i1) { 8635 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8636 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8637 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8638 SDValue Src = LHS.getOperand(0); 8639 if (Src != RHS.getOperand(0)) 8640 return SDValue(); 8641 8642 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8643 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8644 if (!CLHS || !CRHS) 8645 return SDValue(); 8646 8647 // Only 10 bits are used. 8648 static const uint32_t MaxMask = 0x3ff; 8649 8650 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8651 SDLoc DL(N); 8652 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8653 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8654 } 8655 8656 return SDValue(); 8657 } 8658 8659 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8660 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8661 LHS.getOpcode() == AMDGPUISD::PERM && 8662 isa<ConstantSDNode>(LHS.getOperand(2))) { 8663 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8664 if (!Sel) 8665 return SDValue(); 8666 8667 Sel |= LHS.getConstantOperandVal(2); 8668 SDLoc DL(N); 8669 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8670 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8671 } 8672 8673 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8674 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8675 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8676 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8677 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8678 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8679 if (LHSMask != ~0u && RHSMask != ~0u) { 8680 // Canonicalize the expression in an attempt to have fewer unique masks 8681 // and therefore fewer registers used to hold the masks. 8682 if (LHSMask > RHSMask) { 8683 std::swap(LHSMask, RHSMask); 8684 std::swap(LHS, RHS); 8685 } 8686 8687 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8688 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8689 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8690 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8691 8692 // Check of we need to combine values from two sources within a byte. 8693 if (!(LHSUsedLanes & RHSUsedLanes) && 8694 // If we select high and lower word keep it for SDWA. 8695 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8696 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8697 // Kill zero bytes selected by other mask. Zero value is 0xc. 8698 LHSMask &= ~RHSUsedLanes; 8699 RHSMask &= ~LHSUsedLanes; 8700 // Add 4 to each active LHS lane 8701 LHSMask |= LHSUsedLanes & 0x04040404; 8702 // Combine masks 8703 uint32_t Sel = LHSMask | RHSMask; 8704 SDLoc DL(N); 8705 8706 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8707 LHS.getOperand(0), RHS.getOperand(0), 8708 DAG.getConstant(Sel, DL, MVT::i32)); 8709 } 8710 } 8711 } 8712 8713 if (VT != MVT::i64) 8714 return SDValue(); 8715 8716 // TODO: This could be a generic combine with a predicate for extracting the 8717 // high half of an integer being free. 8718 8719 // (or i64:x, (zero_extend i32:y)) -> 8720 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8721 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8722 RHS.getOpcode() != ISD::ZERO_EXTEND) 8723 std::swap(LHS, RHS); 8724 8725 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8726 SDValue ExtSrc = RHS.getOperand(0); 8727 EVT SrcVT = ExtSrc.getValueType(); 8728 if (SrcVT == MVT::i32) { 8729 SDLoc SL(N); 8730 SDValue LowLHS, HiBits; 8731 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 8732 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 8733 8734 DCI.AddToWorklist(LowOr.getNode()); 8735 DCI.AddToWorklist(HiBits.getNode()); 8736 8737 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 8738 LowOr, HiBits); 8739 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 8740 } 8741 } 8742 8743 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8744 if (CRHS) { 8745 if (SDValue Split 8746 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 8747 return Split; 8748 } 8749 8750 return SDValue(); 8751 } 8752 8753 SDValue SITargetLowering::performXorCombine(SDNode *N, 8754 DAGCombinerInfo &DCI) const { 8755 EVT VT = N->getValueType(0); 8756 if (VT != MVT::i64) 8757 return SDValue(); 8758 8759 SDValue LHS = N->getOperand(0); 8760 SDValue RHS = N->getOperand(1); 8761 8762 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8763 if (CRHS) { 8764 if (SDValue Split 8765 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 8766 return Split; 8767 } 8768 8769 return SDValue(); 8770 } 8771 8772 // Instructions that will be lowered with a final instruction that zeros the 8773 // high result bits. 8774 // XXX - probably only need to list legal operations. 8775 static bool fp16SrcZerosHighBits(unsigned Opc) { 8776 switch (Opc) { 8777 case ISD::FADD: 8778 case ISD::FSUB: 8779 case ISD::FMUL: 8780 case ISD::FDIV: 8781 case ISD::FREM: 8782 case ISD::FMA: 8783 case ISD::FMAD: 8784 case ISD::FCANONICALIZE: 8785 case ISD::FP_ROUND: 8786 case ISD::UINT_TO_FP: 8787 case ISD::SINT_TO_FP: 8788 case ISD::FABS: 8789 // Fabs is lowered to a bit operation, but it's an and which will clear the 8790 // high bits anyway. 8791 case ISD::FSQRT: 8792 case ISD::FSIN: 8793 case ISD::FCOS: 8794 case ISD::FPOWI: 8795 case ISD::FPOW: 8796 case ISD::FLOG: 8797 case ISD::FLOG2: 8798 case ISD::FLOG10: 8799 case ISD::FEXP: 8800 case ISD::FEXP2: 8801 case ISD::FCEIL: 8802 case ISD::FTRUNC: 8803 case ISD::FRINT: 8804 case ISD::FNEARBYINT: 8805 case ISD::FROUND: 8806 case ISD::FFLOOR: 8807 case ISD::FMINNUM: 8808 case ISD::FMAXNUM: 8809 case AMDGPUISD::FRACT: 8810 case AMDGPUISD::CLAMP: 8811 case AMDGPUISD::COS_HW: 8812 case AMDGPUISD::SIN_HW: 8813 case AMDGPUISD::FMIN3: 8814 case AMDGPUISD::FMAX3: 8815 case AMDGPUISD::FMED3: 8816 case AMDGPUISD::FMAD_FTZ: 8817 case AMDGPUISD::RCP: 8818 case AMDGPUISD::RSQ: 8819 case AMDGPUISD::RCP_IFLAG: 8820 case AMDGPUISD::LDEXP: 8821 return true; 8822 default: 8823 // fcopysign, select and others may be lowered to 32-bit bit operations 8824 // which don't zero the high bits. 8825 return false; 8826 } 8827 } 8828 8829 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 8830 DAGCombinerInfo &DCI) const { 8831 if (!Subtarget->has16BitInsts() || 8832 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8833 return SDValue(); 8834 8835 EVT VT = N->getValueType(0); 8836 if (VT != MVT::i32) 8837 return SDValue(); 8838 8839 SDValue Src = N->getOperand(0); 8840 if (Src.getValueType() != MVT::i16) 8841 return SDValue(); 8842 8843 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 8844 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 8845 if (Src.getOpcode() == ISD::BITCAST) { 8846 SDValue BCSrc = Src.getOperand(0); 8847 if (BCSrc.getValueType() == MVT::f16 && 8848 fp16SrcZerosHighBits(BCSrc.getOpcode())) 8849 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 8850 } 8851 8852 return SDValue(); 8853 } 8854 8855 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 8856 DAGCombinerInfo &DCI) 8857 const { 8858 SDValue Src = N->getOperand(0); 8859 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 8860 8861 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 8862 VTSign->getVT() == MVT::i8) || 8863 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 8864 VTSign->getVT() == MVT::i16)) && 8865 Src.hasOneUse()) { 8866 auto *M = cast<MemSDNode>(Src); 8867 SDValue Ops[] = { 8868 Src.getOperand(0), // Chain 8869 Src.getOperand(1), // rsrc 8870 Src.getOperand(2), // vindex 8871 Src.getOperand(3), // voffset 8872 Src.getOperand(4), // soffset 8873 Src.getOperand(5), // offset 8874 Src.getOperand(6), 8875 Src.getOperand(7) 8876 }; 8877 // replace with BUFFER_LOAD_BYTE/SHORT 8878 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 8879 Src.getOperand(0).getValueType()); 8880 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 8881 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 8882 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 8883 ResList, 8884 Ops, M->getMemoryVT(), 8885 M->getMemOperand()); 8886 return DCI.DAG.getMergeValues({BufferLoadSignExt, 8887 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 8888 } 8889 return SDValue(); 8890 } 8891 8892 SDValue SITargetLowering::performClassCombine(SDNode *N, 8893 DAGCombinerInfo &DCI) const { 8894 SelectionDAG &DAG = DCI.DAG; 8895 SDValue Mask = N->getOperand(1); 8896 8897 // fp_class x, 0 -> false 8898 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 8899 if (CMask->isNullValue()) 8900 return DAG.getConstant(0, SDLoc(N), MVT::i1); 8901 } 8902 8903 if (N->getOperand(0).isUndef()) 8904 return DAG.getUNDEF(MVT::i1); 8905 8906 return SDValue(); 8907 } 8908 8909 SDValue SITargetLowering::performRcpCombine(SDNode *N, 8910 DAGCombinerInfo &DCI) const { 8911 EVT VT = N->getValueType(0); 8912 SDValue N0 = N->getOperand(0); 8913 8914 if (N0.isUndef()) 8915 return N0; 8916 8917 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 8918 N0.getOpcode() == ISD::SINT_TO_FP)) { 8919 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 8920 N->getFlags()); 8921 } 8922 8923 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 8924 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 8925 N0.getOperand(0), N->getFlags()); 8926 } 8927 8928 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 8929 } 8930 8931 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 8932 unsigned MaxDepth) const { 8933 unsigned Opcode = Op.getOpcode(); 8934 if (Opcode == ISD::FCANONICALIZE) 8935 return true; 8936 8937 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8938 auto F = CFP->getValueAPF(); 8939 if (F.isNaN() && F.isSignaling()) 8940 return false; 8941 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 8942 } 8943 8944 // If source is a result of another standard FP operation it is already in 8945 // canonical form. 8946 if (MaxDepth == 0) 8947 return false; 8948 8949 switch (Opcode) { 8950 // These will flush denorms if required. 8951 case ISD::FADD: 8952 case ISD::FSUB: 8953 case ISD::FMUL: 8954 case ISD::FCEIL: 8955 case ISD::FFLOOR: 8956 case ISD::FMA: 8957 case ISD::FMAD: 8958 case ISD::FSQRT: 8959 case ISD::FDIV: 8960 case ISD::FREM: 8961 case ISD::FP_ROUND: 8962 case ISD::FP_EXTEND: 8963 case AMDGPUISD::FMUL_LEGACY: 8964 case AMDGPUISD::FMAD_FTZ: 8965 case AMDGPUISD::RCP: 8966 case AMDGPUISD::RSQ: 8967 case AMDGPUISD::RSQ_CLAMP: 8968 case AMDGPUISD::RCP_LEGACY: 8969 case AMDGPUISD::RCP_IFLAG: 8970 case AMDGPUISD::TRIG_PREOP: 8971 case AMDGPUISD::DIV_SCALE: 8972 case AMDGPUISD::DIV_FMAS: 8973 case AMDGPUISD::DIV_FIXUP: 8974 case AMDGPUISD::FRACT: 8975 case AMDGPUISD::LDEXP: 8976 case AMDGPUISD::CVT_PKRTZ_F16_F32: 8977 case AMDGPUISD::CVT_F32_UBYTE0: 8978 case AMDGPUISD::CVT_F32_UBYTE1: 8979 case AMDGPUISD::CVT_F32_UBYTE2: 8980 case AMDGPUISD::CVT_F32_UBYTE3: 8981 return true; 8982 8983 // It can/will be lowered or combined as a bit operation. 8984 // Need to check their input recursively to handle. 8985 case ISD::FNEG: 8986 case ISD::FABS: 8987 case ISD::FCOPYSIGN: 8988 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8989 8990 case ISD::FSIN: 8991 case ISD::FCOS: 8992 case ISD::FSINCOS: 8993 return Op.getValueType().getScalarType() != MVT::f16; 8994 8995 case ISD::FMINNUM: 8996 case ISD::FMAXNUM: 8997 case ISD::FMINNUM_IEEE: 8998 case ISD::FMAXNUM_IEEE: 8999 case AMDGPUISD::CLAMP: 9000 case AMDGPUISD::FMED3: 9001 case AMDGPUISD::FMAX3: 9002 case AMDGPUISD::FMIN3: { 9003 // FIXME: Shouldn't treat the generic operations different based these. 9004 // However, we aren't really required to flush the result from 9005 // minnum/maxnum.. 9006 9007 // snans will be quieted, so we only need to worry about denormals. 9008 if (Subtarget->supportsMinMaxDenormModes() || 9009 denormalsEnabledForType(DAG, Op.getValueType())) 9010 return true; 9011 9012 // Flushing may be required. 9013 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9014 // targets need to check their input recursively. 9015 9016 // FIXME: Does this apply with clamp? It's implemented with max. 9017 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9018 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9019 return false; 9020 } 9021 9022 return true; 9023 } 9024 case ISD::SELECT: { 9025 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9026 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9027 } 9028 case ISD::BUILD_VECTOR: { 9029 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9030 SDValue SrcOp = Op.getOperand(i); 9031 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9032 return false; 9033 } 9034 9035 return true; 9036 } 9037 case ISD::EXTRACT_VECTOR_ELT: 9038 case ISD::EXTRACT_SUBVECTOR: { 9039 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9040 } 9041 case ISD::INSERT_VECTOR_ELT: { 9042 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9043 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9044 } 9045 case ISD::UNDEF: 9046 // Could be anything. 9047 return false; 9048 9049 case ISD::BITCAST: { 9050 // Hack round the mess we make when legalizing extract_vector_elt 9051 SDValue Src = Op.getOperand(0); 9052 if (Src.getValueType() == MVT::i16 && 9053 Src.getOpcode() == ISD::TRUNCATE) { 9054 SDValue TruncSrc = Src.getOperand(0); 9055 if (TruncSrc.getValueType() == MVT::i32 && 9056 TruncSrc.getOpcode() == ISD::BITCAST && 9057 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9058 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9059 } 9060 } 9061 9062 return false; 9063 } 9064 case ISD::INTRINSIC_WO_CHAIN: { 9065 unsigned IntrinsicID 9066 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9067 // TODO: Handle more intrinsics 9068 switch (IntrinsicID) { 9069 case Intrinsic::amdgcn_cvt_pkrtz: 9070 case Intrinsic::amdgcn_cubeid: 9071 case Intrinsic::amdgcn_frexp_mant: 9072 case Intrinsic::amdgcn_fdot2: 9073 case Intrinsic::amdgcn_rcp: 9074 case Intrinsic::amdgcn_rsq: 9075 case Intrinsic::amdgcn_rsq_clamp: 9076 case Intrinsic::amdgcn_rcp_legacy: 9077 case Intrinsic::amdgcn_rsq_legacy: 9078 return true; 9079 default: 9080 break; 9081 } 9082 9083 LLVM_FALLTHROUGH; 9084 } 9085 default: 9086 return denormalsEnabledForType(DAG, Op.getValueType()) && 9087 DAG.isKnownNeverSNaN(Op); 9088 } 9089 9090 llvm_unreachable("invalid operation"); 9091 } 9092 9093 // Constant fold canonicalize. 9094 SDValue SITargetLowering::getCanonicalConstantFP( 9095 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9096 // Flush denormals to 0 if not enabled. 9097 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9098 return DAG.getConstantFP(0.0, SL, VT); 9099 9100 if (C.isNaN()) { 9101 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9102 if (C.isSignaling()) { 9103 // Quiet a signaling NaN. 9104 // FIXME: Is this supposed to preserve payload bits? 9105 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9106 } 9107 9108 // Make sure it is the canonical NaN bitpattern. 9109 // 9110 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9111 // immediate? 9112 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9113 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9114 } 9115 9116 // Already canonical. 9117 return DAG.getConstantFP(C, SL, VT); 9118 } 9119 9120 static bool vectorEltWillFoldAway(SDValue Op) { 9121 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9122 } 9123 9124 SDValue SITargetLowering::performFCanonicalizeCombine( 9125 SDNode *N, 9126 DAGCombinerInfo &DCI) const { 9127 SelectionDAG &DAG = DCI.DAG; 9128 SDValue N0 = N->getOperand(0); 9129 EVT VT = N->getValueType(0); 9130 9131 // fcanonicalize undef -> qnan 9132 if (N0.isUndef()) { 9133 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9134 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9135 } 9136 9137 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9138 EVT VT = N->getValueType(0); 9139 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9140 } 9141 9142 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9143 // (fcanonicalize k) 9144 // 9145 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9146 9147 // TODO: This could be better with wider vectors that will be split to v2f16, 9148 // and to consider uses since there aren't that many packed operations. 9149 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9150 isTypeLegal(MVT::v2f16)) { 9151 SDLoc SL(N); 9152 SDValue NewElts[2]; 9153 SDValue Lo = N0.getOperand(0); 9154 SDValue Hi = N0.getOperand(1); 9155 EVT EltVT = Lo.getValueType(); 9156 9157 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9158 for (unsigned I = 0; I != 2; ++I) { 9159 SDValue Op = N0.getOperand(I); 9160 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9161 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9162 CFP->getValueAPF()); 9163 } else if (Op.isUndef()) { 9164 // Handled below based on what the other operand is. 9165 NewElts[I] = Op; 9166 } else { 9167 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9168 } 9169 } 9170 9171 // If one half is undef, and one is constant, perfer a splat vector rather 9172 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9173 // cheaper to use and may be free with a packed operation. 9174 if (NewElts[0].isUndef()) { 9175 if (isa<ConstantFPSDNode>(NewElts[1])) 9176 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9177 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9178 } 9179 9180 if (NewElts[1].isUndef()) { 9181 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9182 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9183 } 9184 9185 return DAG.getBuildVector(VT, SL, NewElts); 9186 } 9187 } 9188 9189 unsigned SrcOpc = N0.getOpcode(); 9190 9191 // If it's free to do so, push canonicalizes further up the source, which may 9192 // find a canonical source. 9193 // 9194 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9195 // sNaNs. 9196 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9197 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9198 if (CRHS && N0.hasOneUse()) { 9199 SDLoc SL(N); 9200 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9201 N0.getOperand(0)); 9202 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9203 DCI.AddToWorklist(Canon0.getNode()); 9204 9205 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9206 } 9207 } 9208 9209 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9210 } 9211 9212 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9213 switch (Opc) { 9214 case ISD::FMAXNUM: 9215 case ISD::FMAXNUM_IEEE: 9216 return AMDGPUISD::FMAX3; 9217 case ISD::SMAX: 9218 return AMDGPUISD::SMAX3; 9219 case ISD::UMAX: 9220 return AMDGPUISD::UMAX3; 9221 case ISD::FMINNUM: 9222 case ISD::FMINNUM_IEEE: 9223 return AMDGPUISD::FMIN3; 9224 case ISD::SMIN: 9225 return AMDGPUISD::SMIN3; 9226 case ISD::UMIN: 9227 return AMDGPUISD::UMIN3; 9228 default: 9229 llvm_unreachable("Not a min/max opcode"); 9230 } 9231 } 9232 9233 SDValue SITargetLowering::performIntMed3ImmCombine( 9234 SelectionDAG &DAG, const SDLoc &SL, 9235 SDValue Op0, SDValue Op1, bool Signed) const { 9236 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9237 if (!K1) 9238 return SDValue(); 9239 9240 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9241 if (!K0) 9242 return SDValue(); 9243 9244 if (Signed) { 9245 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9246 return SDValue(); 9247 } else { 9248 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9249 return SDValue(); 9250 } 9251 9252 EVT VT = K0->getValueType(0); 9253 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9254 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9255 return DAG.getNode(Med3Opc, SL, VT, 9256 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9257 } 9258 9259 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9260 MVT NVT = MVT::i32; 9261 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9262 9263 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9264 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9265 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9266 9267 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9268 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9269 } 9270 9271 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9272 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9273 return C; 9274 9275 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9276 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9277 return C; 9278 } 9279 9280 return nullptr; 9281 } 9282 9283 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9284 const SDLoc &SL, 9285 SDValue Op0, 9286 SDValue Op1) const { 9287 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9288 if (!K1) 9289 return SDValue(); 9290 9291 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9292 if (!K0) 9293 return SDValue(); 9294 9295 // Ordered >= (although NaN inputs should have folded away by now). 9296 if (K0->getValueAPF() > K1->getValueAPF()) 9297 return SDValue(); 9298 9299 const MachineFunction &MF = DAG.getMachineFunction(); 9300 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9301 9302 // TODO: Check IEEE bit enabled? 9303 EVT VT = Op0.getValueType(); 9304 if (Info->getMode().DX10Clamp) { 9305 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9306 // hardware fmed3 behavior converting to a min. 9307 // FIXME: Should this be allowing -0.0? 9308 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9309 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9310 } 9311 9312 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9313 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9314 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9315 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9316 // then give the other result, which is different from med3 with a NaN 9317 // input. 9318 SDValue Var = Op0.getOperand(0); 9319 if (!DAG.isKnownNeverSNaN(Var)) 9320 return SDValue(); 9321 9322 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9323 9324 if ((!K0->hasOneUse() || 9325 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9326 (!K1->hasOneUse() || 9327 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9328 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9329 Var, SDValue(K0, 0), SDValue(K1, 0)); 9330 } 9331 } 9332 9333 return SDValue(); 9334 } 9335 9336 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9337 DAGCombinerInfo &DCI) const { 9338 SelectionDAG &DAG = DCI.DAG; 9339 9340 EVT VT = N->getValueType(0); 9341 unsigned Opc = N->getOpcode(); 9342 SDValue Op0 = N->getOperand(0); 9343 SDValue Op1 = N->getOperand(1); 9344 9345 // Only do this if the inner op has one use since this will just increases 9346 // register pressure for no benefit. 9347 9348 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9349 !VT.isVector() && 9350 (VT == MVT::i32 || VT == MVT::f32 || 9351 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9352 // max(max(a, b), c) -> max3(a, b, c) 9353 // min(min(a, b), c) -> min3(a, b, c) 9354 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9355 SDLoc DL(N); 9356 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9357 DL, 9358 N->getValueType(0), 9359 Op0.getOperand(0), 9360 Op0.getOperand(1), 9361 Op1); 9362 } 9363 9364 // Try commuted. 9365 // max(a, max(b, c)) -> max3(a, b, c) 9366 // min(a, min(b, c)) -> min3(a, b, c) 9367 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9368 SDLoc DL(N); 9369 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9370 DL, 9371 N->getValueType(0), 9372 Op0, 9373 Op1.getOperand(0), 9374 Op1.getOperand(1)); 9375 } 9376 } 9377 9378 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9379 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9380 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9381 return Med3; 9382 } 9383 9384 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9385 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9386 return Med3; 9387 } 9388 9389 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9390 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9391 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9392 (Opc == AMDGPUISD::FMIN_LEGACY && 9393 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9394 (VT == MVT::f32 || VT == MVT::f64 || 9395 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9396 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9397 Op0.hasOneUse()) { 9398 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9399 return Res; 9400 } 9401 9402 return SDValue(); 9403 } 9404 9405 static bool isClampZeroToOne(SDValue A, SDValue B) { 9406 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9407 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9408 // FIXME: Should this be allowing -0.0? 9409 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9410 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9411 } 9412 } 9413 9414 return false; 9415 } 9416 9417 // FIXME: Should only worry about snans for version with chain. 9418 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9419 DAGCombinerInfo &DCI) const { 9420 EVT VT = N->getValueType(0); 9421 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9422 // NaNs. With a NaN input, the order of the operands may change the result. 9423 9424 SelectionDAG &DAG = DCI.DAG; 9425 SDLoc SL(N); 9426 9427 SDValue Src0 = N->getOperand(0); 9428 SDValue Src1 = N->getOperand(1); 9429 SDValue Src2 = N->getOperand(2); 9430 9431 if (isClampZeroToOne(Src0, Src1)) { 9432 // const_a, const_b, x -> clamp is safe in all cases including signaling 9433 // nans. 9434 // FIXME: Should this be allowing -0.0? 9435 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9436 } 9437 9438 const MachineFunction &MF = DAG.getMachineFunction(); 9439 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9440 9441 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9442 // handling no dx10-clamp? 9443 if (Info->getMode().DX10Clamp) { 9444 // If NaNs is clamped to 0, we are free to reorder the inputs. 9445 9446 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9447 std::swap(Src0, Src1); 9448 9449 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9450 std::swap(Src1, Src2); 9451 9452 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9453 std::swap(Src0, Src1); 9454 9455 if (isClampZeroToOne(Src1, Src2)) 9456 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9457 } 9458 9459 return SDValue(); 9460 } 9461 9462 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9463 DAGCombinerInfo &DCI) const { 9464 SDValue Src0 = N->getOperand(0); 9465 SDValue Src1 = N->getOperand(1); 9466 if (Src0.isUndef() && Src1.isUndef()) 9467 return DCI.DAG.getUNDEF(N->getValueType(0)); 9468 return SDValue(); 9469 } 9470 9471 SDValue SITargetLowering::performExtractVectorEltCombine( 9472 SDNode *N, DAGCombinerInfo &DCI) const { 9473 SDValue Vec = N->getOperand(0); 9474 SelectionDAG &DAG = DCI.DAG; 9475 9476 EVT VecVT = Vec.getValueType(); 9477 EVT EltVT = VecVT.getVectorElementType(); 9478 9479 if ((Vec.getOpcode() == ISD::FNEG || 9480 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9481 SDLoc SL(N); 9482 EVT EltVT = N->getValueType(0); 9483 SDValue Idx = N->getOperand(1); 9484 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9485 Vec.getOperand(0), Idx); 9486 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9487 } 9488 9489 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9490 // => 9491 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9492 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9493 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9494 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9495 SDLoc SL(N); 9496 EVT EltVT = N->getValueType(0); 9497 SDValue Idx = N->getOperand(1); 9498 unsigned Opc = Vec.getOpcode(); 9499 9500 switch(Opc) { 9501 default: 9502 break; 9503 // TODO: Support other binary operations. 9504 case ISD::FADD: 9505 case ISD::FSUB: 9506 case ISD::FMUL: 9507 case ISD::ADD: 9508 case ISD::UMIN: 9509 case ISD::UMAX: 9510 case ISD::SMIN: 9511 case ISD::SMAX: 9512 case ISD::FMAXNUM: 9513 case ISD::FMINNUM: 9514 case ISD::FMAXNUM_IEEE: 9515 case ISD::FMINNUM_IEEE: { 9516 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9517 Vec.getOperand(0), Idx); 9518 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9519 Vec.getOperand(1), Idx); 9520 9521 DCI.AddToWorklist(Elt0.getNode()); 9522 DCI.AddToWorklist(Elt1.getNode()); 9523 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9524 } 9525 } 9526 } 9527 9528 unsigned VecSize = VecVT.getSizeInBits(); 9529 unsigned EltSize = EltVT.getSizeInBits(); 9530 9531 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9532 // This elminates non-constant index and subsequent movrel or scratch access. 9533 // Sub-dword vectors of size 2 dword or less have better implementation. 9534 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9535 // instructions. 9536 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) && 9537 !isa<ConstantSDNode>(N->getOperand(1))) { 9538 SDLoc SL(N); 9539 SDValue Idx = N->getOperand(1); 9540 SDValue V; 9541 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9542 SDValue IC = DAG.getVectorIdxConstant(I, SL); 9543 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9544 if (I == 0) 9545 V = Elt; 9546 else 9547 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9548 } 9549 return V; 9550 } 9551 9552 if (!DCI.isBeforeLegalize()) 9553 return SDValue(); 9554 9555 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9556 // elements. This exposes more load reduction opportunities by replacing 9557 // multiple small extract_vector_elements with a single 32-bit extract. 9558 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9559 if (isa<MemSDNode>(Vec) && 9560 EltSize <= 16 && 9561 EltVT.isByteSized() && 9562 VecSize > 32 && 9563 VecSize % 32 == 0 && 9564 Idx) { 9565 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9566 9567 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9568 unsigned EltIdx = BitIndex / 32; 9569 unsigned LeftoverBitIdx = BitIndex % 32; 9570 SDLoc SL(N); 9571 9572 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9573 DCI.AddToWorklist(Cast.getNode()); 9574 9575 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9576 DAG.getConstant(EltIdx, SL, MVT::i32)); 9577 DCI.AddToWorklist(Elt.getNode()); 9578 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9579 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9580 DCI.AddToWorklist(Srl.getNode()); 9581 9582 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9583 DCI.AddToWorklist(Trunc.getNode()); 9584 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9585 } 9586 9587 return SDValue(); 9588 } 9589 9590 SDValue 9591 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9592 DAGCombinerInfo &DCI) const { 9593 SDValue Vec = N->getOperand(0); 9594 SDValue Idx = N->getOperand(2); 9595 EVT VecVT = Vec.getValueType(); 9596 EVT EltVT = VecVT.getVectorElementType(); 9597 unsigned VecSize = VecVT.getSizeInBits(); 9598 unsigned EltSize = EltVT.getSizeInBits(); 9599 9600 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9601 // => BUILD_VECTOR n x select (e, const-idx) 9602 // This elminates non-constant index and subsequent movrel or scratch access. 9603 // Sub-dword vectors of size 2 dword or less have better implementation. 9604 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9605 // instructions. 9606 if (isa<ConstantSDNode>(Idx) || 9607 VecSize > 256 || (VecSize <= 64 && EltSize < 32)) 9608 return SDValue(); 9609 9610 SelectionDAG &DAG = DCI.DAG; 9611 SDLoc SL(N); 9612 SDValue Ins = N->getOperand(1); 9613 EVT IdxVT = Idx.getValueType(); 9614 9615 SmallVector<SDValue, 16> Ops; 9616 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9617 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9618 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9619 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9620 Ops.push_back(V); 9621 } 9622 9623 return DAG.getBuildVector(VecVT, SL, Ops); 9624 } 9625 9626 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9627 const SDNode *N0, 9628 const SDNode *N1) const { 9629 EVT VT = N0->getValueType(0); 9630 9631 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9632 // support denormals ever. 9633 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9634 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9635 getSubtarget()->hasMadF16())) && 9636 isOperationLegal(ISD::FMAD, VT)) 9637 return ISD::FMAD; 9638 9639 const TargetOptions &Options = DAG.getTarget().Options; 9640 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9641 (N0->getFlags().hasAllowContract() && 9642 N1->getFlags().hasAllowContract())) && 9643 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 9644 return ISD::FMA; 9645 } 9646 9647 return 0; 9648 } 9649 9650 // For a reassociatable opcode perform: 9651 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9652 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9653 SelectionDAG &DAG) const { 9654 EVT VT = N->getValueType(0); 9655 if (VT != MVT::i32 && VT != MVT::i64) 9656 return SDValue(); 9657 9658 unsigned Opc = N->getOpcode(); 9659 SDValue Op0 = N->getOperand(0); 9660 SDValue Op1 = N->getOperand(1); 9661 9662 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9663 return SDValue(); 9664 9665 if (Op0->isDivergent()) 9666 std::swap(Op0, Op1); 9667 9668 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9669 return SDValue(); 9670 9671 SDValue Op2 = Op1.getOperand(1); 9672 Op1 = Op1.getOperand(0); 9673 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9674 return SDValue(); 9675 9676 if (Op1->isDivergent()) 9677 std::swap(Op1, Op2); 9678 9679 // If either operand is constant this will conflict with 9680 // DAGCombiner::ReassociateOps(). 9681 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9682 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9683 return SDValue(); 9684 9685 SDLoc SL(N); 9686 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9687 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9688 } 9689 9690 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9691 EVT VT, 9692 SDValue N0, SDValue N1, SDValue N2, 9693 bool Signed) { 9694 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9695 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9696 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 9697 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 9698 } 9699 9700 SDValue SITargetLowering::performAddCombine(SDNode *N, 9701 DAGCombinerInfo &DCI) const { 9702 SelectionDAG &DAG = DCI.DAG; 9703 EVT VT = N->getValueType(0); 9704 SDLoc SL(N); 9705 SDValue LHS = N->getOperand(0); 9706 SDValue RHS = N->getOperand(1); 9707 9708 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 9709 && Subtarget->hasMad64_32() && 9710 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 9711 VT.getScalarSizeInBits() <= 64) { 9712 if (LHS.getOpcode() != ISD::MUL) 9713 std::swap(LHS, RHS); 9714 9715 SDValue MulLHS = LHS.getOperand(0); 9716 SDValue MulRHS = LHS.getOperand(1); 9717 SDValue AddRHS = RHS; 9718 9719 // TODO: Maybe restrict if SGPR inputs. 9720 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 9721 numBitsUnsigned(MulRHS, DAG) <= 32) { 9722 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 9723 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 9724 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 9725 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 9726 } 9727 9728 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 9729 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 9730 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 9731 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 9732 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 9733 } 9734 9735 return SDValue(); 9736 } 9737 9738 if (SDValue V = reassociateScalarOps(N, DAG)) { 9739 return V; 9740 } 9741 9742 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 9743 return SDValue(); 9744 9745 // add x, zext (setcc) => addcarry x, 0, setcc 9746 // add x, sext (setcc) => subcarry x, 0, setcc 9747 unsigned Opc = LHS.getOpcode(); 9748 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9749 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 9750 std::swap(RHS, LHS); 9751 9752 Opc = RHS.getOpcode(); 9753 switch (Opc) { 9754 default: break; 9755 case ISD::ZERO_EXTEND: 9756 case ISD::SIGN_EXTEND: 9757 case ISD::ANY_EXTEND: { 9758 auto Cond = RHS.getOperand(0); 9759 // If this won't be a real VOPC output, we would still need to insert an 9760 // extra instruction anyway. 9761 if (!isBoolSGPR(Cond)) 9762 break; 9763 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9764 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9765 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9766 return DAG.getNode(Opc, SL, VTList, Args); 9767 } 9768 case ISD::ADDCARRY: { 9769 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 9770 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9771 if (!C || C->getZExtValue() != 0) break; 9772 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 9773 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 9774 } 9775 } 9776 return SDValue(); 9777 } 9778 9779 SDValue SITargetLowering::performSubCombine(SDNode *N, 9780 DAGCombinerInfo &DCI) const { 9781 SelectionDAG &DAG = DCI.DAG; 9782 EVT VT = N->getValueType(0); 9783 9784 if (VT != MVT::i32) 9785 return SDValue(); 9786 9787 SDLoc SL(N); 9788 SDValue LHS = N->getOperand(0); 9789 SDValue RHS = N->getOperand(1); 9790 9791 // sub x, zext (setcc) => subcarry x, 0, setcc 9792 // sub x, sext (setcc) => addcarry x, 0, setcc 9793 unsigned Opc = RHS.getOpcode(); 9794 switch (Opc) { 9795 default: break; 9796 case ISD::ZERO_EXTEND: 9797 case ISD::SIGN_EXTEND: 9798 case ISD::ANY_EXTEND: { 9799 auto Cond = RHS.getOperand(0); 9800 // If this won't be a real VOPC output, we would still need to insert an 9801 // extra instruction anyway. 9802 if (!isBoolSGPR(Cond)) 9803 break; 9804 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9805 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9806 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 9807 return DAG.getNode(Opc, SL, VTList, Args); 9808 } 9809 } 9810 9811 if (LHS.getOpcode() == ISD::SUBCARRY) { 9812 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 9813 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9814 if (!C || !C->isNullValue()) 9815 return SDValue(); 9816 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 9817 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 9818 } 9819 return SDValue(); 9820 } 9821 9822 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 9823 DAGCombinerInfo &DCI) const { 9824 9825 if (N->getValueType(0) != MVT::i32) 9826 return SDValue(); 9827 9828 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9829 if (!C || C->getZExtValue() != 0) 9830 return SDValue(); 9831 9832 SelectionDAG &DAG = DCI.DAG; 9833 SDValue LHS = N->getOperand(0); 9834 9835 // addcarry (add x, y), 0, cc => addcarry x, y, cc 9836 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 9837 unsigned LHSOpc = LHS.getOpcode(); 9838 unsigned Opc = N->getOpcode(); 9839 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 9840 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 9841 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 9842 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 9843 } 9844 return SDValue(); 9845 } 9846 9847 SDValue SITargetLowering::performFAddCombine(SDNode *N, 9848 DAGCombinerInfo &DCI) const { 9849 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9850 return SDValue(); 9851 9852 SelectionDAG &DAG = DCI.DAG; 9853 EVT VT = N->getValueType(0); 9854 9855 SDLoc SL(N); 9856 SDValue LHS = N->getOperand(0); 9857 SDValue RHS = N->getOperand(1); 9858 9859 // These should really be instruction patterns, but writing patterns with 9860 // source modiifiers is a pain. 9861 9862 // fadd (fadd (a, a), b) -> mad 2.0, a, b 9863 if (LHS.getOpcode() == ISD::FADD) { 9864 SDValue A = LHS.getOperand(0); 9865 if (A == LHS.getOperand(1)) { 9866 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9867 if (FusedOp != 0) { 9868 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9869 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 9870 } 9871 } 9872 } 9873 9874 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 9875 if (RHS.getOpcode() == ISD::FADD) { 9876 SDValue A = RHS.getOperand(0); 9877 if (A == RHS.getOperand(1)) { 9878 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9879 if (FusedOp != 0) { 9880 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9881 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 9882 } 9883 } 9884 } 9885 9886 return SDValue(); 9887 } 9888 9889 SDValue SITargetLowering::performFSubCombine(SDNode *N, 9890 DAGCombinerInfo &DCI) const { 9891 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9892 return SDValue(); 9893 9894 SelectionDAG &DAG = DCI.DAG; 9895 SDLoc SL(N); 9896 EVT VT = N->getValueType(0); 9897 assert(!VT.isVector()); 9898 9899 // Try to get the fneg to fold into the source modifier. This undoes generic 9900 // DAG combines and folds them into the mad. 9901 // 9902 // Only do this if we are not trying to support denormals. v_mad_f32 does 9903 // not support denormals ever. 9904 SDValue LHS = N->getOperand(0); 9905 SDValue RHS = N->getOperand(1); 9906 if (LHS.getOpcode() == ISD::FADD) { 9907 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 9908 SDValue A = LHS.getOperand(0); 9909 if (A == LHS.getOperand(1)) { 9910 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9911 if (FusedOp != 0){ 9912 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9913 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 9914 9915 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 9916 } 9917 } 9918 } 9919 9920 if (RHS.getOpcode() == ISD::FADD) { 9921 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 9922 9923 SDValue A = RHS.getOperand(0); 9924 if (A == RHS.getOperand(1)) { 9925 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9926 if (FusedOp != 0){ 9927 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 9928 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 9929 } 9930 } 9931 } 9932 9933 return SDValue(); 9934 } 9935 9936 SDValue SITargetLowering::performFMACombine(SDNode *N, 9937 DAGCombinerInfo &DCI) const { 9938 SelectionDAG &DAG = DCI.DAG; 9939 EVT VT = N->getValueType(0); 9940 SDLoc SL(N); 9941 9942 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 9943 return SDValue(); 9944 9945 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 9946 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 9947 SDValue Op1 = N->getOperand(0); 9948 SDValue Op2 = N->getOperand(1); 9949 SDValue FMA = N->getOperand(2); 9950 9951 if (FMA.getOpcode() != ISD::FMA || 9952 Op1.getOpcode() != ISD::FP_EXTEND || 9953 Op2.getOpcode() != ISD::FP_EXTEND) 9954 return SDValue(); 9955 9956 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 9957 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 9958 // is sufficient to allow generaing fdot2. 9959 const TargetOptions &Options = DAG.getTarget().Options; 9960 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9961 (N->getFlags().hasAllowContract() && 9962 FMA->getFlags().hasAllowContract())) { 9963 Op1 = Op1.getOperand(0); 9964 Op2 = Op2.getOperand(0); 9965 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9966 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9967 return SDValue(); 9968 9969 SDValue Vec1 = Op1.getOperand(0); 9970 SDValue Idx1 = Op1.getOperand(1); 9971 SDValue Vec2 = Op2.getOperand(0); 9972 9973 SDValue FMAOp1 = FMA.getOperand(0); 9974 SDValue FMAOp2 = FMA.getOperand(1); 9975 SDValue FMAAcc = FMA.getOperand(2); 9976 9977 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 9978 FMAOp2.getOpcode() != ISD::FP_EXTEND) 9979 return SDValue(); 9980 9981 FMAOp1 = FMAOp1.getOperand(0); 9982 FMAOp2 = FMAOp2.getOperand(0); 9983 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9984 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9985 return SDValue(); 9986 9987 SDValue Vec3 = FMAOp1.getOperand(0); 9988 SDValue Vec4 = FMAOp2.getOperand(0); 9989 SDValue Idx2 = FMAOp1.getOperand(1); 9990 9991 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 9992 // Idx1 and Idx2 cannot be the same. 9993 Idx1 == Idx2) 9994 return SDValue(); 9995 9996 if (Vec1 == Vec2 || Vec3 == Vec4) 9997 return SDValue(); 9998 9999 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10000 return SDValue(); 10001 10002 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10003 (Vec1 == Vec4 && Vec2 == Vec3)) { 10004 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10005 DAG.getTargetConstant(0, SL, MVT::i1)); 10006 } 10007 } 10008 return SDValue(); 10009 } 10010 10011 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10012 DAGCombinerInfo &DCI) const { 10013 SelectionDAG &DAG = DCI.DAG; 10014 SDLoc SL(N); 10015 10016 SDValue LHS = N->getOperand(0); 10017 SDValue RHS = N->getOperand(1); 10018 EVT VT = LHS.getValueType(); 10019 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10020 10021 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10022 if (!CRHS) { 10023 CRHS = dyn_cast<ConstantSDNode>(LHS); 10024 if (CRHS) { 10025 std::swap(LHS, RHS); 10026 CC = getSetCCSwappedOperands(CC); 10027 } 10028 } 10029 10030 if (CRHS) { 10031 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10032 isBoolSGPR(LHS.getOperand(0))) { 10033 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10034 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10035 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10036 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10037 if ((CRHS->isAllOnesValue() && 10038 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10039 (CRHS->isNullValue() && 10040 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10041 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10042 DAG.getConstant(-1, SL, MVT::i1)); 10043 if ((CRHS->isAllOnesValue() && 10044 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10045 (CRHS->isNullValue() && 10046 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10047 return LHS.getOperand(0); 10048 } 10049 10050 uint64_t CRHSVal = CRHS->getZExtValue(); 10051 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10052 LHS.getOpcode() == ISD::SELECT && 10053 isa<ConstantSDNode>(LHS.getOperand(1)) && 10054 isa<ConstantSDNode>(LHS.getOperand(2)) && 10055 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10056 isBoolSGPR(LHS.getOperand(0))) { 10057 // Given CT != FT: 10058 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10059 // setcc (select cc, CT, CF), CF, ne => cc 10060 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10061 // setcc (select cc, CT, CF), CT, eq => cc 10062 uint64_t CT = LHS.getConstantOperandVal(1); 10063 uint64_t CF = LHS.getConstantOperandVal(2); 10064 10065 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10066 (CT == CRHSVal && CC == ISD::SETNE)) 10067 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10068 DAG.getConstant(-1, SL, MVT::i1)); 10069 if ((CF == CRHSVal && CC == ISD::SETNE) || 10070 (CT == CRHSVal && CC == ISD::SETEQ)) 10071 return LHS.getOperand(0); 10072 } 10073 } 10074 10075 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10076 VT != MVT::f16)) 10077 return SDValue(); 10078 10079 // Match isinf/isfinite pattern 10080 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10081 // (fcmp one (fabs x), inf) -> (fp_class x, 10082 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10083 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10084 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10085 if (!CRHS) 10086 return SDValue(); 10087 10088 const APFloat &APF = CRHS->getValueAPF(); 10089 if (APF.isInfinity() && !APF.isNegative()) { 10090 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10091 SIInstrFlags::N_INFINITY; 10092 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10093 SIInstrFlags::P_ZERO | 10094 SIInstrFlags::N_NORMAL | 10095 SIInstrFlags::P_NORMAL | 10096 SIInstrFlags::N_SUBNORMAL | 10097 SIInstrFlags::P_SUBNORMAL; 10098 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10099 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10100 DAG.getConstant(Mask, SL, MVT::i32)); 10101 } 10102 } 10103 10104 return SDValue(); 10105 } 10106 10107 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10108 DAGCombinerInfo &DCI) const { 10109 SelectionDAG &DAG = DCI.DAG; 10110 SDLoc SL(N); 10111 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10112 10113 SDValue Src = N->getOperand(0); 10114 SDValue Shift = N->getOperand(0); 10115 10116 // TODO: Extend type shouldn't matter (assuming legal types). 10117 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10118 Shift = Shift.getOperand(0); 10119 10120 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10121 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10122 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10123 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10124 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10125 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10126 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10127 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10128 SDLoc(Shift.getOperand(0)), MVT::i32); 10129 10130 unsigned ShiftOffset = 8 * Offset; 10131 if (Shift.getOpcode() == ISD::SHL) 10132 ShiftOffset -= C->getZExtValue(); 10133 else 10134 ShiftOffset += C->getZExtValue(); 10135 10136 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10137 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10138 MVT::f32, Shift); 10139 } 10140 } 10141 } 10142 10143 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10144 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10145 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10146 // We simplified Src. If this node is not dead, visit it again so it is 10147 // folded properly. 10148 if (N->getOpcode() != ISD::DELETED_NODE) 10149 DCI.AddToWorklist(N); 10150 return SDValue(N, 0); 10151 } 10152 10153 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10154 if (SDValue DemandedSrc = 10155 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10156 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10157 10158 return SDValue(); 10159 } 10160 10161 SDValue SITargetLowering::performClampCombine(SDNode *N, 10162 DAGCombinerInfo &DCI) const { 10163 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10164 if (!CSrc) 10165 return SDValue(); 10166 10167 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10168 const APFloat &F = CSrc->getValueAPF(); 10169 APFloat Zero = APFloat::getZero(F.getSemantics()); 10170 if (F < Zero || 10171 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10172 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10173 } 10174 10175 APFloat One(F.getSemantics(), "1.0"); 10176 if (F > One) 10177 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10178 10179 return SDValue(CSrc, 0); 10180 } 10181 10182 10183 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10184 DAGCombinerInfo &DCI) const { 10185 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10186 return SDValue(); 10187 switch (N->getOpcode()) { 10188 default: 10189 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10190 case ISD::ADD: 10191 return performAddCombine(N, DCI); 10192 case ISD::SUB: 10193 return performSubCombine(N, DCI); 10194 case ISD::ADDCARRY: 10195 case ISD::SUBCARRY: 10196 return performAddCarrySubCarryCombine(N, DCI); 10197 case ISD::FADD: 10198 return performFAddCombine(N, DCI); 10199 case ISD::FSUB: 10200 return performFSubCombine(N, DCI); 10201 case ISD::SETCC: 10202 return performSetCCCombine(N, DCI); 10203 case ISD::FMAXNUM: 10204 case ISD::FMINNUM: 10205 case ISD::FMAXNUM_IEEE: 10206 case ISD::FMINNUM_IEEE: 10207 case ISD::SMAX: 10208 case ISD::SMIN: 10209 case ISD::UMAX: 10210 case ISD::UMIN: 10211 case AMDGPUISD::FMIN_LEGACY: 10212 case AMDGPUISD::FMAX_LEGACY: 10213 return performMinMaxCombine(N, DCI); 10214 case ISD::FMA: 10215 return performFMACombine(N, DCI); 10216 case ISD::LOAD: { 10217 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10218 return Widended; 10219 LLVM_FALLTHROUGH; 10220 } 10221 case ISD::STORE: 10222 case ISD::ATOMIC_LOAD: 10223 case ISD::ATOMIC_STORE: 10224 case ISD::ATOMIC_CMP_SWAP: 10225 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 10226 case ISD::ATOMIC_SWAP: 10227 case ISD::ATOMIC_LOAD_ADD: 10228 case ISD::ATOMIC_LOAD_SUB: 10229 case ISD::ATOMIC_LOAD_AND: 10230 case ISD::ATOMIC_LOAD_OR: 10231 case ISD::ATOMIC_LOAD_XOR: 10232 case ISD::ATOMIC_LOAD_NAND: 10233 case ISD::ATOMIC_LOAD_MIN: 10234 case ISD::ATOMIC_LOAD_MAX: 10235 case ISD::ATOMIC_LOAD_UMIN: 10236 case ISD::ATOMIC_LOAD_UMAX: 10237 case ISD::ATOMIC_LOAD_FADD: 10238 case AMDGPUISD::ATOMIC_INC: 10239 case AMDGPUISD::ATOMIC_DEC: 10240 case AMDGPUISD::ATOMIC_LOAD_FMIN: 10241 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 10242 if (DCI.isBeforeLegalize()) 10243 break; 10244 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 10245 case ISD::AND: 10246 return performAndCombine(N, DCI); 10247 case ISD::OR: 10248 return performOrCombine(N, DCI); 10249 case ISD::XOR: 10250 return performXorCombine(N, DCI); 10251 case ISD::ZERO_EXTEND: 10252 return performZeroExtendCombine(N, DCI); 10253 case ISD::SIGN_EXTEND_INREG: 10254 return performSignExtendInRegCombine(N , DCI); 10255 case AMDGPUISD::FP_CLASS: 10256 return performClassCombine(N, DCI); 10257 case ISD::FCANONICALIZE: 10258 return performFCanonicalizeCombine(N, DCI); 10259 case AMDGPUISD::RCP: 10260 return performRcpCombine(N, DCI); 10261 case AMDGPUISD::FRACT: 10262 case AMDGPUISD::RSQ: 10263 case AMDGPUISD::RCP_LEGACY: 10264 case AMDGPUISD::RCP_IFLAG: 10265 case AMDGPUISD::RSQ_CLAMP: 10266 case AMDGPUISD::LDEXP: { 10267 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10268 SDValue Src = N->getOperand(0); 10269 if (Src.isUndef()) 10270 return Src; 10271 break; 10272 } 10273 case ISD::SINT_TO_FP: 10274 case ISD::UINT_TO_FP: 10275 return performUCharToFloatCombine(N, DCI); 10276 case AMDGPUISD::CVT_F32_UBYTE0: 10277 case AMDGPUISD::CVT_F32_UBYTE1: 10278 case AMDGPUISD::CVT_F32_UBYTE2: 10279 case AMDGPUISD::CVT_F32_UBYTE3: 10280 return performCvtF32UByteNCombine(N, DCI); 10281 case AMDGPUISD::FMED3: 10282 return performFMed3Combine(N, DCI); 10283 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10284 return performCvtPkRTZCombine(N, DCI); 10285 case AMDGPUISD::CLAMP: 10286 return performClampCombine(N, DCI); 10287 case ISD::SCALAR_TO_VECTOR: { 10288 SelectionDAG &DAG = DCI.DAG; 10289 EVT VT = N->getValueType(0); 10290 10291 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10292 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10293 SDLoc SL(N); 10294 SDValue Src = N->getOperand(0); 10295 EVT EltVT = Src.getValueType(); 10296 if (EltVT == MVT::f16) 10297 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10298 10299 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10300 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10301 } 10302 10303 break; 10304 } 10305 case ISD::EXTRACT_VECTOR_ELT: 10306 return performExtractVectorEltCombine(N, DCI); 10307 case ISD::INSERT_VECTOR_ELT: 10308 return performInsertVectorEltCombine(N, DCI); 10309 } 10310 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10311 } 10312 10313 /// Helper function for adjustWritemask 10314 static unsigned SubIdx2Lane(unsigned Idx) { 10315 switch (Idx) { 10316 default: return 0; 10317 case AMDGPU::sub0: return 0; 10318 case AMDGPU::sub1: return 1; 10319 case AMDGPU::sub2: return 2; 10320 case AMDGPU::sub3: return 3; 10321 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10322 } 10323 } 10324 10325 /// Adjust the writemask of MIMG instructions 10326 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10327 SelectionDAG &DAG) const { 10328 unsigned Opcode = Node->getMachineOpcode(); 10329 10330 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10331 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10332 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10333 return Node; // not implemented for D16 10334 10335 SDNode *Users[5] = { nullptr }; 10336 unsigned Lane = 0; 10337 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10338 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10339 unsigned NewDmask = 0; 10340 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10341 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10342 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10343 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10344 unsigned TFCLane = 0; 10345 bool HasChain = Node->getNumValues() > 1; 10346 10347 if (OldDmask == 0) { 10348 // These are folded out, but on the chance it happens don't assert. 10349 return Node; 10350 } 10351 10352 unsigned OldBitsSet = countPopulation(OldDmask); 10353 // Work out which is the TFE/LWE lane if that is enabled. 10354 if (UsesTFC) { 10355 TFCLane = OldBitsSet; 10356 } 10357 10358 // Try to figure out the used register components 10359 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10360 I != E; ++I) { 10361 10362 // Don't look at users of the chain. 10363 if (I.getUse().getResNo() != 0) 10364 continue; 10365 10366 // Abort if we can't understand the usage 10367 if (!I->isMachineOpcode() || 10368 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10369 return Node; 10370 10371 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10372 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10373 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10374 // set, etc. 10375 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10376 10377 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10378 if (UsesTFC && Lane == TFCLane) { 10379 Users[Lane] = *I; 10380 } else { 10381 // Set which texture component corresponds to the lane. 10382 unsigned Comp; 10383 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10384 Comp = countTrailingZeros(Dmask); 10385 Dmask &= ~(1 << Comp); 10386 } 10387 10388 // Abort if we have more than one user per component. 10389 if (Users[Lane]) 10390 return Node; 10391 10392 Users[Lane] = *I; 10393 NewDmask |= 1 << Comp; 10394 } 10395 } 10396 10397 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10398 bool NoChannels = !NewDmask; 10399 if (NoChannels) { 10400 if (!UsesTFC) { 10401 // No uses of the result and not using TFC. Then do nothing. 10402 return Node; 10403 } 10404 // If the original dmask has one channel - then nothing to do 10405 if (OldBitsSet == 1) 10406 return Node; 10407 // Use an arbitrary dmask - required for the instruction to work 10408 NewDmask = 1; 10409 } 10410 // Abort if there's no change 10411 if (NewDmask == OldDmask) 10412 return Node; 10413 10414 unsigned BitsSet = countPopulation(NewDmask); 10415 10416 // Check for TFE or LWE - increase the number of channels by one to account 10417 // for the extra return value 10418 // This will need adjustment for D16 if this is also included in 10419 // adjustWriteMask (this function) but at present D16 are excluded. 10420 unsigned NewChannels = BitsSet + UsesTFC; 10421 10422 int NewOpcode = 10423 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10424 assert(NewOpcode != -1 && 10425 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10426 "failed to find equivalent MIMG op"); 10427 10428 // Adjust the writemask in the node 10429 SmallVector<SDValue, 12> Ops; 10430 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10431 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10432 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10433 10434 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10435 10436 MVT ResultVT = NewChannels == 1 ? 10437 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10438 NewChannels == 5 ? 8 : NewChannels); 10439 SDVTList NewVTList = HasChain ? 10440 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10441 10442 10443 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10444 NewVTList, Ops); 10445 10446 if (HasChain) { 10447 // Update chain. 10448 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10449 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10450 } 10451 10452 if (NewChannels == 1) { 10453 assert(Node->hasNUsesOfValue(1, 0)); 10454 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10455 SDLoc(Node), Users[Lane]->getValueType(0), 10456 SDValue(NewNode, 0)); 10457 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10458 return nullptr; 10459 } 10460 10461 // Update the users of the node with the new indices 10462 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10463 SDNode *User = Users[i]; 10464 if (!User) { 10465 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10466 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10467 if (i || !NoChannels) 10468 continue; 10469 } else { 10470 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10471 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10472 } 10473 10474 switch (Idx) { 10475 default: break; 10476 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10477 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10478 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10479 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10480 } 10481 } 10482 10483 DAG.RemoveDeadNode(Node); 10484 return nullptr; 10485 } 10486 10487 static bool isFrameIndexOp(SDValue Op) { 10488 if (Op.getOpcode() == ISD::AssertZext) 10489 Op = Op.getOperand(0); 10490 10491 return isa<FrameIndexSDNode>(Op); 10492 } 10493 10494 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10495 /// with frame index operands. 10496 /// LLVM assumes that inputs are to these instructions are registers. 10497 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10498 SelectionDAG &DAG) const { 10499 if (Node->getOpcode() == ISD::CopyToReg) { 10500 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10501 SDValue SrcVal = Node->getOperand(2); 10502 10503 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10504 // to try understanding copies to physical registers. 10505 if (SrcVal.getValueType() == MVT::i1 && 10506 Register::isPhysicalRegister(DestReg->getReg())) { 10507 SDLoc SL(Node); 10508 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10509 SDValue VReg = DAG.getRegister( 10510 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10511 10512 SDNode *Glued = Node->getGluedNode(); 10513 SDValue ToVReg 10514 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10515 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10516 SDValue ToResultReg 10517 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10518 VReg, ToVReg.getValue(1)); 10519 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10520 DAG.RemoveDeadNode(Node); 10521 return ToResultReg.getNode(); 10522 } 10523 } 10524 10525 SmallVector<SDValue, 8> Ops; 10526 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10527 if (!isFrameIndexOp(Node->getOperand(i))) { 10528 Ops.push_back(Node->getOperand(i)); 10529 continue; 10530 } 10531 10532 SDLoc DL(Node); 10533 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10534 Node->getOperand(i).getValueType(), 10535 Node->getOperand(i)), 0)); 10536 } 10537 10538 return DAG.UpdateNodeOperands(Node, Ops); 10539 } 10540 10541 /// Fold the instructions after selecting them. 10542 /// Returns null if users were already updated. 10543 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10544 SelectionDAG &DAG) const { 10545 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10546 unsigned Opcode = Node->getMachineOpcode(); 10547 10548 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10549 !TII->isGather4(Opcode)) { 10550 return adjustWritemask(Node, DAG); 10551 } 10552 10553 if (Opcode == AMDGPU::INSERT_SUBREG || 10554 Opcode == AMDGPU::REG_SEQUENCE) { 10555 legalizeTargetIndependentNode(Node, DAG); 10556 return Node; 10557 } 10558 10559 switch (Opcode) { 10560 case AMDGPU::V_DIV_SCALE_F32: 10561 case AMDGPU::V_DIV_SCALE_F64: { 10562 // Satisfy the operand register constraint when one of the inputs is 10563 // undefined. Ordinarily each undef value will have its own implicit_def of 10564 // a vreg, so force these to use a single register. 10565 SDValue Src0 = Node->getOperand(0); 10566 SDValue Src1 = Node->getOperand(1); 10567 SDValue Src2 = Node->getOperand(2); 10568 10569 if ((Src0.isMachineOpcode() && 10570 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10571 (Src0 == Src1 || Src0 == Src2)) 10572 break; 10573 10574 MVT VT = Src0.getValueType().getSimpleVT(); 10575 const TargetRegisterClass *RC = 10576 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10577 10578 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10579 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10580 10581 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10582 UndefReg, Src0, SDValue()); 10583 10584 // src0 must be the same register as src1 or src2, even if the value is 10585 // undefined, so make sure we don't violate this constraint. 10586 if (Src0.isMachineOpcode() && 10587 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10588 if (Src1.isMachineOpcode() && 10589 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10590 Src0 = Src1; 10591 else if (Src2.isMachineOpcode() && 10592 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10593 Src0 = Src2; 10594 else { 10595 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10596 Src0 = UndefReg; 10597 Src1 = UndefReg; 10598 } 10599 } else 10600 break; 10601 10602 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10603 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10604 Ops.push_back(Node->getOperand(I)); 10605 10606 Ops.push_back(ImpDef.getValue(1)); 10607 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10608 } 10609 default: 10610 break; 10611 } 10612 10613 return Node; 10614 } 10615 10616 /// Assign the register class depending on the number of 10617 /// bits set in the writemask 10618 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10619 SDNode *Node) const { 10620 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10621 10622 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10623 10624 if (TII->isVOP3(MI.getOpcode())) { 10625 // Make sure constant bus requirements are respected. 10626 TII->legalizeOperandsVOP3(MRI, MI); 10627 10628 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10629 // This saves a chain-copy of registers and better ballance register 10630 // use between vgpr and agpr as agpr tuples tend to be big. 10631 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10632 unsigned Opc = MI.getOpcode(); 10633 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10634 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10635 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10636 if (I == -1) 10637 break; 10638 MachineOperand &Op = MI.getOperand(I); 10639 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10640 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10641 !Register::isVirtualRegister(Op.getReg()) || 10642 !TRI->isAGPR(MRI, Op.getReg())) 10643 continue; 10644 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10645 if (!Src || !Src->isCopy() || 10646 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10647 continue; 10648 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10649 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10650 // All uses of agpr64 and agpr32 can also accept vgpr except for 10651 // v_accvgpr_read, but we do not produce agpr reads during selection, 10652 // so no use checks are needed. 10653 MRI.setRegClass(Op.getReg(), NewRC); 10654 } 10655 } 10656 10657 return; 10658 } 10659 10660 // Replace unused atomics with the no return version. 10661 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10662 if (NoRetAtomicOp != -1) { 10663 if (!Node->hasAnyUseOfValue(0)) { 10664 MI.setDesc(TII->get(NoRetAtomicOp)); 10665 MI.RemoveOperand(0); 10666 return; 10667 } 10668 10669 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10670 // instruction, because the return type of these instructions is a vec2 of 10671 // the memory type, so it can be tied to the input operand. 10672 // This means these instructions always have a use, so we need to add a 10673 // special case to check if the atomic has only one extract_subreg use, 10674 // which itself has no uses. 10675 if ((Node->hasNUsesOfValue(1, 0) && 10676 Node->use_begin()->isMachineOpcode() && 10677 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10678 !Node->use_begin()->hasAnyUseOfValue(0))) { 10679 Register Def = MI.getOperand(0).getReg(); 10680 10681 // Change this into a noret atomic. 10682 MI.setDesc(TII->get(NoRetAtomicOp)); 10683 MI.RemoveOperand(0); 10684 10685 // If we only remove the def operand from the atomic instruction, the 10686 // extract_subreg will be left with a use of a vreg without a def. 10687 // So we need to insert an implicit_def to avoid machine verifier 10688 // errors. 10689 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10690 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10691 } 10692 return; 10693 } 10694 } 10695 10696 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 10697 uint64_t Val) { 10698 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 10699 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 10700 } 10701 10702 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 10703 const SDLoc &DL, 10704 SDValue Ptr) const { 10705 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10706 10707 // Build the half of the subregister with the constants before building the 10708 // full 128-bit register. If we are building multiple resource descriptors, 10709 // this will allow CSEing of the 2-component register. 10710 const SDValue Ops0[] = { 10711 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 10712 buildSMovImm32(DAG, DL, 0), 10713 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10714 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 10715 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 10716 }; 10717 10718 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 10719 MVT::v2i32, Ops0), 0); 10720 10721 // Combine the constants and the pointer. 10722 const SDValue Ops1[] = { 10723 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10724 Ptr, 10725 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 10726 SubRegHi, 10727 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 10728 }; 10729 10730 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 10731 } 10732 10733 /// Return a resource descriptor with the 'Add TID' bit enabled 10734 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 10735 /// of the resource descriptor) to create an offset, which is added to 10736 /// the resource pointer. 10737 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 10738 SDValue Ptr, uint32_t RsrcDword1, 10739 uint64_t RsrcDword2And3) const { 10740 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 10741 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 10742 if (RsrcDword1) { 10743 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 10744 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 10745 0); 10746 } 10747 10748 SDValue DataLo = buildSMovImm32(DAG, DL, 10749 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 10750 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 10751 10752 const SDValue Ops[] = { 10753 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10754 PtrLo, 10755 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10756 PtrHi, 10757 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 10758 DataLo, 10759 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 10760 DataHi, 10761 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 10762 }; 10763 10764 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 10765 } 10766 10767 //===----------------------------------------------------------------------===// 10768 // SI Inline Assembly Support 10769 //===----------------------------------------------------------------------===// 10770 10771 std::pair<unsigned, const TargetRegisterClass *> 10772 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10773 StringRef Constraint, 10774 MVT VT) const { 10775 const TargetRegisterClass *RC = nullptr; 10776 if (Constraint.size() == 1) { 10777 const unsigned BitWidth = VT.getSizeInBits(); 10778 switch (Constraint[0]) { 10779 default: 10780 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10781 case 's': 10782 case 'r': 10783 switch (BitWidth) { 10784 case 16: 10785 RC = &AMDGPU::SReg_32RegClass; 10786 break; 10787 case 64: 10788 RC = &AMDGPU::SGPR_64RegClass; 10789 break; 10790 default: 10791 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 10792 if (!RC) 10793 return std::make_pair(0U, nullptr); 10794 break; 10795 } 10796 break; 10797 case 'v': 10798 switch (BitWidth) { 10799 case 16: 10800 RC = &AMDGPU::VGPR_32RegClass; 10801 break; 10802 default: 10803 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 10804 if (!RC) 10805 return std::make_pair(0U, nullptr); 10806 break; 10807 } 10808 break; 10809 case 'a': 10810 if (!Subtarget->hasMAIInsts()) 10811 break; 10812 switch (BitWidth) { 10813 case 16: 10814 RC = &AMDGPU::AGPR_32RegClass; 10815 break; 10816 default: 10817 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 10818 if (!RC) 10819 return std::make_pair(0U, nullptr); 10820 break; 10821 } 10822 break; 10823 } 10824 // We actually support i128, i16 and f16 as inline parameters 10825 // even if they are not reported as legal 10826 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 10827 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 10828 return std::make_pair(0U, RC); 10829 } 10830 10831 if (Constraint.size() > 1) { 10832 if (Constraint[1] == 'v') { 10833 RC = &AMDGPU::VGPR_32RegClass; 10834 } else if (Constraint[1] == 's') { 10835 RC = &AMDGPU::SGPR_32RegClass; 10836 } else if (Constraint[1] == 'a') { 10837 RC = &AMDGPU::AGPR_32RegClass; 10838 } 10839 10840 if (RC) { 10841 uint32_t Idx; 10842 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 10843 if (!Failed && Idx < RC->getNumRegs()) 10844 return std::make_pair(RC->getRegister(Idx), RC); 10845 } 10846 } 10847 10848 // FIXME: Returns VS_32 for physical SGPR constraints 10849 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10850 } 10851 10852 SITargetLowering::ConstraintType 10853 SITargetLowering::getConstraintType(StringRef Constraint) const { 10854 if (Constraint.size() == 1) { 10855 switch (Constraint[0]) { 10856 default: break; 10857 case 's': 10858 case 'v': 10859 case 'a': 10860 return C_RegisterClass; 10861 } 10862 } 10863 return TargetLowering::getConstraintType(Constraint); 10864 } 10865 10866 // Figure out which registers should be reserved for stack access. Only after 10867 // the function is legalized do we know all of the non-spill stack objects or if 10868 // calls are present. 10869 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 10870 MachineRegisterInfo &MRI = MF.getRegInfo(); 10871 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10872 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 10873 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10874 10875 if (Info->isEntryFunction()) { 10876 // Callable functions have fixed registers used for stack access. 10877 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 10878 } 10879 10880 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 10881 Info->getStackPtrOffsetReg())); 10882 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 10883 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 10884 10885 // We need to worry about replacing the default register with itself in case 10886 // of MIR testcases missing the MFI. 10887 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 10888 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 10889 10890 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 10891 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 10892 10893 Info->limitOccupancy(MF); 10894 10895 if (ST.isWave32() && !MF.empty()) { 10896 // Add VCC_HI def because many instructions marked as imp-use VCC where 10897 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 10898 // having a use of undef. 10899 10900 const SIInstrInfo *TII = ST.getInstrInfo(); 10901 DebugLoc DL; 10902 10903 MachineBasicBlock &MBB = MF.front(); 10904 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 10905 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 10906 10907 for (auto &MBB : MF) { 10908 for (auto &MI : MBB) { 10909 TII->fixImplicitOperands(MI); 10910 } 10911 } 10912 } 10913 10914 TargetLoweringBase::finalizeLowering(MF); 10915 10916 // Allocate a VGPR for future SGPR Spill if 10917 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 10918 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 10919 if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill && 10920 !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects()) 10921 Info->reserveVGPRforSGPRSpills(MF); 10922 } 10923 10924 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 10925 KnownBits &Known, 10926 const APInt &DemandedElts, 10927 const SelectionDAG &DAG, 10928 unsigned Depth) const { 10929 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 10930 DAG, Depth); 10931 10932 // Set the high bits to zero based on the maximum allowed scratch size per 10933 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 10934 // calculation won't overflow, so assume the sign bit is never set. 10935 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 10936 } 10937 10938 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 10939 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 10940 const Align CacheLineAlign = Align(64); 10941 10942 // Pre-GFX10 target did not benefit from loop alignment 10943 if (!ML || DisableLoopAlignment || 10944 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 10945 getSubtarget()->hasInstFwdPrefetchBug()) 10946 return PrefAlign; 10947 10948 // On GFX10 I$ is 4 x 64 bytes cache lines. 10949 // By default prefetcher keeps one cache line behind and reads two ahead. 10950 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 10951 // behind and one ahead. 10952 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 10953 // If loop fits 64 bytes it always spans no more than two cache lines and 10954 // does not need an alignment. 10955 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 10956 // Else if loop is less or equal 192 bytes we need two lines behind. 10957 10958 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10959 const MachineBasicBlock *Header = ML->getHeader(); 10960 if (Header->getAlignment() != PrefAlign) 10961 return Header->getAlignment(); // Already processed. 10962 10963 unsigned LoopSize = 0; 10964 for (const MachineBasicBlock *MBB : ML->blocks()) { 10965 // If inner loop block is aligned assume in average half of the alignment 10966 // size to be added as nops. 10967 if (MBB != Header) 10968 LoopSize += MBB->getAlignment().value() / 2; 10969 10970 for (const MachineInstr &MI : *MBB) { 10971 LoopSize += TII->getInstSizeInBytes(MI); 10972 if (LoopSize > 192) 10973 return PrefAlign; 10974 } 10975 } 10976 10977 if (LoopSize <= 64) 10978 return PrefAlign; 10979 10980 if (LoopSize <= 128) 10981 return CacheLineAlign; 10982 10983 // If any of parent loops is surrounded by prefetch instructions do not 10984 // insert new for inner loop, which would reset parent's settings. 10985 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 10986 if (MachineBasicBlock *Exit = P->getExitBlock()) { 10987 auto I = Exit->getFirstNonDebugInstr(); 10988 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 10989 return CacheLineAlign; 10990 } 10991 } 10992 10993 MachineBasicBlock *Pre = ML->getLoopPreheader(); 10994 MachineBasicBlock *Exit = ML->getExitBlock(); 10995 10996 if (Pre && Exit) { 10997 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 10998 TII->get(AMDGPU::S_INST_PREFETCH)) 10999 .addImm(1); // prefetch 2 lines behind PC 11000 11001 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11002 TII->get(AMDGPU::S_INST_PREFETCH)) 11003 .addImm(2); // prefetch 1 line behind PC 11004 } 11005 11006 return CacheLineAlign; 11007 } 11008 11009 LLVM_ATTRIBUTE_UNUSED 11010 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11011 assert(N->getOpcode() == ISD::CopyFromReg); 11012 do { 11013 // Follow the chain until we find an INLINEASM node. 11014 N = N->getOperand(0).getNode(); 11015 if (N->getOpcode() == ISD::INLINEASM || 11016 N->getOpcode() == ISD::INLINEASM_BR) 11017 return true; 11018 } while (N->getOpcode() == ISD::CopyFromReg); 11019 return false; 11020 } 11021 11022 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 11023 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 11024 { 11025 switch (N->getOpcode()) { 11026 case ISD::CopyFromReg: 11027 { 11028 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11029 const MachineFunction * MF = FLI->MF; 11030 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 11031 const MachineRegisterInfo &MRI = MF->getRegInfo(); 11032 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo(); 11033 Register Reg = R->getReg(); 11034 if (Reg.isPhysical()) 11035 return !TRI.isSGPRReg(MRI, Reg); 11036 11037 if (MRI.isLiveIn(Reg)) { 11038 // workitem.id.x workitem.id.y workitem.id.z 11039 // Any VGPR formal argument is also considered divergent 11040 if (!TRI.isSGPRReg(MRI, Reg)) 11041 return true; 11042 // Formal arguments of non-entry functions 11043 // are conservatively considered divergent 11044 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv())) 11045 return true; 11046 return false; 11047 } 11048 const Value *V = FLI->getValueFromVirtualReg(Reg); 11049 if (V) 11050 return KDA->isDivergent(V); 11051 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11052 return !TRI.isSGPRReg(MRI, Reg); 11053 } 11054 break; 11055 case ISD::LOAD: { 11056 const LoadSDNode *L = cast<LoadSDNode>(N); 11057 unsigned AS = L->getAddressSpace(); 11058 // A flat load may access private memory. 11059 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11060 } break; 11061 case ISD::CALLSEQ_END: 11062 return true; 11063 break; 11064 case ISD::INTRINSIC_WO_CHAIN: 11065 { 11066 11067 } 11068 return AMDGPU::isIntrinsicSourceOfDivergence( 11069 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11070 case ISD::INTRINSIC_W_CHAIN: 11071 return AMDGPU::isIntrinsicSourceOfDivergence( 11072 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11073 } 11074 return false; 11075 } 11076 11077 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11078 EVT VT) const { 11079 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11080 case MVT::f32: 11081 return hasFP32Denormals(DAG.getMachineFunction()); 11082 case MVT::f64: 11083 case MVT::f16: 11084 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11085 default: 11086 return false; 11087 } 11088 } 11089 11090 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11091 const SelectionDAG &DAG, 11092 bool SNaN, 11093 unsigned Depth) const { 11094 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11095 const MachineFunction &MF = DAG.getMachineFunction(); 11096 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11097 11098 if (Info->getMode().DX10Clamp) 11099 return true; // Clamped to 0. 11100 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11101 } 11102 11103 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11104 SNaN, Depth); 11105 } 11106 11107 TargetLowering::AtomicExpansionKind 11108 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11109 switch (RMW->getOperation()) { 11110 case AtomicRMWInst::FAdd: { 11111 Type *Ty = RMW->getType(); 11112 11113 // We don't have a way to support 16-bit atomics now, so just leave them 11114 // as-is. 11115 if (Ty->isHalfTy()) 11116 return AtomicExpansionKind::None; 11117 11118 if (!Ty->isFloatTy()) 11119 return AtomicExpansionKind::CmpXChg; 11120 11121 // TODO: Do have these for flat. Older targets also had them for buffers. 11122 unsigned AS = RMW->getPointerAddressSpace(); 11123 11124 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11125 return RMW->use_empty() ? AtomicExpansionKind::None : 11126 AtomicExpansionKind::CmpXChg; 11127 } 11128 11129 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11130 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11131 } 11132 default: 11133 break; 11134 } 11135 11136 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11137 } 11138 11139 const TargetRegisterClass * 11140 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11141 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11142 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11143 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11144 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11145 : &AMDGPU::SReg_32RegClass; 11146 if (!TRI->isSGPRClass(RC) && !isDivergent) 11147 return TRI->getEquivalentSGPRClass(RC); 11148 else if (TRI->isSGPRClass(RC) && isDivergent) 11149 return TRI->getEquivalentVGPRClass(RC); 11150 11151 return RC; 11152 } 11153 11154 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11155 // uniform values (as produced by the mask results of control flow intrinsics) 11156 // used outside of divergent blocks. The phi users need to also be treated as 11157 // always uniform. 11158 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11159 unsigned WaveSize) { 11160 // FIXME: We asssume we never cast the mask results of a control flow 11161 // intrinsic. 11162 // Early exit if the type won't be consistent as a compile time hack. 11163 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11164 if (!IT || IT->getBitWidth() != WaveSize) 11165 return false; 11166 11167 if (!isa<Instruction>(V)) 11168 return false; 11169 if (!Visited.insert(V).second) 11170 return false; 11171 bool Result = false; 11172 for (auto U : V->users()) { 11173 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11174 if (V == U->getOperand(1)) { 11175 switch (Intrinsic->getIntrinsicID()) { 11176 default: 11177 Result = false; 11178 break; 11179 case Intrinsic::amdgcn_if_break: 11180 case Intrinsic::amdgcn_if: 11181 case Intrinsic::amdgcn_else: 11182 Result = true; 11183 break; 11184 } 11185 } 11186 if (V == U->getOperand(0)) { 11187 switch (Intrinsic->getIntrinsicID()) { 11188 default: 11189 Result = false; 11190 break; 11191 case Intrinsic::amdgcn_end_cf: 11192 case Intrinsic::amdgcn_loop: 11193 Result = true; 11194 break; 11195 } 11196 } 11197 } else { 11198 Result = hasCFUser(U, Visited, WaveSize); 11199 } 11200 if (Result) 11201 break; 11202 } 11203 return Result; 11204 } 11205 11206 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11207 const Value *V) const { 11208 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11209 if (CI->isInlineAsm()) { 11210 // FIXME: This cannot give a correct answer. This should only trigger in 11211 // the case where inline asm returns mixed SGPR and VGPR results, used 11212 // outside the defining block. We don't have a specific result to 11213 // consider, so this assumes if any value is SGPR, the overall register 11214 // also needs to be SGPR. 11215 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11216 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11217 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11218 for (auto &TC : TargetConstraints) { 11219 if (TC.Type == InlineAsm::isOutput) { 11220 ComputeConstraintToUse(TC, SDValue()); 11221 unsigned AssignedReg; 11222 const TargetRegisterClass *RC; 11223 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11224 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11225 if (RC) { 11226 MachineRegisterInfo &MRI = MF.getRegInfo(); 11227 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11228 return true; 11229 else if (SIRI->isSGPRClass(RC)) 11230 return true; 11231 } 11232 } 11233 } 11234 } 11235 } 11236 SmallPtrSet<const Value *, 16> Visited; 11237 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11238 } 11239