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