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 // Adjust the stack pointer for the new arguments... 2152 // These operations are automatically eliminated by the prolog/epilog pass 2153 if (!IsSibCall) { 2154 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL); 2155 2156 unsigned OffsetReg = Info->getScratchWaveOffsetReg(); 2157 2158 // In the HSA case, this should be an identity copy. 2159 SDValue ScratchRSrcReg 2160 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2161 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2162 2163 // TODO: Don't hardcode these registers and get from the callee function. 2164 SDValue ScratchWaveOffsetReg 2165 = DAG.getCopyFromReg(Chain, DL, OffsetReg, MVT::i32); 2166 RegsToPass.emplace_back(AMDGPU::SGPR4, ScratchWaveOffsetReg); 2167 } 2168 2169 // Stack pointer relative accesses are done by changing the offset SGPR. This 2170 // is just the VGPR offset component. 2171 SDValue StackPtr = DAG.getConstant(CalleeUsableStackOffset, DL, MVT::i32); 2172 2173 SmallVector<SDValue, 8> MemOpChains; 2174 MVT PtrVT = MVT::i32; 2175 2176 // Walk the register/memloc assignments, inserting copies/loads. 2177 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 2178 ++i, ++realArgIdx) { 2179 CCValAssign &VA = ArgLocs[i]; 2180 SDValue Arg = OutVals[realArgIdx]; 2181 2182 // Promote the value if needed. 2183 switch (VA.getLocInfo()) { 2184 case CCValAssign::Full: 2185 break; 2186 case CCValAssign::BCvt: 2187 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2188 break; 2189 case CCValAssign::ZExt: 2190 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2191 break; 2192 case CCValAssign::SExt: 2193 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2194 break; 2195 case CCValAssign::AExt: 2196 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2197 break; 2198 case CCValAssign::FPExt: 2199 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2200 break; 2201 default: 2202 llvm_unreachable("Unknown loc info!"); 2203 } 2204 2205 if (VA.isRegLoc()) { 2206 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2207 } else { 2208 assert(VA.isMemLoc()); 2209 2210 SDValue DstAddr; 2211 MachinePointerInfo DstInfo; 2212 2213 unsigned LocMemOffset = VA.getLocMemOffset(); 2214 int32_t Offset = LocMemOffset; 2215 SDValue PtrOff = DAG.getConstant(Offset, DL, MVT::i32); 2216 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 2217 2218 if (IsTailCall) { 2219 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2220 unsigned OpSize = Flags.isByVal() ? 2221 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2222 2223 Offset = Offset + FPDiff; 2224 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2225 2226 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2227 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, DstAddr, StackPtr); 2228 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2229 2230 // Make sure any stack arguments overlapping with where we're storing 2231 // are loaded before this eventual operation. Otherwise they'll be 2232 // clobbered. 2233 2234 // FIXME: Why is this really necessary? This seems to just result in a 2235 // lot of code to copy the stack and write them back to the same 2236 // locations, which are supposed to be immutable? 2237 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2238 } else { 2239 DstAddr = PtrOff; 2240 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2241 } 2242 2243 if (Outs[i].Flags.isByVal()) { 2244 SDValue SizeNode = 2245 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2246 SDValue Cpy = DAG.getMemcpy( 2247 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 2248 /*isVol = */ false, /*AlwaysInline = */ true, 2249 /*isTailCall = */ false, 2250 DstInfo, MachinePointerInfo()); 2251 2252 MemOpChains.push_back(Cpy); 2253 } else { 2254 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo); 2255 MemOpChains.push_back(Store); 2256 } 2257 } 2258 } 2259 2260 // Copy special input registers after user input arguments. 2261 passSpecialInputs(CLI, *Info, RegsToPass, MemOpChains, Chain, StackPtr); 2262 2263 if (!MemOpChains.empty()) 2264 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2265 2266 // Build a sequence of copy-to-reg nodes chained together with token chain 2267 // and flag operands which copy the outgoing args into the appropriate regs. 2268 SDValue InFlag; 2269 for (auto &RegToPass : RegsToPass) { 2270 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2271 RegToPass.second, InFlag); 2272 InFlag = Chain.getValue(1); 2273 } 2274 2275 2276 SDValue PhysReturnAddrReg; 2277 if (IsTailCall) { 2278 // Since the return is being combined with the call, we need to pass on the 2279 // return address. 2280 2281 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2282 SDValue ReturnAddrReg = CreateLiveInRegister( 2283 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2284 2285 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2286 MVT::i64); 2287 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2288 InFlag = Chain.getValue(1); 2289 } 2290 2291 // We don't usually want to end the call-sequence here because we would tidy 2292 // the frame up *after* the call, however in the ABI-changing tail-call case 2293 // we've carefully laid out the parameters so that when sp is reset they'll be 2294 // in the correct location. 2295 if (IsTailCall && !IsSibCall) { 2296 Chain = DAG.getCALLSEQ_END(Chain, 2297 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2298 DAG.getTargetConstant(0, DL, MVT::i32), 2299 InFlag, DL); 2300 InFlag = Chain.getValue(1); 2301 } 2302 2303 std::vector<SDValue> Ops; 2304 Ops.push_back(Chain); 2305 Ops.push_back(Callee); 2306 2307 if (IsTailCall) { 2308 // Each tail call may have to adjust the stack by a different amount, so 2309 // this information must travel along with the operation for eventual 2310 // consumption by emitEpilogue. 2311 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 2312 2313 Ops.push_back(PhysReturnAddrReg); 2314 } 2315 2316 // Add argument registers to the end of the list so that they are known live 2317 // into the call. 2318 for (auto &RegToPass : RegsToPass) { 2319 Ops.push_back(DAG.getRegister(RegToPass.first, 2320 RegToPass.second.getValueType())); 2321 } 2322 2323 // Add a register mask operand representing the call-preserved registers. 2324 2325 const AMDGPURegisterInfo *TRI = Subtarget->getRegisterInfo(); 2326 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2327 assert(Mask && "Missing call preserved mask for calling convention"); 2328 Ops.push_back(DAG.getRegisterMask(Mask)); 2329 2330 if (InFlag.getNode()) 2331 Ops.push_back(InFlag); 2332 2333 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2334 2335 // If we're doing a tall call, use a TC_RETURN here rather than an 2336 // actual call instruction. 2337 if (IsTailCall) { 2338 MFI.setHasTailCall(); 2339 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 2340 } 2341 2342 // Returns a chain and a flag for retval copy to use. 2343 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 2344 Chain = Call.getValue(0); 2345 InFlag = Call.getValue(1); 2346 2347 uint64_t CalleePopBytes = 0; 2348 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2349 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 2350 InFlag, DL); 2351 if (!Ins.empty()) 2352 InFlag = Chain.getValue(1); 2353 2354 // Handle result values, copying them out of physregs into vregs that we 2355 // return. 2356 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 2357 InVals, IsThisReturn, 2358 IsThisReturn ? OutVals[0] : SDValue()); 2359 } 2360 2361 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT, 2362 SelectionDAG &DAG) const { 2363 unsigned Reg = StringSwitch<unsigned>(RegName) 2364 .Case("m0", AMDGPU::M0) 2365 .Case("exec", AMDGPU::EXEC) 2366 .Case("exec_lo", AMDGPU::EXEC_LO) 2367 .Case("exec_hi", AMDGPU::EXEC_HI) 2368 .Case("flat_scratch", AMDGPU::FLAT_SCR) 2369 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 2370 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 2371 .Default(AMDGPU::NoRegister); 2372 2373 if (Reg == AMDGPU::NoRegister) { 2374 report_fatal_error(Twine("invalid register name \"" 2375 + StringRef(RegName) + "\".")); 2376 2377 } 2378 2379 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS && 2380 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 2381 report_fatal_error(Twine("invalid register \"" 2382 + StringRef(RegName) + "\" for subtarget.")); 2383 } 2384 2385 switch (Reg) { 2386 case AMDGPU::M0: 2387 case AMDGPU::EXEC_LO: 2388 case AMDGPU::EXEC_HI: 2389 case AMDGPU::FLAT_SCR_LO: 2390 case AMDGPU::FLAT_SCR_HI: 2391 if (VT.getSizeInBits() == 32) 2392 return Reg; 2393 break; 2394 case AMDGPU::EXEC: 2395 case AMDGPU::FLAT_SCR: 2396 if (VT.getSizeInBits() == 64) 2397 return Reg; 2398 break; 2399 default: 2400 llvm_unreachable("missing register type checking"); 2401 } 2402 2403 report_fatal_error(Twine("invalid type for register \"" 2404 + StringRef(RegName) + "\".")); 2405 } 2406 2407 // If kill is not the last instruction, split the block so kill is always a 2408 // proper terminator. 2409 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 2410 MachineBasicBlock *BB) const { 2411 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 2412 2413 MachineBasicBlock::iterator SplitPoint(&MI); 2414 ++SplitPoint; 2415 2416 if (SplitPoint == BB->end()) { 2417 // Don't bother with a new block. 2418 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR)); 2419 return BB; 2420 } 2421 2422 MachineFunction *MF = BB->getParent(); 2423 MachineBasicBlock *SplitBB 2424 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 2425 2426 MF->insert(++MachineFunction::iterator(BB), SplitBB); 2427 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 2428 2429 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 2430 BB->addSuccessor(SplitBB); 2431 2432 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR)); 2433 return SplitBB; 2434 } 2435 2436 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 2437 // wavefront. If the value is uniform and just happens to be in a VGPR, this 2438 // will only do one iteration. In the worst case, this will loop 64 times. 2439 // 2440 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 2441 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 2442 const SIInstrInfo *TII, 2443 MachineRegisterInfo &MRI, 2444 MachineBasicBlock &OrigBB, 2445 MachineBasicBlock &LoopBB, 2446 const DebugLoc &DL, 2447 const MachineOperand &IdxReg, 2448 unsigned InitReg, 2449 unsigned ResultReg, 2450 unsigned PhiReg, 2451 unsigned InitSaveExecReg, 2452 int Offset, 2453 bool UseGPRIdxMode) { 2454 MachineBasicBlock::iterator I = LoopBB.begin(); 2455 2456 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2457 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2458 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 2459 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2460 2461 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 2462 .addReg(InitReg) 2463 .addMBB(&OrigBB) 2464 .addReg(ResultReg) 2465 .addMBB(&LoopBB); 2466 2467 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 2468 .addReg(InitSaveExecReg) 2469 .addMBB(&OrigBB) 2470 .addReg(NewExec) 2471 .addMBB(&LoopBB); 2472 2473 // Read the next variant <- also loop target. 2474 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 2475 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 2476 2477 // Compare the just read M0 value to all possible Idx values. 2478 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 2479 .addReg(CurrentIdxReg) 2480 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 2481 2482 if (UseGPRIdxMode) { 2483 unsigned IdxReg; 2484 if (Offset == 0) { 2485 IdxReg = CurrentIdxReg; 2486 } else { 2487 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 2488 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 2489 .addReg(CurrentIdxReg, RegState::Kill) 2490 .addImm(Offset); 2491 } 2492 2493 MachineInstr *SetIdx = 2494 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_IDX)) 2495 .addReg(IdxReg, RegState::Kill); 2496 SetIdx->getOperand(2).setIsUndef(); 2497 } else { 2498 // Move index from VCC into M0 2499 if (Offset == 0) { 2500 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 2501 .addReg(CurrentIdxReg, RegState::Kill); 2502 } else { 2503 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 2504 .addReg(CurrentIdxReg, RegState::Kill) 2505 .addImm(Offset); 2506 } 2507 } 2508 2509 // Update EXEC, save the original EXEC value to VCC. 2510 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec) 2511 .addReg(CondReg, RegState::Kill); 2512 2513 MRI.setSimpleHint(NewExec, CondReg); 2514 2515 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 2516 MachineInstr *InsertPt = 2517 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC) 2518 .addReg(AMDGPU::EXEC) 2519 .addReg(NewExec); 2520 2521 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 2522 // s_cbranch_scc0? 2523 2524 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 2525 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 2526 .addMBB(&LoopBB); 2527 2528 return InsertPt->getIterator(); 2529 } 2530 2531 // This has slightly sub-optimal regalloc when the source vector is killed by 2532 // the read. The register allocator does not understand that the kill is 2533 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 2534 // subregister from it, using 1 more VGPR than necessary. This was saved when 2535 // this was expanded after register allocation. 2536 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 2537 MachineBasicBlock &MBB, 2538 MachineInstr &MI, 2539 unsigned InitResultReg, 2540 unsigned PhiReg, 2541 int Offset, 2542 bool UseGPRIdxMode) { 2543 MachineFunction *MF = MBB.getParent(); 2544 MachineRegisterInfo &MRI = MF->getRegInfo(); 2545 const DebugLoc &DL = MI.getDebugLoc(); 2546 MachineBasicBlock::iterator I(&MI); 2547 2548 unsigned DstReg = MI.getOperand(0).getReg(); 2549 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2550 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2551 2552 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 2553 2554 // Save the EXEC mask 2555 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec) 2556 .addReg(AMDGPU::EXEC); 2557 2558 // To insert the loop we need to split the block. Move everything after this 2559 // point to a new block, and insert a new empty block between the two. 2560 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 2561 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 2562 MachineFunction::iterator MBBI(MBB); 2563 ++MBBI; 2564 2565 MF->insert(MBBI, LoopBB); 2566 MF->insert(MBBI, RemainderBB); 2567 2568 LoopBB->addSuccessor(LoopBB); 2569 LoopBB->addSuccessor(RemainderBB); 2570 2571 // Move the rest of the block into a new block. 2572 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 2573 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 2574 2575 MBB.addSuccessor(LoopBB); 2576 2577 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 2578 2579 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 2580 InitResultReg, DstReg, PhiReg, TmpExec, 2581 Offset, UseGPRIdxMode); 2582 2583 MachineBasicBlock::iterator First = RemainderBB->begin(); 2584 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC) 2585 .addReg(SaveExec); 2586 2587 return InsPt; 2588 } 2589 2590 // Returns subreg index, offset 2591 static std::pair<unsigned, int> 2592 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 2593 const TargetRegisterClass *SuperRC, 2594 unsigned VecReg, 2595 int Offset) { 2596 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 2597 2598 // Skip out of bounds offsets, or else we would end up using an undefined 2599 // register. 2600 if (Offset >= NumElts || Offset < 0) 2601 return std::make_pair(AMDGPU::sub0, Offset); 2602 2603 return std::make_pair(AMDGPU::sub0 + Offset, 0); 2604 } 2605 2606 // Return true if the index is an SGPR and was set. 2607 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 2608 MachineRegisterInfo &MRI, 2609 MachineInstr &MI, 2610 int Offset, 2611 bool UseGPRIdxMode, 2612 bool IsIndirectSrc) { 2613 MachineBasicBlock *MBB = MI.getParent(); 2614 const DebugLoc &DL = MI.getDebugLoc(); 2615 MachineBasicBlock::iterator I(&MI); 2616 2617 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 2618 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 2619 2620 assert(Idx->getReg() != AMDGPU::NoRegister); 2621 2622 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 2623 return false; 2624 2625 if (UseGPRIdxMode) { 2626 unsigned IdxMode = IsIndirectSrc ? 2627 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE; 2628 if (Offset == 0) { 2629 MachineInstr *SetOn = 2630 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2631 .add(*Idx) 2632 .addImm(IdxMode); 2633 2634 SetOn->getOperand(3).setIsUndef(); 2635 } else { 2636 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 2637 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 2638 .add(*Idx) 2639 .addImm(Offset); 2640 MachineInstr *SetOn = 2641 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2642 .addReg(Tmp, RegState::Kill) 2643 .addImm(IdxMode); 2644 2645 SetOn->getOperand(3).setIsUndef(); 2646 } 2647 2648 return true; 2649 } 2650 2651 if (Offset == 0) { 2652 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 2653 .add(*Idx); 2654 } else { 2655 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 2656 .add(*Idx) 2657 .addImm(Offset); 2658 } 2659 2660 return true; 2661 } 2662 2663 // Control flow needs to be inserted if indexing with a VGPR. 2664 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 2665 MachineBasicBlock &MBB, 2666 const SISubtarget &ST) { 2667 const SIInstrInfo *TII = ST.getInstrInfo(); 2668 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 2669 MachineFunction *MF = MBB.getParent(); 2670 MachineRegisterInfo &MRI = MF->getRegInfo(); 2671 2672 unsigned Dst = MI.getOperand(0).getReg(); 2673 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 2674 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 2675 2676 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 2677 2678 unsigned SubReg; 2679 std::tie(SubReg, Offset) 2680 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 2681 2682 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 2683 2684 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 2685 MachineBasicBlock::iterator I(&MI); 2686 const DebugLoc &DL = MI.getDebugLoc(); 2687 2688 if (UseGPRIdxMode) { 2689 // TODO: Look at the uses to avoid the copy. This may require rescheduling 2690 // to avoid interfering with other uses, so probably requires a new 2691 // optimization pass. 2692 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 2693 .addReg(SrcReg, RegState::Undef, SubReg) 2694 .addReg(SrcReg, RegState::Implicit) 2695 .addReg(AMDGPU::M0, RegState::Implicit); 2696 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2697 } else { 2698 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 2699 .addReg(SrcReg, RegState::Undef, SubReg) 2700 .addReg(SrcReg, RegState::Implicit); 2701 } 2702 2703 MI.eraseFromParent(); 2704 2705 return &MBB; 2706 } 2707 2708 const DebugLoc &DL = MI.getDebugLoc(); 2709 MachineBasicBlock::iterator I(&MI); 2710 2711 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 2712 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 2713 2714 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 2715 2716 if (UseGPRIdxMode) { 2717 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2718 .addImm(0) // Reset inside loop. 2719 .addImm(VGPRIndexMode::SRC0_ENABLE); 2720 SetOn->getOperand(3).setIsUndef(); 2721 2722 // Disable again after the loop. 2723 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2724 } 2725 2726 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, UseGPRIdxMode); 2727 MachineBasicBlock *LoopBB = InsPt->getParent(); 2728 2729 if (UseGPRIdxMode) { 2730 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 2731 .addReg(SrcReg, RegState::Undef, SubReg) 2732 .addReg(SrcReg, RegState::Implicit) 2733 .addReg(AMDGPU::M0, RegState::Implicit); 2734 } else { 2735 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 2736 .addReg(SrcReg, RegState::Undef, SubReg) 2737 .addReg(SrcReg, RegState::Implicit); 2738 } 2739 2740 MI.eraseFromParent(); 2741 2742 return LoopBB; 2743 } 2744 2745 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI, 2746 const TargetRegisterClass *VecRC) { 2747 switch (TRI.getRegSizeInBits(*VecRC)) { 2748 case 32: // 4 bytes 2749 return AMDGPU::V_MOVRELD_B32_V1; 2750 case 64: // 8 bytes 2751 return AMDGPU::V_MOVRELD_B32_V2; 2752 case 128: // 16 bytes 2753 return AMDGPU::V_MOVRELD_B32_V4; 2754 case 256: // 32 bytes 2755 return AMDGPU::V_MOVRELD_B32_V8; 2756 case 512: // 64 bytes 2757 return AMDGPU::V_MOVRELD_B32_V16; 2758 default: 2759 llvm_unreachable("unsupported size for MOVRELD pseudos"); 2760 } 2761 } 2762 2763 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 2764 MachineBasicBlock &MBB, 2765 const SISubtarget &ST) { 2766 const SIInstrInfo *TII = ST.getInstrInfo(); 2767 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 2768 MachineFunction *MF = MBB.getParent(); 2769 MachineRegisterInfo &MRI = MF->getRegInfo(); 2770 2771 unsigned Dst = MI.getOperand(0).getReg(); 2772 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 2773 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 2774 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 2775 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 2776 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 2777 2778 // This can be an immediate, but will be folded later. 2779 assert(Val->getReg()); 2780 2781 unsigned SubReg; 2782 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 2783 SrcVec->getReg(), 2784 Offset); 2785 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 2786 2787 if (Idx->getReg() == AMDGPU::NoRegister) { 2788 MachineBasicBlock::iterator I(&MI); 2789 const DebugLoc &DL = MI.getDebugLoc(); 2790 2791 assert(Offset == 0); 2792 2793 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 2794 .add(*SrcVec) 2795 .add(*Val) 2796 .addImm(SubReg); 2797 2798 MI.eraseFromParent(); 2799 return &MBB; 2800 } 2801 2802 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 2803 MachineBasicBlock::iterator I(&MI); 2804 const DebugLoc &DL = MI.getDebugLoc(); 2805 2806 if (UseGPRIdxMode) { 2807 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 2808 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst 2809 .add(*Val) 2810 .addReg(Dst, RegState::ImplicitDefine) 2811 .addReg(SrcVec->getReg(), RegState::Implicit) 2812 .addReg(AMDGPU::M0, RegState::Implicit); 2813 2814 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2815 } else { 2816 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 2817 2818 BuildMI(MBB, I, DL, MovRelDesc) 2819 .addReg(Dst, RegState::Define) 2820 .addReg(SrcVec->getReg()) 2821 .add(*Val) 2822 .addImm(SubReg - AMDGPU::sub0); 2823 } 2824 2825 MI.eraseFromParent(); 2826 return &MBB; 2827 } 2828 2829 if (Val->isReg()) 2830 MRI.clearKillFlags(Val->getReg()); 2831 2832 const DebugLoc &DL = MI.getDebugLoc(); 2833 2834 if (UseGPRIdxMode) { 2835 MachineBasicBlock::iterator I(&MI); 2836 2837 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2838 .addImm(0) // Reset inside loop. 2839 .addImm(VGPRIndexMode::DST_ENABLE); 2840 SetOn->getOperand(3).setIsUndef(); 2841 2842 // Disable again after the loop. 2843 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2844 } 2845 2846 unsigned PhiReg = MRI.createVirtualRegister(VecRC); 2847 2848 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 2849 Offset, UseGPRIdxMode); 2850 MachineBasicBlock *LoopBB = InsPt->getParent(); 2851 2852 if (UseGPRIdxMode) { 2853 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 2854 .addReg(PhiReg, RegState::Undef, SubReg) // vdst 2855 .add(*Val) // src0 2856 .addReg(Dst, RegState::ImplicitDefine) 2857 .addReg(PhiReg, RegState::Implicit) 2858 .addReg(AMDGPU::M0, RegState::Implicit); 2859 } else { 2860 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 2861 2862 BuildMI(*LoopBB, InsPt, DL, MovRelDesc) 2863 .addReg(Dst, RegState::Define) 2864 .addReg(PhiReg) 2865 .add(*Val) 2866 .addImm(SubReg - AMDGPU::sub0); 2867 } 2868 2869 MI.eraseFromParent(); 2870 2871 return LoopBB; 2872 } 2873 2874 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 2875 MachineInstr &MI, MachineBasicBlock *BB) const { 2876 2877 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 2878 MachineFunction *MF = BB->getParent(); 2879 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 2880 2881 if (TII->isMIMG(MI)) { 2882 if (!MI.memoperands_empty()) 2883 return BB; 2884 // Add a memoperand for mimg instructions so that they aren't assumed to 2885 // be ordered memory instuctions. 2886 2887 MachinePointerInfo PtrInfo(MFI->getImagePSV()); 2888 MachineMemOperand::Flags Flags = MachineMemOperand::MODereferenceable; 2889 if (MI.mayStore()) 2890 Flags |= MachineMemOperand::MOStore; 2891 2892 if (MI.mayLoad()) 2893 Flags |= MachineMemOperand::MOLoad; 2894 2895 auto MMO = MF->getMachineMemOperand(PtrInfo, Flags, 0, 0); 2896 MI.addMemOperand(*MF, MMO); 2897 return BB; 2898 } 2899 2900 switch (MI.getOpcode()) { 2901 case AMDGPU::SI_INIT_M0: 2902 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 2903 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 2904 .add(MI.getOperand(0)); 2905 MI.eraseFromParent(); 2906 return BB; 2907 2908 case AMDGPU::SI_INIT_EXEC: 2909 // This should be before all vector instructions. 2910 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 2911 AMDGPU::EXEC) 2912 .addImm(MI.getOperand(0).getImm()); 2913 MI.eraseFromParent(); 2914 return BB; 2915 2916 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 2917 // Extract the thread count from an SGPR input and set EXEC accordingly. 2918 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 2919 // 2920 // S_BFE_U32 count, input, {shift, 7} 2921 // S_BFM_B64 exec, count, 0 2922 // S_CMP_EQ_U32 count, 64 2923 // S_CMOV_B64 exec, -1 2924 MachineInstr *FirstMI = &*BB->begin(); 2925 MachineRegisterInfo &MRI = MF->getRegInfo(); 2926 unsigned InputReg = MI.getOperand(0).getReg(); 2927 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 2928 bool Found = false; 2929 2930 // Move the COPY of the input reg to the beginning, so that we can use it. 2931 for (auto I = BB->begin(); I != &MI; I++) { 2932 if (I->getOpcode() != TargetOpcode::COPY || 2933 I->getOperand(0).getReg() != InputReg) 2934 continue; 2935 2936 if (I == FirstMI) { 2937 FirstMI = &*++BB->begin(); 2938 } else { 2939 I->removeFromParent(); 2940 BB->insert(FirstMI, &*I); 2941 } 2942 Found = true; 2943 break; 2944 } 2945 assert(Found); 2946 (void)Found; 2947 2948 // This should be before all vector instructions. 2949 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 2950 .addReg(InputReg) 2951 .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000); 2952 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64), 2953 AMDGPU::EXEC) 2954 .addReg(CountReg) 2955 .addImm(0); 2956 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 2957 .addReg(CountReg, RegState::Kill) 2958 .addImm(64); 2959 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64), 2960 AMDGPU::EXEC) 2961 .addImm(-1); 2962 MI.eraseFromParent(); 2963 return BB; 2964 } 2965 2966 case AMDGPU::GET_GROUPSTATICSIZE: { 2967 DebugLoc DL = MI.getDebugLoc(); 2968 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 2969 .add(MI.getOperand(0)) 2970 .addImm(MFI->getLDSSize()); 2971 MI.eraseFromParent(); 2972 return BB; 2973 } 2974 case AMDGPU::SI_INDIRECT_SRC_V1: 2975 case AMDGPU::SI_INDIRECT_SRC_V2: 2976 case AMDGPU::SI_INDIRECT_SRC_V4: 2977 case AMDGPU::SI_INDIRECT_SRC_V8: 2978 case AMDGPU::SI_INDIRECT_SRC_V16: 2979 return emitIndirectSrc(MI, *BB, *getSubtarget()); 2980 case AMDGPU::SI_INDIRECT_DST_V1: 2981 case AMDGPU::SI_INDIRECT_DST_V2: 2982 case AMDGPU::SI_INDIRECT_DST_V4: 2983 case AMDGPU::SI_INDIRECT_DST_V8: 2984 case AMDGPU::SI_INDIRECT_DST_V16: 2985 return emitIndirectDst(MI, *BB, *getSubtarget()); 2986 case AMDGPU::SI_KILL: 2987 return splitKillBlock(MI, BB); 2988 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 2989 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 2990 2991 unsigned Dst = MI.getOperand(0).getReg(); 2992 unsigned Src0 = MI.getOperand(1).getReg(); 2993 unsigned Src1 = MI.getOperand(2).getReg(); 2994 const DebugLoc &DL = MI.getDebugLoc(); 2995 unsigned SrcCond = MI.getOperand(3).getReg(); 2996 2997 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 2998 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 2999 3000 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3001 .addReg(Src0, 0, AMDGPU::sub0) 3002 .addReg(Src1, 0, AMDGPU::sub0) 3003 .addReg(SrcCond); 3004 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3005 .addReg(Src0, 0, AMDGPU::sub1) 3006 .addReg(Src1, 0, AMDGPU::sub1) 3007 .addReg(SrcCond); 3008 3009 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3010 .addReg(DstLo) 3011 .addImm(AMDGPU::sub0) 3012 .addReg(DstHi) 3013 .addImm(AMDGPU::sub1); 3014 MI.eraseFromParent(); 3015 return BB; 3016 } 3017 case AMDGPU::SI_BR_UNDEF: { 3018 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3019 const DebugLoc &DL = MI.getDebugLoc(); 3020 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3021 .add(MI.getOperand(0)); 3022 Br->getOperand(1).setIsUndef(true); // read undef SCC 3023 MI.eraseFromParent(); 3024 return BB; 3025 } 3026 case AMDGPU::ADJCALLSTACKUP: 3027 case AMDGPU::ADJCALLSTACKDOWN: { 3028 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3029 MachineInstrBuilder MIB(*MF, &MI); 3030 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3031 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 3032 return BB; 3033 } 3034 case AMDGPU::SI_CALL_ISEL: 3035 case AMDGPU::SI_TCRETURN_ISEL: { 3036 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3037 const DebugLoc &DL = MI.getDebugLoc(); 3038 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3039 3040 MachineRegisterInfo &MRI = MF->getRegInfo(); 3041 unsigned GlobalAddrReg = MI.getOperand(0).getReg(); 3042 MachineInstr *PCRel = MRI.getVRegDef(GlobalAddrReg); 3043 assert(PCRel->getOpcode() == AMDGPU::SI_PC_ADD_REL_OFFSET); 3044 3045 const GlobalValue *G = PCRel->getOperand(1).getGlobal(); 3046 3047 MachineInstrBuilder MIB; 3048 if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) { 3049 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg) 3050 .add(MI.getOperand(0)) 3051 .addGlobalAddress(G); 3052 } else { 3053 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_TCRETURN)) 3054 .add(MI.getOperand(0)) 3055 .addGlobalAddress(G); 3056 3057 // There is an additional imm operand for tcreturn, but it should be in the 3058 // right place already. 3059 } 3060 3061 for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I) 3062 MIB.add(MI.getOperand(I)); 3063 3064 MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end()); 3065 MI.eraseFromParent(); 3066 return BB; 3067 } 3068 default: 3069 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3070 } 3071 } 3072 3073 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3074 // This currently forces unfolding various combinations of fsub into fma with 3075 // free fneg'd operands. As long as we have fast FMA (controlled by 3076 // isFMAFasterThanFMulAndFAdd), we should perform these. 3077 3078 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3079 // most of these combines appear to be cycle neutral but save on instruction 3080 // count / code size. 3081 return true; 3082 } 3083 3084 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3085 EVT VT) const { 3086 if (!VT.isVector()) { 3087 return MVT::i1; 3088 } 3089 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3090 } 3091 3092 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3093 // TODO: Should i16 be used always if legal? For now it would force VALU 3094 // shifts. 3095 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3096 } 3097 3098 // Answering this is somewhat tricky and depends on the specific device which 3099 // have different rates for fma or all f64 operations. 3100 // 3101 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3102 // regardless of which device (although the number of cycles differs between 3103 // devices), so it is always profitable for f64. 3104 // 3105 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3106 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3107 // which we can always do even without fused FP ops since it returns the same 3108 // result as the separate operations and since it is always full 3109 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3110 // however does not support denormals, so we do report fma as faster if we have 3111 // a fast fma device and require denormals. 3112 // 3113 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 3114 VT = VT.getScalarType(); 3115 3116 switch (VT.getSimpleVT().SimpleTy) { 3117 case MVT::f32: 3118 // This is as fast on some subtargets. However, we always have full rate f32 3119 // mad available which returns the same result as the separate operations 3120 // which we should prefer over fma. We can't use this if we want to support 3121 // denormals, so only report this in these cases. 3122 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32(); 3123 case MVT::f64: 3124 return true; 3125 case MVT::f16: 3126 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals(); 3127 default: 3128 break; 3129 } 3130 3131 return false; 3132 } 3133 3134 //===----------------------------------------------------------------------===// 3135 // Custom DAG Lowering Operations 3136 //===----------------------------------------------------------------------===// 3137 3138 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 3139 switch (Op.getOpcode()) { 3140 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 3141 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 3142 case ISD::LOAD: { 3143 SDValue Result = LowerLOAD(Op, DAG); 3144 assert((!Result.getNode() || 3145 Result.getNode()->getNumValues() == 2) && 3146 "Load should return a value and a chain"); 3147 return Result; 3148 } 3149 3150 case ISD::FSIN: 3151 case ISD::FCOS: 3152 return LowerTrig(Op, DAG); 3153 case ISD::SELECT: return LowerSELECT(Op, DAG); 3154 case ISD::FDIV: return LowerFDIV(Op, DAG); 3155 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 3156 case ISD::STORE: return LowerSTORE(Op, DAG); 3157 case ISD::GlobalAddress: { 3158 MachineFunction &MF = DAG.getMachineFunction(); 3159 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 3160 return LowerGlobalAddress(MFI, Op, DAG); 3161 } 3162 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3163 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 3164 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 3165 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 3166 case ISD::INSERT_VECTOR_ELT: 3167 return lowerINSERT_VECTOR_ELT(Op, DAG); 3168 case ISD::EXTRACT_VECTOR_ELT: 3169 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3170 case ISD::FP_ROUND: 3171 return lowerFP_ROUND(Op, DAG); 3172 3173 case ISD::TRAP: 3174 case ISD::DEBUGTRAP: 3175 return lowerTRAP(Op, DAG); 3176 } 3177 return SDValue(); 3178 } 3179 3180 void SITargetLowering::ReplaceNodeResults(SDNode *N, 3181 SmallVectorImpl<SDValue> &Results, 3182 SelectionDAG &DAG) const { 3183 switch (N->getOpcode()) { 3184 case ISD::INSERT_VECTOR_ELT: { 3185 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 3186 Results.push_back(Res); 3187 return; 3188 } 3189 case ISD::EXTRACT_VECTOR_ELT: { 3190 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 3191 Results.push_back(Res); 3192 return; 3193 } 3194 case ISD::INTRINSIC_WO_CHAIN: { 3195 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 3196 if (IID == Intrinsic::amdgcn_cvt_pkrtz) { 3197 SDValue Src0 = N->getOperand(1); 3198 SDValue Src1 = N->getOperand(2); 3199 SDLoc SL(N); 3200 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 3201 Src0, Src1); 3202 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 3203 return; 3204 } 3205 break; 3206 } 3207 case ISD::SELECT: { 3208 SDLoc SL(N); 3209 EVT VT = N->getValueType(0); 3210 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 3211 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 3212 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 3213 3214 EVT SelectVT = NewVT; 3215 if (NewVT.bitsLT(MVT::i32)) { 3216 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 3217 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 3218 SelectVT = MVT::i32; 3219 } 3220 3221 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 3222 N->getOperand(0), LHS, RHS); 3223 3224 if (NewVT != SelectVT) 3225 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 3226 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 3227 return; 3228 } 3229 default: 3230 break; 3231 } 3232 } 3233 3234 /// \brief Helper function for LowerBRCOND 3235 static SDNode *findUser(SDValue Value, unsigned Opcode) { 3236 3237 SDNode *Parent = Value.getNode(); 3238 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 3239 I != E; ++I) { 3240 3241 if (I.getUse().get() != Value) 3242 continue; 3243 3244 if (I->getOpcode() == Opcode) 3245 return *I; 3246 } 3247 return nullptr; 3248 } 3249 3250 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 3251 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 3252 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 3253 case Intrinsic::amdgcn_if: 3254 return AMDGPUISD::IF; 3255 case Intrinsic::amdgcn_else: 3256 return AMDGPUISD::ELSE; 3257 case Intrinsic::amdgcn_loop: 3258 return AMDGPUISD::LOOP; 3259 case Intrinsic::amdgcn_end_cf: 3260 llvm_unreachable("should not occur"); 3261 default: 3262 return 0; 3263 } 3264 } 3265 3266 // break, if_break, else_break are all only used as inputs to loop, not 3267 // directly as branch conditions. 3268 return 0; 3269 } 3270 3271 void SITargetLowering::createDebuggerPrologueStackObjects( 3272 MachineFunction &MF) const { 3273 // Create stack objects that are used for emitting debugger prologue. 3274 // 3275 // Debugger prologue writes work group IDs and work item IDs to scratch memory 3276 // at fixed location in the following format: 3277 // offset 0: work group ID x 3278 // offset 4: work group ID y 3279 // offset 8: work group ID z 3280 // offset 16: work item ID x 3281 // offset 20: work item ID y 3282 // offset 24: work item ID z 3283 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3284 int ObjectIdx = 0; 3285 3286 // For each dimension: 3287 for (unsigned i = 0; i < 3; ++i) { 3288 // Create fixed stack object for work group ID. 3289 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true); 3290 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx); 3291 // Create fixed stack object for work item ID. 3292 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true); 3293 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx); 3294 } 3295 } 3296 3297 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 3298 const Triple &TT = getTargetMachine().getTargetTriple(); 3299 return GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS && 3300 AMDGPU::shouldEmitConstantsToTextSection(TT); 3301 } 3302 3303 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 3304 return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS || 3305 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) && 3306 !shouldEmitFixup(GV) && 3307 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3308 } 3309 3310 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 3311 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 3312 } 3313 3314 /// This transforms the control flow intrinsics to get the branch destination as 3315 /// last parameter, also switches branch target with BR if the need arise 3316 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 3317 SelectionDAG &DAG) const { 3318 SDLoc DL(BRCOND); 3319 3320 SDNode *Intr = BRCOND.getOperand(1).getNode(); 3321 SDValue Target = BRCOND.getOperand(2); 3322 SDNode *BR = nullptr; 3323 SDNode *SetCC = nullptr; 3324 3325 if (Intr->getOpcode() == ISD::SETCC) { 3326 // As long as we negate the condition everything is fine 3327 SetCC = Intr; 3328 Intr = SetCC->getOperand(0).getNode(); 3329 3330 } else { 3331 // Get the target from BR if we don't negate the condition 3332 BR = findUser(BRCOND, ISD::BR); 3333 Target = BR->getOperand(1); 3334 } 3335 3336 // FIXME: This changes the types of the intrinsics instead of introducing new 3337 // nodes with the correct types. 3338 // e.g. llvm.amdgcn.loop 3339 3340 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 3341 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 3342 3343 unsigned CFNode = isCFIntrinsic(Intr); 3344 if (CFNode == 0) { 3345 // This is a uniform branch so we don't need to legalize. 3346 return BRCOND; 3347 } 3348 3349 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 3350 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 3351 3352 assert(!SetCC || 3353 (SetCC->getConstantOperandVal(1) == 1 && 3354 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 3355 ISD::SETNE)); 3356 3357 // operands of the new intrinsic call 3358 SmallVector<SDValue, 4> Ops; 3359 if (HaveChain) 3360 Ops.push_back(BRCOND.getOperand(0)); 3361 3362 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 3363 Ops.push_back(Target); 3364 3365 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 3366 3367 // build the new intrinsic call 3368 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 3369 3370 if (!HaveChain) { 3371 SDValue Ops[] = { 3372 SDValue(Result, 0), 3373 BRCOND.getOperand(0) 3374 }; 3375 3376 Result = DAG.getMergeValues(Ops, DL).getNode(); 3377 } 3378 3379 if (BR) { 3380 // Give the branch instruction our target 3381 SDValue Ops[] = { 3382 BR->getOperand(0), 3383 BRCOND.getOperand(2) 3384 }; 3385 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 3386 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 3387 BR = NewBR.getNode(); 3388 } 3389 3390 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 3391 3392 // Copy the intrinsic results to registers 3393 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 3394 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 3395 if (!CopyToReg) 3396 continue; 3397 3398 Chain = DAG.getCopyToReg( 3399 Chain, DL, 3400 CopyToReg->getOperand(1), 3401 SDValue(Result, i - 1), 3402 SDValue()); 3403 3404 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 3405 } 3406 3407 // Remove the old intrinsic from the chain 3408 DAG.ReplaceAllUsesOfValueWith( 3409 SDValue(Intr, Intr->getNumValues() - 1), 3410 Intr->getOperand(0)); 3411 3412 return Chain; 3413 } 3414 3415 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 3416 SDValue Op, 3417 const SDLoc &DL, 3418 EVT VT) const { 3419 return Op.getValueType().bitsLE(VT) ? 3420 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 3421 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 3422 } 3423 3424 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 3425 assert(Op.getValueType() == MVT::f16 && 3426 "Do not know how to custom lower FP_ROUND for non-f16 type"); 3427 3428 SDValue Src = Op.getOperand(0); 3429 EVT SrcVT = Src.getValueType(); 3430 if (SrcVT != MVT::f64) 3431 return Op; 3432 3433 SDLoc DL(Op); 3434 3435 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 3436 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 3437 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 3438 } 3439 3440 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 3441 SDLoc SL(Op); 3442 MachineFunction &MF = DAG.getMachineFunction(); 3443 SDValue Chain = Op.getOperand(0); 3444 3445 unsigned TrapID = Op.getOpcode() == ISD::DEBUGTRAP ? 3446 SISubtarget::TrapIDLLVMDebugTrap : SISubtarget::TrapIDLLVMTrap; 3447 3448 if (Subtarget->getTrapHandlerAbi() == SISubtarget::TrapHandlerAbiHsa && 3449 Subtarget->isTrapHandlerEnabled()) { 3450 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3451 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 3452 assert(UserSGPR != AMDGPU::NoRegister); 3453 3454 SDValue QueuePtr = CreateLiveInRegister( 3455 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 3456 3457 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 3458 3459 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 3460 QueuePtr, SDValue()); 3461 3462 SDValue Ops[] = { 3463 ToReg, 3464 DAG.getTargetConstant(TrapID, SL, MVT::i16), 3465 SGPR01, 3466 ToReg.getValue(1) 3467 }; 3468 3469 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 3470 } 3471 3472 switch (TrapID) { 3473 case SISubtarget::TrapIDLLVMTrap: 3474 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 3475 case SISubtarget::TrapIDLLVMDebugTrap: { 3476 DiagnosticInfoUnsupported NoTrap(*MF.getFunction(), 3477 "debugtrap handler not supported", 3478 Op.getDebugLoc(), 3479 DS_Warning); 3480 LLVMContext &Ctx = MF.getFunction()->getContext(); 3481 Ctx.diagnose(NoTrap); 3482 return Chain; 3483 } 3484 default: 3485 llvm_unreachable("unsupported trap handler type!"); 3486 } 3487 3488 return Chain; 3489 } 3490 3491 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 3492 SelectionDAG &DAG) const { 3493 // FIXME: Use inline constants (src_{shared, private}_base) instead. 3494 if (Subtarget->hasApertureRegs()) { 3495 unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ? 3496 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 3497 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 3498 unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ? 3499 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 3500 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 3501 unsigned Encoding = 3502 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 3503 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 3504 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 3505 3506 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 3507 SDValue ApertureReg = SDValue( 3508 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 3509 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 3510 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 3511 } 3512 3513 MachineFunction &MF = DAG.getMachineFunction(); 3514 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3515 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 3516 assert(UserSGPR != AMDGPU::NoRegister); 3517 3518 SDValue QueuePtr = CreateLiveInRegister( 3519 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 3520 3521 // Offset into amd_queue_t for group_segment_aperture_base_hi / 3522 // private_segment_aperture_base_hi. 3523 uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44; 3524 3525 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, QueuePtr, 3526 DAG.getConstant(StructOffset, DL, MVT::i64)); 3527 3528 // TODO: Use custom target PseudoSourceValue. 3529 // TODO: We should use the value from the IR intrinsic call, but it might not 3530 // be available and how do we get it? 3531 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()), 3532 AMDGPUASI.CONSTANT_ADDRESS)); 3533 3534 MachinePointerInfo PtrInfo(V, StructOffset); 3535 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 3536 MinAlign(64, StructOffset), 3537 MachineMemOperand::MODereferenceable | 3538 MachineMemOperand::MOInvariant); 3539 } 3540 3541 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 3542 SelectionDAG &DAG) const { 3543 SDLoc SL(Op); 3544 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 3545 3546 SDValue Src = ASC->getOperand(0); 3547 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 3548 3549 const AMDGPUTargetMachine &TM = 3550 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 3551 3552 // flat -> local/private 3553 if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) { 3554 unsigned DestAS = ASC->getDestAddressSpace(); 3555 3556 if (DestAS == AMDGPUASI.LOCAL_ADDRESS || 3557 DestAS == AMDGPUASI.PRIVATE_ADDRESS) { 3558 unsigned NullVal = TM.getNullPointerValue(DestAS); 3559 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 3560 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 3561 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 3562 3563 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 3564 NonNull, Ptr, SegmentNullPtr); 3565 } 3566 } 3567 3568 // local/private -> flat 3569 if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) { 3570 unsigned SrcAS = ASC->getSrcAddressSpace(); 3571 3572 if (SrcAS == AMDGPUASI.LOCAL_ADDRESS || 3573 SrcAS == AMDGPUASI.PRIVATE_ADDRESS) { 3574 unsigned NullVal = TM.getNullPointerValue(SrcAS); 3575 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 3576 3577 SDValue NonNull 3578 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 3579 3580 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 3581 SDValue CvtPtr 3582 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 3583 3584 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 3585 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 3586 FlatNullPtr); 3587 } 3588 } 3589 3590 // global <-> flat are no-ops and never emitted. 3591 3592 const MachineFunction &MF = DAG.getMachineFunction(); 3593 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 3594 *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 3595 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 3596 3597 return DAG.getUNDEF(ASC->getValueType(0)); 3598 } 3599 3600 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 3601 SelectionDAG &DAG) const { 3602 SDValue Idx = Op.getOperand(2); 3603 if (isa<ConstantSDNode>(Idx)) 3604 return SDValue(); 3605 3606 // Avoid stack access for dynamic indexing. 3607 SDLoc SL(Op); 3608 SDValue Vec = Op.getOperand(0); 3609 SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1)); 3610 3611 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 3612 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val); 3613 3614 // Convert vector index to bit-index. 3615 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, 3616 DAG.getConstant(16, SL, MVT::i32)); 3617 3618 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 3619 3620 SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32, 3621 DAG.getConstant(0xffff, SL, MVT::i32), 3622 ScaledIdx); 3623 3624 SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal); 3625 SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32, 3626 DAG.getNOT(SL, BFM, MVT::i32), BCVec); 3627 3628 SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS); 3629 return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI); 3630 } 3631 3632 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 3633 SelectionDAG &DAG) const { 3634 SDLoc SL(Op); 3635 3636 EVT ResultVT = Op.getValueType(); 3637 SDValue Vec = Op.getOperand(0); 3638 SDValue Idx = Op.getOperand(1); 3639 3640 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 3641 3642 // Make sure we we do any optimizations that will make it easier to fold 3643 // source modifiers before obscuring it with bit operations. 3644 3645 // XXX - Why doesn't this get called when vector_shuffle is expanded? 3646 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 3647 return Combined; 3648 3649 if (const ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) { 3650 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 3651 3652 if (CIdx->getZExtValue() == 1) { 3653 Result = DAG.getNode(ISD::SRL, SL, MVT::i32, Result, 3654 DAG.getConstant(16, SL, MVT::i32)); 3655 } else { 3656 assert(CIdx->getZExtValue() == 0); 3657 } 3658 3659 if (ResultVT.bitsLT(MVT::i32)) 3660 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result); 3661 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 3662 } 3663 3664 SDValue Sixteen = DAG.getConstant(16, SL, MVT::i32); 3665 3666 // Convert vector index to bit-index. 3667 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Sixteen); 3668 3669 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 3670 SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx); 3671 3672 SDValue Result = Elt; 3673 if (ResultVT.bitsLT(MVT::i32)) 3674 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result); 3675 3676 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 3677 } 3678 3679 bool 3680 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 3681 // We can fold offsets for anything that doesn't require a GOT relocation. 3682 return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS || 3683 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) && 3684 !shouldEmitGOTReloc(GA->getGlobal()); 3685 } 3686 3687 static SDValue 3688 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 3689 const SDLoc &DL, unsigned Offset, EVT PtrVT, 3690 unsigned GAFlags = SIInstrInfo::MO_NONE) { 3691 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 3692 // lowered to the following code sequence: 3693 // 3694 // For constant address space: 3695 // s_getpc_b64 s[0:1] 3696 // s_add_u32 s0, s0, $symbol 3697 // s_addc_u32 s1, s1, 0 3698 // 3699 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 3700 // a fixup or relocation is emitted to replace $symbol with a literal 3701 // constant, which is a pc-relative offset from the encoding of the $symbol 3702 // operand to the global variable. 3703 // 3704 // For global address space: 3705 // s_getpc_b64 s[0:1] 3706 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 3707 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 3708 // 3709 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 3710 // fixups or relocations are emitted to replace $symbol@*@lo and 3711 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 3712 // which is a 64-bit pc-relative offset from the encoding of the $symbol 3713 // operand to the global variable. 3714 // 3715 // What we want here is an offset from the value returned by s_getpc 3716 // (which is the address of the s_add_u32 instruction) to the global 3717 // variable, but since the encoding of $symbol starts 4 bytes after the start 3718 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 3719 // small. This requires us to add 4 to the global variable offset in order to 3720 // compute the correct address. 3721 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 3722 GAFlags); 3723 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 3724 GAFlags == SIInstrInfo::MO_NONE ? 3725 GAFlags : GAFlags + 1); 3726 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 3727 } 3728 3729 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 3730 SDValue Op, 3731 SelectionDAG &DAG) const { 3732 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 3733 const GlobalValue *GV = GSD->getGlobal(); 3734 3735 if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS && 3736 GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS && 3737 // FIXME: It isn't correct to rely on the type of the pointer. This should 3738 // be removed when address space 0 is 64-bit. 3739 !GV->getType()->getElementType()->isFunctionTy()) 3740 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 3741 3742 SDLoc DL(GSD); 3743 EVT PtrVT = Op.getValueType(); 3744 3745 if (shouldEmitFixup(GV)) 3746 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 3747 else if (shouldEmitPCReloc(GV)) 3748 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 3749 SIInstrInfo::MO_REL32); 3750 3751 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 3752 SIInstrInfo::MO_GOTPCREL32); 3753 3754 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 3755 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS); 3756 const DataLayout &DataLayout = DAG.getDataLayout(); 3757 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 3758 // FIXME: Use a PseudoSourceValue once those can be assigned an address space. 3759 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 3760 3761 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 3762 MachineMemOperand::MODereferenceable | 3763 MachineMemOperand::MOInvariant); 3764 } 3765 3766 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 3767 const SDLoc &DL, SDValue V) const { 3768 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 3769 // the destination register. 3770 // 3771 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 3772 // so we will end up with redundant moves to m0. 3773 // 3774 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 3775 3776 // A Null SDValue creates a glue result. 3777 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 3778 V, Chain); 3779 return SDValue(M0, 0); 3780 } 3781 3782 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 3783 SDValue Op, 3784 MVT VT, 3785 unsigned Offset) const { 3786 SDLoc SL(Op); 3787 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 3788 DAG.getEntryNode(), Offset, false); 3789 // The local size values will have the hi 16-bits as zero. 3790 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 3791 DAG.getValueType(VT)); 3792 } 3793 3794 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 3795 EVT VT) { 3796 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(), 3797 "non-hsa intrinsic with hsa target", 3798 DL.getDebugLoc()); 3799 DAG.getContext()->diagnose(BadIntrin); 3800 return DAG.getUNDEF(VT); 3801 } 3802 3803 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 3804 EVT VT) { 3805 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(), 3806 "intrinsic not supported on subtarget", 3807 DL.getDebugLoc()); 3808 DAG.getContext()->diagnose(BadIntrin); 3809 return DAG.getUNDEF(VT); 3810 } 3811 3812 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 3813 SelectionDAG &DAG) const { 3814 MachineFunction &MF = DAG.getMachineFunction(); 3815 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 3816 3817 EVT VT = Op.getValueType(); 3818 SDLoc DL(Op); 3819 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3820 3821 // TODO: Should this propagate fast-math-flags? 3822 3823 switch (IntrinsicID) { 3824 case Intrinsic::amdgcn_implicit_buffer_ptr: { 3825 if (getSubtarget()->isAmdCodeObjectV2(MF)) 3826 return emitNonHSAIntrinsicError(DAG, DL, VT); 3827 return getPreloadedValue(DAG, *MFI, VT, 3828 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 3829 } 3830 case Intrinsic::amdgcn_dispatch_ptr: 3831 case Intrinsic::amdgcn_queue_ptr: { 3832 if (!Subtarget->isAmdCodeObjectV2(MF)) { 3833 DiagnosticInfoUnsupported BadIntrin( 3834 *MF.getFunction(), "unsupported hsa intrinsic without hsa target", 3835 DL.getDebugLoc()); 3836 DAG.getContext()->diagnose(BadIntrin); 3837 return DAG.getUNDEF(VT); 3838 } 3839 3840 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 3841 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 3842 return getPreloadedValue(DAG, *MFI, VT, RegID); 3843 } 3844 case Intrinsic::amdgcn_implicitarg_ptr: { 3845 if (MFI->isEntryFunction()) 3846 return getImplicitArgPtr(DAG, DL); 3847 return getPreloadedValue(DAG, *MFI, VT, 3848 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 3849 } 3850 case Intrinsic::amdgcn_kernarg_segment_ptr: { 3851 return getPreloadedValue(DAG, *MFI, VT, 3852 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 3853 } 3854 case Intrinsic::amdgcn_dispatch_id: { 3855 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 3856 } 3857 case Intrinsic::amdgcn_rcp: 3858 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 3859 case Intrinsic::amdgcn_rsq: 3860 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 3861 case Intrinsic::amdgcn_rsq_legacy: 3862 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 3863 return emitRemovedIntrinsicError(DAG, DL, VT); 3864 3865 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 3866 case Intrinsic::amdgcn_rcp_legacy: 3867 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 3868 return emitRemovedIntrinsicError(DAG, DL, VT); 3869 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 3870 case Intrinsic::amdgcn_rsq_clamp: { 3871 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 3872 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 3873 3874 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 3875 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 3876 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 3877 3878 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 3879 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 3880 DAG.getConstantFP(Max, DL, VT)); 3881 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 3882 DAG.getConstantFP(Min, DL, VT)); 3883 } 3884 case Intrinsic::r600_read_ngroups_x: 3885 if (Subtarget->isAmdHsaOS()) 3886 return emitNonHSAIntrinsicError(DAG, DL, VT); 3887 3888 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3889 SI::KernelInputOffsets::NGROUPS_X, false); 3890 case Intrinsic::r600_read_ngroups_y: 3891 if (Subtarget->isAmdHsaOS()) 3892 return emitNonHSAIntrinsicError(DAG, DL, VT); 3893 3894 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3895 SI::KernelInputOffsets::NGROUPS_Y, false); 3896 case Intrinsic::r600_read_ngroups_z: 3897 if (Subtarget->isAmdHsaOS()) 3898 return emitNonHSAIntrinsicError(DAG, DL, VT); 3899 3900 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3901 SI::KernelInputOffsets::NGROUPS_Z, false); 3902 case Intrinsic::r600_read_global_size_x: 3903 if (Subtarget->isAmdHsaOS()) 3904 return emitNonHSAIntrinsicError(DAG, DL, VT); 3905 3906 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3907 SI::KernelInputOffsets::GLOBAL_SIZE_X, false); 3908 case Intrinsic::r600_read_global_size_y: 3909 if (Subtarget->isAmdHsaOS()) 3910 return emitNonHSAIntrinsicError(DAG, DL, VT); 3911 3912 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3913 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false); 3914 case Intrinsic::r600_read_global_size_z: 3915 if (Subtarget->isAmdHsaOS()) 3916 return emitNonHSAIntrinsicError(DAG, DL, VT); 3917 3918 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 3919 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false); 3920 case Intrinsic::r600_read_local_size_x: 3921 if (Subtarget->isAmdHsaOS()) 3922 return emitNonHSAIntrinsicError(DAG, DL, VT); 3923 3924 return lowerImplicitZextParam(DAG, Op, MVT::i16, 3925 SI::KernelInputOffsets::LOCAL_SIZE_X); 3926 case Intrinsic::r600_read_local_size_y: 3927 if (Subtarget->isAmdHsaOS()) 3928 return emitNonHSAIntrinsicError(DAG, DL, VT); 3929 3930 return lowerImplicitZextParam(DAG, Op, MVT::i16, 3931 SI::KernelInputOffsets::LOCAL_SIZE_Y); 3932 case Intrinsic::r600_read_local_size_z: 3933 if (Subtarget->isAmdHsaOS()) 3934 return emitNonHSAIntrinsicError(DAG, DL, VT); 3935 3936 return lowerImplicitZextParam(DAG, Op, MVT::i16, 3937 SI::KernelInputOffsets::LOCAL_SIZE_Z); 3938 case Intrinsic::amdgcn_workgroup_id_x: 3939 case Intrinsic::r600_read_tgid_x: 3940 return getPreloadedValue(DAG, *MFI, VT, 3941 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 3942 case Intrinsic::amdgcn_workgroup_id_y: 3943 case Intrinsic::r600_read_tgid_y: 3944 return getPreloadedValue(DAG, *MFI, VT, 3945 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 3946 case Intrinsic::amdgcn_workgroup_id_z: 3947 case Intrinsic::r600_read_tgid_z: 3948 return getPreloadedValue(DAG, *MFI, VT, 3949 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 3950 case Intrinsic::amdgcn_workitem_id_x: { 3951 case Intrinsic::r600_read_tidig_x: 3952 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 3953 SDLoc(DAG.getEntryNode()), 3954 MFI->getArgInfo().WorkItemIDX); 3955 } 3956 case Intrinsic::amdgcn_workitem_id_y: 3957 case Intrinsic::r600_read_tidig_y: 3958 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 3959 SDLoc(DAG.getEntryNode()), 3960 MFI->getArgInfo().WorkItemIDY); 3961 case Intrinsic::amdgcn_workitem_id_z: 3962 case Intrinsic::r600_read_tidig_z: 3963 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 3964 SDLoc(DAG.getEntryNode()), 3965 MFI->getArgInfo().WorkItemIDZ); 3966 case AMDGPUIntrinsic::SI_load_const: { 3967 SDValue Ops[] = { 3968 Op.getOperand(1), 3969 Op.getOperand(2) 3970 }; 3971 3972 MachineMemOperand *MMO = MF.getMachineMemOperand( 3973 MachinePointerInfo(), 3974 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3975 MachineMemOperand::MOInvariant, 3976 VT.getStoreSize(), 4); 3977 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL, 3978 Op->getVTList(), Ops, VT, MMO); 3979 } 3980 case Intrinsic::amdgcn_fdiv_fast: 3981 return lowerFDIV_FAST(Op, DAG); 3982 case Intrinsic::amdgcn_interp_mov: { 3983 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 3984 SDValue Glue = M0.getValue(1); 3985 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1), 3986 Op.getOperand(2), Op.getOperand(3), Glue); 3987 } 3988 case Intrinsic::amdgcn_interp_p1: { 3989 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 3990 SDValue Glue = M0.getValue(1); 3991 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1), 3992 Op.getOperand(2), Op.getOperand(3), Glue); 3993 } 3994 case Intrinsic::amdgcn_interp_p2: { 3995 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 3996 SDValue Glue = SDValue(M0.getNode(), 1); 3997 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1), 3998 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4), 3999 Glue); 4000 } 4001 case Intrinsic::amdgcn_sin: 4002 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 4003 4004 case Intrinsic::amdgcn_cos: 4005 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 4006 4007 case Intrinsic::amdgcn_log_clamp: { 4008 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 4009 return SDValue(); 4010 4011 DiagnosticInfoUnsupported BadIntrin( 4012 *MF.getFunction(), "intrinsic not supported on subtarget", 4013 DL.getDebugLoc()); 4014 DAG.getContext()->diagnose(BadIntrin); 4015 return DAG.getUNDEF(VT); 4016 } 4017 case Intrinsic::amdgcn_ldexp: 4018 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 4019 Op.getOperand(1), Op.getOperand(2)); 4020 4021 case Intrinsic::amdgcn_fract: 4022 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 4023 4024 case Intrinsic::amdgcn_class: 4025 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 4026 Op.getOperand(1), Op.getOperand(2)); 4027 case Intrinsic::amdgcn_div_fmas: 4028 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 4029 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 4030 Op.getOperand(4)); 4031 4032 case Intrinsic::amdgcn_div_fixup: 4033 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 4034 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4035 4036 case Intrinsic::amdgcn_trig_preop: 4037 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 4038 Op.getOperand(1), Op.getOperand(2)); 4039 case Intrinsic::amdgcn_div_scale: { 4040 // 3rd parameter required to be a constant. 4041 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 4042 if (!Param) 4043 return DAG.getMergeValues({ DAG.getUNDEF(VT), DAG.getUNDEF(MVT::i1) }, DL); 4044 4045 // Translate to the operands expected by the machine instruction. The 4046 // first parameter must be the same as the first instruction. 4047 SDValue Numerator = Op.getOperand(1); 4048 SDValue Denominator = Op.getOperand(2); 4049 4050 // Note this order is opposite of the machine instruction's operations, 4051 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 4052 // intrinsic has the numerator as the first operand to match a normal 4053 // division operation. 4054 4055 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 4056 4057 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 4058 Denominator, Numerator); 4059 } 4060 case Intrinsic::amdgcn_icmp: { 4061 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 4062 if (!CD) 4063 return DAG.getUNDEF(VT); 4064 4065 int CondCode = CD->getSExtValue(); 4066 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4067 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4068 return DAG.getUNDEF(VT); 4069 4070 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4071 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4072 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 4073 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 4074 } 4075 case Intrinsic::amdgcn_fcmp: { 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 < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4082 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) 4083 return DAG.getUNDEF(VT); 4084 4085 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4086 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4087 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 4088 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 4089 } 4090 case Intrinsic::amdgcn_fmed3: 4091 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 4092 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4093 case Intrinsic::amdgcn_fmul_legacy: 4094 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 4095 Op.getOperand(1), Op.getOperand(2)); 4096 case Intrinsic::amdgcn_sffbh: 4097 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 4098 case Intrinsic::amdgcn_sbfe: 4099 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 4100 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4101 case Intrinsic::amdgcn_ubfe: 4102 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 4103 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4104 case Intrinsic::amdgcn_cvt_pkrtz: { 4105 // FIXME: Stop adding cast if v2f16 legal. 4106 EVT VT = Op.getValueType(); 4107 SDValue Node = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, DL, MVT::i32, 4108 Op.getOperand(1), Op.getOperand(2)); 4109 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 4110 } 4111 case Intrinsic::amdgcn_wqm: { 4112 SDValue Src = Op.getOperand(1); 4113 return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src), 4114 0); 4115 } 4116 case Intrinsic::amdgcn_wwm: { 4117 SDValue Src = Op.getOperand(1); 4118 return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src), 4119 0); 4120 } 4121 default: 4122 return Op; 4123 } 4124 } 4125 4126 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4127 SelectionDAG &DAG) const { 4128 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4129 SDLoc DL(Op); 4130 MachineFunction &MF = DAG.getMachineFunction(); 4131 4132 switch (IntrID) { 4133 case Intrinsic::amdgcn_atomic_inc: 4134 case Intrinsic::amdgcn_atomic_dec: { 4135 MemSDNode *M = cast<MemSDNode>(Op); 4136 unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ? 4137 AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC; 4138 SDValue Ops[] = { 4139 M->getOperand(0), // Chain 4140 M->getOperand(2), // Ptr 4141 M->getOperand(3) // Value 4142 }; 4143 4144 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 4145 M->getMemoryVT(), M->getMemOperand()); 4146 } 4147 case Intrinsic::amdgcn_buffer_load: 4148 case Intrinsic::amdgcn_buffer_load_format: { 4149 SDValue Ops[] = { 4150 Op.getOperand(0), // Chain 4151 Op.getOperand(2), // rsrc 4152 Op.getOperand(3), // vindex 4153 Op.getOperand(4), // offset 4154 Op.getOperand(5), // glc 4155 Op.getOperand(6) // slc 4156 }; 4157 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4158 4159 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 4160 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 4161 EVT VT = Op.getValueType(); 4162 EVT IntVT = VT.changeTypeToInteger(); 4163 4164 MachineMemOperand *MMO = MF.getMachineMemOperand( 4165 MachinePointerInfo(MFI->getBufferPSV()), 4166 MachineMemOperand::MOLoad, 4167 VT.getStoreSize(), VT.getStoreSize()); 4168 4169 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, MMO); 4170 } 4171 case Intrinsic::amdgcn_tbuffer_load: { 4172 SDValue Ops[] = { 4173 Op.getOperand(0), // Chain 4174 Op.getOperand(2), // rsrc 4175 Op.getOperand(3), // vindex 4176 Op.getOperand(4), // voffset 4177 Op.getOperand(5), // soffset 4178 Op.getOperand(6), // offset 4179 Op.getOperand(7), // dfmt 4180 Op.getOperand(8), // nfmt 4181 Op.getOperand(9), // glc 4182 Op.getOperand(10) // slc 4183 }; 4184 4185 EVT VT = Op.getOperand(2).getValueType(); 4186 4187 MachineMemOperand *MMO = MF.getMachineMemOperand( 4188 MachinePointerInfo(), 4189 MachineMemOperand::MOLoad, 4190 VT.getStoreSize(), VT.getStoreSize()); 4191 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 4192 Op->getVTList(), Ops, VT, MMO); 4193 } 4194 // Basic sample. 4195 case Intrinsic::amdgcn_image_sample: 4196 case Intrinsic::amdgcn_image_sample_cl: 4197 case Intrinsic::amdgcn_image_sample_d: 4198 case Intrinsic::amdgcn_image_sample_d_cl: 4199 case Intrinsic::amdgcn_image_sample_l: 4200 case Intrinsic::amdgcn_image_sample_b: 4201 case Intrinsic::amdgcn_image_sample_b_cl: 4202 case Intrinsic::amdgcn_image_sample_lz: 4203 case Intrinsic::amdgcn_image_sample_cd: 4204 case Intrinsic::amdgcn_image_sample_cd_cl: 4205 4206 // Sample with comparison. 4207 case Intrinsic::amdgcn_image_sample_c: 4208 case Intrinsic::amdgcn_image_sample_c_cl: 4209 case Intrinsic::amdgcn_image_sample_c_d: 4210 case Intrinsic::amdgcn_image_sample_c_d_cl: 4211 case Intrinsic::amdgcn_image_sample_c_l: 4212 case Intrinsic::amdgcn_image_sample_c_b: 4213 case Intrinsic::amdgcn_image_sample_c_b_cl: 4214 case Intrinsic::amdgcn_image_sample_c_lz: 4215 case Intrinsic::amdgcn_image_sample_c_cd: 4216 case Intrinsic::amdgcn_image_sample_c_cd_cl: 4217 4218 // Sample with offsets. 4219 case Intrinsic::amdgcn_image_sample_o: 4220 case Intrinsic::amdgcn_image_sample_cl_o: 4221 case Intrinsic::amdgcn_image_sample_d_o: 4222 case Intrinsic::amdgcn_image_sample_d_cl_o: 4223 case Intrinsic::amdgcn_image_sample_l_o: 4224 case Intrinsic::amdgcn_image_sample_b_o: 4225 case Intrinsic::amdgcn_image_sample_b_cl_o: 4226 case Intrinsic::amdgcn_image_sample_lz_o: 4227 case Intrinsic::amdgcn_image_sample_cd_o: 4228 case Intrinsic::amdgcn_image_sample_cd_cl_o: 4229 4230 // Sample with comparison and offsets. 4231 case Intrinsic::amdgcn_image_sample_c_o: 4232 case Intrinsic::amdgcn_image_sample_c_cl_o: 4233 case Intrinsic::amdgcn_image_sample_c_d_o: 4234 case Intrinsic::amdgcn_image_sample_c_d_cl_o: 4235 case Intrinsic::amdgcn_image_sample_c_l_o: 4236 case Intrinsic::amdgcn_image_sample_c_b_o: 4237 case Intrinsic::amdgcn_image_sample_c_b_cl_o: 4238 case Intrinsic::amdgcn_image_sample_c_lz_o: 4239 case Intrinsic::amdgcn_image_sample_c_cd_o: 4240 case Intrinsic::amdgcn_image_sample_c_cd_cl_o: 4241 4242 case Intrinsic::amdgcn_image_getlod: { 4243 // Replace dmask with everything disabled with undef. 4244 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(5)); 4245 if (!DMask || DMask->isNullValue()) { 4246 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 4247 return DAG.getMergeValues({ Undef, Op.getOperand(0) }, SDLoc(Op)); 4248 } 4249 4250 return SDValue(); 4251 } 4252 default: 4253 return SDValue(); 4254 } 4255 } 4256 4257 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4258 SelectionDAG &DAG) const { 4259 SDLoc DL(Op); 4260 SDValue Chain = Op.getOperand(0); 4261 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4262 MachineFunction &MF = DAG.getMachineFunction(); 4263 4264 switch (IntrinsicID) { 4265 case Intrinsic::amdgcn_exp: { 4266 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 4267 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 4268 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8)); 4269 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9)); 4270 4271 const SDValue Ops[] = { 4272 Chain, 4273 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 4274 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 4275 Op.getOperand(4), // src0 4276 Op.getOperand(5), // src1 4277 Op.getOperand(6), // src2 4278 Op.getOperand(7), // src3 4279 DAG.getTargetConstant(0, DL, MVT::i1), // compr 4280 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 4281 }; 4282 4283 unsigned Opc = Done->isNullValue() ? 4284 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 4285 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 4286 } 4287 case Intrinsic::amdgcn_exp_compr: { 4288 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 4289 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 4290 SDValue Src0 = Op.getOperand(4); 4291 SDValue Src1 = Op.getOperand(5); 4292 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 4293 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7)); 4294 4295 SDValue Undef = DAG.getUNDEF(MVT::f32); 4296 const SDValue Ops[] = { 4297 Chain, 4298 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 4299 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 4300 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), 4301 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), 4302 Undef, // src2 4303 Undef, // src3 4304 DAG.getTargetConstant(1, DL, MVT::i1), // compr 4305 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 4306 }; 4307 4308 unsigned Opc = Done->isNullValue() ? 4309 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 4310 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 4311 } 4312 case Intrinsic::amdgcn_s_sendmsg: 4313 case Intrinsic::amdgcn_s_sendmsghalt: { 4314 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ? 4315 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT; 4316 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 4317 SDValue Glue = Chain.getValue(1); 4318 return DAG.getNode(NodeOp, DL, MVT::Other, Chain, 4319 Op.getOperand(2), Glue); 4320 } 4321 case Intrinsic::amdgcn_init_exec: { 4322 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain, 4323 Op.getOperand(2)); 4324 } 4325 case Intrinsic::amdgcn_init_exec_from_input: { 4326 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain, 4327 Op.getOperand(2), Op.getOperand(3)); 4328 } 4329 case AMDGPUIntrinsic::AMDGPU_kill: { 4330 SDValue Src = Op.getOperand(2); 4331 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) { 4332 if (!K->isNegative()) 4333 return Chain; 4334 4335 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32); 4336 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne); 4337 } 4338 4339 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src); 4340 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast); 4341 } 4342 case Intrinsic::amdgcn_s_barrier: { 4343 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 4344 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 4345 unsigned WGSize = ST.getFlatWorkGroupSizes(*MF.getFunction()).second; 4346 if (WGSize <= ST.getWavefrontSize()) 4347 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 4348 Op.getOperand(0)), 0); 4349 } 4350 return SDValue(); 4351 }; 4352 case AMDGPUIntrinsic::SI_tbuffer_store: { 4353 4354 // Extract vindex and voffset from vaddr as appropriate 4355 const ConstantSDNode *OffEn = cast<ConstantSDNode>(Op.getOperand(10)); 4356 const ConstantSDNode *IdxEn = cast<ConstantSDNode>(Op.getOperand(11)); 4357 SDValue VAddr = Op.getOperand(5); 4358 4359 SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32); 4360 4361 assert(!(OffEn->isOne() && IdxEn->isOne()) && 4362 "Legacy intrinsic doesn't support both offset and index - use new version"); 4363 4364 SDValue VIndex = IdxEn->isOne() ? VAddr : Zero; 4365 SDValue VOffset = OffEn->isOne() ? VAddr : Zero; 4366 4367 // Deal with the vec-3 case 4368 const ConstantSDNode *NumChannels = cast<ConstantSDNode>(Op.getOperand(4)); 4369 auto Opcode = NumChannels->getZExtValue() == 3 ? 4370 AMDGPUISD::TBUFFER_STORE_FORMAT_X3 : AMDGPUISD::TBUFFER_STORE_FORMAT; 4371 4372 SDValue Ops[] = { 4373 Chain, 4374 Op.getOperand(3), // vdata 4375 Op.getOperand(2), // rsrc 4376 VIndex, 4377 VOffset, 4378 Op.getOperand(6), // soffset 4379 Op.getOperand(7), // inst_offset 4380 Op.getOperand(8), // dfmt 4381 Op.getOperand(9), // nfmt 4382 Op.getOperand(12), // glc 4383 Op.getOperand(13), // slc 4384 }; 4385 4386 assert((cast<ConstantSDNode>(Op.getOperand(14)))->getZExtValue() == 0 && 4387 "Value of tfe other than zero is unsupported"); 4388 4389 EVT VT = Op.getOperand(3).getValueType(); 4390 MachineMemOperand *MMO = MF.getMachineMemOperand( 4391 MachinePointerInfo(), 4392 MachineMemOperand::MOStore, 4393 VT.getStoreSize(), 4); 4394 return DAG.getMemIntrinsicNode(Opcode, DL, 4395 Op->getVTList(), Ops, VT, MMO); 4396 } 4397 4398 case Intrinsic::amdgcn_tbuffer_store: { 4399 SDValue Ops[] = { 4400 Chain, 4401 Op.getOperand(2), // vdata 4402 Op.getOperand(3), // rsrc 4403 Op.getOperand(4), // vindex 4404 Op.getOperand(5), // voffset 4405 Op.getOperand(6), // soffset 4406 Op.getOperand(7), // offset 4407 Op.getOperand(8), // dfmt 4408 Op.getOperand(9), // nfmt 4409 Op.getOperand(10), // glc 4410 Op.getOperand(11) // slc 4411 }; 4412 EVT VT = Op.getOperand(3).getValueType(); 4413 MachineMemOperand *MMO = MF.getMachineMemOperand( 4414 MachinePointerInfo(), 4415 MachineMemOperand::MOStore, 4416 VT.getStoreSize(), 4); 4417 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL, 4418 Op->getVTList(), Ops, VT, MMO); 4419 } 4420 4421 default: 4422 return Op; 4423 } 4424 } 4425 4426 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 4427 SDLoc DL(Op); 4428 LoadSDNode *Load = cast<LoadSDNode>(Op); 4429 ISD::LoadExtType ExtType = Load->getExtensionType(); 4430 EVT MemVT = Load->getMemoryVT(); 4431 4432 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 4433 // FIXME: Copied from PPC 4434 // First, load into 32 bits, then truncate to 1 bit. 4435 4436 SDValue Chain = Load->getChain(); 4437 SDValue BasePtr = Load->getBasePtr(); 4438 MachineMemOperand *MMO = Load->getMemOperand(); 4439 4440 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 4441 4442 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 4443 BasePtr, RealMemVT, MMO); 4444 4445 SDValue Ops[] = { 4446 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 4447 NewLD.getValue(1) 4448 }; 4449 4450 return DAG.getMergeValues(Ops, DL); 4451 } 4452 4453 if (!MemVT.isVector()) 4454 return SDValue(); 4455 4456 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 4457 "Custom lowering for non-i32 vectors hasn't been implemented."); 4458 4459 unsigned AS = Load->getAddressSpace(); 4460 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 4461 AS, Load->getAlignment())) { 4462 SDValue Ops[2]; 4463 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 4464 return DAG.getMergeValues(Ops, DL); 4465 } 4466 4467 MachineFunction &MF = DAG.getMachineFunction(); 4468 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4469 // If there is a possibilty that flat instruction access scratch memory 4470 // then we need to use the same legalization rules we use for private. 4471 if (AS == AMDGPUASI.FLAT_ADDRESS) 4472 AS = MFI->hasFlatScratchInit() ? 4473 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS; 4474 4475 unsigned NumElements = MemVT.getVectorNumElements(); 4476 if (AS == AMDGPUASI.CONSTANT_ADDRESS) { 4477 if (isMemOpUniform(Load)) 4478 return SDValue(); 4479 // Non-uniform loads will be selected to MUBUF instructions, so they 4480 // have the same legalization requirements as global and private 4481 // loads. 4482 // 4483 } 4484 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS) { 4485 if (Subtarget->getScalarizeGlobalBehavior() && isMemOpUniform(Load) && 4486 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load)) 4487 return SDValue(); 4488 // Non-uniform loads will be selected to MUBUF instructions, so they 4489 // have the same legalization requirements as global and private 4490 // loads. 4491 // 4492 } 4493 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS || 4494 AS == AMDGPUASI.FLAT_ADDRESS) { 4495 if (NumElements > 4) 4496 return SplitVectorLoad(Op, DAG); 4497 // v4 loads are supported for private and global memory. 4498 return SDValue(); 4499 } 4500 if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 4501 // Depending on the setting of the private_element_size field in the 4502 // resource descriptor, we can only make private accesses up to a certain 4503 // size. 4504 switch (Subtarget->getMaxPrivateElementSize()) { 4505 case 4: 4506 return scalarizeVectorLoad(Load, DAG); 4507 case 8: 4508 if (NumElements > 2) 4509 return SplitVectorLoad(Op, DAG); 4510 return SDValue(); 4511 case 16: 4512 // Same as global/flat 4513 if (NumElements > 4) 4514 return SplitVectorLoad(Op, DAG); 4515 return SDValue(); 4516 default: 4517 llvm_unreachable("unsupported private_element_size"); 4518 } 4519 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 4520 if (NumElements > 2) 4521 return SplitVectorLoad(Op, DAG); 4522 4523 if (NumElements == 2) 4524 return SDValue(); 4525 4526 // If properly aligned, if we split we might be able to use ds_read_b64. 4527 return SplitVectorLoad(Op, DAG); 4528 } 4529 return SDValue(); 4530 } 4531 4532 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4533 if (Op.getValueType() != MVT::i64) 4534 return SDValue(); 4535 4536 SDLoc DL(Op); 4537 SDValue Cond = Op.getOperand(0); 4538 4539 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 4540 SDValue One = DAG.getConstant(1, DL, MVT::i32); 4541 4542 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 4543 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 4544 4545 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 4546 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 4547 4548 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 4549 4550 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 4551 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 4552 4553 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 4554 4555 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 4556 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res); 4557 } 4558 4559 // Catch division cases where we can use shortcuts with rcp and rsq 4560 // instructions. 4561 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 4562 SelectionDAG &DAG) const { 4563 SDLoc SL(Op); 4564 SDValue LHS = Op.getOperand(0); 4565 SDValue RHS = Op.getOperand(1); 4566 EVT VT = Op.getValueType(); 4567 const SDNodeFlags Flags = Op->getFlags(); 4568 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || 4569 Flags.hasUnsafeAlgebra() || Flags.hasAllowReciprocal(); 4570 4571 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals()) 4572 return SDValue(); 4573 4574 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 4575 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) { 4576 if (CLHS->isExactlyValue(1.0)) { 4577 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 4578 // the CI documentation has a worst case error of 1 ulp. 4579 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 4580 // use it as long as we aren't trying to use denormals. 4581 // 4582 // v_rcp_f16 and v_rsq_f16 DO support denormals. 4583 4584 // 1.0 / sqrt(x) -> rsq(x) 4585 4586 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 4587 // error seems really high at 2^29 ULP. 4588 if (RHS.getOpcode() == ISD::FSQRT) 4589 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 4590 4591 // 1.0 / x -> rcp(x) 4592 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 4593 } 4594 4595 // Same as for 1.0, but expand the sign out of the constant. 4596 if (CLHS->isExactlyValue(-1.0)) { 4597 // -1.0 / x -> rcp (fneg x) 4598 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 4599 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 4600 } 4601 } 4602 } 4603 4604 if (Unsafe) { 4605 // Turn into multiply by the reciprocal. 4606 // x / y -> x * (1.0 / y) 4607 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 4608 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 4609 } 4610 4611 return SDValue(); 4612 } 4613 4614 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 4615 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 4616 if (GlueChain->getNumValues() <= 1) { 4617 return DAG.getNode(Opcode, SL, VT, A, B); 4618 } 4619 4620 assert(GlueChain->getNumValues() == 3); 4621 4622 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 4623 switch (Opcode) { 4624 default: llvm_unreachable("no chain equivalent for opcode"); 4625 case ISD::FMUL: 4626 Opcode = AMDGPUISD::FMUL_W_CHAIN; 4627 break; 4628 } 4629 4630 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 4631 GlueChain.getValue(2)); 4632 } 4633 4634 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 4635 EVT VT, SDValue A, SDValue B, SDValue C, 4636 SDValue GlueChain) { 4637 if (GlueChain->getNumValues() <= 1) { 4638 return DAG.getNode(Opcode, SL, VT, A, B, C); 4639 } 4640 4641 assert(GlueChain->getNumValues() == 3); 4642 4643 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 4644 switch (Opcode) { 4645 default: llvm_unreachable("no chain equivalent for opcode"); 4646 case ISD::FMA: 4647 Opcode = AMDGPUISD::FMA_W_CHAIN; 4648 break; 4649 } 4650 4651 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 4652 GlueChain.getValue(2)); 4653 } 4654 4655 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 4656 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 4657 return FastLowered; 4658 4659 SDLoc SL(Op); 4660 SDValue Src0 = Op.getOperand(0); 4661 SDValue Src1 = Op.getOperand(1); 4662 4663 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4664 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4665 4666 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 4667 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 4668 4669 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 4670 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 4671 4672 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 4673 } 4674 4675 // Faster 2.5 ULP division that does not support denormals. 4676 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 4677 SDLoc SL(Op); 4678 SDValue LHS = Op.getOperand(1); 4679 SDValue RHS = Op.getOperand(2); 4680 4681 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 4682 4683 const APFloat K0Val(BitsToFloat(0x6f800000)); 4684 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 4685 4686 const APFloat K1Val(BitsToFloat(0x2f800000)); 4687 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 4688 4689 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 4690 4691 EVT SetCCVT = 4692 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 4693 4694 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 4695 4696 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 4697 4698 // TODO: Should this propagate fast-math-flags? 4699 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 4700 4701 // rcp does not support denormals. 4702 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 4703 4704 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 4705 4706 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 4707 } 4708 4709 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 4710 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 4711 return FastLowered; 4712 4713 SDLoc SL(Op); 4714 SDValue LHS = Op.getOperand(0); 4715 SDValue RHS = Op.getOperand(1); 4716 4717 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 4718 4719 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 4720 4721 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 4722 RHS, RHS, LHS); 4723 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 4724 LHS, RHS, LHS); 4725 4726 // Denominator is scaled to not be denormal, so using rcp is ok. 4727 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 4728 DenominatorScaled); 4729 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 4730 DenominatorScaled); 4731 4732 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 4733 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 4734 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 4735 4736 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 4737 4738 if (!Subtarget->hasFP32Denormals()) { 4739 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 4740 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 4741 SL, MVT::i32); 4742 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 4743 DAG.getEntryNode(), 4744 EnableDenormValue, BitField); 4745 SDValue Ops[3] = { 4746 NegDivScale0, 4747 EnableDenorm.getValue(0), 4748 EnableDenorm.getValue(1) 4749 }; 4750 4751 NegDivScale0 = DAG.getMergeValues(Ops, SL); 4752 } 4753 4754 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 4755 ApproxRcp, One, NegDivScale0); 4756 4757 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 4758 ApproxRcp, Fma0); 4759 4760 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 4761 Fma1, Fma1); 4762 4763 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 4764 NumeratorScaled, Mul); 4765 4766 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 4767 4768 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 4769 NumeratorScaled, Fma3); 4770 4771 if (!Subtarget->hasFP32Denormals()) { 4772 const SDValue DisableDenormValue = 4773 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 4774 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 4775 Fma4.getValue(1), 4776 DisableDenormValue, 4777 BitField, 4778 Fma4.getValue(2)); 4779 4780 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 4781 DisableDenorm, DAG.getRoot()); 4782 DAG.setRoot(OutputChain); 4783 } 4784 4785 SDValue Scale = NumeratorScaled.getValue(1); 4786 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 4787 Fma4, Fma1, Fma3, Scale); 4788 4789 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 4790 } 4791 4792 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 4793 if (DAG.getTarget().Options.UnsafeFPMath) 4794 return lowerFastUnsafeFDIV(Op, DAG); 4795 4796 SDLoc SL(Op); 4797 SDValue X = Op.getOperand(0); 4798 SDValue Y = Op.getOperand(1); 4799 4800 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 4801 4802 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 4803 4804 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 4805 4806 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 4807 4808 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 4809 4810 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 4811 4812 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 4813 4814 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 4815 4816 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 4817 4818 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 4819 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 4820 4821 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 4822 NegDivScale0, Mul, DivScale1); 4823 4824 SDValue Scale; 4825 4826 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) { 4827 // Workaround a hardware bug on SI where the condition output from div_scale 4828 // is not usable. 4829 4830 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 4831 4832 // Figure out if the scale to use for div_fmas. 4833 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 4834 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 4835 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 4836 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 4837 4838 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 4839 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 4840 4841 SDValue Scale0Hi 4842 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 4843 SDValue Scale1Hi 4844 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 4845 4846 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 4847 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 4848 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 4849 } else { 4850 Scale = DivScale1.getValue(1); 4851 } 4852 4853 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 4854 Fma4, Fma3, Mul, Scale); 4855 4856 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 4857 } 4858 4859 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 4860 EVT VT = Op.getValueType(); 4861 4862 if (VT == MVT::f32) 4863 return LowerFDIV32(Op, DAG); 4864 4865 if (VT == MVT::f64) 4866 return LowerFDIV64(Op, DAG); 4867 4868 if (VT == MVT::f16) 4869 return LowerFDIV16(Op, DAG); 4870 4871 llvm_unreachable("Unexpected type for fdiv"); 4872 } 4873 4874 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 4875 SDLoc DL(Op); 4876 StoreSDNode *Store = cast<StoreSDNode>(Op); 4877 EVT VT = Store->getMemoryVT(); 4878 4879 if (VT == MVT::i1) { 4880 return DAG.getTruncStore(Store->getChain(), DL, 4881 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 4882 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 4883 } 4884 4885 assert(VT.isVector() && 4886 Store->getValue().getValueType().getScalarType() == MVT::i32); 4887 4888 unsigned AS = Store->getAddressSpace(); 4889 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 4890 AS, Store->getAlignment())) { 4891 return expandUnalignedStore(Store, DAG); 4892 } 4893 4894 MachineFunction &MF = DAG.getMachineFunction(); 4895 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4896 // If there is a possibilty that flat instruction access scratch memory 4897 // then we need to use the same legalization rules we use for private. 4898 if (AS == AMDGPUASI.FLAT_ADDRESS) 4899 AS = MFI->hasFlatScratchInit() ? 4900 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS; 4901 4902 unsigned NumElements = VT.getVectorNumElements(); 4903 if (AS == AMDGPUASI.GLOBAL_ADDRESS || 4904 AS == AMDGPUASI.FLAT_ADDRESS) { 4905 if (NumElements > 4) 4906 return SplitVectorStore(Op, DAG); 4907 return SDValue(); 4908 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 4909 switch (Subtarget->getMaxPrivateElementSize()) { 4910 case 4: 4911 return scalarizeVectorStore(Store, DAG); 4912 case 8: 4913 if (NumElements > 2) 4914 return SplitVectorStore(Op, DAG); 4915 return SDValue(); 4916 case 16: 4917 if (NumElements > 4) 4918 return SplitVectorStore(Op, DAG); 4919 return SDValue(); 4920 default: 4921 llvm_unreachable("unsupported private_element_size"); 4922 } 4923 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 4924 if (NumElements > 2) 4925 return SplitVectorStore(Op, DAG); 4926 4927 if (NumElements == 2) 4928 return Op; 4929 4930 // If properly aligned, if we split we might be able to use ds_write_b64. 4931 return SplitVectorStore(Op, DAG); 4932 } else { 4933 llvm_unreachable("unhandled address space"); 4934 } 4935 } 4936 4937 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 4938 SDLoc DL(Op); 4939 EVT VT = Op.getValueType(); 4940 SDValue Arg = Op.getOperand(0); 4941 // TODO: Should this propagate fast-math-flags? 4942 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT, 4943 DAG.getNode(ISD::FMUL, DL, VT, Arg, 4944 DAG.getConstantFP(0.5/M_PI, DL, 4945 VT))); 4946 4947 switch (Op.getOpcode()) { 4948 case ISD::FCOS: 4949 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart); 4950 case ISD::FSIN: 4951 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart); 4952 default: 4953 llvm_unreachable("Wrong trig opcode"); 4954 } 4955 } 4956 4957 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 4958 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 4959 assert(AtomicNode->isCompareAndSwap()); 4960 unsigned AS = AtomicNode->getAddressSpace(); 4961 4962 // No custom lowering required for local address space 4963 if (!isFlatGlobalAddrSpace(AS, AMDGPUASI)) 4964 return Op; 4965 4966 // Non-local address space requires custom lowering for atomic compare 4967 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 4968 SDLoc DL(Op); 4969 SDValue ChainIn = Op.getOperand(0); 4970 SDValue Addr = Op.getOperand(1); 4971 SDValue Old = Op.getOperand(2); 4972 SDValue New = Op.getOperand(3); 4973 EVT VT = Op.getValueType(); 4974 MVT SimpleVT = VT.getSimpleVT(); 4975 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 4976 4977 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 4978 SDValue Ops[] = { ChainIn, Addr, NewOld }; 4979 4980 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 4981 Ops, VT, AtomicNode->getMemOperand()); 4982 } 4983 4984 //===----------------------------------------------------------------------===// 4985 // Custom DAG optimizations 4986 //===----------------------------------------------------------------------===// 4987 4988 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 4989 DAGCombinerInfo &DCI) const { 4990 EVT VT = N->getValueType(0); 4991 EVT ScalarVT = VT.getScalarType(); 4992 if (ScalarVT != MVT::f32) 4993 return SDValue(); 4994 4995 SelectionDAG &DAG = DCI.DAG; 4996 SDLoc DL(N); 4997 4998 SDValue Src = N->getOperand(0); 4999 EVT SrcVT = Src.getValueType(); 5000 5001 // TODO: We could try to match extracting the higher bytes, which would be 5002 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 5003 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 5004 // about in practice. 5005 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) { 5006 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 5007 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 5008 DCI.AddToWorklist(Cvt.getNode()); 5009 return Cvt; 5010 } 5011 } 5012 5013 return SDValue(); 5014 } 5015 5016 /// \brief Return true if the given offset Size in bytes can be folded into 5017 /// the immediate offsets of a memory instruction for the given address space. 5018 static bool canFoldOffset(unsigned OffsetSize, unsigned AS, 5019 const SISubtarget &STI) { 5020 auto AMDGPUASI = STI.getAMDGPUAS(); 5021 if (AS == AMDGPUASI.GLOBAL_ADDRESS) { 5022 // MUBUF instructions a 12-bit offset in bytes. 5023 return isUInt<12>(OffsetSize); 5024 } 5025 if (AS == AMDGPUASI.CONSTANT_ADDRESS) { 5026 // SMRD instructions have an 8-bit offset in dwords on SI and 5027 // a 20-bit offset in bytes on VI. 5028 if (STI.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 5029 return isUInt<20>(OffsetSize); 5030 else 5031 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4); 5032 } 5033 if (AS == AMDGPUASI.LOCAL_ADDRESS || 5034 AS == AMDGPUASI.REGION_ADDRESS) { 5035 // The single offset versions have a 16-bit offset in bytes. 5036 return isUInt<16>(OffsetSize); 5037 } 5038 // Indirect register addressing does not use any offsets. 5039 return false; 5040 } 5041 5042 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 5043 5044 // This is a variant of 5045 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 5046 // 5047 // The normal DAG combiner will do this, but only if the add has one use since 5048 // that would increase the number of instructions. 5049 // 5050 // This prevents us from seeing a constant offset that can be folded into a 5051 // memory instruction's addressing mode. If we know the resulting add offset of 5052 // a pointer can be folded into an addressing offset, we can replace the pointer 5053 // operand with the add of new constant offset. This eliminates one of the uses, 5054 // and may allow the remaining use to also be simplified. 5055 // 5056 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 5057 unsigned AddrSpace, 5058 DAGCombinerInfo &DCI) const { 5059 SDValue N0 = N->getOperand(0); 5060 SDValue N1 = N->getOperand(1); 5061 5062 if (N0.getOpcode() != ISD::ADD) 5063 return SDValue(); 5064 5065 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 5066 if (!CN1) 5067 return SDValue(); 5068 5069 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5070 if (!CAdd) 5071 return SDValue(); 5072 5073 // If the resulting offset is too large, we can't fold it into the addressing 5074 // mode offset. 5075 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 5076 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *getSubtarget())) 5077 return SDValue(); 5078 5079 SelectionDAG &DAG = DCI.DAG; 5080 SDLoc SL(N); 5081 EVT VT = N->getValueType(0); 5082 5083 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 5084 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 5085 5086 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset); 5087 } 5088 5089 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 5090 DAGCombinerInfo &DCI) const { 5091 SDValue Ptr = N->getBasePtr(); 5092 SelectionDAG &DAG = DCI.DAG; 5093 SDLoc SL(N); 5094 5095 // TODO: We could also do this for multiplies. 5096 unsigned AS = N->getAddressSpace(); 5097 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUASI.PRIVATE_ADDRESS) { 5098 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI); 5099 if (NewPtr) { 5100 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 5101 5102 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 5103 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 5104 } 5105 } 5106 5107 return SDValue(); 5108 } 5109 5110 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 5111 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 5112 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 5113 (Opc == ISD::XOR && Val == 0); 5114 } 5115 5116 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 5117 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 5118 // integer combine opportunities since most 64-bit operations are decomposed 5119 // this way. TODO: We won't want this for SALU especially if it is an inline 5120 // immediate. 5121 SDValue SITargetLowering::splitBinaryBitConstantOp( 5122 DAGCombinerInfo &DCI, 5123 const SDLoc &SL, 5124 unsigned Opc, SDValue LHS, 5125 const ConstantSDNode *CRHS) const { 5126 uint64_t Val = CRHS->getZExtValue(); 5127 uint32_t ValLo = Lo_32(Val); 5128 uint32_t ValHi = Hi_32(Val); 5129 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 5130 5131 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 5132 bitOpWithConstantIsReducible(Opc, ValHi)) || 5133 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 5134 // If we need to materialize a 64-bit immediate, it will be split up later 5135 // anyway. Avoid creating the harder to understand 64-bit immediate 5136 // materialization. 5137 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 5138 } 5139 5140 return SDValue(); 5141 } 5142 5143 // Returns true if argument is a boolean value which is not serialized into 5144 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 5145 static bool isBoolSGPR(SDValue V) { 5146 if (V.getValueType() != MVT::i1) 5147 return false; 5148 switch (V.getOpcode()) { 5149 default: break; 5150 case ISD::SETCC: 5151 case ISD::AND: 5152 case ISD::OR: 5153 case ISD::XOR: 5154 case AMDGPUISD::FP_CLASS: 5155 return true; 5156 } 5157 return false; 5158 } 5159 5160 SDValue SITargetLowering::performAndCombine(SDNode *N, 5161 DAGCombinerInfo &DCI) const { 5162 if (DCI.isBeforeLegalize()) 5163 return SDValue(); 5164 5165 SelectionDAG &DAG = DCI.DAG; 5166 EVT VT = N->getValueType(0); 5167 SDValue LHS = N->getOperand(0); 5168 SDValue RHS = N->getOperand(1); 5169 5170 5171 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 5172 if (VT == MVT::i64 && CRHS) { 5173 if (SDValue Split 5174 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 5175 return Split; 5176 } 5177 5178 if (CRHS && VT == MVT::i32) { 5179 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 5180 // nb = number of trailing zeroes in mask 5181 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 5182 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 5183 uint64_t Mask = CRHS->getZExtValue(); 5184 unsigned Bits = countPopulation(Mask); 5185 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 5186 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 5187 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 5188 unsigned Shift = CShift->getZExtValue(); 5189 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 5190 unsigned Offset = NB + Shift; 5191 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 5192 SDLoc SL(N); 5193 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 5194 LHS->getOperand(0), 5195 DAG.getConstant(Offset, SL, MVT::i32), 5196 DAG.getConstant(Bits, SL, MVT::i32)); 5197 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 5198 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 5199 DAG.getValueType(NarrowVT)); 5200 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 5201 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 5202 return Shl; 5203 } 5204 } 5205 } 5206 } 5207 5208 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 5209 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 5210 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 5211 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 5212 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 5213 5214 SDValue X = LHS.getOperand(0); 5215 SDValue Y = RHS.getOperand(0); 5216 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 5217 return SDValue(); 5218 5219 if (LCC == ISD::SETO) { 5220 if (X != LHS.getOperand(1)) 5221 return SDValue(); 5222 5223 if (RCC == ISD::SETUNE) { 5224 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 5225 if (!C1 || !C1->isInfinity() || C1->isNegative()) 5226 return SDValue(); 5227 5228 const uint32_t Mask = SIInstrFlags::N_NORMAL | 5229 SIInstrFlags::N_SUBNORMAL | 5230 SIInstrFlags::N_ZERO | 5231 SIInstrFlags::P_ZERO | 5232 SIInstrFlags::P_SUBNORMAL | 5233 SIInstrFlags::P_NORMAL; 5234 5235 static_assert(((~(SIInstrFlags::S_NAN | 5236 SIInstrFlags::Q_NAN | 5237 SIInstrFlags::N_INFINITY | 5238 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 5239 "mask not equal"); 5240 5241 SDLoc DL(N); 5242 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 5243 X, DAG.getConstant(Mask, DL, MVT::i32)); 5244 } 5245 } 5246 } 5247 5248 if (VT == MVT::i32 && 5249 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 5250 // and x, (sext cc from i1) => select cc, x, 0 5251 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 5252 std::swap(LHS, RHS); 5253 if (isBoolSGPR(RHS.getOperand(0))) 5254 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 5255 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 5256 } 5257 5258 return SDValue(); 5259 } 5260 5261 SDValue SITargetLowering::performOrCombine(SDNode *N, 5262 DAGCombinerInfo &DCI) const { 5263 SelectionDAG &DAG = DCI.DAG; 5264 SDValue LHS = N->getOperand(0); 5265 SDValue RHS = N->getOperand(1); 5266 5267 EVT VT = N->getValueType(0); 5268 if (VT == MVT::i1) { 5269 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 5270 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 5271 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 5272 SDValue Src = LHS.getOperand(0); 5273 if (Src != RHS.getOperand(0)) 5274 return SDValue(); 5275 5276 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 5277 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 5278 if (!CLHS || !CRHS) 5279 return SDValue(); 5280 5281 // Only 10 bits are used. 5282 static const uint32_t MaxMask = 0x3ff; 5283 5284 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 5285 SDLoc DL(N); 5286 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 5287 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 5288 } 5289 5290 return SDValue(); 5291 } 5292 5293 if (VT != MVT::i64) 5294 return SDValue(); 5295 5296 // TODO: This could be a generic combine with a predicate for extracting the 5297 // high half of an integer being free. 5298 5299 // (or i64:x, (zero_extend i32:y)) -> 5300 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 5301 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 5302 RHS.getOpcode() != ISD::ZERO_EXTEND) 5303 std::swap(LHS, RHS); 5304 5305 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 5306 SDValue ExtSrc = RHS.getOperand(0); 5307 EVT SrcVT = ExtSrc.getValueType(); 5308 if (SrcVT == MVT::i32) { 5309 SDLoc SL(N); 5310 SDValue LowLHS, HiBits; 5311 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 5312 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 5313 5314 DCI.AddToWorklist(LowOr.getNode()); 5315 DCI.AddToWorklist(HiBits.getNode()); 5316 5317 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 5318 LowOr, HiBits); 5319 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 5320 } 5321 } 5322 5323 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 5324 if (CRHS) { 5325 if (SDValue Split 5326 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 5327 return Split; 5328 } 5329 5330 return SDValue(); 5331 } 5332 5333 SDValue SITargetLowering::performXorCombine(SDNode *N, 5334 DAGCombinerInfo &DCI) const { 5335 EVT VT = N->getValueType(0); 5336 if (VT != MVT::i64) 5337 return SDValue(); 5338 5339 SDValue LHS = N->getOperand(0); 5340 SDValue RHS = N->getOperand(1); 5341 5342 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 5343 if (CRHS) { 5344 if (SDValue Split 5345 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 5346 return Split; 5347 } 5348 5349 return SDValue(); 5350 } 5351 5352 // Instructions that will be lowered with a final instruction that zeros the 5353 // high result bits. 5354 // XXX - probably only need to list legal operations. 5355 static bool fp16SrcZerosHighBits(unsigned Opc) { 5356 switch (Opc) { 5357 case ISD::FADD: 5358 case ISD::FSUB: 5359 case ISD::FMUL: 5360 case ISD::FDIV: 5361 case ISD::FREM: 5362 case ISD::FMA: 5363 case ISD::FMAD: 5364 case ISD::FCANONICALIZE: 5365 case ISD::FP_ROUND: 5366 case ISD::UINT_TO_FP: 5367 case ISD::SINT_TO_FP: 5368 case ISD::FABS: 5369 // Fabs is lowered to a bit operation, but it's an and which will clear the 5370 // high bits anyway. 5371 case ISD::FSQRT: 5372 case ISD::FSIN: 5373 case ISD::FCOS: 5374 case ISD::FPOWI: 5375 case ISD::FPOW: 5376 case ISD::FLOG: 5377 case ISD::FLOG2: 5378 case ISD::FLOG10: 5379 case ISD::FEXP: 5380 case ISD::FEXP2: 5381 case ISD::FCEIL: 5382 case ISD::FTRUNC: 5383 case ISD::FRINT: 5384 case ISD::FNEARBYINT: 5385 case ISD::FROUND: 5386 case ISD::FFLOOR: 5387 case ISD::FMINNUM: 5388 case ISD::FMAXNUM: 5389 case AMDGPUISD::FRACT: 5390 case AMDGPUISD::CLAMP: 5391 case AMDGPUISD::COS_HW: 5392 case AMDGPUISD::SIN_HW: 5393 case AMDGPUISD::FMIN3: 5394 case AMDGPUISD::FMAX3: 5395 case AMDGPUISD::FMED3: 5396 case AMDGPUISD::FMAD_FTZ: 5397 case AMDGPUISD::RCP: 5398 case AMDGPUISD::RSQ: 5399 case AMDGPUISD::LDEXP: 5400 return true; 5401 default: 5402 // fcopysign, select and others may be lowered to 32-bit bit operations 5403 // which don't zero the high bits. 5404 return false; 5405 } 5406 } 5407 5408 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 5409 DAGCombinerInfo &DCI) const { 5410 if (!Subtarget->has16BitInsts() || 5411 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 5412 return SDValue(); 5413 5414 EVT VT = N->getValueType(0); 5415 if (VT != MVT::i32) 5416 return SDValue(); 5417 5418 SDValue Src = N->getOperand(0); 5419 if (Src.getValueType() != MVT::i16) 5420 return SDValue(); 5421 5422 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 5423 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 5424 if (Src.getOpcode() == ISD::BITCAST) { 5425 SDValue BCSrc = Src.getOperand(0); 5426 if (BCSrc.getValueType() == MVT::f16 && 5427 fp16SrcZerosHighBits(BCSrc.getOpcode())) 5428 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 5429 } 5430 5431 return SDValue(); 5432 } 5433 5434 SDValue SITargetLowering::performClassCombine(SDNode *N, 5435 DAGCombinerInfo &DCI) const { 5436 SelectionDAG &DAG = DCI.DAG; 5437 SDValue Mask = N->getOperand(1); 5438 5439 // fp_class x, 0 -> false 5440 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 5441 if (CMask->isNullValue()) 5442 return DAG.getConstant(0, SDLoc(N), MVT::i1); 5443 } 5444 5445 if (N->getOperand(0).isUndef()) 5446 return DAG.getUNDEF(MVT::i1); 5447 5448 return SDValue(); 5449 } 5450 5451 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) { 5452 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions()) 5453 return true; 5454 5455 return DAG.isKnownNeverNaN(Op); 5456 } 5457 5458 static bool isCanonicalized(SelectionDAG &DAG, SDValue Op, 5459 const SISubtarget *ST, unsigned MaxDepth=5) { 5460 // If source is a result of another standard FP operation it is already in 5461 // canonical form. 5462 5463 switch (Op.getOpcode()) { 5464 default: 5465 break; 5466 5467 // These will flush denorms if required. 5468 case ISD::FADD: 5469 case ISD::FSUB: 5470 case ISD::FMUL: 5471 case ISD::FSQRT: 5472 case ISD::FCEIL: 5473 case ISD::FFLOOR: 5474 case ISD::FMA: 5475 case ISD::FMAD: 5476 5477 case ISD::FCANONICALIZE: 5478 return true; 5479 5480 case ISD::FP_ROUND: 5481 return Op.getValueType().getScalarType() != MVT::f16 || 5482 ST->hasFP16Denormals(); 5483 5484 case ISD::FP_EXTEND: 5485 return Op.getOperand(0).getValueType().getScalarType() != MVT::f16 || 5486 ST->hasFP16Denormals(); 5487 5488 case ISD::FP16_TO_FP: 5489 case ISD::FP_TO_FP16: 5490 return ST->hasFP16Denormals(); 5491 5492 // It can/will be lowered or combined as a bit operation. 5493 // Need to check their input recursively to handle. 5494 case ISD::FNEG: 5495 case ISD::FABS: 5496 return (MaxDepth > 0) && 5497 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1); 5498 5499 case ISD::FSIN: 5500 case ISD::FCOS: 5501 case ISD::FSINCOS: 5502 return Op.getValueType().getScalarType() != MVT::f16; 5503 5504 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. 5505 // For such targets need to check their input recursively. 5506 case ISD::FMINNUM: 5507 case ISD::FMAXNUM: 5508 case ISD::FMINNAN: 5509 case ISD::FMAXNAN: 5510 5511 if (ST->supportsMinMaxDenormModes() && 5512 DAG.isKnownNeverNaN(Op.getOperand(0)) && 5513 DAG.isKnownNeverNaN(Op.getOperand(1))) 5514 return true; 5515 5516 return (MaxDepth > 0) && 5517 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1) && 5518 isCanonicalized(DAG, Op.getOperand(1), ST, MaxDepth - 1); 5519 5520 case ISD::ConstantFP: { 5521 auto F = cast<ConstantFPSDNode>(Op)->getValueAPF(); 5522 return !F.isDenormal() && !(F.isNaN() && F.isSignaling()); 5523 } 5524 } 5525 return false; 5526 } 5527 5528 // Constant fold canonicalize. 5529 SDValue SITargetLowering::performFCanonicalizeCombine( 5530 SDNode *N, 5531 DAGCombinerInfo &DCI) const { 5532 SelectionDAG &DAG = DCI.DAG; 5533 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0)); 5534 5535 if (!CFP) { 5536 SDValue N0 = N->getOperand(0); 5537 EVT VT = N0.getValueType().getScalarType(); 5538 auto ST = getSubtarget(); 5539 5540 if (((VT == MVT::f32 && ST->hasFP32Denormals()) || 5541 (VT == MVT::f64 && ST->hasFP64Denormals()) || 5542 (VT == MVT::f16 && ST->hasFP16Denormals())) && 5543 DAG.isKnownNeverNaN(N0)) 5544 return N0; 5545 5546 bool IsIEEEMode = Subtarget->enableIEEEBit(DAG.getMachineFunction()); 5547 5548 if ((IsIEEEMode || isKnownNeverSNan(DAG, N0)) && 5549 isCanonicalized(DAG, N0, ST)) 5550 return N0; 5551 5552 return SDValue(); 5553 } 5554 5555 const APFloat &C = CFP->getValueAPF(); 5556 5557 // Flush denormals to 0 if not enabled. 5558 if (C.isDenormal()) { 5559 EVT VT = N->getValueType(0); 5560 EVT SVT = VT.getScalarType(); 5561 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals()) 5562 return DAG.getConstantFP(0.0, SDLoc(N), VT); 5563 5564 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals()) 5565 return DAG.getConstantFP(0.0, SDLoc(N), VT); 5566 5567 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals()) 5568 return DAG.getConstantFP(0.0, SDLoc(N), VT); 5569 } 5570 5571 if (C.isNaN()) { 5572 EVT VT = N->getValueType(0); 5573 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 5574 if (C.isSignaling()) { 5575 // Quiet a signaling NaN. 5576 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 5577 } 5578 5579 // Make sure it is the canonical NaN bitpattern. 5580 // 5581 // TODO: Can we use -1 as the canonical NaN value since it's an inline 5582 // immediate? 5583 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 5584 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 5585 } 5586 5587 return N->getOperand(0); 5588 } 5589 5590 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 5591 switch (Opc) { 5592 case ISD::FMAXNUM: 5593 return AMDGPUISD::FMAX3; 5594 case ISD::SMAX: 5595 return AMDGPUISD::SMAX3; 5596 case ISD::UMAX: 5597 return AMDGPUISD::UMAX3; 5598 case ISD::FMINNUM: 5599 return AMDGPUISD::FMIN3; 5600 case ISD::SMIN: 5601 return AMDGPUISD::SMIN3; 5602 case ISD::UMIN: 5603 return AMDGPUISD::UMIN3; 5604 default: 5605 llvm_unreachable("Not a min/max opcode"); 5606 } 5607 } 5608 5609 SDValue SITargetLowering::performIntMed3ImmCombine( 5610 SelectionDAG &DAG, const SDLoc &SL, 5611 SDValue Op0, SDValue Op1, bool Signed) const { 5612 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 5613 if (!K1) 5614 return SDValue(); 5615 5616 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 5617 if (!K0) 5618 return SDValue(); 5619 5620 if (Signed) { 5621 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 5622 return SDValue(); 5623 } else { 5624 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 5625 return SDValue(); 5626 } 5627 5628 EVT VT = K0->getValueType(0); 5629 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 5630 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 5631 return DAG.getNode(Med3Opc, SL, VT, 5632 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 5633 } 5634 5635 // If there isn't a 16-bit med3 operation, convert to 32-bit. 5636 MVT NVT = MVT::i32; 5637 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5638 5639 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 5640 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 5641 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 5642 5643 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 5644 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 5645 } 5646 5647 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 5648 const SDLoc &SL, 5649 SDValue Op0, 5650 SDValue Op1) const { 5651 ConstantFPSDNode *K1 = dyn_cast<ConstantFPSDNode>(Op1); 5652 if (!K1) 5653 return SDValue(); 5654 5655 ConstantFPSDNode *K0 = dyn_cast<ConstantFPSDNode>(Op0.getOperand(1)); 5656 if (!K0) 5657 return SDValue(); 5658 5659 // Ordered >= (although NaN inputs should have folded away by now). 5660 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 5661 if (Cmp == APFloat::cmpGreaterThan) 5662 return SDValue(); 5663 5664 // TODO: Check IEEE bit enabled? 5665 EVT VT = K0->getValueType(0); 5666 if (Subtarget->enableDX10Clamp()) { 5667 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 5668 // hardware fmed3 behavior converting to a min. 5669 // FIXME: Should this be allowing -0.0? 5670 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 5671 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 5672 } 5673 5674 // med3 for f16 is only available on gfx9+. 5675 if (VT == MVT::f64 || (VT == MVT::f16 && !Subtarget->hasMed3_16())) 5676 return SDValue(); 5677 5678 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 5679 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would then 5680 // give the other result, which is different from med3 with a NaN input. 5681 SDValue Var = Op0.getOperand(0); 5682 if (!isKnownNeverSNan(DAG, Var)) 5683 return SDValue(); 5684 5685 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 5686 Var, SDValue(K0, 0), SDValue(K1, 0)); 5687 } 5688 5689 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 5690 DAGCombinerInfo &DCI) const { 5691 SelectionDAG &DAG = DCI.DAG; 5692 5693 EVT VT = N->getValueType(0); 5694 unsigned Opc = N->getOpcode(); 5695 SDValue Op0 = N->getOperand(0); 5696 SDValue Op1 = N->getOperand(1); 5697 5698 // Only do this if the inner op has one use since this will just increases 5699 // register pressure for no benefit. 5700 5701 5702 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 5703 VT != MVT::f64 && 5704 ((VT != MVT::f16 && VT != MVT::i16) || Subtarget->hasMin3Max3_16())) { 5705 // max(max(a, b), c) -> max3(a, b, c) 5706 // min(min(a, b), c) -> min3(a, b, c) 5707 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 5708 SDLoc DL(N); 5709 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 5710 DL, 5711 N->getValueType(0), 5712 Op0.getOperand(0), 5713 Op0.getOperand(1), 5714 Op1); 5715 } 5716 5717 // Try commuted. 5718 // max(a, max(b, c)) -> max3(a, b, c) 5719 // min(a, min(b, c)) -> min3(a, b, c) 5720 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 5721 SDLoc DL(N); 5722 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 5723 DL, 5724 N->getValueType(0), 5725 Op0, 5726 Op1.getOperand(0), 5727 Op1.getOperand(1)); 5728 } 5729 } 5730 5731 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 5732 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 5733 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 5734 return Med3; 5735 } 5736 5737 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 5738 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 5739 return Med3; 5740 } 5741 5742 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 5743 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 5744 (Opc == AMDGPUISD::FMIN_LEGACY && 5745 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 5746 (VT == MVT::f32 || VT == MVT::f64 || 5747 (VT == MVT::f16 && Subtarget->has16BitInsts())) && 5748 Op0.hasOneUse()) { 5749 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 5750 return Res; 5751 } 5752 5753 return SDValue(); 5754 } 5755 5756 static bool isClampZeroToOne(SDValue A, SDValue B) { 5757 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 5758 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 5759 // FIXME: Should this be allowing -0.0? 5760 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 5761 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 5762 } 5763 } 5764 5765 return false; 5766 } 5767 5768 // FIXME: Should only worry about snans for version with chain. 5769 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 5770 DAGCombinerInfo &DCI) const { 5771 EVT VT = N->getValueType(0); 5772 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 5773 // NaNs. With a NaN input, the order of the operands may change the result. 5774 5775 SelectionDAG &DAG = DCI.DAG; 5776 SDLoc SL(N); 5777 5778 SDValue Src0 = N->getOperand(0); 5779 SDValue Src1 = N->getOperand(1); 5780 SDValue Src2 = N->getOperand(2); 5781 5782 if (isClampZeroToOne(Src0, Src1)) { 5783 // const_a, const_b, x -> clamp is safe in all cases including signaling 5784 // nans. 5785 // FIXME: Should this be allowing -0.0? 5786 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 5787 } 5788 5789 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 5790 // handling no dx10-clamp? 5791 if (Subtarget->enableDX10Clamp()) { 5792 // If NaNs is clamped to 0, we are free to reorder the inputs. 5793 5794 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 5795 std::swap(Src0, Src1); 5796 5797 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 5798 std::swap(Src1, Src2); 5799 5800 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 5801 std::swap(Src0, Src1); 5802 5803 if (isClampZeroToOne(Src1, Src2)) 5804 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 5805 } 5806 5807 return SDValue(); 5808 } 5809 5810 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 5811 DAGCombinerInfo &DCI) const { 5812 SDValue Src0 = N->getOperand(0); 5813 SDValue Src1 = N->getOperand(1); 5814 if (Src0.isUndef() && Src1.isUndef()) 5815 return DCI.DAG.getUNDEF(N->getValueType(0)); 5816 return SDValue(); 5817 } 5818 5819 SDValue SITargetLowering::performExtractVectorEltCombine( 5820 SDNode *N, DAGCombinerInfo &DCI) const { 5821 SDValue Vec = N->getOperand(0); 5822 5823 SelectionDAG &DAG= DCI.DAG; 5824 if (Vec.getOpcode() == ISD::FNEG && allUsesHaveSourceMods(N)) { 5825 SDLoc SL(N); 5826 EVT EltVT = N->getValueType(0); 5827 SDValue Idx = N->getOperand(1); 5828 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5829 Vec.getOperand(0), Idx); 5830 return DAG.getNode(ISD::FNEG, SL, EltVT, Elt); 5831 } 5832 5833 return SDValue(); 5834 } 5835 5836 5837 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 5838 const SDNode *N0, 5839 const SDNode *N1) const { 5840 EVT VT = N0->getValueType(0); 5841 5842 // Only do this if we are not trying to support denormals. v_mad_f32 does not 5843 // support denormals ever. 5844 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) || 5845 (VT == MVT::f16 && !Subtarget->hasFP16Denormals())) 5846 return ISD::FMAD; 5847 5848 const TargetOptions &Options = DAG.getTarget().Options; 5849 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 5850 (N0->getFlags().hasUnsafeAlgebra() && 5851 N1->getFlags().hasUnsafeAlgebra())) && 5852 isFMAFasterThanFMulAndFAdd(VT)) { 5853 return ISD::FMA; 5854 } 5855 5856 return 0; 5857 } 5858 5859 SDValue SITargetLowering::performAddCombine(SDNode *N, 5860 DAGCombinerInfo &DCI) const { 5861 SelectionDAG &DAG = DCI.DAG; 5862 EVT VT = N->getValueType(0); 5863 5864 if (VT != MVT::i32) 5865 return SDValue(); 5866 5867 SDLoc SL(N); 5868 SDValue LHS = N->getOperand(0); 5869 SDValue RHS = N->getOperand(1); 5870 5871 // add x, zext (setcc) => addcarry x, 0, setcc 5872 // add x, sext (setcc) => subcarry x, 0, setcc 5873 unsigned Opc = LHS.getOpcode(); 5874 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 5875 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 5876 std::swap(RHS, LHS); 5877 5878 Opc = RHS.getOpcode(); 5879 switch (Opc) { 5880 default: break; 5881 case ISD::ZERO_EXTEND: 5882 case ISD::SIGN_EXTEND: 5883 case ISD::ANY_EXTEND: { 5884 auto Cond = RHS.getOperand(0); 5885 if (!isBoolSGPR(Cond)) 5886 break; 5887 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 5888 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 5889 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 5890 return DAG.getNode(Opc, SL, VTList, Args); 5891 } 5892 case ISD::ADDCARRY: { 5893 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 5894 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 5895 if (!C || C->getZExtValue() != 0) break; 5896 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 5897 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 5898 } 5899 } 5900 return SDValue(); 5901 } 5902 5903 SDValue SITargetLowering::performSubCombine(SDNode *N, 5904 DAGCombinerInfo &DCI) const { 5905 SelectionDAG &DAG = DCI.DAG; 5906 EVT VT = N->getValueType(0); 5907 5908 if (VT != MVT::i32) 5909 return SDValue(); 5910 5911 SDLoc SL(N); 5912 SDValue LHS = N->getOperand(0); 5913 SDValue RHS = N->getOperand(1); 5914 5915 unsigned Opc = LHS.getOpcode(); 5916 if (Opc != ISD::SUBCARRY) 5917 std::swap(RHS, LHS); 5918 5919 if (LHS.getOpcode() == ISD::SUBCARRY) { 5920 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 5921 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 5922 if (!C || C->getZExtValue() != 0) 5923 return SDValue(); 5924 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 5925 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 5926 } 5927 return SDValue(); 5928 } 5929 5930 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 5931 DAGCombinerInfo &DCI) const { 5932 5933 if (N->getValueType(0) != MVT::i32) 5934 return SDValue(); 5935 5936 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 5937 if (!C || C->getZExtValue() != 0) 5938 return SDValue(); 5939 5940 SelectionDAG &DAG = DCI.DAG; 5941 SDValue LHS = N->getOperand(0); 5942 5943 // addcarry (add x, y), 0, cc => addcarry x, y, cc 5944 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 5945 unsigned LHSOpc = LHS.getOpcode(); 5946 unsigned Opc = N->getOpcode(); 5947 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 5948 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 5949 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 5950 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 5951 } 5952 return SDValue(); 5953 } 5954 5955 SDValue SITargetLowering::performFAddCombine(SDNode *N, 5956 DAGCombinerInfo &DCI) const { 5957 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 5958 return SDValue(); 5959 5960 SelectionDAG &DAG = DCI.DAG; 5961 EVT VT = N->getValueType(0); 5962 5963 SDLoc SL(N); 5964 SDValue LHS = N->getOperand(0); 5965 SDValue RHS = N->getOperand(1); 5966 5967 // These should really be instruction patterns, but writing patterns with 5968 // source modiifiers is a pain. 5969 5970 // fadd (fadd (a, a), b) -> mad 2.0, a, b 5971 if (LHS.getOpcode() == ISD::FADD) { 5972 SDValue A = LHS.getOperand(0); 5973 if (A == LHS.getOperand(1)) { 5974 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 5975 if (FusedOp != 0) { 5976 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 5977 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 5978 } 5979 } 5980 } 5981 5982 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 5983 if (RHS.getOpcode() == ISD::FADD) { 5984 SDValue A = RHS.getOperand(0); 5985 if (A == RHS.getOperand(1)) { 5986 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 5987 if (FusedOp != 0) { 5988 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 5989 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 5990 } 5991 } 5992 } 5993 5994 return SDValue(); 5995 } 5996 5997 SDValue SITargetLowering::performFSubCombine(SDNode *N, 5998 DAGCombinerInfo &DCI) const { 5999 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 6000 return SDValue(); 6001 6002 SelectionDAG &DAG = DCI.DAG; 6003 SDLoc SL(N); 6004 EVT VT = N->getValueType(0); 6005 assert(!VT.isVector()); 6006 6007 // Try to get the fneg to fold into the source modifier. This undoes generic 6008 // DAG combines and folds them into the mad. 6009 // 6010 // Only do this if we are not trying to support denormals. v_mad_f32 does 6011 // not support denormals ever. 6012 SDValue LHS = N->getOperand(0); 6013 SDValue RHS = N->getOperand(1); 6014 if (LHS.getOpcode() == ISD::FADD) { 6015 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 6016 SDValue A = LHS.getOperand(0); 6017 if (A == LHS.getOperand(1)) { 6018 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 6019 if (FusedOp != 0){ 6020 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 6021 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 6022 6023 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 6024 } 6025 } 6026 } 6027 6028 if (RHS.getOpcode() == ISD::FADD) { 6029 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 6030 6031 SDValue A = RHS.getOperand(0); 6032 if (A == RHS.getOperand(1)) { 6033 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 6034 if (FusedOp != 0){ 6035 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 6036 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 6037 } 6038 } 6039 } 6040 6041 return SDValue(); 6042 } 6043 6044 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 6045 DAGCombinerInfo &DCI) const { 6046 SelectionDAG &DAG = DCI.DAG; 6047 SDLoc SL(N); 6048 6049 SDValue LHS = N->getOperand(0); 6050 SDValue RHS = N->getOperand(1); 6051 EVT VT = LHS.getValueType(); 6052 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 6053 6054 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 6055 if (!CRHS) { 6056 CRHS = dyn_cast<ConstantSDNode>(LHS); 6057 if (CRHS) { 6058 std::swap(LHS, RHS); 6059 CC = getSetCCSwappedOperands(CC); 6060 } 6061 } 6062 6063 if (CRHS && VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 6064 isBoolSGPR(LHS.getOperand(0))) { 6065 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 6066 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 6067 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 6068 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 6069 if ((CRHS->isAllOnesValue() && 6070 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 6071 (CRHS->isNullValue() && 6072 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 6073 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 6074 DAG.getConstant(-1, SL, MVT::i1)); 6075 if ((CRHS->isAllOnesValue() && 6076 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 6077 (CRHS->isNullValue() && 6078 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 6079 return LHS.getOperand(0); 6080 } 6081 6082 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 6083 VT != MVT::f16)) 6084 return SDValue(); 6085 6086 // Match isinf pattern 6087 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 6088 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) { 6089 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 6090 if (!CRHS) 6091 return SDValue(); 6092 6093 const APFloat &APF = CRHS->getValueAPF(); 6094 if (APF.isInfinity() && !APF.isNegative()) { 6095 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY; 6096 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 6097 DAG.getConstant(Mask, SL, MVT::i32)); 6098 } 6099 } 6100 6101 return SDValue(); 6102 } 6103 6104 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 6105 DAGCombinerInfo &DCI) const { 6106 SelectionDAG &DAG = DCI.DAG; 6107 SDLoc SL(N); 6108 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 6109 6110 SDValue Src = N->getOperand(0); 6111 SDValue Srl = N->getOperand(0); 6112 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 6113 Srl = Srl.getOperand(0); 6114 6115 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 6116 if (Srl.getOpcode() == ISD::SRL) { 6117 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 6118 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 6119 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 6120 6121 if (const ConstantSDNode *C = 6122 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 6123 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 6124 EVT(MVT::i32)); 6125 6126 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 6127 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 6128 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 6129 MVT::f32, Srl); 6130 } 6131 } 6132 } 6133 6134 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 6135 6136 KnownBits Known; 6137 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 6138 !DCI.isBeforeLegalizeOps()); 6139 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6140 if (TLI.ShrinkDemandedConstant(Src, Demanded, TLO) || 6141 TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) { 6142 DCI.CommitTargetLoweringOpt(TLO); 6143 } 6144 6145 return SDValue(); 6146 } 6147 6148 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 6149 DAGCombinerInfo &DCI) const { 6150 switch (N->getOpcode()) { 6151 default: 6152 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 6153 case ISD::ADD: 6154 return performAddCombine(N, DCI); 6155 case ISD::SUB: 6156 return performSubCombine(N, DCI); 6157 case ISD::ADDCARRY: 6158 case ISD::SUBCARRY: 6159 return performAddCarrySubCarryCombine(N, DCI); 6160 case ISD::FADD: 6161 return performFAddCombine(N, DCI); 6162 case ISD::FSUB: 6163 return performFSubCombine(N, DCI); 6164 case ISD::SETCC: 6165 return performSetCCCombine(N, DCI); 6166 case ISD::FMAXNUM: 6167 case ISD::FMINNUM: 6168 case ISD::SMAX: 6169 case ISD::SMIN: 6170 case ISD::UMAX: 6171 case ISD::UMIN: 6172 case AMDGPUISD::FMIN_LEGACY: 6173 case AMDGPUISD::FMAX_LEGACY: { 6174 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG && 6175 getTargetMachine().getOptLevel() > CodeGenOpt::None) 6176 return performMinMaxCombine(N, DCI); 6177 break; 6178 } 6179 case ISD::LOAD: 6180 case ISD::STORE: 6181 case ISD::ATOMIC_LOAD: 6182 case ISD::ATOMIC_STORE: 6183 case ISD::ATOMIC_CMP_SWAP: 6184 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 6185 case ISD::ATOMIC_SWAP: 6186 case ISD::ATOMIC_LOAD_ADD: 6187 case ISD::ATOMIC_LOAD_SUB: 6188 case ISD::ATOMIC_LOAD_AND: 6189 case ISD::ATOMIC_LOAD_OR: 6190 case ISD::ATOMIC_LOAD_XOR: 6191 case ISD::ATOMIC_LOAD_NAND: 6192 case ISD::ATOMIC_LOAD_MIN: 6193 case ISD::ATOMIC_LOAD_MAX: 6194 case ISD::ATOMIC_LOAD_UMIN: 6195 case ISD::ATOMIC_LOAD_UMAX: 6196 case AMDGPUISD::ATOMIC_INC: 6197 case AMDGPUISD::ATOMIC_DEC: // TODO: Target mem intrinsics. 6198 if (DCI.isBeforeLegalize()) 6199 break; 6200 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 6201 case ISD::AND: 6202 return performAndCombine(N, DCI); 6203 case ISD::OR: 6204 return performOrCombine(N, DCI); 6205 case ISD::XOR: 6206 return performXorCombine(N, DCI); 6207 case ISD::ZERO_EXTEND: 6208 return performZeroExtendCombine(N, DCI); 6209 case AMDGPUISD::FP_CLASS: 6210 return performClassCombine(N, DCI); 6211 case ISD::FCANONICALIZE: 6212 return performFCanonicalizeCombine(N, DCI); 6213 case AMDGPUISD::FRACT: 6214 case AMDGPUISD::RCP: 6215 case AMDGPUISD::RSQ: 6216 case AMDGPUISD::RCP_LEGACY: 6217 case AMDGPUISD::RSQ_LEGACY: 6218 case AMDGPUISD::RSQ_CLAMP: 6219 case AMDGPUISD::LDEXP: { 6220 SDValue Src = N->getOperand(0); 6221 if (Src.isUndef()) 6222 return Src; 6223 break; 6224 } 6225 case ISD::SINT_TO_FP: 6226 case ISD::UINT_TO_FP: 6227 return performUCharToFloatCombine(N, DCI); 6228 case AMDGPUISD::CVT_F32_UBYTE0: 6229 case AMDGPUISD::CVT_F32_UBYTE1: 6230 case AMDGPUISD::CVT_F32_UBYTE2: 6231 case AMDGPUISD::CVT_F32_UBYTE3: 6232 return performCvtF32UByteNCombine(N, DCI); 6233 case AMDGPUISD::FMED3: 6234 return performFMed3Combine(N, DCI); 6235 case AMDGPUISD::CVT_PKRTZ_F16_F32: 6236 return performCvtPkRTZCombine(N, DCI); 6237 case ISD::SCALAR_TO_VECTOR: { 6238 SelectionDAG &DAG = DCI.DAG; 6239 EVT VT = N->getValueType(0); 6240 6241 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 6242 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 6243 SDLoc SL(N); 6244 SDValue Src = N->getOperand(0); 6245 EVT EltVT = Src.getValueType(); 6246 if (EltVT == MVT::f16) 6247 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 6248 6249 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 6250 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 6251 } 6252 6253 break; 6254 } 6255 case ISD::EXTRACT_VECTOR_ELT: 6256 return performExtractVectorEltCombine(N, DCI); 6257 } 6258 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 6259 } 6260 6261 /// \brief Helper function for adjustWritemask 6262 static unsigned SubIdx2Lane(unsigned Idx) { 6263 switch (Idx) { 6264 default: return 0; 6265 case AMDGPU::sub0: return 0; 6266 case AMDGPU::sub1: return 1; 6267 case AMDGPU::sub2: return 2; 6268 case AMDGPU::sub3: return 3; 6269 } 6270 } 6271 6272 /// \brief Adjust the writemask of MIMG instructions 6273 void SITargetLowering::adjustWritemask(MachineSDNode *&Node, 6274 SelectionDAG &DAG) const { 6275 SDNode *Users[4] = { }; 6276 unsigned Lane = 0; 6277 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3; 6278 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 6279 unsigned NewDmask = 0; 6280 6281 // Try to figure out the used register components 6282 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 6283 I != E; ++I) { 6284 6285 // Don't look at users of the chain. 6286 if (I.getUse().getResNo() != 0) 6287 continue; 6288 6289 // Abort if we can't understand the usage 6290 if (!I->isMachineOpcode() || 6291 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 6292 return; 6293 6294 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used. 6295 // Note that subregs are packed, i.e. Lane==0 is the first bit set 6296 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 6297 // set, etc. 6298 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 6299 6300 // Set which texture component corresponds to the lane. 6301 unsigned Comp; 6302 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) { 6303 assert(Dmask); 6304 Comp = countTrailingZeros(Dmask); 6305 Dmask &= ~(1 << Comp); 6306 } 6307 6308 // Abort if we have more than one user per component 6309 if (Users[Lane]) 6310 return; 6311 6312 Users[Lane] = *I; 6313 NewDmask |= 1 << Comp; 6314 } 6315 6316 // Abort if there's no change 6317 if (NewDmask == OldDmask) 6318 return; 6319 6320 // Adjust the writemask in the node 6321 std::vector<SDValue> Ops; 6322 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 6323 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 6324 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 6325 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops); 6326 6327 // If we only got one lane, replace it with a copy 6328 // (if NewDmask has only one bit set...) 6329 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) { 6330 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(), 6331 MVT::i32); 6332 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, 6333 SDLoc(), Users[Lane]->getValueType(0), 6334 SDValue(Node, 0), RC); 6335 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 6336 return; 6337 } 6338 6339 // Update the users of the node with the new indices 6340 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) { 6341 SDNode *User = Users[i]; 6342 if (!User) 6343 continue; 6344 6345 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 6346 DAG.UpdateNodeOperands(User, User->getOperand(0), Op); 6347 6348 switch (Idx) { 6349 default: break; 6350 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 6351 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 6352 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 6353 } 6354 } 6355 } 6356 6357 static bool isFrameIndexOp(SDValue Op) { 6358 if (Op.getOpcode() == ISD::AssertZext) 6359 Op = Op.getOperand(0); 6360 6361 return isa<FrameIndexSDNode>(Op); 6362 } 6363 6364 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG) 6365 /// with frame index operands. 6366 /// LLVM assumes that inputs are to these instructions are registers. 6367 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 6368 SelectionDAG &DAG) const { 6369 if (Node->getOpcode() == ISD::CopyToReg) { 6370 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 6371 SDValue SrcVal = Node->getOperand(2); 6372 6373 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 6374 // to try understanding copies to physical registers. 6375 if (SrcVal.getValueType() == MVT::i1 && 6376 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) { 6377 SDLoc SL(Node); 6378 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 6379 SDValue VReg = DAG.getRegister( 6380 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 6381 6382 SDNode *Glued = Node->getGluedNode(); 6383 SDValue ToVReg 6384 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 6385 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 6386 SDValue ToResultReg 6387 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 6388 VReg, ToVReg.getValue(1)); 6389 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 6390 DAG.RemoveDeadNode(Node); 6391 return ToResultReg.getNode(); 6392 } 6393 } 6394 6395 SmallVector<SDValue, 8> Ops; 6396 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 6397 if (!isFrameIndexOp(Node->getOperand(i))) { 6398 Ops.push_back(Node->getOperand(i)); 6399 continue; 6400 } 6401 6402 SDLoc DL(Node); 6403 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 6404 Node->getOperand(i).getValueType(), 6405 Node->getOperand(i)), 0)); 6406 } 6407 6408 DAG.UpdateNodeOperands(Node, Ops); 6409 return Node; 6410 } 6411 6412 /// \brief Fold the instructions after selecting them. 6413 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 6414 SelectionDAG &DAG) const { 6415 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 6416 unsigned Opcode = Node->getMachineOpcode(); 6417 6418 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 6419 !TII->isGather4(Opcode)) 6420 adjustWritemask(Node, DAG); 6421 6422 if (Opcode == AMDGPU::INSERT_SUBREG || 6423 Opcode == AMDGPU::REG_SEQUENCE) { 6424 legalizeTargetIndependentNode(Node, DAG); 6425 return Node; 6426 } 6427 6428 switch (Opcode) { 6429 case AMDGPU::V_DIV_SCALE_F32: 6430 case AMDGPU::V_DIV_SCALE_F64: { 6431 // Satisfy the operand register constraint when one of the inputs is 6432 // undefined. Ordinarily each undef value will have its own implicit_def of 6433 // a vreg, so force these to use a single register. 6434 SDValue Src0 = Node->getOperand(0); 6435 SDValue Src1 = Node->getOperand(1); 6436 SDValue Src2 = Node->getOperand(2); 6437 6438 if ((Src0.isMachineOpcode() && 6439 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 6440 (Src0 == Src1 || Src0 == Src2)) 6441 break; 6442 6443 MVT VT = Src0.getValueType().getSimpleVT(); 6444 const TargetRegisterClass *RC = getRegClassFor(VT); 6445 6446 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 6447 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 6448 6449 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 6450 UndefReg, Src0, SDValue()); 6451 6452 // src0 must be the same register as src1 or src2, even if the value is 6453 // undefined, so make sure we don't violate this constraint. 6454 if (Src0.isMachineOpcode() && 6455 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 6456 if (Src1.isMachineOpcode() && 6457 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 6458 Src0 = Src1; 6459 else if (Src2.isMachineOpcode() && 6460 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 6461 Src0 = Src2; 6462 else { 6463 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 6464 Src0 = UndefReg; 6465 Src1 = UndefReg; 6466 } 6467 } else 6468 break; 6469 6470 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 6471 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 6472 Ops.push_back(Node->getOperand(I)); 6473 6474 Ops.push_back(ImpDef.getValue(1)); 6475 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 6476 } 6477 default: 6478 break; 6479 } 6480 6481 return Node; 6482 } 6483 6484 /// \brief Assign the register class depending on the number of 6485 /// bits set in the writemask 6486 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 6487 SDNode *Node) const { 6488 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 6489 6490 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 6491 6492 if (TII->isVOP3(MI.getOpcode())) { 6493 // Make sure constant bus requirements are respected. 6494 TII->legalizeOperandsVOP3(MRI, MI); 6495 return; 6496 } 6497 6498 if (TII->isMIMG(MI)) { 6499 unsigned VReg = MI.getOperand(0).getReg(); 6500 const TargetRegisterClass *RC = MRI.getRegClass(VReg); 6501 // TODO: Need mapping tables to handle other cases (register classes). 6502 if (RC != &AMDGPU::VReg_128RegClass) 6503 return; 6504 6505 unsigned DmaskIdx = MI.getNumOperands() == 12 ? 3 : 4; 6506 unsigned Writemask = MI.getOperand(DmaskIdx).getImm(); 6507 unsigned BitsSet = 0; 6508 for (unsigned i = 0; i < 4; ++i) 6509 BitsSet += Writemask & (1 << i) ? 1 : 0; 6510 switch (BitsSet) { 6511 default: return; 6512 case 1: RC = &AMDGPU::VGPR_32RegClass; break; 6513 case 2: RC = &AMDGPU::VReg_64RegClass; break; 6514 case 3: RC = &AMDGPU::VReg_96RegClass; break; 6515 } 6516 6517 unsigned NewOpcode = TII->getMaskedMIMGOp(MI.getOpcode(), BitsSet); 6518 MI.setDesc(TII->get(NewOpcode)); 6519 MRI.setRegClass(VReg, RC); 6520 return; 6521 } 6522 6523 // Replace unused atomics with the no return version. 6524 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 6525 if (NoRetAtomicOp != -1) { 6526 if (!Node->hasAnyUseOfValue(0)) { 6527 MI.setDesc(TII->get(NoRetAtomicOp)); 6528 MI.RemoveOperand(0); 6529 return; 6530 } 6531 6532 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 6533 // instruction, because the return type of these instructions is a vec2 of 6534 // the memory type, so it can be tied to the input operand. 6535 // This means these instructions always have a use, so we need to add a 6536 // special case to check if the atomic has only one extract_subreg use, 6537 // which itself has no uses. 6538 if ((Node->hasNUsesOfValue(1, 0) && 6539 Node->use_begin()->isMachineOpcode() && 6540 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 6541 !Node->use_begin()->hasAnyUseOfValue(0))) { 6542 unsigned Def = MI.getOperand(0).getReg(); 6543 6544 // Change this into a noret atomic. 6545 MI.setDesc(TII->get(NoRetAtomicOp)); 6546 MI.RemoveOperand(0); 6547 6548 // If we only remove the def operand from the atomic instruction, the 6549 // extract_subreg will be left with a use of a vreg without a def. 6550 // So we need to insert an implicit_def to avoid machine verifier 6551 // errors. 6552 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 6553 TII->get(AMDGPU::IMPLICIT_DEF), Def); 6554 } 6555 return; 6556 } 6557 } 6558 6559 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 6560 uint64_t Val) { 6561 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 6562 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 6563 } 6564 6565 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 6566 const SDLoc &DL, 6567 SDValue Ptr) const { 6568 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 6569 6570 // Build the half of the subregister with the constants before building the 6571 // full 128-bit register. If we are building multiple resource descriptors, 6572 // this will allow CSEing of the 2-component register. 6573 const SDValue Ops0[] = { 6574 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 6575 buildSMovImm32(DAG, DL, 0), 6576 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 6577 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 6578 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 6579 }; 6580 6581 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 6582 MVT::v2i32, Ops0), 0); 6583 6584 // Combine the constants and the pointer. 6585 const SDValue Ops1[] = { 6586 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 6587 Ptr, 6588 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 6589 SubRegHi, 6590 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 6591 }; 6592 6593 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 6594 } 6595 6596 /// \brief Return a resource descriptor with the 'Add TID' bit enabled 6597 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 6598 /// of the resource descriptor) to create an offset, which is added to 6599 /// the resource pointer. 6600 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 6601 SDValue Ptr, uint32_t RsrcDword1, 6602 uint64_t RsrcDword2And3) const { 6603 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 6604 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 6605 if (RsrcDword1) { 6606 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 6607 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 6608 0); 6609 } 6610 6611 SDValue DataLo = buildSMovImm32(DAG, DL, 6612 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 6613 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 6614 6615 const SDValue Ops[] = { 6616 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 6617 PtrLo, 6618 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 6619 PtrHi, 6620 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 6621 DataLo, 6622 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 6623 DataHi, 6624 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 6625 }; 6626 6627 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 6628 } 6629 6630 //===----------------------------------------------------------------------===// 6631 // SI Inline Assembly Support 6632 //===----------------------------------------------------------------------===// 6633 6634 std::pair<unsigned, const TargetRegisterClass *> 6635 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 6636 StringRef Constraint, 6637 MVT VT) const { 6638 if (!isTypeLegal(VT)) 6639 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 6640 6641 if (Constraint.size() == 1) { 6642 switch (Constraint[0]) { 6643 case 's': 6644 case 'r': 6645 switch (VT.getSizeInBits()) { 6646 default: 6647 return std::make_pair(0U, nullptr); 6648 case 32: 6649 case 16: 6650 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass); 6651 case 64: 6652 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass); 6653 case 128: 6654 return std::make_pair(0U, &AMDGPU::SReg_128RegClass); 6655 case 256: 6656 return std::make_pair(0U, &AMDGPU::SReg_256RegClass); 6657 case 512: 6658 return std::make_pair(0U, &AMDGPU::SReg_512RegClass); 6659 } 6660 6661 case 'v': 6662 switch (VT.getSizeInBits()) { 6663 default: 6664 return std::make_pair(0U, nullptr); 6665 case 32: 6666 case 16: 6667 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass); 6668 case 64: 6669 return std::make_pair(0U, &AMDGPU::VReg_64RegClass); 6670 case 96: 6671 return std::make_pair(0U, &AMDGPU::VReg_96RegClass); 6672 case 128: 6673 return std::make_pair(0U, &AMDGPU::VReg_128RegClass); 6674 case 256: 6675 return std::make_pair(0U, &AMDGPU::VReg_256RegClass); 6676 case 512: 6677 return std::make_pair(0U, &AMDGPU::VReg_512RegClass); 6678 } 6679 } 6680 } 6681 6682 if (Constraint.size() > 1) { 6683 const TargetRegisterClass *RC = nullptr; 6684 if (Constraint[1] == 'v') { 6685 RC = &AMDGPU::VGPR_32RegClass; 6686 } else if (Constraint[1] == 's') { 6687 RC = &AMDGPU::SGPR_32RegClass; 6688 } 6689 6690 if (RC) { 6691 uint32_t Idx; 6692 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 6693 if (!Failed && Idx < RC->getNumRegs()) 6694 return std::make_pair(RC->getRegister(Idx), RC); 6695 } 6696 } 6697 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 6698 } 6699 6700 SITargetLowering::ConstraintType 6701 SITargetLowering::getConstraintType(StringRef Constraint) const { 6702 if (Constraint.size() == 1) { 6703 switch (Constraint[0]) { 6704 default: break; 6705 case 's': 6706 case 'v': 6707 return C_RegisterClass; 6708 } 6709 } 6710 return TargetLowering::getConstraintType(Constraint); 6711 } 6712 6713 // Figure out which registers should be reserved for stack access. Only after 6714 // the function is legalized do we know all of the non-spill stack objects or if 6715 // calls are present. 6716 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 6717 MachineRegisterInfo &MRI = MF.getRegInfo(); 6718 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 6719 const MachineFrameInfo &MFI = MF.getFrameInfo(); 6720 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 6721 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 6722 6723 if (Info->isEntryFunction()) { 6724 // Callable functions have fixed registers used for stack access. 6725 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 6726 } 6727 6728 // We have to assume the SP is needed in case there are calls in the function 6729 // during lowering. Calls are only detected after the function is 6730 // lowered. We're about to reserve registers, so don't bother using it if we 6731 // aren't really going to use it. 6732 bool NeedSP = !Info->isEntryFunction() || 6733 MFI.hasVarSizedObjects() || 6734 MFI.hasCalls(); 6735 6736 if (NeedSP) { 6737 unsigned ReservedStackPtrOffsetReg = TRI->reservedStackPtrOffsetReg(MF); 6738 Info->setStackPtrOffsetReg(ReservedStackPtrOffsetReg); 6739 6740 assert(Info->getStackPtrOffsetReg() != Info->getFrameOffsetReg()); 6741 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 6742 Info->getStackPtrOffsetReg())); 6743 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 6744 } 6745 6746 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 6747 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 6748 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG, 6749 Info->getScratchWaveOffsetReg()); 6750 6751 TargetLoweringBase::finalizeLowering(MF); 6752 } 6753