1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// Custom DAG lowering for SI 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "SIISelLowering.h" 15 #include "AMDGPU.h" 16 #include "AMDGPUSubtarget.h" 17 #include "AMDGPUTargetMachine.h" 18 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 19 #include "SIDefines.h" 20 #include "SIInstrInfo.h" 21 #include "SIMachineFunctionInfo.h" 22 #include "SIRegisterInfo.h" 23 #include "Utils/AMDGPUBaseInfo.h" 24 #include "llvm/ADT/APFloat.h" 25 #include "llvm/ADT/APInt.h" 26 #include "llvm/ADT/ArrayRef.h" 27 #include "llvm/ADT/BitVector.h" 28 #include "llvm/ADT/SmallVector.h" 29 #include "llvm/ADT/Statistic.h" 30 #include "llvm/ADT/StringRef.h" 31 #include "llvm/ADT/StringSwitch.h" 32 #include "llvm/ADT/Twine.h" 33 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 34 #include "llvm/CodeGen/Analysis.h" 35 #include "llvm/CodeGen/CallingConvLower.h" 36 #include "llvm/CodeGen/DAGCombine.h" 37 #include "llvm/CodeGen/ISDOpcodes.h" 38 #include "llvm/CodeGen/MachineBasicBlock.h" 39 #include "llvm/CodeGen/MachineFrameInfo.h" 40 #include "llvm/CodeGen/MachineFunction.h" 41 #include "llvm/CodeGen/MachineInstr.h" 42 #include "llvm/CodeGen/MachineInstrBuilder.h" 43 #include "llvm/CodeGen/MachineLoopInfo.h" 44 #include "llvm/CodeGen/MachineMemOperand.h" 45 #include "llvm/CodeGen/MachineModuleInfo.h" 46 #include "llvm/CodeGen/MachineOperand.h" 47 #include "llvm/CodeGen/MachineRegisterInfo.h" 48 #include "llvm/CodeGen/SelectionDAG.h" 49 #include "llvm/CodeGen/SelectionDAGNodes.h" 50 #include "llvm/CodeGen/TargetCallingConv.h" 51 #include "llvm/CodeGen/TargetRegisterInfo.h" 52 #include "llvm/CodeGen/ValueTypes.h" 53 #include "llvm/IR/Constants.h" 54 #include "llvm/IR/DataLayout.h" 55 #include "llvm/IR/DebugLoc.h" 56 #include "llvm/IR/DerivedTypes.h" 57 #include "llvm/IR/DiagnosticInfo.h" 58 #include "llvm/IR/Function.h" 59 #include "llvm/IR/GlobalValue.h" 60 #include "llvm/IR/InstrTypes.h" 61 #include "llvm/IR/Instruction.h" 62 #include "llvm/IR/Instructions.h" 63 #include "llvm/IR/IntrinsicInst.h" 64 #include "llvm/IR/Type.h" 65 #include "llvm/Support/Casting.h" 66 #include "llvm/Support/CodeGen.h" 67 #include "llvm/Support/CommandLine.h" 68 #include "llvm/Support/Compiler.h" 69 #include "llvm/Support/ErrorHandling.h" 70 #include "llvm/Support/KnownBits.h" 71 #include "llvm/Support/MachineValueType.h" 72 #include "llvm/Support/MathExtras.h" 73 #include "llvm/Target/TargetOptions.h" 74 #include <cassert> 75 #include <cmath> 76 #include <cstdint> 77 #include <iterator> 78 #include <tuple> 79 #include <utility> 80 #include <vector> 81 82 using namespace llvm; 83 84 #define DEBUG_TYPE "si-lower" 85 86 STATISTIC(NumTailCalls, "Number of tail calls"); 87 88 static cl::opt<bool> DisableLoopAlignment( 89 "amdgpu-disable-loop-alignment", 90 cl::desc("Do not align and prefetch loops"), 91 cl::init(false)); 92 93 static cl::opt<bool> VGPRReserveforSGPRSpill( 94 "amdgpu-reserve-vgpr-for-sgpr-spill", 95 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 96 97 static cl::opt<bool> UseDivergentRegisterIndexing( 98 "amdgpu-use-divergent-register-indexing", 99 cl::Hidden, 100 cl::desc("Use indirect register addressing for divergent indexes"), 101 cl::init(false)); 102 103 static bool hasFP32Denormals(const MachineFunction &MF) { 104 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 105 return Info->getMode().allFP32Denormals(); 106 } 107 108 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 109 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 110 return Info->getMode().allFP64FP16Denormals(); 111 } 112 113 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 114 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 115 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 116 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 117 return AMDGPU::SGPR0 + Reg; 118 } 119 } 120 llvm_unreachable("Cannot allocate sgpr"); 121 } 122 123 SITargetLowering::SITargetLowering(const TargetMachine &TM, 124 const GCNSubtarget &STI) 125 : AMDGPUTargetLowering(TM, STI), 126 Subtarget(&STI) { 127 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 128 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 129 130 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 131 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 132 133 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 134 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 135 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 136 137 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 138 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 139 140 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 141 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 142 143 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 144 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 145 146 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 147 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 148 149 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 150 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 151 152 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 153 addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass); 154 155 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 156 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 157 158 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 159 addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass); 160 161 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 162 addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass); 163 164 if (Subtarget->has16BitInsts()) { 165 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 166 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 167 168 // Unless there are also VOP3P operations, not operations are really legal. 169 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 170 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 171 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 172 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 173 } 174 175 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 176 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 177 178 computeRegisterProperties(Subtarget->getRegisterInfo()); 179 180 // The boolean content concept here is too inflexible. Compares only ever 181 // really produce a 1-bit result. Any copy/extend from these will turn into a 182 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 183 // it's what most targets use. 184 setBooleanContents(ZeroOrOneBooleanContent); 185 setBooleanVectorContents(ZeroOrOneBooleanContent); 186 187 // We need to custom lower vector stores from local memory 188 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 189 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 190 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 191 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 192 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 193 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 194 setOperationAction(ISD::LOAD, MVT::i1, Custom); 195 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 196 197 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 198 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 199 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 200 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 201 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 202 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 203 setOperationAction(ISD::STORE, MVT::i1, Custom); 204 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 205 206 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 207 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 208 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 209 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 210 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 211 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 212 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 213 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 214 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 215 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 216 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 217 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 218 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 219 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 220 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 221 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 222 223 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 224 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 225 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 226 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 227 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 228 229 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 230 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 231 232 setOperationAction(ISD::SELECT, MVT::i1, Promote); 233 setOperationAction(ISD::SELECT, MVT::i64, Custom); 234 setOperationAction(ISD::SELECT, MVT::f64, Promote); 235 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 236 237 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 238 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 239 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 240 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 241 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 242 243 setOperationAction(ISD::SETCC, MVT::i1, Promote); 244 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 245 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 246 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 247 248 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 249 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 250 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 251 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 252 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 253 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 254 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 255 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 256 257 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 258 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 259 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 260 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 261 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 262 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 263 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 264 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 265 266 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 267 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 268 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 269 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 270 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 271 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 272 273 setOperationAction(ISD::UADDO, MVT::i32, Legal); 274 setOperationAction(ISD::USUBO, MVT::i32, Legal); 275 276 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 277 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 278 279 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 280 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 281 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 282 283 #if 0 284 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 285 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 286 #endif 287 288 // We only support LOAD/STORE and vector manipulation ops for vectors 289 // with > 4 elements. 290 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 291 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 292 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 293 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 294 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 295 switch (Op) { 296 case ISD::LOAD: 297 case ISD::STORE: 298 case ISD::BUILD_VECTOR: 299 case ISD::BITCAST: 300 case ISD::EXTRACT_VECTOR_ELT: 301 case ISD::INSERT_VECTOR_ELT: 302 case ISD::INSERT_SUBVECTOR: 303 case ISD::EXTRACT_SUBVECTOR: 304 case ISD::SCALAR_TO_VECTOR: 305 break; 306 case ISD::CONCAT_VECTORS: 307 setOperationAction(Op, VT, Custom); 308 break; 309 default: 310 setOperationAction(Op, VT, Expand); 311 break; 312 } 313 } 314 } 315 316 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 317 318 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 319 // is expanded to avoid having two separate loops in case the index is a VGPR. 320 321 // Most operations are naturally 32-bit vector operations. We only support 322 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 323 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 324 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 325 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 326 327 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 328 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 329 330 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 331 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 332 333 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 334 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 335 } 336 337 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 338 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 339 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 340 341 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 342 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 343 344 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 345 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 346 347 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 348 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 349 } 350 351 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 352 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 353 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 354 355 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 356 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 357 358 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 359 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 360 361 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 362 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 363 } 364 365 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 366 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 367 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 368 369 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 370 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 371 372 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 373 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 374 375 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 376 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 377 } 378 379 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 380 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 381 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 382 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 383 384 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 385 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 386 387 // Avoid stack access for these. 388 // TODO: Generalize to more vector types. 389 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 390 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 391 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 392 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 393 394 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 395 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 396 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 398 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 399 400 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 401 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 402 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 403 404 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 405 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 406 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 407 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 408 409 // Deal with vec3 vector operations when widened to vec4. 410 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 411 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 414 415 // Deal with vec5 vector operations when widened to vec8. 416 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 417 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 418 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 419 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 420 421 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 422 // and output demarshalling 423 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 424 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 425 426 // We can't return success/failure, only the old value, 427 // let LLVM add the comparison 428 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 429 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 430 431 if (Subtarget->hasFlatAddressSpace()) { 432 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 433 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 434 } 435 436 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 437 438 // FIXME: This should be narrowed to i32, but that only happens if i64 is 439 // illegal. 440 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 441 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 442 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 443 444 // On SI this is s_memtime and s_memrealtime on VI. 445 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 446 setOperationAction(ISD::TRAP, MVT::Other, Custom); 447 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 448 449 if (Subtarget->has16BitInsts()) { 450 setOperationAction(ISD::FPOW, MVT::f16, Promote); 451 setOperationAction(ISD::FLOG, MVT::f16, Custom); 452 setOperationAction(ISD::FEXP, MVT::f16, Custom); 453 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 454 } 455 456 // v_mad_f32 does not support denormals. We report it as unconditionally 457 // legal, and the context where it is formed will disallow it when fp32 458 // denormals are enabled. 459 setOperationAction(ISD::FMAD, MVT::f32, Legal); 460 461 if (!Subtarget->hasBFI()) { 462 // fcopysign can be done in a single instruction with BFI. 463 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 464 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 465 } 466 467 if (!Subtarget->hasBCNT(32)) 468 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 469 470 if (!Subtarget->hasBCNT(64)) 471 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 472 473 if (Subtarget->hasFFBH()) 474 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 475 476 if (Subtarget->hasFFBL()) 477 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 478 479 // We only really have 32-bit BFE instructions (and 16-bit on VI). 480 // 481 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 482 // effort to match them now. We want this to be false for i64 cases when the 483 // extraction isn't restricted to the upper or lower half. Ideally we would 484 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 485 // span the midpoint are probably relatively rare, so don't worry about them 486 // for now. 487 if (Subtarget->hasBFE()) 488 setHasExtractBitsInsn(true); 489 490 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 491 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 492 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 493 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 494 495 496 // These are really only legal for ieee_mode functions. We should be avoiding 497 // them for functions that don't have ieee_mode enabled, so just say they are 498 // legal. 499 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 500 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 501 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 502 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 503 504 505 if (Subtarget->haveRoundOpsF64()) { 506 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 507 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 508 setOperationAction(ISD::FRINT, MVT::f64, Legal); 509 } else { 510 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 511 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 512 setOperationAction(ISD::FRINT, MVT::f64, Custom); 513 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 514 } 515 516 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 517 518 setOperationAction(ISD::FSIN, MVT::f32, Custom); 519 setOperationAction(ISD::FCOS, MVT::f32, Custom); 520 setOperationAction(ISD::FDIV, MVT::f32, Custom); 521 setOperationAction(ISD::FDIV, MVT::f64, Custom); 522 523 if (Subtarget->has16BitInsts()) { 524 setOperationAction(ISD::Constant, MVT::i16, Legal); 525 526 setOperationAction(ISD::SMIN, MVT::i16, Legal); 527 setOperationAction(ISD::SMAX, MVT::i16, Legal); 528 529 setOperationAction(ISD::UMIN, MVT::i16, Legal); 530 setOperationAction(ISD::UMAX, MVT::i16, Legal); 531 532 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 533 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 534 535 setOperationAction(ISD::ROTR, MVT::i16, Promote); 536 setOperationAction(ISD::ROTL, MVT::i16, Promote); 537 538 setOperationAction(ISD::SDIV, MVT::i16, Promote); 539 setOperationAction(ISD::UDIV, MVT::i16, Promote); 540 setOperationAction(ISD::SREM, MVT::i16, Promote); 541 setOperationAction(ISD::UREM, MVT::i16, Promote); 542 543 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 544 545 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 546 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 547 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 548 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 549 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 550 551 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 552 553 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 554 555 setOperationAction(ISD::LOAD, MVT::i16, Custom); 556 557 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 558 559 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 560 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 561 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 562 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 563 564 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 565 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 566 567 // F16 - Constant Actions. 568 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 569 570 // F16 - Load/Store Actions. 571 setOperationAction(ISD::LOAD, MVT::f16, Promote); 572 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 573 setOperationAction(ISD::STORE, MVT::f16, Promote); 574 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 575 576 // F16 - VOP1 Actions. 577 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 578 setOperationAction(ISD::FCOS, MVT::f16, Custom); 579 setOperationAction(ISD::FSIN, MVT::f16, Custom); 580 581 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 582 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 583 584 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 585 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 586 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 587 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 588 setOperationAction(ISD::FROUND, MVT::f16, Custom); 589 590 // F16 - VOP2 Actions. 591 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 592 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 593 594 setOperationAction(ISD::FDIV, MVT::f16, Custom); 595 596 // F16 - VOP3 Actions. 597 setOperationAction(ISD::FMA, MVT::f16, Legal); 598 if (STI.hasMadF16()) 599 setOperationAction(ISD::FMAD, MVT::f16, Legal); 600 601 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 602 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 603 switch (Op) { 604 case ISD::LOAD: 605 case ISD::STORE: 606 case ISD::BUILD_VECTOR: 607 case ISD::BITCAST: 608 case ISD::EXTRACT_VECTOR_ELT: 609 case ISD::INSERT_VECTOR_ELT: 610 case ISD::INSERT_SUBVECTOR: 611 case ISD::EXTRACT_SUBVECTOR: 612 case ISD::SCALAR_TO_VECTOR: 613 break; 614 case ISD::CONCAT_VECTORS: 615 setOperationAction(Op, VT, Custom); 616 break; 617 default: 618 setOperationAction(Op, VT, Expand); 619 break; 620 } 621 } 622 } 623 624 // v_perm_b32 can handle either of these. 625 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 626 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 627 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 628 629 // XXX - Do these do anything? Vector constants turn into build_vector. 630 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 631 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 632 633 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 634 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 635 636 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 637 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 638 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 639 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 640 641 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 642 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 643 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 644 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 645 646 setOperationAction(ISD::AND, MVT::v2i16, Promote); 647 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 648 setOperationAction(ISD::OR, MVT::v2i16, Promote); 649 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 650 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 651 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 652 653 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 654 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 655 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 656 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 657 658 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 659 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 660 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 661 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 662 663 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 664 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 665 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 666 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 667 668 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 669 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 670 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 671 672 if (!Subtarget->hasVOP3PInsts()) { 673 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 674 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 675 } 676 677 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 678 // This isn't really legal, but this avoids the legalizer unrolling it (and 679 // allows matching fneg (fabs x) patterns) 680 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 681 682 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 683 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 684 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 685 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 686 687 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 688 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 689 690 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 691 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 692 } 693 694 if (Subtarget->hasVOP3PInsts()) { 695 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 696 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 697 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 698 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 699 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 700 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 701 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 702 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 703 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 704 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 705 706 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 707 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 708 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 709 710 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 711 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 712 713 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 714 715 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 716 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 717 718 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 719 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 720 721 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 722 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 723 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 724 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 725 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 726 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 727 728 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 729 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 730 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 731 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 732 733 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 734 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 735 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 736 737 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 738 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 739 740 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 741 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 742 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 743 744 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 745 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 746 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 747 } 748 749 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 750 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 751 752 if (Subtarget->has16BitInsts()) { 753 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 754 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 755 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 756 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 757 } else { 758 // Legalization hack. 759 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 760 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 761 762 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 763 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 764 } 765 766 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 767 setOperationAction(ISD::SELECT, VT, Custom); 768 } 769 770 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 771 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 772 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 773 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 774 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 775 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 776 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 777 778 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 779 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 780 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 781 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 782 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 783 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 784 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 785 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 786 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 787 788 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 789 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 790 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 791 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 792 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 793 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 794 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 795 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 796 797 setTargetDAGCombine(ISD::ADD); 798 setTargetDAGCombine(ISD::ADDCARRY); 799 setTargetDAGCombine(ISD::SUB); 800 setTargetDAGCombine(ISD::SUBCARRY); 801 setTargetDAGCombine(ISD::FADD); 802 setTargetDAGCombine(ISD::FSUB); 803 setTargetDAGCombine(ISD::FMINNUM); 804 setTargetDAGCombine(ISD::FMAXNUM); 805 setTargetDAGCombine(ISD::FMINNUM_IEEE); 806 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 807 setTargetDAGCombine(ISD::FMA); 808 setTargetDAGCombine(ISD::SMIN); 809 setTargetDAGCombine(ISD::SMAX); 810 setTargetDAGCombine(ISD::UMIN); 811 setTargetDAGCombine(ISD::UMAX); 812 setTargetDAGCombine(ISD::SETCC); 813 setTargetDAGCombine(ISD::AND); 814 setTargetDAGCombine(ISD::OR); 815 setTargetDAGCombine(ISD::XOR); 816 setTargetDAGCombine(ISD::SINT_TO_FP); 817 setTargetDAGCombine(ISD::UINT_TO_FP); 818 setTargetDAGCombine(ISD::FCANONICALIZE); 819 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 820 setTargetDAGCombine(ISD::ZERO_EXTEND); 821 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 822 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 823 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 824 825 // All memory operations. Some folding on the pointer operand is done to help 826 // matching the constant offsets in the addressing modes. 827 setTargetDAGCombine(ISD::LOAD); 828 setTargetDAGCombine(ISD::STORE); 829 setTargetDAGCombine(ISD::ATOMIC_LOAD); 830 setTargetDAGCombine(ISD::ATOMIC_STORE); 831 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 832 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 833 setTargetDAGCombine(ISD::ATOMIC_SWAP); 834 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 835 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 836 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 837 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 838 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 839 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 840 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 841 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 842 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 843 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 844 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 845 846 // FIXME: In other contexts we pretend this is a per-function property. 847 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 848 849 setSchedulingPreference(Sched::RegPressure); 850 } 851 852 const GCNSubtarget *SITargetLowering::getSubtarget() const { 853 return Subtarget; 854 } 855 856 //===----------------------------------------------------------------------===// 857 // TargetLowering queries 858 //===----------------------------------------------------------------------===// 859 860 // v_mad_mix* support a conversion from f16 to f32. 861 // 862 // There is only one special case when denormals are enabled we don't currently, 863 // where this is OK to use. 864 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 865 EVT DestVT, EVT SrcVT) const { 866 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 867 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 868 DestVT.getScalarType() == MVT::f32 && 869 SrcVT.getScalarType() == MVT::f16 && 870 // TODO: This probably only requires no input flushing? 871 !hasFP32Denormals(DAG.getMachineFunction()); 872 } 873 874 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 875 // SI has some legal vector types, but no legal vector operations. Say no 876 // shuffles are legal in order to prefer scalarizing some vector operations. 877 return false; 878 } 879 880 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 881 CallingConv::ID CC, 882 EVT VT) const { 883 if (CC == CallingConv::AMDGPU_KERNEL) 884 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 885 886 if (VT.isVector()) { 887 EVT ScalarVT = VT.getScalarType(); 888 unsigned Size = ScalarVT.getSizeInBits(); 889 if (Size == 32) 890 return ScalarVT.getSimpleVT(); 891 892 if (Size > 32) 893 return MVT::i32; 894 895 if (Size == 16 && Subtarget->has16BitInsts()) 896 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 897 } else if (VT.getSizeInBits() > 32) 898 return MVT::i32; 899 900 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 901 } 902 903 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 904 CallingConv::ID CC, 905 EVT VT) const { 906 if (CC == CallingConv::AMDGPU_KERNEL) 907 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 908 909 if (VT.isVector()) { 910 unsigned NumElts = VT.getVectorNumElements(); 911 EVT ScalarVT = VT.getScalarType(); 912 unsigned Size = ScalarVT.getSizeInBits(); 913 914 if (Size == 32) 915 return NumElts; 916 917 if (Size > 32) 918 return NumElts * ((Size + 31) / 32); 919 920 if (Size == 16 && Subtarget->has16BitInsts()) 921 return (NumElts + 1) / 2; 922 } else if (VT.getSizeInBits() > 32) 923 return (VT.getSizeInBits() + 31) / 32; 924 925 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 926 } 927 928 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 929 LLVMContext &Context, CallingConv::ID CC, 930 EVT VT, EVT &IntermediateVT, 931 unsigned &NumIntermediates, MVT &RegisterVT) const { 932 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 933 unsigned NumElts = VT.getVectorNumElements(); 934 EVT ScalarVT = VT.getScalarType(); 935 unsigned Size = ScalarVT.getSizeInBits(); 936 if (Size == 32) { 937 RegisterVT = ScalarVT.getSimpleVT(); 938 IntermediateVT = RegisterVT; 939 NumIntermediates = NumElts; 940 return NumIntermediates; 941 } 942 943 if (Size > 32) { 944 RegisterVT = MVT::i32; 945 IntermediateVT = RegisterVT; 946 NumIntermediates = NumElts * ((Size + 31) / 32); 947 return NumIntermediates; 948 } 949 950 // FIXME: We should fix the ABI to be the same on targets without 16-bit 951 // support, but unless we can properly handle 3-vectors, it will be still be 952 // inconsistent. 953 if (Size == 16 && Subtarget->has16BitInsts()) { 954 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 955 IntermediateVT = RegisterVT; 956 NumIntermediates = (NumElts + 1) / 2; 957 return NumIntermediates; 958 } 959 } 960 961 return TargetLowering::getVectorTypeBreakdownForCallingConv( 962 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 963 } 964 965 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 966 assert(DMaskLanes != 0); 967 968 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 969 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 970 return EVT::getVectorVT(Ty->getContext(), 971 EVT::getEVT(VT->getElementType()), 972 NumElts); 973 } 974 975 return EVT::getEVT(Ty); 976 } 977 978 // Peek through TFE struct returns to only use the data size. 979 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 980 auto *ST = dyn_cast<StructType>(Ty); 981 if (!ST) 982 return memVTFromImageData(Ty, DMaskLanes); 983 984 // Some intrinsics return an aggregate type - special case to work out the 985 // correct memVT. 986 // 987 // Only limited forms of aggregate type currently expected. 988 if (ST->getNumContainedTypes() != 2 || 989 !ST->getContainedType(1)->isIntegerTy(32)) 990 return EVT(); 991 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 992 } 993 994 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 995 const CallInst &CI, 996 MachineFunction &MF, 997 unsigned IntrID) const { 998 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 999 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1000 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1001 (Intrinsic::ID)IntrID); 1002 if (Attr.hasFnAttribute(Attribute::ReadNone)) 1003 return false; 1004 1005 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1006 1007 if (RsrcIntr->IsImage) { 1008 Info.ptrVal = MFI->getImagePSV( 1009 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1010 CI.getArgOperand(RsrcIntr->RsrcArg)); 1011 Info.align.reset(); 1012 } else { 1013 Info.ptrVal = MFI->getBufferPSV( 1014 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1015 CI.getArgOperand(RsrcIntr->RsrcArg)); 1016 } 1017 1018 Info.flags = MachineMemOperand::MODereferenceable; 1019 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 1020 unsigned DMaskLanes = 4; 1021 1022 if (RsrcIntr->IsImage) { 1023 const AMDGPU::ImageDimIntrinsicInfo *Intr 1024 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1025 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1026 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1027 1028 if (!BaseOpcode->Gather4) { 1029 // If this isn't a gather, we may have excess loaded elements in the 1030 // IR type. Check the dmask for the real number of elements loaded. 1031 unsigned DMask 1032 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1033 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1034 } 1035 1036 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1037 } else 1038 Info.memVT = EVT::getEVT(CI.getType()); 1039 1040 // FIXME: What does alignment mean for an image? 1041 Info.opc = ISD::INTRINSIC_W_CHAIN; 1042 Info.flags |= MachineMemOperand::MOLoad; 1043 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1044 Info.opc = ISD::INTRINSIC_VOID; 1045 1046 Type *DataTy = CI.getArgOperand(0)->getType(); 1047 if (RsrcIntr->IsImage) { 1048 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1049 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1050 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1051 } else 1052 Info.memVT = EVT::getEVT(DataTy); 1053 1054 Info.flags |= MachineMemOperand::MOStore; 1055 } else { 1056 // Atomic 1057 Info.opc = ISD::INTRINSIC_W_CHAIN; 1058 Info.memVT = MVT::getVT(CI.getType()); 1059 Info.flags = MachineMemOperand::MOLoad | 1060 MachineMemOperand::MOStore | 1061 MachineMemOperand::MODereferenceable; 1062 1063 // XXX - Should this be volatile without known ordering? 1064 Info.flags |= MachineMemOperand::MOVolatile; 1065 } 1066 return true; 1067 } 1068 1069 switch (IntrID) { 1070 case Intrinsic::amdgcn_atomic_inc: 1071 case Intrinsic::amdgcn_atomic_dec: 1072 case Intrinsic::amdgcn_ds_ordered_add: 1073 case Intrinsic::amdgcn_ds_ordered_swap: 1074 case Intrinsic::amdgcn_ds_fadd: 1075 case Intrinsic::amdgcn_ds_fmin: 1076 case Intrinsic::amdgcn_ds_fmax: { 1077 Info.opc = ISD::INTRINSIC_W_CHAIN; 1078 Info.memVT = MVT::getVT(CI.getType()); 1079 Info.ptrVal = CI.getOperand(0); 1080 Info.align.reset(); 1081 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1082 1083 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1084 if (!Vol->isZero()) 1085 Info.flags |= MachineMemOperand::MOVolatile; 1086 1087 return true; 1088 } 1089 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1090 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1091 1092 Info.opc = ISD::INTRINSIC_VOID; 1093 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1094 Info.ptrVal = MFI->getBufferPSV( 1095 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1096 CI.getArgOperand(1)); 1097 Info.align.reset(); 1098 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1099 1100 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1101 if (!Vol || !Vol->isZero()) 1102 Info.flags |= MachineMemOperand::MOVolatile; 1103 1104 return true; 1105 } 1106 case Intrinsic::amdgcn_global_atomic_fadd: { 1107 Info.opc = ISD::INTRINSIC_VOID; 1108 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 1109 ->getPointerElementType()); 1110 Info.ptrVal = CI.getOperand(0); 1111 Info.align.reset(); 1112 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1113 1114 return true; 1115 } 1116 case Intrinsic::amdgcn_ds_append: 1117 case Intrinsic::amdgcn_ds_consume: { 1118 Info.opc = ISD::INTRINSIC_W_CHAIN; 1119 Info.memVT = MVT::getVT(CI.getType()); 1120 Info.ptrVal = CI.getOperand(0); 1121 Info.align.reset(); 1122 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1123 1124 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1125 if (!Vol->isZero()) 1126 Info.flags |= MachineMemOperand::MOVolatile; 1127 1128 return true; 1129 } 1130 case Intrinsic::amdgcn_ds_gws_init: 1131 case Intrinsic::amdgcn_ds_gws_barrier: 1132 case Intrinsic::amdgcn_ds_gws_sema_v: 1133 case Intrinsic::amdgcn_ds_gws_sema_br: 1134 case Intrinsic::amdgcn_ds_gws_sema_p: 1135 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1136 Info.opc = ISD::INTRINSIC_VOID; 1137 1138 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1139 Info.ptrVal = 1140 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1141 1142 // This is an abstract access, but we need to specify a type and size. 1143 Info.memVT = MVT::i32; 1144 Info.size = 4; 1145 Info.align = Align(4); 1146 1147 Info.flags = MachineMemOperand::MOStore; 1148 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1149 Info.flags = MachineMemOperand::MOLoad; 1150 return true; 1151 } 1152 default: 1153 return false; 1154 } 1155 } 1156 1157 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1158 SmallVectorImpl<Value*> &Ops, 1159 Type *&AccessTy) const { 1160 switch (II->getIntrinsicID()) { 1161 case Intrinsic::amdgcn_atomic_inc: 1162 case Intrinsic::amdgcn_atomic_dec: 1163 case Intrinsic::amdgcn_ds_ordered_add: 1164 case Intrinsic::amdgcn_ds_ordered_swap: 1165 case Intrinsic::amdgcn_ds_fadd: 1166 case Intrinsic::amdgcn_ds_fmin: 1167 case Intrinsic::amdgcn_ds_fmax: { 1168 Value *Ptr = II->getArgOperand(0); 1169 AccessTy = II->getType(); 1170 Ops.push_back(Ptr); 1171 return true; 1172 } 1173 default: 1174 return false; 1175 } 1176 } 1177 1178 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1179 if (!Subtarget->hasFlatInstOffsets()) { 1180 // Flat instructions do not have offsets, and only have the register 1181 // address. 1182 return AM.BaseOffs == 0 && AM.Scale == 0; 1183 } 1184 1185 return AM.Scale == 0 && 1186 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1187 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1188 /*Signed=*/false)); 1189 } 1190 1191 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1192 if (Subtarget->hasFlatGlobalInsts()) 1193 return AM.Scale == 0 && 1194 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1195 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1196 /*Signed=*/true)); 1197 1198 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1199 // Assume the we will use FLAT for all global memory accesses 1200 // on VI. 1201 // FIXME: This assumption is currently wrong. On VI we still use 1202 // MUBUF instructions for the r + i addressing mode. As currently 1203 // implemented, the MUBUF instructions only work on buffer < 4GB. 1204 // It may be possible to support > 4GB buffers with MUBUF instructions, 1205 // by setting the stride value in the resource descriptor which would 1206 // increase the size limit to (stride * 4GB). However, this is risky, 1207 // because it has never been validated. 1208 return isLegalFlatAddressingMode(AM); 1209 } 1210 1211 return isLegalMUBUFAddressingMode(AM); 1212 } 1213 1214 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1215 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1216 // additionally can do r + r + i with addr64. 32-bit has more addressing 1217 // mode options. Depending on the resource constant, it can also do 1218 // (i64 r0) + (i32 r1) * (i14 i). 1219 // 1220 // Private arrays end up using a scratch buffer most of the time, so also 1221 // assume those use MUBUF instructions. Scratch loads / stores are currently 1222 // implemented as mubuf instructions with offen bit set, so slightly 1223 // different than the normal addr64. 1224 if (!isUInt<12>(AM.BaseOffs)) 1225 return false; 1226 1227 // FIXME: Since we can split immediate into soffset and immediate offset, 1228 // would it make sense to allow any immediate? 1229 1230 switch (AM.Scale) { 1231 case 0: // r + i or just i, depending on HasBaseReg. 1232 return true; 1233 case 1: 1234 return true; // We have r + r or r + i. 1235 case 2: 1236 if (AM.HasBaseReg) { 1237 // Reject 2 * r + r. 1238 return false; 1239 } 1240 1241 // Allow 2 * r as r + r 1242 // Or 2 * r + i is allowed as r + r + i. 1243 return true; 1244 default: // Don't allow n * r 1245 return false; 1246 } 1247 } 1248 1249 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1250 const AddrMode &AM, Type *Ty, 1251 unsigned AS, Instruction *I) const { 1252 // No global is ever allowed as a base. 1253 if (AM.BaseGV) 1254 return false; 1255 1256 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1257 return isLegalGlobalAddressingMode(AM); 1258 1259 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1260 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1261 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1262 // If the offset isn't a multiple of 4, it probably isn't going to be 1263 // correctly aligned. 1264 // FIXME: Can we get the real alignment here? 1265 if (AM.BaseOffs % 4 != 0) 1266 return isLegalMUBUFAddressingMode(AM); 1267 1268 // There are no SMRD extloads, so if we have to do a small type access we 1269 // will use a MUBUF load. 1270 // FIXME?: We also need to do this if unaligned, but we don't know the 1271 // alignment here. 1272 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1273 return isLegalGlobalAddressingMode(AM); 1274 1275 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1276 // SMRD instructions have an 8-bit, dword offset on SI. 1277 if (!isUInt<8>(AM.BaseOffs / 4)) 1278 return false; 1279 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1280 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1281 // in 8-bits, it can use a smaller encoding. 1282 if (!isUInt<32>(AM.BaseOffs / 4)) 1283 return false; 1284 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1285 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1286 if (!isUInt<20>(AM.BaseOffs)) 1287 return false; 1288 } else 1289 llvm_unreachable("unhandled generation"); 1290 1291 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1292 return true; 1293 1294 if (AM.Scale == 1 && AM.HasBaseReg) 1295 return true; 1296 1297 return false; 1298 1299 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1300 return isLegalMUBUFAddressingMode(AM); 1301 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1302 AS == AMDGPUAS::REGION_ADDRESS) { 1303 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1304 // field. 1305 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1306 // an 8-bit dword offset but we don't know the alignment here. 1307 if (!isUInt<16>(AM.BaseOffs)) 1308 return false; 1309 1310 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1311 return true; 1312 1313 if (AM.Scale == 1 && AM.HasBaseReg) 1314 return true; 1315 1316 return false; 1317 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1318 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1319 // For an unknown address space, this usually means that this is for some 1320 // reason being used for pure arithmetic, and not based on some addressing 1321 // computation. We don't have instructions that compute pointers with any 1322 // addressing modes, so treat them as having no offset like flat 1323 // instructions. 1324 return isLegalFlatAddressingMode(AM); 1325 } 1326 1327 // Assume a user alias of global for unknown address spaces. 1328 return isLegalGlobalAddressingMode(AM); 1329 } 1330 1331 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1332 const SelectionDAG &DAG) const { 1333 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1334 return (MemVT.getSizeInBits() <= 4 * 32); 1335 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1336 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1337 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1338 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1339 return (MemVT.getSizeInBits() <= 2 * 32); 1340 } 1341 return true; 1342 } 1343 1344 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1345 unsigned Size, unsigned AddrSpace, unsigned Align, 1346 MachineMemOperand::Flags Flags, bool *IsFast) const { 1347 if (IsFast) 1348 *IsFast = false; 1349 1350 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1351 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1352 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1353 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1354 // with adjacent offsets. 1355 bool AlignedBy4 = (Align % 4 == 0); 1356 if (IsFast) 1357 *IsFast = AlignedBy4; 1358 1359 return AlignedBy4; 1360 } 1361 1362 // FIXME: We have to be conservative here and assume that flat operations 1363 // will access scratch. If we had access to the IR function, then we 1364 // could determine if any private memory was used in the function. 1365 if (!Subtarget->hasUnalignedScratchAccess() && 1366 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1367 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1368 bool AlignedBy4 = Align >= 4; 1369 if (IsFast) 1370 *IsFast = AlignedBy4; 1371 1372 return AlignedBy4; 1373 } 1374 1375 if (Subtarget->hasUnalignedBufferAccess()) { 1376 // If we have an uniform constant load, it still requires using a slow 1377 // buffer instruction if unaligned. 1378 if (IsFast) { 1379 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1380 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1381 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1382 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1383 Align >= 4 : Align != 2; 1384 } 1385 1386 return true; 1387 } 1388 1389 // Smaller than dword value must be aligned. 1390 if (Size < 32) 1391 return false; 1392 1393 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1394 // byte-address are ignored, thus forcing Dword alignment. 1395 // This applies to private, global, and constant memory. 1396 if (IsFast) 1397 *IsFast = true; 1398 1399 return Size >= 32 && Align >= 4; 1400 } 1401 1402 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1403 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1404 bool *IsFast) const { 1405 if (IsFast) 1406 *IsFast = false; 1407 1408 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1409 // which isn't a simple VT. 1410 // Until MVT is extended to handle this, simply check for the size and 1411 // rely on the condition below: allow accesses if the size is a multiple of 4. 1412 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1413 VT.getStoreSize() > 16)) { 1414 return false; 1415 } 1416 1417 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1418 Align, Flags, IsFast); 1419 } 1420 1421 EVT SITargetLowering::getOptimalMemOpType( 1422 const MemOp &Op, const AttributeList &FuncAttributes) const { 1423 // FIXME: Should account for address space here. 1424 1425 // The default fallback uses the private pointer size as a guess for a type to 1426 // use. Make sure we switch these to 64-bit accesses. 1427 1428 if (Op.size() >= 16 && 1429 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1430 return MVT::v4i32; 1431 1432 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1433 return MVT::v2i32; 1434 1435 // Use the default. 1436 return MVT::Other; 1437 } 1438 1439 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1440 unsigned DestAS) const { 1441 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1442 } 1443 1444 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1445 const MemSDNode *MemNode = cast<MemSDNode>(N); 1446 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1447 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1448 return I && I->getMetadata("amdgpu.noclobber"); 1449 } 1450 1451 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1452 unsigned DestAS) const { 1453 // Flat -> private/local is a simple truncate. 1454 // Flat -> global is no-op 1455 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1456 return true; 1457 1458 return isNoopAddrSpaceCast(SrcAS, DestAS); 1459 } 1460 1461 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1462 const MemSDNode *MemNode = cast<MemSDNode>(N); 1463 1464 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1465 } 1466 1467 TargetLoweringBase::LegalizeTypeAction 1468 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1469 int NumElts = VT.getVectorNumElements(); 1470 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1471 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1472 return TargetLoweringBase::getPreferredVectorAction(VT); 1473 } 1474 1475 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1476 Type *Ty) const { 1477 // FIXME: Could be smarter if called for vector constants. 1478 return true; 1479 } 1480 1481 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1482 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1483 switch (Op) { 1484 case ISD::LOAD: 1485 case ISD::STORE: 1486 1487 // These operations are done with 32-bit instructions anyway. 1488 case ISD::AND: 1489 case ISD::OR: 1490 case ISD::XOR: 1491 case ISD::SELECT: 1492 // TODO: Extensions? 1493 return true; 1494 default: 1495 return false; 1496 } 1497 } 1498 1499 // SimplifySetCC uses this function to determine whether or not it should 1500 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1501 if (VT == MVT::i1 && Op == ISD::SETCC) 1502 return false; 1503 1504 return TargetLowering::isTypeDesirableForOp(Op, VT); 1505 } 1506 1507 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1508 const SDLoc &SL, 1509 SDValue Chain, 1510 uint64_t Offset) const { 1511 const DataLayout &DL = DAG.getDataLayout(); 1512 MachineFunction &MF = DAG.getMachineFunction(); 1513 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1514 1515 const ArgDescriptor *InputPtrReg; 1516 const TargetRegisterClass *RC; 1517 1518 std::tie(InputPtrReg, RC) 1519 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1520 1521 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1522 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1523 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1524 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1525 1526 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1527 } 1528 1529 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1530 const SDLoc &SL) const { 1531 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1532 FIRST_IMPLICIT); 1533 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1534 } 1535 1536 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1537 const SDLoc &SL, SDValue Val, 1538 bool Signed, 1539 const ISD::InputArg *Arg) const { 1540 // First, if it is a widened vector, narrow it. 1541 if (VT.isVector() && 1542 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1543 EVT NarrowedVT = 1544 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1545 VT.getVectorNumElements()); 1546 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1547 DAG.getConstant(0, SL, MVT::i32)); 1548 } 1549 1550 // Then convert the vector elements or scalar value. 1551 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1552 VT.bitsLT(MemVT)) { 1553 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1554 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1555 } 1556 1557 if (MemVT.isFloatingPoint()) 1558 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1559 else if (Signed) 1560 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1561 else 1562 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1563 1564 return Val; 1565 } 1566 1567 SDValue SITargetLowering::lowerKernargMemParameter( 1568 SelectionDAG &DAG, EVT VT, EVT MemVT, 1569 const SDLoc &SL, SDValue Chain, 1570 uint64_t Offset, unsigned Align, bool Signed, 1571 const ISD::InputArg *Arg) const { 1572 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1573 1574 // Try to avoid using an extload by loading earlier than the argument address, 1575 // and extracting the relevant bits. The load should hopefully be merged with 1576 // the previous argument. 1577 if (MemVT.getStoreSize() < 4 && Align < 4) { 1578 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1579 int64_t AlignDownOffset = alignDown(Offset, 4); 1580 int64_t OffsetDiff = Offset - AlignDownOffset; 1581 1582 EVT IntVT = MemVT.changeTypeToInteger(); 1583 1584 // TODO: If we passed in the base kernel offset we could have a better 1585 // alignment than 4, but we don't really need it. 1586 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1587 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1588 MachineMemOperand::MODereferenceable | 1589 MachineMemOperand::MOInvariant); 1590 1591 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1592 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1593 1594 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1595 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1596 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1597 1598 1599 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1600 } 1601 1602 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1603 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1604 MachineMemOperand::MODereferenceable | 1605 MachineMemOperand::MOInvariant); 1606 1607 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1608 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1609 } 1610 1611 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1612 const SDLoc &SL, SDValue Chain, 1613 const ISD::InputArg &Arg) const { 1614 MachineFunction &MF = DAG.getMachineFunction(); 1615 MachineFrameInfo &MFI = MF.getFrameInfo(); 1616 1617 if (Arg.Flags.isByVal()) { 1618 unsigned Size = Arg.Flags.getByValSize(); 1619 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1620 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1621 } 1622 1623 unsigned ArgOffset = VA.getLocMemOffset(); 1624 unsigned ArgSize = VA.getValVT().getStoreSize(); 1625 1626 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1627 1628 // Create load nodes to retrieve arguments from the stack. 1629 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1630 SDValue ArgValue; 1631 1632 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1633 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1634 MVT MemVT = VA.getValVT(); 1635 1636 switch (VA.getLocInfo()) { 1637 default: 1638 break; 1639 case CCValAssign::BCvt: 1640 MemVT = VA.getLocVT(); 1641 break; 1642 case CCValAssign::SExt: 1643 ExtType = ISD::SEXTLOAD; 1644 break; 1645 case CCValAssign::ZExt: 1646 ExtType = ISD::ZEXTLOAD; 1647 break; 1648 case CCValAssign::AExt: 1649 ExtType = ISD::EXTLOAD; 1650 break; 1651 } 1652 1653 ArgValue = DAG.getExtLoad( 1654 ExtType, SL, VA.getLocVT(), Chain, FIN, 1655 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1656 MemVT); 1657 return ArgValue; 1658 } 1659 1660 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1661 const SIMachineFunctionInfo &MFI, 1662 EVT VT, 1663 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1664 const ArgDescriptor *Reg; 1665 const TargetRegisterClass *RC; 1666 1667 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1668 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1669 } 1670 1671 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1672 CallingConv::ID CallConv, 1673 ArrayRef<ISD::InputArg> Ins, 1674 BitVector &Skipped, 1675 FunctionType *FType, 1676 SIMachineFunctionInfo *Info) { 1677 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1678 const ISD::InputArg *Arg = &Ins[I]; 1679 1680 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1681 "vector type argument should have been split"); 1682 1683 // First check if it's a PS input addr. 1684 if (CallConv == CallingConv::AMDGPU_PS && 1685 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1686 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1687 1688 // Inconveniently only the first part of the split is marked as isSplit, 1689 // so skip to the end. We only want to increment PSInputNum once for the 1690 // entire split argument. 1691 if (Arg->Flags.isSplit()) { 1692 while (!Arg->Flags.isSplitEnd()) { 1693 assert((!Arg->VT.isVector() || 1694 Arg->VT.getScalarSizeInBits() == 16) && 1695 "unexpected vector split in ps argument type"); 1696 if (!SkipArg) 1697 Splits.push_back(*Arg); 1698 Arg = &Ins[++I]; 1699 } 1700 } 1701 1702 if (SkipArg) { 1703 // We can safely skip PS inputs. 1704 Skipped.set(Arg->getOrigArgIndex()); 1705 ++PSInputNum; 1706 continue; 1707 } 1708 1709 Info->markPSInputAllocated(PSInputNum); 1710 if (Arg->Used) 1711 Info->markPSInputEnabled(PSInputNum); 1712 1713 ++PSInputNum; 1714 } 1715 1716 Splits.push_back(*Arg); 1717 } 1718 } 1719 1720 // Allocate special inputs passed in VGPRs. 1721 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1722 MachineFunction &MF, 1723 const SIRegisterInfo &TRI, 1724 SIMachineFunctionInfo &Info) const { 1725 const LLT S32 = LLT::scalar(32); 1726 MachineRegisterInfo &MRI = MF.getRegInfo(); 1727 1728 if (Info.hasWorkItemIDX()) { 1729 Register Reg = AMDGPU::VGPR0; 1730 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1731 1732 CCInfo.AllocateReg(Reg); 1733 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1734 } 1735 1736 if (Info.hasWorkItemIDY()) { 1737 Register Reg = AMDGPU::VGPR1; 1738 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1739 1740 CCInfo.AllocateReg(Reg); 1741 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1742 } 1743 1744 if (Info.hasWorkItemIDZ()) { 1745 Register Reg = AMDGPU::VGPR2; 1746 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1747 1748 CCInfo.AllocateReg(Reg); 1749 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1750 } 1751 } 1752 1753 // Try to allocate a VGPR at the end of the argument list, or if no argument 1754 // VGPRs are left allocating a stack slot. 1755 // If \p Mask is is given it indicates bitfield position in the register. 1756 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1757 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1758 ArgDescriptor Arg = ArgDescriptor()) { 1759 if (Arg.isSet()) 1760 return ArgDescriptor::createArg(Arg, Mask); 1761 1762 ArrayRef<MCPhysReg> ArgVGPRs 1763 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1764 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1765 if (RegIdx == ArgVGPRs.size()) { 1766 // Spill to stack required. 1767 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1768 1769 return ArgDescriptor::createStack(Offset, Mask); 1770 } 1771 1772 unsigned Reg = ArgVGPRs[RegIdx]; 1773 Reg = CCInfo.AllocateReg(Reg); 1774 assert(Reg != AMDGPU::NoRegister); 1775 1776 MachineFunction &MF = CCInfo.getMachineFunction(); 1777 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1778 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1779 return ArgDescriptor::createRegister(Reg, Mask); 1780 } 1781 1782 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1783 const TargetRegisterClass *RC, 1784 unsigned NumArgRegs) { 1785 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1786 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1787 if (RegIdx == ArgSGPRs.size()) 1788 report_fatal_error("ran out of SGPRs for arguments"); 1789 1790 unsigned Reg = ArgSGPRs[RegIdx]; 1791 Reg = CCInfo.AllocateReg(Reg); 1792 assert(Reg != AMDGPU::NoRegister); 1793 1794 MachineFunction &MF = CCInfo.getMachineFunction(); 1795 MF.addLiveIn(Reg, RC); 1796 return ArgDescriptor::createRegister(Reg); 1797 } 1798 1799 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1800 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1801 } 1802 1803 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1804 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1805 } 1806 1807 /// Allocate implicit function VGPR arguments at the end of allocated user 1808 /// arguments. 1809 void SITargetLowering::allocateSpecialInputVGPRs( 1810 CCState &CCInfo, MachineFunction &MF, 1811 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1812 const unsigned Mask = 0x3ff; 1813 ArgDescriptor Arg; 1814 1815 if (Info.hasWorkItemIDX()) { 1816 Arg = allocateVGPR32Input(CCInfo, Mask); 1817 Info.setWorkItemIDX(Arg); 1818 } 1819 1820 if (Info.hasWorkItemIDY()) { 1821 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1822 Info.setWorkItemIDY(Arg); 1823 } 1824 1825 if (Info.hasWorkItemIDZ()) 1826 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1827 } 1828 1829 /// Allocate implicit function VGPR arguments in fixed registers. 1830 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1831 CCState &CCInfo, MachineFunction &MF, 1832 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1833 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1834 if (!Reg) 1835 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1836 1837 const unsigned Mask = 0x3ff; 1838 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1839 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1840 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1841 } 1842 1843 void SITargetLowering::allocateSpecialInputSGPRs( 1844 CCState &CCInfo, 1845 MachineFunction &MF, 1846 const SIRegisterInfo &TRI, 1847 SIMachineFunctionInfo &Info) const { 1848 auto &ArgInfo = Info.getArgInfo(); 1849 1850 // TODO: Unify handling with private memory pointers. 1851 1852 if (Info.hasDispatchPtr()) 1853 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1854 1855 if (Info.hasQueuePtr()) 1856 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1857 1858 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1859 // constant offset from the kernarg segment. 1860 if (Info.hasImplicitArgPtr()) 1861 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1862 1863 if (Info.hasDispatchID()) 1864 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1865 1866 // flat_scratch_init is not applicable for non-kernel functions. 1867 1868 if (Info.hasWorkGroupIDX()) 1869 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1870 1871 if (Info.hasWorkGroupIDY()) 1872 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1873 1874 if (Info.hasWorkGroupIDZ()) 1875 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1876 } 1877 1878 // Allocate special inputs passed in user SGPRs. 1879 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1880 MachineFunction &MF, 1881 const SIRegisterInfo &TRI, 1882 SIMachineFunctionInfo &Info) const { 1883 if (Info.hasImplicitBufferPtr()) { 1884 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1885 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1886 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1887 } 1888 1889 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1890 if (Info.hasPrivateSegmentBuffer()) { 1891 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1892 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1893 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1894 } 1895 1896 if (Info.hasDispatchPtr()) { 1897 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1898 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1899 CCInfo.AllocateReg(DispatchPtrReg); 1900 } 1901 1902 if (Info.hasQueuePtr()) { 1903 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1904 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1905 CCInfo.AllocateReg(QueuePtrReg); 1906 } 1907 1908 if (Info.hasKernargSegmentPtr()) { 1909 MachineRegisterInfo &MRI = MF.getRegInfo(); 1910 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1911 CCInfo.AllocateReg(InputPtrReg); 1912 1913 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1914 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1915 } 1916 1917 if (Info.hasDispatchID()) { 1918 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1919 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1920 CCInfo.AllocateReg(DispatchIDReg); 1921 } 1922 1923 if (Info.hasFlatScratchInit()) { 1924 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1925 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1926 CCInfo.AllocateReg(FlatScratchInitReg); 1927 } 1928 1929 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1930 // these from the dispatch pointer. 1931 } 1932 1933 // Allocate special input registers that are initialized per-wave. 1934 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1935 MachineFunction &MF, 1936 SIMachineFunctionInfo &Info, 1937 CallingConv::ID CallConv, 1938 bool IsShader) const { 1939 if (Info.hasWorkGroupIDX()) { 1940 unsigned Reg = Info.addWorkGroupIDX(); 1941 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1942 CCInfo.AllocateReg(Reg); 1943 } 1944 1945 if (Info.hasWorkGroupIDY()) { 1946 unsigned Reg = Info.addWorkGroupIDY(); 1947 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1948 CCInfo.AllocateReg(Reg); 1949 } 1950 1951 if (Info.hasWorkGroupIDZ()) { 1952 unsigned Reg = Info.addWorkGroupIDZ(); 1953 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1954 CCInfo.AllocateReg(Reg); 1955 } 1956 1957 if (Info.hasWorkGroupInfo()) { 1958 unsigned Reg = Info.addWorkGroupInfo(); 1959 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1960 CCInfo.AllocateReg(Reg); 1961 } 1962 1963 if (Info.hasPrivateSegmentWaveByteOffset()) { 1964 // Scratch wave offset passed in system SGPR. 1965 unsigned PrivateSegmentWaveByteOffsetReg; 1966 1967 if (IsShader) { 1968 PrivateSegmentWaveByteOffsetReg = 1969 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1970 1971 // This is true if the scratch wave byte offset doesn't have a fixed 1972 // location. 1973 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1974 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1975 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1976 } 1977 } else 1978 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1979 1980 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1981 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1982 } 1983 } 1984 1985 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1986 MachineFunction &MF, 1987 const SIRegisterInfo &TRI, 1988 SIMachineFunctionInfo &Info) { 1989 // Now that we've figured out where the scratch register inputs are, see if 1990 // should reserve the arguments and use them directly. 1991 MachineFrameInfo &MFI = MF.getFrameInfo(); 1992 bool HasStackObjects = MFI.hasStackObjects(); 1993 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 1994 1995 // Record that we know we have non-spill stack objects so we don't need to 1996 // check all stack objects later. 1997 if (HasStackObjects) 1998 Info.setHasNonSpillStackObjects(true); 1999 2000 // Everything live out of a block is spilled with fast regalloc, so it's 2001 // almost certain that spilling will be required. 2002 if (TM.getOptLevel() == CodeGenOpt::None) 2003 HasStackObjects = true; 2004 2005 // For now assume stack access is needed in any callee functions, so we need 2006 // the scratch registers to pass in. 2007 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2008 2009 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2010 // If we have stack objects, we unquestionably need the private buffer 2011 // resource. For the Code Object V2 ABI, this will be the first 4 user 2012 // SGPR inputs. We can reserve those and use them directly. 2013 2014 Register PrivateSegmentBufferReg = 2015 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2016 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2017 } else { 2018 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2019 // We tentatively reserve the last registers (skipping the last registers 2020 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2021 // we'll replace these with the ones immediately after those which were 2022 // really allocated. In the prologue copies will be inserted from the 2023 // argument to these reserved registers. 2024 2025 // Without HSA, relocations are used for the scratch pointer and the 2026 // buffer resource setup is always inserted in the prologue. Scratch wave 2027 // offset is still in an input SGPR. 2028 Info.setScratchRSrcReg(ReservedBufferReg); 2029 } 2030 2031 MachineRegisterInfo &MRI = MF.getRegInfo(); 2032 2033 // For entry functions we have to set up the stack pointer if we use it, 2034 // whereas non-entry functions get this "for free". This means there is no 2035 // intrinsic advantage to using S32 over S34 in cases where we do not have 2036 // calls but do need a frame pointer (i.e. if we are requested to have one 2037 // because frame pointer elimination is disabled). To keep things simple we 2038 // only ever use S32 as the call ABI stack pointer, and so using it does not 2039 // imply we need a separate frame pointer. 2040 // 2041 // Try to use s32 as the SP, but move it if it would interfere with input 2042 // arguments. This won't work with calls though. 2043 // 2044 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2045 // registers. 2046 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2047 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2048 } else { 2049 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2050 2051 if (MFI.hasCalls()) 2052 report_fatal_error("call in graphics shader with too many input SGPRs"); 2053 2054 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2055 if (!MRI.isLiveIn(Reg)) { 2056 Info.setStackPtrOffsetReg(Reg); 2057 break; 2058 } 2059 } 2060 2061 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2062 report_fatal_error("failed to find register for SP"); 2063 } 2064 2065 // hasFP should be accurate for entry functions even before the frame is 2066 // finalized, because it does not rely on the known stack size, only 2067 // properties like whether variable sized objects are present. 2068 if (ST.getFrameLowering()->hasFP(MF)) { 2069 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2070 } 2071 } 2072 2073 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2074 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2075 return !Info->isEntryFunction(); 2076 } 2077 2078 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2079 2080 } 2081 2082 void SITargetLowering::insertCopiesSplitCSR( 2083 MachineBasicBlock *Entry, 2084 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2085 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2086 2087 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2088 if (!IStart) 2089 return; 2090 2091 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2092 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2093 MachineBasicBlock::iterator MBBI = Entry->begin(); 2094 for (const MCPhysReg *I = IStart; *I; ++I) { 2095 const TargetRegisterClass *RC = nullptr; 2096 if (AMDGPU::SReg_64RegClass.contains(*I)) 2097 RC = &AMDGPU::SGPR_64RegClass; 2098 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2099 RC = &AMDGPU::SGPR_32RegClass; 2100 else 2101 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2102 2103 Register NewVR = MRI->createVirtualRegister(RC); 2104 // Create copy from CSR to a virtual register. 2105 Entry->addLiveIn(*I); 2106 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2107 .addReg(*I); 2108 2109 // Insert the copy-back instructions right before the terminator. 2110 for (auto *Exit : Exits) 2111 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2112 TII->get(TargetOpcode::COPY), *I) 2113 .addReg(NewVR); 2114 } 2115 } 2116 2117 SDValue SITargetLowering::LowerFormalArguments( 2118 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2119 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2120 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2121 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2122 2123 MachineFunction &MF = DAG.getMachineFunction(); 2124 const Function &Fn = MF.getFunction(); 2125 FunctionType *FType = MF.getFunction().getFunctionType(); 2126 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2127 2128 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2129 DiagnosticInfoUnsupported NoGraphicsHSA( 2130 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2131 DAG.getContext()->diagnose(NoGraphicsHSA); 2132 return DAG.getEntryNode(); 2133 } 2134 2135 SmallVector<ISD::InputArg, 16> Splits; 2136 SmallVector<CCValAssign, 16> ArgLocs; 2137 BitVector Skipped(Ins.size()); 2138 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2139 *DAG.getContext()); 2140 2141 bool IsShader = AMDGPU::isShader(CallConv); 2142 bool IsKernel = AMDGPU::isKernel(CallConv); 2143 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2144 2145 if (IsShader) { 2146 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2147 2148 // At least one interpolation mode must be enabled or else the GPU will 2149 // hang. 2150 // 2151 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2152 // set PSInputAddr, the user wants to enable some bits after the compilation 2153 // based on run-time states. Since we can't know what the final PSInputEna 2154 // will look like, so we shouldn't do anything here and the user should take 2155 // responsibility for the correct programming. 2156 // 2157 // Otherwise, the following restrictions apply: 2158 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2159 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2160 // enabled too. 2161 if (CallConv == CallingConv::AMDGPU_PS) { 2162 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2163 ((Info->getPSInputAddr() & 0xF) == 0 && 2164 Info->isPSInputAllocated(11))) { 2165 CCInfo.AllocateReg(AMDGPU::VGPR0); 2166 CCInfo.AllocateReg(AMDGPU::VGPR1); 2167 Info->markPSInputAllocated(0); 2168 Info->markPSInputEnabled(0); 2169 } 2170 if (Subtarget->isAmdPalOS()) { 2171 // For isAmdPalOS, the user does not enable some bits after compilation 2172 // based on run-time states; the register values being generated here are 2173 // the final ones set in hardware. Therefore we need to apply the 2174 // workaround to PSInputAddr and PSInputEnable together. (The case where 2175 // a bit is set in PSInputAddr but not PSInputEnable is where the 2176 // frontend set up an input arg for a particular interpolation mode, but 2177 // nothing uses that input arg. Really we should have an earlier pass 2178 // that removes such an arg.) 2179 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2180 if ((PsInputBits & 0x7F) == 0 || 2181 ((PsInputBits & 0xF) == 0 && 2182 (PsInputBits >> 11 & 1))) 2183 Info->markPSInputEnabled( 2184 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2185 } 2186 } 2187 2188 assert(!Info->hasDispatchPtr() && 2189 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2190 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2191 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2192 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2193 !Info->hasWorkItemIDZ()); 2194 } else if (IsKernel) { 2195 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2196 } else { 2197 Splits.append(Ins.begin(), Ins.end()); 2198 } 2199 2200 if (IsEntryFunc) { 2201 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2202 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2203 } else { 2204 // For the fixed ABI, pass workitem IDs in the last argument register. 2205 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2206 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2207 } 2208 2209 if (IsKernel) { 2210 analyzeFormalArgumentsCompute(CCInfo, Ins); 2211 } else { 2212 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2213 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2214 } 2215 2216 SmallVector<SDValue, 16> Chains; 2217 2218 // FIXME: This is the minimum kernel argument alignment. We should improve 2219 // this to the maximum alignment of the arguments. 2220 // 2221 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2222 // kern arg offset. 2223 const unsigned KernelArgBaseAlign = 16; 2224 2225 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2226 const ISD::InputArg &Arg = Ins[i]; 2227 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2228 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2229 continue; 2230 } 2231 2232 CCValAssign &VA = ArgLocs[ArgIdx++]; 2233 MVT VT = VA.getLocVT(); 2234 2235 if (IsEntryFunc && VA.isMemLoc()) { 2236 VT = Ins[i].VT; 2237 EVT MemVT = VA.getLocVT(); 2238 2239 const uint64_t Offset = VA.getLocMemOffset(); 2240 unsigned Align = MinAlign(KernelArgBaseAlign, Offset); 2241 2242 SDValue Arg = lowerKernargMemParameter( 2243 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]); 2244 Chains.push_back(Arg.getValue(1)); 2245 2246 auto *ParamTy = 2247 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2248 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2249 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2250 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2251 // On SI local pointers are just offsets into LDS, so they are always 2252 // less than 16-bits. On CI and newer they could potentially be 2253 // real pointers, so we can't guarantee their size. 2254 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2255 DAG.getValueType(MVT::i16)); 2256 } 2257 2258 InVals.push_back(Arg); 2259 continue; 2260 } else if (!IsEntryFunc && VA.isMemLoc()) { 2261 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2262 InVals.push_back(Val); 2263 if (!Arg.Flags.isByVal()) 2264 Chains.push_back(Val.getValue(1)); 2265 continue; 2266 } 2267 2268 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2269 2270 Register Reg = VA.getLocReg(); 2271 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2272 EVT ValVT = VA.getValVT(); 2273 2274 Reg = MF.addLiveIn(Reg, RC); 2275 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2276 2277 if (Arg.Flags.isSRet()) { 2278 // The return object should be reasonably addressable. 2279 2280 // FIXME: This helps when the return is a real sret. If it is a 2281 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2282 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2283 unsigned NumBits 2284 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2285 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2286 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2287 } 2288 2289 // If this is an 8 or 16-bit value, it is really passed promoted 2290 // to 32 bits. Insert an assert[sz]ext to capture this, then 2291 // truncate to the right size. 2292 switch (VA.getLocInfo()) { 2293 case CCValAssign::Full: 2294 break; 2295 case CCValAssign::BCvt: 2296 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2297 break; 2298 case CCValAssign::SExt: 2299 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2300 DAG.getValueType(ValVT)); 2301 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2302 break; 2303 case CCValAssign::ZExt: 2304 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2305 DAG.getValueType(ValVT)); 2306 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2307 break; 2308 case CCValAssign::AExt: 2309 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2310 break; 2311 default: 2312 llvm_unreachable("Unknown loc info!"); 2313 } 2314 2315 InVals.push_back(Val); 2316 } 2317 2318 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2319 // Special inputs come after user arguments. 2320 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2321 } 2322 2323 // Start adding system SGPRs. 2324 if (IsEntryFunc) { 2325 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2326 } else { 2327 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2328 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2329 } 2330 2331 auto &ArgUsageInfo = 2332 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2333 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2334 2335 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2336 Info->setBytesInStackArgArea(StackArgSize); 2337 2338 return Chains.empty() ? Chain : 2339 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2340 } 2341 2342 // TODO: If return values can't fit in registers, we should return as many as 2343 // possible in registers before passing on stack. 2344 bool SITargetLowering::CanLowerReturn( 2345 CallingConv::ID CallConv, 2346 MachineFunction &MF, bool IsVarArg, 2347 const SmallVectorImpl<ISD::OutputArg> &Outs, 2348 LLVMContext &Context) const { 2349 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2350 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2351 // for shaders. Vector types should be explicitly handled by CC. 2352 if (AMDGPU::isEntryFunctionCC(CallConv)) 2353 return true; 2354 2355 SmallVector<CCValAssign, 16> RVLocs; 2356 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2357 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2358 } 2359 2360 SDValue 2361 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2362 bool isVarArg, 2363 const SmallVectorImpl<ISD::OutputArg> &Outs, 2364 const SmallVectorImpl<SDValue> &OutVals, 2365 const SDLoc &DL, SelectionDAG &DAG) const { 2366 MachineFunction &MF = DAG.getMachineFunction(); 2367 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2368 2369 if (AMDGPU::isKernel(CallConv)) { 2370 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2371 OutVals, DL, DAG); 2372 } 2373 2374 bool IsShader = AMDGPU::isShader(CallConv); 2375 2376 Info->setIfReturnsVoid(Outs.empty()); 2377 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2378 2379 // CCValAssign - represent the assignment of the return value to a location. 2380 SmallVector<CCValAssign, 48> RVLocs; 2381 SmallVector<ISD::OutputArg, 48> Splits; 2382 2383 // CCState - Info about the registers and stack slots. 2384 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2385 *DAG.getContext()); 2386 2387 // Analyze outgoing return values. 2388 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2389 2390 SDValue Flag; 2391 SmallVector<SDValue, 48> RetOps; 2392 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2393 2394 // Add return address for callable functions. 2395 if (!Info->isEntryFunction()) { 2396 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2397 SDValue ReturnAddrReg = CreateLiveInRegister( 2398 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2399 2400 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2401 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2402 MVT::i64); 2403 Chain = 2404 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2405 Flag = Chain.getValue(1); 2406 RetOps.push_back(ReturnAddrVirtualReg); 2407 } 2408 2409 // Copy the result values into the output registers. 2410 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2411 ++I, ++RealRVLocIdx) { 2412 CCValAssign &VA = RVLocs[I]; 2413 assert(VA.isRegLoc() && "Can only return in registers!"); 2414 // TODO: Partially return in registers if return values don't fit. 2415 SDValue Arg = OutVals[RealRVLocIdx]; 2416 2417 // Copied from other backends. 2418 switch (VA.getLocInfo()) { 2419 case CCValAssign::Full: 2420 break; 2421 case CCValAssign::BCvt: 2422 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2423 break; 2424 case CCValAssign::SExt: 2425 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2426 break; 2427 case CCValAssign::ZExt: 2428 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2429 break; 2430 case CCValAssign::AExt: 2431 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2432 break; 2433 default: 2434 llvm_unreachable("Unknown loc info!"); 2435 } 2436 2437 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2438 Flag = Chain.getValue(1); 2439 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2440 } 2441 2442 // FIXME: Does sret work properly? 2443 if (!Info->isEntryFunction()) { 2444 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2445 const MCPhysReg *I = 2446 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2447 if (I) { 2448 for (; *I; ++I) { 2449 if (AMDGPU::SReg_64RegClass.contains(*I)) 2450 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2451 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2452 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2453 else 2454 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2455 } 2456 } 2457 } 2458 2459 // Update chain and glue. 2460 RetOps[0] = Chain; 2461 if (Flag.getNode()) 2462 RetOps.push_back(Flag); 2463 2464 unsigned Opc = AMDGPUISD::ENDPGM; 2465 if (!IsWaveEnd) 2466 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2467 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2468 } 2469 2470 SDValue SITargetLowering::LowerCallResult( 2471 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2472 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2473 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2474 SDValue ThisVal) const { 2475 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2476 2477 // Assign locations to each value returned by this call. 2478 SmallVector<CCValAssign, 16> RVLocs; 2479 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2480 *DAG.getContext()); 2481 CCInfo.AnalyzeCallResult(Ins, RetCC); 2482 2483 // Copy all of the result registers out of their specified physreg. 2484 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2485 CCValAssign VA = RVLocs[i]; 2486 SDValue Val; 2487 2488 if (VA.isRegLoc()) { 2489 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2490 Chain = Val.getValue(1); 2491 InFlag = Val.getValue(2); 2492 } else if (VA.isMemLoc()) { 2493 report_fatal_error("TODO: return values in memory"); 2494 } else 2495 llvm_unreachable("unknown argument location type"); 2496 2497 switch (VA.getLocInfo()) { 2498 case CCValAssign::Full: 2499 break; 2500 case CCValAssign::BCvt: 2501 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2502 break; 2503 case CCValAssign::ZExt: 2504 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2505 DAG.getValueType(VA.getValVT())); 2506 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2507 break; 2508 case CCValAssign::SExt: 2509 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2510 DAG.getValueType(VA.getValVT())); 2511 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2512 break; 2513 case CCValAssign::AExt: 2514 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2515 break; 2516 default: 2517 llvm_unreachable("Unknown loc info!"); 2518 } 2519 2520 InVals.push_back(Val); 2521 } 2522 2523 return Chain; 2524 } 2525 2526 // Add code to pass special inputs required depending on used features separate 2527 // from the explicit user arguments present in the IR. 2528 void SITargetLowering::passSpecialInputs( 2529 CallLoweringInfo &CLI, 2530 CCState &CCInfo, 2531 const SIMachineFunctionInfo &Info, 2532 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2533 SmallVectorImpl<SDValue> &MemOpChains, 2534 SDValue Chain) const { 2535 // If we don't have a call site, this was a call inserted by 2536 // legalization. These can never use special inputs. 2537 if (!CLI.CB) 2538 return; 2539 2540 SelectionDAG &DAG = CLI.DAG; 2541 const SDLoc &DL = CLI.DL; 2542 2543 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2544 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2545 2546 const AMDGPUFunctionArgInfo *CalleeArgInfo 2547 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2548 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2549 auto &ArgUsageInfo = 2550 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2551 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2552 } 2553 2554 // TODO: Unify with private memory register handling. This is complicated by 2555 // the fact that at least in kernels, the input argument is not necessarily 2556 // in the same location as the input. 2557 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2558 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2559 AMDGPUFunctionArgInfo::QUEUE_PTR, 2560 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2561 AMDGPUFunctionArgInfo::DISPATCH_ID, 2562 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2563 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2564 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2565 }; 2566 2567 for (auto InputID : InputRegs) { 2568 const ArgDescriptor *OutgoingArg; 2569 const TargetRegisterClass *ArgRC; 2570 2571 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID); 2572 if (!OutgoingArg) 2573 continue; 2574 2575 const ArgDescriptor *IncomingArg; 2576 const TargetRegisterClass *IncomingArgRC; 2577 std::tie(IncomingArg, IncomingArgRC) 2578 = CallerArgInfo.getPreloadedValue(InputID); 2579 assert(IncomingArgRC == ArgRC); 2580 2581 // All special arguments are ints for now. 2582 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2583 SDValue InputReg; 2584 2585 if (IncomingArg) { 2586 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2587 } else { 2588 // The implicit arg ptr is special because it doesn't have a corresponding 2589 // input for kernels, and is computed from the kernarg segment pointer. 2590 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2591 InputReg = getImplicitArgPtr(DAG, DL); 2592 } 2593 2594 if (OutgoingArg->isRegister()) { 2595 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2596 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2597 report_fatal_error("failed to allocate implicit input argument"); 2598 } else { 2599 unsigned SpecialArgOffset = 2600 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2601 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2602 SpecialArgOffset); 2603 MemOpChains.push_back(ArgStore); 2604 } 2605 } 2606 2607 // Pack workitem IDs into a single register or pass it as is if already 2608 // packed. 2609 const ArgDescriptor *OutgoingArg; 2610 const TargetRegisterClass *ArgRC; 2611 2612 std::tie(OutgoingArg, ArgRC) = 2613 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2614 if (!OutgoingArg) 2615 std::tie(OutgoingArg, ArgRC) = 2616 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2617 if (!OutgoingArg) 2618 std::tie(OutgoingArg, ArgRC) = 2619 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2620 if (!OutgoingArg) 2621 return; 2622 2623 const ArgDescriptor *IncomingArgX 2624 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first; 2625 const ArgDescriptor *IncomingArgY 2626 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first; 2627 const ArgDescriptor *IncomingArgZ 2628 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first; 2629 2630 SDValue InputReg; 2631 SDLoc SL; 2632 2633 // If incoming ids are not packed we need to pack them. 2634 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2635 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2636 2637 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2638 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2639 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2640 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2641 InputReg = InputReg.getNode() ? 2642 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2643 } 2644 2645 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2646 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2647 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2648 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2649 InputReg = InputReg.getNode() ? 2650 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2651 } 2652 2653 if (!InputReg.getNode()) { 2654 // Workitem ids are already packed, any of present incoming arguments 2655 // will carry all required fields. 2656 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2657 IncomingArgX ? *IncomingArgX : 2658 IncomingArgY ? *IncomingArgY : 2659 *IncomingArgZ, ~0u); 2660 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2661 } 2662 2663 if (OutgoingArg->isRegister()) { 2664 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2665 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2666 } else { 2667 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2668 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2669 SpecialArgOffset); 2670 MemOpChains.push_back(ArgStore); 2671 } 2672 } 2673 2674 static bool canGuaranteeTCO(CallingConv::ID CC) { 2675 return CC == CallingConv::Fast; 2676 } 2677 2678 /// Return true if we might ever do TCO for calls with this calling convention. 2679 static bool mayTailCallThisCC(CallingConv::ID CC) { 2680 switch (CC) { 2681 case CallingConv::C: 2682 return true; 2683 default: 2684 return canGuaranteeTCO(CC); 2685 } 2686 } 2687 2688 bool SITargetLowering::isEligibleForTailCallOptimization( 2689 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2690 const SmallVectorImpl<ISD::OutputArg> &Outs, 2691 const SmallVectorImpl<SDValue> &OutVals, 2692 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2693 if (!mayTailCallThisCC(CalleeCC)) 2694 return false; 2695 2696 MachineFunction &MF = DAG.getMachineFunction(); 2697 const Function &CallerF = MF.getFunction(); 2698 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2699 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2700 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2701 2702 // Kernels aren't callable, and don't have a live in return address so it 2703 // doesn't make sense to do a tail call with entry functions. 2704 if (!CallerPreserved) 2705 return false; 2706 2707 bool CCMatch = CallerCC == CalleeCC; 2708 2709 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2710 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2711 return true; 2712 return false; 2713 } 2714 2715 // TODO: Can we handle var args? 2716 if (IsVarArg) 2717 return false; 2718 2719 for (const Argument &Arg : CallerF.args()) { 2720 if (Arg.hasByValAttr()) 2721 return false; 2722 } 2723 2724 LLVMContext &Ctx = *DAG.getContext(); 2725 2726 // Check that the call results are passed in the same way. 2727 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2728 CCAssignFnForCall(CalleeCC, IsVarArg), 2729 CCAssignFnForCall(CallerCC, IsVarArg))) 2730 return false; 2731 2732 // The callee has to preserve all registers the caller needs to preserve. 2733 if (!CCMatch) { 2734 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2735 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2736 return false; 2737 } 2738 2739 // Nothing more to check if the callee is taking no arguments. 2740 if (Outs.empty()) 2741 return true; 2742 2743 SmallVector<CCValAssign, 16> ArgLocs; 2744 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2745 2746 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2747 2748 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2749 // If the stack arguments for this call do not fit into our own save area then 2750 // the call cannot be made tail. 2751 // TODO: Is this really necessary? 2752 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2753 return false; 2754 2755 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2756 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2757 } 2758 2759 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2760 if (!CI->isTailCall()) 2761 return false; 2762 2763 const Function *ParentFn = CI->getParent()->getParent(); 2764 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2765 return false; 2766 return true; 2767 } 2768 2769 // The wave scratch offset register is used as the global base pointer. 2770 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2771 SmallVectorImpl<SDValue> &InVals) const { 2772 SelectionDAG &DAG = CLI.DAG; 2773 const SDLoc &DL = CLI.DL; 2774 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2775 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2776 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2777 SDValue Chain = CLI.Chain; 2778 SDValue Callee = CLI.Callee; 2779 bool &IsTailCall = CLI.IsTailCall; 2780 CallingConv::ID CallConv = CLI.CallConv; 2781 bool IsVarArg = CLI.IsVarArg; 2782 bool IsSibCall = false; 2783 bool IsThisReturn = false; 2784 MachineFunction &MF = DAG.getMachineFunction(); 2785 2786 if (Callee.isUndef() || isNullConstant(Callee)) { 2787 if (!CLI.IsTailCall) { 2788 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2789 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2790 } 2791 2792 return Chain; 2793 } 2794 2795 if (IsVarArg) { 2796 return lowerUnhandledCall(CLI, InVals, 2797 "unsupported call to variadic function "); 2798 } 2799 2800 if (!CLI.CB) 2801 report_fatal_error("unsupported libcall legalization"); 2802 2803 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2804 !CLI.CB->getCalledFunction()) { 2805 return lowerUnhandledCall(CLI, InVals, 2806 "unsupported indirect call to function "); 2807 } 2808 2809 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2810 return lowerUnhandledCall(CLI, InVals, 2811 "unsupported required tail call to function "); 2812 } 2813 2814 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2815 // Note the issue is with the CC of the calling function, not of the call 2816 // itself. 2817 return lowerUnhandledCall(CLI, InVals, 2818 "unsupported call from graphics shader of function "); 2819 } 2820 2821 if (IsTailCall) { 2822 IsTailCall = isEligibleForTailCallOptimization( 2823 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2824 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2825 report_fatal_error("failed to perform tail call elimination on a call " 2826 "site marked musttail"); 2827 } 2828 2829 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2830 2831 // A sibling call is one where we're under the usual C ABI and not planning 2832 // to change that but can still do a tail call: 2833 if (!TailCallOpt && IsTailCall) 2834 IsSibCall = true; 2835 2836 if (IsTailCall) 2837 ++NumTailCalls; 2838 } 2839 2840 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2841 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2842 SmallVector<SDValue, 8> MemOpChains; 2843 2844 // Analyze operands of the call, assigning locations to each operand. 2845 SmallVector<CCValAssign, 16> ArgLocs; 2846 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2847 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2848 2849 if (AMDGPUTargetMachine::EnableFixedFunctionABI) { 2850 // With a fixed ABI, allocate fixed registers before user arguments. 2851 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2852 } 2853 2854 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2855 2856 // Get a count of how many bytes are to be pushed on the stack. 2857 unsigned NumBytes = CCInfo.getNextStackOffset(); 2858 2859 if (IsSibCall) { 2860 // Since we're not changing the ABI to make this a tail call, the memory 2861 // operands are already available in the caller's incoming argument space. 2862 NumBytes = 0; 2863 } 2864 2865 // FPDiff is the byte offset of the call's argument area from the callee's. 2866 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2867 // by this amount for a tail call. In a sibling call it must be 0 because the 2868 // caller will deallocate the entire stack and the callee still expects its 2869 // arguments to begin at SP+0. Completely unused for non-tail calls. 2870 int32_t FPDiff = 0; 2871 MachineFrameInfo &MFI = MF.getFrameInfo(); 2872 2873 // Adjust the stack pointer for the new arguments... 2874 // These operations are automatically eliminated by the prolog/epilog pass 2875 if (!IsSibCall) { 2876 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2877 2878 SmallVector<SDValue, 4> CopyFromChains; 2879 2880 // In the HSA case, this should be an identity copy. 2881 SDValue ScratchRSrcReg 2882 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2883 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2884 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2885 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2886 } 2887 2888 MVT PtrVT = MVT::i32; 2889 2890 // Walk the register/memloc assignments, inserting copies/loads. 2891 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2892 CCValAssign &VA = ArgLocs[i]; 2893 SDValue Arg = OutVals[i]; 2894 2895 // Promote the value if needed. 2896 switch (VA.getLocInfo()) { 2897 case CCValAssign::Full: 2898 break; 2899 case CCValAssign::BCvt: 2900 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2901 break; 2902 case CCValAssign::ZExt: 2903 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2904 break; 2905 case CCValAssign::SExt: 2906 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2907 break; 2908 case CCValAssign::AExt: 2909 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2910 break; 2911 case CCValAssign::FPExt: 2912 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2913 break; 2914 default: 2915 llvm_unreachable("Unknown loc info!"); 2916 } 2917 2918 if (VA.isRegLoc()) { 2919 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2920 } else { 2921 assert(VA.isMemLoc()); 2922 2923 SDValue DstAddr; 2924 MachinePointerInfo DstInfo; 2925 2926 unsigned LocMemOffset = VA.getLocMemOffset(); 2927 int32_t Offset = LocMemOffset; 2928 2929 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2930 MaybeAlign Alignment; 2931 2932 if (IsTailCall) { 2933 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2934 unsigned OpSize = Flags.isByVal() ? 2935 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2936 2937 // FIXME: We can have better than the minimum byval required alignment. 2938 Alignment = 2939 Flags.isByVal() 2940 ? Flags.getNonZeroByValAlign() 2941 : commonAlignment(Subtarget->getStackAlignment(), Offset); 2942 2943 Offset = Offset + FPDiff; 2944 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2945 2946 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2947 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2948 2949 // Make sure any stack arguments overlapping with where we're storing 2950 // are loaded before this eventual operation. Otherwise they'll be 2951 // clobbered. 2952 2953 // FIXME: Why is this really necessary? This seems to just result in a 2954 // lot of code to copy the stack and write them back to the same 2955 // locations, which are supposed to be immutable? 2956 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2957 } else { 2958 DstAddr = PtrOff; 2959 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2960 Alignment = 2961 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 2962 } 2963 2964 if (Outs[i].Flags.isByVal()) { 2965 SDValue SizeNode = 2966 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2967 SDValue Cpy = 2968 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 2969 Outs[i].Flags.getNonZeroByValAlign(), 2970 /*isVol = */ false, /*AlwaysInline = */ true, 2971 /*isTailCall = */ false, DstInfo, 2972 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 2973 2974 MemOpChains.push_back(Cpy); 2975 } else { 2976 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 2977 Alignment ? Alignment->value() : 0); 2978 MemOpChains.push_back(Store); 2979 } 2980 } 2981 } 2982 2983 if (!AMDGPUTargetMachine::EnableFixedFunctionABI) { 2984 // Copy special input registers after user input arguments. 2985 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2986 } 2987 2988 if (!MemOpChains.empty()) 2989 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2990 2991 // Build a sequence of copy-to-reg nodes chained together with token chain 2992 // and flag operands which copy the outgoing args into the appropriate regs. 2993 SDValue InFlag; 2994 for (auto &RegToPass : RegsToPass) { 2995 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2996 RegToPass.second, InFlag); 2997 InFlag = Chain.getValue(1); 2998 } 2999 3000 3001 SDValue PhysReturnAddrReg; 3002 if (IsTailCall) { 3003 // Since the return is being combined with the call, we need to pass on the 3004 // return address. 3005 3006 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3007 SDValue ReturnAddrReg = CreateLiveInRegister( 3008 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3009 3010 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3011 MVT::i64); 3012 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3013 InFlag = Chain.getValue(1); 3014 } 3015 3016 // We don't usually want to end the call-sequence here because we would tidy 3017 // the frame up *after* the call, however in the ABI-changing tail-call case 3018 // we've carefully laid out the parameters so that when sp is reset they'll be 3019 // in the correct location. 3020 if (IsTailCall && !IsSibCall) { 3021 Chain = DAG.getCALLSEQ_END(Chain, 3022 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3023 DAG.getTargetConstant(0, DL, MVT::i32), 3024 InFlag, DL); 3025 InFlag = Chain.getValue(1); 3026 } 3027 3028 std::vector<SDValue> Ops; 3029 Ops.push_back(Chain); 3030 Ops.push_back(Callee); 3031 // Add a redundant copy of the callee global which will not be legalized, as 3032 // we need direct access to the callee later. 3033 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3034 const GlobalValue *GV = GSD->getGlobal(); 3035 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3036 } else { 3037 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3038 } 3039 3040 if (IsTailCall) { 3041 // Each tail call may have to adjust the stack by a different amount, so 3042 // this information must travel along with the operation for eventual 3043 // consumption by emitEpilogue. 3044 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3045 3046 Ops.push_back(PhysReturnAddrReg); 3047 } 3048 3049 // Add argument registers to the end of the list so that they are known live 3050 // into the call. 3051 for (auto &RegToPass : RegsToPass) { 3052 Ops.push_back(DAG.getRegister(RegToPass.first, 3053 RegToPass.second.getValueType())); 3054 } 3055 3056 // Add a register mask operand representing the call-preserved registers. 3057 3058 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3059 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3060 assert(Mask && "Missing call preserved mask for calling convention"); 3061 Ops.push_back(DAG.getRegisterMask(Mask)); 3062 3063 if (InFlag.getNode()) 3064 Ops.push_back(InFlag); 3065 3066 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3067 3068 // If we're doing a tall call, use a TC_RETURN here rather than an 3069 // actual call instruction. 3070 if (IsTailCall) { 3071 MFI.setHasTailCall(); 3072 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3073 } 3074 3075 // Returns a chain and a flag for retval copy to use. 3076 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3077 Chain = Call.getValue(0); 3078 InFlag = Call.getValue(1); 3079 3080 uint64_t CalleePopBytes = NumBytes; 3081 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3082 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3083 InFlag, DL); 3084 if (!Ins.empty()) 3085 InFlag = Chain.getValue(1); 3086 3087 // Handle result values, copying them out of physregs into vregs that we 3088 // return. 3089 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3090 InVals, IsThisReturn, 3091 IsThisReturn ? OutVals[0] : SDValue()); 3092 } 3093 3094 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3095 // except for applying the wave size scale to the increment amount. 3096 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3097 SDValue Op, SelectionDAG &DAG) const { 3098 const MachineFunction &MF = DAG.getMachineFunction(); 3099 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3100 3101 SDLoc dl(Op); 3102 EVT VT = Op.getValueType(); 3103 SDValue Tmp1 = Op; 3104 SDValue Tmp2 = Op.getValue(1); 3105 SDValue Tmp3 = Op.getOperand(2); 3106 SDValue Chain = Tmp1.getOperand(0); 3107 3108 Register SPReg = Info->getStackPtrOffsetReg(); 3109 3110 // Chain the dynamic stack allocation so that it doesn't modify the stack 3111 // pointer when other instructions are using the stack. 3112 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3113 3114 SDValue Size = Tmp2.getOperand(1); 3115 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3116 Chain = SP.getValue(1); 3117 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue(); 3118 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3119 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3120 unsigned Opc = 3121 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3122 ISD::ADD : ISD::SUB; 3123 3124 SDValue ScaledSize = DAG.getNode( 3125 ISD::SHL, dl, VT, Size, 3126 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3127 3128 unsigned StackAlign = TFL->getStackAlignment(); 3129 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3130 if (Align > StackAlign) { 3131 Tmp1 = DAG.getNode( 3132 ISD::AND, dl, VT, Tmp1, 3133 DAG.getConstant(-(uint64_t)Align << ST.getWavefrontSizeLog2(), dl, VT)); 3134 } 3135 3136 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3137 Tmp2 = DAG.getCALLSEQ_END( 3138 Chain, DAG.getIntPtrConstant(0, dl, true), 3139 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3140 3141 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3142 } 3143 3144 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3145 SelectionDAG &DAG) const { 3146 // We only handle constant sizes here to allow non-entry block, static sized 3147 // allocas. A truly dynamic value is more difficult to support because we 3148 // don't know if the size value is uniform or not. If the size isn't uniform, 3149 // we would need to do a wave reduction to get the maximum size to know how 3150 // much to increment the uniform stack pointer. 3151 SDValue Size = Op.getOperand(1); 3152 if (isa<ConstantSDNode>(Size)) 3153 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3154 3155 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3156 } 3157 3158 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3159 const MachineFunction &MF) const { 3160 Register Reg = StringSwitch<Register>(RegName) 3161 .Case("m0", AMDGPU::M0) 3162 .Case("exec", AMDGPU::EXEC) 3163 .Case("exec_lo", AMDGPU::EXEC_LO) 3164 .Case("exec_hi", AMDGPU::EXEC_HI) 3165 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3166 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3167 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3168 .Default(Register()); 3169 3170 if (Reg == AMDGPU::NoRegister) { 3171 report_fatal_error(Twine("invalid register name \"" 3172 + StringRef(RegName) + "\".")); 3173 3174 } 3175 3176 if (!Subtarget->hasFlatScrRegister() && 3177 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3178 report_fatal_error(Twine("invalid register \"" 3179 + StringRef(RegName) + "\" for subtarget.")); 3180 } 3181 3182 switch (Reg) { 3183 case AMDGPU::M0: 3184 case AMDGPU::EXEC_LO: 3185 case AMDGPU::EXEC_HI: 3186 case AMDGPU::FLAT_SCR_LO: 3187 case AMDGPU::FLAT_SCR_HI: 3188 if (VT.getSizeInBits() == 32) 3189 return Reg; 3190 break; 3191 case AMDGPU::EXEC: 3192 case AMDGPU::FLAT_SCR: 3193 if (VT.getSizeInBits() == 64) 3194 return Reg; 3195 break; 3196 default: 3197 llvm_unreachable("missing register type checking"); 3198 } 3199 3200 report_fatal_error(Twine("invalid type for register \"" 3201 + StringRef(RegName) + "\".")); 3202 } 3203 3204 // If kill is not the last instruction, split the block so kill is always a 3205 // proper terminator. 3206 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3207 MachineBasicBlock *BB) const { 3208 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3209 3210 MachineBasicBlock::iterator SplitPoint(&MI); 3211 ++SplitPoint; 3212 3213 if (SplitPoint == BB->end()) { 3214 // Don't bother with a new block. 3215 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3216 return BB; 3217 } 3218 3219 MachineFunction *MF = BB->getParent(); 3220 MachineBasicBlock *SplitBB 3221 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3222 3223 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3224 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3225 3226 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3227 BB->addSuccessor(SplitBB); 3228 3229 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3230 return SplitBB; 3231 } 3232 3233 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3234 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3235 // be the first instruction in the remainder block. 3236 // 3237 /// \returns { LoopBody, Remainder } 3238 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3239 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3240 MachineFunction *MF = MBB.getParent(); 3241 MachineBasicBlock::iterator I(&MI); 3242 3243 // To insert the loop we need to split the block. Move everything after this 3244 // point to a new block, and insert a new empty block between the two. 3245 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3246 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3247 MachineFunction::iterator MBBI(MBB); 3248 ++MBBI; 3249 3250 MF->insert(MBBI, LoopBB); 3251 MF->insert(MBBI, RemainderBB); 3252 3253 LoopBB->addSuccessor(LoopBB); 3254 LoopBB->addSuccessor(RemainderBB); 3255 3256 // Move the rest of the block into a new block. 3257 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3258 3259 if (InstInLoop) { 3260 auto Next = std::next(I); 3261 3262 // Move instruction to loop body. 3263 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3264 3265 // Move the rest of the block. 3266 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3267 } else { 3268 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3269 } 3270 3271 MBB.addSuccessor(LoopBB); 3272 3273 return std::make_pair(LoopBB, RemainderBB); 3274 } 3275 3276 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3277 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3278 MachineBasicBlock *MBB = MI.getParent(); 3279 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3280 auto I = MI.getIterator(); 3281 auto E = std::next(I); 3282 3283 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3284 .addImm(0); 3285 3286 MIBundleBuilder Bundler(*MBB, I, E); 3287 finalizeBundle(*MBB, Bundler.begin()); 3288 } 3289 3290 MachineBasicBlock * 3291 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3292 MachineBasicBlock *BB) const { 3293 const DebugLoc &DL = MI.getDebugLoc(); 3294 3295 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3296 3297 MachineBasicBlock *LoopBB; 3298 MachineBasicBlock *RemainderBB; 3299 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3300 3301 // Apparently kill flags are only valid if the def is in the same block? 3302 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3303 Src->setIsKill(false); 3304 3305 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3306 3307 MachineBasicBlock::iterator I = LoopBB->end(); 3308 3309 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3310 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3311 3312 // Clear TRAP_STS.MEM_VIOL 3313 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3314 .addImm(0) 3315 .addImm(EncodedReg); 3316 3317 bundleInstWithWaitcnt(MI); 3318 3319 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3320 3321 // Load and check TRAP_STS.MEM_VIOL 3322 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3323 .addImm(EncodedReg); 3324 3325 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3326 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3327 .addReg(Reg, RegState::Kill) 3328 .addImm(0); 3329 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3330 .addMBB(LoopBB); 3331 3332 return RemainderBB; 3333 } 3334 3335 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3336 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3337 // will only do one iteration. In the worst case, this will loop 64 times. 3338 // 3339 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3340 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3341 const SIInstrInfo *TII, 3342 MachineRegisterInfo &MRI, 3343 MachineBasicBlock &OrigBB, 3344 MachineBasicBlock &LoopBB, 3345 const DebugLoc &DL, 3346 const MachineOperand &IdxReg, 3347 unsigned InitReg, 3348 unsigned ResultReg, 3349 unsigned PhiReg, 3350 unsigned InitSaveExecReg, 3351 int Offset, 3352 bool UseGPRIdxMode, 3353 bool IsIndirectSrc) { 3354 MachineFunction *MF = OrigBB.getParent(); 3355 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3356 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3357 MachineBasicBlock::iterator I = LoopBB.begin(); 3358 3359 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3360 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3361 Register NewExec = MRI.createVirtualRegister(BoolRC); 3362 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3363 Register CondReg = MRI.createVirtualRegister(BoolRC); 3364 3365 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3366 .addReg(InitReg) 3367 .addMBB(&OrigBB) 3368 .addReg(ResultReg) 3369 .addMBB(&LoopBB); 3370 3371 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3372 .addReg(InitSaveExecReg) 3373 .addMBB(&OrigBB) 3374 .addReg(NewExec) 3375 .addMBB(&LoopBB); 3376 3377 // Read the next variant <- also loop target. 3378 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3379 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3380 3381 // Compare the just read M0 value to all possible Idx values. 3382 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3383 .addReg(CurrentIdxReg) 3384 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3385 3386 // Update EXEC, save the original EXEC value to VCC. 3387 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3388 : AMDGPU::S_AND_SAVEEXEC_B64), 3389 NewExec) 3390 .addReg(CondReg, RegState::Kill); 3391 3392 MRI.setSimpleHint(NewExec, CondReg); 3393 3394 if (UseGPRIdxMode) { 3395 unsigned IdxReg; 3396 if (Offset == 0) { 3397 IdxReg = CurrentIdxReg; 3398 } else { 3399 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3400 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3401 .addReg(CurrentIdxReg, RegState::Kill) 3402 .addImm(Offset); 3403 } 3404 unsigned IdxMode = IsIndirectSrc ? 3405 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3406 MachineInstr *SetOn = 3407 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3408 .addReg(IdxReg, RegState::Kill) 3409 .addImm(IdxMode); 3410 SetOn->getOperand(3).setIsUndef(); 3411 } else { 3412 // Move index from VCC into M0 3413 if (Offset == 0) { 3414 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3415 .addReg(CurrentIdxReg, RegState::Kill); 3416 } else { 3417 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3418 .addReg(CurrentIdxReg, RegState::Kill) 3419 .addImm(Offset); 3420 } 3421 } 3422 3423 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3424 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3425 MachineInstr *InsertPt = 3426 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3427 : AMDGPU::S_XOR_B64_term), Exec) 3428 .addReg(Exec) 3429 .addReg(NewExec); 3430 3431 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3432 // s_cbranch_scc0? 3433 3434 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3435 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3436 .addMBB(&LoopBB); 3437 3438 return InsertPt->getIterator(); 3439 } 3440 3441 // This has slightly sub-optimal regalloc when the source vector is killed by 3442 // the read. The register allocator does not understand that the kill is 3443 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3444 // subregister from it, using 1 more VGPR than necessary. This was saved when 3445 // this was expanded after register allocation. 3446 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3447 MachineBasicBlock &MBB, 3448 MachineInstr &MI, 3449 unsigned InitResultReg, 3450 unsigned PhiReg, 3451 int Offset, 3452 bool UseGPRIdxMode, 3453 bool IsIndirectSrc) { 3454 MachineFunction *MF = MBB.getParent(); 3455 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3456 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3457 MachineRegisterInfo &MRI = MF->getRegInfo(); 3458 const DebugLoc &DL = MI.getDebugLoc(); 3459 MachineBasicBlock::iterator I(&MI); 3460 3461 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3462 Register DstReg = MI.getOperand(0).getReg(); 3463 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3464 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3465 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3466 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3467 3468 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3469 3470 // Save the EXEC mask 3471 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3472 .addReg(Exec); 3473 3474 MachineBasicBlock *LoopBB; 3475 MachineBasicBlock *RemainderBB; 3476 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3477 3478 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3479 3480 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3481 InitResultReg, DstReg, PhiReg, TmpExec, 3482 Offset, UseGPRIdxMode, IsIndirectSrc); 3483 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3484 MachineFunction::iterator MBBI(LoopBB); 3485 ++MBBI; 3486 MF->insert(MBBI, LandingPad); 3487 LoopBB->removeSuccessor(RemainderBB); 3488 LandingPad->addSuccessor(RemainderBB); 3489 LoopBB->addSuccessor(LandingPad); 3490 MachineBasicBlock::iterator First = LandingPad->begin(); 3491 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3492 .addReg(SaveExec); 3493 3494 return InsPt; 3495 } 3496 3497 // Returns subreg index, offset 3498 static std::pair<unsigned, int> 3499 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3500 const TargetRegisterClass *SuperRC, 3501 unsigned VecReg, 3502 int Offset) { 3503 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3504 3505 // Skip out of bounds offsets, or else we would end up using an undefined 3506 // register. 3507 if (Offset >= NumElts || Offset < 0) 3508 return std::make_pair(AMDGPU::sub0, Offset); 3509 3510 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3511 } 3512 3513 // Return true if the index is an SGPR and was set. 3514 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3515 MachineRegisterInfo &MRI, 3516 MachineInstr &MI, 3517 int Offset, 3518 bool UseGPRIdxMode, 3519 bool IsIndirectSrc) { 3520 MachineBasicBlock *MBB = MI.getParent(); 3521 const DebugLoc &DL = MI.getDebugLoc(); 3522 MachineBasicBlock::iterator I(&MI); 3523 3524 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3525 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3526 3527 assert(Idx->getReg() != AMDGPU::NoRegister); 3528 3529 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3530 return false; 3531 3532 if (UseGPRIdxMode) { 3533 unsigned IdxMode = IsIndirectSrc ? 3534 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3535 if (Offset == 0) { 3536 MachineInstr *SetOn = 3537 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3538 .add(*Idx) 3539 .addImm(IdxMode); 3540 3541 SetOn->getOperand(3).setIsUndef(); 3542 } else { 3543 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3544 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3545 .add(*Idx) 3546 .addImm(Offset); 3547 MachineInstr *SetOn = 3548 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3549 .addReg(Tmp, RegState::Kill) 3550 .addImm(IdxMode); 3551 3552 SetOn->getOperand(3).setIsUndef(); 3553 } 3554 3555 return true; 3556 } 3557 3558 if (Offset == 0) { 3559 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3560 .add(*Idx); 3561 } else { 3562 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3563 .add(*Idx) 3564 .addImm(Offset); 3565 } 3566 3567 return true; 3568 } 3569 3570 // Control flow needs to be inserted if indexing with a VGPR. 3571 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3572 MachineBasicBlock &MBB, 3573 const GCNSubtarget &ST) { 3574 const SIInstrInfo *TII = ST.getInstrInfo(); 3575 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3576 MachineFunction *MF = MBB.getParent(); 3577 MachineRegisterInfo &MRI = MF->getRegInfo(); 3578 3579 Register Dst = MI.getOperand(0).getReg(); 3580 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3581 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3582 3583 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3584 3585 unsigned SubReg; 3586 std::tie(SubReg, Offset) 3587 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3588 3589 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3590 3591 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3592 MachineBasicBlock::iterator I(&MI); 3593 const DebugLoc &DL = MI.getDebugLoc(); 3594 3595 if (UseGPRIdxMode) { 3596 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3597 // to avoid interfering with other uses, so probably requires a new 3598 // optimization pass. 3599 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3600 .addReg(SrcReg, RegState::Undef, SubReg) 3601 .addReg(SrcReg, RegState::Implicit) 3602 .addReg(AMDGPU::M0, RegState::Implicit); 3603 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3604 } else { 3605 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3606 .addReg(SrcReg, RegState::Undef, SubReg) 3607 .addReg(SrcReg, RegState::Implicit); 3608 } 3609 3610 MI.eraseFromParent(); 3611 3612 return &MBB; 3613 } 3614 3615 const DebugLoc &DL = MI.getDebugLoc(); 3616 MachineBasicBlock::iterator I(&MI); 3617 3618 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3619 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3620 3621 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3622 3623 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3624 Offset, UseGPRIdxMode, true); 3625 MachineBasicBlock *LoopBB = InsPt->getParent(); 3626 3627 if (UseGPRIdxMode) { 3628 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3629 .addReg(SrcReg, RegState::Undef, SubReg) 3630 .addReg(SrcReg, RegState::Implicit) 3631 .addReg(AMDGPU::M0, RegState::Implicit); 3632 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3633 } else { 3634 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3635 .addReg(SrcReg, RegState::Undef, SubReg) 3636 .addReg(SrcReg, RegState::Implicit); 3637 } 3638 3639 MI.eraseFromParent(); 3640 3641 return LoopBB; 3642 } 3643 3644 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3645 MachineBasicBlock &MBB, 3646 const GCNSubtarget &ST) { 3647 const SIInstrInfo *TII = ST.getInstrInfo(); 3648 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3649 MachineFunction *MF = MBB.getParent(); 3650 MachineRegisterInfo &MRI = MF->getRegInfo(); 3651 3652 Register Dst = MI.getOperand(0).getReg(); 3653 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3654 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3655 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3656 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3657 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3658 3659 // This can be an immediate, but will be folded later. 3660 assert(Val->getReg()); 3661 3662 unsigned SubReg; 3663 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3664 SrcVec->getReg(), 3665 Offset); 3666 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3667 3668 if (Idx->getReg() == AMDGPU::NoRegister) { 3669 MachineBasicBlock::iterator I(&MI); 3670 const DebugLoc &DL = MI.getDebugLoc(); 3671 3672 assert(Offset == 0); 3673 3674 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3675 .add(*SrcVec) 3676 .add(*Val) 3677 .addImm(SubReg); 3678 3679 MI.eraseFromParent(); 3680 return &MBB; 3681 } 3682 3683 const MCInstrDesc &MovRelDesc 3684 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3685 3686 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3687 MachineBasicBlock::iterator I(&MI); 3688 const DebugLoc &DL = MI.getDebugLoc(); 3689 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3690 .addReg(SrcVec->getReg()) 3691 .add(*Val) 3692 .addImm(SubReg); 3693 if (UseGPRIdxMode) 3694 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3695 3696 MI.eraseFromParent(); 3697 return &MBB; 3698 } 3699 3700 if (Val->isReg()) 3701 MRI.clearKillFlags(Val->getReg()); 3702 3703 const DebugLoc &DL = MI.getDebugLoc(); 3704 3705 Register PhiReg = MRI.createVirtualRegister(VecRC); 3706 3707 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3708 Offset, UseGPRIdxMode, false); 3709 MachineBasicBlock *LoopBB = InsPt->getParent(); 3710 3711 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3712 .addReg(PhiReg) 3713 .add(*Val) 3714 .addImm(AMDGPU::sub0); 3715 if (UseGPRIdxMode) 3716 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3717 3718 MI.eraseFromParent(); 3719 return LoopBB; 3720 } 3721 3722 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3723 MachineInstr &MI, MachineBasicBlock *BB) const { 3724 3725 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3726 MachineFunction *MF = BB->getParent(); 3727 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3728 3729 switch (MI.getOpcode()) { 3730 case AMDGPU::S_UADDO_PSEUDO: 3731 case AMDGPU::S_USUBO_PSEUDO: { 3732 const DebugLoc &DL = MI.getDebugLoc(); 3733 MachineOperand &Dest0 = MI.getOperand(0); 3734 MachineOperand &Dest1 = MI.getOperand(1); 3735 MachineOperand &Src0 = MI.getOperand(2); 3736 MachineOperand &Src1 = MI.getOperand(3); 3737 3738 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3739 ? AMDGPU::S_ADD_I32 3740 : AMDGPU::S_SUB_I32; 3741 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3742 3743 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3744 .addImm(1) 3745 .addImm(0); 3746 3747 MI.eraseFromParent(); 3748 return BB; 3749 } 3750 case AMDGPU::S_ADD_U64_PSEUDO: 3751 case AMDGPU::S_SUB_U64_PSEUDO: { 3752 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3753 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3754 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3755 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3756 const DebugLoc &DL = MI.getDebugLoc(); 3757 3758 MachineOperand &Dest = MI.getOperand(0); 3759 MachineOperand &Src0 = MI.getOperand(1); 3760 MachineOperand &Src1 = MI.getOperand(2); 3761 3762 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3763 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3764 3765 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3766 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3767 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3768 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3769 3770 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3771 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3772 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3773 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3774 3775 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3776 3777 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3778 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3779 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3780 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3781 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3782 .addReg(DestSub0) 3783 .addImm(AMDGPU::sub0) 3784 .addReg(DestSub1) 3785 .addImm(AMDGPU::sub1); 3786 MI.eraseFromParent(); 3787 return BB; 3788 } 3789 case AMDGPU::V_ADD_U64_PSEUDO: 3790 case AMDGPU::V_SUB_U64_PSEUDO: { 3791 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3792 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3793 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3794 const DebugLoc &DL = MI.getDebugLoc(); 3795 3796 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3797 3798 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3799 3800 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3801 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3802 3803 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3804 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3805 3806 MachineOperand &Dest = MI.getOperand(0); 3807 MachineOperand &Src0 = MI.getOperand(1); 3808 MachineOperand &Src1 = MI.getOperand(2); 3809 3810 const TargetRegisterClass *Src0RC = Src0.isReg() 3811 ? MRI.getRegClass(Src0.getReg()) 3812 : &AMDGPU::VReg_64RegClass; 3813 const TargetRegisterClass *Src1RC = Src1.isReg() 3814 ? MRI.getRegClass(Src1.getReg()) 3815 : &AMDGPU::VReg_64RegClass; 3816 3817 const TargetRegisterClass *Src0SubRC = 3818 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3819 const TargetRegisterClass *Src1SubRC = 3820 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3821 3822 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3823 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3824 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3825 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3826 3827 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3828 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3829 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3830 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3831 3832 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64; 3833 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3834 .addReg(CarryReg, RegState::Define) 3835 .add(SrcReg0Sub0) 3836 .add(SrcReg1Sub0) 3837 .addImm(0); // clamp bit 3838 3839 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3840 MachineInstr *HiHalf = 3841 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3842 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3843 .add(SrcReg0Sub1) 3844 .add(SrcReg1Sub1) 3845 .addReg(CarryReg, RegState::Kill) 3846 .addImm(0); // clamp bit 3847 3848 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3849 .addReg(DestSub0) 3850 .addImm(AMDGPU::sub0) 3851 .addReg(DestSub1) 3852 .addImm(AMDGPU::sub1); 3853 TII->legalizeOperands(*LoHalf); 3854 TII->legalizeOperands(*HiHalf); 3855 MI.eraseFromParent(); 3856 return BB; 3857 } 3858 case AMDGPU::S_ADD_CO_PSEUDO: 3859 case AMDGPU::S_SUB_CO_PSEUDO: { 3860 // This pseudo has a chance to be selected 3861 // only from uniform add/subcarry node. All the VGPR operands 3862 // therefore assumed to be splat vectors. 3863 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3864 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3865 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3866 MachineBasicBlock::iterator MII = MI; 3867 const DebugLoc &DL = MI.getDebugLoc(); 3868 MachineOperand &Dest = MI.getOperand(0); 3869 MachineOperand &Src0 = MI.getOperand(2); 3870 MachineOperand &Src1 = MI.getOperand(3); 3871 MachineOperand &Src2 = MI.getOperand(4); 3872 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 3873 ? AMDGPU::S_ADDC_U32 3874 : AMDGPU::S_SUBB_U32; 3875 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 3876 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3877 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 3878 .addReg(Src0.getReg()); 3879 Src0.setReg(RegOp0); 3880 } 3881 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 3882 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3883 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 3884 .addReg(Src1.getReg()); 3885 Src1.setReg(RegOp1); 3886 } 3887 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3888 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 3889 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 3890 .addReg(Src2.getReg()); 3891 Src2.setReg(RegOp2); 3892 } 3893 3894 if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) { 3895 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 3896 .addReg(Src2.getReg()) 3897 .addImm(0); 3898 } else { 3899 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 3900 .addReg(Src2.getReg()) 3901 .addImm(0); 3902 } 3903 3904 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 3905 MI.eraseFromParent(); 3906 return BB; 3907 } 3908 case AMDGPU::SI_INIT_M0: { 3909 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3910 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3911 .add(MI.getOperand(0)); 3912 MI.eraseFromParent(); 3913 return BB; 3914 } 3915 case AMDGPU::SI_INIT_EXEC: 3916 // This should be before all vector instructions. 3917 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3918 AMDGPU::EXEC) 3919 .addImm(MI.getOperand(0).getImm()); 3920 MI.eraseFromParent(); 3921 return BB; 3922 3923 case AMDGPU::SI_INIT_EXEC_LO: 3924 // This should be before all vector instructions. 3925 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3926 AMDGPU::EXEC_LO) 3927 .addImm(MI.getOperand(0).getImm()); 3928 MI.eraseFromParent(); 3929 return BB; 3930 3931 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3932 // Extract the thread count from an SGPR input and set EXEC accordingly. 3933 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3934 // 3935 // S_BFE_U32 count, input, {shift, 7} 3936 // S_BFM_B64 exec, count, 0 3937 // S_CMP_EQ_U32 count, 64 3938 // S_CMOV_B64 exec, -1 3939 MachineInstr *FirstMI = &*BB->begin(); 3940 MachineRegisterInfo &MRI = MF->getRegInfo(); 3941 Register InputReg = MI.getOperand(0).getReg(); 3942 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3943 bool Found = false; 3944 3945 // Move the COPY of the input reg to the beginning, so that we can use it. 3946 for (auto I = BB->begin(); I != &MI; I++) { 3947 if (I->getOpcode() != TargetOpcode::COPY || 3948 I->getOperand(0).getReg() != InputReg) 3949 continue; 3950 3951 if (I == FirstMI) { 3952 FirstMI = &*++BB->begin(); 3953 } else { 3954 I->removeFromParent(); 3955 BB->insert(FirstMI, &*I); 3956 } 3957 Found = true; 3958 break; 3959 } 3960 assert(Found); 3961 (void)Found; 3962 3963 // This should be before all vector instructions. 3964 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3965 bool isWave32 = getSubtarget()->isWave32(); 3966 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3967 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3968 .addReg(InputReg) 3969 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3970 BuildMI(*BB, FirstMI, DebugLoc(), 3971 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3972 Exec) 3973 .addReg(CountReg) 3974 .addImm(0); 3975 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3976 .addReg(CountReg, RegState::Kill) 3977 .addImm(getSubtarget()->getWavefrontSize()); 3978 BuildMI(*BB, FirstMI, DebugLoc(), 3979 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3980 Exec) 3981 .addImm(-1); 3982 MI.eraseFromParent(); 3983 return BB; 3984 } 3985 3986 case AMDGPU::GET_GROUPSTATICSIZE: { 3987 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 3988 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 3989 DebugLoc DL = MI.getDebugLoc(); 3990 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3991 .add(MI.getOperand(0)) 3992 .addImm(MFI->getLDSSize()); 3993 MI.eraseFromParent(); 3994 return BB; 3995 } 3996 case AMDGPU::SI_INDIRECT_SRC_V1: 3997 case AMDGPU::SI_INDIRECT_SRC_V2: 3998 case AMDGPU::SI_INDIRECT_SRC_V4: 3999 case AMDGPU::SI_INDIRECT_SRC_V8: 4000 case AMDGPU::SI_INDIRECT_SRC_V16: 4001 case AMDGPU::SI_INDIRECT_SRC_V32: 4002 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4003 case AMDGPU::SI_INDIRECT_DST_V1: 4004 case AMDGPU::SI_INDIRECT_DST_V2: 4005 case AMDGPU::SI_INDIRECT_DST_V4: 4006 case AMDGPU::SI_INDIRECT_DST_V8: 4007 case AMDGPU::SI_INDIRECT_DST_V16: 4008 case AMDGPU::SI_INDIRECT_DST_V32: 4009 return emitIndirectDst(MI, *BB, *getSubtarget()); 4010 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4011 case AMDGPU::SI_KILL_I1_PSEUDO: 4012 return splitKillBlock(MI, BB); 4013 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4014 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4015 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4016 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4017 4018 Register Dst = MI.getOperand(0).getReg(); 4019 Register Src0 = MI.getOperand(1).getReg(); 4020 Register Src1 = MI.getOperand(2).getReg(); 4021 const DebugLoc &DL = MI.getDebugLoc(); 4022 Register SrcCond = MI.getOperand(3).getReg(); 4023 4024 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4025 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4026 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4027 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4028 4029 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4030 .addReg(SrcCond); 4031 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4032 .addImm(0) 4033 .addReg(Src0, 0, AMDGPU::sub0) 4034 .addImm(0) 4035 .addReg(Src1, 0, AMDGPU::sub0) 4036 .addReg(SrcCondCopy); 4037 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4038 .addImm(0) 4039 .addReg(Src0, 0, AMDGPU::sub1) 4040 .addImm(0) 4041 .addReg(Src1, 0, AMDGPU::sub1) 4042 .addReg(SrcCondCopy); 4043 4044 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4045 .addReg(DstLo) 4046 .addImm(AMDGPU::sub0) 4047 .addReg(DstHi) 4048 .addImm(AMDGPU::sub1); 4049 MI.eraseFromParent(); 4050 return BB; 4051 } 4052 case AMDGPU::SI_BR_UNDEF: { 4053 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4054 const DebugLoc &DL = MI.getDebugLoc(); 4055 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4056 .add(MI.getOperand(0)); 4057 Br->getOperand(1).setIsUndef(true); // read undef SCC 4058 MI.eraseFromParent(); 4059 return BB; 4060 } 4061 case AMDGPU::ADJCALLSTACKUP: 4062 case AMDGPU::ADJCALLSTACKDOWN: { 4063 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4064 MachineInstrBuilder MIB(*MF, &MI); 4065 4066 // Add an implicit use of the frame offset reg to prevent the restore copy 4067 // inserted after the call from being reorderd after stack operations in the 4068 // the caller's frame. 4069 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4070 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 4071 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 4072 return BB; 4073 } 4074 case AMDGPU::SI_CALL_ISEL: { 4075 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4076 const DebugLoc &DL = MI.getDebugLoc(); 4077 4078 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4079 4080 MachineInstrBuilder MIB; 4081 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4082 4083 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4084 MIB.add(MI.getOperand(I)); 4085 4086 MIB.cloneMemRefs(MI); 4087 MI.eraseFromParent(); 4088 return BB; 4089 } 4090 case AMDGPU::V_ADD_I32_e32: 4091 case AMDGPU::V_SUB_I32_e32: 4092 case AMDGPU::V_SUBREV_I32_e32: { 4093 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4094 const DebugLoc &DL = MI.getDebugLoc(); 4095 unsigned Opc = MI.getOpcode(); 4096 4097 bool NeedClampOperand = false; 4098 if (TII->pseudoToMCOpcode(Opc) == -1) { 4099 Opc = AMDGPU::getVOPe64(Opc); 4100 NeedClampOperand = true; 4101 } 4102 4103 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4104 if (TII->isVOP3(*I)) { 4105 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4106 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4107 I.addReg(TRI->getVCC(), RegState::Define); 4108 } 4109 I.add(MI.getOperand(1)) 4110 .add(MI.getOperand(2)); 4111 if (NeedClampOperand) 4112 I.addImm(0); // clamp bit for e64 encoding 4113 4114 TII->legalizeOperands(*I); 4115 4116 MI.eraseFromParent(); 4117 return BB; 4118 } 4119 case AMDGPU::DS_GWS_INIT: 4120 case AMDGPU::DS_GWS_SEMA_V: 4121 case AMDGPU::DS_GWS_SEMA_BR: 4122 case AMDGPU::DS_GWS_SEMA_P: 4123 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4124 case AMDGPU::DS_GWS_BARRIER: 4125 // A s_waitcnt 0 is required to be the instruction immediately following. 4126 if (getSubtarget()->hasGWSAutoReplay()) { 4127 bundleInstWithWaitcnt(MI); 4128 return BB; 4129 } 4130 4131 return emitGWSMemViolTestLoop(MI, BB); 4132 case AMDGPU::S_SETREG_B32: { 4133 if (!getSubtarget()->hasDenormModeInst()) 4134 return BB; 4135 4136 // Try to optimize cases that only set the denormal mode or rounding mode. 4137 // 4138 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4139 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4140 // instead. 4141 // 4142 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4143 // allow you to have a no side effect instruction in the output of a 4144 // sideeffecting pattern. 4145 4146 // TODO: Should also emit a no side effects pseudo if only FP bits are 4147 // touched, even if not all of them or to a variable. 4148 unsigned ID, Offset, Width; 4149 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4150 if (ID != AMDGPU::Hwreg::ID_MODE) 4151 return BB; 4152 4153 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4154 const unsigned SetMask = WidthMask << Offset; 4155 unsigned SetDenormOp = 0; 4156 unsigned SetRoundOp = 0; 4157 4158 // The dedicated instructions can only set the whole denorm or round mode at 4159 // once, not a subset of bits in either. 4160 if (Width == 8 && (SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4161 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) { 4162 // If this fully sets both the round and denorm mode, emit the two 4163 // dedicated instructions for these. 4164 assert(Offset == 0); 4165 SetRoundOp = AMDGPU::S_ROUND_MODE; 4166 SetDenormOp = AMDGPU::S_DENORM_MODE; 4167 } else if (Width == 4) { 4168 if ((SetMask & AMDGPU::Hwreg::FP_ROUND_MASK) == SetMask) { 4169 SetRoundOp = AMDGPU::S_ROUND_MODE; 4170 assert(Offset == 0); 4171 } else if ((SetMask & AMDGPU::Hwreg::FP_DENORM_MASK) == SetMask) { 4172 SetDenormOp = AMDGPU::S_DENORM_MODE; 4173 assert(Offset == 4); 4174 } 4175 } 4176 4177 if (SetRoundOp || SetDenormOp) { 4178 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4179 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4180 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4181 unsigned ImmVal = Def->getOperand(1).getImm(); 4182 if (SetRoundOp) { 4183 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4184 .addImm(ImmVal & 0xf); 4185 4186 // If we also have the denorm mode, get just the denorm mode bits. 4187 ImmVal >>= 4; 4188 } 4189 4190 if (SetDenormOp) { 4191 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4192 .addImm(ImmVal & 0xf); 4193 } 4194 4195 MI.eraseFromParent(); 4196 } 4197 } 4198 4199 return BB; 4200 } 4201 default: 4202 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4203 } 4204 } 4205 4206 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4207 return isTypeLegal(VT.getScalarType()); 4208 } 4209 4210 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4211 // This currently forces unfolding various combinations of fsub into fma with 4212 // free fneg'd operands. As long as we have fast FMA (controlled by 4213 // isFMAFasterThanFMulAndFAdd), we should perform these. 4214 4215 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4216 // most of these combines appear to be cycle neutral but save on instruction 4217 // count / code size. 4218 return true; 4219 } 4220 4221 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4222 EVT VT) const { 4223 if (!VT.isVector()) { 4224 return MVT::i1; 4225 } 4226 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4227 } 4228 4229 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4230 // TODO: Should i16 be used always if legal? For now it would force VALU 4231 // shifts. 4232 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4233 } 4234 4235 // Answering this is somewhat tricky and depends on the specific device which 4236 // have different rates for fma or all f64 operations. 4237 // 4238 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4239 // regardless of which device (although the number of cycles differs between 4240 // devices), so it is always profitable for f64. 4241 // 4242 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4243 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4244 // which we can always do even without fused FP ops since it returns the same 4245 // result as the separate operations and since it is always full 4246 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4247 // however does not support denormals, so we do report fma as faster if we have 4248 // a fast fma device and require denormals. 4249 // 4250 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4251 EVT VT) const { 4252 VT = VT.getScalarType(); 4253 4254 switch (VT.getSimpleVT().SimpleTy) { 4255 case MVT::f32: { 4256 // This is as fast on some subtargets. However, we always have full rate f32 4257 // mad available which returns the same result as the separate operations 4258 // which we should prefer over fma. We can't use this if we want to support 4259 // denormals, so only report this in these cases. 4260 if (hasFP32Denormals(MF)) 4261 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4262 4263 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4264 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4265 } 4266 case MVT::f64: 4267 return true; 4268 case MVT::f16: 4269 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4270 default: 4271 break; 4272 } 4273 4274 return false; 4275 } 4276 4277 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4278 const SDNode *N) const { 4279 // TODO: Check future ftz flag 4280 // v_mad_f32/v_mac_f32 do not support denormals. 4281 EVT VT = N->getValueType(0); 4282 if (VT == MVT::f32) 4283 return !hasFP32Denormals(DAG.getMachineFunction()); 4284 if (VT == MVT::f16) { 4285 return Subtarget->hasMadF16() && 4286 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4287 } 4288 4289 return false; 4290 } 4291 4292 //===----------------------------------------------------------------------===// 4293 // Custom DAG Lowering Operations 4294 //===----------------------------------------------------------------------===// 4295 4296 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4297 // wider vector type is legal. 4298 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4299 SelectionDAG &DAG) const { 4300 unsigned Opc = Op.getOpcode(); 4301 EVT VT = Op.getValueType(); 4302 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4303 4304 SDValue Lo, Hi; 4305 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4306 4307 SDLoc SL(Op); 4308 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4309 Op->getFlags()); 4310 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4311 Op->getFlags()); 4312 4313 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4314 } 4315 4316 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4317 // wider vector type is legal. 4318 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4319 SelectionDAG &DAG) const { 4320 unsigned Opc = Op.getOpcode(); 4321 EVT VT = Op.getValueType(); 4322 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4323 4324 SDValue Lo0, Hi0; 4325 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4326 SDValue Lo1, Hi1; 4327 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4328 4329 SDLoc SL(Op); 4330 4331 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4332 Op->getFlags()); 4333 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4334 Op->getFlags()); 4335 4336 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4337 } 4338 4339 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4340 SelectionDAG &DAG) const { 4341 unsigned Opc = Op.getOpcode(); 4342 EVT VT = Op.getValueType(); 4343 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4344 4345 SDValue Lo0, Hi0; 4346 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4347 SDValue Lo1, Hi1; 4348 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4349 SDValue Lo2, Hi2; 4350 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4351 4352 SDLoc SL(Op); 4353 4354 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4355 Op->getFlags()); 4356 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4357 Op->getFlags()); 4358 4359 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4360 } 4361 4362 4363 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4364 switch (Op.getOpcode()) { 4365 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4366 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4367 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4368 case ISD::LOAD: { 4369 SDValue Result = LowerLOAD(Op, DAG); 4370 assert((!Result.getNode() || 4371 Result.getNode()->getNumValues() == 2) && 4372 "Load should return a value and a chain"); 4373 return Result; 4374 } 4375 4376 case ISD::FSIN: 4377 case ISD::FCOS: 4378 return LowerTrig(Op, DAG); 4379 case ISD::SELECT: return LowerSELECT(Op, DAG); 4380 case ISD::FDIV: return LowerFDIV(Op, DAG); 4381 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4382 case ISD::STORE: return LowerSTORE(Op, DAG); 4383 case ISD::GlobalAddress: { 4384 MachineFunction &MF = DAG.getMachineFunction(); 4385 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4386 return LowerGlobalAddress(MFI, Op, DAG); 4387 } 4388 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4389 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4390 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4391 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4392 case ISD::INSERT_SUBVECTOR: 4393 return lowerINSERT_SUBVECTOR(Op, DAG); 4394 case ISD::INSERT_VECTOR_ELT: 4395 return lowerINSERT_VECTOR_ELT(Op, DAG); 4396 case ISD::EXTRACT_VECTOR_ELT: 4397 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4398 case ISD::VECTOR_SHUFFLE: 4399 return lowerVECTOR_SHUFFLE(Op, DAG); 4400 case ISD::BUILD_VECTOR: 4401 return lowerBUILD_VECTOR(Op, DAG); 4402 case ISD::FP_ROUND: 4403 return lowerFP_ROUND(Op, DAG); 4404 case ISD::TRAP: 4405 return lowerTRAP(Op, DAG); 4406 case ISD::DEBUGTRAP: 4407 return lowerDEBUGTRAP(Op, DAG); 4408 case ISD::FABS: 4409 case ISD::FNEG: 4410 case ISD::FCANONICALIZE: 4411 case ISD::BSWAP: 4412 return splitUnaryVectorOp(Op, DAG); 4413 case ISD::FMINNUM: 4414 case ISD::FMAXNUM: 4415 return lowerFMINNUM_FMAXNUM(Op, DAG); 4416 case ISD::FMA: 4417 return splitTernaryVectorOp(Op, DAG); 4418 case ISD::SHL: 4419 case ISD::SRA: 4420 case ISD::SRL: 4421 case ISD::ADD: 4422 case ISD::SUB: 4423 case ISD::MUL: 4424 case ISD::SMIN: 4425 case ISD::SMAX: 4426 case ISD::UMIN: 4427 case ISD::UMAX: 4428 case ISD::FADD: 4429 case ISD::FMUL: 4430 case ISD::FMINNUM_IEEE: 4431 case ISD::FMAXNUM_IEEE: 4432 return splitBinaryVectorOp(Op, DAG); 4433 case ISD::DYNAMIC_STACKALLOC: 4434 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4435 } 4436 return SDValue(); 4437 } 4438 4439 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4440 const SDLoc &DL, 4441 SelectionDAG &DAG, bool Unpacked) { 4442 if (!LoadVT.isVector()) 4443 return Result; 4444 4445 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4446 // Truncate to v2i16/v4i16. 4447 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4448 4449 // Workaround legalizer not scalarizing truncate after vector op 4450 // legalization byt not creating intermediate vector trunc. 4451 SmallVector<SDValue, 4> Elts; 4452 DAG.ExtractVectorElements(Result, Elts); 4453 for (SDValue &Elt : Elts) 4454 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4455 4456 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4457 4458 // Bitcast to original type (v2f16/v4f16). 4459 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4460 } 4461 4462 // Cast back to the original packed type. 4463 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4464 } 4465 4466 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4467 MemSDNode *M, 4468 SelectionDAG &DAG, 4469 ArrayRef<SDValue> Ops, 4470 bool IsIntrinsic) const { 4471 SDLoc DL(M); 4472 4473 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4474 EVT LoadVT = M->getValueType(0); 4475 4476 EVT EquivLoadVT = LoadVT; 4477 if (Unpacked && LoadVT.isVector()) { 4478 EquivLoadVT = LoadVT.isVector() ? 4479 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4480 LoadVT.getVectorNumElements()) : LoadVT; 4481 } 4482 4483 // Change from v4f16/v2f16 to EquivLoadVT. 4484 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4485 4486 SDValue Load 4487 = DAG.getMemIntrinsicNode( 4488 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4489 VTList, Ops, M->getMemoryVT(), 4490 M->getMemOperand()); 4491 if (!Unpacked) // Just adjusted the opcode. 4492 return Load; 4493 4494 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4495 4496 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4497 } 4498 4499 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4500 SelectionDAG &DAG, 4501 ArrayRef<SDValue> Ops) const { 4502 SDLoc DL(M); 4503 EVT LoadVT = M->getValueType(0); 4504 EVT EltType = LoadVT.getScalarType(); 4505 EVT IntVT = LoadVT.changeTypeToInteger(); 4506 4507 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4508 4509 unsigned Opc = 4510 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4511 4512 if (IsD16) { 4513 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4514 } 4515 4516 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4517 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4518 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4519 4520 if (isTypeLegal(LoadVT)) { 4521 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4522 M->getMemOperand(), DAG); 4523 } 4524 4525 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4526 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4527 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4528 M->getMemOperand(), DAG); 4529 return DAG.getMergeValues( 4530 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4531 DL); 4532 } 4533 4534 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4535 SDNode *N, SelectionDAG &DAG) { 4536 EVT VT = N->getValueType(0); 4537 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4538 int CondCode = CD->getSExtValue(); 4539 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4540 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4541 return DAG.getUNDEF(VT); 4542 4543 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4544 4545 SDValue LHS = N->getOperand(1); 4546 SDValue RHS = N->getOperand(2); 4547 4548 SDLoc DL(N); 4549 4550 EVT CmpVT = LHS.getValueType(); 4551 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4552 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4553 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4554 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4555 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4556 } 4557 4558 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4559 4560 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4561 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4562 4563 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4564 DAG.getCondCode(CCOpcode)); 4565 if (VT.bitsEq(CCVT)) 4566 return SetCC; 4567 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4568 } 4569 4570 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4571 SDNode *N, SelectionDAG &DAG) { 4572 EVT VT = N->getValueType(0); 4573 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4574 4575 int CondCode = CD->getSExtValue(); 4576 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4577 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4578 return DAG.getUNDEF(VT); 4579 } 4580 4581 SDValue Src0 = N->getOperand(1); 4582 SDValue Src1 = N->getOperand(2); 4583 EVT CmpVT = Src0.getValueType(); 4584 SDLoc SL(N); 4585 4586 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4587 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4588 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4589 } 4590 4591 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4592 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4593 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4594 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4595 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4596 Src1, DAG.getCondCode(CCOpcode)); 4597 if (VT.bitsEq(CCVT)) 4598 return SetCC; 4599 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4600 } 4601 4602 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4603 SelectionDAG &DAG) { 4604 EVT VT = N->getValueType(0); 4605 SDValue Src = N->getOperand(1); 4606 SDLoc SL(N); 4607 4608 if (Src.getOpcode() == ISD::SETCC) { 4609 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4610 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4611 Src.getOperand(1), Src.getOperand(2)); 4612 } 4613 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4614 // (ballot 0) -> 0 4615 if (Arg->isNullValue()) 4616 return DAG.getConstant(0, SL, VT); 4617 4618 // (ballot 1) -> EXEC/EXEC_LO 4619 if (Arg->isOne()) { 4620 Register Exec; 4621 if (VT.getScalarSizeInBits() == 32) 4622 Exec = AMDGPU::EXEC_LO; 4623 else if (VT.getScalarSizeInBits() == 64) 4624 Exec = AMDGPU::EXEC; 4625 else 4626 return SDValue(); 4627 4628 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4629 } 4630 } 4631 4632 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4633 // ISD::SETNE) 4634 return DAG.getNode( 4635 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4636 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4637 } 4638 4639 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4640 SmallVectorImpl<SDValue> &Results, 4641 SelectionDAG &DAG) const { 4642 switch (N->getOpcode()) { 4643 case ISD::INSERT_VECTOR_ELT: { 4644 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4645 Results.push_back(Res); 4646 return; 4647 } 4648 case ISD::EXTRACT_VECTOR_ELT: { 4649 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4650 Results.push_back(Res); 4651 return; 4652 } 4653 case ISD::INTRINSIC_WO_CHAIN: { 4654 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4655 switch (IID) { 4656 case Intrinsic::amdgcn_cvt_pkrtz: { 4657 SDValue Src0 = N->getOperand(1); 4658 SDValue Src1 = N->getOperand(2); 4659 SDLoc SL(N); 4660 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4661 Src0, Src1); 4662 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4663 return; 4664 } 4665 case Intrinsic::amdgcn_cvt_pknorm_i16: 4666 case Intrinsic::amdgcn_cvt_pknorm_u16: 4667 case Intrinsic::amdgcn_cvt_pk_i16: 4668 case Intrinsic::amdgcn_cvt_pk_u16: { 4669 SDValue Src0 = N->getOperand(1); 4670 SDValue Src1 = N->getOperand(2); 4671 SDLoc SL(N); 4672 unsigned Opcode; 4673 4674 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4675 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4676 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4677 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4678 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4679 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4680 else 4681 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4682 4683 EVT VT = N->getValueType(0); 4684 if (isTypeLegal(VT)) 4685 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4686 else { 4687 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4688 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4689 } 4690 return; 4691 } 4692 } 4693 break; 4694 } 4695 case ISD::INTRINSIC_W_CHAIN: { 4696 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4697 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4698 // FIXME: Hacky 4699 Results.push_back(Res.getOperand(0)); 4700 Results.push_back(Res.getOperand(1)); 4701 } else { 4702 Results.push_back(Res); 4703 Results.push_back(Res.getValue(1)); 4704 } 4705 return; 4706 } 4707 4708 break; 4709 } 4710 case ISD::SELECT: { 4711 SDLoc SL(N); 4712 EVT VT = N->getValueType(0); 4713 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4714 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4715 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4716 4717 EVT SelectVT = NewVT; 4718 if (NewVT.bitsLT(MVT::i32)) { 4719 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4720 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4721 SelectVT = MVT::i32; 4722 } 4723 4724 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4725 N->getOperand(0), LHS, RHS); 4726 4727 if (NewVT != SelectVT) 4728 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4729 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4730 return; 4731 } 4732 case ISD::FNEG: { 4733 if (N->getValueType(0) != MVT::v2f16) 4734 break; 4735 4736 SDLoc SL(N); 4737 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4738 4739 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4740 BC, 4741 DAG.getConstant(0x80008000, SL, MVT::i32)); 4742 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4743 return; 4744 } 4745 case ISD::FABS: { 4746 if (N->getValueType(0) != MVT::v2f16) 4747 break; 4748 4749 SDLoc SL(N); 4750 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4751 4752 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4753 BC, 4754 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4755 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4756 return; 4757 } 4758 default: 4759 break; 4760 } 4761 } 4762 4763 /// Helper function for LowerBRCOND 4764 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4765 4766 SDNode *Parent = Value.getNode(); 4767 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4768 I != E; ++I) { 4769 4770 if (I.getUse().get() != Value) 4771 continue; 4772 4773 if (I->getOpcode() == Opcode) 4774 return *I; 4775 } 4776 return nullptr; 4777 } 4778 4779 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4780 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4781 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4782 case Intrinsic::amdgcn_if: 4783 return AMDGPUISD::IF; 4784 case Intrinsic::amdgcn_else: 4785 return AMDGPUISD::ELSE; 4786 case Intrinsic::amdgcn_loop: 4787 return AMDGPUISD::LOOP; 4788 case Intrinsic::amdgcn_end_cf: 4789 llvm_unreachable("should not occur"); 4790 default: 4791 return 0; 4792 } 4793 } 4794 4795 // break, if_break, else_break are all only used as inputs to loop, not 4796 // directly as branch conditions. 4797 return 0; 4798 } 4799 4800 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4801 const Triple &TT = getTargetMachine().getTargetTriple(); 4802 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4803 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4804 AMDGPU::shouldEmitConstantsToTextSection(TT); 4805 } 4806 4807 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4808 // FIXME: Either avoid relying on address space here or change the default 4809 // address space for functions to avoid the explicit check. 4810 return (GV->getValueType()->isFunctionTy() || 4811 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4812 !shouldEmitFixup(GV) && 4813 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4814 } 4815 4816 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4817 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4818 } 4819 4820 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4821 if (!GV->hasExternalLinkage()) 4822 return true; 4823 4824 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4825 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4826 } 4827 4828 /// This transforms the control flow intrinsics to get the branch destination as 4829 /// last parameter, also switches branch target with BR if the need arise 4830 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4831 SelectionDAG &DAG) const { 4832 SDLoc DL(BRCOND); 4833 4834 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4835 SDValue Target = BRCOND.getOperand(2); 4836 SDNode *BR = nullptr; 4837 SDNode *SetCC = nullptr; 4838 4839 if (Intr->getOpcode() == ISD::SETCC) { 4840 // As long as we negate the condition everything is fine 4841 SetCC = Intr; 4842 Intr = SetCC->getOperand(0).getNode(); 4843 4844 } else { 4845 // Get the target from BR if we don't negate the condition 4846 BR = findUser(BRCOND, ISD::BR); 4847 assert(BR && "brcond missing unconditional branch user"); 4848 Target = BR->getOperand(1); 4849 } 4850 4851 unsigned CFNode = isCFIntrinsic(Intr); 4852 if (CFNode == 0) { 4853 // This is a uniform branch so we don't need to legalize. 4854 return BRCOND; 4855 } 4856 4857 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4858 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4859 4860 assert(!SetCC || 4861 (SetCC->getConstantOperandVal(1) == 1 && 4862 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4863 ISD::SETNE)); 4864 4865 // operands of the new intrinsic call 4866 SmallVector<SDValue, 4> Ops; 4867 if (HaveChain) 4868 Ops.push_back(BRCOND.getOperand(0)); 4869 4870 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4871 Ops.push_back(Target); 4872 4873 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4874 4875 // build the new intrinsic call 4876 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4877 4878 if (!HaveChain) { 4879 SDValue Ops[] = { 4880 SDValue(Result, 0), 4881 BRCOND.getOperand(0) 4882 }; 4883 4884 Result = DAG.getMergeValues(Ops, DL).getNode(); 4885 } 4886 4887 if (BR) { 4888 // Give the branch instruction our target 4889 SDValue Ops[] = { 4890 BR->getOperand(0), 4891 BRCOND.getOperand(2) 4892 }; 4893 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4894 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4895 } 4896 4897 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4898 4899 // Copy the intrinsic results to registers 4900 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4901 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4902 if (!CopyToReg) 4903 continue; 4904 4905 Chain = DAG.getCopyToReg( 4906 Chain, DL, 4907 CopyToReg->getOperand(1), 4908 SDValue(Result, i - 1), 4909 SDValue()); 4910 4911 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4912 } 4913 4914 // Remove the old intrinsic from the chain 4915 DAG.ReplaceAllUsesOfValueWith( 4916 SDValue(Intr, Intr->getNumValues() - 1), 4917 Intr->getOperand(0)); 4918 4919 return Chain; 4920 } 4921 4922 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4923 SelectionDAG &DAG) const { 4924 MVT VT = Op.getSimpleValueType(); 4925 SDLoc DL(Op); 4926 // Checking the depth 4927 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4928 return DAG.getConstant(0, DL, VT); 4929 4930 MachineFunction &MF = DAG.getMachineFunction(); 4931 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4932 // Check for kernel and shader functions 4933 if (Info->isEntryFunction()) 4934 return DAG.getConstant(0, DL, VT); 4935 4936 MachineFrameInfo &MFI = MF.getFrameInfo(); 4937 // There is a call to @llvm.returnaddress in this function 4938 MFI.setReturnAddressIsTaken(true); 4939 4940 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4941 // Get the return address reg and mark it as an implicit live-in 4942 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4943 4944 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4945 } 4946 4947 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 4948 SDValue Op, 4949 const SDLoc &DL, 4950 EVT VT) const { 4951 return Op.getValueType().bitsLE(VT) ? 4952 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4953 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 4954 DAG.getTargetConstant(0, DL, MVT::i32)); 4955 } 4956 4957 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4958 assert(Op.getValueType() == MVT::f16 && 4959 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4960 4961 SDValue Src = Op.getOperand(0); 4962 EVT SrcVT = Src.getValueType(); 4963 if (SrcVT != MVT::f64) 4964 return Op; 4965 4966 SDLoc DL(Op); 4967 4968 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4969 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4970 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4971 } 4972 4973 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4974 SelectionDAG &DAG) const { 4975 EVT VT = Op.getValueType(); 4976 const MachineFunction &MF = DAG.getMachineFunction(); 4977 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4978 bool IsIEEEMode = Info->getMode().IEEE; 4979 4980 // FIXME: Assert during selection that this is only selected for 4981 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4982 // mode functions, but this happens to be OK since it's only done in cases 4983 // where there is known no sNaN. 4984 if (IsIEEEMode) 4985 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 4986 4987 if (VT == MVT::v4f16) 4988 return splitBinaryVectorOp(Op, DAG); 4989 return Op; 4990 } 4991 4992 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4993 SDLoc SL(Op); 4994 SDValue Chain = Op.getOperand(0); 4995 4996 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4997 !Subtarget->isTrapHandlerEnabled()) 4998 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4999 5000 MachineFunction &MF = DAG.getMachineFunction(); 5001 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5002 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 5003 assert(UserSGPR != AMDGPU::NoRegister); 5004 SDValue QueuePtr = CreateLiveInRegister( 5005 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5006 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5007 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5008 QueuePtr, SDValue()); 5009 SDValue Ops[] = { 5010 ToReg, 5011 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 5012 SGPR01, 5013 ToReg.getValue(1) 5014 }; 5015 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5016 } 5017 5018 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5019 SDLoc SL(Op); 5020 SDValue Chain = Op.getOperand(0); 5021 MachineFunction &MF = DAG.getMachineFunction(); 5022 5023 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5024 !Subtarget->isTrapHandlerEnabled()) { 5025 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5026 "debugtrap handler not supported", 5027 Op.getDebugLoc(), 5028 DS_Warning); 5029 LLVMContext &Ctx = MF.getFunction().getContext(); 5030 Ctx.diagnose(NoTrap); 5031 return Chain; 5032 } 5033 5034 SDValue Ops[] = { 5035 Chain, 5036 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 5037 }; 5038 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5039 } 5040 5041 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5042 SelectionDAG &DAG) const { 5043 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5044 if (Subtarget->hasApertureRegs()) { 5045 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5046 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5047 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5048 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5049 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5050 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5051 unsigned Encoding = 5052 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5053 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5054 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5055 5056 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5057 SDValue ApertureReg = SDValue( 5058 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5059 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5060 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5061 } 5062 5063 MachineFunction &MF = DAG.getMachineFunction(); 5064 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5065 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5066 assert(UserSGPR != AMDGPU::NoRegister); 5067 5068 SDValue QueuePtr = CreateLiveInRegister( 5069 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5070 5071 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5072 // private_segment_aperture_base_hi. 5073 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5074 5075 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 5076 5077 // TODO: Use custom target PseudoSourceValue. 5078 // TODO: We should use the value from the IR intrinsic call, but it might not 5079 // be available and how do we get it? 5080 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5081 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5082 MinAlign(64, StructOffset), 5083 MachineMemOperand::MODereferenceable | 5084 MachineMemOperand::MOInvariant); 5085 } 5086 5087 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5088 SelectionDAG &DAG) const { 5089 SDLoc SL(Op); 5090 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5091 5092 SDValue Src = ASC->getOperand(0); 5093 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5094 5095 const AMDGPUTargetMachine &TM = 5096 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5097 5098 // flat -> local/private 5099 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5100 unsigned DestAS = ASC->getDestAddressSpace(); 5101 5102 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5103 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5104 unsigned NullVal = TM.getNullPointerValue(DestAS); 5105 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5106 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5107 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5108 5109 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5110 NonNull, Ptr, SegmentNullPtr); 5111 } 5112 } 5113 5114 // local/private -> flat 5115 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5116 unsigned SrcAS = ASC->getSrcAddressSpace(); 5117 5118 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5119 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5120 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5121 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5122 5123 SDValue NonNull 5124 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5125 5126 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5127 SDValue CvtPtr 5128 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5129 5130 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5131 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5132 FlatNullPtr); 5133 } 5134 } 5135 5136 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5137 Src.getValueType() == MVT::i64) 5138 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5139 5140 // global <-> flat are no-ops and never emitted. 5141 5142 const MachineFunction &MF = DAG.getMachineFunction(); 5143 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5144 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5145 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5146 5147 return DAG.getUNDEF(ASC->getValueType(0)); 5148 } 5149 5150 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5151 // the small vector and inserting them into the big vector. That is better than 5152 // the default expansion of doing it via a stack slot. Even though the use of 5153 // the stack slot would be optimized away afterwards, the stack slot itself 5154 // remains. 5155 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5156 SelectionDAG &DAG) const { 5157 SDValue Vec = Op.getOperand(0); 5158 SDValue Ins = Op.getOperand(1); 5159 SDValue Idx = Op.getOperand(2); 5160 EVT VecVT = Vec.getValueType(); 5161 EVT InsVT = Ins.getValueType(); 5162 EVT EltVT = VecVT.getVectorElementType(); 5163 unsigned InsNumElts = InsVT.getVectorNumElements(); 5164 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5165 SDLoc SL(Op); 5166 5167 for (unsigned I = 0; I != InsNumElts; ++I) { 5168 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5169 DAG.getConstant(I, SL, MVT::i32)); 5170 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5171 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5172 } 5173 return Vec; 5174 } 5175 5176 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5177 SelectionDAG &DAG) const { 5178 SDValue Vec = Op.getOperand(0); 5179 SDValue InsVal = Op.getOperand(1); 5180 SDValue Idx = Op.getOperand(2); 5181 EVT VecVT = Vec.getValueType(); 5182 EVT EltVT = VecVT.getVectorElementType(); 5183 unsigned VecSize = VecVT.getSizeInBits(); 5184 unsigned EltSize = EltVT.getSizeInBits(); 5185 5186 5187 assert(VecSize <= 64); 5188 5189 unsigned NumElts = VecVT.getVectorNumElements(); 5190 SDLoc SL(Op); 5191 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5192 5193 if (NumElts == 4 && EltSize == 16 && KIdx) { 5194 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5195 5196 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5197 DAG.getConstant(0, SL, MVT::i32)); 5198 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5199 DAG.getConstant(1, SL, MVT::i32)); 5200 5201 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5202 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5203 5204 unsigned Idx = KIdx->getZExtValue(); 5205 bool InsertLo = Idx < 2; 5206 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5207 InsertLo ? LoVec : HiVec, 5208 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5209 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5210 5211 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5212 5213 SDValue Concat = InsertLo ? 5214 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5215 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5216 5217 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5218 } 5219 5220 if (isa<ConstantSDNode>(Idx)) 5221 return SDValue(); 5222 5223 MVT IntVT = MVT::getIntegerVT(VecSize); 5224 5225 // Avoid stack access for dynamic indexing. 5226 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5227 5228 // Create a congruent vector with the target value in each element so that 5229 // the required element can be masked and ORed into the target vector. 5230 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5231 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5232 5233 assert(isPowerOf2_32(EltSize)); 5234 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5235 5236 // Convert vector index to bit-index. 5237 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5238 5239 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5240 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5241 DAG.getConstant(0xffff, SL, IntVT), 5242 ScaledIdx); 5243 5244 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5245 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5246 DAG.getNOT(SL, BFM, IntVT), BCVec); 5247 5248 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5249 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5250 } 5251 5252 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5253 SelectionDAG &DAG) const { 5254 SDLoc SL(Op); 5255 5256 EVT ResultVT = Op.getValueType(); 5257 SDValue Vec = Op.getOperand(0); 5258 SDValue Idx = Op.getOperand(1); 5259 EVT VecVT = Vec.getValueType(); 5260 unsigned VecSize = VecVT.getSizeInBits(); 5261 EVT EltVT = VecVT.getVectorElementType(); 5262 assert(VecSize <= 64); 5263 5264 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5265 5266 // Make sure we do any optimizations that will make it easier to fold 5267 // source modifiers before obscuring it with bit operations. 5268 5269 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5270 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5271 return Combined; 5272 5273 unsigned EltSize = EltVT.getSizeInBits(); 5274 assert(isPowerOf2_32(EltSize)); 5275 5276 MVT IntVT = MVT::getIntegerVT(VecSize); 5277 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5278 5279 // Convert vector index to bit-index (* EltSize) 5280 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5281 5282 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5283 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5284 5285 if (ResultVT == MVT::f16) { 5286 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5287 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5288 } 5289 5290 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5291 } 5292 5293 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5294 assert(Elt % 2 == 0); 5295 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5296 } 5297 5298 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5299 SelectionDAG &DAG) const { 5300 SDLoc SL(Op); 5301 EVT ResultVT = Op.getValueType(); 5302 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5303 5304 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5305 EVT EltVT = PackVT.getVectorElementType(); 5306 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5307 5308 // vector_shuffle <0,1,6,7> lhs, rhs 5309 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5310 // 5311 // vector_shuffle <6,7,2,3> lhs, rhs 5312 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5313 // 5314 // vector_shuffle <6,7,0,1> lhs, rhs 5315 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5316 5317 // Avoid scalarizing when both halves are reading from consecutive elements. 5318 SmallVector<SDValue, 4> Pieces; 5319 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5320 if (elementPairIsContiguous(SVN->getMask(), I)) { 5321 const int Idx = SVN->getMaskElt(I); 5322 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5323 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5324 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5325 PackVT, SVN->getOperand(VecIdx), 5326 DAG.getConstant(EltIdx, SL, MVT::i32)); 5327 Pieces.push_back(SubVec); 5328 } else { 5329 const int Idx0 = SVN->getMaskElt(I); 5330 const int Idx1 = SVN->getMaskElt(I + 1); 5331 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5332 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5333 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5334 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5335 5336 SDValue Vec0 = SVN->getOperand(VecIdx0); 5337 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5338 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5339 5340 SDValue Vec1 = SVN->getOperand(VecIdx1); 5341 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5342 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5343 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5344 } 5345 } 5346 5347 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5348 } 5349 5350 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5351 SelectionDAG &DAG) const { 5352 SDLoc SL(Op); 5353 EVT VT = Op.getValueType(); 5354 5355 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5356 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5357 5358 // Turn into pair of packed build_vectors. 5359 // TODO: Special case for constants that can be materialized with s_mov_b64. 5360 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5361 { Op.getOperand(0), Op.getOperand(1) }); 5362 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5363 { Op.getOperand(2), Op.getOperand(3) }); 5364 5365 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5366 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5367 5368 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5369 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5370 } 5371 5372 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5373 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5374 5375 SDValue Lo = Op.getOperand(0); 5376 SDValue Hi = Op.getOperand(1); 5377 5378 // Avoid adding defined bits with the zero_extend. 5379 if (Hi.isUndef()) { 5380 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5381 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5382 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5383 } 5384 5385 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5386 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5387 5388 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5389 DAG.getConstant(16, SL, MVT::i32)); 5390 if (Lo.isUndef()) 5391 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5392 5393 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5394 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5395 5396 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5397 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5398 } 5399 5400 bool 5401 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5402 // We can fold offsets for anything that doesn't require a GOT relocation. 5403 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5404 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5405 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5406 !shouldEmitGOTReloc(GA->getGlobal()); 5407 } 5408 5409 static SDValue 5410 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5411 const SDLoc &DL, unsigned Offset, EVT PtrVT, 5412 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5413 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5414 // lowered to the following code sequence: 5415 // 5416 // For constant address space: 5417 // s_getpc_b64 s[0:1] 5418 // s_add_u32 s0, s0, $symbol 5419 // s_addc_u32 s1, s1, 0 5420 // 5421 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5422 // a fixup or relocation is emitted to replace $symbol with a literal 5423 // constant, which is a pc-relative offset from the encoding of the $symbol 5424 // operand to the global variable. 5425 // 5426 // For global address space: 5427 // s_getpc_b64 s[0:1] 5428 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5429 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5430 // 5431 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5432 // fixups or relocations are emitted to replace $symbol@*@lo and 5433 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5434 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5435 // operand to the global variable. 5436 // 5437 // What we want here is an offset from the value returned by s_getpc 5438 // (which is the address of the s_add_u32 instruction) to the global 5439 // variable, but since the encoding of $symbol starts 4 bytes after the start 5440 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5441 // small. This requires us to add 4 to the global variable offset in order to 5442 // compute the correct address. 5443 SDValue PtrLo = 5444 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5445 SDValue PtrHi; 5446 if (GAFlags == SIInstrInfo::MO_NONE) { 5447 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5448 } else { 5449 PtrHi = 5450 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5451 } 5452 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5453 } 5454 5455 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5456 SDValue Op, 5457 SelectionDAG &DAG) const { 5458 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5459 const GlobalValue *GV = GSD->getGlobal(); 5460 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5461 shouldUseLDSConstAddress(GV)) || 5462 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5463 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5464 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5465 5466 SDLoc DL(GSD); 5467 EVT PtrVT = Op.getValueType(); 5468 5469 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5470 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5471 SIInstrInfo::MO_ABS32_LO); 5472 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5473 } 5474 5475 if (shouldEmitFixup(GV)) 5476 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5477 else if (shouldEmitPCReloc(GV)) 5478 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5479 SIInstrInfo::MO_REL32); 5480 5481 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5482 SIInstrInfo::MO_GOTPCREL32); 5483 5484 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5485 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5486 const DataLayout &DataLayout = DAG.getDataLayout(); 5487 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 5488 MachinePointerInfo PtrInfo 5489 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5490 5491 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 5492 MachineMemOperand::MODereferenceable | 5493 MachineMemOperand::MOInvariant); 5494 } 5495 5496 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5497 const SDLoc &DL, SDValue V) const { 5498 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5499 // the destination register. 5500 // 5501 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5502 // so we will end up with redundant moves to m0. 5503 // 5504 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5505 5506 // A Null SDValue creates a glue result. 5507 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5508 V, Chain); 5509 return SDValue(M0, 0); 5510 } 5511 5512 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5513 SDValue Op, 5514 MVT VT, 5515 unsigned Offset) const { 5516 SDLoc SL(Op); 5517 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 5518 DAG.getEntryNode(), Offset, 4, false); 5519 // The local size values will have the hi 16-bits as zero. 5520 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5521 DAG.getValueType(VT)); 5522 } 5523 5524 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5525 EVT VT) { 5526 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5527 "non-hsa intrinsic with hsa target", 5528 DL.getDebugLoc()); 5529 DAG.getContext()->diagnose(BadIntrin); 5530 return DAG.getUNDEF(VT); 5531 } 5532 5533 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5534 EVT VT) { 5535 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5536 "intrinsic not supported on subtarget", 5537 DL.getDebugLoc()); 5538 DAG.getContext()->diagnose(BadIntrin); 5539 return DAG.getUNDEF(VT); 5540 } 5541 5542 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5543 ArrayRef<SDValue> Elts) { 5544 assert(!Elts.empty()); 5545 MVT Type; 5546 unsigned NumElts; 5547 5548 if (Elts.size() == 1) { 5549 Type = MVT::f32; 5550 NumElts = 1; 5551 } else if (Elts.size() == 2) { 5552 Type = MVT::v2f32; 5553 NumElts = 2; 5554 } else if (Elts.size() == 3) { 5555 Type = MVT::v3f32; 5556 NumElts = 3; 5557 } else if (Elts.size() <= 4) { 5558 Type = MVT::v4f32; 5559 NumElts = 4; 5560 } else if (Elts.size() <= 8) { 5561 Type = MVT::v8f32; 5562 NumElts = 8; 5563 } else { 5564 assert(Elts.size() <= 16); 5565 Type = MVT::v16f32; 5566 NumElts = 16; 5567 } 5568 5569 SmallVector<SDValue, 16> VecElts(NumElts); 5570 for (unsigned i = 0; i < Elts.size(); ++i) { 5571 SDValue Elt = Elts[i]; 5572 if (Elt.getValueType() != MVT::f32) 5573 Elt = DAG.getBitcast(MVT::f32, Elt); 5574 VecElts[i] = Elt; 5575 } 5576 for (unsigned i = Elts.size(); i < NumElts; ++i) 5577 VecElts[i] = DAG.getUNDEF(MVT::f32); 5578 5579 if (NumElts == 1) 5580 return VecElts[0]; 5581 return DAG.getBuildVector(Type, DL, VecElts); 5582 } 5583 5584 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5585 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5586 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5587 5588 uint64_t Value = CachePolicyConst->getZExtValue(); 5589 SDLoc DL(CachePolicy); 5590 if (GLC) { 5591 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5592 Value &= ~(uint64_t)0x1; 5593 } 5594 if (SLC) { 5595 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5596 Value &= ~(uint64_t)0x2; 5597 } 5598 if (DLC) { 5599 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5600 Value &= ~(uint64_t)0x4; 5601 } 5602 5603 return Value == 0; 5604 } 5605 5606 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5607 SDValue Src, int ExtraElts) { 5608 EVT SrcVT = Src.getValueType(); 5609 5610 SmallVector<SDValue, 8> Elts; 5611 5612 if (SrcVT.isVector()) 5613 DAG.ExtractVectorElements(Src, Elts); 5614 else 5615 Elts.push_back(Src); 5616 5617 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5618 while (ExtraElts--) 5619 Elts.push_back(Undef); 5620 5621 return DAG.getBuildVector(CastVT, DL, Elts); 5622 } 5623 5624 // Re-construct the required return value for a image load intrinsic. 5625 // This is more complicated due to the optional use TexFailCtrl which means the required 5626 // return type is an aggregate 5627 static SDValue constructRetValue(SelectionDAG &DAG, 5628 MachineSDNode *Result, 5629 ArrayRef<EVT> ResultTypes, 5630 bool IsTexFail, bool Unpacked, bool IsD16, 5631 int DMaskPop, int NumVDataDwords, 5632 const SDLoc &DL, LLVMContext &Context) { 5633 // Determine the required return type. This is the same regardless of IsTexFail flag 5634 EVT ReqRetVT = ResultTypes[0]; 5635 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5636 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5637 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5638 5639 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5640 DMaskPop : (DMaskPop + 1) / 2; 5641 5642 MVT DataDwordVT = NumDataDwords == 1 ? 5643 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5644 5645 MVT MaskPopVT = MaskPopDwords == 1 ? 5646 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5647 5648 SDValue Data(Result, 0); 5649 SDValue TexFail; 5650 5651 if (IsTexFail) { 5652 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5653 if (MaskPopVT.isVector()) { 5654 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5655 SDValue(Result, 0), ZeroIdx); 5656 } else { 5657 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5658 SDValue(Result, 0), ZeroIdx); 5659 } 5660 5661 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5662 SDValue(Result, 0), 5663 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5664 } 5665 5666 if (DataDwordVT.isVector()) 5667 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5668 NumDataDwords - MaskPopDwords); 5669 5670 if (IsD16) 5671 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5672 5673 if (!ReqRetVT.isVector()) 5674 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5675 5676 Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data); 5677 5678 if (TexFail) 5679 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5680 5681 if (Result->getNumValues() == 1) 5682 return Data; 5683 5684 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5685 } 5686 5687 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5688 SDValue *LWE, bool &IsTexFail) { 5689 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5690 5691 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5692 if (Value) { 5693 IsTexFail = true; 5694 } 5695 5696 SDLoc DL(TexFailCtrlConst); 5697 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5698 Value &= ~(uint64_t)0x1; 5699 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5700 Value &= ~(uint64_t)0x2; 5701 5702 return Value == 0; 5703 } 5704 5705 SDValue SITargetLowering::lowerImage(SDValue Op, 5706 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5707 SelectionDAG &DAG) const { 5708 SDLoc DL(Op); 5709 MachineFunction &MF = DAG.getMachineFunction(); 5710 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5711 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5712 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5713 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5714 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5715 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5716 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5717 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5718 unsigned IntrOpcode = Intr->BaseOpcode; 5719 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5720 5721 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5722 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5723 bool IsD16 = false; 5724 bool IsA16 = false; 5725 SDValue VData; 5726 int NumVDataDwords; 5727 bool AdjustRetType = false; 5728 5729 unsigned AddrIdx; // Index of first address argument 5730 unsigned DMask; 5731 unsigned DMaskLanes = 0; 5732 5733 if (BaseOpcode->Atomic) { 5734 VData = Op.getOperand(2); 5735 5736 bool Is64Bit = VData.getValueType() == MVT::i64; 5737 if (BaseOpcode->AtomicX2) { 5738 SDValue VData2 = Op.getOperand(3); 5739 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5740 {VData, VData2}); 5741 if (Is64Bit) 5742 VData = DAG.getBitcast(MVT::v4i32, VData); 5743 5744 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5745 DMask = Is64Bit ? 0xf : 0x3; 5746 NumVDataDwords = Is64Bit ? 4 : 2; 5747 AddrIdx = 4; 5748 } else { 5749 DMask = Is64Bit ? 0x3 : 0x1; 5750 NumVDataDwords = Is64Bit ? 2 : 1; 5751 AddrIdx = 3; 5752 } 5753 } else { 5754 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5755 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5756 DMask = DMaskConst->getZExtValue(); 5757 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5758 5759 if (BaseOpcode->Store) { 5760 VData = Op.getOperand(2); 5761 5762 MVT StoreVT = VData.getSimpleValueType(); 5763 if (StoreVT.getScalarType() == MVT::f16) { 5764 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5765 return Op; // D16 is unsupported for this instruction 5766 5767 IsD16 = true; 5768 VData = handleD16VData(VData, DAG); 5769 } 5770 5771 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5772 } else { 5773 // Work out the num dwords based on the dmask popcount and underlying type 5774 // and whether packing is supported. 5775 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5776 if (LoadVT.getScalarType() == MVT::f16) { 5777 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5778 return Op; // D16 is unsupported for this instruction 5779 5780 IsD16 = true; 5781 } 5782 5783 // Confirm that the return type is large enough for the dmask specified 5784 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5785 (!LoadVT.isVector() && DMaskLanes > 1)) 5786 return Op; 5787 5788 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5789 NumVDataDwords = (DMaskLanes + 1) / 2; 5790 else 5791 NumVDataDwords = DMaskLanes; 5792 5793 AdjustRetType = true; 5794 } 5795 5796 AddrIdx = DMaskIdx + 1; 5797 } 5798 5799 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5800 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5801 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5802 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5803 NumCoords + NumLCM; 5804 unsigned NumMIVAddrs = NumVAddrs; 5805 5806 SmallVector<SDValue, 4> VAddrs; 5807 5808 // Optimize _L to _LZ when _L is zero 5809 if (LZMappingInfo) { 5810 if (auto ConstantLod = 5811 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5812 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5813 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5814 NumMIVAddrs--; // remove 'lod' 5815 } 5816 } 5817 } 5818 5819 // Optimize _mip away, when 'lod' is zero 5820 if (MIPMappingInfo) { 5821 if (auto ConstantLod = 5822 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5823 if (ConstantLod->isNullValue()) { 5824 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5825 NumMIVAddrs--; // remove 'lod' 5826 } 5827 } 5828 } 5829 5830 // Check for 16 bit addresses and pack if true. 5831 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5832 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5833 const MVT VAddrScalarVT = VAddrVT.getScalarType(); 5834 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) { 5835 // Illegal to use a16 images 5836 if (!ST->hasFeature(AMDGPU::FeatureR128A16) && !ST->hasFeature(AMDGPU::FeatureGFX10A16)) 5837 return Op; 5838 5839 IsA16 = true; 5840 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5841 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) { 5842 SDValue AddrLo; 5843 // Push back extra arguments. 5844 if (i < DimIdx) { 5845 AddrLo = Op.getOperand(i); 5846 } else { 5847 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, 5848 // in 1D, derivatives dx/dh and dx/dv are packed with undef. 5849 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) || 5850 ((NumGradients / 2) % 2 == 1 && 5851 (i == DimIdx + (NumGradients / 2) - 1 || 5852 i == DimIdx + NumGradients - 1))) { 5853 AddrLo = Op.getOperand(i); 5854 if (AddrLo.getValueType() != MVT::i16) 5855 AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i)); 5856 AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo); 5857 } else { 5858 AddrLo = DAG.getBuildVector(VectorVT, DL, 5859 {Op.getOperand(i), Op.getOperand(i + 1)}); 5860 i++; 5861 } 5862 AddrLo = DAG.getBitcast(MVT::f32, AddrLo); 5863 } 5864 VAddrs.push_back(AddrLo); 5865 } 5866 } else { 5867 for (unsigned i = 0; i < NumMIVAddrs; ++i) 5868 VAddrs.push_back(Op.getOperand(AddrIdx + i)); 5869 } 5870 5871 // If the register allocator cannot place the address registers contiguously 5872 // without introducing moves, then using the non-sequential address encoding 5873 // is always preferable, since it saves VALU instructions and is usually a 5874 // wash in terms of code size or even better. 5875 // 5876 // However, we currently have no way of hinting to the register allocator that 5877 // MIMG addresses should be placed contiguously when it is possible to do so, 5878 // so force non-NSA for the common 2-address case as a heuristic. 5879 // 5880 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5881 // allocation when possible. 5882 bool UseNSA = 5883 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5884 SDValue VAddr; 5885 if (!UseNSA) 5886 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5887 5888 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5889 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5890 unsigned CtrlIdx; // Index of texfailctrl argument 5891 SDValue Unorm; 5892 if (!BaseOpcode->Sampler) { 5893 Unorm = True; 5894 CtrlIdx = AddrIdx + NumVAddrs + 1; 5895 } else { 5896 auto UnormConst = 5897 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 5898 5899 Unorm = UnormConst->getZExtValue() ? True : False; 5900 CtrlIdx = AddrIdx + NumVAddrs + 3; 5901 } 5902 5903 SDValue TFE; 5904 SDValue LWE; 5905 SDValue TexFail = Op.getOperand(CtrlIdx); 5906 bool IsTexFail = false; 5907 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 5908 return Op; 5909 5910 if (IsTexFail) { 5911 if (!DMaskLanes) { 5912 // Expecting to get an error flag since TFC is on - and dmask is 0 5913 // Force dmask to be at least 1 otherwise the instruction will fail 5914 DMask = 0x1; 5915 DMaskLanes = 1; 5916 NumVDataDwords = 1; 5917 } 5918 NumVDataDwords += 1; 5919 AdjustRetType = true; 5920 } 5921 5922 // Has something earlier tagged that the return type needs adjusting 5923 // This happens if the instruction is a load or has set TexFailCtrl flags 5924 if (AdjustRetType) { 5925 // NumVDataDwords reflects the true number of dwords required in the return type 5926 if (DMaskLanes == 0 && !BaseOpcode->Store) { 5927 // This is a no-op load. This can be eliminated 5928 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 5929 if (isa<MemSDNode>(Op)) 5930 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 5931 return Undef; 5932 } 5933 5934 EVT NewVT = NumVDataDwords > 1 ? 5935 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 5936 : MVT::i32; 5937 5938 ResultTypes[0] = NewVT; 5939 if (ResultTypes.size() == 3) { 5940 // Original result was aggregate type used for TexFailCtrl results 5941 // The actual instruction returns as a vector type which has now been 5942 // created. Remove the aggregate result. 5943 ResultTypes.erase(&ResultTypes[1]); 5944 } 5945 } 5946 5947 SDValue GLC; 5948 SDValue SLC; 5949 SDValue DLC; 5950 if (BaseOpcode->Atomic) { 5951 GLC = True; // TODO no-return optimization 5952 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 5953 IsGFX10 ? &DLC : nullptr)) 5954 return Op; 5955 } else { 5956 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 5957 IsGFX10 ? &DLC : nullptr)) 5958 return Op; 5959 } 5960 5961 SmallVector<SDValue, 26> Ops; 5962 if (BaseOpcode->Store || BaseOpcode->Atomic) 5963 Ops.push_back(VData); // vdata 5964 if (UseNSA) { 5965 for (const SDValue &Addr : VAddrs) 5966 Ops.push_back(Addr); 5967 } else { 5968 Ops.push_back(VAddr); 5969 } 5970 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 5971 if (BaseOpcode->Sampler) 5972 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 5973 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 5974 if (IsGFX10) 5975 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 5976 Ops.push_back(Unorm); 5977 if (IsGFX10) 5978 Ops.push_back(DLC); 5979 Ops.push_back(GLC); 5980 Ops.push_back(SLC); 5981 Ops.push_back(IsA16 && // r128, a16 for gfx9 5982 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 5983 if (IsGFX10) 5984 Ops.push_back(IsA16 ? True : False); 5985 Ops.push_back(TFE); 5986 Ops.push_back(LWE); 5987 if (!IsGFX10) 5988 Ops.push_back(DimInfo->DA ? True : False); 5989 if (BaseOpcode->HasD16) 5990 Ops.push_back(IsD16 ? True : False); 5991 if (isa<MemSDNode>(Op)) 5992 Ops.push_back(Op.getOperand(0)); // chain 5993 5994 int NumVAddrDwords = 5995 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 5996 int Opcode = -1; 5997 5998 if (IsGFX10) { 5999 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6000 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6001 : AMDGPU::MIMGEncGfx10Default, 6002 NumVDataDwords, NumVAddrDwords); 6003 } else { 6004 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6005 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6006 NumVDataDwords, NumVAddrDwords); 6007 if (Opcode == -1) 6008 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6009 NumVDataDwords, NumVAddrDwords); 6010 } 6011 assert(Opcode != -1); 6012 6013 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6014 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6015 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6016 DAG.setNodeMemRefs(NewNode, {MemRef}); 6017 } 6018 6019 if (BaseOpcode->AtomicX2) { 6020 SmallVector<SDValue, 1> Elt; 6021 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6022 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6023 } else if (!BaseOpcode->Store) { 6024 return constructRetValue(DAG, NewNode, 6025 OrigResultTypes, IsTexFail, 6026 Subtarget->hasUnpackedD16VMem(), IsD16, 6027 DMaskLanes, NumVDataDwords, DL, 6028 *DAG.getContext()); 6029 } 6030 6031 return SDValue(NewNode, 0); 6032 } 6033 6034 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6035 SDValue Offset, SDValue CachePolicy, 6036 SelectionDAG &DAG) const { 6037 MachineFunction &MF = DAG.getMachineFunction(); 6038 6039 const DataLayout &DataLayout = DAG.getDataLayout(); 6040 Align Alignment = 6041 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6042 6043 MachineMemOperand *MMO = MF.getMachineMemOperand( 6044 MachinePointerInfo(), 6045 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6046 MachineMemOperand::MOInvariant, 6047 VT.getStoreSize(), Alignment); 6048 6049 if (!Offset->isDivergent()) { 6050 SDValue Ops[] = { 6051 Rsrc, 6052 Offset, // Offset 6053 CachePolicy 6054 }; 6055 6056 // Widen vec3 load to vec4. 6057 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6058 EVT WidenedVT = 6059 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6060 auto WidenedOp = DAG.getMemIntrinsicNode( 6061 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6062 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6063 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6064 DAG.getVectorIdxConstant(0, DL)); 6065 return Subvector; 6066 } 6067 6068 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6069 DAG.getVTList(VT), Ops, VT, MMO); 6070 } 6071 6072 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6073 // assume that the buffer is unswizzled. 6074 SmallVector<SDValue, 4> Loads; 6075 unsigned NumLoads = 1; 6076 MVT LoadVT = VT.getSimpleVT(); 6077 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6078 assert((LoadVT.getScalarType() == MVT::i32 || 6079 LoadVT.getScalarType() == MVT::f32)); 6080 6081 if (NumElts == 8 || NumElts == 16) { 6082 NumLoads = NumElts / 4; 6083 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6084 } 6085 6086 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6087 SDValue Ops[] = { 6088 DAG.getEntryNode(), // Chain 6089 Rsrc, // rsrc 6090 DAG.getConstant(0, DL, MVT::i32), // vindex 6091 {}, // voffset 6092 {}, // soffset 6093 {}, // offset 6094 CachePolicy, // cachepolicy 6095 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6096 }; 6097 6098 // Use the alignment to ensure that the required offsets will fit into the 6099 // immediate offsets. 6100 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 6101 6102 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6103 for (unsigned i = 0; i < NumLoads; ++i) { 6104 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6105 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6106 LoadVT, MMO, DAG)); 6107 } 6108 6109 if (NumElts == 8 || NumElts == 16) 6110 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6111 6112 return Loads[0]; 6113 } 6114 6115 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6116 SelectionDAG &DAG) const { 6117 MachineFunction &MF = DAG.getMachineFunction(); 6118 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6119 6120 EVT VT = Op.getValueType(); 6121 SDLoc DL(Op); 6122 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6123 6124 // TODO: Should this propagate fast-math-flags? 6125 6126 switch (IntrinsicID) { 6127 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6128 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6129 return emitNonHSAIntrinsicError(DAG, DL, VT); 6130 return getPreloadedValue(DAG, *MFI, VT, 6131 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6132 } 6133 case Intrinsic::amdgcn_dispatch_ptr: 6134 case Intrinsic::amdgcn_queue_ptr: { 6135 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6136 DiagnosticInfoUnsupported BadIntrin( 6137 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6138 DL.getDebugLoc()); 6139 DAG.getContext()->diagnose(BadIntrin); 6140 return DAG.getUNDEF(VT); 6141 } 6142 6143 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6144 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6145 return getPreloadedValue(DAG, *MFI, VT, RegID); 6146 } 6147 case Intrinsic::amdgcn_implicitarg_ptr: { 6148 if (MFI->isEntryFunction()) 6149 return getImplicitArgPtr(DAG, DL); 6150 return getPreloadedValue(DAG, *MFI, VT, 6151 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6152 } 6153 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6154 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6155 // This only makes sense to call in a kernel, so just lower to null. 6156 return DAG.getConstant(0, DL, VT); 6157 } 6158 6159 return getPreloadedValue(DAG, *MFI, VT, 6160 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6161 } 6162 case Intrinsic::amdgcn_dispatch_id: { 6163 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6164 } 6165 case Intrinsic::amdgcn_rcp: 6166 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6167 case Intrinsic::amdgcn_rsq: 6168 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6169 case Intrinsic::amdgcn_rsq_legacy: 6170 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6171 return emitRemovedIntrinsicError(DAG, DL, VT); 6172 return SDValue(); 6173 case Intrinsic::amdgcn_rcp_legacy: 6174 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6175 return emitRemovedIntrinsicError(DAG, DL, VT); 6176 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6177 case Intrinsic::amdgcn_rsq_clamp: { 6178 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6179 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6180 6181 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6182 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6183 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6184 6185 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6186 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6187 DAG.getConstantFP(Max, DL, VT)); 6188 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6189 DAG.getConstantFP(Min, DL, VT)); 6190 } 6191 case Intrinsic::r600_read_ngroups_x: 6192 if (Subtarget->isAmdHsaOS()) 6193 return emitNonHSAIntrinsicError(DAG, DL, VT); 6194 6195 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6196 SI::KernelInputOffsets::NGROUPS_X, 4, false); 6197 case Intrinsic::r600_read_ngroups_y: 6198 if (Subtarget->isAmdHsaOS()) 6199 return emitNonHSAIntrinsicError(DAG, DL, VT); 6200 6201 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6202 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 6203 case Intrinsic::r600_read_ngroups_z: 6204 if (Subtarget->isAmdHsaOS()) 6205 return emitNonHSAIntrinsicError(DAG, DL, VT); 6206 6207 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6208 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 6209 case Intrinsic::r600_read_global_size_x: 6210 if (Subtarget->isAmdHsaOS()) 6211 return emitNonHSAIntrinsicError(DAG, DL, VT); 6212 6213 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6214 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 6215 case Intrinsic::r600_read_global_size_y: 6216 if (Subtarget->isAmdHsaOS()) 6217 return emitNonHSAIntrinsicError(DAG, DL, VT); 6218 6219 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6220 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 6221 case Intrinsic::r600_read_global_size_z: 6222 if (Subtarget->isAmdHsaOS()) 6223 return emitNonHSAIntrinsicError(DAG, DL, VT); 6224 6225 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6226 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 6227 case Intrinsic::r600_read_local_size_x: 6228 if (Subtarget->isAmdHsaOS()) 6229 return emitNonHSAIntrinsicError(DAG, DL, VT); 6230 6231 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6232 SI::KernelInputOffsets::LOCAL_SIZE_X); 6233 case Intrinsic::r600_read_local_size_y: 6234 if (Subtarget->isAmdHsaOS()) 6235 return emitNonHSAIntrinsicError(DAG, DL, VT); 6236 6237 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6238 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6239 case Intrinsic::r600_read_local_size_z: 6240 if (Subtarget->isAmdHsaOS()) 6241 return emitNonHSAIntrinsicError(DAG, DL, VT); 6242 6243 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6244 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6245 case Intrinsic::amdgcn_workgroup_id_x: 6246 return getPreloadedValue(DAG, *MFI, VT, 6247 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6248 case Intrinsic::amdgcn_workgroup_id_y: 6249 return getPreloadedValue(DAG, *MFI, VT, 6250 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6251 case Intrinsic::amdgcn_workgroup_id_z: 6252 return getPreloadedValue(DAG, *MFI, VT, 6253 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6254 case Intrinsic::amdgcn_workitem_id_x: 6255 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6256 SDLoc(DAG.getEntryNode()), 6257 MFI->getArgInfo().WorkItemIDX); 6258 case Intrinsic::amdgcn_workitem_id_y: 6259 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6260 SDLoc(DAG.getEntryNode()), 6261 MFI->getArgInfo().WorkItemIDY); 6262 case Intrinsic::amdgcn_workitem_id_z: 6263 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6264 SDLoc(DAG.getEntryNode()), 6265 MFI->getArgInfo().WorkItemIDZ); 6266 case Intrinsic::amdgcn_wavefrontsize: 6267 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6268 SDLoc(Op), MVT::i32); 6269 case Intrinsic::amdgcn_s_buffer_load: { 6270 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 6271 SDValue GLC; 6272 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6273 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6274 IsGFX10 ? &DLC : nullptr)) 6275 return Op; 6276 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6277 DAG); 6278 } 6279 case Intrinsic::amdgcn_fdiv_fast: 6280 return lowerFDIV_FAST(Op, DAG); 6281 case Intrinsic::amdgcn_sin: 6282 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6283 6284 case Intrinsic::amdgcn_cos: 6285 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6286 6287 case Intrinsic::amdgcn_mul_u24: 6288 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6289 case Intrinsic::amdgcn_mul_i24: 6290 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6291 6292 case Intrinsic::amdgcn_log_clamp: { 6293 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6294 return SDValue(); 6295 6296 DiagnosticInfoUnsupported BadIntrin( 6297 MF.getFunction(), "intrinsic not supported on subtarget", 6298 DL.getDebugLoc()); 6299 DAG.getContext()->diagnose(BadIntrin); 6300 return DAG.getUNDEF(VT); 6301 } 6302 case Intrinsic::amdgcn_ldexp: 6303 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6304 Op.getOperand(1), Op.getOperand(2)); 6305 6306 case Intrinsic::amdgcn_fract: 6307 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6308 6309 case Intrinsic::amdgcn_class: 6310 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6311 Op.getOperand(1), Op.getOperand(2)); 6312 case Intrinsic::amdgcn_div_fmas: 6313 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6314 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6315 Op.getOperand(4)); 6316 6317 case Intrinsic::amdgcn_div_fixup: 6318 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6319 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6320 6321 case Intrinsic::amdgcn_trig_preop: 6322 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 6323 Op.getOperand(1), Op.getOperand(2)); 6324 case Intrinsic::amdgcn_div_scale: { 6325 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6326 6327 // Translate to the operands expected by the machine instruction. The 6328 // first parameter must be the same as the first instruction. 6329 SDValue Numerator = Op.getOperand(1); 6330 SDValue Denominator = Op.getOperand(2); 6331 6332 // Note this order is opposite of the machine instruction's operations, 6333 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6334 // intrinsic has the numerator as the first operand to match a normal 6335 // division operation. 6336 6337 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6338 6339 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6340 Denominator, Numerator); 6341 } 6342 case Intrinsic::amdgcn_icmp: { 6343 // There is a Pat that handles this variant, so return it as-is. 6344 if (Op.getOperand(1).getValueType() == MVT::i1 && 6345 Op.getConstantOperandVal(2) == 0 && 6346 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6347 return Op; 6348 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6349 } 6350 case Intrinsic::amdgcn_fcmp: { 6351 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6352 } 6353 case Intrinsic::amdgcn_ballot: 6354 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6355 case Intrinsic::amdgcn_fmed3: 6356 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6357 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6358 case Intrinsic::amdgcn_fdot2: 6359 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6360 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6361 Op.getOperand(4)); 6362 case Intrinsic::amdgcn_fmul_legacy: 6363 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6364 Op.getOperand(1), Op.getOperand(2)); 6365 case Intrinsic::amdgcn_sffbh: 6366 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6367 case Intrinsic::amdgcn_sbfe: 6368 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6369 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6370 case Intrinsic::amdgcn_ubfe: 6371 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6372 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6373 case Intrinsic::amdgcn_cvt_pkrtz: 6374 case Intrinsic::amdgcn_cvt_pknorm_i16: 6375 case Intrinsic::amdgcn_cvt_pknorm_u16: 6376 case Intrinsic::amdgcn_cvt_pk_i16: 6377 case Intrinsic::amdgcn_cvt_pk_u16: { 6378 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6379 EVT VT = Op.getValueType(); 6380 unsigned Opcode; 6381 6382 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6383 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6384 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6385 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6386 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6387 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6388 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6389 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6390 else 6391 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6392 6393 if (isTypeLegal(VT)) 6394 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6395 6396 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6397 Op.getOperand(1), Op.getOperand(2)); 6398 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6399 } 6400 case Intrinsic::amdgcn_fmad_ftz: 6401 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6402 Op.getOperand(2), Op.getOperand(3)); 6403 6404 case Intrinsic::amdgcn_if_break: 6405 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6406 Op->getOperand(1), Op->getOperand(2)), 0); 6407 6408 case Intrinsic::amdgcn_groupstaticsize: { 6409 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6410 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6411 return Op; 6412 6413 const Module *M = MF.getFunction().getParent(); 6414 const GlobalValue *GV = 6415 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6416 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6417 SIInstrInfo::MO_ABS32_LO); 6418 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6419 } 6420 case Intrinsic::amdgcn_is_shared: 6421 case Intrinsic::amdgcn_is_private: { 6422 SDLoc SL(Op); 6423 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6424 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6425 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6426 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6427 Op.getOperand(1)); 6428 6429 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6430 DAG.getConstant(1, SL, MVT::i32)); 6431 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6432 } 6433 case Intrinsic::amdgcn_alignbit: 6434 return DAG.getNode(ISD::FSHR, DL, VT, 6435 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6436 case Intrinsic::amdgcn_reloc_constant: { 6437 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6438 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6439 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6440 auto RelocSymbol = cast<GlobalVariable>( 6441 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6442 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6443 SIInstrInfo::MO_ABS32_LO); 6444 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6445 } 6446 default: 6447 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6448 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6449 return lowerImage(Op, ImageDimIntr, DAG); 6450 6451 return Op; 6452 } 6453 } 6454 6455 // This function computes an appropriate offset to pass to 6456 // MachineMemOperand::setOffset() based on the offset inputs to 6457 // an intrinsic. If any of the offsets are non-contstant or 6458 // if VIndex is non-zero then this function returns 0. Otherwise, 6459 // it returns the sum of VOffset, SOffset, and Offset. 6460 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6461 SDValue SOffset, 6462 SDValue Offset, 6463 SDValue VIndex = SDValue()) { 6464 6465 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6466 !isa<ConstantSDNode>(Offset)) 6467 return 0; 6468 6469 if (VIndex) { 6470 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6471 return 0; 6472 } 6473 6474 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6475 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6476 cast<ConstantSDNode>(Offset)->getSExtValue(); 6477 } 6478 6479 static unsigned getDSShaderTypeValue(const MachineFunction &MF) { 6480 switch (MF.getFunction().getCallingConv()) { 6481 case CallingConv::AMDGPU_PS: 6482 return 1; 6483 case CallingConv::AMDGPU_VS: 6484 return 2; 6485 case CallingConv::AMDGPU_GS: 6486 return 3; 6487 case CallingConv::AMDGPU_HS: 6488 case CallingConv::AMDGPU_LS: 6489 case CallingConv::AMDGPU_ES: 6490 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6491 case CallingConv::AMDGPU_CS: 6492 case CallingConv::AMDGPU_KERNEL: 6493 case CallingConv::C: 6494 case CallingConv::Fast: 6495 default: 6496 // Assume other calling conventions are various compute callable functions 6497 return 0; 6498 } 6499 } 6500 6501 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6502 SelectionDAG &DAG) const { 6503 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6504 SDLoc DL(Op); 6505 6506 switch (IntrID) { 6507 case Intrinsic::amdgcn_ds_ordered_add: 6508 case Intrinsic::amdgcn_ds_ordered_swap: { 6509 MemSDNode *M = cast<MemSDNode>(Op); 6510 SDValue Chain = M->getOperand(0); 6511 SDValue M0 = M->getOperand(2); 6512 SDValue Value = M->getOperand(3); 6513 unsigned IndexOperand = M->getConstantOperandVal(7); 6514 unsigned WaveRelease = M->getConstantOperandVal(8); 6515 unsigned WaveDone = M->getConstantOperandVal(9); 6516 6517 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6518 IndexOperand &= ~0x3f; 6519 unsigned CountDw = 0; 6520 6521 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6522 CountDw = (IndexOperand >> 24) & 0xf; 6523 IndexOperand &= ~(0xf << 24); 6524 6525 if (CountDw < 1 || CountDw > 4) { 6526 report_fatal_error( 6527 "ds_ordered_count: dword count must be between 1 and 4"); 6528 } 6529 } 6530 6531 if (IndexOperand) 6532 report_fatal_error("ds_ordered_count: bad index operand"); 6533 6534 if (WaveDone && !WaveRelease) 6535 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6536 6537 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6538 unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction()); 6539 unsigned Offset0 = OrderedCountIndex << 2; 6540 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6541 (Instruction << 4); 6542 6543 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6544 Offset1 |= (CountDw - 1) << 6; 6545 6546 unsigned Offset = Offset0 | (Offset1 << 8); 6547 6548 SDValue Ops[] = { 6549 Chain, 6550 Value, 6551 DAG.getTargetConstant(Offset, DL, MVT::i16), 6552 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6553 }; 6554 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6555 M->getVTList(), Ops, M->getMemoryVT(), 6556 M->getMemOperand()); 6557 } 6558 case Intrinsic::amdgcn_ds_fadd: { 6559 MemSDNode *M = cast<MemSDNode>(Op); 6560 unsigned Opc; 6561 switch (IntrID) { 6562 case Intrinsic::amdgcn_ds_fadd: 6563 Opc = ISD::ATOMIC_LOAD_FADD; 6564 break; 6565 } 6566 6567 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6568 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6569 M->getMemOperand()); 6570 } 6571 case Intrinsic::amdgcn_atomic_inc: 6572 case Intrinsic::amdgcn_atomic_dec: 6573 case Intrinsic::amdgcn_ds_fmin: 6574 case Intrinsic::amdgcn_ds_fmax: { 6575 MemSDNode *M = cast<MemSDNode>(Op); 6576 unsigned Opc; 6577 switch (IntrID) { 6578 case Intrinsic::amdgcn_atomic_inc: 6579 Opc = AMDGPUISD::ATOMIC_INC; 6580 break; 6581 case Intrinsic::amdgcn_atomic_dec: 6582 Opc = AMDGPUISD::ATOMIC_DEC; 6583 break; 6584 case Intrinsic::amdgcn_ds_fmin: 6585 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6586 break; 6587 case Intrinsic::amdgcn_ds_fmax: 6588 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6589 break; 6590 default: 6591 llvm_unreachable("Unknown intrinsic!"); 6592 } 6593 SDValue Ops[] = { 6594 M->getOperand(0), // Chain 6595 M->getOperand(2), // Ptr 6596 M->getOperand(3) // Value 6597 }; 6598 6599 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6600 M->getMemoryVT(), M->getMemOperand()); 6601 } 6602 case Intrinsic::amdgcn_buffer_load: 6603 case Intrinsic::amdgcn_buffer_load_format: { 6604 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6605 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6606 unsigned IdxEn = 1; 6607 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6608 IdxEn = Idx->getZExtValue() != 0; 6609 SDValue Ops[] = { 6610 Op.getOperand(0), // Chain 6611 Op.getOperand(2), // rsrc 6612 Op.getOperand(3), // vindex 6613 SDValue(), // voffset -- will be set by setBufferOffsets 6614 SDValue(), // soffset -- will be set by setBufferOffsets 6615 SDValue(), // offset -- will be set by setBufferOffsets 6616 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6617 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6618 }; 6619 6620 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6621 // We don't know the offset if vindex is non-zero, so clear it. 6622 if (IdxEn) 6623 Offset = 0; 6624 6625 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6626 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6627 6628 EVT VT = Op.getValueType(); 6629 EVT IntVT = VT.changeTypeToInteger(); 6630 auto *M = cast<MemSDNode>(Op); 6631 M->getMemOperand()->setOffset(Offset); 6632 EVT LoadVT = Op.getValueType(); 6633 6634 if (LoadVT.getScalarType() == MVT::f16) 6635 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6636 M, DAG, Ops); 6637 6638 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6639 if (LoadVT.getScalarType() == MVT::i8 || 6640 LoadVT.getScalarType() == MVT::i16) 6641 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6642 6643 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6644 M->getMemOperand(), DAG); 6645 } 6646 case Intrinsic::amdgcn_raw_buffer_load: 6647 case Intrinsic::amdgcn_raw_buffer_load_format: { 6648 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6649 6650 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6651 SDValue Ops[] = { 6652 Op.getOperand(0), // Chain 6653 Op.getOperand(2), // rsrc 6654 DAG.getConstant(0, DL, MVT::i32), // vindex 6655 Offsets.first, // voffset 6656 Op.getOperand(4), // soffset 6657 Offsets.second, // offset 6658 Op.getOperand(5), // cachepolicy, swizzled buffer 6659 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6660 }; 6661 6662 auto *M = cast<MemSDNode>(Op); 6663 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6664 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6665 } 6666 case Intrinsic::amdgcn_struct_buffer_load: 6667 case Intrinsic::amdgcn_struct_buffer_load_format: { 6668 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6669 6670 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6671 SDValue Ops[] = { 6672 Op.getOperand(0), // Chain 6673 Op.getOperand(2), // rsrc 6674 Op.getOperand(3), // vindex 6675 Offsets.first, // voffset 6676 Op.getOperand(5), // soffset 6677 Offsets.second, // offset 6678 Op.getOperand(6), // cachepolicy, swizzled buffer 6679 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6680 }; 6681 6682 auto *M = cast<MemSDNode>(Op); 6683 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6684 Ops[2])); 6685 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6686 } 6687 case Intrinsic::amdgcn_tbuffer_load: { 6688 MemSDNode *M = cast<MemSDNode>(Op); 6689 EVT LoadVT = Op.getValueType(); 6690 6691 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6692 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6693 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6694 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6695 unsigned IdxEn = 1; 6696 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6697 IdxEn = Idx->getZExtValue() != 0; 6698 SDValue Ops[] = { 6699 Op.getOperand(0), // Chain 6700 Op.getOperand(2), // rsrc 6701 Op.getOperand(3), // vindex 6702 Op.getOperand(4), // voffset 6703 Op.getOperand(5), // soffset 6704 Op.getOperand(6), // offset 6705 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6706 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6707 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6708 }; 6709 6710 if (LoadVT.getScalarType() == MVT::f16) 6711 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6712 M, DAG, Ops); 6713 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6714 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6715 DAG); 6716 } 6717 case Intrinsic::amdgcn_raw_tbuffer_load: { 6718 MemSDNode *M = cast<MemSDNode>(Op); 6719 EVT LoadVT = Op.getValueType(); 6720 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6721 6722 SDValue Ops[] = { 6723 Op.getOperand(0), // Chain 6724 Op.getOperand(2), // rsrc 6725 DAG.getConstant(0, DL, MVT::i32), // vindex 6726 Offsets.first, // voffset 6727 Op.getOperand(4), // soffset 6728 Offsets.second, // offset 6729 Op.getOperand(5), // format 6730 Op.getOperand(6), // cachepolicy, swizzled buffer 6731 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6732 }; 6733 6734 if (LoadVT.getScalarType() == MVT::f16) 6735 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6736 M, DAG, Ops); 6737 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6738 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6739 DAG); 6740 } 6741 case Intrinsic::amdgcn_struct_tbuffer_load: { 6742 MemSDNode *M = cast<MemSDNode>(Op); 6743 EVT LoadVT = Op.getValueType(); 6744 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6745 6746 SDValue Ops[] = { 6747 Op.getOperand(0), // Chain 6748 Op.getOperand(2), // rsrc 6749 Op.getOperand(3), // vindex 6750 Offsets.first, // voffset 6751 Op.getOperand(5), // soffset 6752 Offsets.second, // offset 6753 Op.getOperand(6), // format 6754 Op.getOperand(7), // cachepolicy, swizzled buffer 6755 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6756 }; 6757 6758 if (LoadVT.getScalarType() == MVT::f16) 6759 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6760 M, DAG, Ops); 6761 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6762 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6763 DAG); 6764 } 6765 case Intrinsic::amdgcn_buffer_atomic_swap: 6766 case Intrinsic::amdgcn_buffer_atomic_add: 6767 case Intrinsic::amdgcn_buffer_atomic_sub: 6768 case Intrinsic::amdgcn_buffer_atomic_smin: 6769 case Intrinsic::amdgcn_buffer_atomic_umin: 6770 case Intrinsic::amdgcn_buffer_atomic_smax: 6771 case Intrinsic::amdgcn_buffer_atomic_umax: 6772 case Intrinsic::amdgcn_buffer_atomic_and: 6773 case Intrinsic::amdgcn_buffer_atomic_or: 6774 case Intrinsic::amdgcn_buffer_atomic_xor: { 6775 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6776 unsigned IdxEn = 1; 6777 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6778 IdxEn = Idx->getZExtValue() != 0; 6779 SDValue Ops[] = { 6780 Op.getOperand(0), // Chain 6781 Op.getOperand(2), // vdata 6782 Op.getOperand(3), // rsrc 6783 Op.getOperand(4), // vindex 6784 SDValue(), // voffset -- will be set by setBufferOffsets 6785 SDValue(), // soffset -- will be set by setBufferOffsets 6786 SDValue(), // offset -- will be set by setBufferOffsets 6787 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6788 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6789 }; 6790 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6791 // We don't know the offset if vindex is non-zero, so clear it. 6792 if (IdxEn) 6793 Offset = 0; 6794 EVT VT = Op.getValueType(); 6795 6796 auto *M = cast<MemSDNode>(Op); 6797 M->getMemOperand()->setOffset(Offset); 6798 unsigned Opcode = 0; 6799 6800 switch (IntrID) { 6801 case Intrinsic::amdgcn_buffer_atomic_swap: 6802 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6803 break; 6804 case Intrinsic::amdgcn_buffer_atomic_add: 6805 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6806 break; 6807 case Intrinsic::amdgcn_buffer_atomic_sub: 6808 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6809 break; 6810 case Intrinsic::amdgcn_buffer_atomic_smin: 6811 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6812 break; 6813 case Intrinsic::amdgcn_buffer_atomic_umin: 6814 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6815 break; 6816 case Intrinsic::amdgcn_buffer_atomic_smax: 6817 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6818 break; 6819 case Intrinsic::amdgcn_buffer_atomic_umax: 6820 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6821 break; 6822 case Intrinsic::amdgcn_buffer_atomic_and: 6823 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6824 break; 6825 case Intrinsic::amdgcn_buffer_atomic_or: 6826 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6827 break; 6828 case Intrinsic::amdgcn_buffer_atomic_xor: 6829 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6830 break; 6831 default: 6832 llvm_unreachable("unhandled atomic opcode"); 6833 } 6834 6835 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6836 M->getMemOperand()); 6837 } 6838 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6839 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6840 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6841 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6842 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6843 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6844 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6845 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6846 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6847 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6848 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6849 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 6850 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6851 SDValue Ops[] = { 6852 Op.getOperand(0), // Chain 6853 Op.getOperand(2), // vdata 6854 Op.getOperand(3), // rsrc 6855 DAG.getConstant(0, DL, MVT::i32), // vindex 6856 Offsets.first, // voffset 6857 Op.getOperand(5), // soffset 6858 Offsets.second, // offset 6859 Op.getOperand(6), // cachepolicy 6860 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6861 }; 6862 EVT VT = Op.getValueType(); 6863 6864 auto *M = cast<MemSDNode>(Op); 6865 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6866 unsigned Opcode = 0; 6867 6868 switch (IntrID) { 6869 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6870 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6871 break; 6872 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6873 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6874 break; 6875 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6876 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6877 break; 6878 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6879 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6880 break; 6881 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6882 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6883 break; 6884 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6885 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6886 break; 6887 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6888 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6889 break; 6890 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6891 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6892 break; 6893 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6894 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6895 break; 6896 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6897 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6898 break; 6899 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6900 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6901 break; 6902 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 6903 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6904 break; 6905 default: 6906 llvm_unreachable("unhandled atomic opcode"); 6907 } 6908 6909 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6910 M->getMemOperand()); 6911 } 6912 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6913 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6914 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6915 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6916 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6917 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6918 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6919 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6920 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6921 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6922 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6923 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 6924 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6925 SDValue Ops[] = { 6926 Op.getOperand(0), // Chain 6927 Op.getOperand(2), // vdata 6928 Op.getOperand(3), // rsrc 6929 Op.getOperand(4), // vindex 6930 Offsets.first, // voffset 6931 Op.getOperand(6), // soffset 6932 Offsets.second, // offset 6933 Op.getOperand(7), // cachepolicy 6934 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6935 }; 6936 EVT VT = Op.getValueType(); 6937 6938 auto *M = cast<MemSDNode>(Op); 6939 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6940 Ops[3])); 6941 unsigned Opcode = 0; 6942 6943 switch (IntrID) { 6944 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6945 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6946 break; 6947 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6948 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6949 break; 6950 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6951 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6952 break; 6953 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6954 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6955 break; 6956 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6957 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6958 break; 6959 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6960 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6961 break; 6962 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6963 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6964 break; 6965 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6966 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6967 break; 6968 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6969 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6970 break; 6971 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6972 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6973 break; 6974 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6975 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6976 break; 6977 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 6978 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6979 break; 6980 default: 6981 llvm_unreachable("unhandled atomic opcode"); 6982 } 6983 6984 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6985 M->getMemOperand()); 6986 } 6987 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 6988 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6989 unsigned IdxEn = 1; 6990 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 6991 IdxEn = Idx->getZExtValue() != 0; 6992 SDValue Ops[] = { 6993 Op.getOperand(0), // Chain 6994 Op.getOperand(2), // src 6995 Op.getOperand(3), // cmp 6996 Op.getOperand(4), // rsrc 6997 Op.getOperand(5), // vindex 6998 SDValue(), // voffset -- will be set by setBufferOffsets 6999 SDValue(), // soffset -- will be set by setBufferOffsets 7000 SDValue(), // offset -- will be set by setBufferOffsets 7001 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7002 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7003 }; 7004 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7005 // We don't know the offset if vindex is non-zero, so clear it. 7006 if (IdxEn) 7007 Offset = 0; 7008 EVT VT = Op.getValueType(); 7009 auto *M = cast<MemSDNode>(Op); 7010 M->getMemOperand()->setOffset(Offset); 7011 7012 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7013 Op->getVTList(), Ops, VT, M->getMemOperand()); 7014 } 7015 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7016 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7017 SDValue Ops[] = { 7018 Op.getOperand(0), // Chain 7019 Op.getOperand(2), // src 7020 Op.getOperand(3), // cmp 7021 Op.getOperand(4), // rsrc 7022 DAG.getConstant(0, DL, MVT::i32), // vindex 7023 Offsets.first, // voffset 7024 Op.getOperand(6), // soffset 7025 Offsets.second, // offset 7026 Op.getOperand(7), // cachepolicy 7027 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7028 }; 7029 EVT VT = Op.getValueType(); 7030 auto *M = cast<MemSDNode>(Op); 7031 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7032 7033 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7034 Op->getVTList(), Ops, VT, M->getMemOperand()); 7035 } 7036 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7037 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7038 SDValue Ops[] = { 7039 Op.getOperand(0), // Chain 7040 Op.getOperand(2), // src 7041 Op.getOperand(3), // cmp 7042 Op.getOperand(4), // rsrc 7043 Op.getOperand(5), // vindex 7044 Offsets.first, // voffset 7045 Op.getOperand(7), // soffset 7046 Offsets.second, // offset 7047 Op.getOperand(8), // cachepolicy 7048 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7049 }; 7050 EVT VT = Op.getValueType(); 7051 auto *M = cast<MemSDNode>(Op); 7052 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7053 Ops[4])); 7054 7055 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7056 Op->getVTList(), Ops, VT, M->getMemOperand()); 7057 } 7058 7059 default: 7060 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7061 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7062 return lowerImage(Op, ImageDimIntr, DAG); 7063 7064 return SDValue(); 7065 } 7066 } 7067 7068 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7069 // dwordx4 if on SI. 7070 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7071 SDVTList VTList, 7072 ArrayRef<SDValue> Ops, EVT MemVT, 7073 MachineMemOperand *MMO, 7074 SelectionDAG &DAG) const { 7075 EVT VT = VTList.VTs[0]; 7076 EVT WidenedVT = VT; 7077 EVT WidenedMemVT = MemVT; 7078 if (!Subtarget->hasDwordx3LoadStores() && 7079 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7080 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7081 WidenedVT.getVectorElementType(), 4); 7082 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7083 WidenedMemVT.getVectorElementType(), 4); 7084 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7085 } 7086 7087 assert(VTList.NumVTs == 2); 7088 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7089 7090 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7091 WidenedMemVT, MMO); 7092 if (WidenedVT != VT) { 7093 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7094 DAG.getVectorIdxConstant(0, DL)); 7095 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7096 } 7097 return NewOp; 7098 } 7099 7100 SDValue SITargetLowering::handleD16VData(SDValue VData, 7101 SelectionDAG &DAG) const { 7102 EVT StoreVT = VData.getValueType(); 7103 7104 // No change for f16 and legal vector D16 types. 7105 if (!StoreVT.isVector()) 7106 return VData; 7107 7108 SDLoc DL(VData); 7109 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 7110 7111 if (Subtarget->hasUnpackedD16VMem()) { 7112 // We need to unpack the packed data to store. 7113 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7114 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7115 7116 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 7117 StoreVT.getVectorNumElements()); 7118 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7119 return DAG.UnrollVectorOp(ZExt.getNode()); 7120 } 7121 7122 assert(isTypeLegal(StoreVT)); 7123 return VData; 7124 } 7125 7126 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7127 SelectionDAG &DAG) const { 7128 SDLoc DL(Op); 7129 SDValue Chain = Op.getOperand(0); 7130 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7131 MachineFunction &MF = DAG.getMachineFunction(); 7132 7133 switch (IntrinsicID) { 7134 case Intrinsic::amdgcn_exp_compr: { 7135 SDValue Src0 = Op.getOperand(4); 7136 SDValue Src1 = Op.getOperand(5); 7137 // Hack around illegal type on SI by directly selecting it. 7138 if (isTypeLegal(Src0.getValueType())) 7139 return SDValue(); 7140 7141 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7142 SDValue Undef = DAG.getUNDEF(MVT::f32); 7143 const SDValue Ops[] = { 7144 Op.getOperand(2), // tgt 7145 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7146 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7147 Undef, // src2 7148 Undef, // src3 7149 Op.getOperand(7), // vm 7150 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7151 Op.getOperand(3), // en 7152 Op.getOperand(0) // Chain 7153 }; 7154 7155 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7156 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7157 } 7158 case Intrinsic::amdgcn_s_barrier: { 7159 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7160 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7161 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7162 if (WGSize <= ST.getWavefrontSize()) 7163 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7164 Op.getOperand(0)), 0); 7165 } 7166 return SDValue(); 7167 }; 7168 case Intrinsic::amdgcn_tbuffer_store: { 7169 SDValue VData = Op.getOperand(2); 7170 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7171 if (IsD16) 7172 VData = handleD16VData(VData, DAG); 7173 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7174 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7175 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7176 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7177 unsigned IdxEn = 1; 7178 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7179 IdxEn = Idx->getZExtValue() != 0; 7180 SDValue Ops[] = { 7181 Chain, 7182 VData, // vdata 7183 Op.getOperand(3), // rsrc 7184 Op.getOperand(4), // vindex 7185 Op.getOperand(5), // voffset 7186 Op.getOperand(6), // soffset 7187 Op.getOperand(7), // offset 7188 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7189 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7190 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7191 }; 7192 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7193 AMDGPUISD::TBUFFER_STORE_FORMAT; 7194 MemSDNode *M = cast<MemSDNode>(Op); 7195 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7196 M->getMemoryVT(), M->getMemOperand()); 7197 } 7198 7199 case Intrinsic::amdgcn_struct_tbuffer_store: { 7200 SDValue VData = Op.getOperand(2); 7201 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7202 if (IsD16) 7203 VData = handleD16VData(VData, DAG); 7204 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7205 SDValue Ops[] = { 7206 Chain, 7207 VData, // vdata 7208 Op.getOperand(3), // rsrc 7209 Op.getOperand(4), // vindex 7210 Offsets.first, // voffset 7211 Op.getOperand(6), // soffset 7212 Offsets.second, // offset 7213 Op.getOperand(7), // format 7214 Op.getOperand(8), // cachepolicy, swizzled buffer 7215 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7216 }; 7217 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7218 AMDGPUISD::TBUFFER_STORE_FORMAT; 7219 MemSDNode *M = cast<MemSDNode>(Op); 7220 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7221 M->getMemoryVT(), M->getMemOperand()); 7222 } 7223 7224 case Intrinsic::amdgcn_raw_tbuffer_store: { 7225 SDValue VData = Op.getOperand(2); 7226 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7227 if (IsD16) 7228 VData = handleD16VData(VData, DAG); 7229 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7230 SDValue Ops[] = { 7231 Chain, 7232 VData, // vdata 7233 Op.getOperand(3), // rsrc 7234 DAG.getConstant(0, DL, MVT::i32), // vindex 7235 Offsets.first, // voffset 7236 Op.getOperand(5), // soffset 7237 Offsets.second, // offset 7238 Op.getOperand(6), // format 7239 Op.getOperand(7), // cachepolicy, swizzled buffer 7240 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7241 }; 7242 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7243 AMDGPUISD::TBUFFER_STORE_FORMAT; 7244 MemSDNode *M = cast<MemSDNode>(Op); 7245 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7246 M->getMemoryVT(), M->getMemOperand()); 7247 } 7248 7249 case Intrinsic::amdgcn_buffer_store: 7250 case Intrinsic::amdgcn_buffer_store_format: { 7251 SDValue VData = Op.getOperand(2); 7252 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7253 if (IsD16) 7254 VData = handleD16VData(VData, DAG); 7255 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7256 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7257 unsigned IdxEn = 1; 7258 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7259 IdxEn = Idx->getZExtValue() != 0; 7260 SDValue Ops[] = { 7261 Chain, 7262 VData, 7263 Op.getOperand(3), // rsrc 7264 Op.getOperand(4), // vindex 7265 SDValue(), // voffset -- will be set by setBufferOffsets 7266 SDValue(), // soffset -- will be set by setBufferOffsets 7267 SDValue(), // offset -- will be set by setBufferOffsets 7268 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7269 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7270 }; 7271 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7272 // We don't know the offset if vindex is non-zero, so clear it. 7273 if (IdxEn) 7274 Offset = 0; 7275 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7276 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7277 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7278 MemSDNode *M = cast<MemSDNode>(Op); 7279 M->getMemOperand()->setOffset(Offset); 7280 7281 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7282 EVT VDataType = VData.getValueType().getScalarType(); 7283 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7284 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7285 7286 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7287 M->getMemoryVT(), M->getMemOperand()); 7288 } 7289 7290 case Intrinsic::amdgcn_raw_buffer_store: 7291 case Intrinsic::amdgcn_raw_buffer_store_format: { 7292 const bool IsFormat = 7293 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7294 7295 SDValue VData = Op.getOperand(2); 7296 EVT VDataVT = VData.getValueType(); 7297 EVT EltType = VDataVT.getScalarType(); 7298 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7299 if (IsD16) 7300 VData = handleD16VData(VData, DAG); 7301 7302 if (!isTypeLegal(VDataVT)) { 7303 VData = 7304 DAG.getNode(ISD::BITCAST, DL, 7305 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7306 } 7307 7308 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7309 SDValue Ops[] = { 7310 Chain, 7311 VData, 7312 Op.getOperand(3), // rsrc 7313 DAG.getConstant(0, DL, MVT::i32), // vindex 7314 Offsets.first, // voffset 7315 Op.getOperand(5), // soffset 7316 Offsets.second, // offset 7317 Op.getOperand(6), // cachepolicy, swizzled buffer 7318 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7319 }; 7320 unsigned Opc = 7321 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7322 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7323 MemSDNode *M = cast<MemSDNode>(Op); 7324 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7325 7326 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7327 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7328 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7329 7330 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7331 M->getMemoryVT(), M->getMemOperand()); 7332 } 7333 7334 case Intrinsic::amdgcn_struct_buffer_store: 7335 case Intrinsic::amdgcn_struct_buffer_store_format: { 7336 const bool IsFormat = 7337 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7338 7339 SDValue VData = Op.getOperand(2); 7340 EVT VDataVT = VData.getValueType(); 7341 EVT EltType = VDataVT.getScalarType(); 7342 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7343 7344 if (IsD16) 7345 VData = handleD16VData(VData, DAG); 7346 7347 if (!isTypeLegal(VDataVT)) { 7348 VData = 7349 DAG.getNode(ISD::BITCAST, DL, 7350 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7351 } 7352 7353 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7354 SDValue Ops[] = { 7355 Chain, 7356 VData, 7357 Op.getOperand(3), // rsrc 7358 Op.getOperand(4), // vindex 7359 Offsets.first, // voffset 7360 Op.getOperand(6), // soffset 7361 Offsets.second, // offset 7362 Op.getOperand(7), // cachepolicy, swizzled buffer 7363 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7364 }; 7365 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7366 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7367 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7368 MemSDNode *M = cast<MemSDNode>(Op); 7369 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7370 Ops[3])); 7371 7372 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7373 EVT VDataType = VData.getValueType().getScalarType(); 7374 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7375 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7376 7377 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7378 M->getMemoryVT(), M->getMemOperand()); 7379 } 7380 7381 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7382 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7383 unsigned IdxEn = 1; 7384 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7385 IdxEn = Idx->getZExtValue() != 0; 7386 SDValue Ops[] = { 7387 Chain, 7388 Op.getOperand(2), // vdata 7389 Op.getOperand(3), // rsrc 7390 Op.getOperand(4), // vindex 7391 SDValue(), // voffset -- will be set by setBufferOffsets 7392 SDValue(), // soffset -- will be set by setBufferOffsets 7393 SDValue(), // offset -- will be set by setBufferOffsets 7394 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7395 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7396 }; 7397 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7398 // We don't know the offset if vindex is non-zero, so clear it. 7399 if (IdxEn) 7400 Offset = 0; 7401 EVT VT = Op.getOperand(2).getValueType(); 7402 7403 auto *M = cast<MemSDNode>(Op); 7404 M->getMemOperand()->setOffset(Offset); 7405 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 7406 : AMDGPUISD::BUFFER_ATOMIC_FADD; 7407 7408 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7409 M->getMemOperand()); 7410 } 7411 7412 case Intrinsic::amdgcn_global_atomic_fadd: { 7413 SDValue Ops[] = { 7414 Chain, 7415 Op.getOperand(2), // ptr 7416 Op.getOperand(3) // vdata 7417 }; 7418 EVT VT = Op.getOperand(3).getValueType(); 7419 7420 auto *M = cast<MemSDNode>(Op); 7421 if (VT.isVector()) { 7422 return DAG.getMemIntrinsicNode( 7423 AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT, 7424 M->getMemOperand()); 7425 } 7426 7427 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7428 DAG.getVTList(VT, MVT::Other), Ops, 7429 M->getMemOperand()).getValue(1); 7430 } 7431 case Intrinsic::amdgcn_end_cf: 7432 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7433 Op->getOperand(2), Chain), 0); 7434 7435 default: { 7436 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7437 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7438 return lowerImage(Op, ImageDimIntr, DAG); 7439 7440 return Op; 7441 } 7442 } 7443 } 7444 7445 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7446 // offset (the offset that is included in bounds checking and swizzling, to be 7447 // split between the instruction's voffset and immoffset fields) and soffset 7448 // (the offset that is excluded from bounds checking and swizzling, to go in 7449 // the instruction's soffset field). This function takes the first kind of 7450 // offset and figures out how to split it between voffset and immoffset. 7451 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7452 SDValue Offset, SelectionDAG &DAG) const { 7453 SDLoc DL(Offset); 7454 const unsigned MaxImm = 4095; 7455 SDValue N0 = Offset; 7456 ConstantSDNode *C1 = nullptr; 7457 7458 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7459 N0 = SDValue(); 7460 else if (DAG.isBaseWithConstantOffset(N0)) { 7461 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7462 N0 = N0.getOperand(0); 7463 } 7464 7465 if (C1) { 7466 unsigned ImmOffset = C1->getZExtValue(); 7467 // If the immediate value is too big for the immoffset field, put the value 7468 // and -4096 into the immoffset field so that the value that is copied/added 7469 // for the voffset field is a multiple of 4096, and it stands more chance 7470 // of being CSEd with the copy/add for another similar load/store. 7471 // However, do not do that rounding down to a multiple of 4096 if that is a 7472 // negative number, as it appears to be illegal to have a negative offset 7473 // in the vgpr, even if adding the immediate offset makes it positive. 7474 unsigned Overflow = ImmOffset & ~MaxImm; 7475 ImmOffset -= Overflow; 7476 if ((int32_t)Overflow < 0) { 7477 Overflow += ImmOffset; 7478 ImmOffset = 0; 7479 } 7480 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7481 if (Overflow) { 7482 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7483 if (!N0) 7484 N0 = OverflowVal; 7485 else { 7486 SDValue Ops[] = { N0, OverflowVal }; 7487 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7488 } 7489 } 7490 } 7491 if (!N0) 7492 N0 = DAG.getConstant(0, DL, MVT::i32); 7493 if (!C1) 7494 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7495 return {N0, SDValue(C1, 0)}; 7496 } 7497 7498 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7499 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7500 // pointed to by Offsets. 7501 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7502 SelectionDAG &DAG, SDValue *Offsets, 7503 unsigned Align) const { 7504 SDLoc DL(CombinedOffset); 7505 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7506 uint32_t Imm = C->getZExtValue(); 7507 uint32_t SOffset, ImmOffset; 7508 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 7509 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7510 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7511 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7512 return SOffset + ImmOffset; 7513 } 7514 } 7515 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7516 SDValue N0 = CombinedOffset.getOperand(0); 7517 SDValue N1 = CombinedOffset.getOperand(1); 7518 uint32_t SOffset, ImmOffset; 7519 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7520 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7521 Subtarget, Align)) { 7522 Offsets[0] = N0; 7523 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7524 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7525 return 0; 7526 } 7527 } 7528 Offsets[0] = CombinedOffset; 7529 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7530 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7531 return 0; 7532 } 7533 7534 // Handle 8 bit and 16 bit buffer loads 7535 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7536 EVT LoadVT, SDLoc DL, 7537 ArrayRef<SDValue> Ops, 7538 MemSDNode *M) const { 7539 EVT IntVT = LoadVT.changeTypeToInteger(); 7540 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7541 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7542 7543 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7544 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7545 Ops, IntVT, 7546 M->getMemOperand()); 7547 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7548 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7549 7550 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7551 } 7552 7553 // Handle 8 bit and 16 bit buffer stores 7554 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7555 EVT VDataType, SDLoc DL, 7556 SDValue Ops[], 7557 MemSDNode *M) const { 7558 if (VDataType == MVT::f16) 7559 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7560 7561 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7562 Ops[1] = BufferStoreExt; 7563 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7564 AMDGPUISD::BUFFER_STORE_SHORT; 7565 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7566 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7567 M->getMemOperand()); 7568 } 7569 7570 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7571 ISD::LoadExtType ExtType, SDValue Op, 7572 const SDLoc &SL, EVT VT) { 7573 if (VT.bitsLT(Op.getValueType())) 7574 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7575 7576 switch (ExtType) { 7577 case ISD::SEXTLOAD: 7578 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7579 case ISD::ZEXTLOAD: 7580 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7581 case ISD::EXTLOAD: 7582 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7583 case ISD::NON_EXTLOAD: 7584 return Op; 7585 } 7586 7587 llvm_unreachable("invalid ext type"); 7588 } 7589 7590 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7591 SelectionDAG &DAG = DCI.DAG; 7592 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7593 return SDValue(); 7594 7595 // FIXME: Constant loads should all be marked invariant. 7596 unsigned AS = Ld->getAddressSpace(); 7597 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7598 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7599 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7600 return SDValue(); 7601 7602 // Don't do this early, since it may interfere with adjacent load merging for 7603 // illegal types. We can avoid losing alignment information for exotic types 7604 // pre-legalize. 7605 EVT MemVT = Ld->getMemoryVT(); 7606 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7607 MemVT.getSizeInBits() >= 32) 7608 return SDValue(); 7609 7610 SDLoc SL(Ld); 7611 7612 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7613 "unexpected vector extload"); 7614 7615 // TODO: Drop only high part of range. 7616 SDValue Ptr = Ld->getBasePtr(); 7617 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7618 MVT::i32, SL, Ld->getChain(), Ptr, 7619 Ld->getOffset(), 7620 Ld->getPointerInfo(), MVT::i32, 7621 Ld->getAlignment(), 7622 Ld->getMemOperand()->getFlags(), 7623 Ld->getAAInfo(), 7624 nullptr); // Drop ranges 7625 7626 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7627 if (MemVT.isFloatingPoint()) { 7628 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7629 "unexpected fp extload"); 7630 TruncVT = MemVT.changeTypeToInteger(); 7631 } 7632 7633 SDValue Cvt = NewLoad; 7634 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7635 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7636 DAG.getValueType(TruncVT)); 7637 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7638 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7639 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7640 } else { 7641 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7642 } 7643 7644 EVT VT = Ld->getValueType(0); 7645 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7646 7647 DCI.AddToWorklist(Cvt.getNode()); 7648 7649 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7650 // the appropriate extension from the 32-bit load. 7651 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7652 DCI.AddToWorklist(Cvt.getNode()); 7653 7654 // Handle conversion back to floating point if necessary. 7655 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7656 7657 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7658 } 7659 7660 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7661 SDLoc DL(Op); 7662 LoadSDNode *Load = cast<LoadSDNode>(Op); 7663 ISD::LoadExtType ExtType = Load->getExtensionType(); 7664 EVT MemVT = Load->getMemoryVT(); 7665 7666 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7667 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7668 return SDValue(); 7669 7670 // FIXME: Copied from PPC 7671 // First, load into 32 bits, then truncate to 1 bit. 7672 7673 SDValue Chain = Load->getChain(); 7674 SDValue BasePtr = Load->getBasePtr(); 7675 MachineMemOperand *MMO = Load->getMemOperand(); 7676 7677 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7678 7679 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7680 BasePtr, RealMemVT, MMO); 7681 7682 if (!MemVT.isVector()) { 7683 SDValue Ops[] = { 7684 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7685 NewLD.getValue(1) 7686 }; 7687 7688 return DAG.getMergeValues(Ops, DL); 7689 } 7690 7691 SmallVector<SDValue, 3> Elts; 7692 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7693 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7694 DAG.getConstant(I, DL, MVT::i32)); 7695 7696 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7697 } 7698 7699 SDValue Ops[] = { 7700 DAG.getBuildVector(MemVT, DL, Elts), 7701 NewLD.getValue(1) 7702 }; 7703 7704 return DAG.getMergeValues(Ops, DL); 7705 } 7706 7707 if (!MemVT.isVector()) 7708 return SDValue(); 7709 7710 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7711 "Custom lowering for non-i32 vectors hasn't been implemented."); 7712 7713 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7714 MemVT, *Load->getMemOperand())) { 7715 SDValue Ops[2]; 7716 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7717 return DAG.getMergeValues(Ops, DL); 7718 } 7719 7720 unsigned Alignment = Load->getAlignment(); 7721 unsigned AS = Load->getAddressSpace(); 7722 if (Subtarget->hasLDSMisalignedBug() && 7723 AS == AMDGPUAS::FLAT_ADDRESS && 7724 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7725 return SplitVectorLoad(Op, DAG); 7726 } 7727 7728 MachineFunction &MF = DAG.getMachineFunction(); 7729 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7730 // If there is a possibilty that flat instruction access scratch memory 7731 // then we need to use the same legalization rules we use for private. 7732 if (AS == AMDGPUAS::FLAT_ADDRESS && 7733 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7734 AS = MFI->hasFlatScratchInit() ? 7735 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7736 7737 unsigned NumElements = MemVT.getVectorNumElements(); 7738 7739 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7740 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7741 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7742 if (MemVT.isPow2VectorType()) 7743 return SDValue(); 7744 if (NumElements == 3) 7745 return WidenVectorLoad(Op, DAG); 7746 return SplitVectorLoad(Op, DAG); 7747 } 7748 // Non-uniform loads will be selected to MUBUF instructions, so they 7749 // have the same legalization requirements as global and private 7750 // loads. 7751 // 7752 } 7753 7754 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7755 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7756 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7757 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7758 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 7759 Alignment >= 4 && NumElements < 32) { 7760 if (MemVT.isPow2VectorType()) 7761 return SDValue(); 7762 if (NumElements == 3) 7763 return WidenVectorLoad(Op, DAG); 7764 return SplitVectorLoad(Op, DAG); 7765 } 7766 // Non-uniform loads will be selected to MUBUF instructions, so they 7767 // have the same legalization requirements as global and private 7768 // loads. 7769 // 7770 } 7771 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7772 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7773 AS == AMDGPUAS::GLOBAL_ADDRESS || 7774 AS == AMDGPUAS::FLAT_ADDRESS) { 7775 if (NumElements > 4) 7776 return SplitVectorLoad(Op, DAG); 7777 // v3 loads not supported on SI. 7778 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7779 return WidenVectorLoad(Op, DAG); 7780 // v3 and v4 loads are supported for private and global memory. 7781 return SDValue(); 7782 } 7783 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7784 // Depending on the setting of the private_element_size field in the 7785 // resource descriptor, we can only make private accesses up to a certain 7786 // size. 7787 switch (Subtarget->getMaxPrivateElementSize()) { 7788 case 4: { 7789 SDValue Ops[2]; 7790 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7791 return DAG.getMergeValues(Ops, DL); 7792 } 7793 case 8: 7794 if (NumElements > 2) 7795 return SplitVectorLoad(Op, DAG); 7796 return SDValue(); 7797 case 16: 7798 // Same as global/flat 7799 if (NumElements > 4) 7800 return SplitVectorLoad(Op, DAG); 7801 // v3 loads not supported on SI. 7802 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7803 return WidenVectorLoad(Op, DAG); 7804 return SDValue(); 7805 default: 7806 llvm_unreachable("unsupported private_element_size"); 7807 } 7808 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7809 // Use ds_read_b128 if possible. 7810 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7811 MemVT.getStoreSize() == 16) 7812 return SDValue(); 7813 7814 if (NumElements > 2) 7815 return SplitVectorLoad(Op, DAG); 7816 7817 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7818 // address is negative, then the instruction is incorrectly treated as 7819 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7820 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7821 // load later in the SILoadStoreOptimizer. 7822 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7823 NumElements == 2 && MemVT.getStoreSize() == 8 && 7824 Load->getAlignment() < 8) { 7825 return SplitVectorLoad(Op, DAG); 7826 } 7827 } 7828 return SDValue(); 7829 } 7830 7831 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7832 EVT VT = Op.getValueType(); 7833 assert(VT.getSizeInBits() == 64); 7834 7835 SDLoc DL(Op); 7836 SDValue Cond = Op.getOperand(0); 7837 7838 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7839 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7840 7841 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7842 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7843 7844 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7845 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7846 7847 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7848 7849 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7850 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7851 7852 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7853 7854 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7855 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7856 } 7857 7858 // Catch division cases where we can use shortcuts with rcp and rsq 7859 // instructions. 7860 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7861 SelectionDAG &DAG) const { 7862 SDLoc SL(Op); 7863 SDValue LHS = Op.getOperand(0); 7864 SDValue RHS = Op.getOperand(1); 7865 EVT VT = Op.getValueType(); 7866 const SDNodeFlags Flags = Op->getFlags(); 7867 7868 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 7869 Flags.hasApproximateFuncs(); 7870 7871 // Without !fpmath accuracy information, we can't do more because we don't 7872 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 7873 if (!AllowInaccurateRcp) 7874 return SDValue(); 7875 7876 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7877 if (CLHS->isExactlyValue(1.0)) { 7878 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7879 // the CI documentation has a worst case error of 1 ulp. 7880 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7881 // use it as long as we aren't trying to use denormals. 7882 // 7883 // v_rcp_f16 and v_rsq_f16 DO support denormals. 7884 7885 // 1.0 / sqrt(x) -> rsq(x) 7886 7887 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 7888 // error seems really high at 2^29 ULP. 7889 if (RHS.getOpcode() == ISD::FSQRT) 7890 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 7891 7892 // 1.0 / x -> rcp(x) 7893 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7894 } 7895 7896 // Same as for 1.0, but expand the sign out of the constant. 7897 if (CLHS->isExactlyValue(-1.0)) { 7898 // -1.0 / x -> rcp (fneg x) 7899 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7900 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 7901 } 7902 } 7903 7904 // Turn into multiply by the reciprocal. 7905 // x / y -> x * (1.0 / y) 7906 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7907 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 7908 } 7909 7910 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7911 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 7912 SDNodeFlags Flags) { 7913 if (GlueChain->getNumValues() <= 1) { 7914 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 7915 } 7916 7917 assert(GlueChain->getNumValues() == 3); 7918 7919 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7920 switch (Opcode) { 7921 default: llvm_unreachable("no chain equivalent for opcode"); 7922 case ISD::FMUL: 7923 Opcode = AMDGPUISD::FMUL_W_CHAIN; 7924 break; 7925 } 7926 7927 return DAG.getNode(Opcode, SL, VTList, 7928 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 7929 Flags); 7930 } 7931 7932 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7933 EVT VT, SDValue A, SDValue B, SDValue C, 7934 SDValue GlueChain, SDNodeFlags Flags) { 7935 if (GlueChain->getNumValues() <= 1) { 7936 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 7937 } 7938 7939 assert(GlueChain->getNumValues() == 3); 7940 7941 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7942 switch (Opcode) { 7943 default: llvm_unreachable("no chain equivalent for opcode"); 7944 case ISD::FMA: 7945 Opcode = AMDGPUISD::FMA_W_CHAIN; 7946 break; 7947 } 7948 7949 return DAG.getNode(Opcode, SL, VTList, 7950 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 7951 Flags); 7952 } 7953 7954 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 7955 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7956 return FastLowered; 7957 7958 SDLoc SL(Op); 7959 SDValue Src0 = Op.getOperand(0); 7960 SDValue Src1 = Op.getOperand(1); 7961 7962 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 7963 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 7964 7965 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 7966 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 7967 7968 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 7969 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 7970 7971 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 7972 } 7973 7974 // Faster 2.5 ULP division that does not support denormals. 7975 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 7976 SDLoc SL(Op); 7977 SDValue LHS = Op.getOperand(1); 7978 SDValue RHS = Op.getOperand(2); 7979 7980 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 7981 7982 const APFloat K0Val(BitsToFloat(0x6f800000)); 7983 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 7984 7985 const APFloat K1Val(BitsToFloat(0x2f800000)); 7986 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 7987 7988 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7989 7990 EVT SetCCVT = 7991 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 7992 7993 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 7994 7995 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 7996 7997 // TODO: Should this propagate fast-math-flags? 7998 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 7999 8000 // rcp does not support denormals. 8001 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8002 8003 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8004 8005 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8006 } 8007 8008 // Returns immediate value for setting the F32 denorm mode when using the 8009 // S_DENORM_MODE instruction. 8010 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8011 const SDLoc &SL, const GCNSubtarget *ST) { 8012 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8013 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8014 ? FP_DENORM_FLUSH_NONE 8015 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8016 8017 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8018 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8019 } 8020 8021 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8022 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8023 return FastLowered; 8024 8025 // The selection matcher assumes anything with a chain selecting to a 8026 // mayRaiseFPException machine instruction. Since we're introducing a chain 8027 // here, we need to explicitly report nofpexcept for the regular fdiv 8028 // lowering. 8029 SDNodeFlags Flags = Op->getFlags(); 8030 Flags.setNoFPExcept(true); 8031 8032 SDLoc SL(Op); 8033 SDValue LHS = Op.getOperand(0); 8034 SDValue RHS = Op.getOperand(1); 8035 8036 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8037 8038 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8039 8040 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8041 {RHS, RHS, LHS}, Flags); 8042 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8043 {LHS, RHS, LHS}, Flags); 8044 8045 // Denominator is scaled to not be denormal, so using rcp is ok. 8046 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8047 DenominatorScaled, Flags); 8048 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8049 DenominatorScaled, Flags); 8050 8051 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8052 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8053 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8054 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8055 8056 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8057 8058 if (!HasFP32Denormals) { 8059 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8060 // lowering. The chain dependence is insufficient, and we need glue. We do 8061 // not need the glue variants in a strictfp function. 8062 8063 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8064 8065 SDNode *EnableDenorm; 8066 if (Subtarget->hasDenormModeInst()) { 8067 const SDValue EnableDenormValue = 8068 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8069 8070 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8071 DAG.getEntryNode(), EnableDenormValue).getNode(); 8072 } else { 8073 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8074 SL, MVT::i32); 8075 EnableDenorm = 8076 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8077 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8078 } 8079 8080 SDValue Ops[3] = { 8081 NegDivScale0, 8082 SDValue(EnableDenorm, 0), 8083 SDValue(EnableDenorm, 1) 8084 }; 8085 8086 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8087 } 8088 8089 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8090 ApproxRcp, One, NegDivScale0, Flags); 8091 8092 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8093 ApproxRcp, Fma0, Flags); 8094 8095 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8096 Fma1, Fma1, Flags); 8097 8098 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8099 NumeratorScaled, Mul, Flags); 8100 8101 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8102 Fma2, Fma1, Mul, Fma2, Flags); 8103 8104 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8105 NumeratorScaled, Fma3, Flags); 8106 8107 if (!HasFP32Denormals) { 8108 SDNode *DisableDenorm; 8109 if (Subtarget->hasDenormModeInst()) { 8110 const SDValue DisableDenormValue = 8111 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8112 8113 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8114 Fma4.getValue(1), DisableDenormValue, 8115 Fma4.getValue(2)).getNode(); 8116 } else { 8117 const SDValue DisableDenormValue = 8118 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8119 8120 DisableDenorm = DAG.getMachineNode( 8121 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8122 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8123 } 8124 8125 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8126 SDValue(DisableDenorm, 0), DAG.getRoot()); 8127 DAG.setRoot(OutputChain); 8128 } 8129 8130 SDValue Scale = NumeratorScaled.getValue(1); 8131 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8132 {Fma4, Fma1, Fma3, Scale}, Flags); 8133 8134 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8135 } 8136 8137 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8138 if (DAG.getTarget().Options.UnsafeFPMath) 8139 return lowerFastUnsafeFDIV(Op, DAG); 8140 8141 SDLoc SL(Op); 8142 SDValue X = Op.getOperand(0); 8143 SDValue Y = Op.getOperand(1); 8144 8145 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8146 8147 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8148 8149 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8150 8151 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8152 8153 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8154 8155 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8156 8157 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8158 8159 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8160 8161 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8162 8163 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8164 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8165 8166 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8167 NegDivScale0, Mul, DivScale1); 8168 8169 SDValue Scale; 8170 8171 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8172 // Workaround a hardware bug on SI where the condition output from div_scale 8173 // is not usable. 8174 8175 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8176 8177 // Figure out if the scale to use for div_fmas. 8178 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8179 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8180 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8181 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8182 8183 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8184 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8185 8186 SDValue Scale0Hi 8187 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8188 SDValue Scale1Hi 8189 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8190 8191 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8192 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8193 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8194 } else { 8195 Scale = DivScale1.getValue(1); 8196 } 8197 8198 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8199 Fma4, Fma3, Mul, Scale); 8200 8201 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8202 } 8203 8204 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8205 EVT VT = Op.getValueType(); 8206 8207 if (VT == MVT::f32) 8208 return LowerFDIV32(Op, DAG); 8209 8210 if (VT == MVT::f64) 8211 return LowerFDIV64(Op, DAG); 8212 8213 if (VT == MVT::f16) 8214 return LowerFDIV16(Op, DAG); 8215 8216 llvm_unreachable("Unexpected type for fdiv"); 8217 } 8218 8219 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8220 SDLoc DL(Op); 8221 StoreSDNode *Store = cast<StoreSDNode>(Op); 8222 EVT VT = Store->getMemoryVT(); 8223 8224 if (VT == MVT::i1) { 8225 return DAG.getTruncStore(Store->getChain(), DL, 8226 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8227 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8228 } 8229 8230 assert(VT.isVector() && 8231 Store->getValue().getValueType().getScalarType() == MVT::i32); 8232 8233 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8234 VT, *Store->getMemOperand())) { 8235 return expandUnalignedStore(Store, DAG); 8236 } 8237 8238 unsigned AS = Store->getAddressSpace(); 8239 if (Subtarget->hasLDSMisalignedBug() && 8240 AS == AMDGPUAS::FLAT_ADDRESS && 8241 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8242 return SplitVectorStore(Op, DAG); 8243 } 8244 8245 MachineFunction &MF = DAG.getMachineFunction(); 8246 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8247 // If there is a possibilty that flat instruction access scratch memory 8248 // then we need to use the same legalization rules we use for private. 8249 if (AS == AMDGPUAS::FLAT_ADDRESS && 8250 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8251 AS = MFI->hasFlatScratchInit() ? 8252 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8253 8254 unsigned NumElements = VT.getVectorNumElements(); 8255 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8256 AS == AMDGPUAS::FLAT_ADDRESS) { 8257 if (NumElements > 4) 8258 return SplitVectorStore(Op, DAG); 8259 // v3 stores not supported on SI. 8260 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8261 return SplitVectorStore(Op, DAG); 8262 return SDValue(); 8263 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8264 switch (Subtarget->getMaxPrivateElementSize()) { 8265 case 4: 8266 return scalarizeVectorStore(Store, DAG); 8267 case 8: 8268 if (NumElements > 2) 8269 return SplitVectorStore(Op, DAG); 8270 return SDValue(); 8271 case 16: 8272 if (NumElements > 4 || NumElements == 3) 8273 return SplitVectorStore(Op, DAG); 8274 return SDValue(); 8275 default: 8276 llvm_unreachable("unsupported private_element_size"); 8277 } 8278 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8279 // Use ds_write_b128 if possible. 8280 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 8281 VT.getStoreSize() == 16 && NumElements != 3) 8282 return SDValue(); 8283 8284 if (NumElements > 2) 8285 return SplitVectorStore(Op, DAG); 8286 8287 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8288 // address is negative, then the instruction is incorrectly treated as 8289 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8290 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8291 // store later in the SILoadStoreOptimizer. 8292 if (!Subtarget->hasUsableDSOffset() && 8293 NumElements == 2 && VT.getStoreSize() == 8 && 8294 Store->getAlignment() < 8) { 8295 return SplitVectorStore(Op, DAG); 8296 } 8297 8298 return SDValue(); 8299 } else { 8300 llvm_unreachable("unhandled address space"); 8301 } 8302 } 8303 8304 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8305 SDLoc DL(Op); 8306 EVT VT = Op.getValueType(); 8307 SDValue Arg = Op.getOperand(0); 8308 SDValue TrigVal; 8309 8310 // Propagate fast-math flags so that the multiply we introduce can be folded 8311 // if Arg is already the result of a multiply by constant. 8312 auto Flags = Op->getFlags(); 8313 8314 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8315 8316 if (Subtarget->hasTrigReducedRange()) { 8317 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8318 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8319 } else { 8320 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8321 } 8322 8323 switch (Op.getOpcode()) { 8324 case ISD::FCOS: 8325 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8326 case ISD::FSIN: 8327 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8328 default: 8329 llvm_unreachable("Wrong trig opcode"); 8330 } 8331 } 8332 8333 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8334 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8335 assert(AtomicNode->isCompareAndSwap()); 8336 unsigned AS = AtomicNode->getAddressSpace(); 8337 8338 // No custom lowering required for local address space 8339 if (!isFlatGlobalAddrSpace(AS)) 8340 return Op; 8341 8342 // Non-local address space requires custom lowering for atomic compare 8343 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8344 SDLoc DL(Op); 8345 SDValue ChainIn = Op.getOperand(0); 8346 SDValue Addr = Op.getOperand(1); 8347 SDValue Old = Op.getOperand(2); 8348 SDValue New = Op.getOperand(3); 8349 EVT VT = Op.getValueType(); 8350 MVT SimpleVT = VT.getSimpleVT(); 8351 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8352 8353 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8354 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8355 8356 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8357 Ops, VT, AtomicNode->getMemOperand()); 8358 } 8359 8360 //===----------------------------------------------------------------------===// 8361 // Custom DAG optimizations 8362 //===----------------------------------------------------------------------===// 8363 8364 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8365 DAGCombinerInfo &DCI) const { 8366 EVT VT = N->getValueType(0); 8367 EVT ScalarVT = VT.getScalarType(); 8368 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8369 return SDValue(); 8370 8371 SelectionDAG &DAG = DCI.DAG; 8372 SDLoc DL(N); 8373 8374 SDValue Src = N->getOperand(0); 8375 EVT SrcVT = Src.getValueType(); 8376 8377 // TODO: We could try to match extracting the higher bytes, which would be 8378 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8379 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8380 // about in practice. 8381 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8382 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8383 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8384 DCI.AddToWorklist(Cvt.getNode()); 8385 8386 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8387 if (ScalarVT != MVT::f32) { 8388 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8389 DAG.getTargetConstant(0, DL, MVT::i32)); 8390 } 8391 return Cvt; 8392 } 8393 } 8394 8395 return SDValue(); 8396 } 8397 8398 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8399 8400 // This is a variant of 8401 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8402 // 8403 // The normal DAG combiner will do this, but only if the add has one use since 8404 // that would increase the number of instructions. 8405 // 8406 // This prevents us from seeing a constant offset that can be folded into a 8407 // memory instruction's addressing mode. If we know the resulting add offset of 8408 // a pointer can be folded into an addressing offset, we can replace the pointer 8409 // operand with the add of new constant offset. This eliminates one of the uses, 8410 // and may allow the remaining use to also be simplified. 8411 // 8412 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8413 unsigned AddrSpace, 8414 EVT MemVT, 8415 DAGCombinerInfo &DCI) const { 8416 SDValue N0 = N->getOperand(0); 8417 SDValue N1 = N->getOperand(1); 8418 8419 // We only do this to handle cases where it's profitable when there are 8420 // multiple uses of the add, so defer to the standard combine. 8421 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8422 N0->hasOneUse()) 8423 return SDValue(); 8424 8425 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8426 if (!CN1) 8427 return SDValue(); 8428 8429 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8430 if (!CAdd) 8431 return SDValue(); 8432 8433 // If the resulting offset is too large, we can't fold it into the addressing 8434 // mode offset. 8435 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8436 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8437 8438 AddrMode AM; 8439 AM.HasBaseReg = true; 8440 AM.BaseOffs = Offset.getSExtValue(); 8441 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8442 return SDValue(); 8443 8444 SelectionDAG &DAG = DCI.DAG; 8445 SDLoc SL(N); 8446 EVT VT = N->getValueType(0); 8447 8448 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8449 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 8450 8451 SDNodeFlags Flags; 8452 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8453 (N0.getOpcode() == ISD::OR || 8454 N0->getFlags().hasNoUnsignedWrap())); 8455 8456 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8457 } 8458 8459 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8460 DAGCombinerInfo &DCI) const { 8461 SDValue Ptr = N->getBasePtr(); 8462 SelectionDAG &DAG = DCI.DAG; 8463 SDLoc SL(N); 8464 8465 // TODO: We could also do this for multiplies. 8466 if (Ptr.getOpcode() == ISD::SHL) { 8467 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8468 N->getMemoryVT(), DCI); 8469 if (NewPtr) { 8470 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8471 8472 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8473 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8474 } 8475 } 8476 8477 return SDValue(); 8478 } 8479 8480 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8481 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8482 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8483 (Opc == ISD::XOR && Val == 0); 8484 } 8485 8486 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8487 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8488 // integer combine opportunities since most 64-bit operations are decomposed 8489 // this way. TODO: We won't want this for SALU especially if it is an inline 8490 // immediate. 8491 SDValue SITargetLowering::splitBinaryBitConstantOp( 8492 DAGCombinerInfo &DCI, 8493 const SDLoc &SL, 8494 unsigned Opc, SDValue LHS, 8495 const ConstantSDNode *CRHS) const { 8496 uint64_t Val = CRHS->getZExtValue(); 8497 uint32_t ValLo = Lo_32(Val); 8498 uint32_t ValHi = Hi_32(Val); 8499 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8500 8501 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8502 bitOpWithConstantIsReducible(Opc, ValHi)) || 8503 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8504 // If we need to materialize a 64-bit immediate, it will be split up later 8505 // anyway. Avoid creating the harder to understand 64-bit immediate 8506 // materialization. 8507 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8508 } 8509 8510 return SDValue(); 8511 } 8512 8513 // Returns true if argument is a boolean value which is not serialized into 8514 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8515 static bool isBoolSGPR(SDValue V) { 8516 if (V.getValueType() != MVT::i1) 8517 return false; 8518 switch (V.getOpcode()) { 8519 default: break; 8520 case ISD::SETCC: 8521 case ISD::AND: 8522 case ISD::OR: 8523 case ISD::XOR: 8524 case AMDGPUISD::FP_CLASS: 8525 return true; 8526 } 8527 return false; 8528 } 8529 8530 // If a constant has all zeroes or all ones within each byte return it. 8531 // Otherwise return 0. 8532 static uint32_t getConstantPermuteMask(uint32_t C) { 8533 // 0xff for any zero byte in the mask 8534 uint32_t ZeroByteMask = 0; 8535 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8536 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8537 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8538 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8539 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8540 if ((NonZeroByteMask & C) != NonZeroByteMask) 8541 return 0; // Partial bytes selected. 8542 return C; 8543 } 8544 8545 // Check if a node selects whole bytes from its operand 0 starting at a byte 8546 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8547 // or -1 if not succeeded. 8548 // Note byte select encoding: 8549 // value 0-3 selects corresponding source byte; 8550 // value 0xc selects zero; 8551 // value 0xff selects 0xff. 8552 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8553 assert(V.getValueSizeInBits() == 32); 8554 8555 if (V.getNumOperands() != 2) 8556 return ~0; 8557 8558 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8559 if (!N1) 8560 return ~0; 8561 8562 uint32_t C = N1->getZExtValue(); 8563 8564 switch (V.getOpcode()) { 8565 default: 8566 break; 8567 case ISD::AND: 8568 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8569 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8570 } 8571 break; 8572 8573 case ISD::OR: 8574 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8575 return (0x03020100 & ~ConstMask) | ConstMask; 8576 } 8577 break; 8578 8579 case ISD::SHL: 8580 if (C % 8) 8581 return ~0; 8582 8583 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8584 8585 case ISD::SRL: 8586 if (C % 8) 8587 return ~0; 8588 8589 return uint32_t(0x0c0c0c0c03020100ull >> C); 8590 } 8591 8592 return ~0; 8593 } 8594 8595 SDValue SITargetLowering::performAndCombine(SDNode *N, 8596 DAGCombinerInfo &DCI) const { 8597 if (DCI.isBeforeLegalize()) 8598 return SDValue(); 8599 8600 SelectionDAG &DAG = DCI.DAG; 8601 EVT VT = N->getValueType(0); 8602 SDValue LHS = N->getOperand(0); 8603 SDValue RHS = N->getOperand(1); 8604 8605 8606 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8607 if (VT == MVT::i64 && CRHS) { 8608 if (SDValue Split 8609 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8610 return Split; 8611 } 8612 8613 if (CRHS && VT == MVT::i32) { 8614 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8615 // nb = number of trailing zeroes in mask 8616 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8617 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8618 uint64_t Mask = CRHS->getZExtValue(); 8619 unsigned Bits = countPopulation(Mask); 8620 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8621 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8622 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8623 unsigned Shift = CShift->getZExtValue(); 8624 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8625 unsigned Offset = NB + Shift; 8626 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8627 SDLoc SL(N); 8628 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8629 LHS->getOperand(0), 8630 DAG.getConstant(Offset, SL, MVT::i32), 8631 DAG.getConstant(Bits, SL, MVT::i32)); 8632 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8633 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8634 DAG.getValueType(NarrowVT)); 8635 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8636 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8637 return Shl; 8638 } 8639 } 8640 } 8641 8642 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8643 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8644 isa<ConstantSDNode>(LHS.getOperand(2))) { 8645 uint32_t Sel = getConstantPermuteMask(Mask); 8646 if (!Sel) 8647 return SDValue(); 8648 8649 // Select 0xc for all zero bytes 8650 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8651 SDLoc DL(N); 8652 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8653 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8654 } 8655 } 8656 8657 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8658 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8659 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8660 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8661 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8662 8663 SDValue X = LHS.getOperand(0); 8664 SDValue Y = RHS.getOperand(0); 8665 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8666 return SDValue(); 8667 8668 if (LCC == ISD::SETO) { 8669 if (X != LHS.getOperand(1)) 8670 return SDValue(); 8671 8672 if (RCC == ISD::SETUNE) { 8673 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8674 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8675 return SDValue(); 8676 8677 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8678 SIInstrFlags::N_SUBNORMAL | 8679 SIInstrFlags::N_ZERO | 8680 SIInstrFlags::P_ZERO | 8681 SIInstrFlags::P_SUBNORMAL | 8682 SIInstrFlags::P_NORMAL; 8683 8684 static_assert(((~(SIInstrFlags::S_NAN | 8685 SIInstrFlags::Q_NAN | 8686 SIInstrFlags::N_INFINITY | 8687 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8688 "mask not equal"); 8689 8690 SDLoc DL(N); 8691 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8692 X, DAG.getConstant(Mask, DL, MVT::i32)); 8693 } 8694 } 8695 } 8696 8697 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8698 std::swap(LHS, RHS); 8699 8700 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8701 RHS.hasOneUse()) { 8702 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8703 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8704 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8705 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8706 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8707 (RHS.getOperand(0) == LHS.getOperand(0) && 8708 LHS.getOperand(0) == LHS.getOperand(1))) { 8709 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8710 unsigned NewMask = LCC == ISD::SETO ? 8711 Mask->getZExtValue() & ~OrdMask : 8712 Mask->getZExtValue() & OrdMask; 8713 8714 SDLoc DL(N); 8715 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8716 DAG.getConstant(NewMask, DL, MVT::i32)); 8717 } 8718 } 8719 8720 if (VT == MVT::i32 && 8721 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8722 // and x, (sext cc from i1) => select cc, x, 0 8723 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8724 std::swap(LHS, RHS); 8725 if (isBoolSGPR(RHS.getOperand(0))) 8726 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8727 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8728 } 8729 8730 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8731 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8732 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8733 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8734 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8735 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8736 if (LHSMask != ~0u && RHSMask != ~0u) { 8737 // Canonicalize the expression in an attempt to have fewer unique masks 8738 // and therefore fewer registers used to hold the masks. 8739 if (LHSMask > RHSMask) { 8740 std::swap(LHSMask, RHSMask); 8741 std::swap(LHS, RHS); 8742 } 8743 8744 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8745 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8746 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8747 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8748 8749 // Check of we need to combine values from two sources within a byte. 8750 if (!(LHSUsedLanes & RHSUsedLanes) && 8751 // If we select high and lower word keep it for SDWA. 8752 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8753 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8754 // Each byte in each mask is either selector mask 0-3, or has higher 8755 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8756 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8757 // mask which is not 0xff wins. By anding both masks we have a correct 8758 // result except that 0x0c shall be corrected to give 0x0c only. 8759 uint32_t Mask = LHSMask & RHSMask; 8760 for (unsigned I = 0; I < 32; I += 8) { 8761 uint32_t ByteSel = 0xff << I; 8762 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8763 Mask &= (0x0c << I) & 0xffffffff; 8764 } 8765 8766 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8767 // or 0x0c. 8768 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8769 SDLoc DL(N); 8770 8771 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8772 LHS.getOperand(0), RHS.getOperand(0), 8773 DAG.getConstant(Sel, DL, MVT::i32)); 8774 } 8775 } 8776 } 8777 8778 return SDValue(); 8779 } 8780 8781 SDValue SITargetLowering::performOrCombine(SDNode *N, 8782 DAGCombinerInfo &DCI) const { 8783 SelectionDAG &DAG = DCI.DAG; 8784 SDValue LHS = N->getOperand(0); 8785 SDValue RHS = N->getOperand(1); 8786 8787 EVT VT = N->getValueType(0); 8788 if (VT == MVT::i1) { 8789 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8790 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8791 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8792 SDValue Src = LHS.getOperand(0); 8793 if (Src != RHS.getOperand(0)) 8794 return SDValue(); 8795 8796 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8797 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8798 if (!CLHS || !CRHS) 8799 return SDValue(); 8800 8801 // Only 10 bits are used. 8802 static const uint32_t MaxMask = 0x3ff; 8803 8804 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8805 SDLoc DL(N); 8806 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8807 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8808 } 8809 8810 return SDValue(); 8811 } 8812 8813 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8814 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8815 LHS.getOpcode() == AMDGPUISD::PERM && 8816 isa<ConstantSDNode>(LHS.getOperand(2))) { 8817 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8818 if (!Sel) 8819 return SDValue(); 8820 8821 Sel |= LHS.getConstantOperandVal(2); 8822 SDLoc DL(N); 8823 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8824 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8825 } 8826 8827 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8828 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8829 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8830 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8831 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8832 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8833 if (LHSMask != ~0u && RHSMask != ~0u) { 8834 // Canonicalize the expression in an attempt to have fewer unique masks 8835 // and therefore fewer registers used to hold the masks. 8836 if (LHSMask > RHSMask) { 8837 std::swap(LHSMask, RHSMask); 8838 std::swap(LHS, RHS); 8839 } 8840 8841 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8842 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8843 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8844 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8845 8846 // Check of we need to combine values from two sources within a byte. 8847 if (!(LHSUsedLanes & RHSUsedLanes) && 8848 // If we select high and lower word keep it for SDWA. 8849 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8850 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8851 // Kill zero bytes selected by other mask. Zero value is 0xc. 8852 LHSMask &= ~RHSUsedLanes; 8853 RHSMask &= ~LHSUsedLanes; 8854 // Add 4 to each active LHS lane 8855 LHSMask |= LHSUsedLanes & 0x04040404; 8856 // Combine masks 8857 uint32_t Sel = LHSMask | RHSMask; 8858 SDLoc DL(N); 8859 8860 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8861 LHS.getOperand(0), RHS.getOperand(0), 8862 DAG.getConstant(Sel, DL, MVT::i32)); 8863 } 8864 } 8865 } 8866 8867 if (VT != MVT::i64) 8868 return SDValue(); 8869 8870 // TODO: This could be a generic combine with a predicate for extracting the 8871 // high half of an integer being free. 8872 8873 // (or i64:x, (zero_extend i32:y)) -> 8874 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8875 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8876 RHS.getOpcode() != ISD::ZERO_EXTEND) 8877 std::swap(LHS, RHS); 8878 8879 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8880 SDValue ExtSrc = RHS.getOperand(0); 8881 EVT SrcVT = ExtSrc.getValueType(); 8882 if (SrcVT == MVT::i32) { 8883 SDLoc SL(N); 8884 SDValue LowLHS, HiBits; 8885 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 8886 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 8887 8888 DCI.AddToWorklist(LowOr.getNode()); 8889 DCI.AddToWorklist(HiBits.getNode()); 8890 8891 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 8892 LowOr, HiBits); 8893 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 8894 } 8895 } 8896 8897 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8898 if (CRHS) { 8899 if (SDValue Split 8900 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 8901 return Split; 8902 } 8903 8904 return SDValue(); 8905 } 8906 8907 SDValue SITargetLowering::performXorCombine(SDNode *N, 8908 DAGCombinerInfo &DCI) const { 8909 EVT VT = N->getValueType(0); 8910 if (VT != MVT::i64) 8911 return SDValue(); 8912 8913 SDValue LHS = N->getOperand(0); 8914 SDValue RHS = N->getOperand(1); 8915 8916 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8917 if (CRHS) { 8918 if (SDValue Split 8919 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 8920 return Split; 8921 } 8922 8923 return SDValue(); 8924 } 8925 8926 // Instructions that will be lowered with a final instruction that zeros the 8927 // high result bits. 8928 // XXX - probably only need to list legal operations. 8929 static bool fp16SrcZerosHighBits(unsigned Opc) { 8930 switch (Opc) { 8931 case ISD::FADD: 8932 case ISD::FSUB: 8933 case ISD::FMUL: 8934 case ISD::FDIV: 8935 case ISD::FREM: 8936 case ISD::FMA: 8937 case ISD::FMAD: 8938 case ISD::FCANONICALIZE: 8939 case ISD::FP_ROUND: 8940 case ISD::UINT_TO_FP: 8941 case ISD::SINT_TO_FP: 8942 case ISD::FABS: 8943 // Fabs is lowered to a bit operation, but it's an and which will clear the 8944 // high bits anyway. 8945 case ISD::FSQRT: 8946 case ISD::FSIN: 8947 case ISD::FCOS: 8948 case ISD::FPOWI: 8949 case ISD::FPOW: 8950 case ISD::FLOG: 8951 case ISD::FLOG2: 8952 case ISD::FLOG10: 8953 case ISD::FEXP: 8954 case ISD::FEXP2: 8955 case ISD::FCEIL: 8956 case ISD::FTRUNC: 8957 case ISD::FRINT: 8958 case ISD::FNEARBYINT: 8959 case ISD::FROUND: 8960 case ISD::FFLOOR: 8961 case ISD::FMINNUM: 8962 case ISD::FMAXNUM: 8963 case AMDGPUISD::FRACT: 8964 case AMDGPUISD::CLAMP: 8965 case AMDGPUISD::COS_HW: 8966 case AMDGPUISD::SIN_HW: 8967 case AMDGPUISD::FMIN3: 8968 case AMDGPUISD::FMAX3: 8969 case AMDGPUISD::FMED3: 8970 case AMDGPUISD::FMAD_FTZ: 8971 case AMDGPUISD::RCP: 8972 case AMDGPUISD::RSQ: 8973 case AMDGPUISD::RCP_IFLAG: 8974 case AMDGPUISD::LDEXP: 8975 return true; 8976 default: 8977 // fcopysign, select and others may be lowered to 32-bit bit operations 8978 // which don't zero the high bits. 8979 return false; 8980 } 8981 } 8982 8983 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 8984 DAGCombinerInfo &DCI) const { 8985 if (!Subtarget->has16BitInsts() || 8986 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8987 return SDValue(); 8988 8989 EVT VT = N->getValueType(0); 8990 if (VT != MVT::i32) 8991 return SDValue(); 8992 8993 SDValue Src = N->getOperand(0); 8994 if (Src.getValueType() != MVT::i16) 8995 return SDValue(); 8996 8997 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 8998 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 8999 if (Src.getOpcode() == ISD::BITCAST) { 9000 SDValue BCSrc = Src.getOperand(0); 9001 if (BCSrc.getValueType() == MVT::f16 && 9002 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9003 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9004 } 9005 9006 return SDValue(); 9007 } 9008 9009 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9010 DAGCombinerInfo &DCI) 9011 const { 9012 SDValue Src = N->getOperand(0); 9013 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9014 9015 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9016 VTSign->getVT() == MVT::i8) || 9017 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9018 VTSign->getVT() == MVT::i16)) && 9019 Src.hasOneUse()) { 9020 auto *M = cast<MemSDNode>(Src); 9021 SDValue Ops[] = { 9022 Src.getOperand(0), // Chain 9023 Src.getOperand(1), // rsrc 9024 Src.getOperand(2), // vindex 9025 Src.getOperand(3), // voffset 9026 Src.getOperand(4), // soffset 9027 Src.getOperand(5), // offset 9028 Src.getOperand(6), 9029 Src.getOperand(7) 9030 }; 9031 // replace with BUFFER_LOAD_BYTE/SHORT 9032 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9033 Src.getOperand(0).getValueType()); 9034 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9035 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9036 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9037 ResList, 9038 Ops, M->getMemoryVT(), 9039 M->getMemOperand()); 9040 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9041 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9042 } 9043 return SDValue(); 9044 } 9045 9046 SDValue SITargetLowering::performClassCombine(SDNode *N, 9047 DAGCombinerInfo &DCI) const { 9048 SelectionDAG &DAG = DCI.DAG; 9049 SDValue Mask = N->getOperand(1); 9050 9051 // fp_class x, 0 -> false 9052 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9053 if (CMask->isNullValue()) 9054 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9055 } 9056 9057 if (N->getOperand(0).isUndef()) 9058 return DAG.getUNDEF(MVT::i1); 9059 9060 return SDValue(); 9061 } 9062 9063 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9064 DAGCombinerInfo &DCI) const { 9065 EVT VT = N->getValueType(0); 9066 SDValue N0 = N->getOperand(0); 9067 9068 if (N0.isUndef()) 9069 return N0; 9070 9071 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9072 N0.getOpcode() == ISD::SINT_TO_FP)) { 9073 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9074 N->getFlags()); 9075 } 9076 9077 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9078 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9079 N0.getOperand(0), N->getFlags()); 9080 } 9081 9082 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9083 } 9084 9085 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9086 unsigned MaxDepth) const { 9087 unsigned Opcode = Op.getOpcode(); 9088 if (Opcode == ISD::FCANONICALIZE) 9089 return true; 9090 9091 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9092 auto F = CFP->getValueAPF(); 9093 if (F.isNaN() && F.isSignaling()) 9094 return false; 9095 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9096 } 9097 9098 // If source is a result of another standard FP operation it is already in 9099 // canonical form. 9100 if (MaxDepth == 0) 9101 return false; 9102 9103 switch (Opcode) { 9104 // These will flush denorms if required. 9105 case ISD::FADD: 9106 case ISD::FSUB: 9107 case ISD::FMUL: 9108 case ISD::FCEIL: 9109 case ISD::FFLOOR: 9110 case ISD::FMA: 9111 case ISD::FMAD: 9112 case ISD::FSQRT: 9113 case ISD::FDIV: 9114 case ISD::FREM: 9115 case ISD::FP_ROUND: 9116 case ISD::FP_EXTEND: 9117 case AMDGPUISD::FMUL_LEGACY: 9118 case AMDGPUISD::FMAD_FTZ: 9119 case AMDGPUISD::RCP: 9120 case AMDGPUISD::RSQ: 9121 case AMDGPUISD::RSQ_CLAMP: 9122 case AMDGPUISD::RCP_LEGACY: 9123 case AMDGPUISD::RCP_IFLAG: 9124 case AMDGPUISD::TRIG_PREOP: 9125 case AMDGPUISD::DIV_SCALE: 9126 case AMDGPUISD::DIV_FMAS: 9127 case AMDGPUISD::DIV_FIXUP: 9128 case AMDGPUISD::FRACT: 9129 case AMDGPUISD::LDEXP: 9130 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9131 case AMDGPUISD::CVT_F32_UBYTE0: 9132 case AMDGPUISD::CVT_F32_UBYTE1: 9133 case AMDGPUISD::CVT_F32_UBYTE2: 9134 case AMDGPUISD::CVT_F32_UBYTE3: 9135 return true; 9136 9137 // It can/will be lowered or combined as a bit operation. 9138 // Need to check their input recursively to handle. 9139 case ISD::FNEG: 9140 case ISD::FABS: 9141 case ISD::FCOPYSIGN: 9142 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9143 9144 case ISD::FSIN: 9145 case ISD::FCOS: 9146 case ISD::FSINCOS: 9147 return Op.getValueType().getScalarType() != MVT::f16; 9148 9149 case ISD::FMINNUM: 9150 case ISD::FMAXNUM: 9151 case ISD::FMINNUM_IEEE: 9152 case ISD::FMAXNUM_IEEE: 9153 case AMDGPUISD::CLAMP: 9154 case AMDGPUISD::FMED3: 9155 case AMDGPUISD::FMAX3: 9156 case AMDGPUISD::FMIN3: { 9157 // FIXME: Shouldn't treat the generic operations different based these. 9158 // However, we aren't really required to flush the result from 9159 // minnum/maxnum.. 9160 9161 // snans will be quieted, so we only need to worry about denormals. 9162 if (Subtarget->supportsMinMaxDenormModes() || 9163 denormalsEnabledForType(DAG, Op.getValueType())) 9164 return true; 9165 9166 // Flushing may be required. 9167 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9168 // targets need to check their input recursively. 9169 9170 // FIXME: Does this apply with clamp? It's implemented with max. 9171 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9172 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9173 return false; 9174 } 9175 9176 return true; 9177 } 9178 case ISD::SELECT: { 9179 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9180 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9181 } 9182 case ISD::BUILD_VECTOR: { 9183 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9184 SDValue SrcOp = Op.getOperand(i); 9185 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9186 return false; 9187 } 9188 9189 return true; 9190 } 9191 case ISD::EXTRACT_VECTOR_ELT: 9192 case ISD::EXTRACT_SUBVECTOR: { 9193 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9194 } 9195 case ISD::INSERT_VECTOR_ELT: { 9196 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9197 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9198 } 9199 case ISD::UNDEF: 9200 // Could be anything. 9201 return false; 9202 9203 case ISD::BITCAST: { 9204 // Hack round the mess we make when legalizing extract_vector_elt 9205 SDValue Src = Op.getOperand(0); 9206 if (Src.getValueType() == MVT::i16 && 9207 Src.getOpcode() == ISD::TRUNCATE) { 9208 SDValue TruncSrc = Src.getOperand(0); 9209 if (TruncSrc.getValueType() == MVT::i32 && 9210 TruncSrc.getOpcode() == ISD::BITCAST && 9211 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9212 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9213 } 9214 } 9215 9216 return false; 9217 } 9218 case ISD::INTRINSIC_WO_CHAIN: { 9219 unsigned IntrinsicID 9220 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9221 // TODO: Handle more intrinsics 9222 switch (IntrinsicID) { 9223 case Intrinsic::amdgcn_cvt_pkrtz: 9224 case Intrinsic::amdgcn_cubeid: 9225 case Intrinsic::amdgcn_frexp_mant: 9226 case Intrinsic::amdgcn_fdot2: 9227 case Intrinsic::amdgcn_rcp: 9228 case Intrinsic::amdgcn_rsq: 9229 case Intrinsic::amdgcn_rsq_clamp: 9230 case Intrinsic::amdgcn_rcp_legacy: 9231 case Intrinsic::amdgcn_rsq_legacy: 9232 return true; 9233 default: 9234 break; 9235 } 9236 9237 LLVM_FALLTHROUGH; 9238 } 9239 default: 9240 return denormalsEnabledForType(DAG, Op.getValueType()) && 9241 DAG.isKnownNeverSNaN(Op); 9242 } 9243 9244 llvm_unreachable("invalid operation"); 9245 } 9246 9247 // Constant fold canonicalize. 9248 SDValue SITargetLowering::getCanonicalConstantFP( 9249 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9250 // Flush denormals to 0 if not enabled. 9251 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9252 return DAG.getConstantFP(0.0, SL, VT); 9253 9254 if (C.isNaN()) { 9255 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9256 if (C.isSignaling()) { 9257 // Quiet a signaling NaN. 9258 // FIXME: Is this supposed to preserve payload bits? 9259 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9260 } 9261 9262 // Make sure it is the canonical NaN bitpattern. 9263 // 9264 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9265 // immediate? 9266 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9267 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9268 } 9269 9270 // Already canonical. 9271 return DAG.getConstantFP(C, SL, VT); 9272 } 9273 9274 static bool vectorEltWillFoldAway(SDValue Op) { 9275 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9276 } 9277 9278 SDValue SITargetLowering::performFCanonicalizeCombine( 9279 SDNode *N, 9280 DAGCombinerInfo &DCI) const { 9281 SelectionDAG &DAG = DCI.DAG; 9282 SDValue N0 = N->getOperand(0); 9283 EVT VT = N->getValueType(0); 9284 9285 // fcanonicalize undef -> qnan 9286 if (N0.isUndef()) { 9287 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9288 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9289 } 9290 9291 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9292 EVT VT = N->getValueType(0); 9293 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9294 } 9295 9296 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9297 // (fcanonicalize k) 9298 // 9299 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9300 9301 // TODO: This could be better with wider vectors that will be split to v2f16, 9302 // and to consider uses since there aren't that many packed operations. 9303 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9304 isTypeLegal(MVT::v2f16)) { 9305 SDLoc SL(N); 9306 SDValue NewElts[2]; 9307 SDValue Lo = N0.getOperand(0); 9308 SDValue Hi = N0.getOperand(1); 9309 EVT EltVT = Lo.getValueType(); 9310 9311 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9312 for (unsigned I = 0; I != 2; ++I) { 9313 SDValue Op = N0.getOperand(I); 9314 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9315 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9316 CFP->getValueAPF()); 9317 } else if (Op.isUndef()) { 9318 // Handled below based on what the other operand is. 9319 NewElts[I] = Op; 9320 } else { 9321 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9322 } 9323 } 9324 9325 // If one half is undef, and one is constant, perfer a splat vector rather 9326 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9327 // cheaper to use and may be free with a packed operation. 9328 if (NewElts[0].isUndef()) { 9329 if (isa<ConstantFPSDNode>(NewElts[1])) 9330 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9331 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9332 } 9333 9334 if (NewElts[1].isUndef()) { 9335 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9336 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9337 } 9338 9339 return DAG.getBuildVector(VT, SL, NewElts); 9340 } 9341 } 9342 9343 unsigned SrcOpc = N0.getOpcode(); 9344 9345 // If it's free to do so, push canonicalizes further up the source, which may 9346 // find a canonical source. 9347 // 9348 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9349 // sNaNs. 9350 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9351 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9352 if (CRHS && N0.hasOneUse()) { 9353 SDLoc SL(N); 9354 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9355 N0.getOperand(0)); 9356 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9357 DCI.AddToWorklist(Canon0.getNode()); 9358 9359 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9360 } 9361 } 9362 9363 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9364 } 9365 9366 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9367 switch (Opc) { 9368 case ISD::FMAXNUM: 9369 case ISD::FMAXNUM_IEEE: 9370 return AMDGPUISD::FMAX3; 9371 case ISD::SMAX: 9372 return AMDGPUISD::SMAX3; 9373 case ISD::UMAX: 9374 return AMDGPUISD::UMAX3; 9375 case ISD::FMINNUM: 9376 case ISD::FMINNUM_IEEE: 9377 return AMDGPUISD::FMIN3; 9378 case ISD::SMIN: 9379 return AMDGPUISD::SMIN3; 9380 case ISD::UMIN: 9381 return AMDGPUISD::UMIN3; 9382 default: 9383 llvm_unreachable("Not a min/max opcode"); 9384 } 9385 } 9386 9387 SDValue SITargetLowering::performIntMed3ImmCombine( 9388 SelectionDAG &DAG, const SDLoc &SL, 9389 SDValue Op0, SDValue Op1, bool Signed) const { 9390 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9391 if (!K1) 9392 return SDValue(); 9393 9394 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9395 if (!K0) 9396 return SDValue(); 9397 9398 if (Signed) { 9399 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9400 return SDValue(); 9401 } else { 9402 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9403 return SDValue(); 9404 } 9405 9406 EVT VT = K0->getValueType(0); 9407 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9408 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9409 return DAG.getNode(Med3Opc, SL, VT, 9410 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9411 } 9412 9413 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9414 MVT NVT = MVT::i32; 9415 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9416 9417 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9418 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9419 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9420 9421 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9422 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9423 } 9424 9425 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9426 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9427 return C; 9428 9429 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9430 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9431 return C; 9432 } 9433 9434 return nullptr; 9435 } 9436 9437 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9438 const SDLoc &SL, 9439 SDValue Op0, 9440 SDValue Op1) const { 9441 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9442 if (!K1) 9443 return SDValue(); 9444 9445 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9446 if (!K0) 9447 return SDValue(); 9448 9449 // Ordered >= (although NaN inputs should have folded away by now). 9450 if (K0->getValueAPF() > K1->getValueAPF()) 9451 return SDValue(); 9452 9453 const MachineFunction &MF = DAG.getMachineFunction(); 9454 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9455 9456 // TODO: Check IEEE bit enabled? 9457 EVT VT = Op0.getValueType(); 9458 if (Info->getMode().DX10Clamp) { 9459 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9460 // hardware fmed3 behavior converting to a min. 9461 // FIXME: Should this be allowing -0.0? 9462 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9463 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9464 } 9465 9466 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9467 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9468 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9469 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9470 // then give the other result, which is different from med3 with a NaN 9471 // input. 9472 SDValue Var = Op0.getOperand(0); 9473 if (!DAG.isKnownNeverSNaN(Var)) 9474 return SDValue(); 9475 9476 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9477 9478 if ((!K0->hasOneUse() || 9479 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9480 (!K1->hasOneUse() || 9481 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9482 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9483 Var, SDValue(K0, 0), SDValue(K1, 0)); 9484 } 9485 } 9486 9487 return SDValue(); 9488 } 9489 9490 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9491 DAGCombinerInfo &DCI) const { 9492 SelectionDAG &DAG = DCI.DAG; 9493 9494 EVT VT = N->getValueType(0); 9495 unsigned Opc = N->getOpcode(); 9496 SDValue Op0 = N->getOperand(0); 9497 SDValue Op1 = N->getOperand(1); 9498 9499 // Only do this if the inner op has one use since this will just increases 9500 // register pressure for no benefit. 9501 9502 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9503 !VT.isVector() && 9504 (VT == MVT::i32 || VT == MVT::f32 || 9505 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9506 // max(max(a, b), c) -> max3(a, b, c) 9507 // min(min(a, b), c) -> min3(a, b, c) 9508 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9509 SDLoc DL(N); 9510 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9511 DL, 9512 N->getValueType(0), 9513 Op0.getOperand(0), 9514 Op0.getOperand(1), 9515 Op1); 9516 } 9517 9518 // Try commuted. 9519 // max(a, max(b, c)) -> max3(a, b, c) 9520 // min(a, min(b, c)) -> min3(a, b, c) 9521 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9522 SDLoc DL(N); 9523 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9524 DL, 9525 N->getValueType(0), 9526 Op0, 9527 Op1.getOperand(0), 9528 Op1.getOperand(1)); 9529 } 9530 } 9531 9532 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9533 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9534 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9535 return Med3; 9536 } 9537 9538 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9539 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9540 return Med3; 9541 } 9542 9543 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9544 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9545 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9546 (Opc == AMDGPUISD::FMIN_LEGACY && 9547 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9548 (VT == MVT::f32 || VT == MVT::f64 || 9549 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9550 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9551 Op0.hasOneUse()) { 9552 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9553 return Res; 9554 } 9555 9556 return SDValue(); 9557 } 9558 9559 static bool isClampZeroToOne(SDValue A, SDValue B) { 9560 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9561 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9562 // FIXME: Should this be allowing -0.0? 9563 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9564 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9565 } 9566 } 9567 9568 return false; 9569 } 9570 9571 // FIXME: Should only worry about snans for version with chain. 9572 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9573 DAGCombinerInfo &DCI) const { 9574 EVT VT = N->getValueType(0); 9575 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9576 // NaNs. With a NaN input, the order of the operands may change the result. 9577 9578 SelectionDAG &DAG = DCI.DAG; 9579 SDLoc SL(N); 9580 9581 SDValue Src0 = N->getOperand(0); 9582 SDValue Src1 = N->getOperand(1); 9583 SDValue Src2 = N->getOperand(2); 9584 9585 if (isClampZeroToOne(Src0, Src1)) { 9586 // const_a, const_b, x -> clamp is safe in all cases including signaling 9587 // nans. 9588 // FIXME: Should this be allowing -0.0? 9589 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9590 } 9591 9592 const MachineFunction &MF = DAG.getMachineFunction(); 9593 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9594 9595 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9596 // handling no dx10-clamp? 9597 if (Info->getMode().DX10Clamp) { 9598 // If NaNs is clamped to 0, we are free to reorder the inputs. 9599 9600 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9601 std::swap(Src0, Src1); 9602 9603 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9604 std::swap(Src1, Src2); 9605 9606 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9607 std::swap(Src0, Src1); 9608 9609 if (isClampZeroToOne(Src1, Src2)) 9610 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9611 } 9612 9613 return SDValue(); 9614 } 9615 9616 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9617 DAGCombinerInfo &DCI) const { 9618 SDValue Src0 = N->getOperand(0); 9619 SDValue Src1 = N->getOperand(1); 9620 if (Src0.isUndef() && Src1.isUndef()) 9621 return DCI.DAG.getUNDEF(N->getValueType(0)); 9622 return SDValue(); 9623 } 9624 9625 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 9626 // expanded into a set of cmp/select instructions. 9627 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 9628 unsigned NumElem, 9629 bool IsDivergentIdx) { 9630 if (UseDivergentRegisterIndexing) 9631 return false; 9632 9633 unsigned VecSize = EltSize * NumElem; 9634 9635 // Sub-dword vectors of size 2 dword or less have better implementation. 9636 if (VecSize <= 64 && EltSize < 32) 9637 return false; 9638 9639 // Always expand the rest of sub-dword instructions, otherwise it will be 9640 // lowered via memory. 9641 if (EltSize < 32) 9642 return true; 9643 9644 // Always do this if var-idx is divergent, otherwise it will become a loop. 9645 if (IsDivergentIdx) 9646 return true; 9647 9648 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 9649 unsigned NumInsts = NumElem /* Number of compares */ + 9650 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 9651 return NumInsts <= 16; 9652 } 9653 9654 static bool shouldExpandVectorDynExt(SDNode *N) { 9655 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 9656 if (isa<ConstantSDNode>(Idx)) 9657 return false; 9658 9659 SDValue Vec = N->getOperand(0); 9660 EVT VecVT = Vec.getValueType(); 9661 EVT EltVT = VecVT.getVectorElementType(); 9662 unsigned EltSize = EltVT.getSizeInBits(); 9663 unsigned NumElem = VecVT.getVectorNumElements(); 9664 9665 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 9666 Idx->isDivergent()); 9667 } 9668 9669 SDValue SITargetLowering::performExtractVectorEltCombine( 9670 SDNode *N, DAGCombinerInfo &DCI) const { 9671 SDValue Vec = N->getOperand(0); 9672 SelectionDAG &DAG = DCI.DAG; 9673 9674 EVT VecVT = Vec.getValueType(); 9675 EVT EltVT = VecVT.getVectorElementType(); 9676 9677 if ((Vec.getOpcode() == ISD::FNEG || 9678 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9679 SDLoc SL(N); 9680 EVT EltVT = N->getValueType(0); 9681 SDValue Idx = N->getOperand(1); 9682 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9683 Vec.getOperand(0), Idx); 9684 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9685 } 9686 9687 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9688 // => 9689 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9690 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9691 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9692 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9693 SDLoc SL(N); 9694 EVT EltVT = N->getValueType(0); 9695 SDValue Idx = N->getOperand(1); 9696 unsigned Opc = Vec.getOpcode(); 9697 9698 switch(Opc) { 9699 default: 9700 break; 9701 // TODO: Support other binary operations. 9702 case ISD::FADD: 9703 case ISD::FSUB: 9704 case ISD::FMUL: 9705 case ISD::ADD: 9706 case ISD::UMIN: 9707 case ISD::UMAX: 9708 case ISD::SMIN: 9709 case ISD::SMAX: 9710 case ISD::FMAXNUM: 9711 case ISD::FMINNUM: 9712 case ISD::FMAXNUM_IEEE: 9713 case ISD::FMINNUM_IEEE: { 9714 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9715 Vec.getOperand(0), Idx); 9716 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9717 Vec.getOperand(1), Idx); 9718 9719 DCI.AddToWorklist(Elt0.getNode()); 9720 DCI.AddToWorklist(Elt1.getNode()); 9721 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9722 } 9723 } 9724 } 9725 9726 unsigned VecSize = VecVT.getSizeInBits(); 9727 unsigned EltSize = EltVT.getSizeInBits(); 9728 9729 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9730 if (::shouldExpandVectorDynExt(N)) { 9731 SDLoc SL(N); 9732 SDValue Idx = N->getOperand(1); 9733 SDValue V; 9734 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9735 SDValue IC = DAG.getVectorIdxConstant(I, SL); 9736 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9737 if (I == 0) 9738 V = Elt; 9739 else 9740 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9741 } 9742 return V; 9743 } 9744 9745 if (!DCI.isBeforeLegalize()) 9746 return SDValue(); 9747 9748 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9749 // elements. This exposes more load reduction opportunities by replacing 9750 // multiple small extract_vector_elements with a single 32-bit extract. 9751 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9752 if (isa<MemSDNode>(Vec) && 9753 EltSize <= 16 && 9754 EltVT.isByteSized() && 9755 VecSize > 32 && 9756 VecSize % 32 == 0 && 9757 Idx) { 9758 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9759 9760 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9761 unsigned EltIdx = BitIndex / 32; 9762 unsigned LeftoverBitIdx = BitIndex % 32; 9763 SDLoc SL(N); 9764 9765 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9766 DCI.AddToWorklist(Cast.getNode()); 9767 9768 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9769 DAG.getConstant(EltIdx, SL, MVT::i32)); 9770 DCI.AddToWorklist(Elt.getNode()); 9771 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9772 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9773 DCI.AddToWorklist(Srl.getNode()); 9774 9775 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9776 DCI.AddToWorklist(Trunc.getNode()); 9777 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9778 } 9779 9780 return SDValue(); 9781 } 9782 9783 SDValue 9784 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9785 DAGCombinerInfo &DCI) const { 9786 SDValue Vec = N->getOperand(0); 9787 SDValue Idx = N->getOperand(2); 9788 EVT VecVT = Vec.getValueType(); 9789 EVT EltVT = VecVT.getVectorElementType(); 9790 9791 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9792 // => BUILD_VECTOR n x select (e, const-idx) 9793 if (!::shouldExpandVectorDynExt(N)) 9794 return SDValue(); 9795 9796 SelectionDAG &DAG = DCI.DAG; 9797 SDLoc SL(N); 9798 SDValue Ins = N->getOperand(1); 9799 EVT IdxVT = Idx.getValueType(); 9800 9801 SmallVector<SDValue, 16> Ops; 9802 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9803 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9804 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9805 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9806 Ops.push_back(V); 9807 } 9808 9809 return DAG.getBuildVector(VecVT, SL, Ops); 9810 } 9811 9812 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9813 const SDNode *N0, 9814 const SDNode *N1) const { 9815 EVT VT = N0->getValueType(0); 9816 9817 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9818 // support denormals ever. 9819 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9820 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9821 getSubtarget()->hasMadF16())) && 9822 isOperationLegal(ISD::FMAD, VT)) 9823 return ISD::FMAD; 9824 9825 const TargetOptions &Options = DAG.getTarget().Options; 9826 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9827 (N0->getFlags().hasAllowContract() && 9828 N1->getFlags().hasAllowContract())) && 9829 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 9830 return ISD::FMA; 9831 } 9832 9833 return 0; 9834 } 9835 9836 // For a reassociatable opcode perform: 9837 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9838 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9839 SelectionDAG &DAG) const { 9840 EVT VT = N->getValueType(0); 9841 if (VT != MVT::i32 && VT != MVT::i64) 9842 return SDValue(); 9843 9844 unsigned Opc = N->getOpcode(); 9845 SDValue Op0 = N->getOperand(0); 9846 SDValue Op1 = N->getOperand(1); 9847 9848 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9849 return SDValue(); 9850 9851 if (Op0->isDivergent()) 9852 std::swap(Op0, Op1); 9853 9854 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9855 return SDValue(); 9856 9857 SDValue Op2 = Op1.getOperand(1); 9858 Op1 = Op1.getOperand(0); 9859 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9860 return SDValue(); 9861 9862 if (Op1->isDivergent()) 9863 std::swap(Op1, Op2); 9864 9865 // If either operand is constant this will conflict with 9866 // DAGCombiner::ReassociateOps(). 9867 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9868 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9869 return SDValue(); 9870 9871 SDLoc SL(N); 9872 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9873 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9874 } 9875 9876 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9877 EVT VT, 9878 SDValue N0, SDValue N1, SDValue N2, 9879 bool Signed) { 9880 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9881 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9882 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 9883 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 9884 } 9885 9886 SDValue SITargetLowering::performAddCombine(SDNode *N, 9887 DAGCombinerInfo &DCI) const { 9888 SelectionDAG &DAG = DCI.DAG; 9889 EVT VT = N->getValueType(0); 9890 SDLoc SL(N); 9891 SDValue LHS = N->getOperand(0); 9892 SDValue RHS = N->getOperand(1); 9893 9894 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 9895 && Subtarget->hasMad64_32() && 9896 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 9897 VT.getScalarSizeInBits() <= 64) { 9898 if (LHS.getOpcode() != ISD::MUL) 9899 std::swap(LHS, RHS); 9900 9901 SDValue MulLHS = LHS.getOperand(0); 9902 SDValue MulRHS = LHS.getOperand(1); 9903 SDValue AddRHS = RHS; 9904 9905 // TODO: Maybe restrict if SGPR inputs. 9906 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 9907 numBitsUnsigned(MulRHS, DAG) <= 32) { 9908 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 9909 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 9910 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 9911 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 9912 } 9913 9914 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 9915 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 9916 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 9917 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 9918 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 9919 } 9920 9921 return SDValue(); 9922 } 9923 9924 if (SDValue V = reassociateScalarOps(N, DAG)) { 9925 return V; 9926 } 9927 9928 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 9929 return SDValue(); 9930 9931 // add x, zext (setcc) => addcarry x, 0, setcc 9932 // add x, sext (setcc) => subcarry x, 0, setcc 9933 unsigned Opc = LHS.getOpcode(); 9934 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9935 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 9936 std::swap(RHS, LHS); 9937 9938 Opc = RHS.getOpcode(); 9939 switch (Opc) { 9940 default: break; 9941 case ISD::ZERO_EXTEND: 9942 case ISD::SIGN_EXTEND: 9943 case ISD::ANY_EXTEND: { 9944 auto Cond = RHS.getOperand(0); 9945 // If this won't be a real VOPC output, we would still need to insert an 9946 // extra instruction anyway. 9947 if (!isBoolSGPR(Cond)) 9948 break; 9949 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9950 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9951 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9952 return DAG.getNode(Opc, SL, VTList, Args); 9953 } 9954 case ISD::ADDCARRY: { 9955 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 9956 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9957 if (!C || C->getZExtValue() != 0) break; 9958 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 9959 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 9960 } 9961 } 9962 return SDValue(); 9963 } 9964 9965 SDValue SITargetLowering::performSubCombine(SDNode *N, 9966 DAGCombinerInfo &DCI) const { 9967 SelectionDAG &DAG = DCI.DAG; 9968 EVT VT = N->getValueType(0); 9969 9970 if (VT != MVT::i32) 9971 return SDValue(); 9972 9973 SDLoc SL(N); 9974 SDValue LHS = N->getOperand(0); 9975 SDValue RHS = N->getOperand(1); 9976 9977 // sub x, zext (setcc) => subcarry x, 0, setcc 9978 // sub x, sext (setcc) => addcarry x, 0, setcc 9979 unsigned Opc = RHS.getOpcode(); 9980 switch (Opc) { 9981 default: break; 9982 case ISD::ZERO_EXTEND: 9983 case ISD::SIGN_EXTEND: 9984 case ISD::ANY_EXTEND: { 9985 auto Cond = RHS.getOperand(0); 9986 // If this won't be a real VOPC output, we would still need to insert an 9987 // extra instruction anyway. 9988 if (!isBoolSGPR(Cond)) 9989 break; 9990 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9991 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9992 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 9993 return DAG.getNode(Opc, SL, VTList, Args); 9994 } 9995 } 9996 9997 if (LHS.getOpcode() == ISD::SUBCARRY) { 9998 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 9999 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10000 if (!C || !C->isNullValue()) 10001 return SDValue(); 10002 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10003 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10004 } 10005 return SDValue(); 10006 } 10007 10008 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10009 DAGCombinerInfo &DCI) const { 10010 10011 if (N->getValueType(0) != MVT::i32) 10012 return SDValue(); 10013 10014 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10015 if (!C || C->getZExtValue() != 0) 10016 return SDValue(); 10017 10018 SelectionDAG &DAG = DCI.DAG; 10019 SDValue LHS = N->getOperand(0); 10020 10021 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10022 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10023 unsigned LHSOpc = LHS.getOpcode(); 10024 unsigned Opc = N->getOpcode(); 10025 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10026 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10027 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10028 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10029 } 10030 return SDValue(); 10031 } 10032 10033 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10034 DAGCombinerInfo &DCI) const { 10035 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10036 return SDValue(); 10037 10038 SelectionDAG &DAG = DCI.DAG; 10039 EVT VT = N->getValueType(0); 10040 10041 SDLoc SL(N); 10042 SDValue LHS = N->getOperand(0); 10043 SDValue RHS = N->getOperand(1); 10044 10045 // These should really be instruction patterns, but writing patterns with 10046 // source modiifiers is a pain. 10047 10048 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10049 if (LHS.getOpcode() == ISD::FADD) { 10050 SDValue A = LHS.getOperand(0); 10051 if (A == LHS.getOperand(1)) { 10052 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10053 if (FusedOp != 0) { 10054 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10055 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10056 } 10057 } 10058 } 10059 10060 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10061 if (RHS.getOpcode() == ISD::FADD) { 10062 SDValue A = RHS.getOperand(0); 10063 if (A == RHS.getOperand(1)) { 10064 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10065 if (FusedOp != 0) { 10066 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10067 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10068 } 10069 } 10070 } 10071 10072 return SDValue(); 10073 } 10074 10075 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10076 DAGCombinerInfo &DCI) const { 10077 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10078 return SDValue(); 10079 10080 SelectionDAG &DAG = DCI.DAG; 10081 SDLoc SL(N); 10082 EVT VT = N->getValueType(0); 10083 assert(!VT.isVector()); 10084 10085 // Try to get the fneg to fold into the source modifier. This undoes generic 10086 // DAG combines and folds them into the mad. 10087 // 10088 // Only do this if we are not trying to support denormals. v_mad_f32 does 10089 // not support denormals ever. 10090 SDValue LHS = N->getOperand(0); 10091 SDValue RHS = N->getOperand(1); 10092 if (LHS.getOpcode() == ISD::FADD) { 10093 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10094 SDValue A = LHS.getOperand(0); 10095 if (A == LHS.getOperand(1)) { 10096 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10097 if (FusedOp != 0){ 10098 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10099 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10100 10101 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10102 } 10103 } 10104 } 10105 10106 if (RHS.getOpcode() == ISD::FADD) { 10107 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10108 10109 SDValue A = RHS.getOperand(0); 10110 if (A == RHS.getOperand(1)) { 10111 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10112 if (FusedOp != 0){ 10113 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10114 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10115 } 10116 } 10117 } 10118 10119 return SDValue(); 10120 } 10121 10122 SDValue SITargetLowering::performFMACombine(SDNode *N, 10123 DAGCombinerInfo &DCI) const { 10124 SelectionDAG &DAG = DCI.DAG; 10125 EVT VT = N->getValueType(0); 10126 SDLoc SL(N); 10127 10128 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 10129 return SDValue(); 10130 10131 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10132 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10133 SDValue Op1 = N->getOperand(0); 10134 SDValue Op2 = N->getOperand(1); 10135 SDValue FMA = N->getOperand(2); 10136 10137 if (FMA.getOpcode() != ISD::FMA || 10138 Op1.getOpcode() != ISD::FP_EXTEND || 10139 Op2.getOpcode() != ISD::FP_EXTEND) 10140 return SDValue(); 10141 10142 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10143 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10144 // is sufficient to allow generaing fdot2. 10145 const TargetOptions &Options = DAG.getTarget().Options; 10146 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10147 (N->getFlags().hasAllowContract() && 10148 FMA->getFlags().hasAllowContract())) { 10149 Op1 = Op1.getOperand(0); 10150 Op2 = Op2.getOperand(0); 10151 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10152 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10153 return SDValue(); 10154 10155 SDValue Vec1 = Op1.getOperand(0); 10156 SDValue Idx1 = Op1.getOperand(1); 10157 SDValue Vec2 = Op2.getOperand(0); 10158 10159 SDValue FMAOp1 = FMA.getOperand(0); 10160 SDValue FMAOp2 = FMA.getOperand(1); 10161 SDValue FMAAcc = FMA.getOperand(2); 10162 10163 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10164 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10165 return SDValue(); 10166 10167 FMAOp1 = FMAOp1.getOperand(0); 10168 FMAOp2 = FMAOp2.getOperand(0); 10169 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10170 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10171 return SDValue(); 10172 10173 SDValue Vec3 = FMAOp1.getOperand(0); 10174 SDValue Vec4 = FMAOp2.getOperand(0); 10175 SDValue Idx2 = FMAOp1.getOperand(1); 10176 10177 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10178 // Idx1 and Idx2 cannot be the same. 10179 Idx1 == Idx2) 10180 return SDValue(); 10181 10182 if (Vec1 == Vec2 || Vec3 == Vec4) 10183 return SDValue(); 10184 10185 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10186 return SDValue(); 10187 10188 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10189 (Vec1 == Vec4 && Vec2 == Vec3)) { 10190 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10191 DAG.getTargetConstant(0, SL, MVT::i1)); 10192 } 10193 } 10194 return SDValue(); 10195 } 10196 10197 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10198 DAGCombinerInfo &DCI) const { 10199 SelectionDAG &DAG = DCI.DAG; 10200 SDLoc SL(N); 10201 10202 SDValue LHS = N->getOperand(0); 10203 SDValue RHS = N->getOperand(1); 10204 EVT VT = LHS.getValueType(); 10205 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10206 10207 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10208 if (!CRHS) { 10209 CRHS = dyn_cast<ConstantSDNode>(LHS); 10210 if (CRHS) { 10211 std::swap(LHS, RHS); 10212 CC = getSetCCSwappedOperands(CC); 10213 } 10214 } 10215 10216 if (CRHS) { 10217 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10218 isBoolSGPR(LHS.getOperand(0))) { 10219 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10220 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10221 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10222 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10223 if ((CRHS->isAllOnesValue() && 10224 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10225 (CRHS->isNullValue() && 10226 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10227 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10228 DAG.getConstant(-1, SL, MVT::i1)); 10229 if ((CRHS->isAllOnesValue() && 10230 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10231 (CRHS->isNullValue() && 10232 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10233 return LHS.getOperand(0); 10234 } 10235 10236 uint64_t CRHSVal = CRHS->getZExtValue(); 10237 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10238 LHS.getOpcode() == ISD::SELECT && 10239 isa<ConstantSDNode>(LHS.getOperand(1)) && 10240 isa<ConstantSDNode>(LHS.getOperand(2)) && 10241 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10242 isBoolSGPR(LHS.getOperand(0))) { 10243 // Given CT != FT: 10244 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10245 // setcc (select cc, CT, CF), CF, ne => cc 10246 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10247 // setcc (select cc, CT, CF), CT, eq => cc 10248 uint64_t CT = LHS.getConstantOperandVal(1); 10249 uint64_t CF = LHS.getConstantOperandVal(2); 10250 10251 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10252 (CT == CRHSVal && CC == ISD::SETNE)) 10253 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10254 DAG.getConstant(-1, SL, MVT::i1)); 10255 if ((CF == CRHSVal && CC == ISD::SETNE) || 10256 (CT == CRHSVal && CC == ISD::SETEQ)) 10257 return LHS.getOperand(0); 10258 } 10259 } 10260 10261 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10262 VT != MVT::f16)) 10263 return SDValue(); 10264 10265 // Match isinf/isfinite pattern 10266 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10267 // (fcmp one (fabs x), inf) -> (fp_class x, 10268 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10269 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10270 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10271 if (!CRHS) 10272 return SDValue(); 10273 10274 const APFloat &APF = CRHS->getValueAPF(); 10275 if (APF.isInfinity() && !APF.isNegative()) { 10276 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10277 SIInstrFlags::N_INFINITY; 10278 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10279 SIInstrFlags::P_ZERO | 10280 SIInstrFlags::N_NORMAL | 10281 SIInstrFlags::P_NORMAL | 10282 SIInstrFlags::N_SUBNORMAL | 10283 SIInstrFlags::P_SUBNORMAL; 10284 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10285 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10286 DAG.getConstant(Mask, SL, MVT::i32)); 10287 } 10288 } 10289 10290 return SDValue(); 10291 } 10292 10293 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10294 DAGCombinerInfo &DCI) const { 10295 SelectionDAG &DAG = DCI.DAG; 10296 SDLoc SL(N); 10297 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10298 10299 SDValue Src = N->getOperand(0); 10300 SDValue Shift = N->getOperand(0); 10301 10302 // TODO: Extend type shouldn't matter (assuming legal types). 10303 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10304 Shift = Shift.getOperand(0); 10305 10306 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10307 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10308 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10309 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10310 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10311 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10312 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10313 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10314 SDLoc(Shift.getOperand(0)), MVT::i32); 10315 10316 unsigned ShiftOffset = 8 * Offset; 10317 if (Shift.getOpcode() == ISD::SHL) 10318 ShiftOffset -= C->getZExtValue(); 10319 else 10320 ShiftOffset += C->getZExtValue(); 10321 10322 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10323 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10324 MVT::f32, Shift); 10325 } 10326 } 10327 } 10328 10329 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10330 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10331 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10332 // We simplified Src. If this node is not dead, visit it again so it is 10333 // folded properly. 10334 if (N->getOpcode() != ISD::DELETED_NODE) 10335 DCI.AddToWorklist(N); 10336 return SDValue(N, 0); 10337 } 10338 10339 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10340 if (SDValue DemandedSrc = 10341 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10342 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10343 10344 return SDValue(); 10345 } 10346 10347 SDValue SITargetLowering::performClampCombine(SDNode *N, 10348 DAGCombinerInfo &DCI) const { 10349 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10350 if (!CSrc) 10351 return SDValue(); 10352 10353 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10354 const APFloat &F = CSrc->getValueAPF(); 10355 APFloat Zero = APFloat::getZero(F.getSemantics()); 10356 if (F < Zero || 10357 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10358 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10359 } 10360 10361 APFloat One(F.getSemantics(), "1.0"); 10362 if (F > One) 10363 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10364 10365 return SDValue(CSrc, 0); 10366 } 10367 10368 10369 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10370 DAGCombinerInfo &DCI) const { 10371 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10372 return SDValue(); 10373 switch (N->getOpcode()) { 10374 default: 10375 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10376 case ISD::ADD: 10377 return performAddCombine(N, DCI); 10378 case ISD::SUB: 10379 return performSubCombine(N, DCI); 10380 case ISD::ADDCARRY: 10381 case ISD::SUBCARRY: 10382 return performAddCarrySubCarryCombine(N, DCI); 10383 case ISD::FADD: 10384 return performFAddCombine(N, DCI); 10385 case ISD::FSUB: 10386 return performFSubCombine(N, DCI); 10387 case ISD::SETCC: 10388 return performSetCCCombine(N, DCI); 10389 case ISD::FMAXNUM: 10390 case ISD::FMINNUM: 10391 case ISD::FMAXNUM_IEEE: 10392 case ISD::FMINNUM_IEEE: 10393 case ISD::SMAX: 10394 case ISD::SMIN: 10395 case ISD::UMAX: 10396 case ISD::UMIN: 10397 case AMDGPUISD::FMIN_LEGACY: 10398 case AMDGPUISD::FMAX_LEGACY: 10399 return performMinMaxCombine(N, DCI); 10400 case ISD::FMA: 10401 return performFMACombine(N, DCI); 10402 case ISD::LOAD: { 10403 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10404 return Widended; 10405 LLVM_FALLTHROUGH; 10406 } 10407 case ISD::STORE: 10408 case ISD::ATOMIC_LOAD: 10409 case ISD::ATOMIC_STORE: 10410 case ISD::ATOMIC_CMP_SWAP: 10411 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 10412 case ISD::ATOMIC_SWAP: 10413 case ISD::ATOMIC_LOAD_ADD: 10414 case ISD::ATOMIC_LOAD_SUB: 10415 case ISD::ATOMIC_LOAD_AND: 10416 case ISD::ATOMIC_LOAD_OR: 10417 case ISD::ATOMIC_LOAD_XOR: 10418 case ISD::ATOMIC_LOAD_NAND: 10419 case ISD::ATOMIC_LOAD_MIN: 10420 case ISD::ATOMIC_LOAD_MAX: 10421 case ISD::ATOMIC_LOAD_UMIN: 10422 case ISD::ATOMIC_LOAD_UMAX: 10423 case ISD::ATOMIC_LOAD_FADD: 10424 case AMDGPUISD::ATOMIC_INC: 10425 case AMDGPUISD::ATOMIC_DEC: 10426 case AMDGPUISD::ATOMIC_LOAD_FMIN: 10427 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 10428 if (DCI.isBeforeLegalize()) 10429 break; 10430 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 10431 case ISD::AND: 10432 return performAndCombine(N, DCI); 10433 case ISD::OR: 10434 return performOrCombine(N, DCI); 10435 case ISD::XOR: 10436 return performXorCombine(N, DCI); 10437 case ISD::ZERO_EXTEND: 10438 return performZeroExtendCombine(N, DCI); 10439 case ISD::SIGN_EXTEND_INREG: 10440 return performSignExtendInRegCombine(N , DCI); 10441 case AMDGPUISD::FP_CLASS: 10442 return performClassCombine(N, DCI); 10443 case ISD::FCANONICALIZE: 10444 return performFCanonicalizeCombine(N, DCI); 10445 case AMDGPUISD::RCP: 10446 return performRcpCombine(N, DCI); 10447 case AMDGPUISD::FRACT: 10448 case AMDGPUISD::RSQ: 10449 case AMDGPUISD::RCP_LEGACY: 10450 case AMDGPUISD::RCP_IFLAG: 10451 case AMDGPUISD::RSQ_CLAMP: 10452 case AMDGPUISD::LDEXP: { 10453 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10454 SDValue Src = N->getOperand(0); 10455 if (Src.isUndef()) 10456 return Src; 10457 break; 10458 } 10459 case ISD::SINT_TO_FP: 10460 case ISD::UINT_TO_FP: 10461 return performUCharToFloatCombine(N, DCI); 10462 case AMDGPUISD::CVT_F32_UBYTE0: 10463 case AMDGPUISD::CVT_F32_UBYTE1: 10464 case AMDGPUISD::CVT_F32_UBYTE2: 10465 case AMDGPUISD::CVT_F32_UBYTE3: 10466 return performCvtF32UByteNCombine(N, DCI); 10467 case AMDGPUISD::FMED3: 10468 return performFMed3Combine(N, DCI); 10469 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10470 return performCvtPkRTZCombine(N, DCI); 10471 case AMDGPUISD::CLAMP: 10472 return performClampCombine(N, DCI); 10473 case ISD::SCALAR_TO_VECTOR: { 10474 SelectionDAG &DAG = DCI.DAG; 10475 EVT VT = N->getValueType(0); 10476 10477 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10478 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10479 SDLoc SL(N); 10480 SDValue Src = N->getOperand(0); 10481 EVT EltVT = Src.getValueType(); 10482 if (EltVT == MVT::f16) 10483 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10484 10485 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10486 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10487 } 10488 10489 break; 10490 } 10491 case ISD::EXTRACT_VECTOR_ELT: 10492 return performExtractVectorEltCombine(N, DCI); 10493 case ISD::INSERT_VECTOR_ELT: 10494 return performInsertVectorEltCombine(N, DCI); 10495 } 10496 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10497 } 10498 10499 /// Helper function for adjustWritemask 10500 static unsigned SubIdx2Lane(unsigned Idx) { 10501 switch (Idx) { 10502 default: return 0; 10503 case AMDGPU::sub0: return 0; 10504 case AMDGPU::sub1: return 1; 10505 case AMDGPU::sub2: return 2; 10506 case AMDGPU::sub3: return 3; 10507 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10508 } 10509 } 10510 10511 /// Adjust the writemask of MIMG instructions 10512 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10513 SelectionDAG &DAG) const { 10514 unsigned Opcode = Node->getMachineOpcode(); 10515 10516 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10517 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10518 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10519 return Node; // not implemented for D16 10520 10521 SDNode *Users[5] = { nullptr }; 10522 unsigned Lane = 0; 10523 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10524 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10525 unsigned NewDmask = 0; 10526 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10527 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10528 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10529 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10530 unsigned TFCLane = 0; 10531 bool HasChain = Node->getNumValues() > 1; 10532 10533 if (OldDmask == 0) { 10534 // These are folded out, but on the chance it happens don't assert. 10535 return Node; 10536 } 10537 10538 unsigned OldBitsSet = countPopulation(OldDmask); 10539 // Work out which is the TFE/LWE lane if that is enabled. 10540 if (UsesTFC) { 10541 TFCLane = OldBitsSet; 10542 } 10543 10544 // Try to figure out the used register components 10545 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10546 I != E; ++I) { 10547 10548 // Don't look at users of the chain. 10549 if (I.getUse().getResNo() != 0) 10550 continue; 10551 10552 // Abort if we can't understand the usage 10553 if (!I->isMachineOpcode() || 10554 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10555 return Node; 10556 10557 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10558 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10559 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10560 // set, etc. 10561 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10562 10563 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10564 if (UsesTFC && Lane == TFCLane) { 10565 Users[Lane] = *I; 10566 } else { 10567 // Set which texture component corresponds to the lane. 10568 unsigned Comp; 10569 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10570 Comp = countTrailingZeros(Dmask); 10571 Dmask &= ~(1 << Comp); 10572 } 10573 10574 // Abort if we have more than one user per component. 10575 if (Users[Lane]) 10576 return Node; 10577 10578 Users[Lane] = *I; 10579 NewDmask |= 1 << Comp; 10580 } 10581 } 10582 10583 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10584 bool NoChannels = !NewDmask; 10585 if (NoChannels) { 10586 if (!UsesTFC) { 10587 // No uses of the result and not using TFC. Then do nothing. 10588 return Node; 10589 } 10590 // If the original dmask has one channel - then nothing to do 10591 if (OldBitsSet == 1) 10592 return Node; 10593 // Use an arbitrary dmask - required for the instruction to work 10594 NewDmask = 1; 10595 } 10596 // Abort if there's no change 10597 if (NewDmask == OldDmask) 10598 return Node; 10599 10600 unsigned BitsSet = countPopulation(NewDmask); 10601 10602 // Check for TFE or LWE - increase the number of channels by one to account 10603 // for the extra return value 10604 // This will need adjustment for D16 if this is also included in 10605 // adjustWriteMask (this function) but at present D16 are excluded. 10606 unsigned NewChannels = BitsSet + UsesTFC; 10607 10608 int NewOpcode = 10609 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10610 assert(NewOpcode != -1 && 10611 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10612 "failed to find equivalent MIMG op"); 10613 10614 // Adjust the writemask in the node 10615 SmallVector<SDValue, 12> Ops; 10616 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10617 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10618 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10619 10620 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10621 10622 MVT ResultVT = NewChannels == 1 ? 10623 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10624 NewChannels == 5 ? 8 : NewChannels); 10625 SDVTList NewVTList = HasChain ? 10626 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10627 10628 10629 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10630 NewVTList, Ops); 10631 10632 if (HasChain) { 10633 // Update chain. 10634 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10635 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10636 } 10637 10638 if (NewChannels == 1) { 10639 assert(Node->hasNUsesOfValue(1, 0)); 10640 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10641 SDLoc(Node), Users[Lane]->getValueType(0), 10642 SDValue(NewNode, 0)); 10643 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10644 return nullptr; 10645 } 10646 10647 // Update the users of the node with the new indices 10648 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10649 SDNode *User = Users[i]; 10650 if (!User) { 10651 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10652 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10653 if (i || !NoChannels) 10654 continue; 10655 } else { 10656 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10657 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10658 } 10659 10660 switch (Idx) { 10661 default: break; 10662 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10663 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10664 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10665 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10666 } 10667 } 10668 10669 DAG.RemoveDeadNode(Node); 10670 return nullptr; 10671 } 10672 10673 static bool isFrameIndexOp(SDValue Op) { 10674 if (Op.getOpcode() == ISD::AssertZext) 10675 Op = Op.getOperand(0); 10676 10677 return isa<FrameIndexSDNode>(Op); 10678 } 10679 10680 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10681 /// with frame index operands. 10682 /// LLVM assumes that inputs are to these instructions are registers. 10683 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10684 SelectionDAG &DAG) const { 10685 if (Node->getOpcode() == ISD::CopyToReg) { 10686 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10687 SDValue SrcVal = Node->getOperand(2); 10688 10689 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10690 // to try understanding copies to physical registers. 10691 if (SrcVal.getValueType() == MVT::i1 && 10692 Register::isPhysicalRegister(DestReg->getReg())) { 10693 SDLoc SL(Node); 10694 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10695 SDValue VReg = DAG.getRegister( 10696 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10697 10698 SDNode *Glued = Node->getGluedNode(); 10699 SDValue ToVReg 10700 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10701 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10702 SDValue ToResultReg 10703 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10704 VReg, ToVReg.getValue(1)); 10705 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10706 DAG.RemoveDeadNode(Node); 10707 return ToResultReg.getNode(); 10708 } 10709 } 10710 10711 SmallVector<SDValue, 8> Ops; 10712 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10713 if (!isFrameIndexOp(Node->getOperand(i))) { 10714 Ops.push_back(Node->getOperand(i)); 10715 continue; 10716 } 10717 10718 SDLoc DL(Node); 10719 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10720 Node->getOperand(i).getValueType(), 10721 Node->getOperand(i)), 0)); 10722 } 10723 10724 return DAG.UpdateNodeOperands(Node, Ops); 10725 } 10726 10727 /// Fold the instructions after selecting them. 10728 /// Returns null if users were already updated. 10729 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10730 SelectionDAG &DAG) const { 10731 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10732 unsigned Opcode = Node->getMachineOpcode(); 10733 10734 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10735 !TII->isGather4(Opcode)) { 10736 return adjustWritemask(Node, DAG); 10737 } 10738 10739 if (Opcode == AMDGPU::INSERT_SUBREG || 10740 Opcode == AMDGPU::REG_SEQUENCE) { 10741 legalizeTargetIndependentNode(Node, DAG); 10742 return Node; 10743 } 10744 10745 switch (Opcode) { 10746 case AMDGPU::V_DIV_SCALE_F32: 10747 case AMDGPU::V_DIV_SCALE_F64: { 10748 // Satisfy the operand register constraint when one of the inputs is 10749 // undefined. Ordinarily each undef value will have its own implicit_def of 10750 // a vreg, so force these to use a single register. 10751 SDValue Src0 = Node->getOperand(0); 10752 SDValue Src1 = Node->getOperand(1); 10753 SDValue Src2 = Node->getOperand(2); 10754 10755 if ((Src0.isMachineOpcode() && 10756 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10757 (Src0 == Src1 || Src0 == Src2)) 10758 break; 10759 10760 MVT VT = Src0.getValueType().getSimpleVT(); 10761 const TargetRegisterClass *RC = 10762 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10763 10764 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10765 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10766 10767 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10768 UndefReg, Src0, SDValue()); 10769 10770 // src0 must be the same register as src1 or src2, even if the value is 10771 // undefined, so make sure we don't violate this constraint. 10772 if (Src0.isMachineOpcode() && 10773 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10774 if (Src1.isMachineOpcode() && 10775 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10776 Src0 = Src1; 10777 else if (Src2.isMachineOpcode() && 10778 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10779 Src0 = Src2; 10780 else { 10781 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10782 Src0 = UndefReg; 10783 Src1 = UndefReg; 10784 } 10785 } else 10786 break; 10787 10788 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10789 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10790 Ops.push_back(Node->getOperand(I)); 10791 10792 Ops.push_back(ImpDef.getValue(1)); 10793 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10794 } 10795 default: 10796 break; 10797 } 10798 10799 return Node; 10800 } 10801 10802 /// Assign the register class depending on the number of 10803 /// bits set in the writemask 10804 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10805 SDNode *Node) const { 10806 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10807 10808 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10809 10810 if (TII->isVOP3(MI.getOpcode())) { 10811 // Make sure constant bus requirements are respected. 10812 TII->legalizeOperandsVOP3(MRI, MI); 10813 10814 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10815 // This saves a chain-copy of registers and better ballance register 10816 // use between vgpr and agpr as agpr tuples tend to be big. 10817 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10818 unsigned Opc = MI.getOpcode(); 10819 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10820 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10821 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10822 if (I == -1) 10823 break; 10824 MachineOperand &Op = MI.getOperand(I); 10825 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10826 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10827 !Register::isVirtualRegister(Op.getReg()) || 10828 !TRI->isAGPR(MRI, Op.getReg())) 10829 continue; 10830 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10831 if (!Src || !Src->isCopy() || 10832 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10833 continue; 10834 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10835 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10836 // All uses of agpr64 and agpr32 can also accept vgpr except for 10837 // v_accvgpr_read, but we do not produce agpr reads during selection, 10838 // so no use checks are needed. 10839 MRI.setRegClass(Op.getReg(), NewRC); 10840 } 10841 } 10842 10843 return; 10844 } 10845 10846 // Replace unused atomics with the no return version. 10847 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10848 if (NoRetAtomicOp != -1) { 10849 if (!Node->hasAnyUseOfValue(0)) { 10850 MI.setDesc(TII->get(NoRetAtomicOp)); 10851 MI.RemoveOperand(0); 10852 return; 10853 } 10854 10855 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10856 // instruction, because the return type of these instructions is a vec2 of 10857 // the memory type, so it can be tied to the input operand. 10858 // This means these instructions always have a use, so we need to add a 10859 // special case to check if the atomic has only one extract_subreg use, 10860 // which itself has no uses. 10861 if ((Node->hasNUsesOfValue(1, 0) && 10862 Node->use_begin()->isMachineOpcode() && 10863 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10864 !Node->use_begin()->hasAnyUseOfValue(0))) { 10865 Register Def = MI.getOperand(0).getReg(); 10866 10867 // Change this into a noret atomic. 10868 MI.setDesc(TII->get(NoRetAtomicOp)); 10869 MI.RemoveOperand(0); 10870 10871 // If we only remove the def operand from the atomic instruction, the 10872 // extract_subreg will be left with a use of a vreg without a def. 10873 // So we need to insert an implicit_def to avoid machine verifier 10874 // errors. 10875 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10876 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10877 } 10878 return; 10879 } 10880 } 10881 10882 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 10883 uint64_t Val) { 10884 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 10885 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 10886 } 10887 10888 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 10889 const SDLoc &DL, 10890 SDValue Ptr) const { 10891 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10892 10893 // Build the half of the subregister with the constants before building the 10894 // full 128-bit register. If we are building multiple resource descriptors, 10895 // this will allow CSEing of the 2-component register. 10896 const SDValue Ops0[] = { 10897 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 10898 buildSMovImm32(DAG, DL, 0), 10899 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10900 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 10901 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 10902 }; 10903 10904 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 10905 MVT::v2i32, Ops0), 0); 10906 10907 // Combine the constants and the pointer. 10908 const SDValue Ops1[] = { 10909 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10910 Ptr, 10911 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 10912 SubRegHi, 10913 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 10914 }; 10915 10916 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 10917 } 10918 10919 /// Return a resource descriptor with the 'Add TID' bit enabled 10920 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 10921 /// of the resource descriptor) to create an offset, which is added to 10922 /// the resource pointer. 10923 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 10924 SDValue Ptr, uint32_t RsrcDword1, 10925 uint64_t RsrcDword2And3) const { 10926 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 10927 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 10928 if (RsrcDword1) { 10929 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 10930 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 10931 0); 10932 } 10933 10934 SDValue DataLo = buildSMovImm32(DAG, DL, 10935 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 10936 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 10937 10938 const SDValue Ops[] = { 10939 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10940 PtrLo, 10941 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10942 PtrHi, 10943 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 10944 DataLo, 10945 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 10946 DataHi, 10947 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 10948 }; 10949 10950 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 10951 } 10952 10953 //===----------------------------------------------------------------------===// 10954 // SI Inline Assembly Support 10955 //===----------------------------------------------------------------------===// 10956 10957 std::pair<unsigned, const TargetRegisterClass *> 10958 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10959 StringRef Constraint, 10960 MVT VT) const { 10961 const TargetRegisterClass *RC = nullptr; 10962 if (Constraint.size() == 1) { 10963 const unsigned BitWidth = VT.getSizeInBits(); 10964 switch (Constraint[0]) { 10965 default: 10966 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10967 case 's': 10968 case 'r': 10969 switch (BitWidth) { 10970 case 16: 10971 RC = &AMDGPU::SReg_32RegClass; 10972 break; 10973 case 64: 10974 RC = &AMDGPU::SGPR_64RegClass; 10975 break; 10976 default: 10977 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 10978 if (!RC) 10979 return std::make_pair(0U, nullptr); 10980 break; 10981 } 10982 break; 10983 case 'v': 10984 switch (BitWidth) { 10985 case 16: 10986 RC = &AMDGPU::VGPR_32RegClass; 10987 break; 10988 default: 10989 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 10990 if (!RC) 10991 return std::make_pair(0U, nullptr); 10992 break; 10993 } 10994 break; 10995 case 'a': 10996 if (!Subtarget->hasMAIInsts()) 10997 break; 10998 switch (BitWidth) { 10999 case 16: 11000 RC = &AMDGPU::AGPR_32RegClass; 11001 break; 11002 default: 11003 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 11004 if (!RC) 11005 return std::make_pair(0U, nullptr); 11006 break; 11007 } 11008 break; 11009 } 11010 // We actually support i128, i16 and f16 as inline parameters 11011 // even if they are not reported as legal 11012 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11013 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11014 return std::make_pair(0U, RC); 11015 } 11016 11017 if (Constraint.size() > 1) { 11018 if (Constraint[1] == 'v') { 11019 RC = &AMDGPU::VGPR_32RegClass; 11020 } else if (Constraint[1] == 's') { 11021 RC = &AMDGPU::SGPR_32RegClass; 11022 } else if (Constraint[1] == 'a') { 11023 RC = &AMDGPU::AGPR_32RegClass; 11024 } 11025 11026 if (RC) { 11027 uint32_t Idx; 11028 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11029 if (!Failed && Idx < RC->getNumRegs()) 11030 return std::make_pair(RC->getRegister(Idx), RC); 11031 } 11032 } 11033 11034 // FIXME: Returns VS_32 for physical SGPR constraints 11035 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11036 } 11037 11038 SITargetLowering::ConstraintType 11039 SITargetLowering::getConstraintType(StringRef Constraint) const { 11040 if (Constraint.size() == 1) { 11041 switch (Constraint[0]) { 11042 default: break; 11043 case 's': 11044 case 'v': 11045 case 'a': 11046 return C_RegisterClass; 11047 case 'A': 11048 return C_Other; 11049 } 11050 } 11051 return TargetLowering::getConstraintType(Constraint); 11052 } 11053 11054 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11055 std::string &Constraint, 11056 std::vector<SDValue> &Ops, 11057 SelectionDAG &DAG) const { 11058 if (Constraint.length() == 1 && Constraint[0] == 'A') { 11059 LowerAsmOperandForConstraintA(Op, Ops, DAG); 11060 } else { 11061 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11062 } 11063 } 11064 11065 void SITargetLowering::LowerAsmOperandForConstraintA(SDValue Op, 11066 std::vector<SDValue> &Ops, 11067 SelectionDAG &DAG) const { 11068 unsigned Size = Op.getScalarValueSizeInBits(); 11069 if (Size > 64) 11070 return; 11071 11072 uint64_t Val; 11073 bool IsConst = false; 11074 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11075 Val = C->getSExtValue(); 11076 IsConst = true; 11077 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11078 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11079 IsConst = true; 11080 } else if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11081 if (Size != 16 || Op.getNumOperands() != 2) 11082 return; 11083 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11084 return; 11085 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11086 Val = C->getSExtValue(); 11087 IsConst = true; 11088 } else if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11089 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11090 IsConst = true; 11091 } 11092 } 11093 11094 if (IsConst) { 11095 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11096 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11097 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11098 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11099 // Clear unused bits of fp constants 11100 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11101 unsigned UnusedBits = 64 - Size; 11102 Val = (Val << UnusedBits) >> UnusedBits; 11103 } 11104 auto Res = DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64); 11105 Ops.push_back(Res); 11106 } 11107 } 11108 } 11109 11110 // Figure out which registers should be reserved for stack access. Only after 11111 // the function is legalized do we know all of the non-spill stack objects or if 11112 // calls are present. 11113 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11114 MachineRegisterInfo &MRI = MF.getRegInfo(); 11115 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11116 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11117 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11118 11119 if (Info->isEntryFunction()) { 11120 // Callable functions have fixed registers used for stack access. 11121 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11122 } 11123 11124 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11125 Info->getStackPtrOffsetReg())); 11126 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11127 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11128 11129 // We need to worry about replacing the default register with itself in case 11130 // of MIR testcases missing the MFI. 11131 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11132 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11133 11134 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11135 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11136 11137 Info->limitOccupancy(MF); 11138 11139 if (ST.isWave32() && !MF.empty()) { 11140 // Add VCC_HI def because many instructions marked as imp-use VCC where 11141 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 11142 // having a use of undef. 11143 11144 const SIInstrInfo *TII = ST.getInstrInfo(); 11145 DebugLoc DL; 11146 11147 MachineBasicBlock &MBB = MF.front(); 11148 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 11149 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 11150 11151 for (auto &MBB : MF) { 11152 for (auto &MI : MBB) { 11153 TII->fixImplicitOperands(MI); 11154 } 11155 } 11156 } 11157 11158 TargetLoweringBase::finalizeLowering(MF); 11159 11160 // Allocate a VGPR for future SGPR Spill if 11161 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11162 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11163 if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill && 11164 !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects()) 11165 Info->reserveVGPRforSGPRSpills(MF); 11166 } 11167 11168 void SITargetLowering::computeKnownBitsForFrameIndex( 11169 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11170 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11171 11172 // Set the high bits to zero based on the maximum allowed scratch size per 11173 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11174 // calculation won't overflow, so assume the sign bit is never set. 11175 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11176 } 11177 11178 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11179 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11180 const Align CacheLineAlign = Align(64); 11181 11182 // Pre-GFX10 target did not benefit from loop alignment 11183 if (!ML || DisableLoopAlignment || 11184 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11185 getSubtarget()->hasInstFwdPrefetchBug()) 11186 return PrefAlign; 11187 11188 // On GFX10 I$ is 4 x 64 bytes cache lines. 11189 // By default prefetcher keeps one cache line behind and reads two ahead. 11190 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11191 // behind and one ahead. 11192 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11193 // If loop fits 64 bytes it always spans no more than two cache lines and 11194 // does not need an alignment. 11195 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11196 // Else if loop is less or equal 192 bytes we need two lines behind. 11197 11198 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11199 const MachineBasicBlock *Header = ML->getHeader(); 11200 if (Header->getAlignment() != PrefAlign) 11201 return Header->getAlignment(); // Already processed. 11202 11203 unsigned LoopSize = 0; 11204 for (const MachineBasicBlock *MBB : ML->blocks()) { 11205 // If inner loop block is aligned assume in average half of the alignment 11206 // size to be added as nops. 11207 if (MBB != Header) 11208 LoopSize += MBB->getAlignment().value() / 2; 11209 11210 for (const MachineInstr &MI : *MBB) { 11211 LoopSize += TII->getInstSizeInBytes(MI); 11212 if (LoopSize > 192) 11213 return PrefAlign; 11214 } 11215 } 11216 11217 if (LoopSize <= 64) 11218 return PrefAlign; 11219 11220 if (LoopSize <= 128) 11221 return CacheLineAlign; 11222 11223 // If any of parent loops is surrounded by prefetch instructions do not 11224 // insert new for inner loop, which would reset parent's settings. 11225 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11226 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11227 auto I = Exit->getFirstNonDebugInstr(); 11228 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11229 return CacheLineAlign; 11230 } 11231 } 11232 11233 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11234 MachineBasicBlock *Exit = ML->getExitBlock(); 11235 11236 if (Pre && Exit) { 11237 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11238 TII->get(AMDGPU::S_INST_PREFETCH)) 11239 .addImm(1); // prefetch 2 lines behind PC 11240 11241 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11242 TII->get(AMDGPU::S_INST_PREFETCH)) 11243 .addImm(2); // prefetch 1 line behind PC 11244 } 11245 11246 return CacheLineAlign; 11247 } 11248 11249 LLVM_ATTRIBUTE_UNUSED 11250 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11251 assert(N->getOpcode() == ISD::CopyFromReg); 11252 do { 11253 // Follow the chain until we find an INLINEASM node. 11254 N = N->getOperand(0).getNode(); 11255 if (N->getOpcode() == ISD::INLINEASM || 11256 N->getOpcode() == ISD::INLINEASM_BR) 11257 return true; 11258 } while (N->getOpcode() == ISD::CopyFromReg); 11259 return false; 11260 } 11261 11262 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 11263 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 11264 { 11265 switch (N->getOpcode()) { 11266 case ISD::CopyFromReg: 11267 { 11268 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11269 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11270 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11271 Register Reg = R->getReg(); 11272 11273 // FIXME: Why does this need to consider isLiveIn? 11274 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11275 return !TRI->isSGPRReg(MRI, Reg); 11276 11277 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11278 return KDA->isDivergent(V); 11279 11280 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11281 return !TRI->isSGPRReg(MRI, Reg); 11282 } 11283 break; 11284 case ISD::LOAD: { 11285 const LoadSDNode *L = cast<LoadSDNode>(N); 11286 unsigned AS = L->getAddressSpace(); 11287 // A flat load may access private memory. 11288 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11289 } break; 11290 case ISD::CALLSEQ_END: 11291 return true; 11292 break; 11293 case ISD::INTRINSIC_WO_CHAIN: 11294 { 11295 11296 } 11297 return AMDGPU::isIntrinsicSourceOfDivergence( 11298 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11299 case ISD::INTRINSIC_W_CHAIN: 11300 return AMDGPU::isIntrinsicSourceOfDivergence( 11301 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11302 } 11303 return false; 11304 } 11305 11306 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11307 EVT VT) const { 11308 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11309 case MVT::f32: 11310 return hasFP32Denormals(DAG.getMachineFunction()); 11311 case MVT::f64: 11312 case MVT::f16: 11313 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11314 default: 11315 return false; 11316 } 11317 } 11318 11319 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11320 const SelectionDAG &DAG, 11321 bool SNaN, 11322 unsigned Depth) const { 11323 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11324 const MachineFunction &MF = DAG.getMachineFunction(); 11325 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11326 11327 if (Info->getMode().DX10Clamp) 11328 return true; // Clamped to 0. 11329 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11330 } 11331 11332 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11333 SNaN, Depth); 11334 } 11335 11336 TargetLowering::AtomicExpansionKind 11337 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11338 switch (RMW->getOperation()) { 11339 case AtomicRMWInst::FAdd: { 11340 Type *Ty = RMW->getType(); 11341 11342 // We don't have a way to support 16-bit atomics now, so just leave them 11343 // as-is. 11344 if (Ty->isHalfTy()) 11345 return AtomicExpansionKind::None; 11346 11347 if (!Ty->isFloatTy()) 11348 return AtomicExpansionKind::CmpXChg; 11349 11350 // TODO: Do have these for flat. Older targets also had them for buffers. 11351 unsigned AS = RMW->getPointerAddressSpace(); 11352 11353 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11354 return RMW->use_empty() ? AtomicExpansionKind::None : 11355 AtomicExpansionKind::CmpXChg; 11356 } 11357 11358 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11359 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11360 } 11361 default: 11362 break; 11363 } 11364 11365 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11366 } 11367 11368 const TargetRegisterClass * 11369 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11370 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11371 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11372 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11373 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11374 : &AMDGPU::SReg_32RegClass; 11375 if (!TRI->isSGPRClass(RC) && !isDivergent) 11376 return TRI->getEquivalentSGPRClass(RC); 11377 else if (TRI->isSGPRClass(RC) && isDivergent) 11378 return TRI->getEquivalentVGPRClass(RC); 11379 11380 return RC; 11381 } 11382 11383 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11384 // uniform values (as produced by the mask results of control flow intrinsics) 11385 // used outside of divergent blocks. The phi users need to also be treated as 11386 // always uniform. 11387 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11388 unsigned WaveSize) { 11389 // FIXME: We asssume we never cast the mask results of a control flow 11390 // intrinsic. 11391 // Early exit if the type won't be consistent as a compile time hack. 11392 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11393 if (!IT || IT->getBitWidth() != WaveSize) 11394 return false; 11395 11396 if (!isa<Instruction>(V)) 11397 return false; 11398 if (!Visited.insert(V).second) 11399 return false; 11400 bool Result = false; 11401 for (auto U : V->users()) { 11402 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11403 if (V == U->getOperand(1)) { 11404 switch (Intrinsic->getIntrinsicID()) { 11405 default: 11406 Result = false; 11407 break; 11408 case Intrinsic::amdgcn_if_break: 11409 case Intrinsic::amdgcn_if: 11410 case Intrinsic::amdgcn_else: 11411 Result = true; 11412 break; 11413 } 11414 } 11415 if (V == U->getOperand(0)) { 11416 switch (Intrinsic->getIntrinsicID()) { 11417 default: 11418 Result = false; 11419 break; 11420 case Intrinsic::amdgcn_end_cf: 11421 case Intrinsic::amdgcn_loop: 11422 Result = true; 11423 break; 11424 } 11425 } 11426 } else { 11427 Result = hasCFUser(U, Visited, WaveSize); 11428 } 11429 if (Result) 11430 break; 11431 } 11432 return Result; 11433 } 11434 11435 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11436 const Value *V) const { 11437 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11438 if (CI->isInlineAsm()) { 11439 // FIXME: This cannot give a correct answer. This should only trigger in 11440 // the case where inline asm returns mixed SGPR and VGPR results, used 11441 // outside the defining block. We don't have a specific result to 11442 // consider, so this assumes if any value is SGPR, the overall register 11443 // also needs to be SGPR. 11444 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11445 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11446 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11447 for (auto &TC : TargetConstraints) { 11448 if (TC.Type == InlineAsm::isOutput) { 11449 ComputeConstraintToUse(TC, SDValue()); 11450 unsigned AssignedReg; 11451 const TargetRegisterClass *RC; 11452 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11453 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11454 if (RC) { 11455 MachineRegisterInfo &MRI = MF.getRegInfo(); 11456 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11457 return true; 11458 else if (SIRI->isSGPRClass(RC)) 11459 return true; 11460 } 11461 } 11462 } 11463 } 11464 } 11465 SmallPtrSet<const Value *, 16> Visited; 11466 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11467 } 11468