1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 /// \file 11 /// \brief Custom DAG lowering for SI 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifdef _MSC_VER 16 // Provide M_PI. 17 #define _USE_MATH_DEFINES 18 #endif 19 20 #include "AMDGPU.h" 21 #include "AMDGPUIntrinsicInfo.h" 22 #include "AMDGPUSubtarget.h" 23 #include "SIDefines.h" 24 #include "SIISelLowering.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/StringRef.h" 35 #include "llvm/ADT/StringSwitch.h" 36 #include "llvm/ADT/Twine.h" 37 #include "llvm/CodeGen/Analysis.h" 38 #include "llvm/CodeGen/CallingConvLower.h" 39 #include "llvm/CodeGen/DAGCombine.h" 40 #include "llvm/CodeGen/ISDOpcodes.h" 41 #include "llvm/CodeGen/MachineBasicBlock.h" 42 #include "llvm/CodeGen/MachineFrameInfo.h" 43 #include "llvm/CodeGen/MachineFunction.h" 44 #include "llvm/CodeGen/MachineInstr.h" 45 #include "llvm/CodeGen/MachineInstrBuilder.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineOperand.h" 48 #include "llvm/CodeGen/MachineRegisterInfo.h" 49 #include "llvm/CodeGen/MachineValueType.h" 50 #include "llvm/CodeGen/SelectionDAG.h" 51 #include "llvm/CodeGen/SelectionDAGNodes.h" 52 #include "llvm/CodeGen/ValueTypes.h" 53 #include "llvm/IR/Constants.h" 54 #include "llvm/IR/DataLayout.h" 55 #include "llvm/IR/DebugLoc.h" 56 #include "llvm/IR/DerivedTypes.h" 57 #include "llvm/IR/DiagnosticInfo.h" 58 #include "llvm/IR/Function.h" 59 #include "llvm/IR/GlobalValue.h" 60 #include "llvm/IR/InstrTypes.h" 61 #include "llvm/IR/Instruction.h" 62 #include "llvm/IR/Instructions.h" 63 #include "llvm/IR/Type.h" 64 #include "llvm/Support/Casting.h" 65 #include "llvm/Support/CodeGen.h" 66 #include "llvm/Support/CommandLine.h" 67 #include "llvm/Support/Compiler.h" 68 #include "llvm/Support/ErrorHandling.h" 69 #include "llvm/Support/MathExtras.h" 70 #include "llvm/Target/TargetCallingConv.h" 71 #include "llvm/Target/TargetMachine.h" 72 #include "llvm/Target/TargetOptions.h" 73 #include "llvm/Target/TargetRegisterInfo.h" 74 #include <cassert> 75 #include <cmath> 76 #include <cstdint> 77 #include <iterator> 78 #include <tuple> 79 #include <utility> 80 #include <vector> 81 82 using namespace llvm; 83 84 static cl::opt<bool> EnableVGPRIndexMode( 85 "amdgpu-vgpr-index-mode", 86 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"), 87 cl::init(false)); 88 89 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 90 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 91 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 92 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 93 return AMDGPU::SGPR0 + Reg; 94 } 95 } 96 llvm_unreachable("Cannot allocate sgpr"); 97 } 98 99 SITargetLowering::SITargetLowering(const TargetMachine &TM, 100 const SISubtarget &STI) 101 : AMDGPUTargetLowering(TM, STI) { 102 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 103 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 104 105 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass); 106 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 107 108 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 109 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 110 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 111 112 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass); 113 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass); 114 115 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass); 116 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 117 118 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass); 119 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 120 121 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass); 122 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 123 124 if (Subtarget->has16BitInsts()) { 125 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass); 126 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass); 127 } 128 129 computeRegisterProperties(STI.getRegisterInfo()); 130 131 // We need to custom lower vector stores from local memory 132 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 133 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 134 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 135 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 136 setOperationAction(ISD::LOAD, MVT::i1, Custom); 137 138 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 139 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 140 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 141 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 142 setOperationAction(ISD::STORE, MVT::i1, Custom); 143 144 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 145 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 146 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 147 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 148 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 149 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 150 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 151 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 152 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 153 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 154 155 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 156 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 157 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand); 158 159 setOperationAction(ISD::SELECT, MVT::i1, Promote); 160 setOperationAction(ISD::SELECT, MVT::i64, Custom); 161 setOperationAction(ISD::SELECT, MVT::f64, Promote); 162 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 163 164 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 165 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 166 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 167 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 168 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 169 170 setOperationAction(ISD::SETCC, MVT::i1, Promote); 171 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 172 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 173 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 174 175 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 176 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 177 178 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 179 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 180 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 181 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 182 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 183 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 184 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 185 186 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 187 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 188 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 189 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 190 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 191 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 192 193 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 194 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 195 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 196 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 197 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 198 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 199 200 setOperationAction(ISD::UADDO, MVT::i32, Legal); 201 setOperationAction(ISD::USUBO, MVT::i32, Legal); 202 203 // We only support LOAD/STORE and vector manipulation ops for vectors 204 // with > 4 elements. 205 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, MVT::v2i64, MVT::v2f64}) { 206 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 207 switch (Op) { 208 case ISD::LOAD: 209 case ISD::STORE: 210 case ISD::BUILD_VECTOR: 211 case ISD::BITCAST: 212 case ISD::EXTRACT_VECTOR_ELT: 213 case ISD::INSERT_VECTOR_ELT: 214 case ISD::INSERT_SUBVECTOR: 215 case ISD::EXTRACT_SUBVECTOR: 216 case ISD::SCALAR_TO_VECTOR: 217 break; 218 case ISD::CONCAT_VECTORS: 219 setOperationAction(Op, VT, Custom); 220 break; 221 default: 222 setOperationAction(Op, VT, Expand); 223 break; 224 } 225 } 226 } 227 228 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 229 // is expanded to avoid having two separate loops in case the index is a VGPR. 230 231 // Most operations are naturally 32-bit vector operations. We only support 232 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 233 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 234 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 235 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 236 237 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 238 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 239 240 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 241 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 242 243 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 244 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 245 } 246 247 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 248 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 249 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 250 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 251 252 // Avoid stack access for these. 253 // TODO: Generalize to more vector types. 254 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 255 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 256 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 257 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 258 259 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 260 // and output demarshalling 261 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 262 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 263 264 // We can't return success/failure, only the old value, 265 // let LLVM add the comparison 266 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 267 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 268 269 if (getSubtarget()->hasFlatAddressSpace()) { 270 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 271 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 272 } 273 274 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 275 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 276 277 // On SI this is s_memtime and s_memrealtime on VI. 278 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 279 setOperationAction(ISD::TRAP, MVT::Other, Legal); 280 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 281 282 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 283 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 284 285 if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) { 286 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 287 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 288 setOperationAction(ISD::FRINT, MVT::f64, Legal); 289 } 290 291 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 292 293 setOperationAction(ISD::FSIN, MVT::f32, Custom); 294 setOperationAction(ISD::FCOS, MVT::f32, Custom); 295 setOperationAction(ISD::FDIV, MVT::f32, Custom); 296 setOperationAction(ISD::FDIV, MVT::f64, Custom); 297 298 if (Subtarget->has16BitInsts()) { 299 setOperationAction(ISD::Constant, MVT::i16, Legal); 300 301 setOperationAction(ISD::SMIN, MVT::i16, Legal); 302 setOperationAction(ISD::SMAX, MVT::i16, Legal); 303 304 setOperationAction(ISD::UMIN, MVT::i16, Legal); 305 setOperationAction(ISD::UMAX, MVT::i16, Legal); 306 307 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 308 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 309 310 setOperationAction(ISD::ROTR, MVT::i16, Promote); 311 setOperationAction(ISD::ROTL, MVT::i16, Promote); 312 313 setOperationAction(ISD::SDIV, MVT::i16, Promote); 314 setOperationAction(ISD::UDIV, MVT::i16, Promote); 315 setOperationAction(ISD::SREM, MVT::i16, Promote); 316 setOperationAction(ISD::UREM, MVT::i16, Promote); 317 318 setOperationAction(ISD::BSWAP, MVT::i16, Promote); 319 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 320 321 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 322 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 323 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 324 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 325 326 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 327 328 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 329 330 setOperationAction(ISD::LOAD, MVT::i16, Custom); 331 332 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 333 334 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 335 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 336 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 337 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 338 339 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 340 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 341 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote); 342 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote); 343 344 // F16 - Constant Actions. 345 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 346 347 // F16 - Load/Store Actions. 348 setOperationAction(ISD::LOAD, MVT::f16, Promote); 349 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 350 setOperationAction(ISD::STORE, MVT::f16, Promote); 351 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 352 353 // F16 - VOP1 Actions. 354 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 355 setOperationAction(ISD::FCOS, MVT::f16, Promote); 356 setOperationAction(ISD::FSIN, MVT::f16, Promote); 357 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 358 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 359 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 360 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 361 362 // F16 - VOP2 Actions. 363 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 364 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 365 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 366 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 367 setOperationAction(ISD::FDIV, MVT::f16, Custom); 368 369 // F16 - VOP3 Actions. 370 setOperationAction(ISD::FMA, MVT::f16, Legal); 371 if (!Subtarget->hasFP16Denormals()) 372 setOperationAction(ISD::FMAD, MVT::f16, Legal); 373 } 374 375 setTargetDAGCombine(ISD::FADD); 376 setTargetDAGCombine(ISD::FSUB); 377 setTargetDAGCombine(ISD::FMINNUM); 378 setTargetDAGCombine(ISD::FMAXNUM); 379 setTargetDAGCombine(ISD::SMIN); 380 setTargetDAGCombine(ISD::SMAX); 381 setTargetDAGCombine(ISD::UMIN); 382 setTargetDAGCombine(ISD::UMAX); 383 setTargetDAGCombine(ISD::SETCC); 384 setTargetDAGCombine(ISD::AND); 385 setTargetDAGCombine(ISD::OR); 386 setTargetDAGCombine(ISD::XOR); 387 setTargetDAGCombine(ISD::SINT_TO_FP); 388 setTargetDAGCombine(ISD::UINT_TO_FP); 389 setTargetDAGCombine(ISD::FCANONICALIZE); 390 391 // All memory operations. Some folding on the pointer operand is done to help 392 // matching the constant offsets in the addressing modes. 393 setTargetDAGCombine(ISD::LOAD); 394 setTargetDAGCombine(ISD::STORE); 395 setTargetDAGCombine(ISD::ATOMIC_LOAD); 396 setTargetDAGCombine(ISD::ATOMIC_STORE); 397 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 398 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 399 setTargetDAGCombine(ISD::ATOMIC_SWAP); 400 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 401 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 402 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 403 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 404 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 405 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 406 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 407 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 408 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 409 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 410 411 setSchedulingPreference(Sched::RegPressure); 412 } 413 414 const SISubtarget *SITargetLowering::getSubtarget() const { 415 return static_cast<const SISubtarget *>(Subtarget); 416 } 417 418 //===----------------------------------------------------------------------===// 419 // TargetLowering queries 420 //===----------------------------------------------------------------------===// 421 422 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 423 const CallInst &CI, 424 unsigned IntrID) const { 425 switch (IntrID) { 426 case Intrinsic::amdgcn_atomic_inc: 427 case Intrinsic::amdgcn_atomic_dec: 428 Info.opc = ISD::INTRINSIC_W_CHAIN; 429 Info.memVT = MVT::getVT(CI.getType()); 430 Info.ptrVal = CI.getOperand(0); 431 Info.align = 0; 432 Info.vol = false; 433 Info.readMem = true; 434 Info.writeMem = true; 435 return true; 436 default: 437 return false; 438 } 439 } 440 441 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &, 442 EVT) const { 443 // SI has some legal vector types, but no legal vector operations. Say no 444 // shuffles are legal in order to prefer scalarizing some vector operations. 445 return false; 446 } 447 448 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 449 // Flat instructions do not have offsets, and only have the register 450 // address. 451 return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1); 452 } 453 454 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 455 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 456 // additionally can do r + r + i with addr64. 32-bit has more addressing 457 // mode options. Depending on the resource constant, it can also do 458 // (i64 r0) + (i32 r1) * (i14 i). 459 // 460 // Private arrays end up using a scratch buffer most of the time, so also 461 // assume those use MUBUF instructions. Scratch loads / stores are currently 462 // implemented as mubuf instructions with offen bit set, so slightly 463 // different than the normal addr64. 464 if (!isUInt<12>(AM.BaseOffs)) 465 return false; 466 467 // FIXME: Since we can split immediate into soffset and immediate offset, 468 // would it make sense to allow any immediate? 469 470 switch (AM.Scale) { 471 case 0: // r + i or just i, depending on HasBaseReg. 472 return true; 473 case 1: 474 return true; // We have r + r or r + i. 475 case 2: 476 if (AM.HasBaseReg) { 477 // Reject 2 * r + r. 478 return false; 479 } 480 481 // Allow 2 * r as r + r 482 // Or 2 * r + i is allowed as r + r + i. 483 return true; 484 default: // Don't allow n * r 485 return false; 486 } 487 } 488 489 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 490 const AddrMode &AM, Type *Ty, 491 unsigned AS) const { 492 // No global is ever allowed as a base. 493 if (AM.BaseGV) 494 return false; 495 496 switch (AS) { 497 case AMDGPUAS::GLOBAL_ADDRESS: 498 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) { 499 // Assume the we will use FLAT for all global memory accesses 500 // on VI. 501 // FIXME: This assumption is currently wrong. On VI we still use 502 // MUBUF instructions for the r + i addressing mode. As currently 503 // implemented, the MUBUF instructions only work on buffer < 4GB. 504 // It may be possible to support > 4GB buffers with MUBUF instructions, 505 // by setting the stride value in the resource descriptor which would 506 // increase the size limit to (stride * 4GB). However, this is risky, 507 // because it has never been validated. 508 return isLegalFlatAddressingMode(AM); 509 } 510 511 return isLegalMUBUFAddressingMode(AM); 512 513 case AMDGPUAS::CONSTANT_ADDRESS: 514 // If the offset isn't a multiple of 4, it probably isn't going to be 515 // correctly aligned. 516 // FIXME: Can we get the real alignment here? 517 if (AM.BaseOffs % 4 != 0) 518 return isLegalMUBUFAddressingMode(AM); 519 520 // There are no SMRD extloads, so if we have to do a small type access we 521 // will use a MUBUF load. 522 // FIXME?: We also need to do this if unaligned, but we don't know the 523 // alignment here. 524 if (DL.getTypeStoreSize(Ty) < 4) 525 return isLegalMUBUFAddressingMode(AM); 526 527 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) { 528 // SMRD instructions have an 8-bit, dword offset on SI. 529 if (!isUInt<8>(AM.BaseOffs / 4)) 530 return false; 531 } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) { 532 // On CI+, this can also be a 32-bit literal constant offset. If it fits 533 // in 8-bits, it can use a smaller encoding. 534 if (!isUInt<32>(AM.BaseOffs / 4)) 535 return false; 536 } else if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) { 537 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 538 if (!isUInt<20>(AM.BaseOffs)) 539 return false; 540 } else 541 llvm_unreachable("unhandled generation"); 542 543 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 544 return true; 545 546 if (AM.Scale == 1 && AM.HasBaseReg) 547 return true; 548 549 return false; 550 551 case AMDGPUAS::PRIVATE_ADDRESS: 552 return isLegalMUBUFAddressingMode(AM); 553 554 case AMDGPUAS::LOCAL_ADDRESS: 555 case AMDGPUAS::REGION_ADDRESS: 556 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 557 // field. 558 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 559 // an 8-bit dword offset but we don't know the alignment here. 560 if (!isUInt<16>(AM.BaseOffs)) 561 return false; 562 563 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 564 return true; 565 566 if (AM.Scale == 1 && AM.HasBaseReg) 567 return true; 568 569 return false; 570 571 case AMDGPUAS::FLAT_ADDRESS: 572 case AMDGPUAS::UNKNOWN_ADDRESS_SPACE: 573 // For an unknown address space, this usually means that this is for some 574 // reason being used for pure arithmetic, and not based on some addressing 575 // computation. We don't have instructions that compute pointers with any 576 // addressing modes, so treat them as having no offset like flat 577 // instructions. 578 return isLegalFlatAddressingMode(AM); 579 580 default: 581 llvm_unreachable("unhandled address space"); 582 } 583 } 584 585 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 586 unsigned AddrSpace, 587 unsigned Align, 588 bool *IsFast) const { 589 if (IsFast) 590 *IsFast = false; 591 592 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 593 // which isn't a simple VT. 594 // Until MVT is extended to handle this, simply check for the size and 595 // rely on the condition below: allow accesses if the size is a multiple of 4. 596 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 597 VT.getStoreSize() > 16)) { 598 return false; 599 } 600 601 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 602 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 603 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 604 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 605 // with adjacent offsets. 606 bool AlignedBy4 = (Align % 4 == 0); 607 if (IsFast) 608 *IsFast = AlignedBy4; 609 610 return AlignedBy4; 611 } 612 613 // FIXME: We have to be conservative here and assume that flat operations 614 // will access scratch. If we had access to the IR function, then we 615 // could determine if any private memory was used in the function. 616 if (!Subtarget->hasUnalignedScratchAccess() && 617 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 618 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 619 return false; 620 } 621 622 if (Subtarget->hasUnalignedBufferAccess()) { 623 // If we have an uniform constant load, it still requires using a slow 624 // buffer instruction if unaligned. 625 if (IsFast) { 626 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS) ? 627 (Align % 4 == 0) : true; 628 } 629 630 return true; 631 } 632 633 // Smaller than dword value must be aligned. 634 if (VT.bitsLT(MVT::i32)) 635 return false; 636 637 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 638 // byte-address are ignored, thus forcing Dword alignment. 639 // This applies to private, global, and constant memory. 640 if (IsFast) 641 *IsFast = true; 642 643 return VT.bitsGT(MVT::i32) && Align % 4 == 0; 644 } 645 646 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign, 647 unsigned SrcAlign, bool IsMemset, 648 bool ZeroMemset, 649 bool MemcpyStrSrc, 650 MachineFunction &MF) const { 651 // FIXME: Should account for address space here. 652 653 // The default fallback uses the private pointer size as a guess for a type to 654 // use. Make sure we switch these to 64-bit accesses. 655 656 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global 657 return MVT::v4i32; 658 659 if (Size >= 8 && DstAlign >= 4) 660 return MVT::v2i32; 661 662 // Use the default. 663 return MVT::Other; 664 } 665 666 static bool isFlatGlobalAddrSpace(unsigned AS) { 667 return AS == AMDGPUAS::GLOBAL_ADDRESS || 668 AS == AMDGPUAS::FLAT_ADDRESS || 669 AS == AMDGPUAS::CONSTANT_ADDRESS; 670 } 671 672 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 673 unsigned DestAS) const { 674 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 675 } 676 677 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 678 const MemSDNode *MemNode = cast<MemSDNode>(N); 679 const Value *Ptr = MemNode->getMemOperand()->getValue(); 680 const Instruction *I = dyn_cast<Instruction>(Ptr); 681 return I && I->getMetadata("amdgpu.noclobber"); 682 } 683 684 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS, 685 unsigned DestAS) const { 686 // Flat -> private/local is a simple truncate. 687 // Flat -> global is no-op 688 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 689 return true; 690 691 return isNoopAddrSpaceCast(SrcAS, DestAS); 692 } 693 694 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 695 const MemSDNode *MemNode = cast<MemSDNode>(N); 696 697 return AMDGPU::isUniformMMO(MemNode->getMemOperand()); 698 } 699 700 TargetLoweringBase::LegalizeTypeAction 701 SITargetLowering::getPreferredVectorAction(EVT VT) const { 702 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16)) 703 return TypeSplitVector; 704 705 return TargetLoweringBase::getPreferredVectorAction(VT); 706 } 707 708 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 709 Type *Ty) const { 710 // FIXME: Could be smarter if called for vector constants. 711 return true; 712 } 713 714 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 715 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 716 switch (Op) { 717 case ISD::LOAD: 718 case ISD::STORE: 719 720 // These operations are done with 32-bit instructions anyway. 721 case ISD::AND: 722 case ISD::OR: 723 case ISD::XOR: 724 case ISD::SELECT: 725 // TODO: Extensions? 726 return true; 727 default: 728 return false; 729 } 730 } 731 732 // SimplifySetCC uses this function to determine whether or not it should 733 // create setcc with i1 operands. We don't have instructions for i1 setcc. 734 if (VT == MVT::i1 && Op == ISD::SETCC) 735 return false; 736 737 return TargetLowering::isTypeDesirableForOp(Op, VT); 738 } 739 740 SDValue SITargetLowering::LowerParameterPtr(SelectionDAG &DAG, 741 const SDLoc &SL, SDValue Chain, 742 unsigned Offset) const { 743 const DataLayout &DL = DAG.getDataLayout(); 744 MachineFunction &MF = DAG.getMachineFunction(); 745 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 746 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR); 747 748 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 749 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 750 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 751 MRI.getLiveInVirtReg(InputPtrReg), PtrVT); 752 return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr, 753 DAG.getConstant(Offset, SL, PtrVT)); 754 } 755 756 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT, 757 const SDLoc &SL, SDValue Chain, 758 unsigned Offset, bool Signed, 759 const ISD::InputArg *Arg) const { 760 const DataLayout &DL = DAG.getDataLayout(); 761 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 762 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 763 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 764 765 unsigned Align = DL.getABITypeAlignment(Ty); 766 767 SDValue Ptr = LowerParameterPtr(DAG, SL, Chain, Offset); 768 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 769 MachineMemOperand::MONonTemporal | 770 MachineMemOperand::MODereferenceable | 771 MachineMemOperand::MOInvariant); 772 773 SDValue Val = Load; 774 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 775 VT.bitsLT(MemVT)) { 776 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 777 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 778 } 779 780 if (MemVT.isFloatingPoint()) 781 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT); 782 else if (Signed) 783 Val = DAG.getSExtOrTrunc(Val, SL, VT); 784 else 785 Val = DAG.getZExtOrTrunc(Val, SL, VT); 786 787 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 788 } 789 790 SDValue SITargetLowering::LowerFormalArguments( 791 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 792 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 793 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 794 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 795 796 MachineFunction &MF = DAG.getMachineFunction(); 797 FunctionType *FType = MF.getFunction()->getFunctionType(); 798 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 799 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 800 801 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 802 const Function *Fn = MF.getFunction(); 803 DiagnosticInfoUnsupported NoGraphicsHSA( 804 *Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 805 DAG.getContext()->diagnose(NoGraphicsHSA); 806 return DAG.getEntryNode(); 807 } 808 809 // Create stack objects that are used for emitting debugger prologue if 810 // "amdgpu-debugger-emit-prologue" attribute was specified. 811 if (ST.debuggerEmitPrologue()) 812 createDebuggerPrologueStackObjects(MF); 813 814 SmallVector<ISD::InputArg, 16> Splits; 815 BitVector Skipped(Ins.size()); 816 817 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) { 818 const ISD::InputArg &Arg = Ins[i]; 819 820 // First check if it's a PS input addr 821 if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() && 822 !Arg.Flags.isByVal() && PSInputNum <= 15) { 823 824 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) { 825 // We can safely skip PS inputs 826 Skipped.set(i); 827 ++PSInputNum; 828 continue; 829 } 830 831 Info->markPSInputAllocated(PSInputNum); 832 if (Arg.Used) 833 Info->PSInputEna |= 1 << PSInputNum; 834 835 ++PSInputNum; 836 } 837 838 if (AMDGPU::isShader(CallConv)) { 839 // Second split vertices into their elements 840 if (Arg.VT.isVector()) { 841 ISD::InputArg NewArg = Arg; 842 NewArg.Flags.setSplit(); 843 NewArg.VT = Arg.VT.getVectorElementType(); 844 845 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a 846 // three or five element vertex only needs three or five registers, 847 // NOT four or eight. 848 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 849 unsigned NumElements = ParamType->getVectorNumElements(); 850 851 for (unsigned j = 0; j != NumElements; ++j) { 852 Splits.push_back(NewArg); 853 NewArg.PartOffset += NewArg.VT.getStoreSize(); 854 } 855 } else { 856 Splits.push_back(Arg); 857 } 858 } 859 } 860 861 SmallVector<CCValAssign, 16> ArgLocs; 862 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 863 *DAG.getContext()); 864 865 // At least one interpolation mode must be enabled or else the GPU will hang. 866 // 867 // Check PSInputAddr instead of PSInputEna. The idea is that if the user set 868 // PSInputAddr, the user wants to enable some bits after the compilation 869 // based on run-time states. Since we can't know what the final PSInputEna 870 // will look like, so we shouldn't do anything here and the user should take 871 // responsibility for the correct programming. 872 // 873 // Otherwise, the following restrictions apply: 874 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 875 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 876 // enabled too. 877 if (CallConv == CallingConv::AMDGPU_PS && 878 ((Info->getPSInputAddr() & 0x7F) == 0 || 879 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11)))) { 880 CCInfo.AllocateReg(AMDGPU::VGPR0); 881 CCInfo.AllocateReg(AMDGPU::VGPR1); 882 Info->markPSInputAllocated(0); 883 Info->PSInputEna |= 1; 884 } 885 886 if (!AMDGPU::isShader(CallConv)) { 887 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 888 } else { 889 assert(!Info->hasDispatchPtr() && 890 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 891 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 892 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 893 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 894 !Info->hasWorkItemIDZ()); 895 } 896 897 if (Info->hasPrivateMemoryInputPtr()) { 898 unsigned PrivateMemoryPtrReg = Info->addPrivateMemoryPtr(*TRI); 899 MF.addLiveIn(PrivateMemoryPtrReg, &AMDGPU::SReg_64RegClass); 900 CCInfo.AllocateReg(PrivateMemoryPtrReg); 901 } 902 903 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 904 if (Info->hasPrivateSegmentBuffer()) { 905 unsigned PrivateSegmentBufferReg = Info->addPrivateSegmentBuffer(*TRI); 906 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SReg_128RegClass); 907 CCInfo.AllocateReg(PrivateSegmentBufferReg); 908 } 909 910 if (Info->hasDispatchPtr()) { 911 unsigned DispatchPtrReg = Info->addDispatchPtr(*TRI); 912 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 913 CCInfo.AllocateReg(DispatchPtrReg); 914 } 915 916 if (Info->hasQueuePtr()) { 917 unsigned QueuePtrReg = Info->addQueuePtr(*TRI); 918 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 919 CCInfo.AllocateReg(QueuePtrReg); 920 } 921 922 if (Info->hasKernargSegmentPtr()) { 923 unsigned InputPtrReg = Info->addKernargSegmentPtr(*TRI); 924 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 925 CCInfo.AllocateReg(InputPtrReg); 926 } 927 928 if (Info->hasDispatchID()) { 929 unsigned DispatchIDReg = Info->addDispatchID(*TRI); 930 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 931 CCInfo.AllocateReg(DispatchIDReg); 932 } 933 934 if (Info->hasFlatScratchInit()) { 935 unsigned FlatScratchInitReg = Info->addFlatScratchInit(*TRI); 936 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 937 CCInfo.AllocateReg(FlatScratchInitReg); 938 } 939 940 if (!AMDGPU::isShader(CallConv)) 941 analyzeFormalArgumentsCompute(CCInfo, Ins); 942 else 943 AnalyzeFormalArguments(CCInfo, Splits); 944 945 SmallVector<SDValue, 16> Chains; 946 947 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 948 const ISD::InputArg &Arg = Ins[i]; 949 if (Skipped[i]) { 950 InVals.push_back(DAG.getUNDEF(Arg.VT)); 951 continue; 952 } 953 954 CCValAssign &VA = ArgLocs[ArgIdx++]; 955 MVT VT = VA.getLocVT(); 956 957 if (VA.isMemLoc()) { 958 VT = Ins[i].VT; 959 EVT MemVT = VA.getLocVT(); 960 const unsigned Offset = Subtarget->getExplicitKernelArgOffset(MF) + 961 VA.getLocMemOffset(); 962 // The first 36 bytes of the input buffer contains information about 963 // thread group and global sizes. 964 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, Chain, 965 Offset, Ins[i].Flags.isSExt(), 966 &Ins[i]); 967 Chains.push_back(Arg.getValue(1)); 968 969 auto *ParamTy = 970 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 971 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS && 972 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 973 // On SI local pointers are just offsets into LDS, so they are always 974 // less than 16-bits. On CI and newer they could potentially be 975 // real pointers, so we can't guarantee their size. 976 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 977 DAG.getValueType(MVT::i16)); 978 } 979 980 InVals.push_back(Arg); 981 Info->setABIArgOffset(Offset + MemVT.getStoreSize()); 982 continue; 983 } 984 assert(VA.isRegLoc() && "Parameter must be in a register!"); 985 986 unsigned Reg = VA.getLocReg(); 987 988 if (VT == MVT::i64) { 989 // For now assume it is a pointer 990 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, 991 &AMDGPU::SGPR_64RegClass); 992 Reg = MF.addLiveIn(Reg, &AMDGPU::SGPR_64RegClass); 993 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT); 994 InVals.push_back(Copy); 995 continue; 996 } 997 998 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 999 1000 Reg = MF.addLiveIn(Reg, RC); 1001 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 1002 1003 if (Arg.VT.isVector()) { 1004 // Build a vector from the registers 1005 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 1006 unsigned NumElements = ParamType->getVectorNumElements(); 1007 1008 SmallVector<SDValue, 4> Regs; 1009 Regs.push_back(Val); 1010 for (unsigned j = 1; j != NumElements; ++j) { 1011 Reg = ArgLocs[ArgIdx++].getLocReg(); 1012 Reg = MF.addLiveIn(Reg, RC); 1013 1014 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT); 1015 Regs.push_back(Copy); 1016 } 1017 1018 // Fill up the missing vector elements 1019 NumElements = Arg.VT.getVectorNumElements() - NumElements; 1020 Regs.append(NumElements, DAG.getUNDEF(VT)); 1021 1022 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs)); 1023 continue; 1024 } 1025 1026 InVals.push_back(Val); 1027 } 1028 1029 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1030 // these from the dispatch pointer. 1031 1032 // Start adding system SGPRs. 1033 if (Info->hasWorkGroupIDX()) { 1034 unsigned Reg = Info->addWorkGroupIDX(); 1035 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1036 CCInfo.AllocateReg(Reg); 1037 } 1038 1039 if (Info->hasWorkGroupIDY()) { 1040 unsigned Reg = Info->addWorkGroupIDY(); 1041 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1042 CCInfo.AllocateReg(Reg); 1043 } 1044 1045 if (Info->hasWorkGroupIDZ()) { 1046 unsigned Reg = Info->addWorkGroupIDZ(); 1047 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1048 CCInfo.AllocateReg(Reg); 1049 } 1050 1051 if (Info->hasWorkGroupInfo()) { 1052 unsigned Reg = Info->addWorkGroupInfo(); 1053 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1054 CCInfo.AllocateReg(Reg); 1055 } 1056 1057 if (Info->hasPrivateSegmentWaveByteOffset()) { 1058 // Scratch wave offset passed in system SGPR. 1059 unsigned PrivateSegmentWaveByteOffsetReg; 1060 1061 if (AMDGPU::isShader(CallConv)) { 1062 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1063 Info->setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1064 } else 1065 PrivateSegmentWaveByteOffsetReg = Info->addPrivateSegmentWaveByteOffset(); 1066 1067 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1068 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1069 } 1070 1071 // Now that we've figured out where the scratch register inputs are, see if 1072 // should reserve the arguments and use them directly. 1073 bool HasStackObjects = MF.getFrameInfo().hasStackObjects(); 1074 // Record that we know we have non-spill stack objects so we don't need to 1075 // check all stack objects later. 1076 if (HasStackObjects) 1077 Info->setHasNonSpillStackObjects(true); 1078 1079 // Everything live out of a block is spilled with fast regalloc, so it's 1080 // almost certain that spilling will be required. 1081 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 1082 HasStackObjects = true; 1083 1084 if (ST.isAmdCodeObjectV2(MF)) { 1085 if (HasStackObjects) { 1086 // If we have stack objects, we unquestionably need the private buffer 1087 // resource. For the Code Object V2 ABI, this will be the first 4 user 1088 // SGPR inputs. We can reserve those and use them directly. 1089 1090 unsigned PrivateSegmentBufferReg = TRI->getPreloadedValue( 1091 MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER); 1092 Info->setScratchRSrcReg(PrivateSegmentBufferReg); 1093 1094 unsigned PrivateSegmentWaveByteOffsetReg = TRI->getPreloadedValue( 1095 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1096 Info->setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg); 1097 } else { 1098 unsigned ReservedBufferReg 1099 = TRI->reservedPrivateSegmentBufferReg(MF); 1100 unsigned ReservedOffsetReg 1101 = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF); 1102 1103 // We tentatively reserve the last registers (skipping the last two 1104 // which may contain VCC). After register allocation, we'll replace 1105 // these with the ones immediately after those which were really 1106 // allocated. In the prologue copies will be inserted from the argument 1107 // to these reserved registers. 1108 Info->setScratchRSrcReg(ReservedBufferReg); 1109 Info->setScratchWaveOffsetReg(ReservedOffsetReg); 1110 } 1111 } else { 1112 unsigned ReservedBufferReg = TRI->reservedPrivateSegmentBufferReg(MF); 1113 1114 // Without HSA, relocations are used for the scratch pointer and the 1115 // buffer resource setup is always inserted in the prologue. Scratch wave 1116 // offset is still in an input SGPR. 1117 Info->setScratchRSrcReg(ReservedBufferReg); 1118 1119 if (HasStackObjects) { 1120 unsigned ScratchWaveOffsetReg = TRI->getPreloadedValue( 1121 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1122 Info->setScratchWaveOffsetReg(ScratchWaveOffsetReg); 1123 } else { 1124 unsigned ReservedOffsetReg 1125 = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF); 1126 Info->setScratchWaveOffsetReg(ReservedOffsetReg); 1127 } 1128 } 1129 1130 if (Info->hasWorkItemIDX()) { 1131 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X); 1132 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1133 CCInfo.AllocateReg(Reg); 1134 } 1135 1136 if (Info->hasWorkItemIDY()) { 1137 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y); 1138 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1139 CCInfo.AllocateReg(Reg); 1140 } 1141 1142 if (Info->hasWorkItemIDZ()) { 1143 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z); 1144 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1145 CCInfo.AllocateReg(Reg); 1146 } 1147 1148 if (Chains.empty()) 1149 return Chain; 1150 1151 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 1152 } 1153 1154 SDValue 1155 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 1156 bool isVarArg, 1157 const SmallVectorImpl<ISD::OutputArg> &Outs, 1158 const SmallVectorImpl<SDValue> &OutVals, 1159 const SDLoc &DL, SelectionDAG &DAG) const { 1160 MachineFunction &MF = DAG.getMachineFunction(); 1161 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1162 1163 if (!AMDGPU::isShader(CallConv)) 1164 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 1165 OutVals, DL, DAG); 1166 1167 Info->setIfReturnsVoid(Outs.size() == 0); 1168 1169 SmallVector<ISD::OutputArg, 48> Splits; 1170 SmallVector<SDValue, 48> SplitVals; 1171 1172 // Split vectors into their elements. 1173 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 1174 const ISD::OutputArg &Out = Outs[i]; 1175 1176 if (Out.VT.isVector()) { 1177 MVT VT = Out.VT.getVectorElementType(); 1178 ISD::OutputArg NewOut = Out; 1179 NewOut.Flags.setSplit(); 1180 NewOut.VT = VT; 1181 1182 // We want the original number of vector elements here, e.g. 1183 // three or five, not four or eight. 1184 unsigned NumElements = Out.ArgVT.getVectorNumElements(); 1185 1186 for (unsigned j = 0; j != NumElements; ++j) { 1187 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i], 1188 DAG.getConstant(j, DL, MVT::i32)); 1189 SplitVals.push_back(Elem); 1190 Splits.push_back(NewOut); 1191 NewOut.PartOffset += NewOut.VT.getStoreSize(); 1192 } 1193 } else { 1194 SplitVals.push_back(OutVals[i]); 1195 Splits.push_back(Out); 1196 } 1197 } 1198 1199 // CCValAssign - represent the assignment of the return value to a location. 1200 SmallVector<CCValAssign, 48> RVLocs; 1201 1202 // CCState - Info about the registers and stack slots. 1203 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1204 *DAG.getContext()); 1205 1206 // Analyze outgoing return values. 1207 AnalyzeReturn(CCInfo, Splits); 1208 1209 SDValue Flag; 1210 SmallVector<SDValue, 48> RetOps; 1211 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 1212 1213 // Copy the result values into the output registers. 1214 for (unsigned i = 0, realRVLocIdx = 0; 1215 i != RVLocs.size(); 1216 ++i, ++realRVLocIdx) { 1217 CCValAssign &VA = RVLocs[i]; 1218 assert(VA.isRegLoc() && "Can only return in registers!"); 1219 1220 SDValue Arg = SplitVals[realRVLocIdx]; 1221 1222 // Copied from other backends. 1223 switch (VA.getLocInfo()) { 1224 default: llvm_unreachable("Unknown loc info!"); 1225 case CCValAssign::Full: 1226 break; 1227 case CCValAssign::BCvt: 1228 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 1229 break; 1230 } 1231 1232 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 1233 Flag = Chain.getValue(1); 1234 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 1235 } 1236 1237 // Update chain and glue. 1238 RetOps[0] = Chain; 1239 if (Flag.getNode()) 1240 RetOps.push_back(Flag); 1241 1242 unsigned Opc = Info->returnsVoid() ? AMDGPUISD::ENDPGM : AMDGPUISD::RETURN; 1243 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 1244 } 1245 1246 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT, 1247 SelectionDAG &DAG) const { 1248 unsigned Reg = StringSwitch<unsigned>(RegName) 1249 .Case("m0", AMDGPU::M0) 1250 .Case("exec", AMDGPU::EXEC) 1251 .Case("exec_lo", AMDGPU::EXEC_LO) 1252 .Case("exec_hi", AMDGPU::EXEC_HI) 1253 .Case("flat_scratch", AMDGPU::FLAT_SCR) 1254 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 1255 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 1256 .Default(AMDGPU::NoRegister); 1257 1258 if (Reg == AMDGPU::NoRegister) { 1259 report_fatal_error(Twine("invalid register name \"" 1260 + StringRef(RegName) + "\".")); 1261 1262 } 1263 1264 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS && 1265 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 1266 report_fatal_error(Twine("invalid register \"" 1267 + StringRef(RegName) + "\" for subtarget.")); 1268 } 1269 1270 switch (Reg) { 1271 case AMDGPU::M0: 1272 case AMDGPU::EXEC_LO: 1273 case AMDGPU::EXEC_HI: 1274 case AMDGPU::FLAT_SCR_LO: 1275 case AMDGPU::FLAT_SCR_HI: 1276 if (VT.getSizeInBits() == 32) 1277 return Reg; 1278 break; 1279 case AMDGPU::EXEC: 1280 case AMDGPU::FLAT_SCR: 1281 if (VT.getSizeInBits() == 64) 1282 return Reg; 1283 break; 1284 default: 1285 llvm_unreachable("missing register type checking"); 1286 } 1287 1288 report_fatal_error(Twine("invalid type for register \"" 1289 + StringRef(RegName) + "\".")); 1290 } 1291 1292 // If kill is not the last instruction, split the block so kill is always a 1293 // proper terminator. 1294 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 1295 MachineBasicBlock *BB) const { 1296 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 1297 1298 MachineBasicBlock::iterator SplitPoint(&MI); 1299 ++SplitPoint; 1300 1301 if (SplitPoint == BB->end()) { 1302 // Don't bother with a new block. 1303 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR)); 1304 return BB; 1305 } 1306 1307 MachineFunction *MF = BB->getParent(); 1308 MachineBasicBlock *SplitBB 1309 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 1310 1311 MF->insert(++MachineFunction::iterator(BB), SplitBB); 1312 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 1313 1314 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 1315 BB->addSuccessor(SplitBB); 1316 1317 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR)); 1318 return SplitBB; 1319 } 1320 1321 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 1322 // wavefront. If the value is uniform and just happens to be in a VGPR, this 1323 // will only do one iteration. In the worst case, this will loop 64 times. 1324 // 1325 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 1326 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 1327 const SIInstrInfo *TII, 1328 MachineRegisterInfo &MRI, 1329 MachineBasicBlock &OrigBB, 1330 MachineBasicBlock &LoopBB, 1331 const DebugLoc &DL, 1332 const MachineOperand &IdxReg, 1333 unsigned InitReg, 1334 unsigned ResultReg, 1335 unsigned PhiReg, 1336 unsigned InitSaveExecReg, 1337 int Offset, 1338 bool UseGPRIdxMode) { 1339 MachineBasicBlock::iterator I = LoopBB.begin(); 1340 1341 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 1342 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 1343 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 1344 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 1345 1346 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 1347 .addReg(InitReg) 1348 .addMBB(&OrigBB) 1349 .addReg(ResultReg) 1350 .addMBB(&LoopBB); 1351 1352 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 1353 .addReg(InitSaveExecReg) 1354 .addMBB(&OrigBB) 1355 .addReg(NewExec) 1356 .addMBB(&LoopBB); 1357 1358 // Read the next variant <- also loop target. 1359 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 1360 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 1361 1362 // Compare the just read M0 value to all possible Idx values. 1363 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 1364 .addReg(CurrentIdxReg) 1365 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 1366 1367 if (UseGPRIdxMode) { 1368 unsigned IdxReg; 1369 if (Offset == 0) { 1370 IdxReg = CurrentIdxReg; 1371 } else { 1372 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 1373 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 1374 .addReg(CurrentIdxReg, RegState::Kill) 1375 .addImm(Offset); 1376 } 1377 1378 MachineInstr *SetIdx = 1379 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_IDX)) 1380 .addReg(IdxReg, RegState::Kill); 1381 SetIdx->getOperand(2).setIsUndef(); 1382 } else { 1383 // Move index from VCC into M0 1384 if (Offset == 0) { 1385 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 1386 .addReg(CurrentIdxReg, RegState::Kill); 1387 } else { 1388 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 1389 .addReg(CurrentIdxReg, RegState::Kill) 1390 .addImm(Offset); 1391 } 1392 } 1393 1394 // Update EXEC, save the original EXEC value to VCC. 1395 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec) 1396 .addReg(CondReg, RegState::Kill); 1397 1398 MRI.setSimpleHint(NewExec, CondReg); 1399 1400 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 1401 MachineInstr *InsertPt = 1402 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC) 1403 .addReg(AMDGPU::EXEC) 1404 .addReg(NewExec); 1405 1406 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 1407 // s_cbranch_scc0? 1408 1409 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 1410 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 1411 .addMBB(&LoopBB); 1412 1413 return InsertPt->getIterator(); 1414 } 1415 1416 // This has slightly sub-optimal regalloc when the source vector is killed by 1417 // the read. The register allocator does not understand that the kill is 1418 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 1419 // subregister from it, using 1 more VGPR than necessary. This was saved when 1420 // this was expanded after register allocation. 1421 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 1422 MachineBasicBlock &MBB, 1423 MachineInstr &MI, 1424 unsigned InitResultReg, 1425 unsigned PhiReg, 1426 int Offset, 1427 bool UseGPRIdxMode) { 1428 MachineFunction *MF = MBB.getParent(); 1429 MachineRegisterInfo &MRI = MF->getRegInfo(); 1430 const DebugLoc &DL = MI.getDebugLoc(); 1431 MachineBasicBlock::iterator I(&MI); 1432 1433 unsigned DstReg = MI.getOperand(0).getReg(); 1434 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 1435 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 1436 1437 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 1438 1439 // Save the EXEC mask 1440 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec) 1441 .addReg(AMDGPU::EXEC); 1442 1443 // To insert the loop we need to split the block. Move everything after this 1444 // point to a new block, and insert a new empty block between the two. 1445 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 1446 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 1447 MachineFunction::iterator MBBI(MBB); 1448 ++MBBI; 1449 1450 MF->insert(MBBI, LoopBB); 1451 MF->insert(MBBI, RemainderBB); 1452 1453 LoopBB->addSuccessor(LoopBB); 1454 LoopBB->addSuccessor(RemainderBB); 1455 1456 // Move the rest of the block into a new block. 1457 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 1458 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 1459 1460 MBB.addSuccessor(LoopBB); 1461 1462 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 1463 1464 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 1465 InitResultReg, DstReg, PhiReg, TmpExec, 1466 Offset, UseGPRIdxMode); 1467 1468 MachineBasicBlock::iterator First = RemainderBB->begin(); 1469 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC) 1470 .addReg(SaveExec); 1471 1472 return InsPt; 1473 } 1474 1475 // Returns subreg index, offset 1476 static std::pair<unsigned, int> 1477 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 1478 const TargetRegisterClass *SuperRC, 1479 unsigned VecReg, 1480 int Offset) { 1481 int NumElts = SuperRC->getSize() / 4; 1482 1483 // Skip out of bounds offsets, or else we would end up using an undefined 1484 // register. 1485 if (Offset >= NumElts || Offset < 0) 1486 return std::make_pair(AMDGPU::sub0, Offset); 1487 1488 return std::make_pair(AMDGPU::sub0 + Offset, 0); 1489 } 1490 1491 // Return true if the index is an SGPR and was set. 1492 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 1493 MachineRegisterInfo &MRI, 1494 MachineInstr &MI, 1495 int Offset, 1496 bool UseGPRIdxMode, 1497 bool IsIndirectSrc) { 1498 MachineBasicBlock *MBB = MI.getParent(); 1499 const DebugLoc &DL = MI.getDebugLoc(); 1500 MachineBasicBlock::iterator I(&MI); 1501 1502 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 1503 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 1504 1505 assert(Idx->getReg() != AMDGPU::NoRegister); 1506 1507 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 1508 return false; 1509 1510 if (UseGPRIdxMode) { 1511 unsigned IdxMode = IsIndirectSrc ? 1512 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE; 1513 if (Offset == 0) { 1514 MachineInstr *SetOn = 1515 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 1516 .add(*Idx) 1517 .addImm(IdxMode); 1518 1519 SetOn->getOperand(3).setIsUndef(); 1520 } else { 1521 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 1522 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 1523 .add(*Idx) 1524 .addImm(Offset); 1525 MachineInstr *SetOn = 1526 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 1527 .addReg(Tmp, RegState::Kill) 1528 .addImm(IdxMode); 1529 1530 SetOn->getOperand(3).setIsUndef(); 1531 } 1532 1533 return true; 1534 } 1535 1536 if (Offset == 0) { 1537 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 1538 .add(*Idx); 1539 } else { 1540 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 1541 .add(*Idx) 1542 .addImm(Offset); 1543 } 1544 1545 return true; 1546 } 1547 1548 // Control flow needs to be inserted if indexing with a VGPR. 1549 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 1550 MachineBasicBlock &MBB, 1551 const SISubtarget &ST) { 1552 const SIInstrInfo *TII = ST.getInstrInfo(); 1553 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 1554 MachineFunction *MF = MBB.getParent(); 1555 MachineRegisterInfo &MRI = MF->getRegInfo(); 1556 1557 unsigned Dst = MI.getOperand(0).getReg(); 1558 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 1559 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 1560 1561 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 1562 1563 unsigned SubReg; 1564 std::tie(SubReg, Offset) 1565 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 1566 1567 bool UseGPRIdxMode = ST.hasVGPRIndexMode() && EnableVGPRIndexMode; 1568 1569 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 1570 MachineBasicBlock::iterator I(&MI); 1571 const DebugLoc &DL = MI.getDebugLoc(); 1572 1573 if (UseGPRIdxMode) { 1574 // TODO: Look at the uses to avoid the copy. This may require rescheduling 1575 // to avoid interfering with other uses, so probably requires a new 1576 // optimization pass. 1577 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 1578 .addReg(SrcReg, RegState::Undef, SubReg) 1579 .addReg(SrcReg, RegState::Implicit) 1580 .addReg(AMDGPU::M0, RegState::Implicit); 1581 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 1582 } else { 1583 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 1584 .addReg(SrcReg, RegState::Undef, SubReg) 1585 .addReg(SrcReg, RegState::Implicit); 1586 } 1587 1588 MI.eraseFromParent(); 1589 1590 return &MBB; 1591 } 1592 1593 const DebugLoc &DL = MI.getDebugLoc(); 1594 MachineBasicBlock::iterator I(&MI); 1595 1596 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 1597 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 1598 1599 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 1600 1601 if (UseGPRIdxMode) { 1602 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 1603 .addImm(0) // Reset inside loop. 1604 .addImm(VGPRIndexMode::SRC0_ENABLE); 1605 SetOn->getOperand(3).setIsUndef(); 1606 1607 // Disable again after the loop. 1608 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 1609 } 1610 1611 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, UseGPRIdxMode); 1612 MachineBasicBlock *LoopBB = InsPt->getParent(); 1613 1614 if (UseGPRIdxMode) { 1615 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 1616 .addReg(SrcReg, RegState::Undef, SubReg) 1617 .addReg(SrcReg, RegState::Implicit) 1618 .addReg(AMDGPU::M0, RegState::Implicit); 1619 } else { 1620 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 1621 .addReg(SrcReg, RegState::Undef, SubReg) 1622 .addReg(SrcReg, RegState::Implicit); 1623 } 1624 1625 MI.eraseFromParent(); 1626 1627 return LoopBB; 1628 } 1629 1630 static unsigned getMOVRELDPseudo(const TargetRegisterClass *VecRC) { 1631 switch (VecRC->getSize()) { 1632 case 4: 1633 return AMDGPU::V_MOVRELD_B32_V1; 1634 case 8: 1635 return AMDGPU::V_MOVRELD_B32_V2; 1636 case 16: 1637 return AMDGPU::V_MOVRELD_B32_V4; 1638 case 32: 1639 return AMDGPU::V_MOVRELD_B32_V8; 1640 case 64: 1641 return AMDGPU::V_MOVRELD_B32_V16; 1642 default: 1643 llvm_unreachable("unsupported size for MOVRELD pseudos"); 1644 } 1645 } 1646 1647 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 1648 MachineBasicBlock &MBB, 1649 const SISubtarget &ST) { 1650 const SIInstrInfo *TII = ST.getInstrInfo(); 1651 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 1652 MachineFunction *MF = MBB.getParent(); 1653 MachineRegisterInfo &MRI = MF->getRegInfo(); 1654 1655 unsigned Dst = MI.getOperand(0).getReg(); 1656 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 1657 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 1658 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 1659 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 1660 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 1661 1662 // This can be an immediate, but will be folded later. 1663 assert(Val->getReg()); 1664 1665 unsigned SubReg; 1666 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 1667 SrcVec->getReg(), 1668 Offset); 1669 bool UseGPRIdxMode = ST.hasVGPRIndexMode() && EnableVGPRIndexMode; 1670 1671 if (Idx->getReg() == AMDGPU::NoRegister) { 1672 MachineBasicBlock::iterator I(&MI); 1673 const DebugLoc &DL = MI.getDebugLoc(); 1674 1675 assert(Offset == 0); 1676 1677 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 1678 .add(*SrcVec) 1679 .add(*Val) 1680 .addImm(SubReg); 1681 1682 MI.eraseFromParent(); 1683 return &MBB; 1684 } 1685 1686 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 1687 MachineBasicBlock::iterator I(&MI); 1688 const DebugLoc &DL = MI.getDebugLoc(); 1689 1690 if (UseGPRIdxMode) { 1691 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 1692 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst 1693 .add(*Val) 1694 .addReg(Dst, RegState::ImplicitDefine) 1695 .addReg(SrcVec->getReg(), RegState::Implicit) 1696 .addReg(AMDGPU::M0, RegState::Implicit); 1697 1698 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 1699 } else { 1700 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(VecRC)); 1701 1702 BuildMI(MBB, I, DL, MovRelDesc) 1703 .addReg(Dst, RegState::Define) 1704 .addReg(SrcVec->getReg()) 1705 .add(*Val) 1706 .addImm(SubReg - AMDGPU::sub0); 1707 } 1708 1709 MI.eraseFromParent(); 1710 return &MBB; 1711 } 1712 1713 if (Val->isReg()) 1714 MRI.clearKillFlags(Val->getReg()); 1715 1716 const DebugLoc &DL = MI.getDebugLoc(); 1717 1718 if (UseGPRIdxMode) { 1719 MachineBasicBlock::iterator I(&MI); 1720 1721 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 1722 .addImm(0) // Reset inside loop. 1723 .addImm(VGPRIndexMode::DST_ENABLE); 1724 SetOn->getOperand(3).setIsUndef(); 1725 1726 // Disable again after the loop. 1727 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 1728 } 1729 1730 unsigned PhiReg = MRI.createVirtualRegister(VecRC); 1731 1732 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 1733 Offset, UseGPRIdxMode); 1734 MachineBasicBlock *LoopBB = InsPt->getParent(); 1735 1736 if (UseGPRIdxMode) { 1737 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 1738 .addReg(PhiReg, RegState::Undef, SubReg) // vdst 1739 .add(*Val) // src0 1740 .addReg(Dst, RegState::ImplicitDefine) 1741 .addReg(PhiReg, RegState::Implicit) 1742 .addReg(AMDGPU::M0, RegState::Implicit); 1743 } else { 1744 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(VecRC)); 1745 1746 BuildMI(*LoopBB, InsPt, DL, MovRelDesc) 1747 .addReg(Dst, RegState::Define) 1748 .addReg(PhiReg) 1749 .add(*Val) 1750 .addImm(SubReg - AMDGPU::sub0); 1751 } 1752 1753 MI.eraseFromParent(); 1754 1755 return LoopBB; 1756 } 1757 1758 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 1759 MachineInstr &MI, MachineBasicBlock *BB) const { 1760 1761 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 1762 MachineFunction *MF = BB->getParent(); 1763 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 1764 1765 if (TII->isMIMG(MI)) { 1766 if (!MI.memoperands_empty()) 1767 return BB; 1768 // Add a memoperand for mimg instructions so that they aren't assumed to 1769 // be ordered memory instuctions. 1770 1771 MachinePointerInfo PtrInfo(MFI->getImagePSV()); 1772 MachineMemOperand::Flags Flags = MachineMemOperand::MODereferenceable; 1773 if (MI.mayStore()) 1774 Flags |= MachineMemOperand::MOStore; 1775 1776 if (MI.mayLoad()) 1777 Flags |= MachineMemOperand::MOLoad; 1778 1779 auto MMO = MF->getMachineMemOperand(PtrInfo, Flags, 0, 0); 1780 MI.addMemOperand(*MF, MMO); 1781 return BB; 1782 } 1783 1784 switch (MI.getOpcode()) { 1785 case AMDGPU::S_TRAP_PSEUDO: { 1786 const DebugLoc &DL = MI.getDebugLoc(); 1787 const int TrapType = MI.getOperand(0).getImm(); 1788 1789 if (Subtarget->getTrapHandlerAbi() == SISubtarget::TrapHandlerAbiHsa && 1790 Subtarget->isTrapHandlerEnabled()) { 1791 1792 MachineFunction *MF = BB->getParent(); 1793 SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 1794 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 1795 assert(UserSGPR != AMDGPU::NoRegister); 1796 1797 if (!BB->isLiveIn(UserSGPR)) 1798 BB->addLiveIn(UserSGPR); 1799 1800 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), AMDGPU::SGPR0_SGPR1) 1801 .addReg(UserSGPR); 1802 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_TRAP)) 1803 .addImm(TrapType) 1804 .addReg(AMDGPU::SGPR0_SGPR1, RegState::Implicit); 1805 } else { 1806 switch (TrapType) { 1807 case SISubtarget::TrapIDLLVMTrap: 1808 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_ENDPGM)); 1809 break; 1810 case SISubtarget::TrapIDLLVMDebugTrap: { 1811 DiagnosticInfoUnsupported NoTrap(*MF->getFunction(), 1812 "debugtrap handler not supported", 1813 DL, 1814 DS_Warning); 1815 LLVMContext &C = MF->getFunction()->getContext(); 1816 C.diagnose(NoTrap); 1817 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_NOP)) 1818 .addImm(0); 1819 break; 1820 } 1821 default: 1822 llvm_unreachable("unsupported trap handler type!"); 1823 } 1824 } 1825 1826 MI.eraseFromParent(); 1827 return BB; 1828 } 1829 case AMDGPU::SI_INIT_M0: 1830 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 1831 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 1832 .add(MI.getOperand(0)); 1833 MI.eraseFromParent(); 1834 return BB; 1835 1836 case AMDGPU::GET_GROUPSTATICSIZE: { 1837 DebugLoc DL = MI.getDebugLoc(); 1838 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 1839 .add(MI.getOperand(0)) 1840 .addImm(MFI->getLDSSize()); 1841 MI.eraseFromParent(); 1842 return BB; 1843 } 1844 case AMDGPU::SI_INDIRECT_SRC_V1: 1845 case AMDGPU::SI_INDIRECT_SRC_V2: 1846 case AMDGPU::SI_INDIRECT_SRC_V4: 1847 case AMDGPU::SI_INDIRECT_SRC_V8: 1848 case AMDGPU::SI_INDIRECT_SRC_V16: 1849 return emitIndirectSrc(MI, *BB, *getSubtarget()); 1850 case AMDGPU::SI_INDIRECT_DST_V1: 1851 case AMDGPU::SI_INDIRECT_DST_V2: 1852 case AMDGPU::SI_INDIRECT_DST_V4: 1853 case AMDGPU::SI_INDIRECT_DST_V8: 1854 case AMDGPU::SI_INDIRECT_DST_V16: 1855 return emitIndirectDst(MI, *BB, *getSubtarget()); 1856 case AMDGPU::SI_KILL: 1857 return splitKillBlock(MI, BB); 1858 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 1859 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 1860 1861 unsigned Dst = MI.getOperand(0).getReg(); 1862 unsigned Src0 = MI.getOperand(1).getReg(); 1863 unsigned Src1 = MI.getOperand(2).getReg(); 1864 const DebugLoc &DL = MI.getDebugLoc(); 1865 unsigned SrcCond = MI.getOperand(3).getReg(); 1866 1867 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 1868 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 1869 1870 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 1871 .addReg(Src0, 0, AMDGPU::sub0) 1872 .addReg(Src1, 0, AMDGPU::sub0) 1873 .addReg(SrcCond); 1874 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 1875 .addReg(Src0, 0, AMDGPU::sub1) 1876 .addReg(Src1, 0, AMDGPU::sub1) 1877 .addReg(SrcCond); 1878 1879 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 1880 .addReg(DstLo) 1881 .addImm(AMDGPU::sub0) 1882 .addReg(DstHi) 1883 .addImm(AMDGPU::sub1); 1884 MI.eraseFromParent(); 1885 return BB; 1886 } 1887 case AMDGPU::SI_BR_UNDEF: { 1888 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 1889 const DebugLoc &DL = MI.getDebugLoc(); 1890 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 1891 .add(MI.getOperand(0)); 1892 Br->getOperand(1).setIsUndef(true); // read undef SCC 1893 MI.eraseFromParent(); 1894 return BB; 1895 } 1896 default: 1897 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 1898 } 1899 } 1900 1901 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1902 // This currently forces unfolding various combinations of fsub into fma with 1903 // free fneg'd operands. As long as we have fast FMA (controlled by 1904 // isFMAFasterThanFMulAndFAdd), we should perform these. 1905 1906 // When fma is quarter rate, for f64 where add / sub are at best half rate, 1907 // most of these combines appear to be cycle neutral but save on instruction 1908 // count / code size. 1909 return true; 1910 } 1911 1912 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 1913 EVT VT) const { 1914 if (!VT.isVector()) { 1915 return MVT::i1; 1916 } 1917 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 1918 } 1919 1920 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 1921 // TODO: Should i16 be used always if legal? For now it would force VALU 1922 // shifts. 1923 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 1924 } 1925 1926 // Answering this is somewhat tricky and depends on the specific device which 1927 // have different rates for fma or all f64 operations. 1928 // 1929 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 1930 // regardless of which device (although the number of cycles differs between 1931 // devices), so it is always profitable for f64. 1932 // 1933 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 1934 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 1935 // which we can always do even without fused FP ops since it returns the same 1936 // result as the separate operations and since it is always full 1937 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 1938 // however does not support denormals, so we do report fma as faster if we have 1939 // a fast fma device and require denormals. 1940 // 1941 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 1942 VT = VT.getScalarType(); 1943 1944 switch (VT.getSimpleVT().SimpleTy) { 1945 case MVT::f32: 1946 // This is as fast on some subtargets. However, we always have full rate f32 1947 // mad available which returns the same result as the separate operations 1948 // which we should prefer over fma. We can't use this if we want to support 1949 // denormals, so only report this in these cases. 1950 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32(); 1951 case MVT::f64: 1952 return true; 1953 case MVT::f16: 1954 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals(); 1955 default: 1956 break; 1957 } 1958 1959 return false; 1960 } 1961 1962 //===----------------------------------------------------------------------===// 1963 // Custom DAG Lowering Operations 1964 //===----------------------------------------------------------------------===// 1965 1966 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 1967 switch (Op.getOpcode()) { 1968 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 1969 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 1970 case ISD::LOAD: { 1971 SDValue Result = LowerLOAD(Op, DAG); 1972 assert((!Result.getNode() || 1973 Result.getNode()->getNumValues() == 2) && 1974 "Load should return a value and a chain"); 1975 return Result; 1976 } 1977 1978 case ISD::FSIN: 1979 case ISD::FCOS: 1980 return LowerTrig(Op, DAG); 1981 case ISD::SELECT: return LowerSELECT(Op, DAG); 1982 case ISD::FDIV: return LowerFDIV(Op, DAG); 1983 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 1984 case ISD::STORE: return LowerSTORE(Op, DAG); 1985 case ISD::GlobalAddress: { 1986 MachineFunction &MF = DAG.getMachineFunction(); 1987 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1988 return LowerGlobalAddress(MFI, Op, DAG); 1989 } 1990 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 1991 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 1992 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 1993 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 1994 case ISD::INSERT_VECTOR_ELT: 1995 return lowerINSERT_VECTOR_ELT(Op, DAG); 1996 case ISD::EXTRACT_VECTOR_ELT: 1997 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 1998 case ISD::FP_ROUND: 1999 return lowerFP_ROUND(Op, DAG); 2000 } 2001 return SDValue(); 2002 } 2003 2004 void SITargetLowering::ReplaceNodeResults(SDNode *N, 2005 SmallVectorImpl<SDValue> &Results, 2006 SelectionDAG &DAG) const { 2007 switch (N->getOpcode()) { 2008 case ISD::INSERT_VECTOR_ELT: { 2009 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 2010 Results.push_back(Res); 2011 return; 2012 } 2013 case ISD::EXTRACT_VECTOR_ELT: { 2014 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 2015 Results.push_back(Res); 2016 return; 2017 } 2018 case ISD::INTRINSIC_WO_CHAIN: { 2019 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 2020 switch (IID) { 2021 case Intrinsic::amdgcn_cvt_pkrtz: { 2022 SDValue Src0 = N->getOperand(1); 2023 SDValue Src1 = N->getOperand(2); 2024 SDLoc SL(N); 2025 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 2026 Src0, Src1); 2027 2028 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 2029 return; 2030 } 2031 default: 2032 break; 2033 } 2034 } 2035 default: 2036 break; 2037 } 2038 } 2039 2040 /// \brief Helper function for LowerBRCOND 2041 static SDNode *findUser(SDValue Value, unsigned Opcode) { 2042 2043 SDNode *Parent = Value.getNode(); 2044 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 2045 I != E; ++I) { 2046 2047 if (I.getUse().get() != Value) 2048 continue; 2049 2050 if (I->getOpcode() == Opcode) 2051 return *I; 2052 } 2053 return nullptr; 2054 } 2055 2056 bool SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 2057 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 2058 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 2059 case AMDGPUIntrinsic::amdgcn_if: 2060 case AMDGPUIntrinsic::amdgcn_else: 2061 case AMDGPUIntrinsic::amdgcn_end_cf: 2062 case AMDGPUIntrinsic::amdgcn_loop: 2063 return true; 2064 default: 2065 return false; 2066 } 2067 } 2068 2069 if (Intr->getOpcode() == ISD::INTRINSIC_WO_CHAIN) { 2070 switch (cast<ConstantSDNode>(Intr->getOperand(0))->getZExtValue()) { 2071 case AMDGPUIntrinsic::amdgcn_break: 2072 case AMDGPUIntrinsic::amdgcn_if_break: 2073 case AMDGPUIntrinsic::amdgcn_else_break: 2074 return true; 2075 default: 2076 return false; 2077 } 2078 } 2079 2080 return false; 2081 } 2082 2083 void SITargetLowering::createDebuggerPrologueStackObjects( 2084 MachineFunction &MF) const { 2085 // Create stack objects that are used for emitting debugger prologue. 2086 // 2087 // Debugger prologue writes work group IDs and work item IDs to scratch memory 2088 // at fixed location in the following format: 2089 // offset 0: work group ID x 2090 // offset 4: work group ID y 2091 // offset 8: work group ID z 2092 // offset 16: work item ID x 2093 // offset 20: work item ID y 2094 // offset 24: work item ID z 2095 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2096 int ObjectIdx = 0; 2097 2098 // For each dimension: 2099 for (unsigned i = 0; i < 3; ++i) { 2100 // Create fixed stack object for work group ID. 2101 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true); 2102 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx); 2103 // Create fixed stack object for work item ID. 2104 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true); 2105 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx); 2106 } 2107 } 2108 2109 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 2110 const Triple &TT = getTargetMachine().getTargetTriple(); 2111 return GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS && 2112 AMDGPU::shouldEmitConstantsToTextSection(TT); 2113 } 2114 2115 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 2116 return (GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 2117 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS) && 2118 !shouldEmitFixup(GV) && 2119 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 2120 } 2121 2122 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 2123 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 2124 } 2125 2126 /// This transforms the control flow intrinsics to get the branch destination as 2127 /// last parameter, also switches branch target with BR if the need arise 2128 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 2129 SelectionDAG &DAG) const { 2130 SDLoc DL(BRCOND); 2131 2132 SDNode *Intr = BRCOND.getOperand(1).getNode(); 2133 SDValue Target = BRCOND.getOperand(2); 2134 SDNode *BR = nullptr; 2135 SDNode *SetCC = nullptr; 2136 2137 if (Intr->getOpcode() == ISD::SETCC) { 2138 // As long as we negate the condition everything is fine 2139 SetCC = Intr; 2140 Intr = SetCC->getOperand(0).getNode(); 2141 2142 } else { 2143 // Get the target from BR if we don't negate the condition 2144 BR = findUser(BRCOND, ISD::BR); 2145 Target = BR->getOperand(1); 2146 } 2147 2148 // FIXME: This changes the types of the intrinsics instead of introducing new 2149 // nodes with the correct types. 2150 // e.g. llvm.amdgcn.loop 2151 2152 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 2153 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 2154 2155 if (!isCFIntrinsic(Intr)) { 2156 // This is a uniform branch so we don't need to legalize. 2157 return BRCOND; 2158 } 2159 2160 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 2161 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 2162 2163 assert(!SetCC || 2164 (SetCC->getConstantOperandVal(1) == 1 && 2165 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 2166 ISD::SETNE)); 2167 2168 // operands of the new intrinsic call 2169 SmallVector<SDValue, 4> Ops; 2170 if (HaveChain) 2171 Ops.push_back(BRCOND.getOperand(0)); 2172 2173 Ops.append(Intr->op_begin() + (HaveChain ? 1 : 0), Intr->op_end()); 2174 Ops.push_back(Target); 2175 2176 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 2177 2178 // build the new intrinsic call 2179 SDNode *Result = DAG.getNode( 2180 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL, 2181 DAG.getVTList(Res), Ops).getNode(); 2182 2183 if (!HaveChain) { 2184 SDValue Ops[] = { 2185 SDValue(Result, 0), 2186 BRCOND.getOperand(0) 2187 }; 2188 2189 Result = DAG.getMergeValues(Ops, DL).getNode(); 2190 } 2191 2192 if (BR) { 2193 // Give the branch instruction our target 2194 SDValue Ops[] = { 2195 BR->getOperand(0), 2196 BRCOND.getOperand(2) 2197 }; 2198 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 2199 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 2200 BR = NewBR.getNode(); 2201 } 2202 2203 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 2204 2205 // Copy the intrinsic results to registers 2206 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 2207 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 2208 if (!CopyToReg) 2209 continue; 2210 2211 Chain = DAG.getCopyToReg( 2212 Chain, DL, 2213 CopyToReg->getOperand(1), 2214 SDValue(Result, i - 1), 2215 SDValue()); 2216 2217 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 2218 } 2219 2220 // Remove the old intrinsic from the chain 2221 DAG.ReplaceAllUsesOfValueWith( 2222 SDValue(Intr, Intr->getNumValues() - 1), 2223 Intr->getOperand(0)); 2224 2225 return Chain; 2226 } 2227 2228 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 2229 SDValue Op, 2230 const SDLoc &DL, 2231 EVT VT) const { 2232 return Op.getValueType().bitsLE(VT) ? 2233 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 2234 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 2235 } 2236 2237 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 2238 assert(Op.getValueType() == MVT::f16 && 2239 "Do not know how to custom lower FP_ROUND for non-f16 type"); 2240 2241 SDValue Src = Op.getOperand(0); 2242 EVT SrcVT = Src.getValueType(); 2243 if (SrcVT != MVT::f64) 2244 return Op; 2245 2246 SDLoc DL(Op); 2247 2248 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 2249 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 2250 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);; 2251 } 2252 2253 SDValue SITargetLowering::getSegmentAperture(unsigned AS, 2254 SelectionDAG &DAG) const { 2255 2256 if (Subtarget->hasApertureRegs()) { // Read from Aperture Registers directly. 2257 unsigned RegNo = (AS == AMDGPUAS::LOCAL_ADDRESS) ? AMDGPU::SRC_SHARED_BASE : 2258 AMDGPU::SRC_PRIVATE_BASE; 2259 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass, RegNo, MVT::i32); 2260 } 2261 2262 SDLoc SL; 2263 MachineFunction &MF = DAG.getMachineFunction(); 2264 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2265 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 2266 assert(UserSGPR != AMDGPU::NoRegister); 2267 2268 SDValue QueuePtr = CreateLiveInRegister( 2269 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 2270 2271 // Offset into amd_queue_t for group_segment_aperture_base_hi / 2272 // private_segment_aperture_base_hi. 2273 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 2274 2275 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, QueuePtr, 2276 DAG.getConstant(StructOffset, SL, MVT::i64)); 2277 2278 // TODO: Use custom target PseudoSourceValue. 2279 // TODO: We should use the value from the IR intrinsic call, but it might not 2280 // be available and how do we get it? 2281 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()), 2282 AMDGPUAS::CONSTANT_ADDRESS)); 2283 2284 MachinePointerInfo PtrInfo(V, StructOffset); 2285 return DAG.getLoad(MVT::i32, SL, QueuePtr.getValue(1), Ptr, PtrInfo, 2286 MinAlign(64, StructOffset), 2287 MachineMemOperand::MODereferenceable | 2288 MachineMemOperand::MOInvariant); 2289 } 2290 2291 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 2292 SelectionDAG &DAG) const { 2293 SDLoc SL(Op); 2294 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 2295 2296 SDValue Src = ASC->getOperand(0); 2297 2298 // FIXME: Really support non-0 null pointers. 2299 SDValue SegmentNullPtr = DAG.getConstant(-1, SL, MVT::i32); 2300 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 2301 2302 // flat -> local/private 2303 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 2304 if (ASC->getDestAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2305 ASC->getDestAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 2306 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 2307 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 2308 2309 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 2310 NonNull, Ptr, SegmentNullPtr); 2311 } 2312 } 2313 2314 // local/private -> flat 2315 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 2316 if (ASC->getSrcAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2317 ASC->getSrcAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 2318 SDValue NonNull 2319 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 2320 2321 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), DAG); 2322 SDValue CvtPtr 2323 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 2324 2325 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 2326 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 2327 FlatNullPtr); 2328 } 2329 } 2330 2331 // global <-> flat are no-ops and never emitted. 2332 2333 const MachineFunction &MF = DAG.getMachineFunction(); 2334 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 2335 *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 2336 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 2337 2338 return DAG.getUNDEF(ASC->getValueType(0)); 2339 } 2340 2341 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 2342 SelectionDAG &DAG) const { 2343 SDValue Idx = Op.getOperand(2); 2344 if (isa<ConstantSDNode>(Idx)) 2345 return SDValue(); 2346 2347 // Avoid stack access for dynamic indexing. 2348 SDLoc SL(Op); 2349 SDValue Vec = Op.getOperand(0); 2350 SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1)); 2351 2352 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 2353 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val); 2354 2355 // Convert vector index to bit-index. 2356 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, 2357 DAG.getConstant(16, SL, MVT::i32)); 2358 2359 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 2360 2361 SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32, 2362 DAG.getConstant(0xffff, SL, MVT::i32), 2363 ScaledIdx); 2364 2365 SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal); 2366 SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32, 2367 DAG.getNOT(SL, BFM, MVT::i32), BCVec); 2368 2369 SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS); 2370 return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI); 2371 } 2372 2373 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 2374 SelectionDAG &DAG) const { 2375 SDLoc SL(Op); 2376 2377 EVT ResultVT = Op.getValueType(); 2378 SDValue Vec = Op.getOperand(0); 2379 SDValue Idx = Op.getOperand(1); 2380 2381 if (const ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) { 2382 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 2383 2384 if (CIdx->getZExtValue() == 1) { 2385 Result = DAG.getNode(ISD::SRL, SL, MVT::i32, Result, 2386 DAG.getConstant(16, SL, MVT::i32)); 2387 } else { 2388 assert(CIdx->getZExtValue() == 0); 2389 } 2390 2391 if (ResultVT.bitsLT(MVT::i32)) 2392 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result); 2393 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 2394 } 2395 2396 SDValue Sixteen = DAG.getConstant(16, SL, MVT::i32); 2397 2398 // Convert vector index to bit-index. 2399 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Sixteen); 2400 2401 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 2402 SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx); 2403 2404 SDValue Result = Elt; 2405 if (ResultVT.bitsLT(MVT::i32)) 2406 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result); 2407 2408 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 2409 } 2410 2411 bool 2412 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 2413 // We can fold offsets for anything that doesn't require a GOT relocation. 2414 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 2415 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS) && 2416 !shouldEmitGOTReloc(GA->getGlobal()); 2417 } 2418 2419 static SDValue 2420 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 2421 const SDLoc &DL, unsigned Offset, EVT PtrVT, 2422 unsigned GAFlags = SIInstrInfo::MO_NONE) { 2423 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 2424 // lowered to the following code sequence: 2425 // 2426 // For constant address space: 2427 // s_getpc_b64 s[0:1] 2428 // s_add_u32 s0, s0, $symbol 2429 // s_addc_u32 s1, s1, 0 2430 // 2431 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 2432 // a fixup or relocation is emitted to replace $symbol with a literal 2433 // constant, which is a pc-relative offset from the encoding of the $symbol 2434 // operand to the global variable. 2435 // 2436 // For global address space: 2437 // s_getpc_b64 s[0:1] 2438 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 2439 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 2440 // 2441 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 2442 // fixups or relocations are emitted to replace $symbol@*@lo and 2443 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 2444 // which is a 64-bit pc-relative offset from the encoding of the $symbol 2445 // operand to the global variable. 2446 // 2447 // What we want here is an offset from the value returned by s_getpc 2448 // (which is the address of the s_add_u32 instruction) to the global 2449 // variable, but since the encoding of $symbol starts 4 bytes after the start 2450 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 2451 // small. This requires us to add 4 to the global variable offset in order to 2452 // compute the correct address. 2453 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 2454 GAFlags); 2455 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 2456 GAFlags == SIInstrInfo::MO_NONE ? 2457 GAFlags : GAFlags + 1); 2458 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 2459 } 2460 2461 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 2462 SDValue Op, 2463 SelectionDAG &DAG) const { 2464 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 2465 2466 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS && 2467 GSD->getAddressSpace() != AMDGPUAS::GLOBAL_ADDRESS) 2468 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 2469 2470 SDLoc DL(GSD); 2471 const GlobalValue *GV = GSD->getGlobal(); 2472 EVT PtrVT = Op.getValueType(); 2473 2474 if (shouldEmitFixup(GV)) 2475 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 2476 else if (shouldEmitPCReloc(GV)) 2477 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 2478 SIInstrInfo::MO_REL32); 2479 2480 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 2481 SIInstrInfo::MO_GOTPCREL32); 2482 2483 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 2484 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 2485 const DataLayout &DataLayout = DAG.getDataLayout(); 2486 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 2487 // FIXME: Use a PseudoSourceValue once those can be assigned an address space. 2488 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 2489 2490 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 2491 MachineMemOperand::MODereferenceable | 2492 MachineMemOperand::MOInvariant); 2493 } 2494 2495 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 2496 const SDLoc &DL, SDValue V) const { 2497 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 2498 // the destination register. 2499 // 2500 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 2501 // so we will end up with redundant moves to m0. 2502 // 2503 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 2504 2505 // A Null SDValue creates a glue result. 2506 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 2507 V, Chain); 2508 return SDValue(M0, 0); 2509 } 2510 2511 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 2512 SDValue Op, 2513 MVT VT, 2514 unsigned Offset) const { 2515 SDLoc SL(Op); 2516 SDValue Param = LowerParameter(DAG, MVT::i32, MVT::i32, SL, 2517 DAG.getEntryNode(), Offset, false); 2518 // The local size values will have the hi 16-bits as zero. 2519 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 2520 DAG.getValueType(VT)); 2521 } 2522 2523 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 2524 EVT VT) { 2525 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(), 2526 "non-hsa intrinsic with hsa target", 2527 DL.getDebugLoc()); 2528 DAG.getContext()->diagnose(BadIntrin); 2529 return DAG.getUNDEF(VT); 2530 } 2531 2532 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 2533 EVT VT) { 2534 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(), 2535 "intrinsic not supported on subtarget", 2536 DL.getDebugLoc()); 2537 DAG.getContext()->diagnose(BadIntrin); 2538 return DAG.getUNDEF(VT); 2539 } 2540 2541 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 2542 SelectionDAG &DAG) const { 2543 MachineFunction &MF = DAG.getMachineFunction(); 2544 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 2545 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2546 2547 EVT VT = Op.getValueType(); 2548 SDLoc DL(Op); 2549 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2550 2551 // TODO: Should this propagate fast-math-flags? 2552 2553 switch (IntrinsicID) { 2554 case Intrinsic::amdgcn_implicit_buffer_ptr: { 2555 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER); 2556 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT); 2557 } 2558 case Intrinsic::amdgcn_dispatch_ptr: 2559 case Intrinsic::amdgcn_queue_ptr: { 2560 if (!Subtarget->isAmdCodeObjectV2(MF)) { 2561 DiagnosticInfoUnsupported BadIntrin( 2562 *MF.getFunction(), "unsupported hsa intrinsic without hsa target", 2563 DL.getDebugLoc()); 2564 DAG.getContext()->diagnose(BadIntrin); 2565 return DAG.getUNDEF(VT); 2566 } 2567 2568 auto Reg = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 2569 SIRegisterInfo::DISPATCH_PTR : SIRegisterInfo::QUEUE_PTR; 2570 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, 2571 TRI->getPreloadedValue(MF, Reg), VT); 2572 } 2573 case Intrinsic::amdgcn_implicitarg_ptr: { 2574 unsigned offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT); 2575 return LowerParameterPtr(DAG, DL, DAG.getEntryNode(), offset); 2576 } 2577 case Intrinsic::amdgcn_kernarg_segment_ptr: { 2578 unsigned Reg 2579 = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR); 2580 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT); 2581 } 2582 case Intrinsic::amdgcn_dispatch_id: { 2583 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_ID); 2584 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT); 2585 } 2586 case Intrinsic::amdgcn_rcp: 2587 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 2588 case Intrinsic::amdgcn_rsq: 2589 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 2590 case Intrinsic::amdgcn_rsq_legacy: 2591 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 2592 return emitRemovedIntrinsicError(DAG, DL, VT); 2593 2594 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 2595 case Intrinsic::amdgcn_rcp_legacy: 2596 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 2597 return emitRemovedIntrinsicError(DAG, DL, VT); 2598 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 2599 case Intrinsic::amdgcn_rsq_clamp: { 2600 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 2601 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 2602 2603 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 2604 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 2605 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 2606 2607 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 2608 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 2609 DAG.getConstantFP(Max, DL, VT)); 2610 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 2611 DAG.getConstantFP(Min, DL, VT)); 2612 } 2613 case Intrinsic::r600_read_ngroups_x: 2614 if (Subtarget->isAmdHsaOS()) 2615 return emitNonHSAIntrinsicError(DAG, DL, VT); 2616 2617 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 2618 SI::KernelInputOffsets::NGROUPS_X, false); 2619 case Intrinsic::r600_read_ngroups_y: 2620 if (Subtarget->isAmdHsaOS()) 2621 return emitNonHSAIntrinsicError(DAG, DL, VT); 2622 2623 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 2624 SI::KernelInputOffsets::NGROUPS_Y, false); 2625 case Intrinsic::r600_read_ngroups_z: 2626 if (Subtarget->isAmdHsaOS()) 2627 return emitNonHSAIntrinsicError(DAG, DL, VT); 2628 2629 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 2630 SI::KernelInputOffsets::NGROUPS_Z, false); 2631 case Intrinsic::r600_read_global_size_x: 2632 if (Subtarget->isAmdHsaOS()) 2633 return emitNonHSAIntrinsicError(DAG, DL, VT); 2634 2635 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 2636 SI::KernelInputOffsets::GLOBAL_SIZE_X, false); 2637 case Intrinsic::r600_read_global_size_y: 2638 if (Subtarget->isAmdHsaOS()) 2639 return emitNonHSAIntrinsicError(DAG, DL, VT); 2640 2641 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 2642 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false); 2643 case Intrinsic::r600_read_global_size_z: 2644 if (Subtarget->isAmdHsaOS()) 2645 return emitNonHSAIntrinsicError(DAG, DL, VT); 2646 2647 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 2648 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false); 2649 case Intrinsic::r600_read_local_size_x: 2650 if (Subtarget->isAmdHsaOS()) 2651 return emitNonHSAIntrinsicError(DAG, DL, VT); 2652 2653 return lowerImplicitZextParam(DAG, Op, MVT::i16, 2654 SI::KernelInputOffsets::LOCAL_SIZE_X); 2655 case Intrinsic::r600_read_local_size_y: 2656 if (Subtarget->isAmdHsaOS()) 2657 return emitNonHSAIntrinsicError(DAG, DL, VT); 2658 2659 return lowerImplicitZextParam(DAG, Op, MVT::i16, 2660 SI::KernelInputOffsets::LOCAL_SIZE_Y); 2661 case Intrinsic::r600_read_local_size_z: 2662 if (Subtarget->isAmdHsaOS()) 2663 return emitNonHSAIntrinsicError(DAG, DL, VT); 2664 2665 return lowerImplicitZextParam(DAG, Op, MVT::i16, 2666 SI::KernelInputOffsets::LOCAL_SIZE_Z); 2667 case Intrinsic::amdgcn_workgroup_id_x: 2668 case Intrinsic::r600_read_tgid_x: 2669 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass, 2670 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT); 2671 case Intrinsic::amdgcn_workgroup_id_y: 2672 case Intrinsic::r600_read_tgid_y: 2673 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass, 2674 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT); 2675 case Intrinsic::amdgcn_workgroup_id_z: 2676 case Intrinsic::r600_read_tgid_z: 2677 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass, 2678 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT); 2679 case Intrinsic::amdgcn_workitem_id_x: 2680 case Intrinsic::r600_read_tidig_x: 2681 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass, 2682 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT); 2683 case Intrinsic::amdgcn_workitem_id_y: 2684 case Intrinsic::r600_read_tidig_y: 2685 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass, 2686 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT); 2687 case Intrinsic::amdgcn_workitem_id_z: 2688 case Intrinsic::r600_read_tidig_z: 2689 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass, 2690 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT); 2691 case AMDGPUIntrinsic::SI_load_const: { 2692 SDValue Ops[] = { 2693 Op.getOperand(1), 2694 Op.getOperand(2) 2695 }; 2696 2697 MachineMemOperand *MMO = MF.getMachineMemOperand( 2698 MachinePointerInfo(), 2699 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 2700 MachineMemOperand::MOInvariant, 2701 VT.getStoreSize(), 4); 2702 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL, 2703 Op->getVTList(), Ops, VT, MMO); 2704 } 2705 case AMDGPUIntrinsic::amdgcn_fdiv_fast: 2706 return lowerFDIV_FAST(Op, DAG); 2707 case AMDGPUIntrinsic::SI_vs_load_input: 2708 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT, 2709 Op.getOperand(1), 2710 Op.getOperand(2), 2711 Op.getOperand(3)); 2712 case Intrinsic::amdgcn_interp_mov: { 2713 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 2714 SDValue Glue = M0.getValue(1); 2715 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1), 2716 Op.getOperand(2), Op.getOperand(3), Glue); 2717 } 2718 case Intrinsic::amdgcn_interp_p1: { 2719 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 2720 SDValue Glue = M0.getValue(1); 2721 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1), 2722 Op.getOperand(2), Op.getOperand(3), Glue); 2723 } 2724 case Intrinsic::amdgcn_interp_p2: { 2725 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 2726 SDValue Glue = SDValue(M0.getNode(), 1); 2727 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1), 2728 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4), 2729 Glue); 2730 } 2731 case Intrinsic::amdgcn_sin: 2732 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 2733 2734 case Intrinsic::amdgcn_cos: 2735 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 2736 2737 case Intrinsic::amdgcn_log_clamp: { 2738 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 2739 return SDValue(); 2740 2741 DiagnosticInfoUnsupported BadIntrin( 2742 *MF.getFunction(), "intrinsic not supported on subtarget", 2743 DL.getDebugLoc()); 2744 DAG.getContext()->diagnose(BadIntrin); 2745 return DAG.getUNDEF(VT); 2746 } 2747 case Intrinsic::amdgcn_ldexp: 2748 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 2749 Op.getOperand(1), Op.getOperand(2)); 2750 2751 case Intrinsic::amdgcn_fract: 2752 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 2753 2754 case Intrinsic::amdgcn_class: 2755 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 2756 Op.getOperand(1), Op.getOperand(2)); 2757 case Intrinsic::amdgcn_div_fmas: 2758 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 2759 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 2760 Op.getOperand(4)); 2761 2762 case Intrinsic::amdgcn_div_fixup: 2763 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 2764 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 2765 2766 case Intrinsic::amdgcn_trig_preop: 2767 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 2768 Op.getOperand(1), Op.getOperand(2)); 2769 case Intrinsic::amdgcn_div_scale: { 2770 // 3rd parameter required to be a constant. 2771 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 2772 if (!Param) 2773 return DAG.getUNDEF(VT); 2774 2775 // Translate to the operands expected by the machine instruction. The 2776 // first parameter must be the same as the first instruction. 2777 SDValue Numerator = Op.getOperand(1); 2778 SDValue Denominator = Op.getOperand(2); 2779 2780 // Note this order is opposite of the machine instruction's operations, 2781 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 2782 // intrinsic has the numerator as the first operand to match a normal 2783 // division operation. 2784 2785 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 2786 2787 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 2788 Denominator, Numerator); 2789 } 2790 case Intrinsic::amdgcn_icmp: { 2791 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 2792 if (!CD) 2793 return DAG.getUNDEF(VT); 2794 2795 int CondCode = CD->getSExtValue(); 2796 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 2797 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 2798 return DAG.getUNDEF(VT); 2799 2800 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 2801 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 2802 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 2803 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 2804 } 2805 case Intrinsic::amdgcn_fcmp: { 2806 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 2807 if (!CD) 2808 return DAG.getUNDEF(VT); 2809 2810 int CondCode = CD->getSExtValue(); 2811 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 2812 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) 2813 return DAG.getUNDEF(VT); 2814 2815 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 2816 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 2817 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 2818 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 2819 } 2820 case Intrinsic::amdgcn_fmed3: 2821 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 2822 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 2823 case Intrinsic::amdgcn_fmul_legacy: 2824 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 2825 Op.getOperand(1), Op.getOperand(2)); 2826 case Intrinsic::amdgcn_sffbh: 2827 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 2828 case Intrinsic::amdgcn_sbfe: 2829 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 2830 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 2831 case Intrinsic::amdgcn_ubfe: 2832 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 2833 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 2834 case Intrinsic::amdgcn_cvt_pkrtz: { 2835 // FIXME: Stop adding cast if v2f16 legal. 2836 EVT VT = Op.getValueType(); 2837 SDValue Node = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, DL, MVT::i32, 2838 Op.getOperand(1), Op.getOperand(2)); 2839 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 2840 } 2841 case AMDGPUIntrinsic::SI_packf16: { // Legacy name 2842 EVT VT = Op.getValueType(); 2843 return DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, DL, VT, 2844 Op.getOperand(1), Op.getOperand(2)); 2845 } 2846 default: 2847 return AMDGPUTargetLowering::LowerOperation(Op, DAG); 2848 } 2849 } 2850 2851 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 2852 SelectionDAG &DAG) const { 2853 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 2854 SDLoc DL(Op); 2855 switch (IntrID) { 2856 case Intrinsic::amdgcn_atomic_inc: 2857 case Intrinsic::amdgcn_atomic_dec: { 2858 MemSDNode *M = cast<MemSDNode>(Op); 2859 unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ? 2860 AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC; 2861 SDValue Ops[] = { 2862 M->getOperand(0), // Chain 2863 M->getOperand(2), // Ptr 2864 M->getOperand(3) // Value 2865 }; 2866 2867 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 2868 M->getMemoryVT(), M->getMemOperand()); 2869 } 2870 case Intrinsic::amdgcn_buffer_load: 2871 case Intrinsic::amdgcn_buffer_load_format: { 2872 SDValue Ops[] = { 2873 Op.getOperand(0), // Chain 2874 Op.getOperand(2), // rsrc 2875 Op.getOperand(3), // vindex 2876 Op.getOperand(4), // offset 2877 Op.getOperand(5), // glc 2878 Op.getOperand(6) // slc 2879 }; 2880 MachineFunction &MF = DAG.getMachineFunction(); 2881 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 2882 2883 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 2884 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 2885 EVT VT = Op.getValueType(); 2886 EVT IntVT = VT.changeTypeToInteger(); 2887 2888 MachineMemOperand *MMO = MF.getMachineMemOperand( 2889 MachinePointerInfo(MFI->getBufferPSV()), 2890 MachineMemOperand::MOLoad, 2891 VT.getStoreSize(), VT.getStoreSize()); 2892 2893 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, MMO); 2894 } 2895 default: 2896 return SDValue(); 2897 } 2898 } 2899 2900 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 2901 SelectionDAG &DAG) const { 2902 MachineFunction &MF = DAG.getMachineFunction(); 2903 SDLoc DL(Op); 2904 SDValue Chain = Op.getOperand(0); 2905 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 2906 2907 switch (IntrinsicID) { 2908 case Intrinsic::amdgcn_exp: { 2909 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 2910 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 2911 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8)); 2912 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9)); 2913 2914 const SDValue Ops[] = { 2915 Chain, 2916 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 2917 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 2918 Op.getOperand(4), // src0 2919 Op.getOperand(5), // src1 2920 Op.getOperand(6), // src2 2921 Op.getOperand(7), // src3 2922 DAG.getTargetConstant(0, DL, MVT::i1), // compr 2923 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 2924 }; 2925 2926 unsigned Opc = Done->isNullValue() ? 2927 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 2928 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 2929 } 2930 case Intrinsic::amdgcn_exp_compr: { 2931 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 2932 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 2933 SDValue Src0 = Op.getOperand(4); 2934 SDValue Src1 = Op.getOperand(5); 2935 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 2936 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7)); 2937 2938 SDValue Undef = DAG.getUNDEF(MVT::f32); 2939 const SDValue Ops[] = { 2940 Chain, 2941 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 2942 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 2943 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), 2944 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), 2945 Undef, // src2 2946 Undef, // src3 2947 DAG.getTargetConstant(1, DL, MVT::i1), // compr 2948 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 2949 }; 2950 2951 unsigned Opc = Done->isNullValue() ? 2952 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 2953 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 2954 } 2955 case Intrinsic::amdgcn_s_sendmsg: 2956 case Intrinsic::amdgcn_s_sendmsghalt: { 2957 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ? 2958 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT; 2959 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 2960 SDValue Glue = Chain.getValue(1); 2961 return DAG.getNode(NodeOp, DL, MVT::Other, Chain, 2962 Op.getOperand(2), Glue); 2963 } 2964 case AMDGPUIntrinsic::SI_tbuffer_store: { 2965 SDValue Ops[] = { 2966 Chain, 2967 Op.getOperand(2), 2968 Op.getOperand(3), 2969 Op.getOperand(4), 2970 Op.getOperand(5), 2971 Op.getOperand(6), 2972 Op.getOperand(7), 2973 Op.getOperand(8), 2974 Op.getOperand(9), 2975 Op.getOperand(10), 2976 Op.getOperand(11), 2977 Op.getOperand(12), 2978 Op.getOperand(13), 2979 Op.getOperand(14) 2980 }; 2981 2982 EVT VT = Op.getOperand(3).getValueType(); 2983 2984 MachineMemOperand *MMO = MF.getMachineMemOperand( 2985 MachinePointerInfo(), 2986 MachineMemOperand::MOStore, 2987 VT.getStoreSize(), 4); 2988 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL, 2989 Op->getVTList(), Ops, VT, MMO); 2990 } 2991 case AMDGPUIntrinsic::AMDGPU_kill: { 2992 SDValue Src = Op.getOperand(2); 2993 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) { 2994 if (!K->isNegative()) 2995 return Chain; 2996 2997 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32); 2998 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne); 2999 } 3000 3001 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src); 3002 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast); 3003 } 3004 case AMDGPUIntrinsic::SI_export: { // Legacy intrinsic. 3005 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(2)); 3006 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(3)); 3007 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(4)); 3008 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(5)); 3009 const ConstantSDNode *Compr = cast<ConstantSDNode>(Op.getOperand(6)); 3010 3011 const SDValue Ops[] = { 3012 Chain, 3013 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), 3014 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), 3015 Op.getOperand(7), // src0 3016 Op.getOperand(8), // src1 3017 Op.getOperand(9), // src2 3018 Op.getOperand(10), // src3 3019 DAG.getTargetConstant(Compr->getZExtValue(), DL, MVT::i1), 3020 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 3021 }; 3022 3023 unsigned Opc = Done->isNullValue() ? 3024 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 3025 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 3026 } 3027 default: 3028 return SDValue(); 3029 } 3030 } 3031 3032 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 3033 SDLoc DL(Op); 3034 LoadSDNode *Load = cast<LoadSDNode>(Op); 3035 ISD::LoadExtType ExtType = Load->getExtensionType(); 3036 EVT MemVT = Load->getMemoryVT(); 3037 3038 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 3039 // FIXME: Copied from PPC 3040 // First, load into 32 bits, then truncate to 1 bit. 3041 3042 SDValue Chain = Load->getChain(); 3043 SDValue BasePtr = Load->getBasePtr(); 3044 MachineMemOperand *MMO = Load->getMemOperand(); 3045 3046 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 3047 3048 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 3049 BasePtr, RealMemVT, MMO); 3050 3051 SDValue Ops[] = { 3052 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 3053 NewLD.getValue(1) 3054 }; 3055 3056 return DAG.getMergeValues(Ops, DL); 3057 } 3058 3059 if (!MemVT.isVector()) 3060 return SDValue(); 3061 3062 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 3063 "Custom lowering for non-i32 vectors hasn't been implemented."); 3064 3065 unsigned AS = Load->getAddressSpace(); 3066 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 3067 AS, Load->getAlignment())) { 3068 SDValue Ops[2]; 3069 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 3070 return DAG.getMergeValues(Ops, DL); 3071 } 3072 3073 MachineFunction &MF = DAG.getMachineFunction(); 3074 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 3075 // If there is a possibilty that flat instruction access scratch memory 3076 // then we need to use the same legalization rules we use for private. 3077 if (AS == AMDGPUAS::FLAT_ADDRESS) 3078 AS = MFI->hasFlatScratchInit() ? 3079 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 3080 3081 unsigned NumElements = MemVT.getVectorNumElements(); 3082 switch (AS) { 3083 case AMDGPUAS::CONSTANT_ADDRESS: 3084 if (isMemOpUniform(Load)) 3085 return SDValue(); 3086 // Non-uniform loads will be selected to MUBUF instructions, so they 3087 // have the same legalization requirements as global and private 3088 // loads. 3089 // 3090 LLVM_FALLTHROUGH; 3091 case AMDGPUAS::GLOBAL_ADDRESS: 3092 if (Subtarget->getScalarizeGlobalBehavior() && isMemOpUniform(Load) && 3093 isMemOpHasNoClobberedMemOperand(Load)) 3094 return SDValue(); 3095 // Non-uniform loads will be selected to MUBUF instructions, so they 3096 // have the same legalization requirements as global and private 3097 // loads. 3098 // 3099 LLVM_FALLTHROUGH; 3100 case AMDGPUAS::FLAT_ADDRESS: 3101 if (NumElements > 4) 3102 return SplitVectorLoad(Op, DAG); 3103 // v4 loads are supported for private and global memory. 3104 return SDValue(); 3105 case AMDGPUAS::PRIVATE_ADDRESS: 3106 // Depending on the setting of the private_element_size field in the 3107 // resource descriptor, we can only make private accesses up to a certain 3108 // size. 3109 switch (Subtarget->getMaxPrivateElementSize()) { 3110 case 4: 3111 return scalarizeVectorLoad(Load, DAG); 3112 case 8: 3113 if (NumElements > 2) 3114 return SplitVectorLoad(Op, DAG); 3115 return SDValue(); 3116 case 16: 3117 // Same as global/flat 3118 if (NumElements > 4) 3119 return SplitVectorLoad(Op, DAG); 3120 return SDValue(); 3121 default: 3122 llvm_unreachable("unsupported private_element_size"); 3123 } 3124 case AMDGPUAS::LOCAL_ADDRESS: 3125 if (NumElements > 2) 3126 return SplitVectorLoad(Op, DAG); 3127 3128 if (NumElements == 2) 3129 return SDValue(); 3130 3131 // If properly aligned, if we split we might be able to use ds_read_b64. 3132 return SplitVectorLoad(Op, DAG); 3133 default: 3134 return SDValue(); 3135 } 3136 } 3137 3138 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3139 if (Op.getValueType() != MVT::i64) 3140 return SDValue(); 3141 3142 SDLoc DL(Op); 3143 SDValue Cond = Op.getOperand(0); 3144 3145 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 3146 SDValue One = DAG.getConstant(1, DL, MVT::i32); 3147 3148 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 3149 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 3150 3151 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 3152 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 3153 3154 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 3155 3156 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 3157 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 3158 3159 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 3160 3161 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 3162 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res); 3163 } 3164 3165 // Catch division cases where we can use shortcuts with rcp and rsq 3166 // instructions. 3167 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 3168 SelectionDAG &DAG) const { 3169 SDLoc SL(Op); 3170 SDValue LHS = Op.getOperand(0); 3171 SDValue RHS = Op.getOperand(1); 3172 EVT VT = Op.getValueType(); 3173 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath; 3174 3175 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 3176 if (Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals()) || 3177 VT == MVT::f16) { 3178 if (CLHS->isExactlyValue(1.0)) { 3179 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 3180 // the CI documentation has a worst case error of 1 ulp. 3181 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 3182 // use it as long as we aren't trying to use denormals. 3183 // 3184 // v_rcp_f16 and v_rsq_f16 DO support denormals. 3185 3186 // 1.0 / sqrt(x) -> rsq(x) 3187 3188 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 3189 // error seems really high at 2^29 ULP. 3190 if (RHS.getOpcode() == ISD::FSQRT) 3191 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 3192 3193 // 1.0 / x -> rcp(x) 3194 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 3195 } 3196 3197 // Same as for 1.0, but expand the sign out of the constant. 3198 if (CLHS->isExactlyValue(-1.0)) { 3199 // -1.0 / x -> rcp (fneg x) 3200 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 3201 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 3202 } 3203 } 3204 } 3205 3206 const SDNodeFlags *Flags = Op->getFlags(); 3207 3208 if (Unsafe || Flags->hasAllowReciprocal()) { 3209 // Turn into multiply by the reciprocal. 3210 // x / y -> x * (1.0 / y) 3211 SDNodeFlags Flags; 3212 Flags.setUnsafeAlgebra(true); 3213 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 3214 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, &Flags); 3215 } 3216 3217 return SDValue(); 3218 } 3219 3220 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 3221 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 3222 if (GlueChain->getNumValues() <= 1) { 3223 return DAG.getNode(Opcode, SL, VT, A, B); 3224 } 3225 3226 assert(GlueChain->getNumValues() == 3); 3227 3228 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 3229 switch (Opcode) { 3230 default: llvm_unreachable("no chain equivalent for opcode"); 3231 case ISD::FMUL: 3232 Opcode = AMDGPUISD::FMUL_W_CHAIN; 3233 break; 3234 } 3235 3236 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 3237 GlueChain.getValue(2)); 3238 } 3239 3240 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 3241 EVT VT, SDValue A, SDValue B, SDValue C, 3242 SDValue GlueChain) { 3243 if (GlueChain->getNumValues() <= 1) { 3244 return DAG.getNode(Opcode, SL, VT, A, B, C); 3245 } 3246 3247 assert(GlueChain->getNumValues() == 3); 3248 3249 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 3250 switch (Opcode) { 3251 default: llvm_unreachable("no chain equivalent for opcode"); 3252 case ISD::FMA: 3253 Opcode = AMDGPUISD::FMA_W_CHAIN; 3254 break; 3255 } 3256 3257 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 3258 GlueChain.getValue(2)); 3259 } 3260 3261 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 3262 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 3263 return FastLowered; 3264 3265 SDLoc SL(Op); 3266 SDValue Src0 = Op.getOperand(0); 3267 SDValue Src1 = Op.getOperand(1); 3268 3269 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 3270 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 3271 3272 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 3273 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 3274 3275 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 3276 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 3277 3278 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 3279 } 3280 3281 // Faster 2.5 ULP division that does not support denormals. 3282 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 3283 SDLoc SL(Op); 3284 SDValue LHS = Op.getOperand(1); 3285 SDValue RHS = Op.getOperand(2); 3286 3287 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 3288 3289 const APFloat K0Val(BitsToFloat(0x6f800000)); 3290 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 3291 3292 const APFloat K1Val(BitsToFloat(0x2f800000)); 3293 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 3294 3295 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 3296 3297 EVT SetCCVT = 3298 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 3299 3300 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 3301 3302 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 3303 3304 // TODO: Should this propagate fast-math-flags? 3305 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 3306 3307 // rcp does not support denormals. 3308 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 3309 3310 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 3311 3312 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 3313 } 3314 3315 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 3316 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 3317 return FastLowered; 3318 3319 SDLoc SL(Op); 3320 SDValue LHS = Op.getOperand(0); 3321 SDValue RHS = Op.getOperand(1); 3322 3323 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 3324 3325 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 3326 3327 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 3328 RHS, RHS, LHS); 3329 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 3330 LHS, RHS, LHS); 3331 3332 // Denominator is scaled to not be denormal, so using rcp is ok. 3333 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 3334 DenominatorScaled); 3335 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 3336 DenominatorScaled); 3337 3338 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 3339 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 3340 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 3341 3342 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 3343 3344 if (!Subtarget->hasFP32Denormals()) { 3345 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 3346 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 3347 SL, MVT::i32); 3348 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 3349 DAG.getEntryNode(), 3350 EnableDenormValue, BitField); 3351 SDValue Ops[3] = { 3352 NegDivScale0, 3353 EnableDenorm.getValue(0), 3354 EnableDenorm.getValue(1) 3355 }; 3356 3357 NegDivScale0 = DAG.getMergeValues(Ops, SL); 3358 } 3359 3360 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 3361 ApproxRcp, One, NegDivScale0); 3362 3363 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 3364 ApproxRcp, Fma0); 3365 3366 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 3367 Fma1, Fma1); 3368 3369 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 3370 NumeratorScaled, Mul); 3371 3372 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 3373 3374 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 3375 NumeratorScaled, Fma3); 3376 3377 if (!Subtarget->hasFP32Denormals()) { 3378 const SDValue DisableDenormValue = 3379 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 3380 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 3381 Fma4.getValue(1), 3382 DisableDenormValue, 3383 BitField, 3384 Fma4.getValue(2)); 3385 3386 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 3387 DisableDenorm, DAG.getRoot()); 3388 DAG.setRoot(OutputChain); 3389 } 3390 3391 SDValue Scale = NumeratorScaled.getValue(1); 3392 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 3393 Fma4, Fma1, Fma3, Scale); 3394 3395 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 3396 } 3397 3398 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 3399 if (DAG.getTarget().Options.UnsafeFPMath) 3400 return lowerFastUnsafeFDIV(Op, DAG); 3401 3402 SDLoc SL(Op); 3403 SDValue X = Op.getOperand(0); 3404 SDValue Y = Op.getOperand(1); 3405 3406 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 3407 3408 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 3409 3410 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 3411 3412 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 3413 3414 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 3415 3416 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 3417 3418 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 3419 3420 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 3421 3422 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 3423 3424 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 3425 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 3426 3427 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 3428 NegDivScale0, Mul, DivScale1); 3429 3430 SDValue Scale; 3431 3432 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) { 3433 // Workaround a hardware bug on SI where the condition output from div_scale 3434 // is not usable. 3435 3436 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 3437 3438 // Figure out if the scale to use for div_fmas. 3439 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 3440 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 3441 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 3442 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 3443 3444 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 3445 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 3446 3447 SDValue Scale0Hi 3448 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 3449 SDValue Scale1Hi 3450 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 3451 3452 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 3453 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 3454 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 3455 } else { 3456 Scale = DivScale1.getValue(1); 3457 } 3458 3459 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 3460 Fma4, Fma3, Mul, Scale); 3461 3462 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 3463 } 3464 3465 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 3466 EVT VT = Op.getValueType(); 3467 3468 if (VT == MVT::f32) 3469 return LowerFDIV32(Op, DAG); 3470 3471 if (VT == MVT::f64) 3472 return LowerFDIV64(Op, DAG); 3473 3474 if (VT == MVT::f16) 3475 return LowerFDIV16(Op, DAG); 3476 3477 llvm_unreachable("Unexpected type for fdiv"); 3478 } 3479 3480 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 3481 SDLoc DL(Op); 3482 StoreSDNode *Store = cast<StoreSDNode>(Op); 3483 EVT VT = Store->getMemoryVT(); 3484 3485 if (VT == MVT::i1) { 3486 return DAG.getTruncStore(Store->getChain(), DL, 3487 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 3488 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 3489 } 3490 3491 assert(VT.isVector() && 3492 Store->getValue().getValueType().getScalarType() == MVT::i32); 3493 3494 unsigned AS = Store->getAddressSpace(); 3495 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 3496 AS, Store->getAlignment())) { 3497 return expandUnalignedStore(Store, DAG); 3498 } 3499 3500 MachineFunction &MF = DAG.getMachineFunction(); 3501 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 3502 // If there is a possibilty that flat instruction access scratch memory 3503 // then we need to use the same legalization rules we use for private. 3504 if (AS == AMDGPUAS::FLAT_ADDRESS) 3505 AS = MFI->hasFlatScratchInit() ? 3506 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 3507 3508 unsigned NumElements = VT.getVectorNumElements(); 3509 switch (AS) { 3510 case AMDGPUAS::GLOBAL_ADDRESS: 3511 case AMDGPUAS::FLAT_ADDRESS: 3512 if (NumElements > 4) 3513 return SplitVectorStore(Op, DAG); 3514 return SDValue(); 3515 case AMDGPUAS::PRIVATE_ADDRESS: { 3516 switch (Subtarget->getMaxPrivateElementSize()) { 3517 case 4: 3518 return scalarizeVectorStore(Store, DAG); 3519 case 8: 3520 if (NumElements > 2) 3521 return SplitVectorStore(Op, DAG); 3522 return SDValue(); 3523 case 16: 3524 if (NumElements > 4) 3525 return SplitVectorStore(Op, DAG); 3526 return SDValue(); 3527 default: 3528 llvm_unreachable("unsupported private_element_size"); 3529 } 3530 } 3531 case AMDGPUAS::LOCAL_ADDRESS: { 3532 if (NumElements > 2) 3533 return SplitVectorStore(Op, DAG); 3534 3535 if (NumElements == 2) 3536 return Op; 3537 3538 // If properly aligned, if we split we might be able to use ds_write_b64. 3539 return SplitVectorStore(Op, DAG); 3540 } 3541 default: 3542 llvm_unreachable("unhandled address space"); 3543 } 3544 } 3545 3546 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 3547 SDLoc DL(Op); 3548 EVT VT = Op.getValueType(); 3549 SDValue Arg = Op.getOperand(0); 3550 // TODO: Should this propagate fast-math-flags? 3551 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT, 3552 DAG.getNode(ISD::FMUL, DL, VT, Arg, 3553 DAG.getConstantFP(0.5/M_PI, DL, 3554 VT))); 3555 3556 switch (Op.getOpcode()) { 3557 case ISD::FCOS: 3558 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart); 3559 case ISD::FSIN: 3560 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart); 3561 default: 3562 llvm_unreachable("Wrong trig opcode"); 3563 } 3564 } 3565 3566 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 3567 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 3568 assert(AtomicNode->isCompareAndSwap()); 3569 unsigned AS = AtomicNode->getAddressSpace(); 3570 3571 // No custom lowering required for local address space 3572 if (!isFlatGlobalAddrSpace(AS)) 3573 return Op; 3574 3575 // Non-local address space requires custom lowering for atomic compare 3576 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 3577 SDLoc DL(Op); 3578 SDValue ChainIn = Op.getOperand(0); 3579 SDValue Addr = Op.getOperand(1); 3580 SDValue Old = Op.getOperand(2); 3581 SDValue New = Op.getOperand(3); 3582 EVT VT = Op.getValueType(); 3583 MVT SimpleVT = VT.getSimpleVT(); 3584 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 3585 3586 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 3587 SDValue Ops[] = { ChainIn, Addr, NewOld }; 3588 3589 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 3590 Ops, VT, AtomicNode->getMemOperand()); 3591 } 3592 3593 //===----------------------------------------------------------------------===// 3594 // Custom DAG optimizations 3595 //===----------------------------------------------------------------------===// 3596 3597 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 3598 DAGCombinerInfo &DCI) const { 3599 EVT VT = N->getValueType(0); 3600 EVT ScalarVT = VT.getScalarType(); 3601 if (ScalarVT != MVT::f32) 3602 return SDValue(); 3603 3604 SelectionDAG &DAG = DCI.DAG; 3605 SDLoc DL(N); 3606 3607 SDValue Src = N->getOperand(0); 3608 EVT SrcVT = Src.getValueType(); 3609 3610 // TODO: We could try to match extracting the higher bytes, which would be 3611 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 3612 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 3613 // about in practice. 3614 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) { 3615 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 3616 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 3617 DCI.AddToWorklist(Cvt.getNode()); 3618 return Cvt; 3619 } 3620 } 3621 3622 return SDValue(); 3623 } 3624 3625 /// \brief Return true if the given offset Size in bytes can be folded into 3626 /// the immediate offsets of a memory instruction for the given address space. 3627 static bool canFoldOffset(unsigned OffsetSize, unsigned AS, 3628 const SISubtarget &STI) { 3629 switch (AS) { 3630 case AMDGPUAS::GLOBAL_ADDRESS: 3631 // MUBUF instructions a 12-bit offset in bytes. 3632 return isUInt<12>(OffsetSize); 3633 case AMDGPUAS::CONSTANT_ADDRESS: 3634 // SMRD instructions have an 8-bit offset in dwords on SI and 3635 // a 20-bit offset in bytes on VI. 3636 if (STI.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 3637 return isUInt<20>(OffsetSize); 3638 else 3639 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4); 3640 case AMDGPUAS::LOCAL_ADDRESS: 3641 case AMDGPUAS::REGION_ADDRESS: 3642 // The single offset versions have a 16-bit offset in bytes. 3643 return isUInt<16>(OffsetSize); 3644 case AMDGPUAS::PRIVATE_ADDRESS: 3645 // Indirect register addressing does not use any offsets. 3646 default: 3647 return false; 3648 } 3649 } 3650 3651 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 3652 3653 // This is a variant of 3654 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 3655 // 3656 // The normal DAG combiner will do this, but only if the add has one use since 3657 // that would increase the number of instructions. 3658 // 3659 // This prevents us from seeing a constant offset that can be folded into a 3660 // memory instruction's addressing mode. If we know the resulting add offset of 3661 // a pointer can be folded into an addressing offset, we can replace the pointer 3662 // operand with the add of new constant offset. This eliminates one of the uses, 3663 // and may allow the remaining use to also be simplified. 3664 // 3665 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 3666 unsigned AddrSpace, 3667 DAGCombinerInfo &DCI) const { 3668 SDValue N0 = N->getOperand(0); 3669 SDValue N1 = N->getOperand(1); 3670 3671 if (N0.getOpcode() != ISD::ADD) 3672 return SDValue(); 3673 3674 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 3675 if (!CN1) 3676 return SDValue(); 3677 3678 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3679 if (!CAdd) 3680 return SDValue(); 3681 3682 // If the resulting offset is too large, we can't fold it into the addressing 3683 // mode offset. 3684 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 3685 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *getSubtarget())) 3686 return SDValue(); 3687 3688 SelectionDAG &DAG = DCI.DAG; 3689 SDLoc SL(N); 3690 EVT VT = N->getValueType(0); 3691 3692 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 3693 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 3694 3695 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset); 3696 } 3697 3698 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 3699 DAGCombinerInfo &DCI) const { 3700 SDValue Ptr = N->getBasePtr(); 3701 SelectionDAG &DAG = DCI.DAG; 3702 SDLoc SL(N); 3703 3704 // TODO: We could also do this for multiplies. 3705 unsigned AS = N->getAddressSpace(); 3706 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) { 3707 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI); 3708 if (NewPtr) { 3709 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 3710 3711 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 3712 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 3713 } 3714 } 3715 3716 return SDValue(); 3717 } 3718 3719 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 3720 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 3721 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 3722 (Opc == ISD::XOR && Val == 0); 3723 } 3724 3725 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 3726 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 3727 // integer combine opportunities since most 64-bit operations are decomposed 3728 // this way. TODO: We won't want this for SALU especially if it is an inline 3729 // immediate. 3730 SDValue SITargetLowering::splitBinaryBitConstantOp( 3731 DAGCombinerInfo &DCI, 3732 const SDLoc &SL, 3733 unsigned Opc, SDValue LHS, 3734 const ConstantSDNode *CRHS) const { 3735 uint64_t Val = CRHS->getZExtValue(); 3736 uint32_t ValLo = Lo_32(Val); 3737 uint32_t ValHi = Hi_32(Val); 3738 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3739 3740 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 3741 bitOpWithConstantIsReducible(Opc, ValHi)) || 3742 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 3743 // If we need to materialize a 64-bit immediate, it will be split up later 3744 // anyway. Avoid creating the harder to understand 64-bit immediate 3745 // materialization. 3746 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 3747 } 3748 3749 return SDValue(); 3750 } 3751 3752 SDValue SITargetLowering::performAndCombine(SDNode *N, 3753 DAGCombinerInfo &DCI) const { 3754 if (DCI.isBeforeLegalize()) 3755 return SDValue(); 3756 3757 SelectionDAG &DAG = DCI.DAG; 3758 EVT VT = N->getValueType(0); 3759 SDValue LHS = N->getOperand(0); 3760 SDValue RHS = N->getOperand(1); 3761 3762 3763 if (VT == MVT::i64) { 3764 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 3765 if (CRHS) { 3766 if (SDValue Split 3767 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 3768 return Split; 3769 } 3770 } 3771 3772 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 3773 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 3774 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 3775 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 3776 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 3777 3778 SDValue X = LHS.getOperand(0); 3779 SDValue Y = RHS.getOperand(0); 3780 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 3781 return SDValue(); 3782 3783 if (LCC == ISD::SETO) { 3784 if (X != LHS.getOperand(1)) 3785 return SDValue(); 3786 3787 if (RCC == ISD::SETUNE) { 3788 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 3789 if (!C1 || !C1->isInfinity() || C1->isNegative()) 3790 return SDValue(); 3791 3792 const uint32_t Mask = SIInstrFlags::N_NORMAL | 3793 SIInstrFlags::N_SUBNORMAL | 3794 SIInstrFlags::N_ZERO | 3795 SIInstrFlags::P_ZERO | 3796 SIInstrFlags::P_SUBNORMAL | 3797 SIInstrFlags::P_NORMAL; 3798 3799 static_assert(((~(SIInstrFlags::S_NAN | 3800 SIInstrFlags::Q_NAN | 3801 SIInstrFlags::N_INFINITY | 3802 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 3803 "mask not equal"); 3804 3805 SDLoc DL(N); 3806 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 3807 X, DAG.getConstant(Mask, DL, MVT::i32)); 3808 } 3809 } 3810 } 3811 3812 return SDValue(); 3813 } 3814 3815 SDValue SITargetLowering::performOrCombine(SDNode *N, 3816 DAGCombinerInfo &DCI) const { 3817 SelectionDAG &DAG = DCI.DAG; 3818 SDValue LHS = N->getOperand(0); 3819 SDValue RHS = N->getOperand(1); 3820 3821 EVT VT = N->getValueType(0); 3822 if (VT == MVT::i1) { 3823 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 3824 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 3825 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 3826 SDValue Src = LHS.getOperand(0); 3827 if (Src != RHS.getOperand(0)) 3828 return SDValue(); 3829 3830 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 3831 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 3832 if (!CLHS || !CRHS) 3833 return SDValue(); 3834 3835 // Only 10 bits are used. 3836 static const uint32_t MaxMask = 0x3ff; 3837 3838 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 3839 SDLoc DL(N); 3840 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 3841 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 3842 } 3843 3844 return SDValue(); 3845 } 3846 3847 if (VT != MVT::i64) 3848 return SDValue(); 3849 3850 // TODO: This could be a generic combine with a predicate for extracting the 3851 // high half of an integer being free. 3852 3853 // (or i64:x, (zero_extend i32:y)) -> 3854 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 3855 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 3856 RHS.getOpcode() != ISD::ZERO_EXTEND) 3857 std::swap(LHS, RHS); 3858 3859 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 3860 SDValue ExtSrc = RHS.getOperand(0); 3861 EVT SrcVT = ExtSrc.getValueType(); 3862 if (SrcVT == MVT::i32) { 3863 SDLoc SL(N); 3864 SDValue LowLHS, HiBits; 3865 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 3866 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 3867 3868 DCI.AddToWorklist(LowOr.getNode()); 3869 DCI.AddToWorklist(HiBits.getNode()); 3870 3871 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 3872 LowOr, HiBits); 3873 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 3874 } 3875 } 3876 3877 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 3878 if (CRHS) { 3879 if (SDValue Split 3880 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 3881 return Split; 3882 } 3883 3884 return SDValue(); 3885 } 3886 3887 SDValue SITargetLowering::performXorCombine(SDNode *N, 3888 DAGCombinerInfo &DCI) const { 3889 EVT VT = N->getValueType(0); 3890 if (VT != MVT::i64) 3891 return SDValue(); 3892 3893 SDValue LHS = N->getOperand(0); 3894 SDValue RHS = N->getOperand(1); 3895 3896 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 3897 if (CRHS) { 3898 if (SDValue Split 3899 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 3900 return Split; 3901 } 3902 3903 return SDValue(); 3904 } 3905 3906 SDValue SITargetLowering::performClassCombine(SDNode *N, 3907 DAGCombinerInfo &DCI) const { 3908 SelectionDAG &DAG = DCI.DAG; 3909 SDValue Mask = N->getOperand(1); 3910 3911 // fp_class x, 0 -> false 3912 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 3913 if (CMask->isNullValue()) 3914 return DAG.getConstant(0, SDLoc(N), MVT::i1); 3915 } 3916 3917 if (N->getOperand(0).isUndef()) 3918 return DAG.getUNDEF(MVT::i1); 3919 3920 return SDValue(); 3921 } 3922 3923 // Constant fold canonicalize. 3924 SDValue SITargetLowering::performFCanonicalizeCombine( 3925 SDNode *N, 3926 DAGCombinerInfo &DCI) const { 3927 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 3928 if (!CFP) 3929 return SDValue(); 3930 3931 SelectionDAG &DAG = DCI.DAG; 3932 const APFloat &C = CFP->getValueAPF(); 3933 3934 // Flush denormals to 0 if not enabled. 3935 if (C.isDenormal()) { 3936 EVT VT = N->getValueType(0); 3937 if (VT == MVT::f32 && !Subtarget->hasFP32Denormals()) 3938 return DAG.getConstantFP(0.0, SDLoc(N), VT); 3939 3940 if (VT == MVT::f64 && !Subtarget->hasFP64Denormals()) 3941 return DAG.getConstantFP(0.0, SDLoc(N), VT); 3942 3943 if (VT == MVT::f16 && !Subtarget->hasFP16Denormals()) 3944 return DAG.getConstantFP(0.0, SDLoc(N), VT); 3945 } 3946 3947 if (C.isNaN()) { 3948 EVT VT = N->getValueType(0); 3949 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 3950 if (C.isSignaling()) { 3951 // Quiet a signaling NaN. 3952 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 3953 } 3954 3955 // Make sure it is the canonical NaN bitpattern. 3956 // 3957 // TODO: Can we use -1 as the canonical NaN value since it's an inline 3958 // immediate? 3959 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 3960 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 3961 } 3962 3963 return SDValue(CFP, 0); 3964 } 3965 3966 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 3967 switch (Opc) { 3968 case ISD::FMAXNUM: 3969 return AMDGPUISD::FMAX3; 3970 case ISD::SMAX: 3971 return AMDGPUISD::SMAX3; 3972 case ISD::UMAX: 3973 return AMDGPUISD::UMAX3; 3974 case ISD::FMINNUM: 3975 return AMDGPUISD::FMIN3; 3976 case ISD::SMIN: 3977 return AMDGPUISD::SMIN3; 3978 case ISD::UMIN: 3979 return AMDGPUISD::UMIN3; 3980 default: 3981 llvm_unreachable("Not a min/max opcode"); 3982 } 3983 } 3984 3985 static SDValue performIntMed3ImmCombine(SelectionDAG &DAG, const SDLoc &SL, 3986 SDValue Op0, SDValue Op1, bool Signed) { 3987 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 3988 if (!K1) 3989 return SDValue(); 3990 3991 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 3992 if (!K0) 3993 return SDValue(); 3994 3995 if (Signed) { 3996 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 3997 return SDValue(); 3998 } else { 3999 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 4000 return SDValue(); 4001 } 4002 4003 EVT VT = K0->getValueType(0); 4004 4005 MVT NVT = MVT::i32; 4006 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4007 4008 SDValue Tmp1, Tmp2, Tmp3; 4009 Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 4010 Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 4011 Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 4012 4013 if (VT == MVT::i16) { 4014 Tmp1 = DAG.getNode(Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3, SL, NVT, 4015 Tmp1, Tmp2, Tmp3); 4016 4017 return DAG.getNode(ISD::TRUNCATE, SL, VT, Tmp1); 4018 } else 4019 return DAG.getNode(Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3, SL, VT, 4020 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 4021 } 4022 4023 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) { 4024 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions()) 4025 return true; 4026 4027 return DAG.isKnownNeverNaN(Op); 4028 } 4029 4030 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 4031 const SDLoc &SL, 4032 SDValue Op0, 4033 SDValue Op1) const { 4034 ConstantFPSDNode *K1 = dyn_cast<ConstantFPSDNode>(Op1); 4035 if (!K1) 4036 return SDValue(); 4037 4038 ConstantFPSDNode *K0 = dyn_cast<ConstantFPSDNode>(Op0.getOperand(1)); 4039 if (!K0) 4040 return SDValue(); 4041 4042 // Ordered >= (although NaN inputs should have folded away by now). 4043 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 4044 if (Cmp == APFloat::cmpGreaterThan) 4045 return SDValue(); 4046 4047 // TODO: Check IEEE bit enabled? 4048 EVT VT = K0->getValueType(0); 4049 if (Subtarget->enableDX10Clamp()) { 4050 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 4051 // hardware fmed3 behavior converting to a min. 4052 // FIXME: Should this be allowing -0.0? 4053 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 4054 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 4055 } 4056 4057 // No med3 for f16, but clamp is possible. 4058 // TODO: gfx9 has med3 f16 4059 if (VT == MVT::f16 || VT == MVT::f64) 4060 return SDValue(); 4061 4062 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 4063 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would then 4064 // give the other result, which is different from med3 with a NaN input. 4065 SDValue Var = Op0.getOperand(0); 4066 if (!isKnownNeverSNan(DAG, Var)) 4067 return SDValue(); 4068 4069 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 4070 Var, SDValue(K0, 0), SDValue(K1, 0)); 4071 } 4072 4073 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 4074 DAGCombinerInfo &DCI) const { 4075 SelectionDAG &DAG = DCI.DAG; 4076 4077 EVT VT = N->getValueType(0); 4078 unsigned Opc = N->getOpcode(); 4079 SDValue Op0 = N->getOperand(0); 4080 SDValue Op1 = N->getOperand(1); 4081 4082 // Only do this if the inner op has one use since this will just increases 4083 // register pressure for no benefit. 4084 4085 4086 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 4087 VT != MVT::f64) { 4088 // max(max(a, b), c) -> max3(a, b, c) 4089 // min(min(a, b), c) -> min3(a, b, c) 4090 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 4091 SDLoc DL(N); 4092 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 4093 DL, 4094 N->getValueType(0), 4095 Op0.getOperand(0), 4096 Op0.getOperand(1), 4097 Op1); 4098 } 4099 4100 // Try commuted. 4101 // max(a, max(b, c)) -> max3(a, b, c) 4102 // min(a, min(b, c)) -> min3(a, b, c) 4103 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 4104 SDLoc DL(N); 4105 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 4106 DL, 4107 N->getValueType(0), 4108 Op0, 4109 Op1.getOperand(0), 4110 Op1.getOperand(1)); 4111 } 4112 } 4113 4114 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 4115 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 4116 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 4117 return Med3; 4118 } 4119 4120 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 4121 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 4122 return Med3; 4123 } 4124 4125 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 4126 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 4127 (Opc == AMDGPUISD::FMIN_LEGACY && 4128 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 4129 (VT == MVT::f32 || VT == MVT::f64 || 4130 (VT == MVT::f16 && Subtarget->has16BitInsts())) && 4131 Op0.hasOneUse()) { 4132 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 4133 return Res; 4134 } 4135 4136 return SDValue(); 4137 } 4138 4139 static bool isClampZeroToOne(SDValue A, SDValue B) { 4140 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 4141 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 4142 // FIXME: Should this be allowing -0.0? 4143 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 4144 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 4145 } 4146 } 4147 4148 return false; 4149 } 4150 4151 // FIXME: Should only worry about snans for version with chain. 4152 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 4153 DAGCombinerInfo &DCI) const { 4154 EVT VT = N->getValueType(0); 4155 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 4156 // NaNs. With a NaN input, the order of the operands may change the result. 4157 4158 SelectionDAG &DAG = DCI.DAG; 4159 SDLoc SL(N); 4160 4161 SDValue Src0 = N->getOperand(0); 4162 SDValue Src1 = N->getOperand(1); 4163 SDValue Src2 = N->getOperand(2); 4164 4165 if (isClampZeroToOne(Src0, Src1)) { 4166 // const_a, const_b, x -> clamp is safe in all cases including signaling 4167 // nans. 4168 // FIXME: Should this be allowing -0.0? 4169 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 4170 } 4171 4172 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 4173 // handling no dx10-clamp? 4174 if (Subtarget->enableDX10Clamp()) { 4175 // If NaNs is clamped to 0, we are free to reorder the inputs. 4176 4177 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 4178 std::swap(Src0, Src1); 4179 4180 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 4181 std::swap(Src1, Src2); 4182 4183 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 4184 std::swap(Src0, Src1); 4185 4186 if (isClampZeroToOne(Src1, Src2)) 4187 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 4188 } 4189 4190 return SDValue(); 4191 } 4192 4193 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 4194 DAGCombinerInfo &DCI) const { 4195 SDValue Src0 = N->getOperand(0); 4196 SDValue Src1 = N->getOperand(1); 4197 if (Src0.isUndef() && Src1.isUndef()) 4198 return DCI.DAG.getUNDEF(N->getValueType(0)); 4199 return SDValue(); 4200 } 4201 4202 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 4203 const SDNode *N0, 4204 const SDNode *N1) const { 4205 EVT VT = N0->getValueType(0); 4206 4207 // Only do this if we are not trying to support denormals. v_mad_f32 does not 4208 // support denormals ever. 4209 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) || 4210 (VT == MVT::f16 && !Subtarget->hasFP16Denormals())) 4211 return ISD::FMAD; 4212 4213 const TargetOptions &Options = DAG.getTarget().Options; 4214 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || 4215 Options.UnsafeFPMath || 4216 (cast<BinaryWithFlagsSDNode>(N0)->Flags.hasUnsafeAlgebra() && 4217 cast<BinaryWithFlagsSDNode>(N1)->Flags.hasUnsafeAlgebra())) && 4218 isFMAFasterThanFMulAndFAdd(VT)) { 4219 return ISD::FMA; 4220 } 4221 4222 return 0; 4223 } 4224 4225 SDValue SITargetLowering::performFAddCombine(SDNode *N, 4226 DAGCombinerInfo &DCI) const { 4227 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 4228 return SDValue(); 4229 4230 SelectionDAG &DAG = DCI.DAG; 4231 EVT VT = N->getValueType(0); 4232 assert(!VT.isVector()); 4233 4234 SDLoc SL(N); 4235 SDValue LHS = N->getOperand(0); 4236 SDValue RHS = N->getOperand(1); 4237 4238 // These should really be instruction patterns, but writing patterns with 4239 // source modiifiers is a pain. 4240 4241 // fadd (fadd (a, a), b) -> mad 2.0, a, b 4242 if (LHS.getOpcode() == ISD::FADD) { 4243 SDValue A = LHS.getOperand(0); 4244 if (A == LHS.getOperand(1)) { 4245 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 4246 if (FusedOp != 0) { 4247 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 4248 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 4249 } 4250 } 4251 } 4252 4253 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 4254 if (RHS.getOpcode() == ISD::FADD) { 4255 SDValue A = RHS.getOperand(0); 4256 if (A == RHS.getOperand(1)) { 4257 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 4258 if (FusedOp != 0) { 4259 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 4260 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 4261 } 4262 } 4263 } 4264 4265 return SDValue(); 4266 } 4267 4268 SDValue SITargetLowering::performFSubCombine(SDNode *N, 4269 DAGCombinerInfo &DCI) const { 4270 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 4271 return SDValue(); 4272 4273 SelectionDAG &DAG = DCI.DAG; 4274 SDLoc SL(N); 4275 EVT VT = N->getValueType(0); 4276 assert(!VT.isVector()); 4277 4278 // Try to get the fneg to fold into the source modifier. This undoes generic 4279 // DAG combines and folds them into the mad. 4280 // 4281 // Only do this if we are not trying to support denormals. v_mad_f32 does 4282 // not support denormals ever. 4283 SDValue LHS = N->getOperand(0); 4284 SDValue RHS = N->getOperand(1); 4285 if (LHS.getOpcode() == ISD::FADD) { 4286 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 4287 SDValue A = LHS.getOperand(0); 4288 if (A == LHS.getOperand(1)) { 4289 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 4290 if (FusedOp != 0){ 4291 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 4292 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 4293 4294 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 4295 } 4296 } 4297 } 4298 4299 if (RHS.getOpcode() == ISD::FADD) { 4300 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 4301 4302 SDValue A = RHS.getOperand(0); 4303 if (A == RHS.getOperand(1)) { 4304 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 4305 if (FusedOp != 0){ 4306 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 4307 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 4308 } 4309 } 4310 } 4311 4312 return SDValue(); 4313 } 4314 4315 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 4316 DAGCombinerInfo &DCI) const { 4317 SelectionDAG &DAG = DCI.DAG; 4318 SDLoc SL(N); 4319 4320 SDValue LHS = N->getOperand(0); 4321 SDValue RHS = N->getOperand(1); 4322 EVT VT = LHS.getValueType(); 4323 4324 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 4325 VT != MVT::f16)) 4326 return SDValue(); 4327 4328 // Match isinf pattern 4329 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 4330 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 4331 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) { 4332 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 4333 if (!CRHS) 4334 return SDValue(); 4335 4336 const APFloat &APF = CRHS->getValueAPF(); 4337 if (APF.isInfinity() && !APF.isNegative()) { 4338 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY; 4339 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 4340 DAG.getConstant(Mask, SL, MVT::i32)); 4341 } 4342 } 4343 4344 return SDValue(); 4345 } 4346 4347 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 4348 DAGCombinerInfo &DCI) const { 4349 SelectionDAG &DAG = DCI.DAG; 4350 SDLoc SL(N); 4351 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 4352 4353 SDValue Src = N->getOperand(0); 4354 SDValue Srl = N->getOperand(0); 4355 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 4356 Srl = Srl.getOperand(0); 4357 4358 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 4359 if (Srl.getOpcode() == ISD::SRL) { 4360 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 4361 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 4362 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 4363 4364 if (const ConstantSDNode *C = 4365 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 4366 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 4367 EVT(MVT::i32)); 4368 4369 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 4370 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 4371 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 4372 MVT::f32, Srl); 4373 } 4374 } 4375 } 4376 4377 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 4378 4379 APInt KnownZero, KnownOne; 4380 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 4381 !DCI.isBeforeLegalizeOps()); 4382 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4383 if (TLO.ShrinkDemandedConstant(Src, Demanded) || 4384 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) { 4385 DCI.CommitTargetLoweringOpt(TLO); 4386 } 4387 4388 return SDValue(); 4389 } 4390 4391 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 4392 DAGCombinerInfo &DCI) const { 4393 switch (N->getOpcode()) { 4394 default: 4395 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 4396 case ISD::FADD: 4397 return performFAddCombine(N, DCI); 4398 case ISD::FSUB: 4399 return performFSubCombine(N, DCI); 4400 case ISD::SETCC: 4401 return performSetCCCombine(N, DCI); 4402 case ISD::FMAXNUM: 4403 case ISD::FMINNUM: 4404 case ISD::SMAX: 4405 case ISD::SMIN: 4406 case ISD::UMAX: 4407 case ISD::UMIN: 4408 case AMDGPUISD::FMIN_LEGACY: 4409 case AMDGPUISD::FMAX_LEGACY: { 4410 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG && 4411 getTargetMachine().getOptLevel() > CodeGenOpt::None) 4412 return performMinMaxCombine(N, DCI); 4413 break; 4414 } 4415 case ISD::LOAD: 4416 case ISD::STORE: 4417 case ISD::ATOMIC_LOAD: 4418 case ISD::ATOMIC_STORE: 4419 case ISD::ATOMIC_CMP_SWAP: 4420 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4421 case ISD::ATOMIC_SWAP: 4422 case ISD::ATOMIC_LOAD_ADD: 4423 case ISD::ATOMIC_LOAD_SUB: 4424 case ISD::ATOMIC_LOAD_AND: 4425 case ISD::ATOMIC_LOAD_OR: 4426 case ISD::ATOMIC_LOAD_XOR: 4427 case ISD::ATOMIC_LOAD_NAND: 4428 case ISD::ATOMIC_LOAD_MIN: 4429 case ISD::ATOMIC_LOAD_MAX: 4430 case ISD::ATOMIC_LOAD_UMIN: 4431 case ISD::ATOMIC_LOAD_UMAX: 4432 case AMDGPUISD::ATOMIC_INC: 4433 case AMDGPUISD::ATOMIC_DEC: // TODO: Target mem intrinsics. 4434 if (DCI.isBeforeLegalize()) 4435 break; 4436 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 4437 case ISD::AND: 4438 return performAndCombine(N, DCI); 4439 case ISD::OR: 4440 return performOrCombine(N, DCI); 4441 case ISD::XOR: 4442 return performXorCombine(N, DCI); 4443 case AMDGPUISD::FP_CLASS: 4444 return performClassCombine(N, DCI); 4445 case ISD::FCANONICALIZE: 4446 return performFCanonicalizeCombine(N, DCI); 4447 case AMDGPUISD::FRACT: 4448 case AMDGPUISD::RCP: 4449 case AMDGPUISD::RSQ: 4450 case AMDGPUISD::RCP_LEGACY: 4451 case AMDGPUISD::RSQ_LEGACY: 4452 case AMDGPUISD::RSQ_CLAMP: 4453 case AMDGPUISD::LDEXP: { 4454 SDValue Src = N->getOperand(0); 4455 if (Src.isUndef()) 4456 return Src; 4457 break; 4458 } 4459 case ISD::SINT_TO_FP: 4460 case ISD::UINT_TO_FP: 4461 return performUCharToFloatCombine(N, DCI); 4462 case AMDGPUISD::CVT_F32_UBYTE0: 4463 case AMDGPUISD::CVT_F32_UBYTE1: 4464 case AMDGPUISD::CVT_F32_UBYTE2: 4465 case AMDGPUISD::CVT_F32_UBYTE3: 4466 return performCvtF32UByteNCombine(N, DCI); 4467 case AMDGPUISD::FMED3: 4468 return performFMed3Combine(N, DCI); 4469 case AMDGPUISD::CVT_PKRTZ_F16_F32: 4470 return performCvtPkRTZCombine(N, DCI); 4471 } 4472 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 4473 } 4474 4475 /// \brief Helper function for adjustWritemask 4476 static unsigned SubIdx2Lane(unsigned Idx) { 4477 switch (Idx) { 4478 default: return 0; 4479 case AMDGPU::sub0: return 0; 4480 case AMDGPU::sub1: return 1; 4481 case AMDGPU::sub2: return 2; 4482 case AMDGPU::sub3: return 3; 4483 } 4484 } 4485 4486 /// \brief Adjust the writemask of MIMG instructions 4487 void SITargetLowering::adjustWritemask(MachineSDNode *&Node, 4488 SelectionDAG &DAG) const { 4489 SDNode *Users[4] = { }; 4490 unsigned Lane = 0; 4491 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3; 4492 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 4493 unsigned NewDmask = 0; 4494 4495 // Try to figure out the used register components 4496 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 4497 I != E; ++I) { 4498 4499 // Don't look at users of the chain. 4500 if (I.getUse().getResNo() != 0) 4501 continue; 4502 4503 // Abort if we can't understand the usage 4504 if (!I->isMachineOpcode() || 4505 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 4506 return; 4507 4508 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used. 4509 // Note that subregs are packed, i.e. Lane==0 is the first bit set 4510 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 4511 // set, etc. 4512 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 4513 4514 // Set which texture component corresponds to the lane. 4515 unsigned Comp; 4516 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) { 4517 assert(Dmask); 4518 Comp = countTrailingZeros(Dmask); 4519 Dmask &= ~(1 << Comp); 4520 } 4521 4522 // Abort if we have more than one user per component 4523 if (Users[Lane]) 4524 return; 4525 4526 Users[Lane] = *I; 4527 NewDmask |= 1 << Comp; 4528 } 4529 4530 // Abort if there's no change 4531 if (NewDmask == OldDmask) 4532 return; 4533 4534 // Adjust the writemask in the node 4535 std::vector<SDValue> Ops; 4536 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 4537 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 4538 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 4539 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops); 4540 4541 // If we only got one lane, replace it with a copy 4542 // (if NewDmask has only one bit set...) 4543 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) { 4544 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(), 4545 MVT::i32); 4546 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, 4547 SDLoc(), Users[Lane]->getValueType(0), 4548 SDValue(Node, 0), RC); 4549 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 4550 return; 4551 } 4552 4553 // Update the users of the node with the new indices 4554 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) { 4555 SDNode *User = Users[i]; 4556 if (!User) 4557 continue; 4558 4559 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 4560 DAG.UpdateNodeOperands(User, User->getOperand(0), Op); 4561 4562 switch (Idx) { 4563 default: break; 4564 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 4565 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 4566 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 4567 } 4568 } 4569 } 4570 4571 static bool isFrameIndexOp(SDValue Op) { 4572 if (Op.getOpcode() == ISD::AssertZext) 4573 Op = Op.getOperand(0); 4574 4575 return isa<FrameIndexSDNode>(Op); 4576 } 4577 4578 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG) 4579 /// with frame index operands. 4580 /// LLVM assumes that inputs are to these instructions are registers. 4581 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 4582 SelectionDAG &DAG) const { 4583 4584 SmallVector<SDValue, 8> Ops; 4585 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 4586 if (!isFrameIndexOp(Node->getOperand(i))) { 4587 Ops.push_back(Node->getOperand(i)); 4588 continue; 4589 } 4590 4591 SDLoc DL(Node); 4592 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 4593 Node->getOperand(i).getValueType(), 4594 Node->getOperand(i)), 0)); 4595 } 4596 4597 DAG.UpdateNodeOperands(Node, Ops); 4598 } 4599 4600 /// \brief Fold the instructions after selecting them. 4601 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 4602 SelectionDAG &DAG) const { 4603 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4604 unsigned Opcode = Node->getMachineOpcode(); 4605 4606 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 4607 !TII->isGather4(Opcode)) 4608 adjustWritemask(Node, DAG); 4609 4610 if (Opcode == AMDGPU::INSERT_SUBREG || 4611 Opcode == AMDGPU::REG_SEQUENCE) { 4612 legalizeTargetIndependentNode(Node, DAG); 4613 return Node; 4614 } 4615 return Node; 4616 } 4617 4618 /// \brief Assign the register class depending on the number of 4619 /// bits set in the writemask 4620 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 4621 SDNode *Node) const { 4622 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4623 4624 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 4625 4626 if (TII->isVOP3(MI.getOpcode())) { 4627 // Make sure constant bus requirements are respected. 4628 TII->legalizeOperandsVOP3(MRI, MI); 4629 return; 4630 } 4631 4632 if (TII->isMIMG(MI)) { 4633 unsigned VReg = MI.getOperand(0).getReg(); 4634 const TargetRegisterClass *RC = MRI.getRegClass(VReg); 4635 // TODO: Need mapping tables to handle other cases (register classes). 4636 if (RC != &AMDGPU::VReg_128RegClass) 4637 return; 4638 4639 unsigned DmaskIdx = MI.getNumOperands() == 12 ? 3 : 4; 4640 unsigned Writemask = MI.getOperand(DmaskIdx).getImm(); 4641 unsigned BitsSet = 0; 4642 for (unsigned i = 0; i < 4; ++i) 4643 BitsSet += Writemask & (1 << i) ? 1 : 0; 4644 switch (BitsSet) { 4645 default: return; 4646 case 1: RC = &AMDGPU::VGPR_32RegClass; break; 4647 case 2: RC = &AMDGPU::VReg_64RegClass; break; 4648 case 3: RC = &AMDGPU::VReg_96RegClass; break; 4649 } 4650 4651 unsigned NewOpcode = TII->getMaskedMIMGOp(MI.getOpcode(), BitsSet); 4652 MI.setDesc(TII->get(NewOpcode)); 4653 MRI.setRegClass(VReg, RC); 4654 return; 4655 } 4656 4657 // Replace unused atomics with the no return version. 4658 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 4659 if (NoRetAtomicOp != -1) { 4660 if (!Node->hasAnyUseOfValue(0)) { 4661 MI.setDesc(TII->get(NoRetAtomicOp)); 4662 MI.RemoveOperand(0); 4663 return; 4664 } 4665 4666 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 4667 // instruction, because the return type of these instructions is a vec2 of 4668 // the memory type, so it can be tied to the input operand. 4669 // This means these instructions always have a use, so we need to add a 4670 // special case to check if the atomic has only one extract_subreg use, 4671 // which itself has no uses. 4672 if ((Node->hasNUsesOfValue(1, 0) && 4673 Node->use_begin()->isMachineOpcode() && 4674 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 4675 !Node->use_begin()->hasAnyUseOfValue(0))) { 4676 unsigned Def = MI.getOperand(0).getReg(); 4677 4678 // Change this into a noret atomic. 4679 MI.setDesc(TII->get(NoRetAtomicOp)); 4680 MI.RemoveOperand(0); 4681 4682 // If we only remove the def operand from the atomic instruction, the 4683 // extract_subreg will be left with a use of a vreg without a def. 4684 // So we need to insert an implicit_def to avoid machine verifier 4685 // errors. 4686 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 4687 TII->get(AMDGPU::IMPLICIT_DEF), Def); 4688 } 4689 return; 4690 } 4691 } 4692 4693 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 4694 uint64_t Val) { 4695 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 4696 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 4697 } 4698 4699 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 4700 const SDLoc &DL, 4701 SDValue Ptr) const { 4702 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4703 4704 // Build the half of the subregister with the constants before building the 4705 // full 128-bit register. If we are building multiple resource descriptors, 4706 // this will allow CSEing of the 2-component register. 4707 const SDValue Ops0[] = { 4708 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 4709 buildSMovImm32(DAG, DL, 0), 4710 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 4711 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 4712 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 4713 }; 4714 4715 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 4716 MVT::v2i32, Ops0), 0); 4717 4718 // Combine the constants and the pointer. 4719 const SDValue Ops1[] = { 4720 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 4721 Ptr, 4722 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 4723 SubRegHi, 4724 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 4725 }; 4726 4727 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 4728 } 4729 4730 /// \brief Return a resource descriptor with the 'Add TID' bit enabled 4731 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 4732 /// of the resource descriptor) to create an offset, which is added to 4733 /// the resource pointer. 4734 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 4735 SDValue Ptr, uint32_t RsrcDword1, 4736 uint64_t RsrcDword2And3) const { 4737 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 4738 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 4739 if (RsrcDword1) { 4740 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 4741 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 4742 0); 4743 } 4744 4745 SDValue DataLo = buildSMovImm32(DAG, DL, 4746 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 4747 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 4748 4749 const SDValue Ops[] = { 4750 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 4751 PtrLo, 4752 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 4753 PtrHi, 4754 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 4755 DataLo, 4756 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 4757 DataHi, 4758 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 4759 }; 4760 4761 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 4762 } 4763 4764 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG, 4765 const TargetRegisterClass *RC, 4766 unsigned Reg, EVT VT) const { 4767 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT); 4768 4769 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()), 4770 cast<RegisterSDNode>(VReg)->getReg(), VT); 4771 } 4772 4773 //===----------------------------------------------------------------------===// 4774 // SI Inline Assembly Support 4775 //===----------------------------------------------------------------------===// 4776 4777 std::pair<unsigned, const TargetRegisterClass *> 4778 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 4779 StringRef Constraint, 4780 MVT VT) const { 4781 if (!isTypeLegal(VT)) 4782 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 4783 4784 if (Constraint.size() == 1) { 4785 switch (Constraint[0]) { 4786 case 's': 4787 case 'r': 4788 switch (VT.getSizeInBits()) { 4789 default: 4790 return std::make_pair(0U, nullptr); 4791 case 32: 4792 case 16: 4793 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass); 4794 case 64: 4795 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass); 4796 case 128: 4797 return std::make_pair(0U, &AMDGPU::SReg_128RegClass); 4798 case 256: 4799 return std::make_pair(0U, &AMDGPU::SReg_256RegClass); 4800 case 512: 4801 return std::make_pair(0U, &AMDGPU::SReg_512RegClass); 4802 } 4803 4804 case 'v': 4805 switch (VT.getSizeInBits()) { 4806 default: 4807 return std::make_pair(0U, nullptr); 4808 case 32: 4809 case 16: 4810 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass); 4811 case 64: 4812 return std::make_pair(0U, &AMDGPU::VReg_64RegClass); 4813 case 96: 4814 return std::make_pair(0U, &AMDGPU::VReg_96RegClass); 4815 case 128: 4816 return std::make_pair(0U, &AMDGPU::VReg_128RegClass); 4817 case 256: 4818 return std::make_pair(0U, &AMDGPU::VReg_256RegClass); 4819 case 512: 4820 return std::make_pair(0U, &AMDGPU::VReg_512RegClass); 4821 } 4822 } 4823 } 4824 4825 if (Constraint.size() > 1) { 4826 const TargetRegisterClass *RC = nullptr; 4827 if (Constraint[1] == 'v') { 4828 RC = &AMDGPU::VGPR_32RegClass; 4829 } else if (Constraint[1] == 's') { 4830 RC = &AMDGPU::SGPR_32RegClass; 4831 } 4832 4833 if (RC) { 4834 uint32_t Idx; 4835 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 4836 if (!Failed && Idx < RC->getNumRegs()) 4837 return std::make_pair(RC->getRegister(Idx), RC); 4838 } 4839 } 4840 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 4841 } 4842 4843 SITargetLowering::ConstraintType 4844 SITargetLowering::getConstraintType(StringRef Constraint) const { 4845 if (Constraint.size() == 1) { 4846 switch (Constraint[0]) { 4847 default: break; 4848 case 's': 4849 case 'v': 4850 return C_RegisterClass; 4851 } 4852 } 4853 return TargetLowering::getConstraintType(Constraint); 4854 } 4855