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 "SIISelLowering.h" 21 #include "AMDGPU.h" 22 #include "AMDGPUIntrinsicInfo.h" 23 #include "AMDGPUSubtarget.h" 24 #include "AMDGPUTargetMachine.h" 25 #include "SIDefines.h" 26 #include "SIInstrInfo.h" 27 #include "SIMachineFunctionInfo.h" 28 #include "SIRegisterInfo.h" 29 #include "Utils/AMDGPUBaseInfo.h" 30 #include "llvm/ADT/APFloat.h" 31 #include "llvm/ADT/APInt.h" 32 #include "llvm/ADT/ArrayRef.h" 33 #include "llvm/ADT/BitVector.h" 34 #include "llvm/ADT/SmallVector.h" 35 #include "llvm/ADT/Statistic.h" 36 #include "llvm/ADT/StringRef.h" 37 #include "llvm/ADT/StringSwitch.h" 38 #include "llvm/ADT/Twine.h" 39 #include "llvm/CodeGen/Analysis.h" 40 #include "llvm/CodeGen/CallingConvLower.h" 41 #include "llvm/CodeGen/DAGCombine.h" 42 #include "llvm/CodeGen/ISDOpcodes.h" 43 #include "llvm/CodeGen/MachineBasicBlock.h" 44 #include "llvm/CodeGen/MachineFrameInfo.h" 45 #include "llvm/CodeGen/MachineFunction.h" 46 #include "llvm/CodeGen/MachineInstr.h" 47 #include "llvm/CodeGen/MachineInstrBuilder.h" 48 #include "llvm/CodeGen/MachineMemOperand.h" 49 #include "llvm/CodeGen/MachineModuleInfo.h" 50 #include "llvm/CodeGen/MachineOperand.h" 51 #include "llvm/CodeGen/MachineRegisterInfo.h" 52 #include "llvm/CodeGen/MachineValueType.h" 53 #include "llvm/CodeGen/SelectionDAG.h" 54 #include "llvm/CodeGen/SelectionDAGNodes.h" 55 #include "llvm/CodeGen/ValueTypes.h" 56 #include "llvm/IR/Constants.h" 57 #include "llvm/IR/DataLayout.h" 58 #include "llvm/IR/DebugLoc.h" 59 #include "llvm/IR/DerivedTypes.h" 60 #include "llvm/IR/DiagnosticInfo.h" 61 #include "llvm/IR/Function.h" 62 #include "llvm/IR/GlobalValue.h" 63 #include "llvm/IR/InstrTypes.h" 64 #include "llvm/IR/Instruction.h" 65 #include "llvm/IR/Instructions.h" 66 #include "llvm/IR/IntrinsicInst.h" 67 #include "llvm/IR/Type.h" 68 #include "llvm/Support/Casting.h" 69 #include "llvm/Support/CodeGen.h" 70 #include "llvm/Support/CommandLine.h" 71 #include "llvm/Support/Compiler.h" 72 #include "llvm/Support/ErrorHandling.h" 73 #include "llvm/Support/KnownBits.h" 74 #include "llvm/Support/MathExtras.h" 75 #include "llvm/Target/TargetCallingConv.h" 76 #include "llvm/Target/TargetOptions.h" 77 #include "llvm/Target/TargetRegisterInfo.h" 78 #include <cassert> 79 #include <cmath> 80 #include <cstdint> 81 #include <iterator> 82 #include <tuple> 83 #include <utility> 84 #include <vector> 85 86 using namespace llvm; 87 88 #define DEBUG_TYPE "si-lower" 89 90 STATISTIC(NumTailCalls, "Number of tail calls"); 91 92 static cl::opt<bool> EnableVGPRIndexMode( 93 "amdgpu-vgpr-index-mode", 94 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"), 95 cl::init(false)); 96 97 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 98 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 99 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 100 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 101 return AMDGPU::SGPR0 + Reg; 102 } 103 } 104 llvm_unreachable("Cannot allocate sgpr"); 105 } 106 107 SITargetLowering::SITargetLowering(const TargetMachine &TM, 108 const SISubtarget &STI) 109 : AMDGPUTargetLowering(TM, STI) { 110 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 111 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 112 113 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass); 114 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 115 116 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 117 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 118 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 119 120 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass); 121 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass); 122 123 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass); 124 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 125 126 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass); 127 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 128 129 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass); 130 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 131 132 if (Subtarget->has16BitInsts()) { 133 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass); 134 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass); 135 } 136 137 if (Subtarget->hasVOP3PInsts()) { 138 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass); 139 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass); 140 } 141 142 computeRegisterProperties(STI.getRegisterInfo()); 143 144 // We need to custom lower vector stores from local memory 145 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 146 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 147 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 148 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 149 setOperationAction(ISD::LOAD, MVT::i1, Custom); 150 151 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 152 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 153 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 154 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 155 setOperationAction(ISD::STORE, MVT::i1, Custom); 156 157 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 158 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 159 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 160 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 161 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 162 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 163 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 164 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 165 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 166 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 167 168 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 169 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 170 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand); 171 172 setOperationAction(ISD::SELECT, MVT::i1, Promote); 173 setOperationAction(ISD::SELECT, MVT::i64, Custom); 174 setOperationAction(ISD::SELECT, MVT::f64, Promote); 175 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 176 177 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 178 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 179 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 180 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 181 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 182 183 setOperationAction(ISD::SETCC, MVT::i1, Promote); 184 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 185 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 186 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 187 188 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 189 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 190 191 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 192 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 193 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 194 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 195 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 196 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 197 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 198 199 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 200 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 201 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 202 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 203 204 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 205 206 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 207 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 208 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 209 210 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 211 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 212 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 213 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 214 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 215 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 216 217 setOperationAction(ISD::UADDO, MVT::i32, Legal); 218 setOperationAction(ISD::USUBO, MVT::i32, Legal); 219 220 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 221 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 222 223 // We only support LOAD/STORE and vector manipulation ops for vectors 224 // with > 4 elements. 225 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 226 MVT::v2i64, MVT::v2f64}) { 227 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 228 switch (Op) { 229 case ISD::LOAD: 230 case ISD::STORE: 231 case ISD::BUILD_VECTOR: 232 case ISD::BITCAST: 233 case ISD::EXTRACT_VECTOR_ELT: 234 case ISD::INSERT_VECTOR_ELT: 235 case ISD::INSERT_SUBVECTOR: 236 case ISD::EXTRACT_SUBVECTOR: 237 case ISD::SCALAR_TO_VECTOR: 238 break; 239 case ISD::CONCAT_VECTORS: 240 setOperationAction(Op, VT, Custom); 241 break; 242 default: 243 setOperationAction(Op, VT, Expand); 244 break; 245 } 246 } 247 } 248 249 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 250 // is expanded to avoid having two separate loops in case the index is a VGPR. 251 252 // Most operations are naturally 32-bit vector operations. We only support 253 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 254 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 255 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 256 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 257 258 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 259 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 260 261 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 262 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 263 264 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 265 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 266 } 267 268 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 269 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 270 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 271 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 272 273 // Avoid stack access for these. 274 // TODO: Generalize to more vector types. 275 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 276 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 277 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 278 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 279 280 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 281 // and output demarshalling 282 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 283 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 284 285 // We can't return success/failure, only the old value, 286 // let LLVM add the comparison 287 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 288 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 289 290 if (getSubtarget()->hasFlatAddressSpace()) { 291 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 292 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 293 } 294 295 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 296 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 297 298 // On SI this is s_memtime and s_memrealtime on VI. 299 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 300 setOperationAction(ISD::TRAP, MVT::Other, Custom); 301 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 302 303 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 304 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 305 306 if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) { 307 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 308 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 309 setOperationAction(ISD::FRINT, MVT::f64, Legal); 310 } 311 312 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 313 314 setOperationAction(ISD::FSIN, MVT::f32, Custom); 315 setOperationAction(ISD::FCOS, MVT::f32, Custom); 316 setOperationAction(ISD::FDIV, MVT::f32, Custom); 317 setOperationAction(ISD::FDIV, MVT::f64, Custom); 318 319 if (Subtarget->has16BitInsts()) { 320 setOperationAction(ISD::Constant, MVT::i16, Legal); 321 322 setOperationAction(ISD::SMIN, MVT::i16, Legal); 323 setOperationAction(ISD::SMAX, MVT::i16, Legal); 324 325 setOperationAction(ISD::UMIN, MVT::i16, Legal); 326 setOperationAction(ISD::UMAX, MVT::i16, Legal); 327 328 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 329 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 330 331 setOperationAction(ISD::ROTR, MVT::i16, Promote); 332 setOperationAction(ISD::ROTL, MVT::i16, Promote); 333 334 setOperationAction(ISD::SDIV, MVT::i16, Promote); 335 setOperationAction(ISD::UDIV, MVT::i16, Promote); 336 setOperationAction(ISD::SREM, MVT::i16, Promote); 337 setOperationAction(ISD::UREM, MVT::i16, Promote); 338 339 setOperationAction(ISD::BSWAP, MVT::i16, Promote); 340 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 341 342 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 343 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 344 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 345 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 346 347 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 348 349 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 350 351 setOperationAction(ISD::LOAD, MVT::i16, Custom); 352 353 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 354 355 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 356 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 357 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 358 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 359 360 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 361 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 362 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote); 363 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote); 364 365 // F16 - Constant Actions. 366 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 367 368 // F16 - Load/Store Actions. 369 setOperationAction(ISD::LOAD, MVT::f16, Promote); 370 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 371 setOperationAction(ISD::STORE, MVT::f16, Promote); 372 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 373 374 // F16 - VOP1 Actions. 375 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 376 setOperationAction(ISD::FCOS, MVT::f16, Promote); 377 setOperationAction(ISD::FSIN, MVT::f16, Promote); 378 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 379 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 380 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 381 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 382 setOperationAction(ISD::FROUND, MVT::f16, Custom); 383 384 // F16 - VOP2 Actions. 385 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 386 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 387 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 388 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 389 setOperationAction(ISD::FDIV, MVT::f16, Custom); 390 391 // F16 - VOP3 Actions. 392 setOperationAction(ISD::FMA, MVT::f16, Legal); 393 if (!Subtarget->hasFP16Denormals()) 394 setOperationAction(ISD::FMAD, MVT::f16, Legal); 395 } 396 397 if (Subtarget->hasVOP3PInsts()) { 398 for (MVT VT : {MVT::v2i16, MVT::v2f16}) { 399 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 400 switch (Op) { 401 case ISD::LOAD: 402 case ISD::STORE: 403 case ISD::BUILD_VECTOR: 404 case ISD::BITCAST: 405 case ISD::EXTRACT_VECTOR_ELT: 406 case ISD::INSERT_VECTOR_ELT: 407 case ISD::INSERT_SUBVECTOR: 408 case ISD::EXTRACT_SUBVECTOR: 409 case ISD::SCALAR_TO_VECTOR: 410 break; 411 case ISD::CONCAT_VECTORS: 412 setOperationAction(Op, VT, Custom); 413 break; 414 default: 415 setOperationAction(Op, VT, Expand); 416 break; 417 } 418 } 419 } 420 421 // XXX - Do these do anything? Vector constants turn into build_vector. 422 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 423 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 424 425 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 426 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 427 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 428 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 429 430 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 431 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 432 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 433 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 434 435 setOperationAction(ISD::AND, MVT::v2i16, Promote); 436 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 437 setOperationAction(ISD::OR, MVT::v2i16, Promote); 438 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 439 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 440 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 441 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 442 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 443 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 444 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 445 446 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 447 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 448 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 449 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 450 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 451 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 452 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 453 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 454 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 455 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 456 457 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 458 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 459 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 460 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 461 setOperationAction(ISD::FMINNUM, MVT::v2f16, Legal); 462 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Legal); 463 464 // This isn't really legal, but this avoids the legalizer unrolling it (and 465 // allows matching fneg (fabs x) patterns) 466 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 467 468 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 469 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 470 471 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 472 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 473 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 474 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 475 } else { 476 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 477 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 478 } 479 480 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 481 setOperationAction(ISD::SELECT, VT, Custom); 482 } 483 484 setTargetDAGCombine(ISD::ADD); 485 setTargetDAGCombine(ISD::ADDCARRY); 486 setTargetDAGCombine(ISD::SUB); 487 setTargetDAGCombine(ISD::SUBCARRY); 488 setTargetDAGCombine(ISD::FADD); 489 setTargetDAGCombine(ISD::FSUB); 490 setTargetDAGCombine(ISD::FMINNUM); 491 setTargetDAGCombine(ISD::FMAXNUM); 492 setTargetDAGCombine(ISD::SMIN); 493 setTargetDAGCombine(ISD::SMAX); 494 setTargetDAGCombine(ISD::UMIN); 495 setTargetDAGCombine(ISD::UMAX); 496 setTargetDAGCombine(ISD::SETCC); 497 setTargetDAGCombine(ISD::AND); 498 setTargetDAGCombine(ISD::OR); 499 setTargetDAGCombine(ISD::XOR); 500 setTargetDAGCombine(ISD::SINT_TO_FP); 501 setTargetDAGCombine(ISD::UINT_TO_FP); 502 setTargetDAGCombine(ISD::FCANONICALIZE); 503 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 504 setTargetDAGCombine(ISD::ZERO_EXTEND); 505 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 506 setTargetDAGCombine(ISD::BUILD_VECTOR); 507 508 // All memory operations. Some folding on the pointer operand is done to help 509 // matching the constant offsets in the addressing modes. 510 setTargetDAGCombine(ISD::LOAD); 511 setTargetDAGCombine(ISD::STORE); 512 setTargetDAGCombine(ISD::ATOMIC_LOAD); 513 setTargetDAGCombine(ISD::ATOMIC_STORE); 514 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 515 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 516 setTargetDAGCombine(ISD::ATOMIC_SWAP); 517 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 518 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 519 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 520 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 521 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 522 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 523 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 524 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 525 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 526 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 527 528 setSchedulingPreference(Sched::RegPressure); 529 } 530 531 const SISubtarget *SITargetLowering::getSubtarget() const { 532 return static_cast<const SISubtarget *>(Subtarget); 533 } 534 535 //===----------------------------------------------------------------------===// 536 // TargetLowering queries 537 //===----------------------------------------------------------------------===// 538 539 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 540 // SI has some legal vector types, but no legal vector operations. Say no 541 // shuffles are legal in order to prefer scalarizing some vector operations. 542 return false; 543 } 544 545 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 546 const CallInst &CI, 547 unsigned IntrID) const { 548 switch (IntrID) { 549 case Intrinsic::amdgcn_atomic_inc: 550 case Intrinsic::amdgcn_atomic_dec: { 551 Info.opc = ISD::INTRINSIC_W_CHAIN; 552 Info.memVT = MVT::getVT(CI.getType()); 553 Info.ptrVal = CI.getOperand(0); 554 Info.align = 0; 555 556 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 557 Info.vol = !Vol || !Vol->isZero(); 558 Info.readMem = true; 559 Info.writeMem = true; 560 return true; 561 } 562 default: 563 return false; 564 } 565 } 566 567 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 568 SmallVectorImpl<Value*> &Ops, 569 Type *&AccessTy) const { 570 switch (II->getIntrinsicID()) { 571 case Intrinsic::amdgcn_atomic_inc: 572 case Intrinsic::amdgcn_atomic_dec: { 573 Value *Ptr = II->getArgOperand(0); 574 AccessTy = II->getType(); 575 Ops.push_back(Ptr); 576 return true; 577 } 578 default: 579 return false; 580 } 581 } 582 583 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 584 if (!Subtarget->hasFlatInstOffsets()) { 585 // Flat instructions do not have offsets, and only have the register 586 // address. 587 return AM.BaseOffs == 0 && AM.Scale == 0; 588 } 589 590 // GFX9 added a 13-bit signed offset. When using regular flat instructions, 591 // the sign bit is ignored and is treated as a 12-bit unsigned offset. 592 593 // Just r + i 594 return isUInt<12>(AM.BaseOffs) && AM.Scale == 0; 595 } 596 597 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 598 if (Subtarget->hasFlatGlobalInsts()) 599 return isInt<13>(AM.BaseOffs) && AM.Scale == 0; 600 601 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 602 // Assume the we will use FLAT for all global memory accesses 603 // on VI. 604 // FIXME: This assumption is currently wrong. On VI we still use 605 // MUBUF instructions for the r + i addressing mode. As currently 606 // implemented, the MUBUF instructions only work on buffer < 4GB. 607 // It may be possible to support > 4GB buffers with MUBUF instructions, 608 // by setting the stride value in the resource descriptor which would 609 // increase the size limit to (stride * 4GB). However, this is risky, 610 // because it has never been validated. 611 return isLegalFlatAddressingMode(AM); 612 } 613 614 return isLegalMUBUFAddressingMode(AM); 615 } 616 617 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 618 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 619 // additionally can do r + r + i with addr64. 32-bit has more addressing 620 // mode options. Depending on the resource constant, it can also do 621 // (i64 r0) + (i32 r1) * (i14 i). 622 // 623 // Private arrays end up using a scratch buffer most of the time, so also 624 // assume those use MUBUF instructions. Scratch loads / stores are currently 625 // implemented as mubuf instructions with offen bit set, so slightly 626 // different than the normal addr64. 627 if (!isUInt<12>(AM.BaseOffs)) 628 return false; 629 630 // FIXME: Since we can split immediate into soffset and immediate offset, 631 // would it make sense to allow any immediate? 632 633 switch (AM.Scale) { 634 case 0: // r + i or just i, depending on HasBaseReg. 635 return true; 636 case 1: 637 return true; // We have r + r or r + i. 638 case 2: 639 if (AM.HasBaseReg) { 640 // Reject 2 * r + r. 641 return false; 642 } 643 644 // Allow 2 * r as r + r 645 // Or 2 * r + i is allowed as r + r + i. 646 return true; 647 default: // Don't allow n * r 648 return false; 649 } 650 } 651 652 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 653 const AddrMode &AM, Type *Ty, 654 unsigned AS, Instruction *I) const { 655 // No global is ever allowed as a base. 656 if (AM.BaseGV) 657 return false; 658 659 if (AS == AMDGPUASI.GLOBAL_ADDRESS) 660 return isLegalGlobalAddressingMode(AM); 661 662 if (AS == AMDGPUASI.CONSTANT_ADDRESS) { 663 // If the offset isn't a multiple of 4, it probably isn't going to be 664 // correctly aligned. 665 // FIXME: Can we get the real alignment here? 666 if (AM.BaseOffs % 4 != 0) 667 return isLegalMUBUFAddressingMode(AM); 668 669 // There are no SMRD extloads, so if we have to do a small type access we 670 // will use a MUBUF load. 671 // FIXME?: We also need to do this if unaligned, but we don't know the 672 // alignment here. 673 if (DL.getTypeStoreSize(Ty) < 4) 674 return isLegalGlobalAddressingMode(AM); 675 676 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) { 677 // SMRD instructions have an 8-bit, dword offset on SI. 678 if (!isUInt<8>(AM.BaseOffs / 4)) 679 return false; 680 } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) { 681 // On CI+, this can also be a 32-bit literal constant offset. If it fits 682 // in 8-bits, it can use a smaller encoding. 683 if (!isUInt<32>(AM.BaseOffs / 4)) 684 return false; 685 } else if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) { 686 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 687 if (!isUInt<20>(AM.BaseOffs)) 688 return false; 689 } else 690 llvm_unreachable("unhandled generation"); 691 692 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 693 return true; 694 695 if (AM.Scale == 1 && AM.HasBaseReg) 696 return true; 697 698 return false; 699 700 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 701 return isLegalMUBUFAddressingMode(AM); 702 } else if (AS == AMDGPUASI.LOCAL_ADDRESS || 703 AS == AMDGPUASI.REGION_ADDRESS) { 704 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 705 // field. 706 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 707 // an 8-bit dword offset but we don't know the alignment here. 708 if (!isUInt<16>(AM.BaseOffs)) 709 return false; 710 711 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 712 return true; 713 714 if (AM.Scale == 1 && AM.HasBaseReg) 715 return true; 716 717 return false; 718 } else if (AS == AMDGPUASI.FLAT_ADDRESS || 719 AS == AMDGPUASI.UNKNOWN_ADDRESS_SPACE) { 720 // For an unknown address space, this usually means that this is for some 721 // reason being used for pure arithmetic, and not based on some addressing 722 // computation. We don't have instructions that compute pointers with any 723 // addressing modes, so treat them as having no offset like flat 724 // instructions. 725 return isLegalFlatAddressingMode(AM); 726 } else { 727 llvm_unreachable("unhandled address space"); 728 } 729 } 730 731 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 732 const SelectionDAG &DAG) const { 733 if (AS == AMDGPUASI.GLOBAL_ADDRESS || AS == AMDGPUASI.FLAT_ADDRESS) { 734 return (MemVT.getSizeInBits() <= 4 * 32); 735 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 736 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 737 return (MemVT.getSizeInBits() <= MaxPrivateBits); 738 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 739 return (MemVT.getSizeInBits() <= 2 * 32); 740 } 741 return true; 742 } 743 744 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 745 unsigned AddrSpace, 746 unsigned Align, 747 bool *IsFast) const { 748 if (IsFast) 749 *IsFast = false; 750 751 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 752 // which isn't a simple VT. 753 // Until MVT is extended to handle this, simply check for the size and 754 // rely on the condition below: allow accesses if the size is a multiple of 4. 755 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 756 VT.getStoreSize() > 16)) { 757 return false; 758 } 759 760 if (AddrSpace == AMDGPUASI.LOCAL_ADDRESS || 761 AddrSpace == AMDGPUASI.REGION_ADDRESS) { 762 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 763 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 764 // with adjacent offsets. 765 bool AlignedBy4 = (Align % 4 == 0); 766 if (IsFast) 767 *IsFast = AlignedBy4; 768 769 return AlignedBy4; 770 } 771 772 // FIXME: We have to be conservative here and assume that flat operations 773 // will access scratch. If we had access to the IR function, then we 774 // could determine if any private memory was used in the function. 775 if (!Subtarget->hasUnalignedScratchAccess() && 776 (AddrSpace == AMDGPUASI.PRIVATE_ADDRESS || 777 AddrSpace == AMDGPUASI.FLAT_ADDRESS)) { 778 return false; 779 } 780 781 if (Subtarget->hasUnalignedBufferAccess()) { 782 // If we have an uniform constant load, it still requires using a slow 783 // buffer instruction if unaligned. 784 if (IsFast) { 785 *IsFast = (AddrSpace == AMDGPUASI.CONSTANT_ADDRESS) ? 786 (Align % 4 == 0) : true; 787 } 788 789 return true; 790 } 791 792 // Smaller than dword value must be aligned. 793 if (VT.bitsLT(MVT::i32)) 794 return false; 795 796 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 797 // byte-address are ignored, thus forcing Dword alignment. 798 // This applies to private, global, and constant memory. 799 if (IsFast) 800 *IsFast = true; 801 802 return VT.bitsGT(MVT::i32) && Align % 4 == 0; 803 } 804 805 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign, 806 unsigned SrcAlign, bool IsMemset, 807 bool ZeroMemset, 808 bool MemcpyStrSrc, 809 MachineFunction &MF) const { 810 // FIXME: Should account for address space here. 811 812 // The default fallback uses the private pointer size as a guess for a type to 813 // use. Make sure we switch these to 64-bit accesses. 814 815 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global 816 return MVT::v4i32; 817 818 if (Size >= 8 && DstAlign >= 4) 819 return MVT::v2i32; 820 821 // Use the default. 822 return MVT::Other; 823 } 824 825 static bool isFlatGlobalAddrSpace(unsigned AS, AMDGPUAS AMDGPUASI) { 826 return AS == AMDGPUASI.GLOBAL_ADDRESS || 827 AS == AMDGPUASI.FLAT_ADDRESS || 828 AS == AMDGPUASI.CONSTANT_ADDRESS; 829 } 830 831 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 832 unsigned DestAS) const { 833 return isFlatGlobalAddrSpace(SrcAS, AMDGPUASI) && 834 isFlatGlobalAddrSpace(DestAS, AMDGPUASI); 835 } 836 837 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 838 const MemSDNode *MemNode = cast<MemSDNode>(N); 839 const Value *Ptr = MemNode->getMemOperand()->getValue(); 840 const Instruction *I = dyn_cast<Instruction>(Ptr); 841 return I && I->getMetadata("amdgpu.noclobber"); 842 } 843 844 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS, 845 unsigned DestAS) const { 846 // Flat -> private/local is a simple truncate. 847 // Flat -> global is no-op 848 if (SrcAS == AMDGPUASI.FLAT_ADDRESS) 849 return true; 850 851 return isNoopAddrSpaceCast(SrcAS, DestAS); 852 } 853 854 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 855 const MemSDNode *MemNode = cast<MemSDNode>(N); 856 857 return AMDGPU::isUniformMMO(MemNode->getMemOperand()); 858 } 859 860 TargetLoweringBase::LegalizeTypeAction 861 SITargetLowering::getPreferredVectorAction(EVT VT) const { 862 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16)) 863 return TypeSplitVector; 864 865 return TargetLoweringBase::getPreferredVectorAction(VT); 866 } 867 868 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 869 Type *Ty) const { 870 // FIXME: Could be smarter if called for vector constants. 871 return true; 872 } 873 874 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 875 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 876 switch (Op) { 877 case ISD::LOAD: 878 case ISD::STORE: 879 880 // These operations are done with 32-bit instructions anyway. 881 case ISD::AND: 882 case ISD::OR: 883 case ISD::XOR: 884 case ISD::SELECT: 885 // TODO: Extensions? 886 return true; 887 default: 888 return false; 889 } 890 } 891 892 // SimplifySetCC uses this function to determine whether or not it should 893 // create setcc with i1 operands. We don't have instructions for i1 setcc. 894 if (VT == MVT::i1 && Op == ISD::SETCC) 895 return false; 896 897 return TargetLowering::isTypeDesirableForOp(Op, VT); 898 } 899 900 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 901 const SDLoc &SL, 902 SDValue Chain, 903 uint64_t Offset) const { 904 const DataLayout &DL = DAG.getDataLayout(); 905 MachineFunction &MF = DAG.getMachineFunction(); 906 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 907 908 const ArgDescriptor *InputPtrReg; 909 const TargetRegisterClass *RC; 910 911 std::tie(InputPtrReg, RC) 912 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 913 914 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 915 MVT PtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS); 916 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 917 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 918 919 return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr, 920 DAG.getConstant(Offset, SL, PtrVT)); 921 } 922 923 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 924 const SDLoc &SL) const { 925 auto MFI = DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>(); 926 uint64_t Offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT); 927 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 928 } 929 930 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 931 const SDLoc &SL, SDValue Val, 932 bool Signed, 933 const ISD::InputArg *Arg) const { 934 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 935 VT.bitsLT(MemVT)) { 936 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 937 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 938 } 939 940 if (MemVT.isFloatingPoint()) 941 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT); 942 else if (Signed) 943 Val = DAG.getSExtOrTrunc(Val, SL, VT); 944 else 945 Val = DAG.getZExtOrTrunc(Val, SL, VT); 946 947 return Val; 948 } 949 950 SDValue SITargetLowering::lowerKernargMemParameter( 951 SelectionDAG &DAG, EVT VT, EVT MemVT, 952 const SDLoc &SL, SDValue Chain, 953 uint64_t Offset, bool Signed, 954 const ISD::InputArg *Arg) const { 955 const DataLayout &DL = DAG.getDataLayout(); 956 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 957 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS); 958 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 959 960 unsigned Align = DL.getABITypeAlignment(Ty); 961 962 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 963 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 964 MachineMemOperand::MONonTemporal | 965 MachineMemOperand::MODereferenceable | 966 MachineMemOperand::MOInvariant); 967 968 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 969 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 970 } 971 972 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 973 const SDLoc &SL, SDValue Chain, 974 const ISD::InputArg &Arg) const { 975 MachineFunction &MF = DAG.getMachineFunction(); 976 MachineFrameInfo &MFI = MF.getFrameInfo(); 977 978 if (Arg.Flags.isByVal()) { 979 unsigned Size = Arg.Flags.getByValSize(); 980 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 981 return DAG.getFrameIndex(FrameIdx, MVT::i32); 982 } 983 984 unsigned ArgOffset = VA.getLocMemOffset(); 985 unsigned ArgSize = VA.getValVT().getStoreSize(); 986 987 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 988 989 // Create load nodes to retrieve arguments from the stack. 990 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 991 SDValue ArgValue; 992 993 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 994 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 995 MVT MemVT = VA.getValVT(); 996 997 switch (VA.getLocInfo()) { 998 default: 999 break; 1000 case CCValAssign::BCvt: 1001 MemVT = VA.getLocVT(); 1002 break; 1003 case CCValAssign::SExt: 1004 ExtType = ISD::SEXTLOAD; 1005 break; 1006 case CCValAssign::ZExt: 1007 ExtType = ISD::ZEXTLOAD; 1008 break; 1009 case CCValAssign::AExt: 1010 ExtType = ISD::EXTLOAD; 1011 break; 1012 } 1013 1014 ArgValue = DAG.getExtLoad( 1015 ExtType, SL, VA.getLocVT(), Chain, FIN, 1016 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1017 MemVT); 1018 return ArgValue; 1019 } 1020 1021 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1022 const SIMachineFunctionInfo &MFI, 1023 EVT VT, 1024 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1025 const ArgDescriptor *Reg; 1026 const TargetRegisterClass *RC; 1027 1028 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1029 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1030 } 1031 1032 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1033 CallingConv::ID CallConv, 1034 ArrayRef<ISD::InputArg> Ins, 1035 BitVector &Skipped, 1036 FunctionType *FType, 1037 SIMachineFunctionInfo *Info) { 1038 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1039 const ISD::InputArg &Arg = Ins[I]; 1040 1041 // First check if it's a PS input addr. 1042 if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() && 1043 !Arg.Flags.isByVal() && PSInputNum <= 15) { 1044 1045 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) { 1046 // We can safely skip PS inputs. 1047 Skipped.set(I); 1048 ++PSInputNum; 1049 continue; 1050 } 1051 1052 Info->markPSInputAllocated(PSInputNum); 1053 if (Arg.Used) 1054 Info->markPSInputEnabled(PSInputNum); 1055 1056 ++PSInputNum; 1057 } 1058 1059 // Second split vertices into their elements. 1060 if (Arg.VT.isVector()) { 1061 ISD::InputArg NewArg = Arg; 1062 NewArg.Flags.setSplit(); 1063 NewArg.VT = Arg.VT.getVectorElementType(); 1064 1065 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a 1066 // three or five element vertex only needs three or five registers, 1067 // NOT four or eight. 1068 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 1069 unsigned NumElements = ParamType->getVectorNumElements(); 1070 1071 for (unsigned J = 0; J != NumElements; ++J) { 1072 Splits.push_back(NewArg); 1073 NewArg.PartOffset += NewArg.VT.getStoreSize(); 1074 } 1075 } else { 1076 Splits.push_back(Arg); 1077 } 1078 } 1079 } 1080 1081 // Allocate special inputs passed in VGPRs. 1082 static void allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1083 MachineFunction &MF, 1084 const SIRegisterInfo &TRI, 1085 SIMachineFunctionInfo &Info) { 1086 if (Info.hasWorkItemIDX()) { 1087 unsigned Reg = AMDGPU::VGPR0; 1088 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1089 1090 CCInfo.AllocateReg(Reg); 1091 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1092 } 1093 1094 if (Info.hasWorkItemIDY()) { 1095 unsigned Reg = AMDGPU::VGPR1; 1096 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1097 1098 CCInfo.AllocateReg(Reg); 1099 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1100 } 1101 1102 if (Info.hasWorkItemIDZ()) { 1103 unsigned Reg = AMDGPU::VGPR2; 1104 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1105 1106 CCInfo.AllocateReg(Reg); 1107 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1108 } 1109 } 1110 1111 // Try to allocate a VGPR at the end of the argument list, or if no argument 1112 // VGPRs are left allocating a stack slot. 1113 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo) { 1114 ArrayRef<MCPhysReg> ArgVGPRs 1115 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1116 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1117 if (RegIdx == ArgVGPRs.size()) { 1118 // Spill to stack required. 1119 int64_t Offset = CCInfo.AllocateStack(4, 4); 1120 1121 return ArgDescriptor::createStack(Offset); 1122 } 1123 1124 unsigned Reg = ArgVGPRs[RegIdx]; 1125 Reg = CCInfo.AllocateReg(Reg); 1126 assert(Reg != AMDGPU::NoRegister); 1127 1128 MachineFunction &MF = CCInfo.getMachineFunction(); 1129 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1130 return ArgDescriptor::createRegister(Reg); 1131 } 1132 1133 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1134 const TargetRegisterClass *RC, 1135 unsigned NumArgRegs) { 1136 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1137 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1138 if (RegIdx == ArgSGPRs.size()) 1139 report_fatal_error("ran out of SGPRs for arguments"); 1140 1141 unsigned Reg = ArgSGPRs[RegIdx]; 1142 Reg = CCInfo.AllocateReg(Reg); 1143 assert(Reg != AMDGPU::NoRegister); 1144 1145 MachineFunction &MF = CCInfo.getMachineFunction(); 1146 MF.addLiveIn(Reg, RC); 1147 return ArgDescriptor::createRegister(Reg); 1148 } 1149 1150 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1151 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1152 } 1153 1154 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1155 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1156 } 1157 1158 static void allocateSpecialInputVGPRs(CCState &CCInfo, 1159 MachineFunction &MF, 1160 const SIRegisterInfo &TRI, 1161 SIMachineFunctionInfo &Info) { 1162 if (Info.hasWorkItemIDX()) 1163 Info.setWorkItemIDX(allocateVGPR32Input(CCInfo)); 1164 1165 if (Info.hasWorkItemIDY()) 1166 Info.setWorkItemIDY(allocateVGPR32Input(CCInfo)); 1167 1168 if (Info.hasWorkItemIDZ()) 1169 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo)); 1170 } 1171 1172 static void allocateSpecialInputSGPRs(CCState &CCInfo, 1173 MachineFunction &MF, 1174 const SIRegisterInfo &TRI, 1175 SIMachineFunctionInfo &Info) { 1176 auto &ArgInfo = Info.getArgInfo(); 1177 1178 // TODO: Unify handling with private memory pointers. 1179 1180 if (Info.hasDispatchPtr()) 1181 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1182 1183 if (Info.hasQueuePtr()) 1184 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1185 1186 if (Info.hasKernargSegmentPtr()) 1187 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo); 1188 1189 if (Info.hasDispatchID()) 1190 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1191 1192 // flat_scratch_init is not applicable for non-kernel functions. 1193 1194 if (Info.hasWorkGroupIDX()) 1195 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1196 1197 if (Info.hasWorkGroupIDY()) 1198 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1199 1200 if (Info.hasWorkGroupIDZ()) 1201 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1202 1203 if (Info.hasImplicitArgPtr()) 1204 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1205 } 1206 1207 // Allocate special inputs passed in user SGPRs. 1208 static void allocateHSAUserSGPRs(CCState &CCInfo, 1209 MachineFunction &MF, 1210 const SIRegisterInfo &TRI, 1211 SIMachineFunctionInfo &Info) { 1212 if (Info.hasImplicitBufferPtr()) { 1213 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1214 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1215 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1216 } 1217 1218 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1219 if (Info.hasPrivateSegmentBuffer()) { 1220 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1221 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1222 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1223 } 1224 1225 if (Info.hasDispatchPtr()) { 1226 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1227 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1228 CCInfo.AllocateReg(DispatchPtrReg); 1229 } 1230 1231 if (Info.hasQueuePtr()) { 1232 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1233 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1234 CCInfo.AllocateReg(QueuePtrReg); 1235 } 1236 1237 if (Info.hasKernargSegmentPtr()) { 1238 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI); 1239 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1240 CCInfo.AllocateReg(InputPtrReg); 1241 } 1242 1243 if (Info.hasDispatchID()) { 1244 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1245 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1246 CCInfo.AllocateReg(DispatchIDReg); 1247 } 1248 1249 if (Info.hasFlatScratchInit()) { 1250 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1251 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1252 CCInfo.AllocateReg(FlatScratchInitReg); 1253 } 1254 1255 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1256 // these from the dispatch pointer. 1257 } 1258 1259 // Allocate special input registers that are initialized per-wave. 1260 static void allocateSystemSGPRs(CCState &CCInfo, 1261 MachineFunction &MF, 1262 SIMachineFunctionInfo &Info, 1263 CallingConv::ID CallConv, 1264 bool IsShader) { 1265 if (Info.hasWorkGroupIDX()) { 1266 unsigned Reg = Info.addWorkGroupIDX(); 1267 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1268 CCInfo.AllocateReg(Reg); 1269 } 1270 1271 if (Info.hasWorkGroupIDY()) { 1272 unsigned Reg = Info.addWorkGroupIDY(); 1273 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1274 CCInfo.AllocateReg(Reg); 1275 } 1276 1277 if (Info.hasWorkGroupIDZ()) { 1278 unsigned Reg = Info.addWorkGroupIDZ(); 1279 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1280 CCInfo.AllocateReg(Reg); 1281 } 1282 1283 if (Info.hasWorkGroupInfo()) { 1284 unsigned Reg = Info.addWorkGroupInfo(); 1285 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1286 CCInfo.AllocateReg(Reg); 1287 } 1288 1289 if (Info.hasPrivateSegmentWaveByteOffset()) { 1290 // Scratch wave offset passed in system SGPR. 1291 unsigned PrivateSegmentWaveByteOffsetReg; 1292 1293 if (IsShader) { 1294 PrivateSegmentWaveByteOffsetReg = 1295 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1296 1297 // This is true if the scratch wave byte offset doesn't have a fixed 1298 // location. 1299 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1300 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1301 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1302 } 1303 } else 1304 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1305 1306 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1307 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1308 } 1309 } 1310 1311 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1312 MachineFunction &MF, 1313 const SIRegisterInfo &TRI, 1314 SIMachineFunctionInfo &Info) { 1315 // Now that we've figured out where the scratch register inputs are, see if 1316 // should reserve the arguments and use them directly. 1317 MachineFrameInfo &MFI = MF.getFrameInfo(); 1318 bool HasStackObjects = MFI.hasStackObjects(); 1319 1320 // Record that we know we have non-spill stack objects so we don't need to 1321 // check all stack objects later. 1322 if (HasStackObjects) 1323 Info.setHasNonSpillStackObjects(true); 1324 1325 // Everything live out of a block is spilled with fast regalloc, so it's 1326 // almost certain that spilling will be required. 1327 if (TM.getOptLevel() == CodeGenOpt::None) 1328 HasStackObjects = true; 1329 1330 // For now assume stack access is needed in any callee functions, so we need 1331 // the scratch registers to pass in. 1332 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1333 1334 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 1335 if (ST.isAmdCodeObjectV2(MF)) { 1336 if (RequiresStackAccess) { 1337 // If we have stack objects, we unquestionably need the private buffer 1338 // resource. For the Code Object V2 ABI, this will be the first 4 user 1339 // SGPR inputs. We can reserve those and use them directly. 1340 1341 unsigned PrivateSegmentBufferReg = Info.getPreloadedReg( 1342 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 1343 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1344 1345 if (MFI.hasCalls()) { 1346 // If we have calls, we need to keep the frame register in a register 1347 // that won't be clobbered by a call, so ensure it is copied somewhere. 1348 1349 // This is not a problem for the scratch wave offset, because the same 1350 // registers are reserved in all functions. 1351 1352 // FIXME: Nothing is really ensuring this is a call preserved register, 1353 // it's just selected from the end so it happens to be. 1354 unsigned ReservedOffsetReg 1355 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1356 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1357 } else { 1358 unsigned PrivateSegmentWaveByteOffsetReg = Info.getPreloadedReg( 1359 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1360 Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg); 1361 } 1362 } else { 1363 unsigned ReservedBufferReg 1364 = TRI.reservedPrivateSegmentBufferReg(MF); 1365 unsigned ReservedOffsetReg 1366 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1367 1368 // We tentatively reserve the last registers (skipping the last two 1369 // which may contain VCC). After register allocation, we'll replace 1370 // these with the ones immediately after those which were really 1371 // allocated. In the prologue copies will be inserted from the argument 1372 // to these reserved registers. 1373 Info.setScratchRSrcReg(ReservedBufferReg); 1374 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1375 } 1376 } else { 1377 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1378 1379 // Without HSA, relocations are used for the scratch pointer and the 1380 // buffer resource setup is always inserted in the prologue. Scratch wave 1381 // offset is still in an input SGPR. 1382 Info.setScratchRSrcReg(ReservedBufferReg); 1383 1384 if (HasStackObjects && !MFI.hasCalls()) { 1385 unsigned ScratchWaveOffsetReg = Info.getPreloadedReg( 1386 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1387 Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg); 1388 } else { 1389 unsigned ReservedOffsetReg 1390 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1391 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1392 } 1393 } 1394 } 1395 1396 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 1397 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 1398 return !Info->isEntryFunction(); 1399 } 1400 1401 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 1402 1403 } 1404 1405 void SITargetLowering::insertCopiesSplitCSR( 1406 MachineBasicBlock *Entry, 1407 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 1408 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1409 1410 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 1411 if (!IStart) 1412 return; 1413 1414 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1415 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 1416 MachineBasicBlock::iterator MBBI = Entry->begin(); 1417 for (const MCPhysReg *I = IStart; *I; ++I) { 1418 const TargetRegisterClass *RC = nullptr; 1419 if (AMDGPU::SReg_64RegClass.contains(*I)) 1420 RC = &AMDGPU::SGPR_64RegClass; 1421 else if (AMDGPU::SReg_32RegClass.contains(*I)) 1422 RC = &AMDGPU::SGPR_32RegClass; 1423 else 1424 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 1425 1426 unsigned NewVR = MRI->createVirtualRegister(RC); 1427 // Create copy from CSR to a virtual register. 1428 Entry->addLiveIn(*I); 1429 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 1430 .addReg(*I); 1431 1432 // Insert the copy-back instructions right before the terminator. 1433 for (auto *Exit : Exits) 1434 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 1435 TII->get(TargetOpcode::COPY), *I) 1436 .addReg(NewVR); 1437 } 1438 } 1439 1440 SDValue SITargetLowering::LowerFormalArguments( 1441 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 1442 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 1443 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 1444 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1445 1446 MachineFunction &MF = DAG.getMachineFunction(); 1447 FunctionType *FType = MF.getFunction()->getFunctionType(); 1448 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1449 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 1450 1451 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 1452 const Function *Fn = MF.getFunction(); 1453 DiagnosticInfoUnsupported NoGraphicsHSA( 1454 *Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 1455 DAG.getContext()->diagnose(NoGraphicsHSA); 1456 return DAG.getEntryNode(); 1457 } 1458 1459 // Create stack objects that are used for emitting debugger prologue if 1460 // "amdgpu-debugger-emit-prologue" attribute was specified. 1461 if (ST.debuggerEmitPrologue()) 1462 createDebuggerPrologueStackObjects(MF); 1463 1464 SmallVector<ISD::InputArg, 16> Splits; 1465 SmallVector<CCValAssign, 16> ArgLocs; 1466 BitVector Skipped(Ins.size()); 1467 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1468 *DAG.getContext()); 1469 1470 bool IsShader = AMDGPU::isShader(CallConv); 1471 bool IsKernel = AMDGPU::isKernel(CallConv); 1472 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 1473 1474 if (!IsEntryFunc) { 1475 // 4 bytes are reserved at offset 0 for the emergency stack slot. Skip over 1476 // this when allocating argument fixed offsets. 1477 CCInfo.AllocateStack(4, 4); 1478 } 1479 1480 if (IsShader) { 1481 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 1482 1483 // At least one interpolation mode must be enabled or else the GPU will 1484 // hang. 1485 // 1486 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 1487 // set PSInputAddr, the user wants to enable some bits after the compilation 1488 // based on run-time states. Since we can't know what the final PSInputEna 1489 // will look like, so we shouldn't do anything here and the user should take 1490 // responsibility for the correct programming. 1491 // 1492 // Otherwise, the following restrictions apply: 1493 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 1494 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 1495 // enabled too. 1496 if (CallConv == CallingConv::AMDGPU_PS) { 1497 if ((Info->getPSInputAddr() & 0x7F) == 0 || 1498 ((Info->getPSInputAddr() & 0xF) == 0 && 1499 Info->isPSInputAllocated(11))) { 1500 CCInfo.AllocateReg(AMDGPU::VGPR0); 1501 CCInfo.AllocateReg(AMDGPU::VGPR1); 1502 Info->markPSInputAllocated(0); 1503 Info->markPSInputEnabled(0); 1504 } 1505 if (Subtarget->isAmdPalOS()) { 1506 // For isAmdPalOS, the user does not enable some bits after compilation 1507 // based on run-time states; the register values being generated here are 1508 // the final ones set in hardware. Therefore we need to apply the 1509 // workaround to PSInputAddr and PSInputEnable together. (The case where 1510 // a bit is set in PSInputAddr but not PSInputEnable is where the 1511 // frontend set up an input arg for a particular interpolation mode, but 1512 // nothing uses that input arg. Really we should have an earlier pass 1513 // that removes such an arg.) 1514 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 1515 if ((PsInputBits & 0x7F) == 0 || 1516 ((PsInputBits & 0xF) == 0 && 1517 (PsInputBits >> 11 & 1))) 1518 Info->markPSInputEnabled( 1519 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 1520 } 1521 } 1522 1523 assert(!Info->hasDispatchPtr() && 1524 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 1525 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 1526 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 1527 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 1528 !Info->hasWorkItemIDZ()); 1529 } else if (IsKernel) { 1530 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 1531 } else { 1532 Splits.append(Ins.begin(), Ins.end()); 1533 } 1534 1535 if (IsEntryFunc) { 1536 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 1537 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 1538 } 1539 1540 if (IsKernel) { 1541 analyzeFormalArgumentsCompute(CCInfo, Ins); 1542 } else { 1543 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 1544 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 1545 } 1546 1547 SmallVector<SDValue, 16> Chains; 1548 1549 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 1550 const ISD::InputArg &Arg = Ins[i]; 1551 if (Skipped[i]) { 1552 InVals.push_back(DAG.getUNDEF(Arg.VT)); 1553 continue; 1554 } 1555 1556 CCValAssign &VA = ArgLocs[ArgIdx++]; 1557 MVT VT = VA.getLocVT(); 1558 1559 if (IsEntryFunc && VA.isMemLoc()) { 1560 VT = Ins[i].VT; 1561 EVT MemVT = VA.getLocVT(); 1562 1563 const uint64_t Offset = Subtarget->getExplicitKernelArgOffset(MF) + 1564 VA.getLocMemOffset(); 1565 Info->setABIArgOffset(Offset + MemVT.getStoreSize()); 1566 1567 // The first 36 bytes of the input buffer contains information about 1568 // thread group and global sizes. 1569 SDValue Arg = lowerKernargMemParameter( 1570 DAG, VT, MemVT, DL, Chain, Offset, Ins[i].Flags.isSExt(), &Ins[i]); 1571 Chains.push_back(Arg.getValue(1)); 1572 1573 auto *ParamTy = 1574 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 1575 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS && 1576 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 1577 // On SI local pointers are just offsets into LDS, so they are always 1578 // less than 16-bits. On CI and newer they could potentially be 1579 // real pointers, so we can't guarantee their size. 1580 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 1581 DAG.getValueType(MVT::i16)); 1582 } 1583 1584 InVals.push_back(Arg); 1585 continue; 1586 } else if (!IsEntryFunc && VA.isMemLoc()) { 1587 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 1588 InVals.push_back(Val); 1589 if (!Arg.Flags.isByVal()) 1590 Chains.push_back(Val.getValue(1)); 1591 continue; 1592 } 1593 1594 assert(VA.isRegLoc() && "Parameter must be in a register!"); 1595 1596 unsigned Reg = VA.getLocReg(); 1597 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 1598 EVT ValVT = VA.getValVT(); 1599 1600 Reg = MF.addLiveIn(Reg, RC); 1601 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 1602 1603 // If this is an 8 or 16-bit value, it is really passed promoted 1604 // to 32 bits. Insert an assert[sz]ext to capture this, then 1605 // truncate to the right size. 1606 switch (VA.getLocInfo()) { 1607 case CCValAssign::Full: 1608 break; 1609 case CCValAssign::BCvt: 1610 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 1611 break; 1612 case CCValAssign::SExt: 1613 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 1614 DAG.getValueType(ValVT)); 1615 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 1616 break; 1617 case CCValAssign::ZExt: 1618 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 1619 DAG.getValueType(ValVT)); 1620 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 1621 break; 1622 case CCValAssign::AExt: 1623 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 1624 break; 1625 default: 1626 llvm_unreachable("Unknown loc info!"); 1627 } 1628 1629 if (IsShader && Arg.VT.isVector()) { 1630 // Build a vector from the registers 1631 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 1632 unsigned NumElements = ParamType->getVectorNumElements(); 1633 1634 SmallVector<SDValue, 4> Regs; 1635 Regs.push_back(Val); 1636 for (unsigned j = 1; j != NumElements; ++j) { 1637 Reg = ArgLocs[ArgIdx++].getLocReg(); 1638 Reg = MF.addLiveIn(Reg, RC); 1639 1640 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT); 1641 Regs.push_back(Copy); 1642 } 1643 1644 // Fill up the missing vector elements 1645 NumElements = Arg.VT.getVectorNumElements() - NumElements; 1646 Regs.append(NumElements, DAG.getUNDEF(VT)); 1647 1648 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs)); 1649 continue; 1650 } 1651 1652 InVals.push_back(Val); 1653 } 1654 1655 if (!IsEntryFunc) { 1656 // Special inputs come after user arguments. 1657 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 1658 } 1659 1660 // Start adding system SGPRs. 1661 if (IsEntryFunc) { 1662 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 1663 } else { 1664 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 1665 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg()); 1666 CCInfo.AllocateReg(Info->getFrameOffsetReg()); 1667 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 1668 } 1669 1670 auto &ArgUsageInfo = 1671 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 1672 ArgUsageInfo.setFuncArgInfo(*MF.getFunction(), Info->getArgInfo()); 1673 1674 unsigned StackArgSize = CCInfo.getNextStackOffset(); 1675 Info->setBytesInStackArgArea(StackArgSize); 1676 1677 return Chains.empty() ? Chain : 1678 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 1679 } 1680 1681 // TODO: If return values can't fit in registers, we should return as many as 1682 // possible in registers before passing on stack. 1683 bool SITargetLowering::CanLowerReturn( 1684 CallingConv::ID CallConv, 1685 MachineFunction &MF, bool IsVarArg, 1686 const SmallVectorImpl<ISD::OutputArg> &Outs, 1687 LLVMContext &Context) const { 1688 // Replacing returns with sret/stack usage doesn't make sense for shaders. 1689 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 1690 // for shaders. Vector types should be explicitly handled by CC. 1691 if (AMDGPU::isEntryFunctionCC(CallConv)) 1692 return true; 1693 1694 SmallVector<CCValAssign, 16> RVLocs; 1695 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 1696 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 1697 } 1698 1699 SDValue 1700 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 1701 bool isVarArg, 1702 const SmallVectorImpl<ISD::OutputArg> &Outs, 1703 const SmallVectorImpl<SDValue> &OutVals, 1704 const SDLoc &DL, SelectionDAG &DAG) const { 1705 MachineFunction &MF = DAG.getMachineFunction(); 1706 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1707 1708 if (AMDGPU::isKernel(CallConv)) { 1709 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 1710 OutVals, DL, DAG); 1711 } 1712 1713 bool IsShader = AMDGPU::isShader(CallConv); 1714 1715 Info->setIfReturnsVoid(Outs.size() == 0); 1716 bool IsWaveEnd = Info->returnsVoid() && IsShader; 1717 1718 SmallVector<ISD::OutputArg, 48> Splits; 1719 SmallVector<SDValue, 48> SplitVals; 1720 1721 // Split vectors into their elements. 1722 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 1723 const ISD::OutputArg &Out = Outs[i]; 1724 1725 if (IsShader && Out.VT.isVector()) { 1726 MVT VT = Out.VT.getVectorElementType(); 1727 ISD::OutputArg NewOut = Out; 1728 NewOut.Flags.setSplit(); 1729 NewOut.VT = VT; 1730 1731 // We want the original number of vector elements here, e.g. 1732 // three or five, not four or eight. 1733 unsigned NumElements = Out.ArgVT.getVectorNumElements(); 1734 1735 for (unsigned j = 0; j != NumElements; ++j) { 1736 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i], 1737 DAG.getConstant(j, DL, MVT::i32)); 1738 SplitVals.push_back(Elem); 1739 Splits.push_back(NewOut); 1740 NewOut.PartOffset += NewOut.VT.getStoreSize(); 1741 } 1742 } else { 1743 SplitVals.push_back(OutVals[i]); 1744 Splits.push_back(Out); 1745 } 1746 } 1747 1748 // CCValAssign - represent the assignment of the return value to a location. 1749 SmallVector<CCValAssign, 48> RVLocs; 1750 1751 // CCState - Info about the registers and stack slots. 1752 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1753 *DAG.getContext()); 1754 1755 // Analyze outgoing return values. 1756 CCInfo.AnalyzeReturn(Splits, CCAssignFnForReturn(CallConv, isVarArg)); 1757 1758 SDValue Flag; 1759 SmallVector<SDValue, 48> RetOps; 1760 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 1761 1762 // Add return address for callable functions. 1763 if (!Info->isEntryFunction()) { 1764 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1765 SDValue ReturnAddrReg = CreateLiveInRegister( 1766 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 1767 1768 // FIXME: Should be able to use a vreg here, but need a way to prevent it 1769 // from being allcoated to a CSR. 1770 1771 SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 1772 MVT::i64); 1773 1774 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag); 1775 Flag = Chain.getValue(1); 1776 1777 RetOps.push_back(PhysReturnAddrReg); 1778 } 1779 1780 // Copy the result values into the output registers. 1781 for (unsigned i = 0, realRVLocIdx = 0; 1782 i != RVLocs.size(); 1783 ++i, ++realRVLocIdx) { 1784 CCValAssign &VA = RVLocs[i]; 1785 assert(VA.isRegLoc() && "Can only return in registers!"); 1786 // TODO: Partially return in registers if return values don't fit. 1787 1788 SDValue Arg = SplitVals[realRVLocIdx]; 1789 1790 // Copied from other backends. 1791 switch (VA.getLocInfo()) { 1792 case CCValAssign::Full: 1793 break; 1794 case CCValAssign::BCvt: 1795 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 1796 break; 1797 case CCValAssign::SExt: 1798 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 1799 break; 1800 case CCValAssign::ZExt: 1801 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 1802 break; 1803 case CCValAssign::AExt: 1804 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 1805 break; 1806 default: 1807 llvm_unreachable("Unknown loc info!"); 1808 } 1809 1810 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 1811 Flag = Chain.getValue(1); 1812 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 1813 } 1814 1815 // FIXME: Does sret work properly? 1816 if (!Info->isEntryFunction()) { 1817 const SIRegisterInfo *TRI 1818 = static_cast<const SISubtarget *>(Subtarget)->getRegisterInfo(); 1819 const MCPhysReg *I = 1820 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 1821 if (I) { 1822 for (; *I; ++I) { 1823 if (AMDGPU::SReg_64RegClass.contains(*I)) 1824 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 1825 else if (AMDGPU::SReg_32RegClass.contains(*I)) 1826 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 1827 else 1828 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 1829 } 1830 } 1831 } 1832 1833 // Update chain and glue. 1834 RetOps[0] = Chain; 1835 if (Flag.getNode()) 1836 RetOps.push_back(Flag); 1837 1838 unsigned Opc = AMDGPUISD::ENDPGM; 1839 if (!IsWaveEnd) 1840 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 1841 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 1842 } 1843 1844 SDValue SITargetLowering::LowerCallResult( 1845 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 1846 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 1847 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 1848 SDValue ThisVal) const { 1849 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 1850 1851 // Assign locations to each value returned by this call. 1852 SmallVector<CCValAssign, 16> RVLocs; 1853 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 1854 *DAG.getContext()); 1855 CCInfo.AnalyzeCallResult(Ins, RetCC); 1856 1857 // Copy all of the result registers out of their specified physreg. 1858 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1859 CCValAssign VA = RVLocs[i]; 1860 SDValue Val; 1861 1862 if (VA.isRegLoc()) { 1863 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 1864 Chain = Val.getValue(1); 1865 InFlag = Val.getValue(2); 1866 } else if (VA.isMemLoc()) { 1867 report_fatal_error("TODO: return values in memory"); 1868 } else 1869 llvm_unreachable("unknown argument location type"); 1870 1871 switch (VA.getLocInfo()) { 1872 case CCValAssign::Full: 1873 break; 1874 case CCValAssign::BCvt: 1875 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 1876 break; 1877 case CCValAssign::ZExt: 1878 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 1879 DAG.getValueType(VA.getValVT())); 1880 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 1881 break; 1882 case CCValAssign::SExt: 1883 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 1884 DAG.getValueType(VA.getValVT())); 1885 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 1886 break; 1887 case CCValAssign::AExt: 1888 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 1889 break; 1890 default: 1891 llvm_unreachable("Unknown loc info!"); 1892 } 1893 1894 InVals.push_back(Val); 1895 } 1896 1897 return Chain; 1898 } 1899 1900 // Add code to pass special inputs required depending on used features separate 1901 // from the explicit user arguments present in the IR. 1902 void SITargetLowering::passSpecialInputs( 1903 CallLoweringInfo &CLI, 1904 const SIMachineFunctionInfo &Info, 1905 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 1906 SmallVectorImpl<SDValue> &MemOpChains, 1907 SDValue Chain, 1908 SDValue StackPtr) const { 1909 // If we don't have a call site, this was a call inserted by 1910 // legalization. These can never use special inputs. 1911 if (!CLI.CS) 1912 return; 1913 1914 const Function *CalleeFunc = CLI.CS.getCalledFunction(); 1915 assert(CalleeFunc); 1916 1917 SelectionDAG &DAG = CLI.DAG; 1918 const SDLoc &DL = CLI.DL; 1919 1920 const SISubtarget *ST = getSubtarget(); 1921 const SIRegisterInfo *TRI = ST->getRegisterInfo(); 1922 1923 auto &ArgUsageInfo = 1924 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 1925 const AMDGPUFunctionArgInfo &CalleeArgInfo 1926 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 1927 1928 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 1929 1930 // TODO: Unify with private memory register handling. This is complicated by 1931 // the fact that at least in kernels, the input argument is not necessarily 1932 // in the same location as the input. 1933 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 1934 AMDGPUFunctionArgInfo::DISPATCH_PTR, 1935 AMDGPUFunctionArgInfo::QUEUE_PTR, 1936 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR, 1937 AMDGPUFunctionArgInfo::DISPATCH_ID, 1938 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 1939 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 1940 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z, 1941 AMDGPUFunctionArgInfo::WORKITEM_ID_X, 1942 AMDGPUFunctionArgInfo::WORKITEM_ID_Y, 1943 AMDGPUFunctionArgInfo::WORKITEM_ID_Z, 1944 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR 1945 }; 1946 1947 for (auto InputID : InputRegs) { 1948 const ArgDescriptor *OutgoingArg; 1949 const TargetRegisterClass *ArgRC; 1950 1951 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID); 1952 if (!OutgoingArg) 1953 continue; 1954 1955 const ArgDescriptor *IncomingArg; 1956 const TargetRegisterClass *IncomingArgRC; 1957 std::tie(IncomingArg, IncomingArgRC) 1958 = CallerArgInfo.getPreloadedValue(InputID); 1959 assert(IncomingArgRC == ArgRC); 1960 1961 // All special arguments are ints for now. 1962 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 1963 SDValue InputReg; 1964 1965 if (IncomingArg) { 1966 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 1967 } else { 1968 // The implicit arg ptr is special because it doesn't have a corresponding 1969 // input for kernels, and is computed from the kernarg segment pointer. 1970 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 1971 InputReg = getImplicitArgPtr(DAG, DL); 1972 } 1973 1974 if (OutgoingArg->isRegister()) { 1975 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 1976 } else { 1977 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, StackPtr, 1978 InputReg, 1979 OutgoingArg->getStackOffset()); 1980 MemOpChains.push_back(ArgStore); 1981 } 1982 } 1983 } 1984 1985 static bool canGuaranteeTCO(CallingConv::ID CC) { 1986 return CC == CallingConv::Fast; 1987 } 1988 1989 /// Return true if we might ever do TCO for calls with this calling convention. 1990 static bool mayTailCallThisCC(CallingConv::ID CC) { 1991 switch (CC) { 1992 case CallingConv::C: 1993 return true; 1994 default: 1995 return canGuaranteeTCO(CC); 1996 } 1997 } 1998 1999 bool SITargetLowering::isEligibleForTailCallOptimization( 2000 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2001 const SmallVectorImpl<ISD::OutputArg> &Outs, 2002 const SmallVectorImpl<SDValue> &OutVals, 2003 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2004 if (!mayTailCallThisCC(CalleeCC)) 2005 return false; 2006 2007 MachineFunction &MF = DAG.getMachineFunction(); 2008 const Function *CallerF = MF.getFunction(); 2009 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2010 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2011 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2012 2013 // Kernels aren't callable, and don't have a live in return address so it 2014 // doesn't make sense to do a tail call with entry functions. 2015 if (!CallerPreserved) 2016 return false; 2017 2018 bool CCMatch = CallerCC == CalleeCC; 2019 2020 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2021 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2022 return true; 2023 return false; 2024 } 2025 2026 // TODO: Can we handle var args? 2027 if (IsVarArg) 2028 return false; 2029 2030 for (const Argument &Arg : CallerF->args()) { 2031 if (Arg.hasByValAttr()) 2032 return false; 2033 } 2034 2035 LLVMContext &Ctx = *DAG.getContext(); 2036 2037 // Check that the call results are passed in the same way. 2038 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2039 CCAssignFnForCall(CalleeCC, IsVarArg), 2040 CCAssignFnForCall(CallerCC, IsVarArg))) 2041 return false; 2042 2043 // The callee has to preserve all registers the caller needs to preserve. 2044 if (!CCMatch) { 2045 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2046 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2047 return false; 2048 } 2049 2050 // Nothing more to check if the callee is taking no arguments. 2051 if (Outs.empty()) 2052 return true; 2053 2054 SmallVector<CCValAssign, 16> ArgLocs; 2055 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2056 2057 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2058 2059 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2060 // If the stack arguments for this call do not fit into our own save area then 2061 // the call cannot be made tail. 2062 // TODO: Is this really necessary? 2063 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2064 return false; 2065 2066 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2067 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2068 } 2069 2070 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2071 if (!CI->isTailCall()) 2072 return false; 2073 2074 const Function *ParentFn = CI->getParent()->getParent(); 2075 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2076 return false; 2077 2078 auto Attr = ParentFn->getFnAttribute("disable-tail-calls"); 2079 return (Attr.getValueAsString() != "true"); 2080 } 2081 2082 // The wave scratch offset register is used as the global base pointer. 2083 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2084 SmallVectorImpl<SDValue> &InVals) const { 2085 SelectionDAG &DAG = CLI.DAG; 2086 const SDLoc &DL = CLI.DL; 2087 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2088 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2089 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2090 SDValue Chain = CLI.Chain; 2091 SDValue Callee = CLI.Callee; 2092 bool &IsTailCall = CLI.IsTailCall; 2093 CallingConv::ID CallConv = CLI.CallConv; 2094 bool IsVarArg = CLI.IsVarArg; 2095 bool IsSibCall = false; 2096 bool IsThisReturn = false; 2097 MachineFunction &MF = DAG.getMachineFunction(); 2098 2099 if (IsVarArg) { 2100 return lowerUnhandledCall(CLI, InVals, 2101 "unsupported call to variadic function "); 2102 } 2103 2104 if (!CLI.CS.getCalledFunction()) { 2105 return lowerUnhandledCall(CLI, InVals, 2106 "unsupported indirect call to function "); 2107 } 2108 2109 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2110 return lowerUnhandledCall(CLI, InVals, 2111 "unsupported required tail call to function "); 2112 } 2113 2114 // The first 4 bytes are reserved for the callee's emergency stack slot. 2115 const unsigned CalleeUsableStackOffset = 4; 2116 2117 if (IsTailCall) { 2118 IsTailCall = isEligibleForTailCallOptimization( 2119 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2120 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) { 2121 report_fatal_error("failed to perform tail call elimination on a call " 2122 "site marked musttail"); 2123 } 2124 2125 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2126 2127 // A sibling call is one where we're under the usual C ABI and not planning 2128 // to change that but can still do a tail call: 2129 if (!TailCallOpt && IsTailCall) 2130 IsSibCall = true; 2131 2132 if (IsTailCall) 2133 ++NumTailCalls; 2134 } 2135 2136 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Callee)) { 2137 // FIXME: Remove this hack for function pointer types after removing 2138 // support of old address space mapping. In the new address space 2139 // mapping the pointer in default address space is 64 bit, therefore 2140 // does not need this hack. 2141 if (Callee.getValueType() == MVT::i32) { 2142 const GlobalValue *GV = GA->getGlobal(); 2143 Callee = DAG.getGlobalAddress(GV, DL, MVT::i64, GA->getOffset(), false, 2144 GA->getTargetFlags()); 2145 } 2146 } 2147 assert(Callee.getValueType() == MVT::i64); 2148 2149 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2150 2151 // Analyze operands of the call, assigning locations to each operand. 2152 SmallVector<CCValAssign, 16> ArgLocs; 2153 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2154 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2155 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2156 2157 // Get a count of how many bytes are to be pushed on the stack. 2158 unsigned NumBytes = CCInfo.getNextStackOffset(); 2159 2160 if (IsSibCall) { 2161 // Since we're not changing the ABI to make this a tail call, the memory 2162 // operands are already available in the caller's incoming argument space. 2163 NumBytes = 0; 2164 } 2165 2166 // FPDiff is the byte offset of the call's argument area from the callee's. 2167 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2168 // by this amount for a tail call. In a sibling call it must be 0 because the 2169 // caller will deallocate the entire stack and the callee still expects its 2170 // arguments to begin at SP+0. Completely unused for non-tail calls. 2171 int32_t FPDiff = 0; 2172 MachineFrameInfo &MFI = MF.getFrameInfo(); 2173 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2174 2175 SDValue CallerSavedFP; 2176 2177 // Adjust the stack pointer for the new arguments... 2178 // These operations are automatically eliminated by the prolog/epilog pass 2179 if (!IsSibCall) { 2180 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2181 2182 unsigned OffsetReg = Info->getScratchWaveOffsetReg(); 2183 2184 // In the HSA case, this should be an identity copy. 2185 SDValue ScratchRSrcReg 2186 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2187 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2188 2189 // TODO: Don't hardcode these registers and get from the callee function. 2190 SDValue ScratchWaveOffsetReg 2191 = DAG.getCopyFromReg(Chain, DL, OffsetReg, MVT::i32); 2192 RegsToPass.emplace_back(AMDGPU::SGPR4, ScratchWaveOffsetReg); 2193 2194 if (!Info->isEntryFunction()) { 2195 // Avoid clobbering this function's FP value. In the current convention 2196 // callee will overwrite this, so do save/restore around the call site. 2197 CallerSavedFP = DAG.getCopyFromReg(Chain, DL, 2198 Info->getFrameOffsetReg(), MVT::i32); 2199 } 2200 } 2201 2202 // Stack pointer relative accesses are done by changing the offset SGPR. This 2203 // is just the VGPR offset component. 2204 SDValue StackPtr = DAG.getConstant(CalleeUsableStackOffset, DL, MVT::i32); 2205 2206 SmallVector<SDValue, 8> MemOpChains; 2207 MVT PtrVT = MVT::i32; 2208 2209 // Walk the register/memloc assignments, inserting copies/loads. 2210 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 2211 ++i, ++realArgIdx) { 2212 CCValAssign &VA = ArgLocs[i]; 2213 SDValue Arg = OutVals[realArgIdx]; 2214 2215 // Promote the value if needed. 2216 switch (VA.getLocInfo()) { 2217 case CCValAssign::Full: 2218 break; 2219 case CCValAssign::BCvt: 2220 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2221 break; 2222 case CCValAssign::ZExt: 2223 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2224 break; 2225 case CCValAssign::SExt: 2226 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2227 break; 2228 case CCValAssign::AExt: 2229 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2230 break; 2231 case CCValAssign::FPExt: 2232 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2233 break; 2234 default: 2235 llvm_unreachable("Unknown loc info!"); 2236 } 2237 2238 if (VA.isRegLoc()) { 2239 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2240 } else { 2241 assert(VA.isMemLoc()); 2242 2243 SDValue DstAddr; 2244 MachinePointerInfo DstInfo; 2245 2246 unsigned LocMemOffset = VA.getLocMemOffset(); 2247 int32_t Offset = LocMemOffset; 2248 SDValue PtrOff = DAG.getConstant(Offset, DL, MVT::i32); 2249 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 2250 2251 if (IsTailCall) { 2252 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2253 unsigned OpSize = Flags.isByVal() ? 2254 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2255 2256 Offset = Offset + FPDiff; 2257 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2258 2259 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2260 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, DstAddr, StackPtr); 2261 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2262 2263 // Make sure any stack arguments overlapping with where we're storing 2264 // are loaded before this eventual operation. Otherwise they'll be 2265 // clobbered. 2266 2267 // FIXME: Why is this really necessary? This seems to just result in a 2268 // lot of code to copy the stack and write them back to the same 2269 // locations, which are supposed to be immutable? 2270 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2271 } else { 2272 DstAddr = PtrOff; 2273 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2274 } 2275 2276 if (Outs[i].Flags.isByVal()) { 2277 SDValue SizeNode = 2278 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2279 SDValue Cpy = DAG.getMemcpy( 2280 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 2281 /*isVol = */ false, /*AlwaysInline = */ true, 2282 /*isTailCall = */ false, 2283 DstInfo, MachinePointerInfo()); 2284 2285 MemOpChains.push_back(Cpy); 2286 } else { 2287 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo); 2288 MemOpChains.push_back(Store); 2289 } 2290 } 2291 } 2292 2293 // Copy special input registers after user input arguments. 2294 passSpecialInputs(CLI, *Info, RegsToPass, MemOpChains, Chain, StackPtr); 2295 2296 if (!MemOpChains.empty()) 2297 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2298 2299 // Build a sequence of copy-to-reg nodes chained together with token chain 2300 // and flag operands which copy the outgoing args into the appropriate regs. 2301 SDValue InFlag; 2302 for (auto &RegToPass : RegsToPass) { 2303 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2304 RegToPass.second, InFlag); 2305 InFlag = Chain.getValue(1); 2306 } 2307 2308 2309 SDValue PhysReturnAddrReg; 2310 if (IsTailCall) { 2311 // Since the return is being combined with the call, we need to pass on the 2312 // return address. 2313 2314 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2315 SDValue ReturnAddrReg = CreateLiveInRegister( 2316 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2317 2318 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2319 MVT::i64); 2320 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2321 InFlag = Chain.getValue(1); 2322 } 2323 2324 // We don't usually want to end the call-sequence here because we would tidy 2325 // the frame up *after* the call, however in the ABI-changing tail-call case 2326 // we've carefully laid out the parameters so that when sp is reset they'll be 2327 // in the correct location. 2328 if (IsTailCall && !IsSibCall) { 2329 Chain = DAG.getCALLSEQ_END(Chain, 2330 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2331 DAG.getTargetConstant(0, DL, MVT::i32), 2332 InFlag, DL); 2333 InFlag = Chain.getValue(1); 2334 } 2335 2336 std::vector<SDValue> Ops; 2337 Ops.push_back(Chain); 2338 Ops.push_back(Callee); 2339 2340 if (IsTailCall) { 2341 // Each tail call may have to adjust the stack by a different amount, so 2342 // this information must travel along with the operation for eventual 2343 // consumption by emitEpilogue. 2344 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 2345 2346 Ops.push_back(PhysReturnAddrReg); 2347 } 2348 2349 // Add argument registers to the end of the list so that they are known live 2350 // into the call. 2351 for (auto &RegToPass : RegsToPass) { 2352 Ops.push_back(DAG.getRegister(RegToPass.first, 2353 RegToPass.second.getValueType())); 2354 } 2355 2356 // Add a register mask operand representing the call-preserved registers. 2357 2358 const AMDGPURegisterInfo *TRI = Subtarget->getRegisterInfo(); 2359 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2360 assert(Mask && "Missing call preserved mask for calling convention"); 2361 Ops.push_back(DAG.getRegisterMask(Mask)); 2362 2363 if (InFlag.getNode()) 2364 Ops.push_back(InFlag); 2365 2366 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2367 2368 // If we're doing a tall call, use a TC_RETURN here rather than an 2369 // actual call instruction. 2370 if (IsTailCall) { 2371 MFI.setHasTailCall(); 2372 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 2373 } 2374 2375 // Returns a chain and a flag for retval copy to use. 2376 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 2377 Chain = Call.getValue(0); 2378 InFlag = Call.getValue(1); 2379 2380 if (CallerSavedFP) { 2381 SDValue FPReg = DAG.getRegister(Info->getFrameOffsetReg(), MVT::i32); 2382 Chain = DAG.getCopyToReg(Chain, DL, FPReg, CallerSavedFP, InFlag); 2383 InFlag = Chain.getValue(1); 2384 } 2385 2386 uint64_t CalleePopBytes = NumBytes; 2387 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 2388 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 2389 InFlag, DL); 2390 if (!Ins.empty()) 2391 InFlag = Chain.getValue(1); 2392 2393 // Handle result values, copying them out of physregs into vregs that we 2394 // return. 2395 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 2396 InVals, IsThisReturn, 2397 IsThisReturn ? OutVals[0] : SDValue()); 2398 } 2399 2400 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT, 2401 SelectionDAG &DAG) const { 2402 unsigned Reg = StringSwitch<unsigned>(RegName) 2403 .Case("m0", AMDGPU::M0) 2404 .Case("exec", AMDGPU::EXEC) 2405 .Case("exec_lo", AMDGPU::EXEC_LO) 2406 .Case("exec_hi", AMDGPU::EXEC_HI) 2407 .Case("flat_scratch", AMDGPU::FLAT_SCR) 2408 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 2409 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 2410 .Default(AMDGPU::NoRegister); 2411 2412 if (Reg == AMDGPU::NoRegister) { 2413 report_fatal_error(Twine("invalid register name \"" 2414 + StringRef(RegName) + "\".")); 2415 2416 } 2417 2418 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS && 2419 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 2420 report_fatal_error(Twine("invalid register \"" 2421 + StringRef(RegName) + "\" for subtarget.")); 2422 } 2423 2424 switch (Reg) { 2425 case AMDGPU::M0: 2426 case AMDGPU::EXEC_LO: 2427 case AMDGPU::EXEC_HI: 2428 case AMDGPU::FLAT_SCR_LO: 2429 case AMDGPU::FLAT_SCR_HI: 2430 if (VT.getSizeInBits() == 32) 2431 return Reg; 2432 break; 2433 case AMDGPU::EXEC: 2434 case AMDGPU::FLAT_SCR: 2435 if (VT.getSizeInBits() == 64) 2436 return Reg; 2437 break; 2438 default: 2439 llvm_unreachable("missing register type checking"); 2440 } 2441 2442 report_fatal_error(Twine("invalid type for register \"" 2443 + StringRef(RegName) + "\".")); 2444 } 2445 2446 // If kill is not the last instruction, split the block so kill is always a 2447 // proper terminator. 2448 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 2449 MachineBasicBlock *BB) const { 2450 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 2451 2452 MachineBasicBlock::iterator SplitPoint(&MI); 2453 ++SplitPoint; 2454 2455 if (SplitPoint == BB->end()) { 2456 // Don't bother with a new block. 2457 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 2458 return BB; 2459 } 2460 2461 MachineFunction *MF = BB->getParent(); 2462 MachineBasicBlock *SplitBB 2463 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 2464 2465 MF->insert(++MachineFunction::iterator(BB), SplitBB); 2466 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 2467 2468 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 2469 BB->addSuccessor(SplitBB); 2470 2471 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 2472 return SplitBB; 2473 } 2474 2475 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 2476 // wavefront. If the value is uniform and just happens to be in a VGPR, this 2477 // will only do one iteration. In the worst case, this will loop 64 times. 2478 // 2479 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 2480 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 2481 const SIInstrInfo *TII, 2482 MachineRegisterInfo &MRI, 2483 MachineBasicBlock &OrigBB, 2484 MachineBasicBlock &LoopBB, 2485 const DebugLoc &DL, 2486 const MachineOperand &IdxReg, 2487 unsigned InitReg, 2488 unsigned ResultReg, 2489 unsigned PhiReg, 2490 unsigned InitSaveExecReg, 2491 int Offset, 2492 bool UseGPRIdxMode) { 2493 MachineBasicBlock::iterator I = LoopBB.begin(); 2494 2495 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2496 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2497 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 2498 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2499 2500 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 2501 .addReg(InitReg) 2502 .addMBB(&OrigBB) 2503 .addReg(ResultReg) 2504 .addMBB(&LoopBB); 2505 2506 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 2507 .addReg(InitSaveExecReg) 2508 .addMBB(&OrigBB) 2509 .addReg(NewExec) 2510 .addMBB(&LoopBB); 2511 2512 // Read the next variant <- also loop target. 2513 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 2514 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 2515 2516 // Compare the just read M0 value to all possible Idx values. 2517 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 2518 .addReg(CurrentIdxReg) 2519 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 2520 2521 if (UseGPRIdxMode) { 2522 unsigned IdxReg; 2523 if (Offset == 0) { 2524 IdxReg = CurrentIdxReg; 2525 } else { 2526 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 2527 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 2528 .addReg(CurrentIdxReg, RegState::Kill) 2529 .addImm(Offset); 2530 } 2531 2532 MachineInstr *SetIdx = 2533 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_IDX)) 2534 .addReg(IdxReg, RegState::Kill); 2535 SetIdx->getOperand(2).setIsUndef(); 2536 } else { 2537 // Move index from VCC into M0 2538 if (Offset == 0) { 2539 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 2540 .addReg(CurrentIdxReg, RegState::Kill); 2541 } else { 2542 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 2543 .addReg(CurrentIdxReg, RegState::Kill) 2544 .addImm(Offset); 2545 } 2546 } 2547 2548 // Update EXEC, save the original EXEC value to VCC. 2549 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec) 2550 .addReg(CondReg, RegState::Kill); 2551 2552 MRI.setSimpleHint(NewExec, CondReg); 2553 2554 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 2555 MachineInstr *InsertPt = 2556 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC) 2557 .addReg(AMDGPU::EXEC) 2558 .addReg(NewExec); 2559 2560 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 2561 // s_cbranch_scc0? 2562 2563 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 2564 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 2565 .addMBB(&LoopBB); 2566 2567 return InsertPt->getIterator(); 2568 } 2569 2570 // This has slightly sub-optimal regalloc when the source vector is killed by 2571 // the read. The register allocator does not understand that the kill is 2572 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 2573 // subregister from it, using 1 more VGPR than necessary. This was saved when 2574 // this was expanded after register allocation. 2575 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 2576 MachineBasicBlock &MBB, 2577 MachineInstr &MI, 2578 unsigned InitResultReg, 2579 unsigned PhiReg, 2580 int Offset, 2581 bool UseGPRIdxMode) { 2582 MachineFunction *MF = MBB.getParent(); 2583 MachineRegisterInfo &MRI = MF->getRegInfo(); 2584 const DebugLoc &DL = MI.getDebugLoc(); 2585 MachineBasicBlock::iterator I(&MI); 2586 2587 unsigned DstReg = MI.getOperand(0).getReg(); 2588 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2589 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2590 2591 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 2592 2593 // Save the EXEC mask 2594 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec) 2595 .addReg(AMDGPU::EXEC); 2596 2597 // To insert the loop we need to split the block. Move everything after this 2598 // point to a new block, and insert a new empty block between the two. 2599 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 2600 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 2601 MachineFunction::iterator MBBI(MBB); 2602 ++MBBI; 2603 2604 MF->insert(MBBI, LoopBB); 2605 MF->insert(MBBI, RemainderBB); 2606 2607 LoopBB->addSuccessor(LoopBB); 2608 LoopBB->addSuccessor(RemainderBB); 2609 2610 // Move the rest of the block into a new block. 2611 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 2612 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 2613 2614 MBB.addSuccessor(LoopBB); 2615 2616 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 2617 2618 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 2619 InitResultReg, DstReg, PhiReg, TmpExec, 2620 Offset, UseGPRIdxMode); 2621 2622 MachineBasicBlock::iterator First = RemainderBB->begin(); 2623 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC) 2624 .addReg(SaveExec); 2625 2626 return InsPt; 2627 } 2628 2629 // Returns subreg index, offset 2630 static std::pair<unsigned, int> 2631 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 2632 const TargetRegisterClass *SuperRC, 2633 unsigned VecReg, 2634 int Offset) { 2635 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 2636 2637 // Skip out of bounds offsets, or else we would end up using an undefined 2638 // register. 2639 if (Offset >= NumElts || Offset < 0) 2640 return std::make_pair(AMDGPU::sub0, Offset); 2641 2642 return std::make_pair(AMDGPU::sub0 + Offset, 0); 2643 } 2644 2645 // Return true if the index is an SGPR and was set. 2646 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 2647 MachineRegisterInfo &MRI, 2648 MachineInstr &MI, 2649 int Offset, 2650 bool UseGPRIdxMode, 2651 bool IsIndirectSrc) { 2652 MachineBasicBlock *MBB = MI.getParent(); 2653 const DebugLoc &DL = MI.getDebugLoc(); 2654 MachineBasicBlock::iterator I(&MI); 2655 2656 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 2657 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 2658 2659 assert(Idx->getReg() != AMDGPU::NoRegister); 2660 2661 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 2662 return false; 2663 2664 if (UseGPRIdxMode) { 2665 unsigned IdxMode = IsIndirectSrc ? 2666 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE; 2667 if (Offset == 0) { 2668 MachineInstr *SetOn = 2669 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2670 .add(*Idx) 2671 .addImm(IdxMode); 2672 2673 SetOn->getOperand(3).setIsUndef(); 2674 } else { 2675 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 2676 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 2677 .add(*Idx) 2678 .addImm(Offset); 2679 MachineInstr *SetOn = 2680 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2681 .addReg(Tmp, RegState::Kill) 2682 .addImm(IdxMode); 2683 2684 SetOn->getOperand(3).setIsUndef(); 2685 } 2686 2687 return true; 2688 } 2689 2690 if (Offset == 0) { 2691 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 2692 .add(*Idx); 2693 } else { 2694 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 2695 .add(*Idx) 2696 .addImm(Offset); 2697 } 2698 2699 return true; 2700 } 2701 2702 // Control flow needs to be inserted if indexing with a VGPR. 2703 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 2704 MachineBasicBlock &MBB, 2705 const SISubtarget &ST) { 2706 const SIInstrInfo *TII = ST.getInstrInfo(); 2707 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 2708 MachineFunction *MF = MBB.getParent(); 2709 MachineRegisterInfo &MRI = MF->getRegInfo(); 2710 2711 unsigned Dst = MI.getOperand(0).getReg(); 2712 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 2713 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 2714 2715 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 2716 2717 unsigned SubReg; 2718 std::tie(SubReg, Offset) 2719 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 2720 2721 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 2722 2723 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 2724 MachineBasicBlock::iterator I(&MI); 2725 const DebugLoc &DL = MI.getDebugLoc(); 2726 2727 if (UseGPRIdxMode) { 2728 // TODO: Look at the uses to avoid the copy. This may require rescheduling 2729 // to avoid interfering with other uses, so probably requires a new 2730 // optimization pass. 2731 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 2732 .addReg(SrcReg, RegState::Undef, SubReg) 2733 .addReg(SrcReg, RegState::Implicit) 2734 .addReg(AMDGPU::M0, RegState::Implicit); 2735 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2736 } else { 2737 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 2738 .addReg(SrcReg, RegState::Undef, SubReg) 2739 .addReg(SrcReg, RegState::Implicit); 2740 } 2741 2742 MI.eraseFromParent(); 2743 2744 return &MBB; 2745 } 2746 2747 const DebugLoc &DL = MI.getDebugLoc(); 2748 MachineBasicBlock::iterator I(&MI); 2749 2750 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 2751 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 2752 2753 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 2754 2755 if (UseGPRIdxMode) { 2756 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2757 .addImm(0) // Reset inside loop. 2758 .addImm(VGPRIndexMode::SRC0_ENABLE); 2759 SetOn->getOperand(3).setIsUndef(); 2760 2761 // Disable again after the loop. 2762 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2763 } 2764 2765 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, UseGPRIdxMode); 2766 MachineBasicBlock *LoopBB = InsPt->getParent(); 2767 2768 if (UseGPRIdxMode) { 2769 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 2770 .addReg(SrcReg, RegState::Undef, SubReg) 2771 .addReg(SrcReg, RegState::Implicit) 2772 .addReg(AMDGPU::M0, RegState::Implicit); 2773 } else { 2774 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 2775 .addReg(SrcReg, RegState::Undef, SubReg) 2776 .addReg(SrcReg, RegState::Implicit); 2777 } 2778 2779 MI.eraseFromParent(); 2780 2781 return LoopBB; 2782 } 2783 2784 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI, 2785 const TargetRegisterClass *VecRC) { 2786 switch (TRI.getRegSizeInBits(*VecRC)) { 2787 case 32: // 4 bytes 2788 return AMDGPU::V_MOVRELD_B32_V1; 2789 case 64: // 8 bytes 2790 return AMDGPU::V_MOVRELD_B32_V2; 2791 case 128: // 16 bytes 2792 return AMDGPU::V_MOVRELD_B32_V4; 2793 case 256: // 32 bytes 2794 return AMDGPU::V_MOVRELD_B32_V8; 2795 case 512: // 64 bytes 2796 return AMDGPU::V_MOVRELD_B32_V16; 2797 default: 2798 llvm_unreachable("unsupported size for MOVRELD pseudos"); 2799 } 2800 } 2801 2802 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 2803 MachineBasicBlock &MBB, 2804 const SISubtarget &ST) { 2805 const SIInstrInfo *TII = ST.getInstrInfo(); 2806 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 2807 MachineFunction *MF = MBB.getParent(); 2808 MachineRegisterInfo &MRI = MF->getRegInfo(); 2809 2810 unsigned Dst = MI.getOperand(0).getReg(); 2811 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 2812 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 2813 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 2814 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 2815 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 2816 2817 // This can be an immediate, but will be folded later. 2818 assert(Val->getReg()); 2819 2820 unsigned SubReg; 2821 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 2822 SrcVec->getReg(), 2823 Offset); 2824 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 2825 2826 if (Idx->getReg() == AMDGPU::NoRegister) { 2827 MachineBasicBlock::iterator I(&MI); 2828 const DebugLoc &DL = MI.getDebugLoc(); 2829 2830 assert(Offset == 0); 2831 2832 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 2833 .add(*SrcVec) 2834 .add(*Val) 2835 .addImm(SubReg); 2836 2837 MI.eraseFromParent(); 2838 return &MBB; 2839 } 2840 2841 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 2842 MachineBasicBlock::iterator I(&MI); 2843 const DebugLoc &DL = MI.getDebugLoc(); 2844 2845 if (UseGPRIdxMode) { 2846 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 2847 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst 2848 .add(*Val) 2849 .addReg(Dst, RegState::ImplicitDefine) 2850 .addReg(SrcVec->getReg(), RegState::Implicit) 2851 .addReg(AMDGPU::M0, RegState::Implicit); 2852 2853 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2854 } else { 2855 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 2856 2857 BuildMI(MBB, I, DL, MovRelDesc) 2858 .addReg(Dst, RegState::Define) 2859 .addReg(SrcVec->getReg()) 2860 .add(*Val) 2861 .addImm(SubReg - AMDGPU::sub0); 2862 } 2863 2864 MI.eraseFromParent(); 2865 return &MBB; 2866 } 2867 2868 if (Val->isReg()) 2869 MRI.clearKillFlags(Val->getReg()); 2870 2871 const DebugLoc &DL = MI.getDebugLoc(); 2872 2873 if (UseGPRIdxMode) { 2874 MachineBasicBlock::iterator I(&MI); 2875 2876 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2877 .addImm(0) // Reset inside loop. 2878 .addImm(VGPRIndexMode::DST_ENABLE); 2879 SetOn->getOperand(3).setIsUndef(); 2880 2881 // Disable again after the loop. 2882 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2883 } 2884 2885 unsigned PhiReg = MRI.createVirtualRegister(VecRC); 2886 2887 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 2888 Offset, UseGPRIdxMode); 2889 MachineBasicBlock *LoopBB = InsPt->getParent(); 2890 2891 if (UseGPRIdxMode) { 2892 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 2893 .addReg(PhiReg, RegState::Undef, SubReg) // vdst 2894 .add(*Val) // src0 2895 .addReg(Dst, RegState::ImplicitDefine) 2896 .addReg(PhiReg, RegState::Implicit) 2897 .addReg(AMDGPU::M0, RegState::Implicit); 2898 } else { 2899 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 2900 2901 BuildMI(*LoopBB, InsPt, DL, MovRelDesc) 2902 .addReg(Dst, RegState::Define) 2903 .addReg(PhiReg) 2904 .add(*Val) 2905 .addImm(SubReg - AMDGPU::sub0); 2906 } 2907 2908 MI.eraseFromParent(); 2909 2910 return LoopBB; 2911 } 2912 2913 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 2914 MachineInstr &MI, MachineBasicBlock *BB) const { 2915 2916 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 2917 MachineFunction *MF = BB->getParent(); 2918 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 2919 2920 if (TII->isMIMG(MI)) { 2921 if (!MI.memoperands_empty()) 2922 return BB; 2923 // Add a memoperand for mimg instructions so that they aren't assumed to 2924 // be ordered memory instuctions. 2925 2926 MachinePointerInfo PtrInfo(MFI->getImagePSV()); 2927 MachineMemOperand::Flags Flags = MachineMemOperand::MODereferenceable; 2928 if (MI.mayStore()) 2929 Flags |= MachineMemOperand::MOStore; 2930 2931 if (MI.mayLoad()) 2932 Flags |= MachineMemOperand::MOLoad; 2933 2934 auto MMO = MF->getMachineMemOperand(PtrInfo, Flags, 0, 0); 2935 MI.addMemOperand(*MF, MMO); 2936 return BB; 2937 } 2938 2939 switch (MI.getOpcode()) { 2940 case AMDGPU::SI_INIT_M0: 2941 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 2942 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 2943 .add(MI.getOperand(0)); 2944 MI.eraseFromParent(); 2945 return BB; 2946 2947 case AMDGPU::SI_INIT_EXEC: 2948 // This should be before all vector instructions. 2949 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 2950 AMDGPU::EXEC) 2951 .addImm(MI.getOperand(0).getImm()); 2952 MI.eraseFromParent(); 2953 return BB; 2954 2955 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 2956 // Extract the thread count from an SGPR input and set EXEC accordingly. 2957 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 2958 // 2959 // S_BFE_U32 count, input, {shift, 7} 2960 // S_BFM_B64 exec, count, 0 2961 // S_CMP_EQ_U32 count, 64 2962 // S_CMOV_B64 exec, -1 2963 MachineInstr *FirstMI = &*BB->begin(); 2964 MachineRegisterInfo &MRI = MF->getRegInfo(); 2965 unsigned InputReg = MI.getOperand(0).getReg(); 2966 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 2967 bool Found = false; 2968 2969 // Move the COPY of the input reg to the beginning, so that we can use it. 2970 for (auto I = BB->begin(); I != &MI; I++) { 2971 if (I->getOpcode() != TargetOpcode::COPY || 2972 I->getOperand(0).getReg() != InputReg) 2973 continue; 2974 2975 if (I == FirstMI) { 2976 FirstMI = &*++BB->begin(); 2977 } else { 2978 I->removeFromParent(); 2979 BB->insert(FirstMI, &*I); 2980 } 2981 Found = true; 2982 break; 2983 } 2984 assert(Found); 2985 (void)Found; 2986 2987 // This should be before all vector instructions. 2988 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 2989 .addReg(InputReg) 2990 .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000); 2991 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64), 2992 AMDGPU::EXEC) 2993 .addReg(CountReg) 2994 .addImm(0); 2995 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 2996 .addReg(CountReg, RegState::Kill) 2997 .addImm(64); 2998 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64), 2999 AMDGPU::EXEC) 3000 .addImm(-1); 3001 MI.eraseFromParent(); 3002 return BB; 3003 } 3004 3005 case AMDGPU::GET_GROUPSTATICSIZE: { 3006 DebugLoc DL = MI.getDebugLoc(); 3007 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3008 .add(MI.getOperand(0)) 3009 .addImm(MFI->getLDSSize()); 3010 MI.eraseFromParent(); 3011 return BB; 3012 } 3013 case AMDGPU::SI_INDIRECT_SRC_V1: 3014 case AMDGPU::SI_INDIRECT_SRC_V2: 3015 case AMDGPU::SI_INDIRECT_SRC_V4: 3016 case AMDGPU::SI_INDIRECT_SRC_V8: 3017 case AMDGPU::SI_INDIRECT_SRC_V16: 3018 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3019 case AMDGPU::SI_INDIRECT_DST_V1: 3020 case AMDGPU::SI_INDIRECT_DST_V2: 3021 case AMDGPU::SI_INDIRECT_DST_V4: 3022 case AMDGPU::SI_INDIRECT_DST_V8: 3023 case AMDGPU::SI_INDIRECT_DST_V16: 3024 return emitIndirectDst(MI, *BB, *getSubtarget()); 3025 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3026 case AMDGPU::SI_KILL_I1_PSEUDO: 3027 return splitKillBlock(MI, BB); 3028 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3029 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3030 3031 unsigned Dst = MI.getOperand(0).getReg(); 3032 unsigned Src0 = MI.getOperand(1).getReg(); 3033 unsigned Src1 = MI.getOperand(2).getReg(); 3034 const DebugLoc &DL = MI.getDebugLoc(); 3035 unsigned SrcCond = MI.getOperand(3).getReg(); 3036 3037 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3038 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3039 unsigned SrcCondCopy = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass); 3040 3041 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3042 .addReg(SrcCond); 3043 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3044 .addReg(Src0, 0, AMDGPU::sub0) 3045 .addReg(Src1, 0, AMDGPU::sub0) 3046 .addReg(SrcCondCopy); 3047 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3048 .addReg(Src0, 0, AMDGPU::sub1) 3049 .addReg(Src1, 0, AMDGPU::sub1) 3050 .addReg(SrcCondCopy); 3051 3052 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3053 .addReg(DstLo) 3054 .addImm(AMDGPU::sub0) 3055 .addReg(DstHi) 3056 .addImm(AMDGPU::sub1); 3057 MI.eraseFromParent(); 3058 return BB; 3059 } 3060 case AMDGPU::SI_BR_UNDEF: { 3061 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3062 const DebugLoc &DL = MI.getDebugLoc(); 3063 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3064 .add(MI.getOperand(0)); 3065 Br->getOperand(1).setIsUndef(true); // read undef SCC 3066 MI.eraseFromParent(); 3067 return BB; 3068 } 3069 case AMDGPU::ADJCALLSTACKUP: 3070 case AMDGPU::ADJCALLSTACKDOWN: { 3071 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3072 MachineInstrBuilder MIB(*MF, &MI); 3073 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3074 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 3075 return BB; 3076 } 3077 case AMDGPU::SI_CALL_ISEL: 3078 case AMDGPU::SI_TCRETURN_ISEL: { 3079 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3080 const DebugLoc &DL = MI.getDebugLoc(); 3081 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3082 3083 MachineRegisterInfo &MRI = MF->getRegInfo(); 3084 unsigned GlobalAddrReg = MI.getOperand(0).getReg(); 3085 MachineInstr *PCRel = MRI.getVRegDef(GlobalAddrReg); 3086 assert(PCRel->getOpcode() == AMDGPU::SI_PC_ADD_REL_OFFSET); 3087 3088 const GlobalValue *G = PCRel->getOperand(1).getGlobal(); 3089 3090 MachineInstrBuilder MIB; 3091 if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) { 3092 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg) 3093 .add(MI.getOperand(0)) 3094 .addGlobalAddress(G); 3095 } else { 3096 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_TCRETURN)) 3097 .add(MI.getOperand(0)) 3098 .addGlobalAddress(G); 3099 3100 // There is an additional imm operand for tcreturn, but it should be in the 3101 // right place already. 3102 } 3103 3104 for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I) 3105 MIB.add(MI.getOperand(I)); 3106 3107 MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end()); 3108 MI.eraseFromParent(); 3109 return BB; 3110 } 3111 default: 3112 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3113 } 3114 } 3115 3116 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 3117 return isTypeLegal(VT.getScalarType()); 3118 } 3119 3120 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3121 // This currently forces unfolding various combinations of fsub into fma with 3122 // free fneg'd operands. As long as we have fast FMA (controlled by 3123 // isFMAFasterThanFMulAndFAdd), we should perform these. 3124 3125 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3126 // most of these combines appear to be cycle neutral but save on instruction 3127 // count / code size. 3128 return true; 3129 } 3130 3131 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3132 EVT VT) const { 3133 if (!VT.isVector()) { 3134 return MVT::i1; 3135 } 3136 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3137 } 3138 3139 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3140 // TODO: Should i16 be used always if legal? For now it would force VALU 3141 // shifts. 3142 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3143 } 3144 3145 // Answering this is somewhat tricky and depends on the specific device which 3146 // have different rates for fma or all f64 operations. 3147 // 3148 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3149 // regardless of which device (although the number of cycles differs between 3150 // devices), so it is always profitable for f64. 3151 // 3152 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3153 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3154 // which we can always do even without fused FP ops since it returns the same 3155 // result as the separate operations and since it is always full 3156 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3157 // however does not support denormals, so we do report fma as faster if we have 3158 // a fast fma device and require denormals. 3159 // 3160 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 3161 VT = VT.getScalarType(); 3162 3163 switch (VT.getSimpleVT().SimpleTy) { 3164 case MVT::f32: 3165 // This is as fast on some subtargets. However, we always have full rate f32 3166 // mad available which returns the same result as the separate operations 3167 // which we should prefer over fma. We can't use this if we want to support 3168 // denormals, so only report this in these cases. 3169 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32(); 3170 case MVT::f64: 3171 return true; 3172 case MVT::f16: 3173 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals(); 3174 default: 3175 break; 3176 } 3177 3178 return false; 3179 } 3180 3181 //===----------------------------------------------------------------------===// 3182 // Custom DAG Lowering Operations 3183 //===----------------------------------------------------------------------===// 3184 3185 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 3186 switch (Op.getOpcode()) { 3187 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 3188 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 3189 case ISD::LOAD: { 3190 SDValue Result = LowerLOAD(Op, DAG); 3191 assert((!Result.getNode() || 3192 Result.getNode()->getNumValues() == 2) && 3193 "Load should return a value and a chain"); 3194 return Result; 3195 } 3196 3197 case ISD::FSIN: 3198 case ISD::FCOS: 3199 return LowerTrig(Op, DAG); 3200 case ISD::SELECT: return LowerSELECT(Op, DAG); 3201 case ISD::FDIV: return LowerFDIV(Op, DAG); 3202 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 3203 case ISD::STORE: return LowerSTORE(Op, DAG); 3204 case ISD::GlobalAddress: { 3205 MachineFunction &MF = DAG.getMachineFunction(); 3206 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 3207 return LowerGlobalAddress(MFI, Op, DAG); 3208 } 3209 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3210 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 3211 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 3212 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 3213 case ISD::INSERT_VECTOR_ELT: 3214 return lowerINSERT_VECTOR_ELT(Op, DAG); 3215 case ISD::EXTRACT_VECTOR_ELT: 3216 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3217 case ISD::FP_ROUND: 3218 return lowerFP_ROUND(Op, DAG); 3219 3220 case ISD::TRAP: 3221 case ISD::DEBUGTRAP: 3222 return lowerTRAP(Op, DAG); 3223 } 3224 return SDValue(); 3225 } 3226 3227 void SITargetLowering::ReplaceNodeResults(SDNode *N, 3228 SmallVectorImpl<SDValue> &Results, 3229 SelectionDAG &DAG) const { 3230 switch (N->getOpcode()) { 3231 case ISD::INSERT_VECTOR_ELT: { 3232 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 3233 Results.push_back(Res); 3234 return; 3235 } 3236 case ISD::EXTRACT_VECTOR_ELT: { 3237 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 3238 Results.push_back(Res); 3239 return; 3240 } 3241 case ISD::INTRINSIC_WO_CHAIN: { 3242 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 3243 if (IID == Intrinsic::amdgcn_cvt_pkrtz) { 3244 SDValue Src0 = N->getOperand(1); 3245 SDValue Src1 = N->getOperand(2); 3246 SDLoc SL(N); 3247 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 3248 Src0, Src1); 3249 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 3250 return; 3251 } 3252 break; 3253 } 3254 case ISD::SELECT: { 3255 SDLoc SL(N); 3256 EVT VT = N->getValueType(0); 3257 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 3258 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 3259 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 3260 3261 EVT SelectVT = NewVT; 3262 if (NewVT.bitsLT(MVT::i32)) { 3263 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 3264 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 3265 SelectVT = MVT::i32; 3266 } 3267 3268 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 3269 N->getOperand(0), LHS, RHS); 3270 3271 if (NewVT != SelectVT) 3272 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 3273 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 3274 return; 3275 } 3276 default: 3277 break; 3278 } 3279 } 3280 3281 /// \brief Helper function for LowerBRCOND 3282 static SDNode *findUser(SDValue Value, unsigned Opcode) { 3283 3284 SDNode *Parent = Value.getNode(); 3285 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 3286 I != E; ++I) { 3287 3288 if (I.getUse().get() != Value) 3289 continue; 3290 3291 if (I->getOpcode() == Opcode) 3292 return *I; 3293 } 3294 return nullptr; 3295 } 3296 3297 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 3298 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 3299 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 3300 case Intrinsic::amdgcn_if: 3301 return AMDGPUISD::IF; 3302 case Intrinsic::amdgcn_else: 3303 return AMDGPUISD::ELSE; 3304 case Intrinsic::amdgcn_loop: 3305 return AMDGPUISD::LOOP; 3306 case Intrinsic::amdgcn_end_cf: 3307 llvm_unreachable("should not occur"); 3308 default: 3309 return 0; 3310 } 3311 } 3312 3313 // break, if_break, else_break are all only used as inputs to loop, not 3314 // directly as branch conditions. 3315 return 0; 3316 } 3317 3318 void SITargetLowering::createDebuggerPrologueStackObjects( 3319 MachineFunction &MF) const { 3320 // Create stack objects that are used for emitting debugger prologue. 3321 // 3322 // Debugger prologue writes work group IDs and work item IDs to scratch memory 3323 // at fixed location in the following format: 3324 // offset 0: work group ID x 3325 // offset 4: work group ID y 3326 // offset 8: work group ID z 3327 // offset 16: work item ID x 3328 // offset 20: work item ID y 3329 // offset 24: work item ID z 3330 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3331 int ObjectIdx = 0; 3332 3333 // For each dimension: 3334 for (unsigned i = 0; i < 3; ++i) { 3335 // Create fixed stack object for work group ID. 3336 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true); 3337 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx); 3338 // Create fixed stack object for work item ID. 3339 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true); 3340 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx); 3341 } 3342 } 3343 3344 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 3345 const Triple &TT = getTargetMachine().getTargetTriple(); 3346 return GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS && 3347 AMDGPU::shouldEmitConstantsToTextSection(TT); 3348 } 3349 3350 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 3351 return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS || 3352 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) && 3353 !shouldEmitFixup(GV) && 3354 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3355 } 3356 3357 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 3358 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 3359 } 3360 3361 /// This transforms the control flow intrinsics to get the branch destination as 3362 /// last parameter, also switches branch target with BR if the need arise 3363 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 3364 SelectionDAG &DAG) const { 3365 SDLoc DL(BRCOND); 3366 3367 SDNode *Intr = BRCOND.getOperand(1).getNode(); 3368 SDValue Target = BRCOND.getOperand(2); 3369 SDNode *BR = nullptr; 3370 SDNode *SetCC = nullptr; 3371 3372 if (Intr->getOpcode() == ISD::SETCC) { 3373 // As long as we negate the condition everything is fine 3374 SetCC = Intr; 3375 Intr = SetCC->getOperand(0).getNode(); 3376 3377 } else { 3378 // Get the target from BR if we don't negate the condition 3379 BR = findUser(BRCOND, ISD::BR); 3380 Target = BR->getOperand(1); 3381 } 3382 3383 // FIXME: This changes the types of the intrinsics instead of introducing new 3384 // nodes with the correct types. 3385 // e.g. llvm.amdgcn.loop 3386 3387 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 3388 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 3389 3390 unsigned CFNode = isCFIntrinsic(Intr); 3391 if (CFNode == 0) { 3392 // This is a uniform branch so we don't need to legalize. 3393 return BRCOND; 3394 } 3395 3396 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 3397 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 3398 3399 assert(!SetCC || 3400 (SetCC->getConstantOperandVal(1) == 1 && 3401 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 3402 ISD::SETNE)); 3403 3404 // operands of the new intrinsic call 3405 SmallVector<SDValue, 4> Ops; 3406 if (HaveChain) 3407 Ops.push_back(BRCOND.getOperand(0)); 3408 3409 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 3410 Ops.push_back(Target); 3411 3412 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 3413 3414 // build the new intrinsic call 3415 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 3416 3417 if (!HaveChain) { 3418 SDValue Ops[] = { 3419 SDValue(Result, 0), 3420 BRCOND.getOperand(0) 3421 }; 3422 3423 Result = DAG.getMergeValues(Ops, DL).getNode(); 3424 } 3425 3426 if (BR) { 3427 // Give the branch instruction our target 3428 SDValue Ops[] = { 3429 BR->getOperand(0), 3430 BRCOND.getOperand(2) 3431 }; 3432 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 3433 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 3434 BR = NewBR.getNode(); 3435 } 3436 3437 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 3438 3439 // Copy the intrinsic results to registers 3440 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 3441 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 3442 if (!CopyToReg) 3443 continue; 3444 3445 Chain = DAG.getCopyToReg( 3446 Chain, DL, 3447 CopyToReg->getOperand(1), 3448 SDValue(Result, i - 1), 3449 SDValue()); 3450 3451 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 3452 } 3453 3454 // Remove the old intrinsic from the chain 3455 DAG.ReplaceAllUsesOfValueWith( 3456 SDValue(Intr, Intr->getNumValues() - 1), 3457 Intr->getOperand(0)); 3458 3459 return Chain; 3460 } 3461 3462 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 3463 SDValue Op, 3464 const SDLoc &DL, 3465 EVT VT) const { 3466 return Op.getValueType().bitsLE(VT) ? 3467 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 3468 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 3469 } 3470 3471 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 3472 assert(Op.getValueType() == MVT::f16 && 3473 "Do not know how to custom lower FP_ROUND for non-f16 type"); 3474 3475 SDValue Src = Op.getOperand(0); 3476 EVT SrcVT = Src.getValueType(); 3477 if (SrcVT != MVT::f64) 3478 return Op; 3479 3480 SDLoc DL(Op); 3481 3482 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 3483 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 3484 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 3485 } 3486 3487 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 3488 SDLoc SL(Op); 3489 MachineFunction &MF = DAG.getMachineFunction(); 3490 SDValue Chain = Op.getOperand(0); 3491 3492 unsigned TrapID = Op.getOpcode() == ISD::DEBUGTRAP ? 3493 SISubtarget::TrapIDLLVMDebugTrap : SISubtarget::TrapIDLLVMTrap; 3494 3495 if (Subtarget->getTrapHandlerAbi() == SISubtarget::TrapHandlerAbiHsa && 3496 Subtarget->isTrapHandlerEnabled()) { 3497 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3498 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 3499 assert(UserSGPR != AMDGPU::NoRegister); 3500 3501 SDValue QueuePtr = CreateLiveInRegister( 3502 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 3503 3504 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 3505 3506 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 3507 QueuePtr, SDValue()); 3508 3509 SDValue Ops[] = { 3510 ToReg, 3511 DAG.getTargetConstant(TrapID, SL, MVT::i16), 3512 SGPR01, 3513 ToReg.getValue(1) 3514 }; 3515 3516 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 3517 } 3518 3519 switch (TrapID) { 3520 case SISubtarget::TrapIDLLVMTrap: 3521 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 3522 case SISubtarget::TrapIDLLVMDebugTrap: { 3523 DiagnosticInfoUnsupported NoTrap(*MF.getFunction(), 3524 "debugtrap handler not supported", 3525 Op.getDebugLoc(), 3526 DS_Warning); 3527 LLVMContext &Ctx = MF.getFunction()->getContext(); 3528 Ctx.diagnose(NoTrap); 3529 return Chain; 3530 } 3531 default: 3532 llvm_unreachable("unsupported trap handler type!"); 3533 } 3534 3535 return Chain; 3536 } 3537 3538 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 3539 SelectionDAG &DAG) const { 3540 // FIXME: Use inline constants (src_{shared, private}_base) instead. 3541 if (Subtarget->hasApertureRegs()) { 3542 unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ? 3543 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 3544 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 3545 unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ? 3546 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 3547 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 3548 unsigned Encoding = 3549 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 3550 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 3551 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 3552 3553 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 3554 SDValue ApertureReg = SDValue( 3555 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 3556 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 3557 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 3558 } 3559 3560 MachineFunction &MF = DAG.getMachineFunction(); 3561 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3562 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 3563 assert(UserSGPR != AMDGPU::NoRegister); 3564 3565 SDValue QueuePtr = CreateLiveInRegister( 3566 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 3567 3568 // Offset into amd_queue_t for group_segment_aperture_base_hi / 3569 // private_segment_aperture_base_hi. 3570 uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44; 3571 3572 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, QueuePtr, 3573 DAG.getConstant(StructOffset, DL, MVT::i64)); 3574 3575 // TODO: Use custom target PseudoSourceValue. 3576 // TODO: We should use the value from the IR intrinsic call, but it might not 3577 // be available and how do we get it? 3578 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()), 3579 AMDGPUASI.CONSTANT_ADDRESS)); 3580 3581 MachinePointerInfo PtrInfo(V, StructOffset); 3582 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 3583 MinAlign(64, StructOffset), 3584 MachineMemOperand::MODereferenceable | 3585 MachineMemOperand::MOInvariant); 3586 } 3587 3588 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 3589 SelectionDAG &DAG) const { 3590 SDLoc SL(Op); 3591 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 3592 3593 SDValue Src = ASC->getOperand(0); 3594 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 3595 3596 const AMDGPUTargetMachine &TM = 3597 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 3598 3599 // flat -> local/private 3600 if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) { 3601 unsigned DestAS = ASC->getDestAddressSpace(); 3602 3603 if (DestAS == AMDGPUASI.LOCAL_ADDRESS || 3604 DestAS == AMDGPUASI.PRIVATE_ADDRESS) { 3605 unsigned NullVal = TM.getNullPointerValue(DestAS); 3606 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 3607 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 3608 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 3609 3610 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 3611 NonNull, Ptr, SegmentNullPtr); 3612 } 3613 } 3614 3615 // local/private -> flat 3616 if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) { 3617 unsigned SrcAS = ASC->getSrcAddressSpace(); 3618 3619 if (SrcAS == AMDGPUASI.LOCAL_ADDRESS || 3620 SrcAS == AMDGPUASI.PRIVATE_ADDRESS) { 3621 unsigned NullVal = TM.getNullPointerValue(SrcAS); 3622 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 3623 3624 SDValue NonNull 3625 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 3626 3627 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 3628 SDValue CvtPtr 3629 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 3630 3631 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 3632 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 3633 FlatNullPtr); 3634 } 3635 } 3636 3637 // global <-> flat are no-ops and never emitted. 3638 3639 const MachineFunction &MF = DAG.getMachineFunction(); 3640 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 3641 *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 3642 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 3643 3644 return DAG.getUNDEF(ASC->getValueType(0)); 3645 } 3646 3647 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 3648 SelectionDAG &DAG) const { 3649 SDValue Idx = Op.getOperand(2); 3650 if (isa<ConstantSDNode>(Idx)) 3651 return SDValue(); 3652 3653 // Avoid stack access for dynamic indexing. 3654 SDLoc SL(Op); 3655 SDValue Vec = Op.getOperand(0); 3656 SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1)); 3657 3658 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 3659 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val); 3660 3661 // Convert vector index to bit-index. 3662 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, 3663 DAG.getConstant(16, SL, MVT::i32)); 3664 3665 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 3666 3667 SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32, 3668 DAG.getConstant(0xffff, SL, MVT::i32), 3669 ScaledIdx); 3670 3671 SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal); 3672 SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32, 3673 DAG.getNOT(SL, BFM, MVT::i32), BCVec); 3674 3675 SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS); 3676 return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI); 3677 } 3678 3679 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 3680 SelectionDAG &DAG) const { 3681 SDLoc SL(Op); 3682 3683 EVT ResultVT = Op.getValueType(); 3684 SDValue Vec = Op.getOperand(0); 3685 SDValue Idx = Op.getOperand(1); 3686 3687 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 3688 3689 // Make sure we we do any optimizations that will make it easier to fold 3690 // source modifiers before obscuring it with bit operations. 3691 3692 // XXX - Why doesn't this get called when vector_shuffle is expanded? 3693 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 3694 return Combined; 3695 3696 if (const ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) { 3697 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 3698 3699 if (CIdx->getZExtValue() == 1) { 3700 Result = DAG.getNode(ISD::SRL, SL, MVT::i32, Result, 3701 DAG.getConstant(16, SL, MVT::i32)); 3702 } else { 3703 assert(CIdx->getZExtValue() == 0); 3704 } 3705 3706 if (ResultVT.bitsLT(MVT::i32)) 3707 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result); 3708 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 3709 } 3710 3711 SDValue Sixteen = DAG.getConstant(16, SL, MVT::i32); 3712 3713 // Convert vector index to bit-index. 3714 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Sixteen); 3715 3716 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 3717 SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx); 3718 3719 SDValue Result = Elt; 3720 if (ResultVT.bitsLT(MVT::i32)) 3721 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result); 3722 3723 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 3724 } 3725 3726 bool 3727 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 3728 // We can fold offsets for anything that doesn't require a GOT relocation. 3729 return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS || 3730 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) && 3731 !shouldEmitGOTReloc(GA->getGlobal()); 3732 } 3733 3734 static SDValue 3735 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 3736 const SDLoc &DL, unsigned Offset, EVT PtrVT, 3737 unsigned GAFlags = SIInstrInfo::MO_NONE) { 3738 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 3739 // lowered to the following code sequence: 3740 // 3741 // For constant address space: 3742 // s_getpc_b64 s[0:1] 3743 // s_add_u32 s0, s0, $symbol 3744 // s_addc_u32 s1, s1, 0 3745 // 3746 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 3747 // a fixup or relocation is emitted to replace $symbol with a literal 3748 // constant, which is a pc-relative offset from the encoding of the $symbol 3749 // operand to the global variable. 3750 // 3751 // For global address space: 3752 // s_getpc_b64 s[0:1] 3753 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 3754 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 3755 // 3756 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 3757 // fixups or relocations are emitted to replace $symbol@*@lo and 3758 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 3759 // which is a 64-bit pc-relative offset from the encoding of the $symbol 3760 // operand to the global variable. 3761 // 3762 // What we want here is an offset from the value returned by s_getpc 3763 // (which is the address of the s_add_u32 instruction) to the global 3764 // variable, but since the encoding of $symbol starts 4 bytes after the start 3765 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 3766 // small. This requires us to add 4 to the global variable offset in order to 3767 // compute the correct address. 3768 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 3769 GAFlags); 3770 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 3771 GAFlags == SIInstrInfo::MO_NONE ? 3772 GAFlags : GAFlags + 1); 3773 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 3774 } 3775 3776 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 3777 SDValue Op, 3778 SelectionDAG &DAG) const { 3779 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 3780 const GlobalValue *GV = GSD->getGlobal(); 3781 3782 if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS && 3783 GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS && 3784 // FIXME: It isn't correct to rely on the type of the pointer. This should 3785 // be removed when address space 0 is 64-bit. 3786 !GV->getType()->getElementType()->isFunctionTy()) 3787 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 3788 3789 SDLoc DL(GSD); 3790 EVT PtrVT = Op.getValueType(); 3791 3792 if (shouldEmitFixup(GV)) 3793 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 3794 else if (shouldEmitPCReloc(GV)) 3795 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 3796 SIInstrInfo::MO_REL32); 3797 3798 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 3799 SIInstrInfo::MO_GOTPCREL32); 3800 3801 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 3802 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS); 3803 const DataLayout &DataLayout = DAG.getDataLayout(); 3804 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 3805 // FIXME: Use a PseudoSourceValue once those can be assigned an address space. 3806 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 3807 3808 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 3809 MachineMemOperand::MODereferenceable | 3810 MachineMemOperand::MOInvariant); 3811 } 3812 3813 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 3814 const SDLoc &DL, SDValue V) const { 3815 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 3816 // the destination register. 3817 // 3818 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 3819 // so we will end up with redundant moves to m0. 3820 // 3821 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 3822 3823 // A Null SDValue creates a glue result. 3824 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 3825 V, Chain); 3826 return SDValue(M0, 0); 3827 } 3828 3829 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 3830 SDValue Op, 3831 MVT VT, 3832 unsigned Offset) const { 3833 SDLoc SL(Op); 3834 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 3835 DAG.getEntryNode(), Offset, false); 3836 // The local size values will have the hi 16-bits as zero. 3837 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 3838 DAG.getValueType(VT)); 3839 } 3840 3841 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 3842 EVT VT) { 3843 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(), 3844 "non-hsa intrinsic with hsa target", 3845 DL.getDebugLoc()); 3846 DAG.getContext()->diagnose(BadIntrin); 3847 return DAG.getUNDEF(VT); 3848 } 3849 3850 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 3851 EVT VT) { 3852 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(), 3853 "intrinsic not supported on subtarget", 3854 DL.getDebugLoc()); 3855 DAG.getContext()->diagnose(BadIntrin); 3856 return DAG.getUNDEF(VT); 3857 } 3858 3859 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 3860 SelectionDAG &DAG) const { 3861 MachineFunction &MF = DAG.getMachineFunction(); 3862 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 3863 3864 EVT VT = Op.getValueType(); 3865 SDLoc DL(Op); 3866 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3867 3868 // TODO: Should this propagate fast-math-flags? 3869 3870 switch (IntrinsicID) { 3871 case Intrinsic::amdgcn_implicit_buffer_ptr: { 3872 if (getSubtarget()->isAmdCodeObjectV2(MF)) 3873 return emitNonHSAIntrinsicError(DAG, DL, VT); 3874 return getPreloadedValue(DAG, *MFI, VT, 3875 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 3876 } 3877 case Intrinsic::amdgcn_dispatch_ptr: 3878 case Intrinsic::amdgcn_queue_ptr: { 3879 if (!Subtarget->isAmdCodeObjectV2(MF)) { 3880 DiagnosticInfoUnsupported BadIntrin( 3881 *MF.getFunction(), "unsupported hsa intrinsic without hsa target", 3882 DL.getDebugLoc()); 3883 DAG.getContext()->diagnose(BadIntrin); 3884 return DAG.getUNDEF(VT); 3885 } 3886 3887 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 3888 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 3889 return getPreloadedValue(DAG, *MFI, VT, RegID); 3890 } 3891 case Intrinsic::amdgcn_implicitarg_ptr: { 3892 if (MFI->isEntryFunction()) 3893 return getImplicitArgPtr(DAG, DL); 3894 return getPreloadedValue(DAG, *MFI, VT, 3895 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 3896 } 3897 case Intrinsic::amdgcn_kernarg_segment_ptr: { 3898 return getPreloadedValue(DAG, *MFI, VT, 3899 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 3900 } 3901 case Intrinsic::amdgcn_dispatch_id: { 3902 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 3903 } 3904 case Intrinsic::amdgcn_rcp: 3905 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 3906 case Intrinsic::amdgcn_rsq: 3907 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 3908 case Intrinsic::amdgcn_rsq_legacy: 3909 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 3910 return emitRemovedIntrinsicError(DAG, DL, VT); 3911 3912 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 3913 case Intrinsic::amdgcn_rcp_legacy: 3914 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 3915 return emitRemovedIntrinsicError(DAG, DL, VT); 3916 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 3917 case Intrinsic::amdgcn_rsq_clamp: { 3918 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 3919 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 3920 3921 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 3922 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 3923 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 3924 3925 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 3926 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 3927 DAG.getConstantFP(Max, DL, VT)); 3928 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 3929 DAG.getConstantFP(Min, DL, VT)); 3930 } 3931 case Intrinsic::r600_read_ngroups_x: 3932 if (Subtarget->isAmdHsaOS()) 3933 return emitNonHSAIntrinsicError(DAG, DL, VT); 3934 3935 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3936 SI::KernelInputOffsets::NGROUPS_X, false); 3937 case Intrinsic::r600_read_ngroups_y: 3938 if (Subtarget->isAmdHsaOS()) 3939 return emitNonHSAIntrinsicError(DAG, DL, VT); 3940 3941 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3942 SI::KernelInputOffsets::NGROUPS_Y, false); 3943 case Intrinsic::r600_read_ngroups_z: 3944 if (Subtarget->isAmdHsaOS()) 3945 return emitNonHSAIntrinsicError(DAG, DL, VT); 3946 3947 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3948 SI::KernelInputOffsets::NGROUPS_Z, false); 3949 case Intrinsic::r600_read_global_size_x: 3950 if (Subtarget->isAmdHsaOS()) 3951 return emitNonHSAIntrinsicError(DAG, DL, VT); 3952 3953 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3954 SI::KernelInputOffsets::GLOBAL_SIZE_X, false); 3955 case Intrinsic::r600_read_global_size_y: 3956 if (Subtarget->isAmdHsaOS()) 3957 return emitNonHSAIntrinsicError(DAG, DL, VT); 3958 3959 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3960 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false); 3961 case Intrinsic::r600_read_global_size_z: 3962 if (Subtarget->isAmdHsaOS()) 3963 return emitNonHSAIntrinsicError(DAG, DL, VT); 3964 3965 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3966 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false); 3967 case Intrinsic::r600_read_local_size_x: 3968 if (Subtarget->isAmdHsaOS()) 3969 return emitNonHSAIntrinsicError(DAG, DL, VT); 3970 3971 return lowerImplicitZextParam(DAG, Op, MVT::i16, 3972 SI::KernelInputOffsets::LOCAL_SIZE_X); 3973 case Intrinsic::r600_read_local_size_y: 3974 if (Subtarget->isAmdHsaOS()) 3975 return emitNonHSAIntrinsicError(DAG, DL, VT); 3976 3977 return lowerImplicitZextParam(DAG, Op, MVT::i16, 3978 SI::KernelInputOffsets::LOCAL_SIZE_Y); 3979 case Intrinsic::r600_read_local_size_z: 3980 if (Subtarget->isAmdHsaOS()) 3981 return emitNonHSAIntrinsicError(DAG, DL, VT); 3982 3983 return lowerImplicitZextParam(DAG, Op, MVT::i16, 3984 SI::KernelInputOffsets::LOCAL_SIZE_Z); 3985 case Intrinsic::amdgcn_workgroup_id_x: 3986 case Intrinsic::r600_read_tgid_x: 3987 return getPreloadedValue(DAG, *MFI, VT, 3988 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 3989 case Intrinsic::amdgcn_workgroup_id_y: 3990 case Intrinsic::r600_read_tgid_y: 3991 return getPreloadedValue(DAG, *MFI, VT, 3992 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 3993 case Intrinsic::amdgcn_workgroup_id_z: 3994 case Intrinsic::r600_read_tgid_z: 3995 return getPreloadedValue(DAG, *MFI, VT, 3996 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 3997 case Intrinsic::amdgcn_workitem_id_x: { 3998 case Intrinsic::r600_read_tidig_x: 3999 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 4000 SDLoc(DAG.getEntryNode()), 4001 MFI->getArgInfo().WorkItemIDX); 4002 } 4003 case Intrinsic::amdgcn_workitem_id_y: 4004 case Intrinsic::r600_read_tidig_y: 4005 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 4006 SDLoc(DAG.getEntryNode()), 4007 MFI->getArgInfo().WorkItemIDY); 4008 case Intrinsic::amdgcn_workitem_id_z: 4009 case Intrinsic::r600_read_tidig_z: 4010 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 4011 SDLoc(DAG.getEntryNode()), 4012 MFI->getArgInfo().WorkItemIDZ); 4013 case AMDGPUIntrinsic::SI_load_const: { 4014 SDValue Ops[] = { 4015 Op.getOperand(1), 4016 Op.getOperand(2) 4017 }; 4018 4019 MachineMemOperand *MMO = MF.getMachineMemOperand( 4020 MachinePointerInfo(), 4021 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 4022 MachineMemOperand::MOInvariant, 4023 VT.getStoreSize(), 4); 4024 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL, 4025 Op->getVTList(), Ops, VT, MMO); 4026 } 4027 case Intrinsic::amdgcn_fdiv_fast: 4028 return lowerFDIV_FAST(Op, DAG); 4029 case Intrinsic::amdgcn_interp_mov: { 4030 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 4031 SDValue Glue = M0.getValue(1); 4032 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1), 4033 Op.getOperand(2), Op.getOperand(3), Glue); 4034 } 4035 case Intrinsic::amdgcn_interp_p1: { 4036 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 4037 SDValue Glue = M0.getValue(1); 4038 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1), 4039 Op.getOperand(2), Op.getOperand(3), Glue); 4040 } 4041 case Intrinsic::amdgcn_interp_p2: { 4042 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 4043 SDValue Glue = SDValue(M0.getNode(), 1); 4044 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1), 4045 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4), 4046 Glue); 4047 } 4048 case Intrinsic::amdgcn_sin: 4049 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 4050 4051 case Intrinsic::amdgcn_cos: 4052 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 4053 4054 case Intrinsic::amdgcn_log_clamp: { 4055 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 4056 return SDValue(); 4057 4058 DiagnosticInfoUnsupported BadIntrin( 4059 *MF.getFunction(), "intrinsic not supported on subtarget", 4060 DL.getDebugLoc()); 4061 DAG.getContext()->diagnose(BadIntrin); 4062 return DAG.getUNDEF(VT); 4063 } 4064 case Intrinsic::amdgcn_ldexp: 4065 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 4066 Op.getOperand(1), Op.getOperand(2)); 4067 4068 case Intrinsic::amdgcn_fract: 4069 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 4070 4071 case Intrinsic::amdgcn_class: 4072 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 4073 Op.getOperand(1), Op.getOperand(2)); 4074 case Intrinsic::amdgcn_div_fmas: 4075 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 4076 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 4077 Op.getOperand(4)); 4078 4079 case Intrinsic::amdgcn_div_fixup: 4080 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 4081 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4082 4083 case Intrinsic::amdgcn_trig_preop: 4084 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 4085 Op.getOperand(1), Op.getOperand(2)); 4086 case Intrinsic::amdgcn_div_scale: { 4087 // 3rd parameter required to be a constant. 4088 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 4089 if (!Param) 4090 return DAG.getMergeValues({ DAG.getUNDEF(VT), DAG.getUNDEF(MVT::i1) }, DL); 4091 4092 // Translate to the operands expected by the machine instruction. The 4093 // first parameter must be the same as the first instruction. 4094 SDValue Numerator = Op.getOperand(1); 4095 SDValue Denominator = Op.getOperand(2); 4096 4097 // Note this order is opposite of the machine instruction's operations, 4098 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 4099 // intrinsic has the numerator as the first operand to match a normal 4100 // division operation. 4101 4102 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 4103 4104 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 4105 Denominator, Numerator); 4106 } 4107 case Intrinsic::amdgcn_icmp: { 4108 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 4109 if (!CD) 4110 return DAG.getUNDEF(VT); 4111 4112 int CondCode = CD->getSExtValue(); 4113 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4114 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4115 return DAG.getUNDEF(VT); 4116 4117 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4118 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4119 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 4120 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 4121 } 4122 case Intrinsic::amdgcn_fcmp: { 4123 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 4124 if (!CD) 4125 return DAG.getUNDEF(VT); 4126 4127 int CondCode = CD->getSExtValue(); 4128 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4129 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) 4130 return DAG.getUNDEF(VT); 4131 4132 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4133 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4134 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 4135 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 4136 } 4137 case Intrinsic::amdgcn_fmed3: 4138 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 4139 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4140 case Intrinsic::amdgcn_fmul_legacy: 4141 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 4142 Op.getOperand(1), Op.getOperand(2)); 4143 case Intrinsic::amdgcn_sffbh: 4144 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 4145 case Intrinsic::amdgcn_sbfe: 4146 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 4147 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4148 case Intrinsic::amdgcn_ubfe: 4149 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 4150 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4151 case Intrinsic::amdgcn_cvt_pkrtz: { 4152 // FIXME: Stop adding cast if v2f16 legal. 4153 EVT VT = Op.getValueType(); 4154 SDValue Node = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, DL, MVT::i32, 4155 Op.getOperand(1), Op.getOperand(2)); 4156 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 4157 } 4158 case Intrinsic::amdgcn_wqm: { 4159 SDValue Src = Op.getOperand(1); 4160 return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src), 4161 0); 4162 } 4163 case Intrinsic::amdgcn_wwm: { 4164 SDValue Src = Op.getOperand(1); 4165 return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src), 4166 0); 4167 } 4168 default: 4169 return Op; 4170 } 4171 } 4172 4173 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4174 SelectionDAG &DAG) const { 4175 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4176 SDLoc DL(Op); 4177 MachineFunction &MF = DAG.getMachineFunction(); 4178 4179 switch (IntrID) { 4180 case Intrinsic::amdgcn_atomic_inc: 4181 case Intrinsic::amdgcn_atomic_dec: { 4182 MemSDNode *M = cast<MemSDNode>(Op); 4183 unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ? 4184 AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC; 4185 SDValue Ops[] = { 4186 M->getOperand(0), // Chain 4187 M->getOperand(2), // Ptr 4188 M->getOperand(3) // Value 4189 }; 4190 4191 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 4192 M->getMemoryVT(), M->getMemOperand()); 4193 } 4194 case Intrinsic::amdgcn_buffer_load: 4195 case Intrinsic::amdgcn_buffer_load_format: { 4196 SDValue Ops[] = { 4197 Op.getOperand(0), // Chain 4198 Op.getOperand(2), // rsrc 4199 Op.getOperand(3), // vindex 4200 Op.getOperand(4), // offset 4201 Op.getOperand(5), // glc 4202 Op.getOperand(6) // slc 4203 }; 4204 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4205 4206 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 4207 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 4208 EVT VT = Op.getValueType(); 4209 EVT IntVT = VT.changeTypeToInteger(); 4210 4211 MachineMemOperand *MMO = MF.getMachineMemOperand( 4212 MachinePointerInfo(MFI->getBufferPSV()), 4213 MachineMemOperand::MOLoad, 4214 VT.getStoreSize(), VT.getStoreSize()); 4215 4216 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, MMO); 4217 } 4218 case Intrinsic::amdgcn_tbuffer_load: { 4219 SDValue Ops[] = { 4220 Op.getOperand(0), // Chain 4221 Op.getOperand(2), // rsrc 4222 Op.getOperand(3), // vindex 4223 Op.getOperand(4), // voffset 4224 Op.getOperand(5), // soffset 4225 Op.getOperand(6), // offset 4226 Op.getOperand(7), // dfmt 4227 Op.getOperand(8), // nfmt 4228 Op.getOperand(9), // glc 4229 Op.getOperand(10) // slc 4230 }; 4231 4232 EVT VT = Op.getOperand(2).getValueType(); 4233 4234 MachineMemOperand *MMO = MF.getMachineMemOperand( 4235 MachinePointerInfo(), 4236 MachineMemOperand::MOLoad, 4237 VT.getStoreSize(), VT.getStoreSize()); 4238 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 4239 Op->getVTList(), Ops, VT, MMO); 4240 } 4241 // Basic sample. 4242 case Intrinsic::amdgcn_image_sample: 4243 case Intrinsic::amdgcn_image_sample_cl: 4244 case Intrinsic::amdgcn_image_sample_d: 4245 case Intrinsic::amdgcn_image_sample_d_cl: 4246 case Intrinsic::amdgcn_image_sample_l: 4247 case Intrinsic::amdgcn_image_sample_b: 4248 case Intrinsic::amdgcn_image_sample_b_cl: 4249 case Intrinsic::amdgcn_image_sample_lz: 4250 case Intrinsic::amdgcn_image_sample_cd: 4251 case Intrinsic::amdgcn_image_sample_cd_cl: 4252 4253 // Sample with comparison. 4254 case Intrinsic::amdgcn_image_sample_c: 4255 case Intrinsic::amdgcn_image_sample_c_cl: 4256 case Intrinsic::amdgcn_image_sample_c_d: 4257 case Intrinsic::amdgcn_image_sample_c_d_cl: 4258 case Intrinsic::amdgcn_image_sample_c_l: 4259 case Intrinsic::amdgcn_image_sample_c_b: 4260 case Intrinsic::amdgcn_image_sample_c_b_cl: 4261 case Intrinsic::amdgcn_image_sample_c_lz: 4262 case Intrinsic::amdgcn_image_sample_c_cd: 4263 case Intrinsic::amdgcn_image_sample_c_cd_cl: 4264 4265 // Sample with offsets. 4266 case Intrinsic::amdgcn_image_sample_o: 4267 case Intrinsic::amdgcn_image_sample_cl_o: 4268 case Intrinsic::amdgcn_image_sample_d_o: 4269 case Intrinsic::amdgcn_image_sample_d_cl_o: 4270 case Intrinsic::amdgcn_image_sample_l_o: 4271 case Intrinsic::amdgcn_image_sample_b_o: 4272 case Intrinsic::amdgcn_image_sample_b_cl_o: 4273 case Intrinsic::amdgcn_image_sample_lz_o: 4274 case Intrinsic::amdgcn_image_sample_cd_o: 4275 case Intrinsic::amdgcn_image_sample_cd_cl_o: 4276 4277 // Sample with comparison and offsets. 4278 case Intrinsic::amdgcn_image_sample_c_o: 4279 case Intrinsic::amdgcn_image_sample_c_cl_o: 4280 case Intrinsic::amdgcn_image_sample_c_d_o: 4281 case Intrinsic::amdgcn_image_sample_c_d_cl_o: 4282 case Intrinsic::amdgcn_image_sample_c_l_o: 4283 case Intrinsic::amdgcn_image_sample_c_b_o: 4284 case Intrinsic::amdgcn_image_sample_c_b_cl_o: 4285 case Intrinsic::amdgcn_image_sample_c_lz_o: 4286 case Intrinsic::amdgcn_image_sample_c_cd_o: 4287 case Intrinsic::amdgcn_image_sample_c_cd_cl_o: 4288 4289 case Intrinsic::amdgcn_image_getlod: { 4290 // Replace dmask with everything disabled with undef. 4291 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(5)); 4292 if (!DMask || DMask->isNullValue()) { 4293 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 4294 return DAG.getMergeValues({ Undef, Op.getOperand(0) }, SDLoc(Op)); 4295 } 4296 4297 return SDValue(); 4298 } 4299 default: 4300 return SDValue(); 4301 } 4302 } 4303 4304 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4305 SelectionDAG &DAG) const { 4306 SDLoc DL(Op); 4307 SDValue Chain = Op.getOperand(0); 4308 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4309 MachineFunction &MF = DAG.getMachineFunction(); 4310 4311 switch (IntrinsicID) { 4312 case Intrinsic::amdgcn_exp: { 4313 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 4314 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 4315 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8)); 4316 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9)); 4317 4318 const SDValue Ops[] = { 4319 Chain, 4320 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 4321 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 4322 Op.getOperand(4), // src0 4323 Op.getOperand(5), // src1 4324 Op.getOperand(6), // src2 4325 Op.getOperand(7), // src3 4326 DAG.getTargetConstant(0, DL, MVT::i1), // compr 4327 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 4328 }; 4329 4330 unsigned Opc = Done->isNullValue() ? 4331 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 4332 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 4333 } 4334 case Intrinsic::amdgcn_exp_compr: { 4335 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 4336 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 4337 SDValue Src0 = Op.getOperand(4); 4338 SDValue Src1 = Op.getOperand(5); 4339 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 4340 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7)); 4341 4342 SDValue Undef = DAG.getUNDEF(MVT::f32); 4343 const SDValue Ops[] = { 4344 Chain, 4345 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 4346 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 4347 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), 4348 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), 4349 Undef, // src2 4350 Undef, // src3 4351 DAG.getTargetConstant(1, DL, MVT::i1), // compr 4352 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 4353 }; 4354 4355 unsigned Opc = Done->isNullValue() ? 4356 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 4357 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 4358 } 4359 case Intrinsic::amdgcn_s_sendmsg: 4360 case Intrinsic::amdgcn_s_sendmsghalt: { 4361 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ? 4362 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT; 4363 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 4364 SDValue Glue = Chain.getValue(1); 4365 return DAG.getNode(NodeOp, DL, MVT::Other, Chain, 4366 Op.getOperand(2), Glue); 4367 } 4368 case Intrinsic::amdgcn_init_exec: { 4369 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain, 4370 Op.getOperand(2)); 4371 } 4372 case Intrinsic::amdgcn_init_exec_from_input: { 4373 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain, 4374 Op.getOperand(2), Op.getOperand(3)); 4375 } 4376 case AMDGPUIntrinsic::AMDGPU_kill: { 4377 SDValue Src = Op.getOperand(2); 4378 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) { 4379 if (!K->isNegative()) 4380 return Chain; 4381 4382 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32); 4383 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne); 4384 } 4385 4386 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src); 4387 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast); 4388 } 4389 case Intrinsic::amdgcn_s_barrier: { 4390 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 4391 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 4392 unsigned WGSize = ST.getFlatWorkGroupSizes(*MF.getFunction()).second; 4393 if (WGSize <= ST.getWavefrontSize()) 4394 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 4395 Op.getOperand(0)), 0); 4396 } 4397 return SDValue(); 4398 }; 4399 case AMDGPUIntrinsic::SI_tbuffer_store: { 4400 4401 // Extract vindex and voffset from vaddr as appropriate 4402 const ConstantSDNode *OffEn = cast<ConstantSDNode>(Op.getOperand(10)); 4403 const ConstantSDNode *IdxEn = cast<ConstantSDNode>(Op.getOperand(11)); 4404 SDValue VAddr = Op.getOperand(5); 4405 4406 SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32); 4407 4408 assert(!(OffEn->isOne() && IdxEn->isOne()) && 4409 "Legacy intrinsic doesn't support both offset and index - use new version"); 4410 4411 SDValue VIndex = IdxEn->isOne() ? VAddr : Zero; 4412 SDValue VOffset = OffEn->isOne() ? VAddr : Zero; 4413 4414 // Deal with the vec-3 case 4415 const ConstantSDNode *NumChannels = cast<ConstantSDNode>(Op.getOperand(4)); 4416 auto Opcode = NumChannels->getZExtValue() == 3 ? 4417 AMDGPUISD::TBUFFER_STORE_FORMAT_X3 : AMDGPUISD::TBUFFER_STORE_FORMAT; 4418 4419 SDValue Ops[] = { 4420 Chain, 4421 Op.getOperand(3), // vdata 4422 Op.getOperand(2), // rsrc 4423 VIndex, 4424 VOffset, 4425 Op.getOperand(6), // soffset 4426 Op.getOperand(7), // inst_offset 4427 Op.getOperand(8), // dfmt 4428 Op.getOperand(9), // nfmt 4429 Op.getOperand(12), // glc 4430 Op.getOperand(13), // slc 4431 }; 4432 4433 assert((cast<ConstantSDNode>(Op.getOperand(14)))->getZExtValue() == 0 && 4434 "Value of tfe other than zero is unsupported"); 4435 4436 EVT VT = Op.getOperand(3).getValueType(); 4437 MachineMemOperand *MMO = MF.getMachineMemOperand( 4438 MachinePointerInfo(), 4439 MachineMemOperand::MOStore, 4440 VT.getStoreSize(), 4); 4441 return DAG.getMemIntrinsicNode(Opcode, DL, 4442 Op->getVTList(), Ops, VT, MMO); 4443 } 4444 4445 case Intrinsic::amdgcn_tbuffer_store: { 4446 SDValue Ops[] = { 4447 Chain, 4448 Op.getOperand(2), // vdata 4449 Op.getOperand(3), // rsrc 4450 Op.getOperand(4), // vindex 4451 Op.getOperand(5), // voffset 4452 Op.getOperand(6), // soffset 4453 Op.getOperand(7), // offset 4454 Op.getOperand(8), // dfmt 4455 Op.getOperand(9), // nfmt 4456 Op.getOperand(10), // glc 4457 Op.getOperand(11) // slc 4458 }; 4459 EVT VT = Op.getOperand(3).getValueType(); 4460 MachineMemOperand *MMO = MF.getMachineMemOperand( 4461 MachinePointerInfo(), 4462 MachineMemOperand::MOStore, 4463 VT.getStoreSize(), 4); 4464 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL, 4465 Op->getVTList(), Ops, VT, MMO); 4466 } 4467 4468 default: 4469 return Op; 4470 } 4471 } 4472 4473 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 4474 SDLoc DL(Op); 4475 LoadSDNode *Load = cast<LoadSDNode>(Op); 4476 ISD::LoadExtType ExtType = Load->getExtensionType(); 4477 EVT MemVT = Load->getMemoryVT(); 4478 4479 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 4480 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 4481 return SDValue(); 4482 4483 // FIXME: Copied from PPC 4484 // First, load into 32 bits, then truncate to 1 bit. 4485 4486 SDValue Chain = Load->getChain(); 4487 SDValue BasePtr = Load->getBasePtr(); 4488 MachineMemOperand *MMO = Load->getMemOperand(); 4489 4490 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 4491 4492 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 4493 BasePtr, RealMemVT, MMO); 4494 4495 SDValue Ops[] = { 4496 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 4497 NewLD.getValue(1) 4498 }; 4499 4500 return DAG.getMergeValues(Ops, DL); 4501 } 4502 4503 if (!MemVT.isVector()) 4504 return SDValue(); 4505 4506 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 4507 "Custom lowering for non-i32 vectors hasn't been implemented."); 4508 4509 unsigned AS = Load->getAddressSpace(); 4510 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 4511 AS, Load->getAlignment())) { 4512 SDValue Ops[2]; 4513 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 4514 return DAG.getMergeValues(Ops, DL); 4515 } 4516 4517 MachineFunction &MF = DAG.getMachineFunction(); 4518 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4519 // If there is a possibilty that flat instruction access scratch memory 4520 // then we need to use the same legalization rules we use for private. 4521 if (AS == AMDGPUASI.FLAT_ADDRESS) 4522 AS = MFI->hasFlatScratchInit() ? 4523 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS; 4524 4525 unsigned NumElements = MemVT.getVectorNumElements(); 4526 if (AS == AMDGPUASI.CONSTANT_ADDRESS) { 4527 if (isMemOpUniform(Load)) 4528 return SDValue(); 4529 // Non-uniform loads will be selected to MUBUF instructions, so they 4530 // have the same legalization requirements as global and private 4531 // loads. 4532 // 4533 } 4534 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS) { 4535 if (Subtarget->getScalarizeGlobalBehavior() && isMemOpUniform(Load) && 4536 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load)) 4537 return SDValue(); 4538 // Non-uniform loads will be selected to MUBUF instructions, so they 4539 // have the same legalization requirements as global and private 4540 // loads. 4541 // 4542 } 4543 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS || 4544 AS == AMDGPUASI.FLAT_ADDRESS) { 4545 if (NumElements > 4) 4546 return SplitVectorLoad(Op, DAG); 4547 // v4 loads are supported for private and global memory. 4548 return SDValue(); 4549 } 4550 if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 4551 // Depending on the setting of the private_element_size field in the 4552 // resource descriptor, we can only make private accesses up to a certain 4553 // size. 4554 switch (Subtarget->getMaxPrivateElementSize()) { 4555 case 4: 4556 return scalarizeVectorLoad(Load, DAG); 4557 case 8: 4558 if (NumElements > 2) 4559 return SplitVectorLoad(Op, DAG); 4560 return SDValue(); 4561 case 16: 4562 // Same as global/flat 4563 if (NumElements > 4) 4564 return SplitVectorLoad(Op, DAG); 4565 return SDValue(); 4566 default: 4567 llvm_unreachable("unsupported private_element_size"); 4568 } 4569 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 4570 if (NumElements > 2) 4571 return SplitVectorLoad(Op, DAG); 4572 4573 if (NumElements == 2) 4574 return SDValue(); 4575 4576 // If properly aligned, if we split we might be able to use ds_read_b64. 4577 return SplitVectorLoad(Op, DAG); 4578 } 4579 return SDValue(); 4580 } 4581 4582 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4583 if (Op.getValueType() != MVT::i64) 4584 return SDValue(); 4585 4586 SDLoc DL(Op); 4587 SDValue Cond = Op.getOperand(0); 4588 4589 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 4590 SDValue One = DAG.getConstant(1, DL, MVT::i32); 4591 4592 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 4593 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 4594 4595 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 4596 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 4597 4598 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 4599 4600 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 4601 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 4602 4603 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 4604 4605 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 4606 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res); 4607 } 4608 4609 // Catch division cases where we can use shortcuts with rcp and rsq 4610 // instructions. 4611 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 4612 SelectionDAG &DAG) const { 4613 SDLoc SL(Op); 4614 SDValue LHS = Op.getOperand(0); 4615 SDValue RHS = Op.getOperand(1); 4616 EVT VT = Op.getValueType(); 4617 const SDNodeFlags Flags = Op->getFlags(); 4618 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || 4619 Flags.hasUnsafeAlgebra() || Flags.hasAllowReciprocal(); 4620 4621 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals()) 4622 return SDValue(); 4623 4624 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 4625 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) { 4626 if (CLHS->isExactlyValue(1.0)) { 4627 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 4628 // the CI documentation has a worst case error of 1 ulp. 4629 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 4630 // use it as long as we aren't trying to use denormals. 4631 // 4632 // v_rcp_f16 and v_rsq_f16 DO support denormals. 4633 4634 // 1.0 / sqrt(x) -> rsq(x) 4635 4636 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 4637 // error seems really high at 2^29 ULP. 4638 if (RHS.getOpcode() == ISD::FSQRT) 4639 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 4640 4641 // 1.0 / x -> rcp(x) 4642 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 4643 } 4644 4645 // Same as for 1.0, but expand the sign out of the constant. 4646 if (CLHS->isExactlyValue(-1.0)) { 4647 // -1.0 / x -> rcp (fneg x) 4648 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 4649 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 4650 } 4651 } 4652 } 4653 4654 if (Unsafe) { 4655 // Turn into multiply by the reciprocal. 4656 // x / y -> x * (1.0 / y) 4657 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 4658 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 4659 } 4660 4661 return SDValue(); 4662 } 4663 4664 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 4665 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 4666 if (GlueChain->getNumValues() <= 1) { 4667 return DAG.getNode(Opcode, SL, VT, A, B); 4668 } 4669 4670 assert(GlueChain->getNumValues() == 3); 4671 4672 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 4673 switch (Opcode) { 4674 default: llvm_unreachable("no chain equivalent for opcode"); 4675 case ISD::FMUL: 4676 Opcode = AMDGPUISD::FMUL_W_CHAIN; 4677 break; 4678 } 4679 4680 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 4681 GlueChain.getValue(2)); 4682 } 4683 4684 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 4685 EVT VT, SDValue A, SDValue B, SDValue C, 4686 SDValue GlueChain) { 4687 if (GlueChain->getNumValues() <= 1) { 4688 return DAG.getNode(Opcode, SL, VT, A, B, C); 4689 } 4690 4691 assert(GlueChain->getNumValues() == 3); 4692 4693 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 4694 switch (Opcode) { 4695 default: llvm_unreachable("no chain equivalent for opcode"); 4696 case ISD::FMA: 4697 Opcode = AMDGPUISD::FMA_W_CHAIN; 4698 break; 4699 } 4700 4701 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 4702 GlueChain.getValue(2)); 4703 } 4704 4705 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 4706 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 4707 return FastLowered; 4708 4709 SDLoc SL(Op); 4710 SDValue Src0 = Op.getOperand(0); 4711 SDValue Src1 = Op.getOperand(1); 4712 4713 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4714 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4715 4716 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 4717 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 4718 4719 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 4720 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 4721 4722 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 4723 } 4724 4725 // Faster 2.5 ULP division that does not support denormals. 4726 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 4727 SDLoc SL(Op); 4728 SDValue LHS = Op.getOperand(1); 4729 SDValue RHS = Op.getOperand(2); 4730 4731 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 4732 4733 const APFloat K0Val(BitsToFloat(0x6f800000)); 4734 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 4735 4736 const APFloat K1Val(BitsToFloat(0x2f800000)); 4737 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 4738 4739 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 4740 4741 EVT SetCCVT = 4742 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 4743 4744 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 4745 4746 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 4747 4748 // TODO: Should this propagate fast-math-flags? 4749 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 4750 4751 // rcp does not support denormals. 4752 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 4753 4754 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 4755 4756 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 4757 } 4758 4759 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 4760 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 4761 return FastLowered; 4762 4763 SDLoc SL(Op); 4764 SDValue LHS = Op.getOperand(0); 4765 SDValue RHS = Op.getOperand(1); 4766 4767 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 4768 4769 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 4770 4771 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 4772 RHS, RHS, LHS); 4773 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 4774 LHS, RHS, LHS); 4775 4776 // Denominator is scaled to not be denormal, so using rcp is ok. 4777 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 4778 DenominatorScaled); 4779 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 4780 DenominatorScaled); 4781 4782 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 4783 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 4784 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 4785 4786 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 4787 4788 if (!Subtarget->hasFP32Denormals()) { 4789 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 4790 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 4791 SL, MVT::i32); 4792 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 4793 DAG.getEntryNode(), 4794 EnableDenormValue, BitField); 4795 SDValue Ops[3] = { 4796 NegDivScale0, 4797 EnableDenorm.getValue(0), 4798 EnableDenorm.getValue(1) 4799 }; 4800 4801 NegDivScale0 = DAG.getMergeValues(Ops, SL); 4802 } 4803 4804 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 4805 ApproxRcp, One, NegDivScale0); 4806 4807 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 4808 ApproxRcp, Fma0); 4809 4810 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 4811 Fma1, Fma1); 4812 4813 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 4814 NumeratorScaled, Mul); 4815 4816 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 4817 4818 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 4819 NumeratorScaled, Fma3); 4820 4821 if (!Subtarget->hasFP32Denormals()) { 4822 const SDValue DisableDenormValue = 4823 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 4824 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 4825 Fma4.getValue(1), 4826 DisableDenormValue, 4827 BitField, 4828 Fma4.getValue(2)); 4829 4830 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 4831 DisableDenorm, DAG.getRoot()); 4832 DAG.setRoot(OutputChain); 4833 } 4834 4835 SDValue Scale = NumeratorScaled.getValue(1); 4836 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 4837 Fma4, Fma1, Fma3, Scale); 4838 4839 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 4840 } 4841 4842 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 4843 if (DAG.getTarget().Options.UnsafeFPMath) 4844 return lowerFastUnsafeFDIV(Op, DAG); 4845 4846 SDLoc SL(Op); 4847 SDValue X = Op.getOperand(0); 4848 SDValue Y = Op.getOperand(1); 4849 4850 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 4851 4852 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 4853 4854 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 4855 4856 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 4857 4858 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 4859 4860 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 4861 4862 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 4863 4864 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 4865 4866 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 4867 4868 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 4869 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 4870 4871 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 4872 NegDivScale0, Mul, DivScale1); 4873 4874 SDValue Scale; 4875 4876 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) { 4877 // Workaround a hardware bug on SI where the condition output from div_scale 4878 // is not usable. 4879 4880 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 4881 4882 // Figure out if the scale to use for div_fmas. 4883 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 4884 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 4885 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 4886 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 4887 4888 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 4889 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 4890 4891 SDValue Scale0Hi 4892 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 4893 SDValue Scale1Hi 4894 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 4895 4896 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 4897 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 4898 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 4899 } else { 4900 Scale = DivScale1.getValue(1); 4901 } 4902 4903 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 4904 Fma4, Fma3, Mul, Scale); 4905 4906 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 4907 } 4908 4909 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 4910 EVT VT = Op.getValueType(); 4911 4912 if (VT == MVT::f32) 4913 return LowerFDIV32(Op, DAG); 4914 4915 if (VT == MVT::f64) 4916 return LowerFDIV64(Op, DAG); 4917 4918 if (VT == MVT::f16) 4919 return LowerFDIV16(Op, DAG); 4920 4921 llvm_unreachable("Unexpected type for fdiv"); 4922 } 4923 4924 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 4925 SDLoc DL(Op); 4926 StoreSDNode *Store = cast<StoreSDNode>(Op); 4927 EVT VT = Store->getMemoryVT(); 4928 4929 if (VT == MVT::i1) { 4930 return DAG.getTruncStore(Store->getChain(), DL, 4931 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 4932 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 4933 } 4934 4935 assert(VT.isVector() && 4936 Store->getValue().getValueType().getScalarType() == MVT::i32); 4937 4938 unsigned AS = Store->getAddressSpace(); 4939 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 4940 AS, Store->getAlignment())) { 4941 return expandUnalignedStore(Store, DAG); 4942 } 4943 4944 MachineFunction &MF = DAG.getMachineFunction(); 4945 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4946 // If there is a possibilty that flat instruction access scratch memory 4947 // then we need to use the same legalization rules we use for private. 4948 if (AS == AMDGPUASI.FLAT_ADDRESS) 4949 AS = MFI->hasFlatScratchInit() ? 4950 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS; 4951 4952 unsigned NumElements = VT.getVectorNumElements(); 4953 if (AS == AMDGPUASI.GLOBAL_ADDRESS || 4954 AS == AMDGPUASI.FLAT_ADDRESS) { 4955 if (NumElements > 4) 4956 return SplitVectorStore(Op, DAG); 4957 return SDValue(); 4958 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 4959 switch (Subtarget->getMaxPrivateElementSize()) { 4960 case 4: 4961 return scalarizeVectorStore(Store, DAG); 4962 case 8: 4963 if (NumElements > 2) 4964 return SplitVectorStore(Op, DAG); 4965 return SDValue(); 4966 case 16: 4967 if (NumElements > 4) 4968 return SplitVectorStore(Op, DAG); 4969 return SDValue(); 4970 default: 4971 llvm_unreachable("unsupported private_element_size"); 4972 } 4973 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 4974 if (NumElements > 2) 4975 return SplitVectorStore(Op, DAG); 4976 4977 if (NumElements == 2) 4978 return Op; 4979 4980 // If properly aligned, if we split we might be able to use ds_write_b64. 4981 return SplitVectorStore(Op, DAG); 4982 } else { 4983 llvm_unreachable("unhandled address space"); 4984 } 4985 } 4986 4987 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 4988 SDLoc DL(Op); 4989 EVT VT = Op.getValueType(); 4990 SDValue Arg = Op.getOperand(0); 4991 // TODO: Should this propagate fast-math-flags? 4992 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT, 4993 DAG.getNode(ISD::FMUL, DL, VT, Arg, 4994 DAG.getConstantFP(0.5/M_PI, DL, 4995 VT))); 4996 4997 switch (Op.getOpcode()) { 4998 case ISD::FCOS: 4999 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart); 5000 case ISD::FSIN: 5001 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart); 5002 default: 5003 llvm_unreachable("Wrong trig opcode"); 5004 } 5005 } 5006 5007 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 5008 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 5009 assert(AtomicNode->isCompareAndSwap()); 5010 unsigned AS = AtomicNode->getAddressSpace(); 5011 5012 // No custom lowering required for local address space 5013 if (!isFlatGlobalAddrSpace(AS, AMDGPUASI)) 5014 return Op; 5015 5016 // Non-local address space requires custom lowering for atomic compare 5017 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 5018 SDLoc DL(Op); 5019 SDValue ChainIn = Op.getOperand(0); 5020 SDValue Addr = Op.getOperand(1); 5021 SDValue Old = Op.getOperand(2); 5022 SDValue New = Op.getOperand(3); 5023 EVT VT = Op.getValueType(); 5024 MVT SimpleVT = VT.getSimpleVT(); 5025 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 5026 5027 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 5028 SDValue Ops[] = { ChainIn, Addr, NewOld }; 5029 5030 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 5031 Ops, VT, AtomicNode->getMemOperand()); 5032 } 5033 5034 //===----------------------------------------------------------------------===// 5035 // Custom DAG optimizations 5036 //===----------------------------------------------------------------------===// 5037 5038 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 5039 DAGCombinerInfo &DCI) const { 5040 EVT VT = N->getValueType(0); 5041 EVT ScalarVT = VT.getScalarType(); 5042 if (ScalarVT != MVT::f32) 5043 return SDValue(); 5044 5045 SelectionDAG &DAG = DCI.DAG; 5046 SDLoc DL(N); 5047 5048 SDValue Src = N->getOperand(0); 5049 EVT SrcVT = Src.getValueType(); 5050 5051 // TODO: We could try to match extracting the higher bytes, which would be 5052 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 5053 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 5054 // about in practice. 5055 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) { 5056 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 5057 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 5058 DCI.AddToWorklist(Cvt.getNode()); 5059 return Cvt; 5060 } 5061 } 5062 5063 return SDValue(); 5064 } 5065 5066 /// \brief Return true if the given offset Size in bytes can be folded into 5067 /// the immediate offsets of a memory instruction for the given address space. 5068 static bool canFoldOffset(unsigned OffsetSize, unsigned AS, 5069 const SISubtarget &STI) { 5070 auto AMDGPUASI = STI.getAMDGPUAS(); 5071 if (AS == AMDGPUASI.GLOBAL_ADDRESS) { 5072 // MUBUF instructions a 12-bit offset in bytes. 5073 return isUInt<12>(OffsetSize); 5074 } 5075 if (AS == AMDGPUASI.CONSTANT_ADDRESS) { 5076 // SMRD instructions have an 8-bit offset in dwords on SI and 5077 // a 20-bit offset in bytes on VI. 5078 if (STI.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 5079 return isUInt<20>(OffsetSize); 5080 else 5081 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4); 5082 } 5083 if (AS == AMDGPUASI.LOCAL_ADDRESS || 5084 AS == AMDGPUASI.REGION_ADDRESS) { 5085 // The single offset versions have a 16-bit offset in bytes. 5086 return isUInt<16>(OffsetSize); 5087 } 5088 // Indirect register addressing does not use any offsets. 5089 return false; 5090 } 5091 5092 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 5093 5094 // This is a variant of 5095 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 5096 // 5097 // The normal DAG combiner will do this, but only if the add has one use since 5098 // that would increase the number of instructions. 5099 // 5100 // This prevents us from seeing a constant offset that can be folded into a 5101 // memory instruction's addressing mode. If we know the resulting add offset of 5102 // a pointer can be folded into an addressing offset, we can replace the pointer 5103 // operand with the add of new constant offset. This eliminates one of the uses, 5104 // and may allow the remaining use to also be simplified. 5105 // 5106 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 5107 unsigned AddrSpace, 5108 DAGCombinerInfo &DCI) const { 5109 SDValue N0 = N->getOperand(0); 5110 SDValue N1 = N->getOperand(1); 5111 5112 if (N0.getOpcode() != ISD::ADD) 5113 return SDValue(); 5114 5115 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 5116 if (!CN1) 5117 return SDValue(); 5118 5119 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5120 if (!CAdd) 5121 return SDValue(); 5122 5123 // If the resulting offset is too large, we can't fold it into the addressing 5124 // mode offset. 5125 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 5126 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *getSubtarget())) 5127 return SDValue(); 5128 5129 SelectionDAG &DAG = DCI.DAG; 5130 SDLoc SL(N); 5131 EVT VT = N->getValueType(0); 5132 5133 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 5134 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 5135 5136 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset); 5137 } 5138 5139 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 5140 DAGCombinerInfo &DCI) const { 5141 SDValue Ptr = N->getBasePtr(); 5142 SelectionDAG &DAG = DCI.DAG; 5143 SDLoc SL(N); 5144 5145 // TODO: We could also do this for multiplies. 5146 unsigned AS = N->getAddressSpace(); 5147 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUASI.PRIVATE_ADDRESS) { 5148 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI); 5149 if (NewPtr) { 5150 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 5151 5152 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 5153 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 5154 } 5155 } 5156 5157 return SDValue(); 5158 } 5159 5160 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 5161 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 5162 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 5163 (Opc == ISD::XOR && Val == 0); 5164 } 5165 5166 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 5167 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 5168 // integer combine opportunities since most 64-bit operations are decomposed 5169 // this way. TODO: We won't want this for SALU especially if it is an inline 5170 // immediate. 5171 SDValue SITargetLowering::splitBinaryBitConstantOp( 5172 DAGCombinerInfo &DCI, 5173 const SDLoc &SL, 5174 unsigned Opc, SDValue LHS, 5175 const ConstantSDNode *CRHS) const { 5176 uint64_t Val = CRHS->getZExtValue(); 5177 uint32_t ValLo = Lo_32(Val); 5178 uint32_t ValHi = Hi_32(Val); 5179 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 5180 5181 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 5182 bitOpWithConstantIsReducible(Opc, ValHi)) || 5183 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 5184 // If we need to materialize a 64-bit immediate, it will be split up later 5185 // anyway. Avoid creating the harder to understand 64-bit immediate 5186 // materialization. 5187 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 5188 } 5189 5190 return SDValue(); 5191 } 5192 5193 // Returns true if argument is a boolean value which is not serialized into 5194 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 5195 static bool isBoolSGPR(SDValue V) { 5196 if (V.getValueType() != MVT::i1) 5197 return false; 5198 switch (V.getOpcode()) { 5199 default: break; 5200 case ISD::SETCC: 5201 case ISD::AND: 5202 case ISD::OR: 5203 case ISD::XOR: 5204 case AMDGPUISD::FP_CLASS: 5205 return true; 5206 } 5207 return false; 5208 } 5209 5210 SDValue SITargetLowering::performAndCombine(SDNode *N, 5211 DAGCombinerInfo &DCI) const { 5212 if (DCI.isBeforeLegalize()) 5213 return SDValue(); 5214 5215 SelectionDAG &DAG = DCI.DAG; 5216 EVT VT = N->getValueType(0); 5217 SDValue LHS = N->getOperand(0); 5218 SDValue RHS = N->getOperand(1); 5219 5220 5221 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 5222 if (VT == MVT::i64 && CRHS) { 5223 if (SDValue Split 5224 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 5225 return Split; 5226 } 5227 5228 if (CRHS && VT == MVT::i32) { 5229 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 5230 // nb = number of trailing zeroes in mask 5231 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 5232 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 5233 uint64_t Mask = CRHS->getZExtValue(); 5234 unsigned Bits = countPopulation(Mask); 5235 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 5236 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 5237 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 5238 unsigned Shift = CShift->getZExtValue(); 5239 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 5240 unsigned Offset = NB + Shift; 5241 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 5242 SDLoc SL(N); 5243 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 5244 LHS->getOperand(0), 5245 DAG.getConstant(Offset, SL, MVT::i32), 5246 DAG.getConstant(Bits, SL, MVT::i32)); 5247 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 5248 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 5249 DAG.getValueType(NarrowVT)); 5250 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 5251 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 5252 return Shl; 5253 } 5254 } 5255 } 5256 } 5257 5258 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 5259 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 5260 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 5261 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 5262 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 5263 5264 SDValue X = LHS.getOperand(0); 5265 SDValue Y = RHS.getOperand(0); 5266 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 5267 return SDValue(); 5268 5269 if (LCC == ISD::SETO) { 5270 if (X != LHS.getOperand(1)) 5271 return SDValue(); 5272 5273 if (RCC == ISD::SETUNE) { 5274 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 5275 if (!C1 || !C1->isInfinity() || C1->isNegative()) 5276 return SDValue(); 5277 5278 const uint32_t Mask = SIInstrFlags::N_NORMAL | 5279 SIInstrFlags::N_SUBNORMAL | 5280 SIInstrFlags::N_ZERO | 5281 SIInstrFlags::P_ZERO | 5282 SIInstrFlags::P_SUBNORMAL | 5283 SIInstrFlags::P_NORMAL; 5284 5285 static_assert(((~(SIInstrFlags::S_NAN | 5286 SIInstrFlags::Q_NAN | 5287 SIInstrFlags::N_INFINITY | 5288 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 5289 "mask not equal"); 5290 5291 SDLoc DL(N); 5292 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 5293 X, DAG.getConstant(Mask, DL, MVT::i32)); 5294 } 5295 } 5296 } 5297 5298 if (VT == MVT::i32 && 5299 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 5300 // and x, (sext cc from i1) => select cc, x, 0 5301 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 5302 std::swap(LHS, RHS); 5303 if (isBoolSGPR(RHS.getOperand(0))) 5304 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 5305 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 5306 } 5307 5308 return SDValue(); 5309 } 5310 5311 SDValue SITargetLowering::performOrCombine(SDNode *N, 5312 DAGCombinerInfo &DCI) const { 5313 SelectionDAG &DAG = DCI.DAG; 5314 SDValue LHS = N->getOperand(0); 5315 SDValue RHS = N->getOperand(1); 5316 5317 EVT VT = N->getValueType(0); 5318 if (VT == MVT::i1) { 5319 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 5320 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 5321 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 5322 SDValue Src = LHS.getOperand(0); 5323 if (Src != RHS.getOperand(0)) 5324 return SDValue(); 5325 5326 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 5327 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 5328 if (!CLHS || !CRHS) 5329 return SDValue(); 5330 5331 // Only 10 bits are used. 5332 static const uint32_t MaxMask = 0x3ff; 5333 5334 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 5335 SDLoc DL(N); 5336 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 5337 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 5338 } 5339 5340 return SDValue(); 5341 } 5342 5343 if (VT != MVT::i64) 5344 return SDValue(); 5345 5346 // TODO: This could be a generic combine with a predicate for extracting the 5347 // high half of an integer being free. 5348 5349 // (or i64:x, (zero_extend i32:y)) -> 5350 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 5351 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 5352 RHS.getOpcode() != ISD::ZERO_EXTEND) 5353 std::swap(LHS, RHS); 5354 5355 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 5356 SDValue ExtSrc = RHS.getOperand(0); 5357 EVT SrcVT = ExtSrc.getValueType(); 5358 if (SrcVT == MVT::i32) { 5359 SDLoc SL(N); 5360 SDValue LowLHS, HiBits; 5361 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 5362 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 5363 5364 DCI.AddToWorklist(LowOr.getNode()); 5365 DCI.AddToWorklist(HiBits.getNode()); 5366 5367 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 5368 LowOr, HiBits); 5369 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 5370 } 5371 } 5372 5373 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 5374 if (CRHS) { 5375 if (SDValue Split 5376 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 5377 return Split; 5378 } 5379 5380 return SDValue(); 5381 } 5382 5383 SDValue SITargetLowering::performXorCombine(SDNode *N, 5384 DAGCombinerInfo &DCI) const { 5385 EVT VT = N->getValueType(0); 5386 if (VT != MVT::i64) 5387 return SDValue(); 5388 5389 SDValue LHS = N->getOperand(0); 5390 SDValue RHS = N->getOperand(1); 5391 5392 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 5393 if (CRHS) { 5394 if (SDValue Split 5395 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 5396 return Split; 5397 } 5398 5399 return SDValue(); 5400 } 5401 5402 // Instructions that will be lowered with a final instruction that zeros the 5403 // high result bits. 5404 // XXX - probably only need to list legal operations. 5405 static bool fp16SrcZerosHighBits(unsigned Opc) { 5406 switch (Opc) { 5407 case ISD::FADD: 5408 case ISD::FSUB: 5409 case ISD::FMUL: 5410 case ISD::FDIV: 5411 case ISD::FREM: 5412 case ISD::FMA: 5413 case ISD::FMAD: 5414 case ISD::FCANONICALIZE: 5415 case ISD::FP_ROUND: 5416 case ISD::UINT_TO_FP: 5417 case ISD::SINT_TO_FP: 5418 case ISD::FABS: 5419 // Fabs is lowered to a bit operation, but it's an and which will clear the 5420 // high bits anyway. 5421 case ISD::FSQRT: 5422 case ISD::FSIN: 5423 case ISD::FCOS: 5424 case ISD::FPOWI: 5425 case ISD::FPOW: 5426 case ISD::FLOG: 5427 case ISD::FLOG2: 5428 case ISD::FLOG10: 5429 case ISD::FEXP: 5430 case ISD::FEXP2: 5431 case ISD::FCEIL: 5432 case ISD::FTRUNC: 5433 case ISD::FRINT: 5434 case ISD::FNEARBYINT: 5435 case ISD::FROUND: 5436 case ISD::FFLOOR: 5437 case ISD::FMINNUM: 5438 case ISD::FMAXNUM: 5439 case AMDGPUISD::FRACT: 5440 case AMDGPUISD::CLAMP: 5441 case AMDGPUISD::COS_HW: 5442 case AMDGPUISD::SIN_HW: 5443 case AMDGPUISD::FMIN3: 5444 case AMDGPUISD::FMAX3: 5445 case AMDGPUISD::FMED3: 5446 case AMDGPUISD::FMAD_FTZ: 5447 case AMDGPUISD::RCP: 5448 case AMDGPUISD::RSQ: 5449 case AMDGPUISD::LDEXP: 5450 return true; 5451 default: 5452 // fcopysign, select and others may be lowered to 32-bit bit operations 5453 // which don't zero the high bits. 5454 return false; 5455 } 5456 } 5457 5458 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 5459 DAGCombinerInfo &DCI) const { 5460 if (!Subtarget->has16BitInsts() || 5461 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 5462 return SDValue(); 5463 5464 EVT VT = N->getValueType(0); 5465 if (VT != MVT::i32) 5466 return SDValue(); 5467 5468 SDValue Src = N->getOperand(0); 5469 if (Src.getValueType() != MVT::i16) 5470 return SDValue(); 5471 5472 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 5473 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 5474 if (Src.getOpcode() == ISD::BITCAST) { 5475 SDValue BCSrc = Src.getOperand(0); 5476 if (BCSrc.getValueType() == MVT::f16 && 5477 fp16SrcZerosHighBits(BCSrc.getOpcode())) 5478 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 5479 } 5480 5481 return SDValue(); 5482 } 5483 5484 SDValue SITargetLowering::performClassCombine(SDNode *N, 5485 DAGCombinerInfo &DCI) const { 5486 SelectionDAG &DAG = DCI.DAG; 5487 SDValue Mask = N->getOperand(1); 5488 5489 // fp_class x, 0 -> false 5490 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 5491 if (CMask->isNullValue()) 5492 return DAG.getConstant(0, SDLoc(N), MVT::i1); 5493 } 5494 5495 if (N->getOperand(0).isUndef()) 5496 return DAG.getUNDEF(MVT::i1); 5497 5498 return SDValue(); 5499 } 5500 5501 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) { 5502 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions()) 5503 return true; 5504 5505 return DAG.isKnownNeverNaN(Op); 5506 } 5507 5508 static bool isCanonicalized(SelectionDAG &DAG, SDValue Op, 5509 const SISubtarget *ST, unsigned MaxDepth=5) { 5510 // If source is a result of another standard FP operation it is already in 5511 // canonical form. 5512 5513 switch (Op.getOpcode()) { 5514 default: 5515 break; 5516 5517 // These will flush denorms if required. 5518 case ISD::FADD: 5519 case ISD::FSUB: 5520 case ISD::FMUL: 5521 case ISD::FSQRT: 5522 case ISD::FCEIL: 5523 case ISD::FFLOOR: 5524 case ISD::FMA: 5525 case ISD::FMAD: 5526 5527 case ISD::FCANONICALIZE: 5528 return true; 5529 5530 case ISD::FP_ROUND: 5531 return Op.getValueType().getScalarType() != MVT::f16 || 5532 ST->hasFP16Denormals(); 5533 5534 case ISD::FP_EXTEND: 5535 return Op.getOperand(0).getValueType().getScalarType() != MVT::f16 || 5536 ST->hasFP16Denormals(); 5537 5538 case ISD::FP16_TO_FP: 5539 case ISD::FP_TO_FP16: 5540 return ST->hasFP16Denormals(); 5541 5542 // It can/will be lowered or combined as a bit operation. 5543 // Need to check their input recursively to handle. 5544 case ISD::FNEG: 5545 case ISD::FABS: 5546 return (MaxDepth > 0) && 5547 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1); 5548 5549 case ISD::FSIN: 5550 case ISD::FCOS: 5551 case ISD::FSINCOS: 5552 return Op.getValueType().getScalarType() != MVT::f16; 5553 5554 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. 5555 // For such targets need to check their input recursively. 5556 case ISD::FMINNUM: 5557 case ISD::FMAXNUM: 5558 case ISD::FMINNAN: 5559 case ISD::FMAXNAN: 5560 5561 if (ST->supportsMinMaxDenormModes() && 5562 DAG.isKnownNeverNaN(Op.getOperand(0)) && 5563 DAG.isKnownNeverNaN(Op.getOperand(1))) 5564 return true; 5565 5566 return (MaxDepth > 0) && 5567 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1) && 5568 isCanonicalized(DAG, Op.getOperand(1), ST, MaxDepth - 1); 5569 5570 case ISD::ConstantFP: { 5571 auto F = cast<ConstantFPSDNode>(Op)->getValueAPF(); 5572 return !F.isDenormal() && !(F.isNaN() && F.isSignaling()); 5573 } 5574 } 5575 return false; 5576 } 5577 5578 // Constant fold canonicalize. 5579 SDValue SITargetLowering::performFCanonicalizeCombine( 5580 SDNode *N, 5581 DAGCombinerInfo &DCI) const { 5582 SelectionDAG &DAG = DCI.DAG; 5583 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0)); 5584 5585 if (!CFP) { 5586 SDValue N0 = N->getOperand(0); 5587 EVT VT = N0.getValueType().getScalarType(); 5588 auto ST = getSubtarget(); 5589 5590 if (((VT == MVT::f32 && ST->hasFP32Denormals()) || 5591 (VT == MVT::f64 && ST->hasFP64Denormals()) || 5592 (VT == MVT::f16 && ST->hasFP16Denormals())) && 5593 DAG.isKnownNeverNaN(N0)) 5594 return N0; 5595 5596 bool IsIEEEMode = Subtarget->enableIEEEBit(DAG.getMachineFunction()); 5597 5598 if ((IsIEEEMode || isKnownNeverSNan(DAG, N0)) && 5599 isCanonicalized(DAG, N0, ST)) 5600 return N0; 5601 5602 return SDValue(); 5603 } 5604 5605 const APFloat &C = CFP->getValueAPF(); 5606 5607 // Flush denormals to 0 if not enabled. 5608 if (C.isDenormal()) { 5609 EVT VT = N->getValueType(0); 5610 EVT SVT = VT.getScalarType(); 5611 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals()) 5612 return DAG.getConstantFP(0.0, SDLoc(N), VT); 5613 5614 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals()) 5615 return DAG.getConstantFP(0.0, SDLoc(N), VT); 5616 5617 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals()) 5618 return DAG.getConstantFP(0.0, SDLoc(N), VT); 5619 } 5620 5621 if (C.isNaN()) { 5622 EVT VT = N->getValueType(0); 5623 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 5624 if (C.isSignaling()) { 5625 // Quiet a signaling NaN. 5626 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 5627 } 5628 5629 // Make sure it is the canonical NaN bitpattern. 5630 // 5631 // TODO: Can we use -1 as the canonical NaN value since it's an inline 5632 // immediate? 5633 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 5634 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 5635 } 5636 5637 return N->getOperand(0); 5638 } 5639 5640 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 5641 switch (Opc) { 5642 case ISD::FMAXNUM: 5643 return AMDGPUISD::FMAX3; 5644 case ISD::SMAX: 5645 return AMDGPUISD::SMAX3; 5646 case ISD::UMAX: 5647 return AMDGPUISD::UMAX3; 5648 case ISD::FMINNUM: 5649 return AMDGPUISD::FMIN3; 5650 case ISD::SMIN: 5651 return AMDGPUISD::SMIN3; 5652 case ISD::UMIN: 5653 return AMDGPUISD::UMIN3; 5654 default: 5655 llvm_unreachable("Not a min/max opcode"); 5656 } 5657 } 5658 5659 SDValue SITargetLowering::performIntMed3ImmCombine( 5660 SelectionDAG &DAG, const SDLoc &SL, 5661 SDValue Op0, SDValue Op1, bool Signed) const { 5662 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 5663 if (!K1) 5664 return SDValue(); 5665 5666 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 5667 if (!K0) 5668 return SDValue(); 5669 5670 if (Signed) { 5671 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 5672 return SDValue(); 5673 } else { 5674 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 5675 return SDValue(); 5676 } 5677 5678 EVT VT = K0->getValueType(0); 5679 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 5680 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 5681 return DAG.getNode(Med3Opc, SL, VT, 5682 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 5683 } 5684 5685 // If there isn't a 16-bit med3 operation, convert to 32-bit. 5686 MVT NVT = MVT::i32; 5687 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5688 5689 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 5690 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 5691 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 5692 5693 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 5694 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 5695 } 5696 5697 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 5698 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 5699 return C; 5700 5701 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 5702 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 5703 return C; 5704 } 5705 5706 return nullptr; 5707 } 5708 5709 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 5710 const SDLoc &SL, 5711 SDValue Op0, 5712 SDValue Op1) const { 5713 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 5714 if (!K1) 5715 return SDValue(); 5716 5717 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 5718 if (!K0) 5719 return SDValue(); 5720 5721 // Ordered >= (although NaN inputs should have folded away by now). 5722 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 5723 if (Cmp == APFloat::cmpGreaterThan) 5724 return SDValue(); 5725 5726 // TODO: Check IEEE bit enabled? 5727 EVT VT = Op0.getValueType(); 5728 if (Subtarget->enableDX10Clamp()) { 5729 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 5730 // hardware fmed3 behavior converting to a min. 5731 // FIXME: Should this be allowing -0.0? 5732 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 5733 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 5734 } 5735 5736 // med3 for f16 is only available on gfx9+, and not available for v2f16. 5737 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 5738 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 5739 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 5740 // then give the other result, which is different from med3 with a NaN 5741 // input. 5742 SDValue Var = Op0.getOperand(0); 5743 if (!isKnownNeverSNan(DAG, Var)) 5744 return SDValue(); 5745 5746 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 5747 Var, SDValue(K0, 0), SDValue(K1, 0)); 5748 } 5749 5750 return SDValue(); 5751 } 5752 5753 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 5754 DAGCombinerInfo &DCI) const { 5755 SelectionDAG &DAG = DCI.DAG; 5756 5757 EVT VT = N->getValueType(0); 5758 unsigned Opc = N->getOpcode(); 5759 SDValue Op0 = N->getOperand(0); 5760 SDValue Op1 = N->getOperand(1); 5761 5762 // Only do this if the inner op has one use since this will just increases 5763 // register pressure for no benefit. 5764 5765 5766 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 5767 VT != MVT::f64 && 5768 ((VT != MVT::f16 && VT != MVT::i16) || Subtarget->hasMin3Max3_16())) { 5769 // max(max(a, b), c) -> max3(a, b, c) 5770 // min(min(a, b), c) -> min3(a, b, c) 5771 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 5772 SDLoc DL(N); 5773 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 5774 DL, 5775 N->getValueType(0), 5776 Op0.getOperand(0), 5777 Op0.getOperand(1), 5778 Op1); 5779 } 5780 5781 // Try commuted. 5782 // max(a, max(b, c)) -> max3(a, b, c) 5783 // min(a, min(b, c)) -> min3(a, b, c) 5784 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 5785 SDLoc DL(N); 5786 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 5787 DL, 5788 N->getValueType(0), 5789 Op0, 5790 Op1.getOperand(0), 5791 Op1.getOperand(1)); 5792 } 5793 } 5794 5795 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 5796 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 5797 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 5798 return Med3; 5799 } 5800 5801 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 5802 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 5803 return Med3; 5804 } 5805 5806 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 5807 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 5808 (Opc == AMDGPUISD::FMIN_LEGACY && 5809 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 5810 (VT == MVT::f32 || VT == MVT::f64 || 5811 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 5812 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 5813 Op0.hasOneUse()) { 5814 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 5815 return Res; 5816 } 5817 5818 return SDValue(); 5819 } 5820 5821 static bool isClampZeroToOne(SDValue A, SDValue B) { 5822 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 5823 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 5824 // FIXME: Should this be allowing -0.0? 5825 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 5826 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 5827 } 5828 } 5829 5830 return false; 5831 } 5832 5833 // FIXME: Should only worry about snans for version with chain. 5834 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 5835 DAGCombinerInfo &DCI) const { 5836 EVT VT = N->getValueType(0); 5837 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 5838 // NaNs. With a NaN input, the order of the operands may change the result. 5839 5840 SelectionDAG &DAG = DCI.DAG; 5841 SDLoc SL(N); 5842 5843 SDValue Src0 = N->getOperand(0); 5844 SDValue Src1 = N->getOperand(1); 5845 SDValue Src2 = N->getOperand(2); 5846 5847 if (isClampZeroToOne(Src0, Src1)) { 5848 // const_a, const_b, x -> clamp is safe in all cases including signaling 5849 // nans. 5850 // FIXME: Should this be allowing -0.0? 5851 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 5852 } 5853 5854 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 5855 // handling no dx10-clamp? 5856 if (Subtarget->enableDX10Clamp()) { 5857 // If NaNs is clamped to 0, we are free to reorder the inputs. 5858 5859 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 5860 std::swap(Src0, Src1); 5861 5862 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 5863 std::swap(Src1, Src2); 5864 5865 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 5866 std::swap(Src0, Src1); 5867 5868 if (isClampZeroToOne(Src1, Src2)) 5869 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 5870 } 5871 5872 return SDValue(); 5873 } 5874 5875 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 5876 DAGCombinerInfo &DCI) const { 5877 SDValue Src0 = N->getOperand(0); 5878 SDValue Src1 = N->getOperand(1); 5879 if (Src0.isUndef() && Src1.isUndef()) 5880 return DCI.DAG.getUNDEF(N->getValueType(0)); 5881 return SDValue(); 5882 } 5883 5884 SDValue SITargetLowering::performExtractVectorEltCombine( 5885 SDNode *N, DAGCombinerInfo &DCI) const { 5886 SDValue Vec = N->getOperand(0); 5887 5888 SelectionDAG &DAG = DCI.DAG; 5889 if (Vec.getOpcode() == ISD::FNEG && allUsesHaveSourceMods(N)) { 5890 SDLoc SL(N); 5891 EVT EltVT = N->getValueType(0); 5892 SDValue Idx = N->getOperand(1); 5893 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5894 Vec.getOperand(0), Idx); 5895 return DAG.getNode(ISD::FNEG, SL, EltVT, Elt); 5896 } 5897 5898 return SDValue(); 5899 } 5900 5901 static bool convertBuildVectorCastElt(SelectionDAG &DAG, 5902 SDValue &Lo, SDValue &Hi) { 5903 if (Hi.getOpcode() == ISD::BITCAST && 5904 Hi.getOperand(0).getValueType() == MVT::f16 && 5905 (isa<ConstantSDNode>(Lo) || Lo.isUndef())) { 5906 Lo = DAG.getNode(ISD::BITCAST, SDLoc(Lo), MVT::f16, Lo); 5907 Hi = Hi.getOperand(0); 5908 return true; 5909 } 5910 5911 return false; 5912 } 5913 5914 SDValue SITargetLowering::performBuildVectorCombine( 5915 SDNode *N, DAGCombinerInfo &DCI) const { 5916 SDLoc SL(N); 5917 5918 if (!isTypeLegal(MVT::v2i16)) 5919 return SDValue(); 5920 SelectionDAG &DAG = DCI.DAG; 5921 EVT VT = N->getValueType(0); 5922 5923 if (VT == MVT::v2i16) { 5924 SDValue Lo = N->getOperand(0); 5925 SDValue Hi = N->getOperand(1); 5926 5927 // v2i16 build_vector (const|undef), (bitcast f16:$x) 5928 // -> bitcast (v2f16 build_vector const|undef, $x 5929 if (convertBuildVectorCastElt(DAG, Lo, Hi)) { 5930 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Lo, Hi }); 5931 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec); 5932 } 5933 5934 if (convertBuildVectorCastElt(DAG, Hi, Lo)) { 5935 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Hi, Lo }); 5936 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec); 5937 } 5938 } 5939 5940 return SDValue(); 5941 } 5942 5943 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 5944 const SDNode *N0, 5945 const SDNode *N1) const { 5946 EVT VT = N0->getValueType(0); 5947 5948 // Only do this if we are not trying to support denormals. v_mad_f32 does not 5949 // support denormals ever. 5950 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) || 5951 (VT == MVT::f16 && !Subtarget->hasFP16Denormals())) 5952 return ISD::FMAD; 5953 5954 const TargetOptions &Options = DAG.getTarget().Options; 5955 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 5956 (N0->getFlags().hasUnsafeAlgebra() && 5957 N1->getFlags().hasUnsafeAlgebra())) && 5958 isFMAFasterThanFMulAndFAdd(VT)) { 5959 return ISD::FMA; 5960 } 5961 5962 return 0; 5963 } 5964 5965 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 5966 EVT VT, 5967 SDValue N0, SDValue N1, SDValue N2, 5968 bool Signed) { 5969 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 5970 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 5971 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 5972 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 5973 } 5974 5975 SDValue SITargetLowering::performAddCombine(SDNode *N, 5976 DAGCombinerInfo &DCI) const { 5977 SelectionDAG &DAG = DCI.DAG; 5978 EVT VT = N->getValueType(0); 5979 SDLoc SL(N); 5980 SDValue LHS = N->getOperand(0); 5981 SDValue RHS = N->getOperand(1); 5982 5983 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 5984 && Subtarget->hasMad64_32() && 5985 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 5986 VT.getScalarSizeInBits() <= 64) { 5987 if (LHS.getOpcode() != ISD::MUL) 5988 std::swap(LHS, RHS); 5989 5990 SDValue MulLHS = LHS.getOperand(0); 5991 SDValue MulRHS = LHS.getOperand(1); 5992 SDValue AddRHS = RHS; 5993 5994 // TODO: Maybe restrict if SGPR inputs. 5995 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 5996 numBitsUnsigned(MulRHS, DAG) <= 32) { 5997 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 5998 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 5999 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 6000 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 6001 } 6002 6003 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 6004 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 6005 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 6006 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 6007 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 6008 } 6009 6010 return SDValue(); 6011 } 6012 6013 if (VT != MVT::i32) 6014 return SDValue(); 6015 6016 // add x, zext (setcc) => addcarry x, 0, setcc 6017 // add x, sext (setcc) => subcarry x, 0, setcc 6018 unsigned Opc = LHS.getOpcode(); 6019 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 6020 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 6021 std::swap(RHS, LHS); 6022 6023 Opc = RHS.getOpcode(); 6024 switch (Opc) { 6025 default: break; 6026 case ISD::ZERO_EXTEND: 6027 case ISD::SIGN_EXTEND: 6028 case ISD::ANY_EXTEND: { 6029 auto Cond = RHS.getOperand(0); 6030 if (!isBoolSGPR(Cond)) 6031 break; 6032 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 6033 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 6034 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 6035 return DAG.getNode(Opc, SL, VTList, Args); 6036 } 6037 case ISD::ADDCARRY: { 6038 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 6039 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 6040 if (!C || C->getZExtValue() != 0) break; 6041 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 6042 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 6043 } 6044 } 6045 return SDValue(); 6046 } 6047 6048 SDValue SITargetLowering::performSubCombine(SDNode *N, 6049 DAGCombinerInfo &DCI) const { 6050 SelectionDAG &DAG = DCI.DAG; 6051 EVT VT = N->getValueType(0); 6052 6053 if (VT != MVT::i32) 6054 return SDValue(); 6055 6056 SDLoc SL(N); 6057 SDValue LHS = N->getOperand(0); 6058 SDValue RHS = N->getOperand(1); 6059 6060 unsigned Opc = LHS.getOpcode(); 6061 if (Opc != ISD::SUBCARRY) 6062 std::swap(RHS, LHS); 6063 6064 if (LHS.getOpcode() == ISD::SUBCARRY) { 6065 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 6066 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 6067 if (!C || C->getZExtValue() != 0) 6068 return SDValue(); 6069 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 6070 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 6071 } 6072 return SDValue(); 6073 } 6074 6075 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 6076 DAGCombinerInfo &DCI) const { 6077 6078 if (N->getValueType(0) != MVT::i32) 6079 return SDValue(); 6080 6081 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6082 if (!C || C->getZExtValue() != 0) 6083 return SDValue(); 6084 6085 SelectionDAG &DAG = DCI.DAG; 6086 SDValue LHS = N->getOperand(0); 6087 6088 // addcarry (add x, y), 0, cc => addcarry x, y, cc 6089 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 6090 unsigned LHSOpc = LHS.getOpcode(); 6091 unsigned Opc = N->getOpcode(); 6092 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 6093 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 6094 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 6095 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 6096 } 6097 return SDValue(); 6098 } 6099 6100 SDValue SITargetLowering::performFAddCombine(SDNode *N, 6101 DAGCombinerInfo &DCI) const { 6102 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 6103 return SDValue(); 6104 6105 SelectionDAG &DAG = DCI.DAG; 6106 EVT VT = N->getValueType(0); 6107 6108 SDLoc SL(N); 6109 SDValue LHS = N->getOperand(0); 6110 SDValue RHS = N->getOperand(1); 6111 6112 // These should really be instruction patterns, but writing patterns with 6113 // source modiifiers is a pain. 6114 6115 // fadd (fadd (a, a), b) -> mad 2.0, a, b 6116 if (LHS.getOpcode() == ISD::FADD) { 6117 SDValue A = LHS.getOperand(0); 6118 if (A == LHS.getOperand(1)) { 6119 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 6120 if (FusedOp != 0) { 6121 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 6122 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 6123 } 6124 } 6125 } 6126 6127 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 6128 if (RHS.getOpcode() == ISD::FADD) { 6129 SDValue A = RHS.getOperand(0); 6130 if (A == RHS.getOperand(1)) { 6131 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 6132 if (FusedOp != 0) { 6133 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 6134 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 6135 } 6136 } 6137 } 6138 6139 return SDValue(); 6140 } 6141 6142 SDValue SITargetLowering::performFSubCombine(SDNode *N, 6143 DAGCombinerInfo &DCI) const { 6144 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 6145 return SDValue(); 6146 6147 SelectionDAG &DAG = DCI.DAG; 6148 SDLoc SL(N); 6149 EVT VT = N->getValueType(0); 6150 assert(!VT.isVector()); 6151 6152 // Try to get the fneg to fold into the source modifier. This undoes generic 6153 // DAG combines and folds them into the mad. 6154 // 6155 // Only do this if we are not trying to support denormals. v_mad_f32 does 6156 // not support denormals ever. 6157 SDValue LHS = N->getOperand(0); 6158 SDValue RHS = N->getOperand(1); 6159 if (LHS.getOpcode() == ISD::FADD) { 6160 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 6161 SDValue A = LHS.getOperand(0); 6162 if (A == LHS.getOperand(1)) { 6163 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 6164 if (FusedOp != 0){ 6165 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 6166 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 6167 6168 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 6169 } 6170 } 6171 } 6172 6173 if (RHS.getOpcode() == ISD::FADD) { 6174 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 6175 6176 SDValue A = RHS.getOperand(0); 6177 if (A == RHS.getOperand(1)) { 6178 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 6179 if (FusedOp != 0){ 6180 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 6181 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 6182 } 6183 } 6184 } 6185 6186 return SDValue(); 6187 } 6188 6189 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 6190 DAGCombinerInfo &DCI) const { 6191 SelectionDAG &DAG = DCI.DAG; 6192 SDLoc SL(N); 6193 6194 SDValue LHS = N->getOperand(0); 6195 SDValue RHS = N->getOperand(1); 6196 EVT VT = LHS.getValueType(); 6197 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 6198 6199 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 6200 if (!CRHS) { 6201 CRHS = dyn_cast<ConstantSDNode>(LHS); 6202 if (CRHS) { 6203 std::swap(LHS, RHS); 6204 CC = getSetCCSwappedOperands(CC); 6205 } 6206 } 6207 6208 if (CRHS && VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 6209 isBoolSGPR(LHS.getOperand(0))) { 6210 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 6211 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 6212 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 6213 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 6214 if ((CRHS->isAllOnesValue() && 6215 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 6216 (CRHS->isNullValue() && 6217 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 6218 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 6219 DAG.getConstant(-1, SL, MVT::i1)); 6220 if ((CRHS->isAllOnesValue() && 6221 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 6222 (CRHS->isNullValue() && 6223 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 6224 return LHS.getOperand(0); 6225 } 6226 6227 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 6228 VT != MVT::f16)) 6229 return SDValue(); 6230 6231 // Match isinf pattern 6232 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 6233 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) { 6234 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 6235 if (!CRHS) 6236 return SDValue(); 6237 6238 const APFloat &APF = CRHS->getValueAPF(); 6239 if (APF.isInfinity() && !APF.isNegative()) { 6240 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY; 6241 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 6242 DAG.getConstant(Mask, SL, MVT::i32)); 6243 } 6244 } 6245 6246 return SDValue(); 6247 } 6248 6249 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 6250 DAGCombinerInfo &DCI) const { 6251 SelectionDAG &DAG = DCI.DAG; 6252 SDLoc SL(N); 6253 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 6254 6255 SDValue Src = N->getOperand(0); 6256 SDValue Srl = N->getOperand(0); 6257 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 6258 Srl = Srl.getOperand(0); 6259 6260 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 6261 if (Srl.getOpcode() == ISD::SRL) { 6262 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 6263 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 6264 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 6265 6266 if (const ConstantSDNode *C = 6267 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 6268 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 6269 EVT(MVT::i32)); 6270 6271 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 6272 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 6273 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 6274 MVT::f32, Srl); 6275 } 6276 } 6277 } 6278 6279 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 6280 6281 KnownBits Known; 6282 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 6283 !DCI.isBeforeLegalizeOps()); 6284 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6285 if (TLI.ShrinkDemandedConstant(Src, Demanded, TLO) || 6286 TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) { 6287 DCI.CommitTargetLoweringOpt(TLO); 6288 } 6289 6290 return SDValue(); 6291 } 6292 6293 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 6294 DAGCombinerInfo &DCI) const { 6295 switch (N->getOpcode()) { 6296 default: 6297 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 6298 case ISD::ADD: 6299 return performAddCombine(N, DCI); 6300 case ISD::SUB: 6301 return performSubCombine(N, DCI); 6302 case ISD::ADDCARRY: 6303 case ISD::SUBCARRY: 6304 return performAddCarrySubCarryCombine(N, DCI); 6305 case ISD::FADD: 6306 return performFAddCombine(N, DCI); 6307 case ISD::FSUB: 6308 return performFSubCombine(N, DCI); 6309 case ISD::SETCC: 6310 return performSetCCCombine(N, DCI); 6311 case ISD::FMAXNUM: 6312 case ISD::FMINNUM: 6313 case ISD::SMAX: 6314 case ISD::SMIN: 6315 case ISD::UMAX: 6316 case ISD::UMIN: 6317 case AMDGPUISD::FMIN_LEGACY: 6318 case AMDGPUISD::FMAX_LEGACY: { 6319 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG && 6320 getTargetMachine().getOptLevel() > CodeGenOpt::None) 6321 return performMinMaxCombine(N, DCI); 6322 break; 6323 } 6324 case ISD::LOAD: 6325 case ISD::STORE: 6326 case ISD::ATOMIC_LOAD: 6327 case ISD::ATOMIC_STORE: 6328 case ISD::ATOMIC_CMP_SWAP: 6329 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 6330 case ISD::ATOMIC_SWAP: 6331 case ISD::ATOMIC_LOAD_ADD: 6332 case ISD::ATOMIC_LOAD_SUB: 6333 case ISD::ATOMIC_LOAD_AND: 6334 case ISD::ATOMIC_LOAD_OR: 6335 case ISD::ATOMIC_LOAD_XOR: 6336 case ISD::ATOMIC_LOAD_NAND: 6337 case ISD::ATOMIC_LOAD_MIN: 6338 case ISD::ATOMIC_LOAD_MAX: 6339 case ISD::ATOMIC_LOAD_UMIN: 6340 case ISD::ATOMIC_LOAD_UMAX: 6341 case AMDGPUISD::ATOMIC_INC: 6342 case AMDGPUISD::ATOMIC_DEC: // TODO: Target mem intrinsics. 6343 if (DCI.isBeforeLegalize()) 6344 break; 6345 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 6346 case ISD::AND: 6347 return performAndCombine(N, DCI); 6348 case ISD::OR: 6349 return performOrCombine(N, DCI); 6350 case ISD::XOR: 6351 return performXorCombine(N, DCI); 6352 case ISD::ZERO_EXTEND: 6353 return performZeroExtendCombine(N, DCI); 6354 case AMDGPUISD::FP_CLASS: 6355 return performClassCombine(N, DCI); 6356 case ISD::FCANONICALIZE: 6357 return performFCanonicalizeCombine(N, DCI); 6358 case AMDGPUISD::FRACT: 6359 case AMDGPUISD::RCP: 6360 case AMDGPUISD::RSQ: 6361 case AMDGPUISD::RCP_LEGACY: 6362 case AMDGPUISD::RSQ_LEGACY: 6363 case AMDGPUISD::RSQ_CLAMP: 6364 case AMDGPUISD::LDEXP: { 6365 SDValue Src = N->getOperand(0); 6366 if (Src.isUndef()) 6367 return Src; 6368 break; 6369 } 6370 case ISD::SINT_TO_FP: 6371 case ISD::UINT_TO_FP: 6372 return performUCharToFloatCombine(N, DCI); 6373 case AMDGPUISD::CVT_F32_UBYTE0: 6374 case AMDGPUISD::CVT_F32_UBYTE1: 6375 case AMDGPUISD::CVT_F32_UBYTE2: 6376 case AMDGPUISD::CVT_F32_UBYTE3: 6377 return performCvtF32UByteNCombine(N, DCI); 6378 case AMDGPUISD::FMED3: 6379 return performFMed3Combine(N, DCI); 6380 case AMDGPUISD::CVT_PKRTZ_F16_F32: 6381 return performCvtPkRTZCombine(N, DCI); 6382 case ISD::SCALAR_TO_VECTOR: { 6383 SelectionDAG &DAG = DCI.DAG; 6384 EVT VT = N->getValueType(0); 6385 6386 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 6387 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 6388 SDLoc SL(N); 6389 SDValue Src = N->getOperand(0); 6390 EVT EltVT = Src.getValueType(); 6391 if (EltVT == MVT::f16) 6392 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 6393 6394 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 6395 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 6396 } 6397 6398 break; 6399 } 6400 case ISD::EXTRACT_VECTOR_ELT: 6401 return performExtractVectorEltCombine(N, DCI); 6402 case ISD::BUILD_VECTOR: 6403 return performBuildVectorCombine(N, DCI); 6404 } 6405 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 6406 } 6407 6408 /// \brief Helper function for adjustWritemask 6409 static unsigned SubIdx2Lane(unsigned Idx) { 6410 switch (Idx) { 6411 default: return 0; 6412 case AMDGPU::sub0: return 0; 6413 case AMDGPU::sub1: return 1; 6414 case AMDGPU::sub2: return 2; 6415 case AMDGPU::sub3: return 3; 6416 } 6417 } 6418 6419 /// \brief Adjust the writemask of MIMG instructions 6420 void SITargetLowering::adjustWritemask(MachineSDNode *&Node, 6421 SelectionDAG &DAG) const { 6422 SDNode *Users[4] = { }; 6423 unsigned Lane = 0; 6424 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3; 6425 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 6426 unsigned NewDmask = 0; 6427 6428 // Try to figure out the used register components 6429 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 6430 I != E; ++I) { 6431 6432 // Don't look at users of the chain. 6433 if (I.getUse().getResNo() != 0) 6434 continue; 6435 6436 // Abort if we can't understand the usage 6437 if (!I->isMachineOpcode() || 6438 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 6439 return; 6440 6441 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used. 6442 // Note that subregs are packed, i.e. Lane==0 is the first bit set 6443 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 6444 // set, etc. 6445 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 6446 6447 // Set which texture component corresponds to the lane. 6448 unsigned Comp; 6449 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) { 6450 assert(Dmask); 6451 Comp = countTrailingZeros(Dmask); 6452 Dmask &= ~(1 << Comp); 6453 } 6454 6455 // Abort if we have more than one user per component 6456 if (Users[Lane]) 6457 return; 6458 6459 Users[Lane] = *I; 6460 NewDmask |= 1 << Comp; 6461 } 6462 6463 // Abort if there's no change 6464 if (NewDmask == OldDmask) 6465 return; 6466 6467 // Adjust the writemask in the node 6468 std::vector<SDValue> Ops; 6469 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 6470 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 6471 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 6472 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops); 6473 6474 // If we only got one lane, replace it with a copy 6475 // (if NewDmask has only one bit set...) 6476 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) { 6477 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(), 6478 MVT::i32); 6479 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, 6480 SDLoc(), Users[Lane]->getValueType(0), 6481 SDValue(Node, 0), RC); 6482 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 6483 return; 6484 } 6485 6486 // Update the users of the node with the new indices 6487 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) { 6488 SDNode *User = Users[i]; 6489 if (!User) 6490 continue; 6491 6492 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 6493 DAG.UpdateNodeOperands(User, User->getOperand(0), Op); 6494 6495 switch (Idx) { 6496 default: break; 6497 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 6498 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 6499 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 6500 } 6501 } 6502 } 6503 6504 static bool isFrameIndexOp(SDValue Op) { 6505 if (Op.getOpcode() == ISD::AssertZext) 6506 Op = Op.getOperand(0); 6507 6508 return isa<FrameIndexSDNode>(Op); 6509 } 6510 6511 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG) 6512 /// with frame index operands. 6513 /// LLVM assumes that inputs are to these instructions are registers. 6514 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 6515 SelectionDAG &DAG) const { 6516 if (Node->getOpcode() == ISD::CopyToReg) { 6517 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 6518 SDValue SrcVal = Node->getOperand(2); 6519 6520 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 6521 // to try understanding copies to physical registers. 6522 if (SrcVal.getValueType() == MVT::i1 && 6523 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) { 6524 SDLoc SL(Node); 6525 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 6526 SDValue VReg = DAG.getRegister( 6527 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 6528 6529 SDNode *Glued = Node->getGluedNode(); 6530 SDValue ToVReg 6531 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 6532 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 6533 SDValue ToResultReg 6534 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 6535 VReg, ToVReg.getValue(1)); 6536 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 6537 DAG.RemoveDeadNode(Node); 6538 return ToResultReg.getNode(); 6539 } 6540 } 6541 6542 SmallVector<SDValue, 8> Ops; 6543 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 6544 if (!isFrameIndexOp(Node->getOperand(i))) { 6545 Ops.push_back(Node->getOperand(i)); 6546 continue; 6547 } 6548 6549 SDLoc DL(Node); 6550 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 6551 Node->getOperand(i).getValueType(), 6552 Node->getOperand(i)), 0)); 6553 } 6554 6555 return DAG.UpdateNodeOperands(Node, Ops); 6556 } 6557 6558 /// \brief Fold the instructions after selecting them. 6559 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 6560 SelectionDAG &DAG) const { 6561 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 6562 unsigned Opcode = Node->getMachineOpcode(); 6563 6564 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 6565 !TII->isGather4(Opcode)) 6566 adjustWritemask(Node, DAG); 6567 6568 if (Opcode == AMDGPU::INSERT_SUBREG || 6569 Opcode == AMDGPU::REG_SEQUENCE) { 6570 legalizeTargetIndependentNode(Node, DAG); 6571 return Node; 6572 } 6573 6574 switch (Opcode) { 6575 case AMDGPU::V_DIV_SCALE_F32: 6576 case AMDGPU::V_DIV_SCALE_F64: { 6577 // Satisfy the operand register constraint when one of the inputs is 6578 // undefined. Ordinarily each undef value will have its own implicit_def of 6579 // a vreg, so force these to use a single register. 6580 SDValue Src0 = Node->getOperand(0); 6581 SDValue Src1 = Node->getOperand(1); 6582 SDValue Src2 = Node->getOperand(2); 6583 6584 if ((Src0.isMachineOpcode() && 6585 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 6586 (Src0 == Src1 || Src0 == Src2)) 6587 break; 6588 6589 MVT VT = Src0.getValueType().getSimpleVT(); 6590 const TargetRegisterClass *RC = getRegClassFor(VT); 6591 6592 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 6593 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 6594 6595 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 6596 UndefReg, Src0, SDValue()); 6597 6598 // src0 must be the same register as src1 or src2, even if the value is 6599 // undefined, so make sure we don't violate this constraint. 6600 if (Src0.isMachineOpcode() && 6601 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 6602 if (Src1.isMachineOpcode() && 6603 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 6604 Src0 = Src1; 6605 else if (Src2.isMachineOpcode() && 6606 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 6607 Src0 = Src2; 6608 else { 6609 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 6610 Src0 = UndefReg; 6611 Src1 = UndefReg; 6612 } 6613 } else 6614 break; 6615 6616 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 6617 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 6618 Ops.push_back(Node->getOperand(I)); 6619 6620 Ops.push_back(ImpDef.getValue(1)); 6621 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 6622 } 6623 default: 6624 break; 6625 } 6626 6627 return Node; 6628 } 6629 6630 /// \brief Assign the register class depending on the number of 6631 /// bits set in the writemask 6632 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 6633 SDNode *Node) const { 6634 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 6635 6636 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 6637 6638 if (TII->isVOP3(MI.getOpcode())) { 6639 // Make sure constant bus requirements are respected. 6640 TII->legalizeOperandsVOP3(MRI, MI); 6641 return; 6642 } 6643 6644 if (TII->isMIMG(MI)) { 6645 unsigned VReg = MI.getOperand(0).getReg(); 6646 const TargetRegisterClass *RC = MRI.getRegClass(VReg); 6647 // TODO: Need mapping tables to handle other cases (register classes). 6648 if (RC != &AMDGPU::VReg_128RegClass) 6649 return; 6650 6651 unsigned DmaskIdx = MI.getNumOperands() == 12 ? 3 : 4; 6652 unsigned Writemask = MI.getOperand(DmaskIdx).getImm(); 6653 unsigned BitsSet = 0; 6654 for (unsigned i = 0; i < 4; ++i) 6655 BitsSet += Writemask & (1 << i) ? 1 : 0; 6656 switch (BitsSet) { 6657 default: return; 6658 case 1: RC = &AMDGPU::VGPR_32RegClass; break; 6659 case 2: RC = &AMDGPU::VReg_64RegClass; break; 6660 case 3: RC = &AMDGPU::VReg_96RegClass; break; 6661 } 6662 6663 unsigned NewOpcode = TII->getMaskedMIMGOp(MI.getOpcode(), BitsSet); 6664 MI.setDesc(TII->get(NewOpcode)); 6665 MRI.setRegClass(VReg, RC); 6666 return; 6667 } 6668 6669 // Replace unused atomics with the no return version. 6670 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 6671 if (NoRetAtomicOp != -1) { 6672 if (!Node->hasAnyUseOfValue(0)) { 6673 MI.setDesc(TII->get(NoRetAtomicOp)); 6674 MI.RemoveOperand(0); 6675 return; 6676 } 6677 6678 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 6679 // instruction, because the return type of these instructions is a vec2 of 6680 // the memory type, so it can be tied to the input operand. 6681 // This means these instructions always have a use, so we need to add a 6682 // special case to check if the atomic has only one extract_subreg use, 6683 // which itself has no uses. 6684 if ((Node->hasNUsesOfValue(1, 0) && 6685 Node->use_begin()->isMachineOpcode() && 6686 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 6687 !Node->use_begin()->hasAnyUseOfValue(0))) { 6688 unsigned Def = MI.getOperand(0).getReg(); 6689 6690 // Change this into a noret atomic. 6691 MI.setDesc(TII->get(NoRetAtomicOp)); 6692 MI.RemoveOperand(0); 6693 6694 // If we only remove the def operand from the atomic instruction, the 6695 // extract_subreg will be left with a use of a vreg without a def. 6696 // So we need to insert an implicit_def to avoid machine verifier 6697 // errors. 6698 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 6699 TII->get(AMDGPU::IMPLICIT_DEF), Def); 6700 } 6701 return; 6702 } 6703 } 6704 6705 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 6706 uint64_t Val) { 6707 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 6708 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 6709 } 6710 6711 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 6712 const SDLoc &DL, 6713 SDValue Ptr) const { 6714 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 6715 6716 // Build the half of the subregister with the constants before building the 6717 // full 128-bit register. If we are building multiple resource descriptors, 6718 // this will allow CSEing of the 2-component register. 6719 const SDValue Ops0[] = { 6720 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 6721 buildSMovImm32(DAG, DL, 0), 6722 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 6723 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 6724 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 6725 }; 6726 6727 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 6728 MVT::v2i32, Ops0), 0); 6729 6730 // Combine the constants and the pointer. 6731 const SDValue Ops1[] = { 6732 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 6733 Ptr, 6734 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 6735 SubRegHi, 6736 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 6737 }; 6738 6739 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 6740 } 6741 6742 /// \brief Return a resource descriptor with the 'Add TID' bit enabled 6743 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 6744 /// of the resource descriptor) to create an offset, which is added to 6745 /// the resource pointer. 6746 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 6747 SDValue Ptr, uint32_t RsrcDword1, 6748 uint64_t RsrcDword2And3) const { 6749 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 6750 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 6751 if (RsrcDword1) { 6752 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 6753 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 6754 0); 6755 } 6756 6757 SDValue DataLo = buildSMovImm32(DAG, DL, 6758 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 6759 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 6760 6761 const SDValue Ops[] = { 6762 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 6763 PtrLo, 6764 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 6765 PtrHi, 6766 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 6767 DataLo, 6768 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 6769 DataHi, 6770 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 6771 }; 6772 6773 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 6774 } 6775 6776 //===----------------------------------------------------------------------===// 6777 // SI Inline Assembly Support 6778 //===----------------------------------------------------------------------===// 6779 6780 std::pair<unsigned, const TargetRegisterClass *> 6781 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 6782 StringRef Constraint, 6783 MVT VT) const { 6784 if (!isTypeLegal(VT)) 6785 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 6786 6787 if (Constraint.size() == 1) { 6788 switch (Constraint[0]) { 6789 case 's': 6790 case 'r': 6791 switch (VT.getSizeInBits()) { 6792 default: 6793 return std::make_pair(0U, nullptr); 6794 case 32: 6795 case 16: 6796 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass); 6797 case 64: 6798 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass); 6799 case 128: 6800 return std::make_pair(0U, &AMDGPU::SReg_128RegClass); 6801 case 256: 6802 return std::make_pair(0U, &AMDGPU::SReg_256RegClass); 6803 case 512: 6804 return std::make_pair(0U, &AMDGPU::SReg_512RegClass); 6805 } 6806 6807 case 'v': 6808 switch (VT.getSizeInBits()) { 6809 default: 6810 return std::make_pair(0U, nullptr); 6811 case 32: 6812 case 16: 6813 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass); 6814 case 64: 6815 return std::make_pair(0U, &AMDGPU::VReg_64RegClass); 6816 case 96: 6817 return std::make_pair(0U, &AMDGPU::VReg_96RegClass); 6818 case 128: 6819 return std::make_pair(0U, &AMDGPU::VReg_128RegClass); 6820 case 256: 6821 return std::make_pair(0U, &AMDGPU::VReg_256RegClass); 6822 case 512: 6823 return std::make_pair(0U, &AMDGPU::VReg_512RegClass); 6824 } 6825 } 6826 } 6827 6828 if (Constraint.size() > 1) { 6829 const TargetRegisterClass *RC = nullptr; 6830 if (Constraint[1] == 'v') { 6831 RC = &AMDGPU::VGPR_32RegClass; 6832 } else if (Constraint[1] == 's') { 6833 RC = &AMDGPU::SGPR_32RegClass; 6834 } 6835 6836 if (RC) { 6837 uint32_t Idx; 6838 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 6839 if (!Failed && Idx < RC->getNumRegs()) 6840 return std::make_pair(RC->getRegister(Idx), RC); 6841 } 6842 } 6843 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 6844 } 6845 6846 SITargetLowering::ConstraintType 6847 SITargetLowering::getConstraintType(StringRef Constraint) const { 6848 if (Constraint.size() == 1) { 6849 switch (Constraint[0]) { 6850 default: break; 6851 case 's': 6852 case 'v': 6853 return C_RegisterClass; 6854 } 6855 } 6856 return TargetLowering::getConstraintType(Constraint); 6857 } 6858 6859 // Figure out which registers should be reserved for stack access. Only after 6860 // the function is legalized do we know all of the non-spill stack objects or if 6861 // calls are present. 6862 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 6863 MachineRegisterInfo &MRI = MF.getRegInfo(); 6864 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 6865 const MachineFrameInfo &MFI = MF.getFrameInfo(); 6866 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 6867 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 6868 6869 if (Info->isEntryFunction()) { 6870 // Callable functions have fixed registers used for stack access. 6871 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 6872 } 6873 6874 // We have to assume the SP is needed in case there are calls in the function 6875 // during lowering. Calls are only detected after the function is 6876 // lowered. We're about to reserve registers, so don't bother using it if we 6877 // aren't really going to use it. 6878 bool NeedSP = !Info->isEntryFunction() || 6879 MFI.hasVarSizedObjects() || 6880 MFI.hasCalls(); 6881 6882 if (NeedSP) { 6883 unsigned ReservedStackPtrOffsetReg = TRI->reservedStackPtrOffsetReg(MF); 6884 Info->setStackPtrOffsetReg(ReservedStackPtrOffsetReg); 6885 6886 assert(Info->getStackPtrOffsetReg() != Info->getFrameOffsetReg()); 6887 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 6888 Info->getStackPtrOffsetReg())); 6889 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 6890 } 6891 6892 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 6893 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 6894 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG, 6895 Info->getScratchWaveOffsetReg()); 6896 6897 TargetLoweringBase::finalizeLowering(MF); 6898 } 6899