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/GlobalISel/GISelKnownBits.h" 39 #include "llvm/CodeGen/MachineBasicBlock.h" 40 #include "llvm/CodeGen/MachineFrameInfo.h" 41 #include "llvm/CodeGen/MachineFunction.h" 42 #include "llvm/CodeGen/MachineInstr.h" 43 #include "llvm/CodeGen/MachineInstrBuilder.h" 44 #include "llvm/CodeGen/MachineLoopInfo.h" 45 #include "llvm/CodeGen/MachineMemOperand.h" 46 #include "llvm/CodeGen/MachineModuleInfo.h" 47 #include "llvm/CodeGen/MachineOperand.h" 48 #include "llvm/CodeGen/MachineRegisterInfo.h" 49 #include "llvm/CodeGen/SelectionDAG.h" 50 #include "llvm/CodeGen/SelectionDAGNodes.h" 51 #include "llvm/CodeGen/TargetCallingConv.h" 52 #include "llvm/CodeGen/TargetRegisterInfo.h" 53 #include "llvm/CodeGen/ValueTypes.h" 54 #include "llvm/IR/Constants.h" 55 #include "llvm/IR/DataLayout.h" 56 #include "llvm/IR/DebugLoc.h" 57 #include "llvm/IR/DerivedTypes.h" 58 #include "llvm/IR/DiagnosticInfo.h" 59 #include "llvm/IR/Function.h" 60 #include "llvm/IR/GlobalValue.h" 61 #include "llvm/IR/InstrTypes.h" 62 #include "llvm/IR/Instruction.h" 63 #include "llvm/IR/Instructions.h" 64 #include "llvm/IR/IntrinsicInst.h" 65 #include "llvm/IR/Type.h" 66 #include "llvm/Support/Casting.h" 67 #include "llvm/Support/CodeGen.h" 68 #include "llvm/Support/CommandLine.h" 69 #include "llvm/Support/Compiler.h" 70 #include "llvm/Support/ErrorHandling.h" 71 #include "llvm/Support/KnownBits.h" 72 #include "llvm/Support/MachineValueType.h" 73 #include "llvm/Support/MathExtras.h" 74 #include "llvm/Target/TargetOptions.h" 75 #include <cassert> 76 #include <cmath> 77 #include <cstdint> 78 #include <iterator> 79 #include <tuple> 80 #include <utility> 81 #include <vector> 82 83 using namespace llvm; 84 85 #define DEBUG_TYPE "si-lower" 86 87 STATISTIC(NumTailCalls, "Number of tail calls"); 88 89 static cl::opt<bool> DisableLoopAlignment( 90 "amdgpu-disable-loop-alignment", 91 cl::desc("Do not align and prefetch loops"), 92 cl::init(false)); 93 94 static cl::opt<bool> VGPRReserveforSGPRSpill( 95 "amdgpu-reserve-vgpr-for-sgpr-spill", 96 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 97 98 static cl::opt<bool> UseDivergentRegisterIndexing( 99 "amdgpu-use-divergent-register-indexing", 100 cl::Hidden, 101 cl::desc("Use indirect register addressing for divergent indexes"), 102 cl::init(false)); 103 104 static bool hasFP32Denormals(const MachineFunction &MF) { 105 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 106 return Info->getMode().allFP32Denormals(); 107 } 108 109 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 110 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 111 return Info->getMode().allFP64FP16Denormals(); 112 } 113 114 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 115 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 116 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 117 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 118 return AMDGPU::SGPR0 + Reg; 119 } 120 } 121 llvm_unreachable("Cannot allocate sgpr"); 122 } 123 124 SITargetLowering::SITargetLowering(const TargetMachine &TM, 125 const GCNSubtarget &STI) 126 : AMDGPUTargetLowering(TM, STI), 127 Subtarget(&STI) { 128 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 129 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 130 131 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 132 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 133 134 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 135 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 136 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 137 138 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 139 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 140 141 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 142 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 143 144 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 145 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 146 147 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 148 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 149 150 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 151 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 152 153 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 154 addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass); 155 156 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 157 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 158 159 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 160 addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass); 161 162 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 163 addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass); 164 165 if (Subtarget->has16BitInsts()) { 166 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 167 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 168 169 // Unless there are also VOP3P operations, not operations are really legal. 170 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 171 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 172 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 173 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 174 } 175 176 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 177 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 178 179 computeRegisterProperties(Subtarget->getRegisterInfo()); 180 181 // The boolean content concept here is too inflexible. Compares only ever 182 // really produce a 1-bit result. Any copy/extend from these will turn into a 183 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 184 // it's what most targets use. 185 setBooleanContents(ZeroOrOneBooleanContent); 186 setBooleanVectorContents(ZeroOrOneBooleanContent); 187 188 // We need to custom lower vector stores from local memory 189 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 190 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 191 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 192 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 193 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 194 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 195 setOperationAction(ISD::LOAD, MVT::i1, Custom); 196 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 197 198 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 199 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 200 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 201 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 202 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 203 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 204 setOperationAction(ISD::STORE, MVT::i1, Custom); 205 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 206 207 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 208 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 209 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 210 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 211 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 212 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 213 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 214 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 215 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 216 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 217 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 218 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 219 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 220 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 221 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 222 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 223 224 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 225 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 226 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 227 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 228 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 229 230 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 231 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 232 233 setOperationAction(ISD::SELECT, MVT::i1, Promote); 234 setOperationAction(ISD::SELECT, MVT::i64, Custom); 235 setOperationAction(ISD::SELECT, MVT::f64, Promote); 236 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 237 238 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 239 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 240 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 241 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 242 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 243 244 setOperationAction(ISD::SETCC, MVT::i1, Promote); 245 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 246 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 247 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 248 249 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 250 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 251 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 252 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 253 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 254 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 255 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 256 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 257 258 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 259 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 260 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 261 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 262 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 263 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 264 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 266 267 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 268 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 269 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 270 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 271 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 272 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 273 274 setOperationAction(ISD::UADDO, MVT::i32, Legal); 275 setOperationAction(ISD::USUBO, MVT::i32, Legal); 276 277 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 278 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 279 280 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 281 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 282 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 283 284 #if 0 285 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 286 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 287 #endif 288 289 // We only support LOAD/STORE and vector manipulation ops for vectors 290 // with > 4 elements. 291 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 292 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 293 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 294 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 295 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 296 switch (Op) { 297 case ISD::LOAD: 298 case ISD::STORE: 299 case ISD::BUILD_VECTOR: 300 case ISD::BITCAST: 301 case ISD::EXTRACT_VECTOR_ELT: 302 case ISD::INSERT_VECTOR_ELT: 303 case ISD::INSERT_SUBVECTOR: 304 case ISD::EXTRACT_SUBVECTOR: 305 case ISD::SCALAR_TO_VECTOR: 306 break; 307 case ISD::CONCAT_VECTORS: 308 setOperationAction(Op, VT, Custom); 309 break; 310 default: 311 setOperationAction(Op, VT, Expand); 312 break; 313 } 314 } 315 } 316 317 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 318 319 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 320 // is expanded to avoid having two separate loops in case the index is a VGPR. 321 322 // Most operations are naturally 32-bit vector operations. We only support 323 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 324 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 325 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 326 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 327 328 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 329 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 330 331 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 332 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 333 334 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 335 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 336 } 337 338 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 339 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 340 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 341 342 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 343 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 344 345 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 346 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 347 348 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 349 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 350 } 351 352 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 353 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 354 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 355 356 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 357 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 358 359 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 360 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 361 362 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 363 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 364 } 365 366 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 367 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 368 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 369 370 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 371 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 372 373 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 374 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 375 376 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 377 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 378 } 379 380 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 381 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 382 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 383 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 384 385 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 386 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 387 388 // Avoid stack access for these. 389 // TODO: Generalize to more vector types. 390 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 391 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 392 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 393 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 394 395 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 396 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 398 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 399 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 400 401 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 402 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 403 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 404 405 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 406 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 407 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 408 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 409 410 // Deal with vec3 vector operations when widened to vec4. 411 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 414 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 415 416 // Deal with vec5 vector operations when widened to vec8. 417 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 418 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 419 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 420 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 421 422 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 423 // and output demarshalling 424 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 425 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 426 427 // We can't return success/failure, only the old value, 428 // let LLVM add the comparison 429 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 430 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 431 432 if (Subtarget->hasFlatAddressSpace()) { 433 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 434 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 435 } 436 437 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 438 439 // FIXME: This should be narrowed to i32, but that only happens if i64 is 440 // illegal. 441 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 442 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 443 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 444 445 // On SI this is s_memtime and s_memrealtime on VI. 446 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 447 setOperationAction(ISD::TRAP, MVT::Other, Custom); 448 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 449 450 if (Subtarget->has16BitInsts()) { 451 setOperationAction(ISD::FPOW, MVT::f16, Promote); 452 setOperationAction(ISD::FLOG, MVT::f16, Custom); 453 setOperationAction(ISD::FEXP, MVT::f16, Custom); 454 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 455 } 456 457 if (Subtarget->hasMadMacF32Insts()) 458 setOperationAction(ISD::FMAD, MVT::f32, Legal); 459 460 if (!Subtarget->hasBFI()) { 461 // fcopysign can be done in a single instruction with BFI. 462 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 463 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 464 } 465 466 if (!Subtarget->hasBCNT(32)) 467 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 468 469 if (!Subtarget->hasBCNT(64)) 470 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 471 472 if (Subtarget->hasFFBH()) 473 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 474 475 if (Subtarget->hasFFBL()) 476 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 477 478 // We only really have 32-bit BFE instructions (and 16-bit on VI). 479 // 480 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 481 // effort to match them now. We want this to be false for i64 cases when the 482 // extraction isn't restricted to the upper or lower half. Ideally we would 483 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 484 // span the midpoint are probably relatively rare, so don't worry about them 485 // for now. 486 if (Subtarget->hasBFE()) 487 setHasExtractBitsInsn(true); 488 489 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 490 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 491 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 492 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 493 494 495 // These are really only legal for ieee_mode functions. We should be avoiding 496 // them for functions that don't have ieee_mode enabled, so just say they are 497 // legal. 498 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 499 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 500 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 501 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 502 503 504 if (Subtarget->haveRoundOpsF64()) { 505 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 506 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 507 setOperationAction(ISD::FRINT, MVT::f64, Legal); 508 } else { 509 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 510 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 511 setOperationAction(ISD::FRINT, MVT::f64, Custom); 512 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 513 } 514 515 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 516 517 setOperationAction(ISD::FSIN, MVT::f32, Custom); 518 setOperationAction(ISD::FCOS, MVT::f32, Custom); 519 setOperationAction(ISD::FDIV, MVT::f32, Custom); 520 setOperationAction(ISD::FDIV, MVT::f64, Custom); 521 522 if (Subtarget->has16BitInsts()) { 523 setOperationAction(ISD::Constant, MVT::i16, Legal); 524 525 setOperationAction(ISD::SMIN, MVT::i16, Legal); 526 setOperationAction(ISD::SMAX, MVT::i16, Legal); 527 528 setOperationAction(ISD::UMIN, MVT::i16, Legal); 529 setOperationAction(ISD::UMAX, MVT::i16, Legal); 530 531 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 532 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 533 534 setOperationAction(ISD::ROTR, MVT::i16, Promote); 535 setOperationAction(ISD::ROTL, MVT::i16, Promote); 536 537 setOperationAction(ISD::SDIV, MVT::i16, Promote); 538 setOperationAction(ISD::UDIV, MVT::i16, Promote); 539 setOperationAction(ISD::SREM, MVT::i16, Promote); 540 setOperationAction(ISD::UREM, MVT::i16, Promote); 541 542 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 543 544 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 545 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 546 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 547 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 548 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 549 550 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 551 552 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 553 554 setOperationAction(ISD::LOAD, MVT::i16, Custom); 555 556 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 557 558 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 559 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 560 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 561 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 562 563 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 564 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 565 566 // F16 - Constant Actions. 567 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 568 569 // F16 - Load/Store Actions. 570 setOperationAction(ISD::LOAD, MVT::f16, Promote); 571 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 572 setOperationAction(ISD::STORE, MVT::f16, Promote); 573 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 574 575 // F16 - VOP1 Actions. 576 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 577 setOperationAction(ISD::FCOS, MVT::f16, Custom); 578 setOperationAction(ISD::FSIN, MVT::f16, Custom); 579 580 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 581 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 582 583 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 584 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 585 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 586 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 587 setOperationAction(ISD::FROUND, MVT::f16, Custom); 588 589 // F16 - VOP2 Actions. 590 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 591 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 592 593 setOperationAction(ISD::FDIV, MVT::f16, Custom); 594 595 // F16 - VOP3 Actions. 596 setOperationAction(ISD::FMA, MVT::f16, Legal); 597 if (STI.hasMadF16()) 598 setOperationAction(ISD::FMAD, MVT::f16, Legal); 599 600 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 601 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 602 switch (Op) { 603 case ISD::LOAD: 604 case ISD::STORE: 605 case ISD::BUILD_VECTOR: 606 case ISD::BITCAST: 607 case ISD::EXTRACT_VECTOR_ELT: 608 case ISD::INSERT_VECTOR_ELT: 609 case ISD::INSERT_SUBVECTOR: 610 case ISD::EXTRACT_SUBVECTOR: 611 case ISD::SCALAR_TO_VECTOR: 612 break; 613 case ISD::CONCAT_VECTORS: 614 setOperationAction(Op, VT, Custom); 615 break; 616 default: 617 setOperationAction(Op, VT, Expand); 618 break; 619 } 620 } 621 } 622 623 // v_perm_b32 can handle either of these. 624 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 625 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 626 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 627 628 // XXX - Do these do anything? Vector constants turn into build_vector. 629 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 630 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 631 632 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 633 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 634 635 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 636 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 637 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 638 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 639 640 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 641 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 642 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 643 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 644 645 setOperationAction(ISD::AND, MVT::v2i16, Promote); 646 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 647 setOperationAction(ISD::OR, MVT::v2i16, Promote); 648 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 649 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 650 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 651 652 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 653 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 654 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 655 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 656 657 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 658 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 659 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 660 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 661 662 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 663 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 664 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 665 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 666 667 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 668 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 669 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 670 671 if (!Subtarget->hasVOP3PInsts()) { 672 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 673 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 674 } 675 676 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 677 // This isn't really legal, but this avoids the legalizer unrolling it (and 678 // allows matching fneg (fabs x) patterns) 679 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 680 681 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 682 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 683 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 684 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 685 686 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 687 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 688 689 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 690 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 691 } 692 693 if (Subtarget->hasVOP3PInsts()) { 694 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 695 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 696 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 697 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 698 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 699 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 700 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 701 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 702 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 703 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 704 705 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 706 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 707 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 708 709 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 710 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 711 712 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 713 714 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 715 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 716 717 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 718 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 719 720 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 721 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 722 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 723 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 724 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 725 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 726 727 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 728 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 729 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 730 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 731 732 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 733 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 734 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 735 736 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 737 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 738 739 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 740 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 741 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 742 743 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 744 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 745 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 746 } 747 748 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 749 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 750 751 if (Subtarget->has16BitInsts()) { 752 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 753 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 754 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 755 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 756 } else { 757 // Legalization hack. 758 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 759 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 760 761 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 762 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 763 } 764 765 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 766 setOperationAction(ISD::SELECT, VT, Custom); 767 } 768 769 setOperationAction(ISD::SMULO, MVT::i64, Custom); 770 setOperationAction(ISD::UMULO, MVT::i64, Custom); 771 772 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 773 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 774 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 775 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 776 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 777 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 778 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 779 780 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 781 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 782 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 783 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 784 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 785 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 786 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 787 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 788 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 789 790 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 791 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 792 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 793 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 794 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 795 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 796 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 797 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 798 799 setTargetDAGCombine(ISD::ADD); 800 setTargetDAGCombine(ISD::ADDCARRY); 801 setTargetDAGCombine(ISD::SUB); 802 setTargetDAGCombine(ISD::SUBCARRY); 803 setTargetDAGCombine(ISD::FADD); 804 setTargetDAGCombine(ISD::FSUB); 805 setTargetDAGCombine(ISD::FMINNUM); 806 setTargetDAGCombine(ISD::FMAXNUM); 807 setTargetDAGCombine(ISD::FMINNUM_IEEE); 808 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 809 setTargetDAGCombine(ISD::FMA); 810 setTargetDAGCombine(ISD::SMIN); 811 setTargetDAGCombine(ISD::SMAX); 812 setTargetDAGCombine(ISD::UMIN); 813 setTargetDAGCombine(ISD::UMAX); 814 setTargetDAGCombine(ISD::SETCC); 815 setTargetDAGCombine(ISD::AND); 816 setTargetDAGCombine(ISD::OR); 817 setTargetDAGCombine(ISD::XOR); 818 setTargetDAGCombine(ISD::SINT_TO_FP); 819 setTargetDAGCombine(ISD::UINT_TO_FP); 820 setTargetDAGCombine(ISD::FCANONICALIZE); 821 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 822 setTargetDAGCombine(ISD::ZERO_EXTEND); 823 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 824 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 825 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 826 827 // All memory operations. Some folding on the pointer operand is done to help 828 // matching the constant offsets in the addressing modes. 829 setTargetDAGCombine(ISD::LOAD); 830 setTargetDAGCombine(ISD::STORE); 831 setTargetDAGCombine(ISD::ATOMIC_LOAD); 832 setTargetDAGCombine(ISD::ATOMIC_STORE); 833 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 834 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 835 setTargetDAGCombine(ISD::ATOMIC_SWAP); 836 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 837 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 838 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 839 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 840 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 841 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 842 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 843 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 844 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 845 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 846 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 847 848 // FIXME: In other contexts we pretend this is a per-function property. 849 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 850 851 setSchedulingPreference(Sched::RegPressure); 852 } 853 854 const GCNSubtarget *SITargetLowering::getSubtarget() const { 855 return Subtarget; 856 } 857 858 //===----------------------------------------------------------------------===// 859 // TargetLowering queries 860 //===----------------------------------------------------------------------===// 861 862 // v_mad_mix* support a conversion from f16 to f32. 863 // 864 // There is only one special case when denormals are enabled we don't currently, 865 // where this is OK to use. 866 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 867 EVT DestVT, EVT SrcVT) const { 868 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 869 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 870 DestVT.getScalarType() == MVT::f32 && 871 SrcVT.getScalarType() == MVT::f16 && 872 // TODO: This probably only requires no input flushing? 873 !hasFP32Denormals(DAG.getMachineFunction()); 874 } 875 876 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 877 // SI has some legal vector types, but no legal vector operations. Say no 878 // shuffles are legal in order to prefer scalarizing some vector operations. 879 return false; 880 } 881 882 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 883 CallingConv::ID CC, 884 EVT VT) const { 885 if (CC == CallingConv::AMDGPU_KERNEL) 886 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 887 888 if (VT.isVector()) { 889 EVT ScalarVT = VT.getScalarType(); 890 unsigned Size = ScalarVT.getSizeInBits(); 891 if (Size == 32) 892 return ScalarVT.getSimpleVT(); 893 894 if (Size > 32) 895 return MVT::i32; 896 897 if (Size == 16 && Subtarget->has16BitInsts()) 898 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 899 } else if (VT.getSizeInBits() > 32) 900 return MVT::i32; 901 902 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 903 } 904 905 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 906 CallingConv::ID CC, 907 EVT VT) const { 908 if (CC == CallingConv::AMDGPU_KERNEL) 909 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 910 911 if (VT.isVector()) { 912 unsigned NumElts = VT.getVectorNumElements(); 913 EVT ScalarVT = VT.getScalarType(); 914 unsigned Size = ScalarVT.getSizeInBits(); 915 916 if (Size == 32) 917 return NumElts; 918 919 if (Size > 32) 920 return NumElts * ((Size + 31) / 32); 921 922 if (Size == 16 && Subtarget->has16BitInsts()) 923 return (NumElts + 1) / 2; 924 } else if (VT.getSizeInBits() > 32) 925 return (VT.getSizeInBits() + 31) / 32; 926 927 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 928 } 929 930 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 931 LLVMContext &Context, CallingConv::ID CC, 932 EVT VT, EVT &IntermediateVT, 933 unsigned &NumIntermediates, MVT &RegisterVT) const { 934 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 935 unsigned NumElts = VT.getVectorNumElements(); 936 EVT ScalarVT = VT.getScalarType(); 937 unsigned Size = ScalarVT.getSizeInBits(); 938 if (Size == 32) { 939 RegisterVT = ScalarVT.getSimpleVT(); 940 IntermediateVT = RegisterVT; 941 NumIntermediates = NumElts; 942 return NumIntermediates; 943 } 944 945 if (Size > 32) { 946 RegisterVT = MVT::i32; 947 IntermediateVT = RegisterVT; 948 NumIntermediates = NumElts * ((Size + 31) / 32); 949 return NumIntermediates; 950 } 951 952 // FIXME: We should fix the ABI to be the same on targets without 16-bit 953 // support, but unless we can properly handle 3-vectors, it will be still be 954 // inconsistent. 955 if (Size == 16 && Subtarget->has16BitInsts()) { 956 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 957 IntermediateVT = RegisterVT; 958 NumIntermediates = (NumElts + 1) / 2; 959 return NumIntermediates; 960 } 961 } 962 963 return TargetLowering::getVectorTypeBreakdownForCallingConv( 964 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 965 } 966 967 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 968 assert(DMaskLanes != 0); 969 970 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 971 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 972 return EVT::getVectorVT(Ty->getContext(), 973 EVT::getEVT(VT->getElementType()), 974 NumElts); 975 } 976 977 return EVT::getEVT(Ty); 978 } 979 980 // Peek through TFE struct returns to only use the data size. 981 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 982 auto *ST = dyn_cast<StructType>(Ty); 983 if (!ST) 984 return memVTFromImageData(Ty, DMaskLanes); 985 986 // Some intrinsics return an aggregate type - special case to work out the 987 // correct memVT. 988 // 989 // Only limited forms of aggregate type currently expected. 990 if (ST->getNumContainedTypes() != 2 || 991 !ST->getContainedType(1)->isIntegerTy(32)) 992 return EVT(); 993 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 994 } 995 996 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 997 const CallInst &CI, 998 MachineFunction &MF, 999 unsigned IntrID) const { 1000 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1001 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1002 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1003 (Intrinsic::ID)IntrID); 1004 if (Attr.hasFnAttribute(Attribute::ReadNone)) 1005 return false; 1006 1007 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1008 1009 if (RsrcIntr->IsImage) { 1010 Info.ptrVal = MFI->getImagePSV( 1011 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1012 CI.getArgOperand(RsrcIntr->RsrcArg)); 1013 Info.align.reset(); 1014 } else { 1015 Info.ptrVal = MFI->getBufferPSV( 1016 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1017 CI.getArgOperand(RsrcIntr->RsrcArg)); 1018 } 1019 1020 Info.flags = MachineMemOperand::MODereferenceable; 1021 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 1022 unsigned DMaskLanes = 4; 1023 1024 if (RsrcIntr->IsImage) { 1025 const AMDGPU::ImageDimIntrinsicInfo *Intr 1026 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1027 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1028 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1029 1030 if (!BaseOpcode->Gather4) { 1031 // If this isn't a gather, we may have excess loaded elements in the 1032 // IR type. Check the dmask for the real number of elements loaded. 1033 unsigned DMask 1034 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1035 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1036 } 1037 1038 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1039 } else 1040 Info.memVT = EVT::getEVT(CI.getType()); 1041 1042 // FIXME: What does alignment mean for an image? 1043 Info.opc = ISD::INTRINSIC_W_CHAIN; 1044 Info.flags |= MachineMemOperand::MOLoad; 1045 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1046 Info.opc = ISD::INTRINSIC_VOID; 1047 1048 Type *DataTy = CI.getArgOperand(0)->getType(); 1049 if (RsrcIntr->IsImage) { 1050 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1051 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1052 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1053 } else 1054 Info.memVT = EVT::getEVT(DataTy); 1055 1056 Info.flags |= MachineMemOperand::MOStore; 1057 } else { 1058 // Atomic 1059 Info.opc = ISD::INTRINSIC_W_CHAIN; 1060 Info.memVT = MVT::getVT(CI.getType()); 1061 Info.flags = MachineMemOperand::MOLoad | 1062 MachineMemOperand::MOStore | 1063 MachineMemOperand::MODereferenceable; 1064 1065 // XXX - Should this be volatile without known ordering? 1066 Info.flags |= MachineMemOperand::MOVolatile; 1067 } 1068 return true; 1069 } 1070 1071 switch (IntrID) { 1072 case Intrinsic::amdgcn_atomic_inc: 1073 case Intrinsic::amdgcn_atomic_dec: 1074 case Intrinsic::amdgcn_ds_ordered_add: 1075 case Intrinsic::amdgcn_ds_ordered_swap: 1076 case Intrinsic::amdgcn_ds_fadd: 1077 case Intrinsic::amdgcn_ds_fmin: 1078 case Intrinsic::amdgcn_ds_fmax: { 1079 Info.opc = ISD::INTRINSIC_W_CHAIN; 1080 Info.memVT = MVT::getVT(CI.getType()); 1081 Info.ptrVal = CI.getOperand(0); 1082 Info.align.reset(); 1083 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1084 1085 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1086 if (!Vol->isZero()) 1087 Info.flags |= MachineMemOperand::MOVolatile; 1088 1089 return true; 1090 } 1091 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1092 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1093 1094 Info.opc = ISD::INTRINSIC_VOID; 1095 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1096 Info.ptrVal = MFI->getBufferPSV( 1097 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1098 CI.getArgOperand(1)); 1099 Info.align.reset(); 1100 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1101 1102 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1103 if (!Vol || !Vol->isZero()) 1104 Info.flags |= MachineMemOperand::MOVolatile; 1105 1106 return true; 1107 } 1108 case Intrinsic::amdgcn_global_atomic_fadd: { 1109 Info.opc = ISD::INTRINSIC_VOID; 1110 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 1111 ->getPointerElementType()); 1112 Info.ptrVal = CI.getOperand(0); 1113 Info.align.reset(); 1114 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1115 1116 return true; 1117 } 1118 case Intrinsic::amdgcn_ds_append: 1119 case Intrinsic::amdgcn_ds_consume: { 1120 Info.opc = ISD::INTRINSIC_W_CHAIN; 1121 Info.memVT = MVT::getVT(CI.getType()); 1122 Info.ptrVal = CI.getOperand(0); 1123 Info.align.reset(); 1124 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1125 1126 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1127 if (!Vol->isZero()) 1128 Info.flags |= MachineMemOperand::MOVolatile; 1129 1130 return true; 1131 } 1132 case Intrinsic::amdgcn_global_atomic_csub: { 1133 Info.opc = ISD::INTRINSIC_W_CHAIN; 1134 Info.memVT = MVT::getVT(CI.getType()); 1135 Info.ptrVal = CI.getOperand(0); 1136 Info.align.reset(); 1137 Info.flags = MachineMemOperand::MOLoad | 1138 MachineMemOperand::MOStore | 1139 MachineMemOperand::MODereferenceable | 1140 MachineMemOperand::MOVolatile; 1141 return true; 1142 } 1143 case Intrinsic::amdgcn_ds_gws_init: 1144 case Intrinsic::amdgcn_ds_gws_barrier: 1145 case Intrinsic::amdgcn_ds_gws_sema_v: 1146 case Intrinsic::amdgcn_ds_gws_sema_br: 1147 case Intrinsic::amdgcn_ds_gws_sema_p: 1148 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1149 Info.opc = ISD::INTRINSIC_VOID; 1150 1151 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1152 Info.ptrVal = 1153 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1154 1155 // This is an abstract access, but we need to specify a type and size. 1156 Info.memVT = MVT::i32; 1157 Info.size = 4; 1158 Info.align = Align(4); 1159 1160 Info.flags = MachineMemOperand::MOStore; 1161 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1162 Info.flags = MachineMemOperand::MOLoad; 1163 return true; 1164 } 1165 default: 1166 return false; 1167 } 1168 } 1169 1170 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1171 SmallVectorImpl<Value*> &Ops, 1172 Type *&AccessTy) const { 1173 switch (II->getIntrinsicID()) { 1174 case Intrinsic::amdgcn_atomic_inc: 1175 case Intrinsic::amdgcn_atomic_dec: 1176 case Intrinsic::amdgcn_ds_ordered_add: 1177 case Intrinsic::amdgcn_ds_ordered_swap: 1178 case Intrinsic::amdgcn_ds_fadd: 1179 case Intrinsic::amdgcn_ds_fmin: 1180 case Intrinsic::amdgcn_ds_fmax: { 1181 Value *Ptr = II->getArgOperand(0); 1182 AccessTy = II->getType(); 1183 Ops.push_back(Ptr); 1184 return true; 1185 } 1186 default: 1187 return false; 1188 } 1189 } 1190 1191 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1192 if (!Subtarget->hasFlatInstOffsets()) { 1193 // Flat instructions do not have offsets, and only have the register 1194 // address. 1195 return AM.BaseOffs == 0 && AM.Scale == 0; 1196 } 1197 1198 return AM.Scale == 0 && 1199 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1200 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1201 /*Signed=*/false)); 1202 } 1203 1204 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1205 if (Subtarget->hasFlatGlobalInsts()) 1206 return AM.Scale == 0 && 1207 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1208 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1209 /*Signed=*/true)); 1210 1211 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1212 // Assume the we will use FLAT for all global memory accesses 1213 // on VI. 1214 // FIXME: This assumption is currently wrong. On VI we still use 1215 // MUBUF instructions for the r + i addressing mode. As currently 1216 // implemented, the MUBUF instructions only work on buffer < 4GB. 1217 // It may be possible to support > 4GB buffers with MUBUF instructions, 1218 // by setting the stride value in the resource descriptor which would 1219 // increase the size limit to (stride * 4GB). However, this is risky, 1220 // because it has never been validated. 1221 return isLegalFlatAddressingMode(AM); 1222 } 1223 1224 return isLegalMUBUFAddressingMode(AM); 1225 } 1226 1227 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1228 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1229 // additionally can do r + r + i with addr64. 32-bit has more addressing 1230 // mode options. Depending on the resource constant, it can also do 1231 // (i64 r0) + (i32 r1) * (i14 i). 1232 // 1233 // Private arrays end up using a scratch buffer most of the time, so also 1234 // assume those use MUBUF instructions. Scratch loads / stores are currently 1235 // implemented as mubuf instructions with offen bit set, so slightly 1236 // different than the normal addr64. 1237 if (!isUInt<12>(AM.BaseOffs)) 1238 return false; 1239 1240 // FIXME: Since we can split immediate into soffset and immediate offset, 1241 // would it make sense to allow any immediate? 1242 1243 switch (AM.Scale) { 1244 case 0: // r + i or just i, depending on HasBaseReg. 1245 return true; 1246 case 1: 1247 return true; // We have r + r or r + i. 1248 case 2: 1249 if (AM.HasBaseReg) { 1250 // Reject 2 * r + r. 1251 return false; 1252 } 1253 1254 // Allow 2 * r as r + r 1255 // Or 2 * r + i is allowed as r + r + i. 1256 return true; 1257 default: // Don't allow n * r 1258 return false; 1259 } 1260 } 1261 1262 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1263 const AddrMode &AM, Type *Ty, 1264 unsigned AS, Instruction *I) const { 1265 // No global is ever allowed as a base. 1266 if (AM.BaseGV) 1267 return false; 1268 1269 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1270 return isLegalGlobalAddressingMode(AM); 1271 1272 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1273 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1274 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1275 // If the offset isn't a multiple of 4, it probably isn't going to be 1276 // correctly aligned. 1277 // FIXME: Can we get the real alignment here? 1278 if (AM.BaseOffs % 4 != 0) 1279 return isLegalMUBUFAddressingMode(AM); 1280 1281 // There are no SMRD extloads, so if we have to do a small type access we 1282 // will use a MUBUF load. 1283 // FIXME?: We also need to do this if unaligned, but we don't know the 1284 // alignment here. 1285 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1286 return isLegalGlobalAddressingMode(AM); 1287 1288 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1289 // SMRD instructions have an 8-bit, dword offset on SI. 1290 if (!isUInt<8>(AM.BaseOffs / 4)) 1291 return false; 1292 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1293 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1294 // in 8-bits, it can use a smaller encoding. 1295 if (!isUInt<32>(AM.BaseOffs / 4)) 1296 return false; 1297 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1298 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1299 if (!isUInt<20>(AM.BaseOffs)) 1300 return false; 1301 } else 1302 llvm_unreachable("unhandled generation"); 1303 1304 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1305 return true; 1306 1307 if (AM.Scale == 1 && AM.HasBaseReg) 1308 return true; 1309 1310 return false; 1311 1312 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1313 return isLegalMUBUFAddressingMode(AM); 1314 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1315 AS == AMDGPUAS::REGION_ADDRESS) { 1316 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1317 // field. 1318 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1319 // an 8-bit dword offset but we don't know the alignment here. 1320 if (!isUInt<16>(AM.BaseOffs)) 1321 return false; 1322 1323 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1324 return true; 1325 1326 if (AM.Scale == 1 && AM.HasBaseReg) 1327 return true; 1328 1329 return false; 1330 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1331 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1332 // For an unknown address space, this usually means that this is for some 1333 // reason being used for pure arithmetic, and not based on some addressing 1334 // computation. We don't have instructions that compute pointers with any 1335 // addressing modes, so treat them as having no offset like flat 1336 // instructions. 1337 return isLegalFlatAddressingMode(AM); 1338 } 1339 1340 // Assume a user alias of global for unknown address spaces. 1341 return isLegalGlobalAddressingMode(AM); 1342 } 1343 1344 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1345 const SelectionDAG &DAG) const { 1346 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1347 return (MemVT.getSizeInBits() <= 4 * 32); 1348 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1349 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1350 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1351 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1352 return (MemVT.getSizeInBits() <= 2 * 32); 1353 } 1354 return true; 1355 } 1356 1357 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1358 unsigned Size, unsigned AddrSpace, unsigned Align, 1359 MachineMemOperand::Flags Flags, bool *IsFast) const { 1360 if (IsFast) 1361 *IsFast = false; 1362 1363 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1364 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1365 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1366 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1367 // with adjacent offsets. 1368 bool AlignedBy4 = (Align % 4 == 0); 1369 if (IsFast) 1370 *IsFast = AlignedBy4; 1371 1372 return AlignedBy4; 1373 } 1374 1375 // FIXME: We have to be conservative here and assume that flat operations 1376 // will access scratch. If we had access to the IR function, then we 1377 // could determine if any private memory was used in the function. 1378 if (!Subtarget->hasUnalignedScratchAccess() && 1379 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1380 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1381 bool AlignedBy4 = Align >= 4; 1382 if (IsFast) 1383 *IsFast = AlignedBy4; 1384 1385 return AlignedBy4; 1386 } 1387 1388 if (Subtarget->hasUnalignedBufferAccess()) { 1389 // If we have an uniform constant load, it still requires using a slow 1390 // buffer instruction if unaligned. 1391 if (IsFast) { 1392 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1393 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1394 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1395 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1396 Align >= 4 : Align != 2; 1397 } 1398 1399 return true; 1400 } 1401 1402 // Smaller than dword value must be aligned. 1403 if (Size < 32) 1404 return false; 1405 1406 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1407 // byte-address are ignored, thus forcing Dword alignment. 1408 // This applies to private, global, and constant memory. 1409 if (IsFast) 1410 *IsFast = true; 1411 1412 return Size >= 32 && Align >= 4; 1413 } 1414 1415 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1416 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1417 bool *IsFast) const { 1418 if (IsFast) 1419 *IsFast = false; 1420 1421 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1422 // which isn't a simple VT. 1423 // Until MVT is extended to handle this, simply check for the size and 1424 // rely on the condition below: allow accesses if the size is a multiple of 4. 1425 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1426 VT.getStoreSize() > 16)) { 1427 return false; 1428 } 1429 1430 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1431 Align, Flags, IsFast); 1432 } 1433 1434 EVT SITargetLowering::getOptimalMemOpType( 1435 const MemOp &Op, const AttributeList &FuncAttributes) const { 1436 // FIXME: Should account for address space here. 1437 1438 // The default fallback uses the private pointer size as a guess for a type to 1439 // use. Make sure we switch these to 64-bit accesses. 1440 1441 if (Op.size() >= 16 && 1442 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1443 return MVT::v4i32; 1444 1445 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1446 return MVT::v2i32; 1447 1448 // Use the default. 1449 return MVT::Other; 1450 } 1451 1452 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1453 unsigned DestAS) const { 1454 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1455 } 1456 1457 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1458 const MemSDNode *MemNode = cast<MemSDNode>(N); 1459 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1460 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1461 return I && I->getMetadata("amdgpu.noclobber"); 1462 } 1463 1464 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1465 unsigned DestAS) const { 1466 // Flat -> private/local is a simple truncate. 1467 // Flat -> global is no-op 1468 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1469 return true; 1470 1471 return isNoopAddrSpaceCast(SrcAS, DestAS); 1472 } 1473 1474 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1475 const MemSDNode *MemNode = cast<MemSDNode>(N); 1476 1477 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1478 } 1479 1480 TargetLoweringBase::LegalizeTypeAction 1481 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1482 int NumElts = VT.getVectorNumElements(); 1483 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1484 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1485 return TargetLoweringBase::getPreferredVectorAction(VT); 1486 } 1487 1488 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1489 Type *Ty) const { 1490 // FIXME: Could be smarter if called for vector constants. 1491 return true; 1492 } 1493 1494 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1495 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1496 switch (Op) { 1497 case ISD::LOAD: 1498 case ISD::STORE: 1499 1500 // These operations are done with 32-bit instructions anyway. 1501 case ISD::AND: 1502 case ISD::OR: 1503 case ISD::XOR: 1504 case ISD::SELECT: 1505 // TODO: Extensions? 1506 return true; 1507 default: 1508 return false; 1509 } 1510 } 1511 1512 // SimplifySetCC uses this function to determine whether or not it should 1513 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1514 if (VT == MVT::i1 && Op == ISD::SETCC) 1515 return false; 1516 1517 return TargetLowering::isTypeDesirableForOp(Op, VT); 1518 } 1519 1520 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1521 const SDLoc &SL, 1522 SDValue Chain, 1523 uint64_t Offset) const { 1524 const DataLayout &DL = DAG.getDataLayout(); 1525 MachineFunction &MF = DAG.getMachineFunction(); 1526 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1527 1528 const ArgDescriptor *InputPtrReg; 1529 const TargetRegisterClass *RC; 1530 1531 std::tie(InputPtrReg, RC) 1532 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1533 1534 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1535 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1536 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1537 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1538 1539 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1540 } 1541 1542 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1543 const SDLoc &SL) const { 1544 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1545 FIRST_IMPLICIT); 1546 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1547 } 1548 1549 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1550 const SDLoc &SL, SDValue Val, 1551 bool Signed, 1552 const ISD::InputArg *Arg) const { 1553 // First, if it is a widened vector, narrow it. 1554 if (VT.isVector() && 1555 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1556 EVT NarrowedVT = 1557 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1558 VT.getVectorNumElements()); 1559 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1560 DAG.getConstant(0, SL, MVT::i32)); 1561 } 1562 1563 // Then convert the vector elements or scalar value. 1564 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1565 VT.bitsLT(MemVT)) { 1566 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1567 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1568 } 1569 1570 if (MemVT.isFloatingPoint()) 1571 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1572 else if (Signed) 1573 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1574 else 1575 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1576 1577 return Val; 1578 } 1579 1580 SDValue SITargetLowering::lowerKernargMemParameter( 1581 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1582 uint64_t Offset, Align Alignment, bool Signed, 1583 const ISD::InputArg *Arg) const { 1584 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1585 1586 // Try to avoid using an extload by loading earlier than the argument address, 1587 // and extracting the relevant bits. The load should hopefully be merged with 1588 // the previous argument. 1589 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1590 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1591 int64_t AlignDownOffset = alignDown(Offset, 4); 1592 int64_t OffsetDiff = Offset - AlignDownOffset; 1593 1594 EVT IntVT = MemVT.changeTypeToInteger(); 1595 1596 // TODO: If we passed in the base kernel offset we could have a better 1597 // alignment than 4, but we don't really need it. 1598 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1599 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1600 MachineMemOperand::MODereferenceable | 1601 MachineMemOperand::MOInvariant); 1602 1603 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1604 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1605 1606 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1607 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1608 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1609 1610 1611 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1612 } 1613 1614 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1615 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1616 MachineMemOperand::MODereferenceable | 1617 MachineMemOperand::MOInvariant); 1618 1619 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1620 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1621 } 1622 1623 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1624 const SDLoc &SL, SDValue Chain, 1625 const ISD::InputArg &Arg) const { 1626 MachineFunction &MF = DAG.getMachineFunction(); 1627 MachineFrameInfo &MFI = MF.getFrameInfo(); 1628 1629 if (Arg.Flags.isByVal()) { 1630 unsigned Size = Arg.Flags.getByValSize(); 1631 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1632 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1633 } 1634 1635 unsigned ArgOffset = VA.getLocMemOffset(); 1636 unsigned ArgSize = VA.getValVT().getStoreSize(); 1637 1638 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1639 1640 // Create load nodes to retrieve arguments from the stack. 1641 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1642 SDValue ArgValue; 1643 1644 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1645 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1646 MVT MemVT = VA.getValVT(); 1647 1648 switch (VA.getLocInfo()) { 1649 default: 1650 break; 1651 case CCValAssign::BCvt: 1652 MemVT = VA.getLocVT(); 1653 break; 1654 case CCValAssign::SExt: 1655 ExtType = ISD::SEXTLOAD; 1656 break; 1657 case CCValAssign::ZExt: 1658 ExtType = ISD::ZEXTLOAD; 1659 break; 1660 case CCValAssign::AExt: 1661 ExtType = ISD::EXTLOAD; 1662 break; 1663 } 1664 1665 ArgValue = DAG.getExtLoad( 1666 ExtType, SL, VA.getLocVT(), Chain, FIN, 1667 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1668 MemVT); 1669 return ArgValue; 1670 } 1671 1672 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1673 const SIMachineFunctionInfo &MFI, 1674 EVT VT, 1675 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1676 const ArgDescriptor *Reg; 1677 const TargetRegisterClass *RC; 1678 1679 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1680 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1681 } 1682 1683 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1684 CallingConv::ID CallConv, 1685 ArrayRef<ISD::InputArg> Ins, 1686 BitVector &Skipped, 1687 FunctionType *FType, 1688 SIMachineFunctionInfo *Info) { 1689 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1690 const ISD::InputArg *Arg = &Ins[I]; 1691 1692 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1693 "vector type argument should have been split"); 1694 1695 // First check if it's a PS input addr. 1696 if (CallConv == CallingConv::AMDGPU_PS && 1697 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1698 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1699 1700 // Inconveniently only the first part of the split is marked as isSplit, 1701 // so skip to the end. We only want to increment PSInputNum once for the 1702 // entire split argument. 1703 if (Arg->Flags.isSplit()) { 1704 while (!Arg->Flags.isSplitEnd()) { 1705 assert((!Arg->VT.isVector() || 1706 Arg->VT.getScalarSizeInBits() == 16) && 1707 "unexpected vector split in ps argument type"); 1708 if (!SkipArg) 1709 Splits.push_back(*Arg); 1710 Arg = &Ins[++I]; 1711 } 1712 } 1713 1714 if (SkipArg) { 1715 // We can safely skip PS inputs. 1716 Skipped.set(Arg->getOrigArgIndex()); 1717 ++PSInputNum; 1718 continue; 1719 } 1720 1721 Info->markPSInputAllocated(PSInputNum); 1722 if (Arg->Used) 1723 Info->markPSInputEnabled(PSInputNum); 1724 1725 ++PSInputNum; 1726 } 1727 1728 Splits.push_back(*Arg); 1729 } 1730 } 1731 1732 // Allocate special inputs passed in VGPRs. 1733 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1734 MachineFunction &MF, 1735 const SIRegisterInfo &TRI, 1736 SIMachineFunctionInfo &Info) const { 1737 const LLT S32 = LLT::scalar(32); 1738 MachineRegisterInfo &MRI = MF.getRegInfo(); 1739 1740 if (Info.hasWorkItemIDX()) { 1741 Register Reg = AMDGPU::VGPR0; 1742 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1743 1744 CCInfo.AllocateReg(Reg); 1745 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1746 } 1747 1748 if (Info.hasWorkItemIDY()) { 1749 Register Reg = AMDGPU::VGPR1; 1750 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1751 1752 CCInfo.AllocateReg(Reg); 1753 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1754 } 1755 1756 if (Info.hasWorkItemIDZ()) { 1757 Register Reg = AMDGPU::VGPR2; 1758 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1759 1760 CCInfo.AllocateReg(Reg); 1761 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1762 } 1763 } 1764 1765 // Try to allocate a VGPR at the end of the argument list, or if no argument 1766 // VGPRs are left allocating a stack slot. 1767 // If \p Mask is is given it indicates bitfield position in the register. 1768 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1769 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1770 ArgDescriptor Arg = ArgDescriptor()) { 1771 if (Arg.isSet()) 1772 return ArgDescriptor::createArg(Arg, Mask); 1773 1774 ArrayRef<MCPhysReg> ArgVGPRs 1775 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1776 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1777 if (RegIdx == ArgVGPRs.size()) { 1778 // Spill to stack required. 1779 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1780 1781 return ArgDescriptor::createStack(Offset, Mask); 1782 } 1783 1784 unsigned Reg = ArgVGPRs[RegIdx]; 1785 Reg = CCInfo.AllocateReg(Reg); 1786 assert(Reg != AMDGPU::NoRegister); 1787 1788 MachineFunction &MF = CCInfo.getMachineFunction(); 1789 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1790 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1791 return ArgDescriptor::createRegister(Reg, Mask); 1792 } 1793 1794 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1795 const TargetRegisterClass *RC, 1796 unsigned NumArgRegs) { 1797 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1798 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1799 if (RegIdx == ArgSGPRs.size()) 1800 report_fatal_error("ran out of SGPRs for arguments"); 1801 1802 unsigned Reg = ArgSGPRs[RegIdx]; 1803 Reg = CCInfo.AllocateReg(Reg); 1804 assert(Reg != AMDGPU::NoRegister); 1805 1806 MachineFunction &MF = CCInfo.getMachineFunction(); 1807 MF.addLiveIn(Reg, RC); 1808 return ArgDescriptor::createRegister(Reg); 1809 } 1810 1811 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1812 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1813 } 1814 1815 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1816 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1817 } 1818 1819 /// Allocate implicit function VGPR arguments at the end of allocated user 1820 /// arguments. 1821 void SITargetLowering::allocateSpecialInputVGPRs( 1822 CCState &CCInfo, MachineFunction &MF, 1823 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1824 const unsigned Mask = 0x3ff; 1825 ArgDescriptor Arg; 1826 1827 if (Info.hasWorkItemIDX()) { 1828 Arg = allocateVGPR32Input(CCInfo, Mask); 1829 Info.setWorkItemIDX(Arg); 1830 } 1831 1832 if (Info.hasWorkItemIDY()) { 1833 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1834 Info.setWorkItemIDY(Arg); 1835 } 1836 1837 if (Info.hasWorkItemIDZ()) 1838 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1839 } 1840 1841 /// Allocate implicit function VGPR arguments in fixed registers. 1842 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1843 CCState &CCInfo, MachineFunction &MF, 1844 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1845 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1846 if (!Reg) 1847 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1848 1849 const unsigned Mask = 0x3ff; 1850 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1851 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1852 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1853 } 1854 1855 void SITargetLowering::allocateSpecialInputSGPRs( 1856 CCState &CCInfo, 1857 MachineFunction &MF, 1858 const SIRegisterInfo &TRI, 1859 SIMachineFunctionInfo &Info) const { 1860 auto &ArgInfo = Info.getArgInfo(); 1861 1862 // TODO: Unify handling with private memory pointers. 1863 1864 if (Info.hasDispatchPtr()) 1865 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1866 1867 if (Info.hasQueuePtr()) 1868 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1869 1870 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1871 // constant offset from the kernarg segment. 1872 if (Info.hasImplicitArgPtr()) 1873 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1874 1875 if (Info.hasDispatchID()) 1876 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1877 1878 // flat_scratch_init is not applicable for non-kernel functions. 1879 1880 if (Info.hasWorkGroupIDX()) 1881 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1882 1883 if (Info.hasWorkGroupIDY()) 1884 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1885 1886 if (Info.hasWorkGroupIDZ()) 1887 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1888 } 1889 1890 // Allocate special inputs passed in user SGPRs. 1891 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1892 MachineFunction &MF, 1893 const SIRegisterInfo &TRI, 1894 SIMachineFunctionInfo &Info) const { 1895 if (Info.hasImplicitBufferPtr()) { 1896 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1897 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1898 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1899 } 1900 1901 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1902 if (Info.hasPrivateSegmentBuffer()) { 1903 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1904 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1905 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1906 } 1907 1908 if (Info.hasDispatchPtr()) { 1909 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1910 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1911 CCInfo.AllocateReg(DispatchPtrReg); 1912 } 1913 1914 if (Info.hasQueuePtr()) { 1915 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1916 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1917 CCInfo.AllocateReg(QueuePtrReg); 1918 } 1919 1920 if (Info.hasKernargSegmentPtr()) { 1921 MachineRegisterInfo &MRI = MF.getRegInfo(); 1922 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1923 CCInfo.AllocateReg(InputPtrReg); 1924 1925 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1926 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1927 } 1928 1929 if (Info.hasDispatchID()) { 1930 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1931 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1932 CCInfo.AllocateReg(DispatchIDReg); 1933 } 1934 1935 if (Info.hasFlatScratchInit()) { 1936 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1937 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1938 CCInfo.AllocateReg(FlatScratchInitReg); 1939 } 1940 1941 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1942 // these from the dispatch pointer. 1943 } 1944 1945 // Allocate special input registers that are initialized per-wave. 1946 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1947 MachineFunction &MF, 1948 SIMachineFunctionInfo &Info, 1949 CallingConv::ID CallConv, 1950 bool IsShader) const { 1951 if (Info.hasWorkGroupIDX()) { 1952 unsigned Reg = Info.addWorkGroupIDX(); 1953 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1954 CCInfo.AllocateReg(Reg); 1955 } 1956 1957 if (Info.hasWorkGroupIDY()) { 1958 unsigned Reg = Info.addWorkGroupIDY(); 1959 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1960 CCInfo.AllocateReg(Reg); 1961 } 1962 1963 if (Info.hasWorkGroupIDZ()) { 1964 unsigned Reg = Info.addWorkGroupIDZ(); 1965 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1966 CCInfo.AllocateReg(Reg); 1967 } 1968 1969 if (Info.hasWorkGroupInfo()) { 1970 unsigned Reg = Info.addWorkGroupInfo(); 1971 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1972 CCInfo.AllocateReg(Reg); 1973 } 1974 1975 if (Info.hasPrivateSegmentWaveByteOffset()) { 1976 // Scratch wave offset passed in system SGPR. 1977 unsigned PrivateSegmentWaveByteOffsetReg; 1978 1979 if (IsShader) { 1980 PrivateSegmentWaveByteOffsetReg = 1981 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1982 1983 // This is true if the scratch wave byte offset doesn't have a fixed 1984 // location. 1985 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1986 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1987 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1988 } 1989 } else 1990 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1991 1992 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1993 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1994 } 1995 } 1996 1997 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1998 MachineFunction &MF, 1999 const SIRegisterInfo &TRI, 2000 SIMachineFunctionInfo &Info) { 2001 // Now that we've figured out where the scratch register inputs are, see if 2002 // should reserve the arguments and use them directly. 2003 MachineFrameInfo &MFI = MF.getFrameInfo(); 2004 bool HasStackObjects = MFI.hasStackObjects(); 2005 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2006 2007 // Record that we know we have non-spill stack objects so we don't need to 2008 // check all stack objects later. 2009 if (HasStackObjects) 2010 Info.setHasNonSpillStackObjects(true); 2011 2012 // Everything live out of a block is spilled with fast regalloc, so it's 2013 // almost certain that spilling will be required. 2014 if (TM.getOptLevel() == CodeGenOpt::None) 2015 HasStackObjects = true; 2016 2017 // For now assume stack access is needed in any callee functions, so we need 2018 // the scratch registers to pass in. 2019 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2020 2021 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2022 // If we have stack objects, we unquestionably need the private buffer 2023 // resource. For the Code Object V2 ABI, this will be the first 4 user 2024 // SGPR inputs. We can reserve those and use them directly. 2025 2026 Register PrivateSegmentBufferReg = 2027 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2028 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2029 } else { 2030 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2031 // We tentatively reserve the last registers (skipping the last registers 2032 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2033 // we'll replace these with the ones immediately after those which were 2034 // really allocated. In the prologue copies will be inserted from the 2035 // argument to these reserved registers. 2036 2037 // Without HSA, relocations are used for the scratch pointer and the 2038 // buffer resource setup is always inserted in the prologue. Scratch wave 2039 // offset is still in an input SGPR. 2040 Info.setScratchRSrcReg(ReservedBufferReg); 2041 } 2042 2043 MachineRegisterInfo &MRI = MF.getRegInfo(); 2044 2045 // For entry functions we have to set up the stack pointer if we use it, 2046 // whereas non-entry functions get this "for free". This means there is no 2047 // intrinsic advantage to using S32 over S34 in cases where we do not have 2048 // calls but do need a frame pointer (i.e. if we are requested to have one 2049 // because frame pointer elimination is disabled). To keep things simple we 2050 // only ever use S32 as the call ABI stack pointer, and so using it does not 2051 // imply we need a separate frame pointer. 2052 // 2053 // Try to use s32 as the SP, but move it if it would interfere with input 2054 // arguments. This won't work with calls though. 2055 // 2056 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2057 // registers. 2058 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2059 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2060 } else { 2061 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2062 2063 if (MFI.hasCalls()) 2064 report_fatal_error("call in graphics shader with too many input SGPRs"); 2065 2066 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2067 if (!MRI.isLiveIn(Reg)) { 2068 Info.setStackPtrOffsetReg(Reg); 2069 break; 2070 } 2071 } 2072 2073 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2074 report_fatal_error("failed to find register for SP"); 2075 } 2076 2077 // hasFP should be accurate for entry functions even before the frame is 2078 // finalized, because it does not rely on the known stack size, only 2079 // properties like whether variable sized objects are present. 2080 if (ST.getFrameLowering()->hasFP(MF)) { 2081 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2082 } 2083 } 2084 2085 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2086 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2087 return !Info->isEntryFunction(); 2088 } 2089 2090 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2091 2092 } 2093 2094 void SITargetLowering::insertCopiesSplitCSR( 2095 MachineBasicBlock *Entry, 2096 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2097 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2098 2099 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2100 if (!IStart) 2101 return; 2102 2103 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2104 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2105 MachineBasicBlock::iterator MBBI = Entry->begin(); 2106 for (const MCPhysReg *I = IStart; *I; ++I) { 2107 const TargetRegisterClass *RC = nullptr; 2108 if (AMDGPU::SReg_64RegClass.contains(*I)) 2109 RC = &AMDGPU::SGPR_64RegClass; 2110 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2111 RC = &AMDGPU::SGPR_32RegClass; 2112 else 2113 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2114 2115 Register NewVR = MRI->createVirtualRegister(RC); 2116 // Create copy from CSR to a virtual register. 2117 Entry->addLiveIn(*I); 2118 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2119 .addReg(*I); 2120 2121 // Insert the copy-back instructions right before the terminator. 2122 for (auto *Exit : Exits) 2123 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2124 TII->get(TargetOpcode::COPY), *I) 2125 .addReg(NewVR); 2126 } 2127 } 2128 2129 SDValue SITargetLowering::LowerFormalArguments( 2130 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2131 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2132 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2133 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2134 2135 MachineFunction &MF = DAG.getMachineFunction(); 2136 const Function &Fn = MF.getFunction(); 2137 FunctionType *FType = MF.getFunction().getFunctionType(); 2138 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2139 2140 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2141 DiagnosticInfoUnsupported NoGraphicsHSA( 2142 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2143 DAG.getContext()->diagnose(NoGraphicsHSA); 2144 return DAG.getEntryNode(); 2145 } 2146 2147 SmallVector<ISD::InputArg, 16> Splits; 2148 SmallVector<CCValAssign, 16> ArgLocs; 2149 BitVector Skipped(Ins.size()); 2150 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2151 *DAG.getContext()); 2152 2153 bool IsShader = AMDGPU::isShader(CallConv); 2154 bool IsKernel = AMDGPU::isKernel(CallConv); 2155 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2156 2157 if (IsShader) { 2158 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2159 2160 // At least one interpolation mode must be enabled or else the GPU will 2161 // hang. 2162 // 2163 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2164 // set PSInputAddr, the user wants to enable some bits after the compilation 2165 // based on run-time states. Since we can't know what the final PSInputEna 2166 // will look like, so we shouldn't do anything here and the user should take 2167 // responsibility for the correct programming. 2168 // 2169 // Otherwise, the following restrictions apply: 2170 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2171 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2172 // enabled too. 2173 if (CallConv == CallingConv::AMDGPU_PS) { 2174 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2175 ((Info->getPSInputAddr() & 0xF) == 0 && 2176 Info->isPSInputAllocated(11))) { 2177 CCInfo.AllocateReg(AMDGPU::VGPR0); 2178 CCInfo.AllocateReg(AMDGPU::VGPR1); 2179 Info->markPSInputAllocated(0); 2180 Info->markPSInputEnabled(0); 2181 } 2182 if (Subtarget->isAmdPalOS()) { 2183 // For isAmdPalOS, the user does not enable some bits after compilation 2184 // based on run-time states; the register values being generated here are 2185 // the final ones set in hardware. Therefore we need to apply the 2186 // workaround to PSInputAddr and PSInputEnable together. (The case where 2187 // a bit is set in PSInputAddr but not PSInputEnable is where the 2188 // frontend set up an input arg for a particular interpolation mode, but 2189 // nothing uses that input arg. Really we should have an earlier pass 2190 // that removes such an arg.) 2191 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2192 if ((PsInputBits & 0x7F) == 0 || 2193 ((PsInputBits & 0xF) == 0 && 2194 (PsInputBits >> 11 & 1))) 2195 Info->markPSInputEnabled( 2196 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2197 } 2198 } 2199 2200 assert(!Info->hasDispatchPtr() && 2201 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2202 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2203 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2204 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2205 !Info->hasWorkItemIDZ()); 2206 } else if (IsKernel) { 2207 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2208 } else { 2209 Splits.append(Ins.begin(), Ins.end()); 2210 } 2211 2212 if (IsEntryFunc) { 2213 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2214 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2215 } else { 2216 // For the fixed ABI, pass workitem IDs in the last argument register. 2217 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2218 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2219 } 2220 2221 if (IsKernel) { 2222 analyzeFormalArgumentsCompute(CCInfo, Ins); 2223 } else { 2224 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2225 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2226 } 2227 2228 SmallVector<SDValue, 16> Chains; 2229 2230 // FIXME: This is the minimum kernel argument alignment. We should improve 2231 // this to the maximum alignment of the arguments. 2232 // 2233 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2234 // kern arg offset. 2235 const Align KernelArgBaseAlign = Align(16); 2236 2237 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2238 const ISD::InputArg &Arg = Ins[i]; 2239 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2240 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2241 continue; 2242 } 2243 2244 CCValAssign &VA = ArgLocs[ArgIdx++]; 2245 MVT VT = VA.getLocVT(); 2246 2247 if (IsEntryFunc && VA.isMemLoc()) { 2248 VT = Ins[i].VT; 2249 EVT MemVT = VA.getLocVT(); 2250 2251 const uint64_t Offset = VA.getLocMemOffset(); 2252 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2253 2254 SDValue Arg = 2255 lowerKernargMemParameter(DAG, VT, MemVT, DL, Chain, Offset, Alignment, 2256 Ins[i].Flags.isSExt(), &Ins[i]); 2257 Chains.push_back(Arg.getValue(1)); 2258 2259 auto *ParamTy = 2260 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2261 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2262 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2263 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2264 // On SI local pointers are just offsets into LDS, so they are always 2265 // less than 16-bits. On CI and newer they could potentially be 2266 // real pointers, so we can't guarantee their size. 2267 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2268 DAG.getValueType(MVT::i16)); 2269 } 2270 2271 InVals.push_back(Arg); 2272 continue; 2273 } else if (!IsEntryFunc && VA.isMemLoc()) { 2274 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2275 InVals.push_back(Val); 2276 if (!Arg.Flags.isByVal()) 2277 Chains.push_back(Val.getValue(1)); 2278 continue; 2279 } 2280 2281 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2282 2283 Register Reg = VA.getLocReg(); 2284 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2285 EVT ValVT = VA.getValVT(); 2286 2287 Reg = MF.addLiveIn(Reg, RC); 2288 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2289 2290 if (Arg.Flags.isSRet()) { 2291 // The return object should be reasonably addressable. 2292 2293 // FIXME: This helps when the return is a real sret. If it is a 2294 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2295 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2296 unsigned NumBits 2297 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2298 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2299 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2300 } 2301 2302 // If this is an 8 or 16-bit value, it is really passed promoted 2303 // to 32 bits. Insert an assert[sz]ext to capture this, then 2304 // truncate to the right size. 2305 switch (VA.getLocInfo()) { 2306 case CCValAssign::Full: 2307 break; 2308 case CCValAssign::BCvt: 2309 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2310 break; 2311 case CCValAssign::SExt: 2312 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2313 DAG.getValueType(ValVT)); 2314 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2315 break; 2316 case CCValAssign::ZExt: 2317 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2318 DAG.getValueType(ValVT)); 2319 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2320 break; 2321 case CCValAssign::AExt: 2322 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2323 break; 2324 default: 2325 llvm_unreachable("Unknown loc info!"); 2326 } 2327 2328 InVals.push_back(Val); 2329 } 2330 2331 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2332 // Special inputs come after user arguments. 2333 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2334 } 2335 2336 // Start adding system SGPRs. 2337 if (IsEntryFunc) { 2338 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2339 } else { 2340 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2341 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2342 } 2343 2344 auto &ArgUsageInfo = 2345 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2346 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2347 2348 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2349 Info->setBytesInStackArgArea(StackArgSize); 2350 2351 return Chains.empty() ? Chain : 2352 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2353 } 2354 2355 // TODO: If return values can't fit in registers, we should return as many as 2356 // possible in registers before passing on stack. 2357 bool SITargetLowering::CanLowerReturn( 2358 CallingConv::ID CallConv, 2359 MachineFunction &MF, bool IsVarArg, 2360 const SmallVectorImpl<ISD::OutputArg> &Outs, 2361 LLVMContext &Context) const { 2362 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2363 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2364 // for shaders. Vector types should be explicitly handled by CC. 2365 if (AMDGPU::isEntryFunctionCC(CallConv)) 2366 return true; 2367 2368 SmallVector<CCValAssign, 16> RVLocs; 2369 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2370 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2371 } 2372 2373 SDValue 2374 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2375 bool isVarArg, 2376 const SmallVectorImpl<ISD::OutputArg> &Outs, 2377 const SmallVectorImpl<SDValue> &OutVals, 2378 const SDLoc &DL, SelectionDAG &DAG) const { 2379 MachineFunction &MF = DAG.getMachineFunction(); 2380 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2381 2382 if (AMDGPU::isKernel(CallConv)) { 2383 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2384 OutVals, DL, DAG); 2385 } 2386 2387 bool IsShader = AMDGPU::isShader(CallConv); 2388 2389 Info->setIfReturnsVoid(Outs.empty()); 2390 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2391 2392 // CCValAssign - represent the assignment of the return value to a location. 2393 SmallVector<CCValAssign, 48> RVLocs; 2394 SmallVector<ISD::OutputArg, 48> Splits; 2395 2396 // CCState - Info about the registers and stack slots. 2397 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2398 *DAG.getContext()); 2399 2400 // Analyze outgoing return values. 2401 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2402 2403 SDValue Flag; 2404 SmallVector<SDValue, 48> RetOps; 2405 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2406 2407 // Add return address for callable functions. 2408 if (!Info->isEntryFunction()) { 2409 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2410 SDValue ReturnAddrReg = CreateLiveInRegister( 2411 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2412 2413 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2414 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2415 MVT::i64); 2416 Chain = 2417 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2418 Flag = Chain.getValue(1); 2419 RetOps.push_back(ReturnAddrVirtualReg); 2420 } 2421 2422 // Copy the result values into the output registers. 2423 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2424 ++I, ++RealRVLocIdx) { 2425 CCValAssign &VA = RVLocs[I]; 2426 assert(VA.isRegLoc() && "Can only return in registers!"); 2427 // TODO: Partially return in registers if return values don't fit. 2428 SDValue Arg = OutVals[RealRVLocIdx]; 2429 2430 // Copied from other backends. 2431 switch (VA.getLocInfo()) { 2432 case CCValAssign::Full: 2433 break; 2434 case CCValAssign::BCvt: 2435 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2436 break; 2437 case CCValAssign::SExt: 2438 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2439 break; 2440 case CCValAssign::ZExt: 2441 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2442 break; 2443 case CCValAssign::AExt: 2444 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2445 break; 2446 default: 2447 llvm_unreachable("Unknown loc info!"); 2448 } 2449 2450 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2451 Flag = Chain.getValue(1); 2452 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2453 } 2454 2455 // FIXME: Does sret work properly? 2456 if (!Info->isEntryFunction()) { 2457 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2458 const MCPhysReg *I = 2459 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2460 if (I) { 2461 for (; *I; ++I) { 2462 if (AMDGPU::SReg_64RegClass.contains(*I)) 2463 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2464 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2465 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2466 else 2467 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2468 } 2469 } 2470 } 2471 2472 // Update chain and glue. 2473 RetOps[0] = Chain; 2474 if (Flag.getNode()) 2475 RetOps.push_back(Flag); 2476 2477 unsigned Opc = AMDGPUISD::ENDPGM; 2478 if (!IsWaveEnd) 2479 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2480 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2481 } 2482 2483 SDValue SITargetLowering::LowerCallResult( 2484 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2485 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2486 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2487 SDValue ThisVal) const { 2488 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2489 2490 // Assign locations to each value returned by this call. 2491 SmallVector<CCValAssign, 16> RVLocs; 2492 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2493 *DAG.getContext()); 2494 CCInfo.AnalyzeCallResult(Ins, RetCC); 2495 2496 // Copy all of the result registers out of their specified physreg. 2497 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2498 CCValAssign VA = RVLocs[i]; 2499 SDValue Val; 2500 2501 if (VA.isRegLoc()) { 2502 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2503 Chain = Val.getValue(1); 2504 InFlag = Val.getValue(2); 2505 } else if (VA.isMemLoc()) { 2506 report_fatal_error("TODO: return values in memory"); 2507 } else 2508 llvm_unreachable("unknown argument location type"); 2509 2510 switch (VA.getLocInfo()) { 2511 case CCValAssign::Full: 2512 break; 2513 case CCValAssign::BCvt: 2514 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2515 break; 2516 case CCValAssign::ZExt: 2517 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2518 DAG.getValueType(VA.getValVT())); 2519 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2520 break; 2521 case CCValAssign::SExt: 2522 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2523 DAG.getValueType(VA.getValVT())); 2524 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2525 break; 2526 case CCValAssign::AExt: 2527 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2528 break; 2529 default: 2530 llvm_unreachable("Unknown loc info!"); 2531 } 2532 2533 InVals.push_back(Val); 2534 } 2535 2536 return Chain; 2537 } 2538 2539 // Add code to pass special inputs required depending on used features separate 2540 // from the explicit user arguments present in the IR. 2541 void SITargetLowering::passSpecialInputs( 2542 CallLoweringInfo &CLI, 2543 CCState &CCInfo, 2544 const SIMachineFunctionInfo &Info, 2545 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2546 SmallVectorImpl<SDValue> &MemOpChains, 2547 SDValue Chain) const { 2548 // If we don't have a call site, this was a call inserted by 2549 // legalization. These can never use special inputs. 2550 if (!CLI.CB) 2551 return; 2552 2553 SelectionDAG &DAG = CLI.DAG; 2554 const SDLoc &DL = CLI.DL; 2555 2556 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2557 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2558 2559 const AMDGPUFunctionArgInfo *CalleeArgInfo 2560 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2561 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2562 auto &ArgUsageInfo = 2563 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2564 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2565 } 2566 2567 // TODO: Unify with private memory register handling. This is complicated by 2568 // the fact that at least in kernels, the input argument is not necessarily 2569 // in the same location as the input. 2570 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2571 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2572 AMDGPUFunctionArgInfo::QUEUE_PTR, 2573 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2574 AMDGPUFunctionArgInfo::DISPATCH_ID, 2575 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2576 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2577 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2578 }; 2579 2580 for (auto InputID : InputRegs) { 2581 const ArgDescriptor *OutgoingArg; 2582 const TargetRegisterClass *ArgRC; 2583 2584 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID); 2585 if (!OutgoingArg) 2586 continue; 2587 2588 const ArgDescriptor *IncomingArg; 2589 const TargetRegisterClass *IncomingArgRC; 2590 std::tie(IncomingArg, IncomingArgRC) 2591 = CallerArgInfo.getPreloadedValue(InputID); 2592 assert(IncomingArgRC == ArgRC); 2593 2594 // All special arguments are ints for now. 2595 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2596 SDValue InputReg; 2597 2598 if (IncomingArg) { 2599 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2600 } else { 2601 // The implicit arg ptr is special because it doesn't have a corresponding 2602 // input for kernels, and is computed from the kernarg segment pointer. 2603 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2604 InputReg = getImplicitArgPtr(DAG, DL); 2605 } 2606 2607 if (OutgoingArg->isRegister()) { 2608 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2609 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2610 report_fatal_error("failed to allocate implicit input argument"); 2611 } else { 2612 unsigned SpecialArgOffset = 2613 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2614 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2615 SpecialArgOffset); 2616 MemOpChains.push_back(ArgStore); 2617 } 2618 } 2619 2620 // Pack workitem IDs into a single register or pass it as is if already 2621 // packed. 2622 const ArgDescriptor *OutgoingArg; 2623 const TargetRegisterClass *ArgRC; 2624 2625 std::tie(OutgoingArg, ArgRC) = 2626 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2627 if (!OutgoingArg) 2628 std::tie(OutgoingArg, ArgRC) = 2629 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2630 if (!OutgoingArg) 2631 std::tie(OutgoingArg, ArgRC) = 2632 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2633 if (!OutgoingArg) 2634 return; 2635 2636 const ArgDescriptor *IncomingArgX 2637 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first; 2638 const ArgDescriptor *IncomingArgY 2639 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first; 2640 const ArgDescriptor *IncomingArgZ 2641 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first; 2642 2643 SDValue InputReg; 2644 SDLoc SL; 2645 2646 // If incoming ids are not packed we need to pack them. 2647 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2648 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2649 2650 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2651 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2652 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2653 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2654 InputReg = InputReg.getNode() ? 2655 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2656 } 2657 2658 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2659 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2660 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2661 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2662 InputReg = InputReg.getNode() ? 2663 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2664 } 2665 2666 if (!InputReg.getNode()) { 2667 // Workitem ids are already packed, any of present incoming arguments 2668 // will carry all required fields. 2669 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2670 IncomingArgX ? *IncomingArgX : 2671 IncomingArgY ? *IncomingArgY : 2672 *IncomingArgZ, ~0u); 2673 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2674 } 2675 2676 if (OutgoingArg->isRegister()) { 2677 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2678 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2679 } else { 2680 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2681 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2682 SpecialArgOffset); 2683 MemOpChains.push_back(ArgStore); 2684 } 2685 } 2686 2687 static bool canGuaranteeTCO(CallingConv::ID CC) { 2688 return CC == CallingConv::Fast; 2689 } 2690 2691 /// Return true if we might ever do TCO for calls with this calling convention. 2692 static bool mayTailCallThisCC(CallingConv::ID CC) { 2693 switch (CC) { 2694 case CallingConv::C: 2695 return true; 2696 default: 2697 return canGuaranteeTCO(CC); 2698 } 2699 } 2700 2701 bool SITargetLowering::isEligibleForTailCallOptimization( 2702 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2703 const SmallVectorImpl<ISD::OutputArg> &Outs, 2704 const SmallVectorImpl<SDValue> &OutVals, 2705 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2706 if (!mayTailCallThisCC(CalleeCC)) 2707 return false; 2708 2709 MachineFunction &MF = DAG.getMachineFunction(); 2710 const Function &CallerF = MF.getFunction(); 2711 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2712 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2713 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2714 2715 // Kernels aren't callable, and don't have a live in return address so it 2716 // doesn't make sense to do a tail call with entry functions. 2717 if (!CallerPreserved) 2718 return false; 2719 2720 bool CCMatch = CallerCC == CalleeCC; 2721 2722 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2723 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2724 return true; 2725 return false; 2726 } 2727 2728 // TODO: Can we handle var args? 2729 if (IsVarArg) 2730 return false; 2731 2732 for (const Argument &Arg : CallerF.args()) { 2733 if (Arg.hasByValAttr()) 2734 return false; 2735 } 2736 2737 LLVMContext &Ctx = *DAG.getContext(); 2738 2739 // Check that the call results are passed in the same way. 2740 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2741 CCAssignFnForCall(CalleeCC, IsVarArg), 2742 CCAssignFnForCall(CallerCC, IsVarArg))) 2743 return false; 2744 2745 // The callee has to preserve all registers the caller needs to preserve. 2746 if (!CCMatch) { 2747 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2748 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2749 return false; 2750 } 2751 2752 // Nothing more to check if the callee is taking no arguments. 2753 if (Outs.empty()) 2754 return true; 2755 2756 SmallVector<CCValAssign, 16> ArgLocs; 2757 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2758 2759 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2760 2761 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2762 // If the stack arguments for this call do not fit into our own save area then 2763 // the call cannot be made tail. 2764 // TODO: Is this really necessary? 2765 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2766 return false; 2767 2768 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2769 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2770 } 2771 2772 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2773 if (!CI->isTailCall()) 2774 return false; 2775 2776 const Function *ParentFn = CI->getParent()->getParent(); 2777 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2778 return false; 2779 return true; 2780 } 2781 2782 // The wave scratch offset register is used as the global base pointer. 2783 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2784 SmallVectorImpl<SDValue> &InVals) const { 2785 SelectionDAG &DAG = CLI.DAG; 2786 const SDLoc &DL = CLI.DL; 2787 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2788 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2789 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2790 SDValue Chain = CLI.Chain; 2791 SDValue Callee = CLI.Callee; 2792 bool &IsTailCall = CLI.IsTailCall; 2793 CallingConv::ID CallConv = CLI.CallConv; 2794 bool IsVarArg = CLI.IsVarArg; 2795 bool IsSibCall = false; 2796 bool IsThisReturn = false; 2797 MachineFunction &MF = DAG.getMachineFunction(); 2798 2799 if (Callee.isUndef() || isNullConstant(Callee)) { 2800 if (!CLI.IsTailCall) { 2801 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2802 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2803 } 2804 2805 return Chain; 2806 } 2807 2808 if (IsVarArg) { 2809 return lowerUnhandledCall(CLI, InVals, 2810 "unsupported call to variadic function "); 2811 } 2812 2813 if (!CLI.CB) 2814 report_fatal_error("unsupported libcall legalization"); 2815 2816 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2817 !CLI.CB->getCalledFunction()) { 2818 return lowerUnhandledCall(CLI, InVals, 2819 "unsupported indirect call to function "); 2820 } 2821 2822 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2823 return lowerUnhandledCall(CLI, InVals, 2824 "unsupported required tail call to function "); 2825 } 2826 2827 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2828 // Note the issue is with the CC of the calling function, not of the call 2829 // itself. 2830 return lowerUnhandledCall(CLI, InVals, 2831 "unsupported call from graphics shader of function "); 2832 } 2833 2834 if (IsTailCall) { 2835 IsTailCall = isEligibleForTailCallOptimization( 2836 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2837 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2838 report_fatal_error("failed to perform tail call elimination on a call " 2839 "site marked musttail"); 2840 } 2841 2842 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2843 2844 // A sibling call is one where we're under the usual C ABI and not planning 2845 // to change that but can still do a tail call: 2846 if (!TailCallOpt && IsTailCall) 2847 IsSibCall = true; 2848 2849 if (IsTailCall) 2850 ++NumTailCalls; 2851 } 2852 2853 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2854 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2855 SmallVector<SDValue, 8> MemOpChains; 2856 2857 // Analyze operands of the call, assigning locations to each operand. 2858 SmallVector<CCValAssign, 16> ArgLocs; 2859 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2860 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2861 2862 if (AMDGPUTargetMachine::EnableFixedFunctionABI) { 2863 // With a fixed ABI, allocate fixed registers before user arguments. 2864 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2865 } 2866 2867 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2868 2869 // Get a count of how many bytes are to be pushed on the stack. 2870 unsigned NumBytes = CCInfo.getNextStackOffset(); 2871 2872 if (IsSibCall) { 2873 // Since we're not changing the ABI to make this a tail call, the memory 2874 // operands are already available in the caller's incoming argument space. 2875 NumBytes = 0; 2876 } 2877 2878 // FPDiff is the byte offset of the call's argument area from the callee's. 2879 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2880 // by this amount for a tail call. In a sibling call it must be 0 because the 2881 // caller will deallocate the entire stack and the callee still expects its 2882 // arguments to begin at SP+0. Completely unused for non-tail calls. 2883 int32_t FPDiff = 0; 2884 MachineFrameInfo &MFI = MF.getFrameInfo(); 2885 2886 // Adjust the stack pointer for the new arguments... 2887 // These operations are automatically eliminated by the prolog/epilog pass 2888 if (!IsSibCall) { 2889 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2890 2891 SmallVector<SDValue, 4> CopyFromChains; 2892 2893 // In the HSA case, this should be an identity copy. 2894 SDValue ScratchRSrcReg 2895 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2896 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2897 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2898 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2899 } 2900 2901 MVT PtrVT = MVT::i32; 2902 2903 // Walk the register/memloc assignments, inserting copies/loads. 2904 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2905 CCValAssign &VA = ArgLocs[i]; 2906 SDValue Arg = OutVals[i]; 2907 2908 // Promote the value if needed. 2909 switch (VA.getLocInfo()) { 2910 case CCValAssign::Full: 2911 break; 2912 case CCValAssign::BCvt: 2913 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2914 break; 2915 case CCValAssign::ZExt: 2916 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2917 break; 2918 case CCValAssign::SExt: 2919 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2920 break; 2921 case CCValAssign::AExt: 2922 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2923 break; 2924 case CCValAssign::FPExt: 2925 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2926 break; 2927 default: 2928 llvm_unreachable("Unknown loc info!"); 2929 } 2930 2931 if (VA.isRegLoc()) { 2932 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2933 } else { 2934 assert(VA.isMemLoc()); 2935 2936 SDValue DstAddr; 2937 MachinePointerInfo DstInfo; 2938 2939 unsigned LocMemOffset = VA.getLocMemOffset(); 2940 int32_t Offset = LocMemOffset; 2941 2942 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2943 MaybeAlign Alignment; 2944 2945 if (IsTailCall) { 2946 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2947 unsigned OpSize = Flags.isByVal() ? 2948 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2949 2950 // FIXME: We can have better than the minimum byval required alignment. 2951 Alignment = 2952 Flags.isByVal() 2953 ? Flags.getNonZeroByValAlign() 2954 : commonAlignment(Subtarget->getStackAlignment(), Offset); 2955 2956 Offset = Offset + FPDiff; 2957 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2958 2959 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2960 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2961 2962 // Make sure any stack arguments overlapping with where we're storing 2963 // are loaded before this eventual operation. Otherwise they'll be 2964 // clobbered. 2965 2966 // FIXME: Why is this really necessary? This seems to just result in a 2967 // lot of code to copy the stack and write them back to the same 2968 // locations, which are supposed to be immutable? 2969 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2970 } else { 2971 DstAddr = PtrOff; 2972 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2973 Alignment = 2974 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 2975 } 2976 2977 if (Outs[i].Flags.isByVal()) { 2978 SDValue SizeNode = 2979 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2980 SDValue Cpy = 2981 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 2982 Outs[i].Flags.getNonZeroByValAlign(), 2983 /*isVol = */ false, /*AlwaysInline = */ true, 2984 /*isTailCall = */ false, DstInfo, 2985 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 2986 2987 MemOpChains.push_back(Cpy); 2988 } else { 2989 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 2990 Alignment ? Alignment->value() : 0); 2991 MemOpChains.push_back(Store); 2992 } 2993 } 2994 } 2995 2996 if (!AMDGPUTargetMachine::EnableFixedFunctionABI) { 2997 // Copy special input registers after user input arguments. 2998 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2999 } 3000 3001 if (!MemOpChains.empty()) 3002 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3003 3004 // Build a sequence of copy-to-reg nodes chained together with token chain 3005 // and flag operands which copy the outgoing args into the appropriate regs. 3006 SDValue InFlag; 3007 for (auto &RegToPass : RegsToPass) { 3008 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3009 RegToPass.second, InFlag); 3010 InFlag = Chain.getValue(1); 3011 } 3012 3013 3014 SDValue PhysReturnAddrReg; 3015 if (IsTailCall) { 3016 // Since the return is being combined with the call, we need to pass on the 3017 // return address. 3018 3019 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3020 SDValue ReturnAddrReg = CreateLiveInRegister( 3021 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3022 3023 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3024 MVT::i64); 3025 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3026 InFlag = Chain.getValue(1); 3027 } 3028 3029 // We don't usually want to end the call-sequence here because we would tidy 3030 // the frame up *after* the call, however in the ABI-changing tail-call case 3031 // we've carefully laid out the parameters so that when sp is reset they'll be 3032 // in the correct location. 3033 if (IsTailCall && !IsSibCall) { 3034 Chain = DAG.getCALLSEQ_END(Chain, 3035 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3036 DAG.getTargetConstant(0, DL, MVT::i32), 3037 InFlag, DL); 3038 InFlag = Chain.getValue(1); 3039 } 3040 3041 std::vector<SDValue> Ops; 3042 Ops.push_back(Chain); 3043 Ops.push_back(Callee); 3044 // Add a redundant copy of the callee global which will not be legalized, as 3045 // we need direct access to the callee later. 3046 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3047 const GlobalValue *GV = GSD->getGlobal(); 3048 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3049 } else { 3050 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3051 } 3052 3053 if (IsTailCall) { 3054 // Each tail call may have to adjust the stack by a different amount, so 3055 // this information must travel along with the operation for eventual 3056 // consumption by emitEpilogue. 3057 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3058 3059 Ops.push_back(PhysReturnAddrReg); 3060 } 3061 3062 // Add argument registers to the end of the list so that they are known live 3063 // into the call. 3064 for (auto &RegToPass : RegsToPass) { 3065 Ops.push_back(DAG.getRegister(RegToPass.first, 3066 RegToPass.second.getValueType())); 3067 } 3068 3069 // Add a register mask operand representing the call-preserved registers. 3070 3071 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3072 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3073 assert(Mask && "Missing call preserved mask for calling convention"); 3074 Ops.push_back(DAG.getRegisterMask(Mask)); 3075 3076 if (InFlag.getNode()) 3077 Ops.push_back(InFlag); 3078 3079 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3080 3081 // If we're doing a tall call, use a TC_RETURN here rather than an 3082 // actual call instruction. 3083 if (IsTailCall) { 3084 MFI.setHasTailCall(); 3085 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3086 } 3087 3088 // Returns a chain and a flag for retval copy to use. 3089 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3090 Chain = Call.getValue(0); 3091 InFlag = Call.getValue(1); 3092 3093 uint64_t CalleePopBytes = NumBytes; 3094 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3095 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3096 InFlag, DL); 3097 if (!Ins.empty()) 3098 InFlag = Chain.getValue(1); 3099 3100 // Handle result values, copying them out of physregs into vregs that we 3101 // return. 3102 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3103 InVals, IsThisReturn, 3104 IsThisReturn ? OutVals[0] : SDValue()); 3105 } 3106 3107 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3108 // except for applying the wave size scale to the increment amount. 3109 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3110 SDValue Op, SelectionDAG &DAG) const { 3111 const MachineFunction &MF = DAG.getMachineFunction(); 3112 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3113 3114 SDLoc dl(Op); 3115 EVT VT = Op.getValueType(); 3116 SDValue Tmp1 = Op; 3117 SDValue Tmp2 = Op.getValue(1); 3118 SDValue Tmp3 = Op.getOperand(2); 3119 SDValue Chain = Tmp1.getOperand(0); 3120 3121 Register SPReg = Info->getStackPtrOffsetReg(); 3122 3123 // Chain the dynamic stack allocation so that it doesn't modify the stack 3124 // pointer when other instructions are using the stack. 3125 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3126 3127 SDValue Size = Tmp2.getOperand(1); 3128 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3129 Chain = SP.getValue(1); 3130 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3131 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3132 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3133 unsigned Opc = 3134 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3135 ISD::ADD : ISD::SUB; 3136 3137 SDValue ScaledSize = DAG.getNode( 3138 ISD::SHL, dl, VT, Size, 3139 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3140 3141 Align StackAlign = TFL->getStackAlign(); 3142 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3143 if (Alignment && *Alignment > StackAlign) { 3144 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3145 DAG.getConstant(-(uint64_t)Alignment->value() 3146 << ST.getWavefrontSizeLog2(), 3147 dl, VT)); 3148 } 3149 3150 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3151 Tmp2 = DAG.getCALLSEQ_END( 3152 Chain, DAG.getIntPtrConstant(0, dl, true), 3153 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3154 3155 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3156 } 3157 3158 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3159 SelectionDAG &DAG) const { 3160 // We only handle constant sizes here to allow non-entry block, static sized 3161 // allocas. A truly dynamic value is more difficult to support because we 3162 // don't know if the size value is uniform or not. If the size isn't uniform, 3163 // we would need to do a wave reduction to get the maximum size to know how 3164 // much to increment the uniform stack pointer. 3165 SDValue Size = Op.getOperand(1); 3166 if (isa<ConstantSDNode>(Size)) 3167 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3168 3169 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3170 } 3171 3172 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3173 const MachineFunction &MF) const { 3174 Register Reg = StringSwitch<Register>(RegName) 3175 .Case("m0", AMDGPU::M0) 3176 .Case("exec", AMDGPU::EXEC) 3177 .Case("exec_lo", AMDGPU::EXEC_LO) 3178 .Case("exec_hi", AMDGPU::EXEC_HI) 3179 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3180 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3181 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3182 .Default(Register()); 3183 3184 if (Reg == AMDGPU::NoRegister) { 3185 report_fatal_error(Twine("invalid register name \"" 3186 + StringRef(RegName) + "\".")); 3187 3188 } 3189 3190 if (!Subtarget->hasFlatScrRegister() && 3191 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3192 report_fatal_error(Twine("invalid register \"" 3193 + StringRef(RegName) + "\" for subtarget.")); 3194 } 3195 3196 switch (Reg) { 3197 case AMDGPU::M0: 3198 case AMDGPU::EXEC_LO: 3199 case AMDGPU::EXEC_HI: 3200 case AMDGPU::FLAT_SCR_LO: 3201 case AMDGPU::FLAT_SCR_HI: 3202 if (VT.getSizeInBits() == 32) 3203 return Reg; 3204 break; 3205 case AMDGPU::EXEC: 3206 case AMDGPU::FLAT_SCR: 3207 if (VT.getSizeInBits() == 64) 3208 return Reg; 3209 break; 3210 default: 3211 llvm_unreachable("missing register type checking"); 3212 } 3213 3214 report_fatal_error(Twine("invalid type for register \"" 3215 + StringRef(RegName) + "\".")); 3216 } 3217 3218 // If kill is not the last instruction, split the block so kill is always a 3219 // proper terminator. 3220 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3221 MachineBasicBlock *BB) const { 3222 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3223 3224 MachineBasicBlock::iterator SplitPoint(&MI); 3225 ++SplitPoint; 3226 3227 if (SplitPoint == BB->end()) { 3228 // Don't bother with a new block. 3229 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3230 return BB; 3231 } 3232 3233 MachineFunction *MF = BB->getParent(); 3234 MachineBasicBlock *SplitBB 3235 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3236 3237 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3238 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3239 3240 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3241 BB->addSuccessor(SplitBB); 3242 3243 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3244 return SplitBB; 3245 } 3246 3247 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3248 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3249 // be the first instruction in the remainder block. 3250 // 3251 /// \returns { LoopBody, Remainder } 3252 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3253 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3254 MachineFunction *MF = MBB.getParent(); 3255 MachineBasicBlock::iterator I(&MI); 3256 3257 // To insert the loop we need to split the block. Move everything after this 3258 // point to a new block, and insert a new empty block between the two. 3259 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3260 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3261 MachineFunction::iterator MBBI(MBB); 3262 ++MBBI; 3263 3264 MF->insert(MBBI, LoopBB); 3265 MF->insert(MBBI, RemainderBB); 3266 3267 LoopBB->addSuccessor(LoopBB); 3268 LoopBB->addSuccessor(RemainderBB); 3269 3270 // Move the rest of the block into a new block. 3271 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3272 3273 if (InstInLoop) { 3274 auto Next = std::next(I); 3275 3276 // Move instruction to loop body. 3277 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3278 3279 // Move the rest of the block. 3280 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3281 } else { 3282 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3283 } 3284 3285 MBB.addSuccessor(LoopBB); 3286 3287 return std::make_pair(LoopBB, RemainderBB); 3288 } 3289 3290 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3291 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3292 MachineBasicBlock *MBB = MI.getParent(); 3293 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3294 auto I = MI.getIterator(); 3295 auto E = std::next(I); 3296 3297 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3298 .addImm(0); 3299 3300 MIBundleBuilder Bundler(*MBB, I, E); 3301 finalizeBundle(*MBB, Bundler.begin()); 3302 } 3303 3304 MachineBasicBlock * 3305 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3306 MachineBasicBlock *BB) const { 3307 const DebugLoc &DL = MI.getDebugLoc(); 3308 3309 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3310 3311 MachineBasicBlock *LoopBB; 3312 MachineBasicBlock *RemainderBB; 3313 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3314 3315 // Apparently kill flags are only valid if the def is in the same block? 3316 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3317 Src->setIsKill(false); 3318 3319 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3320 3321 MachineBasicBlock::iterator I = LoopBB->end(); 3322 3323 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3324 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3325 3326 // Clear TRAP_STS.MEM_VIOL 3327 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3328 .addImm(0) 3329 .addImm(EncodedReg); 3330 3331 bundleInstWithWaitcnt(MI); 3332 3333 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3334 3335 // Load and check TRAP_STS.MEM_VIOL 3336 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3337 .addImm(EncodedReg); 3338 3339 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3340 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3341 .addReg(Reg, RegState::Kill) 3342 .addImm(0); 3343 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3344 .addMBB(LoopBB); 3345 3346 return RemainderBB; 3347 } 3348 3349 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3350 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3351 // will only do one iteration. In the worst case, this will loop 64 times. 3352 // 3353 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3354 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3355 const SIInstrInfo *TII, 3356 MachineRegisterInfo &MRI, 3357 MachineBasicBlock &OrigBB, 3358 MachineBasicBlock &LoopBB, 3359 const DebugLoc &DL, 3360 const MachineOperand &IdxReg, 3361 unsigned InitReg, 3362 unsigned ResultReg, 3363 unsigned PhiReg, 3364 unsigned InitSaveExecReg, 3365 int Offset, 3366 bool UseGPRIdxMode, 3367 bool IsIndirectSrc) { 3368 MachineFunction *MF = OrigBB.getParent(); 3369 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3370 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3371 MachineBasicBlock::iterator I = LoopBB.begin(); 3372 3373 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3374 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3375 Register NewExec = MRI.createVirtualRegister(BoolRC); 3376 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3377 Register CondReg = MRI.createVirtualRegister(BoolRC); 3378 3379 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3380 .addReg(InitReg) 3381 .addMBB(&OrigBB) 3382 .addReg(ResultReg) 3383 .addMBB(&LoopBB); 3384 3385 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3386 .addReg(InitSaveExecReg) 3387 .addMBB(&OrigBB) 3388 .addReg(NewExec) 3389 .addMBB(&LoopBB); 3390 3391 // Read the next variant <- also loop target. 3392 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3393 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3394 3395 // Compare the just read M0 value to all possible Idx values. 3396 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3397 .addReg(CurrentIdxReg) 3398 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3399 3400 // Update EXEC, save the original EXEC value to VCC. 3401 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3402 : AMDGPU::S_AND_SAVEEXEC_B64), 3403 NewExec) 3404 .addReg(CondReg, RegState::Kill); 3405 3406 MRI.setSimpleHint(NewExec, CondReg); 3407 3408 if (UseGPRIdxMode) { 3409 unsigned IdxReg; 3410 if (Offset == 0) { 3411 IdxReg = CurrentIdxReg; 3412 } else { 3413 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3414 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3415 .addReg(CurrentIdxReg, RegState::Kill) 3416 .addImm(Offset); 3417 } 3418 unsigned IdxMode = IsIndirectSrc ? 3419 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3420 MachineInstr *SetOn = 3421 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3422 .addReg(IdxReg, RegState::Kill) 3423 .addImm(IdxMode); 3424 SetOn->getOperand(3).setIsUndef(); 3425 } else { 3426 // Move index from VCC into M0 3427 if (Offset == 0) { 3428 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3429 .addReg(CurrentIdxReg, RegState::Kill); 3430 } else { 3431 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3432 .addReg(CurrentIdxReg, RegState::Kill) 3433 .addImm(Offset); 3434 } 3435 } 3436 3437 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3438 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3439 MachineInstr *InsertPt = 3440 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3441 : AMDGPU::S_XOR_B64_term), Exec) 3442 .addReg(Exec) 3443 .addReg(NewExec); 3444 3445 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3446 // s_cbranch_scc0? 3447 3448 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3449 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3450 .addMBB(&LoopBB); 3451 3452 return InsertPt->getIterator(); 3453 } 3454 3455 // This has slightly sub-optimal regalloc when the source vector is killed by 3456 // the read. The register allocator does not understand that the kill is 3457 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3458 // subregister from it, using 1 more VGPR than necessary. This was saved when 3459 // this was expanded after register allocation. 3460 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3461 MachineBasicBlock &MBB, 3462 MachineInstr &MI, 3463 unsigned InitResultReg, 3464 unsigned PhiReg, 3465 int Offset, 3466 bool UseGPRIdxMode, 3467 bool IsIndirectSrc) { 3468 MachineFunction *MF = MBB.getParent(); 3469 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3470 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3471 MachineRegisterInfo &MRI = MF->getRegInfo(); 3472 const DebugLoc &DL = MI.getDebugLoc(); 3473 MachineBasicBlock::iterator I(&MI); 3474 3475 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3476 Register DstReg = MI.getOperand(0).getReg(); 3477 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3478 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3479 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3480 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3481 3482 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3483 3484 // Save the EXEC mask 3485 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3486 .addReg(Exec); 3487 3488 MachineBasicBlock *LoopBB; 3489 MachineBasicBlock *RemainderBB; 3490 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3491 3492 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3493 3494 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3495 InitResultReg, DstReg, PhiReg, TmpExec, 3496 Offset, UseGPRIdxMode, IsIndirectSrc); 3497 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3498 MachineFunction::iterator MBBI(LoopBB); 3499 ++MBBI; 3500 MF->insert(MBBI, LandingPad); 3501 LoopBB->removeSuccessor(RemainderBB); 3502 LandingPad->addSuccessor(RemainderBB); 3503 LoopBB->addSuccessor(LandingPad); 3504 MachineBasicBlock::iterator First = LandingPad->begin(); 3505 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3506 .addReg(SaveExec); 3507 3508 return InsPt; 3509 } 3510 3511 // Returns subreg index, offset 3512 static std::pair<unsigned, int> 3513 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3514 const TargetRegisterClass *SuperRC, 3515 unsigned VecReg, 3516 int Offset) { 3517 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3518 3519 // Skip out of bounds offsets, or else we would end up using an undefined 3520 // register. 3521 if (Offset >= NumElts || Offset < 0) 3522 return std::make_pair(AMDGPU::sub0, Offset); 3523 3524 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3525 } 3526 3527 // Return true if the index is an SGPR and was set. 3528 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3529 MachineRegisterInfo &MRI, 3530 MachineInstr &MI, 3531 int Offset, 3532 bool UseGPRIdxMode, 3533 bool IsIndirectSrc) { 3534 MachineBasicBlock *MBB = MI.getParent(); 3535 const DebugLoc &DL = MI.getDebugLoc(); 3536 MachineBasicBlock::iterator I(&MI); 3537 3538 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3539 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3540 3541 assert(Idx->getReg() != AMDGPU::NoRegister); 3542 3543 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3544 return false; 3545 3546 if (UseGPRIdxMode) { 3547 unsigned IdxMode = IsIndirectSrc ? 3548 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3549 if (Offset == 0) { 3550 MachineInstr *SetOn = 3551 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3552 .add(*Idx) 3553 .addImm(IdxMode); 3554 3555 SetOn->getOperand(3).setIsUndef(); 3556 } else { 3557 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3558 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3559 .add(*Idx) 3560 .addImm(Offset); 3561 MachineInstr *SetOn = 3562 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3563 .addReg(Tmp, RegState::Kill) 3564 .addImm(IdxMode); 3565 3566 SetOn->getOperand(3).setIsUndef(); 3567 } 3568 3569 return true; 3570 } 3571 3572 if (Offset == 0) { 3573 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3574 .add(*Idx); 3575 } else { 3576 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3577 .add(*Idx) 3578 .addImm(Offset); 3579 } 3580 3581 return true; 3582 } 3583 3584 // Control flow needs to be inserted if indexing with a VGPR. 3585 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3586 MachineBasicBlock &MBB, 3587 const GCNSubtarget &ST) { 3588 const SIInstrInfo *TII = ST.getInstrInfo(); 3589 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3590 MachineFunction *MF = MBB.getParent(); 3591 MachineRegisterInfo &MRI = MF->getRegInfo(); 3592 3593 Register Dst = MI.getOperand(0).getReg(); 3594 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3595 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3596 3597 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3598 3599 unsigned SubReg; 3600 std::tie(SubReg, Offset) 3601 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3602 3603 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3604 3605 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3606 MachineBasicBlock::iterator I(&MI); 3607 const DebugLoc &DL = MI.getDebugLoc(); 3608 3609 if (UseGPRIdxMode) { 3610 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3611 // to avoid interfering with other uses, so probably requires a new 3612 // optimization pass. 3613 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3614 .addReg(SrcReg, RegState::Undef, SubReg) 3615 .addReg(SrcReg, RegState::Implicit) 3616 .addReg(AMDGPU::M0, RegState::Implicit); 3617 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3618 } else { 3619 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3620 .addReg(SrcReg, RegState::Undef, SubReg) 3621 .addReg(SrcReg, RegState::Implicit); 3622 } 3623 3624 MI.eraseFromParent(); 3625 3626 return &MBB; 3627 } 3628 3629 const DebugLoc &DL = MI.getDebugLoc(); 3630 MachineBasicBlock::iterator I(&MI); 3631 3632 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3633 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3634 3635 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3636 3637 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3638 Offset, UseGPRIdxMode, true); 3639 MachineBasicBlock *LoopBB = InsPt->getParent(); 3640 3641 if (UseGPRIdxMode) { 3642 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3643 .addReg(SrcReg, RegState::Undef, SubReg) 3644 .addReg(SrcReg, RegState::Implicit) 3645 .addReg(AMDGPU::M0, RegState::Implicit); 3646 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3647 } else { 3648 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3649 .addReg(SrcReg, RegState::Undef, SubReg) 3650 .addReg(SrcReg, RegState::Implicit); 3651 } 3652 3653 MI.eraseFromParent(); 3654 3655 return LoopBB; 3656 } 3657 3658 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3659 MachineBasicBlock &MBB, 3660 const GCNSubtarget &ST) { 3661 const SIInstrInfo *TII = ST.getInstrInfo(); 3662 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3663 MachineFunction *MF = MBB.getParent(); 3664 MachineRegisterInfo &MRI = MF->getRegInfo(); 3665 3666 Register Dst = MI.getOperand(0).getReg(); 3667 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3668 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3669 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3670 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3671 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3672 3673 // This can be an immediate, but will be folded later. 3674 assert(Val->getReg()); 3675 3676 unsigned SubReg; 3677 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3678 SrcVec->getReg(), 3679 Offset); 3680 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3681 3682 if (Idx->getReg() == AMDGPU::NoRegister) { 3683 MachineBasicBlock::iterator I(&MI); 3684 const DebugLoc &DL = MI.getDebugLoc(); 3685 3686 assert(Offset == 0); 3687 3688 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3689 .add(*SrcVec) 3690 .add(*Val) 3691 .addImm(SubReg); 3692 3693 MI.eraseFromParent(); 3694 return &MBB; 3695 } 3696 3697 const MCInstrDesc &MovRelDesc 3698 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3699 3700 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3701 MachineBasicBlock::iterator I(&MI); 3702 const DebugLoc &DL = MI.getDebugLoc(); 3703 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3704 .addReg(SrcVec->getReg()) 3705 .add(*Val) 3706 .addImm(SubReg); 3707 if (UseGPRIdxMode) 3708 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3709 3710 MI.eraseFromParent(); 3711 return &MBB; 3712 } 3713 3714 if (Val->isReg()) 3715 MRI.clearKillFlags(Val->getReg()); 3716 3717 const DebugLoc &DL = MI.getDebugLoc(); 3718 3719 Register PhiReg = MRI.createVirtualRegister(VecRC); 3720 3721 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3722 Offset, UseGPRIdxMode, false); 3723 MachineBasicBlock *LoopBB = InsPt->getParent(); 3724 3725 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3726 .addReg(PhiReg) 3727 .add(*Val) 3728 .addImm(AMDGPU::sub0); 3729 if (UseGPRIdxMode) 3730 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3731 3732 MI.eraseFromParent(); 3733 return LoopBB; 3734 } 3735 3736 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3737 MachineInstr &MI, MachineBasicBlock *BB) const { 3738 3739 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3740 MachineFunction *MF = BB->getParent(); 3741 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3742 3743 switch (MI.getOpcode()) { 3744 case AMDGPU::S_UADDO_PSEUDO: 3745 case AMDGPU::S_USUBO_PSEUDO: { 3746 const DebugLoc &DL = MI.getDebugLoc(); 3747 MachineOperand &Dest0 = MI.getOperand(0); 3748 MachineOperand &Dest1 = MI.getOperand(1); 3749 MachineOperand &Src0 = MI.getOperand(2); 3750 MachineOperand &Src1 = MI.getOperand(3); 3751 3752 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3753 ? AMDGPU::S_ADD_I32 3754 : AMDGPU::S_SUB_I32; 3755 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3756 3757 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3758 .addImm(1) 3759 .addImm(0); 3760 3761 MI.eraseFromParent(); 3762 return BB; 3763 } 3764 case AMDGPU::S_ADD_U64_PSEUDO: 3765 case AMDGPU::S_SUB_U64_PSEUDO: { 3766 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3767 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3768 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3769 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3770 const DebugLoc &DL = MI.getDebugLoc(); 3771 3772 MachineOperand &Dest = MI.getOperand(0); 3773 MachineOperand &Src0 = MI.getOperand(1); 3774 MachineOperand &Src1 = MI.getOperand(2); 3775 3776 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3777 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3778 3779 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3780 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3781 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3782 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3783 3784 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3785 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3786 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3787 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3788 3789 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3790 3791 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3792 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3793 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3794 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3795 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3796 .addReg(DestSub0) 3797 .addImm(AMDGPU::sub0) 3798 .addReg(DestSub1) 3799 .addImm(AMDGPU::sub1); 3800 MI.eraseFromParent(); 3801 return BB; 3802 } 3803 case AMDGPU::V_ADD_U64_PSEUDO: 3804 case AMDGPU::V_SUB_U64_PSEUDO: { 3805 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3806 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3807 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3808 const DebugLoc &DL = MI.getDebugLoc(); 3809 3810 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3811 3812 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3813 3814 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3815 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3816 3817 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3818 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3819 3820 MachineOperand &Dest = MI.getOperand(0); 3821 MachineOperand &Src0 = MI.getOperand(1); 3822 MachineOperand &Src1 = MI.getOperand(2); 3823 3824 const TargetRegisterClass *Src0RC = Src0.isReg() 3825 ? MRI.getRegClass(Src0.getReg()) 3826 : &AMDGPU::VReg_64RegClass; 3827 const TargetRegisterClass *Src1RC = Src1.isReg() 3828 ? MRI.getRegClass(Src1.getReg()) 3829 : &AMDGPU::VReg_64RegClass; 3830 3831 const TargetRegisterClass *Src0SubRC = 3832 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3833 const TargetRegisterClass *Src1SubRC = 3834 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3835 3836 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3837 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3838 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3839 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3840 3841 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3842 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3843 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3844 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3845 3846 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64; 3847 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3848 .addReg(CarryReg, RegState::Define) 3849 .add(SrcReg0Sub0) 3850 .add(SrcReg1Sub0) 3851 .addImm(0); // clamp bit 3852 3853 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3854 MachineInstr *HiHalf = 3855 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3856 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3857 .add(SrcReg0Sub1) 3858 .add(SrcReg1Sub1) 3859 .addReg(CarryReg, RegState::Kill) 3860 .addImm(0); // clamp bit 3861 3862 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3863 .addReg(DestSub0) 3864 .addImm(AMDGPU::sub0) 3865 .addReg(DestSub1) 3866 .addImm(AMDGPU::sub1); 3867 TII->legalizeOperands(*LoHalf); 3868 TII->legalizeOperands(*HiHalf); 3869 MI.eraseFromParent(); 3870 return BB; 3871 } 3872 case AMDGPU::S_ADD_CO_PSEUDO: 3873 case AMDGPU::S_SUB_CO_PSEUDO: { 3874 // This pseudo has a chance to be selected 3875 // only from uniform add/subcarry node. All the VGPR operands 3876 // therefore assumed to be splat vectors. 3877 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3878 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3879 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3880 MachineBasicBlock::iterator MII = MI; 3881 const DebugLoc &DL = MI.getDebugLoc(); 3882 MachineOperand &Dest = MI.getOperand(0); 3883 MachineOperand &Src0 = MI.getOperand(2); 3884 MachineOperand &Src1 = MI.getOperand(3); 3885 MachineOperand &Src2 = MI.getOperand(4); 3886 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 3887 ? AMDGPU::S_ADDC_U32 3888 : AMDGPU::S_SUBB_U32; 3889 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 3890 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3891 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 3892 .addReg(Src0.getReg()); 3893 Src0.setReg(RegOp0); 3894 } 3895 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 3896 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3897 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 3898 .addReg(Src1.getReg()); 3899 Src1.setReg(RegOp1); 3900 } 3901 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3902 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 3903 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 3904 .addReg(Src2.getReg()); 3905 Src2.setReg(RegOp2); 3906 } 3907 3908 if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) { 3909 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 3910 .addReg(Src2.getReg()) 3911 .addImm(0); 3912 } else { 3913 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 3914 .addReg(Src2.getReg()) 3915 .addImm(0); 3916 } 3917 3918 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 3919 MI.eraseFromParent(); 3920 return BB; 3921 } 3922 case AMDGPU::SI_INIT_M0: { 3923 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3924 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3925 .add(MI.getOperand(0)); 3926 MI.eraseFromParent(); 3927 return BB; 3928 } 3929 case AMDGPU::SI_INIT_EXEC: 3930 // This should be before all vector instructions. 3931 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3932 AMDGPU::EXEC) 3933 .addImm(MI.getOperand(0).getImm()); 3934 MI.eraseFromParent(); 3935 return BB; 3936 3937 case AMDGPU::SI_INIT_EXEC_LO: 3938 // This should be before all vector instructions. 3939 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3940 AMDGPU::EXEC_LO) 3941 .addImm(MI.getOperand(0).getImm()); 3942 MI.eraseFromParent(); 3943 return BB; 3944 3945 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3946 // Extract the thread count from an SGPR input and set EXEC accordingly. 3947 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3948 // 3949 // S_BFE_U32 count, input, {shift, 7} 3950 // S_BFM_B64 exec, count, 0 3951 // S_CMP_EQ_U32 count, 64 3952 // S_CMOV_B64 exec, -1 3953 MachineInstr *FirstMI = &*BB->begin(); 3954 MachineRegisterInfo &MRI = MF->getRegInfo(); 3955 Register InputReg = MI.getOperand(0).getReg(); 3956 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3957 bool Found = false; 3958 3959 // Move the COPY of the input reg to the beginning, so that we can use it. 3960 for (auto I = BB->begin(); I != &MI; I++) { 3961 if (I->getOpcode() != TargetOpcode::COPY || 3962 I->getOperand(0).getReg() != InputReg) 3963 continue; 3964 3965 if (I == FirstMI) { 3966 FirstMI = &*++BB->begin(); 3967 } else { 3968 I->removeFromParent(); 3969 BB->insert(FirstMI, &*I); 3970 } 3971 Found = true; 3972 break; 3973 } 3974 assert(Found); 3975 (void)Found; 3976 3977 // This should be before all vector instructions. 3978 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3979 bool isWave32 = getSubtarget()->isWave32(); 3980 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3981 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3982 .addReg(InputReg) 3983 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3984 BuildMI(*BB, FirstMI, DebugLoc(), 3985 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3986 Exec) 3987 .addReg(CountReg) 3988 .addImm(0); 3989 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3990 .addReg(CountReg, RegState::Kill) 3991 .addImm(getSubtarget()->getWavefrontSize()); 3992 BuildMI(*BB, FirstMI, DebugLoc(), 3993 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3994 Exec) 3995 .addImm(-1); 3996 MI.eraseFromParent(); 3997 return BB; 3998 } 3999 4000 case AMDGPU::GET_GROUPSTATICSIZE: { 4001 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4002 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4003 DebugLoc DL = MI.getDebugLoc(); 4004 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4005 .add(MI.getOperand(0)) 4006 .addImm(MFI->getLDSSize()); 4007 MI.eraseFromParent(); 4008 return BB; 4009 } 4010 case AMDGPU::SI_INDIRECT_SRC_V1: 4011 case AMDGPU::SI_INDIRECT_SRC_V2: 4012 case AMDGPU::SI_INDIRECT_SRC_V4: 4013 case AMDGPU::SI_INDIRECT_SRC_V8: 4014 case AMDGPU::SI_INDIRECT_SRC_V16: 4015 case AMDGPU::SI_INDIRECT_SRC_V32: 4016 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4017 case AMDGPU::SI_INDIRECT_DST_V1: 4018 case AMDGPU::SI_INDIRECT_DST_V2: 4019 case AMDGPU::SI_INDIRECT_DST_V4: 4020 case AMDGPU::SI_INDIRECT_DST_V8: 4021 case AMDGPU::SI_INDIRECT_DST_V16: 4022 case AMDGPU::SI_INDIRECT_DST_V32: 4023 return emitIndirectDst(MI, *BB, *getSubtarget()); 4024 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4025 case AMDGPU::SI_KILL_I1_PSEUDO: 4026 return splitKillBlock(MI, BB); 4027 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4028 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4029 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4030 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4031 4032 Register Dst = MI.getOperand(0).getReg(); 4033 Register Src0 = MI.getOperand(1).getReg(); 4034 Register Src1 = MI.getOperand(2).getReg(); 4035 const DebugLoc &DL = MI.getDebugLoc(); 4036 Register SrcCond = MI.getOperand(3).getReg(); 4037 4038 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4039 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4040 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4041 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4042 4043 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4044 .addReg(SrcCond); 4045 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4046 .addImm(0) 4047 .addReg(Src0, 0, AMDGPU::sub0) 4048 .addImm(0) 4049 .addReg(Src1, 0, AMDGPU::sub0) 4050 .addReg(SrcCondCopy); 4051 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4052 .addImm(0) 4053 .addReg(Src0, 0, AMDGPU::sub1) 4054 .addImm(0) 4055 .addReg(Src1, 0, AMDGPU::sub1) 4056 .addReg(SrcCondCopy); 4057 4058 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4059 .addReg(DstLo) 4060 .addImm(AMDGPU::sub0) 4061 .addReg(DstHi) 4062 .addImm(AMDGPU::sub1); 4063 MI.eraseFromParent(); 4064 return BB; 4065 } 4066 case AMDGPU::SI_BR_UNDEF: { 4067 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4068 const DebugLoc &DL = MI.getDebugLoc(); 4069 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4070 .add(MI.getOperand(0)); 4071 Br->getOperand(1).setIsUndef(true); // read undef SCC 4072 MI.eraseFromParent(); 4073 return BB; 4074 } 4075 case AMDGPU::ADJCALLSTACKUP: 4076 case AMDGPU::ADJCALLSTACKDOWN: { 4077 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4078 MachineInstrBuilder MIB(*MF, &MI); 4079 4080 // Add an implicit use of the frame offset reg to prevent the restore copy 4081 // inserted after the call from being reorderd after stack operations in the 4082 // the caller's frame. 4083 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4084 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 4085 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 4086 return BB; 4087 } 4088 case AMDGPU::SI_CALL_ISEL: { 4089 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4090 const DebugLoc &DL = MI.getDebugLoc(); 4091 4092 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4093 4094 MachineInstrBuilder MIB; 4095 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4096 4097 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4098 MIB.add(MI.getOperand(I)); 4099 4100 MIB.cloneMemRefs(MI); 4101 MI.eraseFromParent(); 4102 return BB; 4103 } 4104 case AMDGPU::V_ADD_I32_e32: 4105 case AMDGPU::V_SUB_I32_e32: 4106 case AMDGPU::V_SUBREV_I32_e32: { 4107 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4108 const DebugLoc &DL = MI.getDebugLoc(); 4109 unsigned Opc = MI.getOpcode(); 4110 4111 bool NeedClampOperand = false; 4112 if (TII->pseudoToMCOpcode(Opc) == -1) { 4113 Opc = AMDGPU::getVOPe64(Opc); 4114 NeedClampOperand = true; 4115 } 4116 4117 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4118 if (TII->isVOP3(*I)) { 4119 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4120 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4121 I.addReg(TRI->getVCC(), RegState::Define); 4122 } 4123 I.add(MI.getOperand(1)) 4124 .add(MI.getOperand(2)); 4125 if (NeedClampOperand) 4126 I.addImm(0); // clamp bit for e64 encoding 4127 4128 TII->legalizeOperands(*I); 4129 4130 MI.eraseFromParent(); 4131 return BB; 4132 } 4133 case AMDGPU::DS_GWS_INIT: 4134 case AMDGPU::DS_GWS_SEMA_V: 4135 case AMDGPU::DS_GWS_SEMA_BR: 4136 case AMDGPU::DS_GWS_SEMA_P: 4137 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4138 case AMDGPU::DS_GWS_BARRIER: 4139 // A s_waitcnt 0 is required to be the instruction immediately following. 4140 if (getSubtarget()->hasGWSAutoReplay()) { 4141 bundleInstWithWaitcnt(MI); 4142 return BB; 4143 } 4144 4145 return emitGWSMemViolTestLoop(MI, BB); 4146 case AMDGPU::S_SETREG_B32: { 4147 if (!getSubtarget()->hasDenormModeInst()) 4148 return BB; 4149 4150 // Try to optimize cases that only set the denormal mode or rounding mode. 4151 // 4152 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4153 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4154 // instead. 4155 // 4156 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4157 // allow you to have a no side effect instruction in the output of a 4158 // sideeffecting pattern. 4159 4160 // TODO: Should also emit a no side effects pseudo if only FP bits are 4161 // touched, even if not all of them or to a variable. 4162 unsigned ID, Offset, Width; 4163 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4164 if (ID != AMDGPU::Hwreg::ID_MODE) 4165 return BB; 4166 4167 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4168 const unsigned SetMask = WidthMask << Offset; 4169 unsigned SetDenormOp = 0; 4170 unsigned SetRoundOp = 0; 4171 4172 // The dedicated instructions can only set the whole denorm or round mode at 4173 // once, not a subset of bits in either. 4174 if (Width == 8 && (SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4175 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) { 4176 // If this fully sets both the round and denorm mode, emit the two 4177 // dedicated instructions for these. 4178 assert(Offset == 0); 4179 SetRoundOp = AMDGPU::S_ROUND_MODE; 4180 SetDenormOp = AMDGPU::S_DENORM_MODE; 4181 } else if (Width == 4) { 4182 if ((SetMask & AMDGPU::Hwreg::FP_ROUND_MASK) == SetMask) { 4183 SetRoundOp = AMDGPU::S_ROUND_MODE; 4184 assert(Offset == 0); 4185 } else if ((SetMask & AMDGPU::Hwreg::FP_DENORM_MASK) == SetMask) { 4186 SetDenormOp = AMDGPU::S_DENORM_MODE; 4187 assert(Offset == 4); 4188 } 4189 } 4190 4191 if (SetRoundOp || SetDenormOp) { 4192 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4193 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4194 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4195 unsigned ImmVal = Def->getOperand(1).getImm(); 4196 if (SetRoundOp) { 4197 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4198 .addImm(ImmVal & 0xf); 4199 4200 // If we also have the denorm mode, get just the denorm mode bits. 4201 ImmVal >>= 4; 4202 } 4203 4204 if (SetDenormOp) { 4205 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4206 .addImm(ImmVal & 0xf); 4207 } 4208 4209 MI.eraseFromParent(); 4210 } 4211 } 4212 4213 return BB; 4214 } 4215 default: 4216 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4217 } 4218 } 4219 4220 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4221 return isTypeLegal(VT.getScalarType()); 4222 } 4223 4224 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4225 // This currently forces unfolding various combinations of fsub into fma with 4226 // free fneg'd operands. As long as we have fast FMA (controlled by 4227 // isFMAFasterThanFMulAndFAdd), we should perform these. 4228 4229 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4230 // most of these combines appear to be cycle neutral but save on instruction 4231 // count / code size. 4232 return true; 4233 } 4234 4235 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4236 EVT VT) const { 4237 if (!VT.isVector()) { 4238 return MVT::i1; 4239 } 4240 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4241 } 4242 4243 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4244 // TODO: Should i16 be used always if legal? For now it would force VALU 4245 // shifts. 4246 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4247 } 4248 4249 // Answering this is somewhat tricky and depends on the specific device which 4250 // have different rates for fma or all f64 operations. 4251 // 4252 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4253 // regardless of which device (although the number of cycles differs between 4254 // devices), so it is always profitable for f64. 4255 // 4256 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4257 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4258 // which we can always do even without fused FP ops since it returns the same 4259 // result as the separate operations and since it is always full 4260 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4261 // however does not support denormals, so we do report fma as faster if we have 4262 // a fast fma device and require denormals. 4263 // 4264 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4265 EVT VT) const { 4266 VT = VT.getScalarType(); 4267 4268 switch (VT.getSimpleVT().SimpleTy) { 4269 case MVT::f32: { 4270 // This is as fast on some subtargets. However, we always have full rate f32 4271 // mad available which returns the same result as the separate operations 4272 // which we should prefer over fma. We can't use this if we want to support 4273 // denormals, so only report this in these cases. 4274 if (hasFP32Denormals(MF)) 4275 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4276 4277 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4278 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4279 } 4280 case MVT::f64: 4281 return true; 4282 case MVT::f16: 4283 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4284 default: 4285 break; 4286 } 4287 4288 return false; 4289 } 4290 4291 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4292 const SDNode *N) const { 4293 // TODO: Check future ftz flag 4294 // v_mad_f32/v_mac_f32 do not support denormals. 4295 EVT VT = N->getValueType(0); 4296 if (VT == MVT::f32) 4297 return Subtarget->hasMadMacF32Insts() && 4298 !hasFP32Denormals(DAG.getMachineFunction()); 4299 if (VT == MVT::f16) { 4300 return Subtarget->hasMadF16() && 4301 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4302 } 4303 4304 return false; 4305 } 4306 4307 //===----------------------------------------------------------------------===// 4308 // Custom DAG Lowering Operations 4309 //===----------------------------------------------------------------------===// 4310 4311 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4312 // wider vector type is legal. 4313 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4314 SelectionDAG &DAG) const { 4315 unsigned Opc = Op.getOpcode(); 4316 EVT VT = Op.getValueType(); 4317 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4318 4319 SDValue Lo, Hi; 4320 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4321 4322 SDLoc SL(Op); 4323 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4324 Op->getFlags()); 4325 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4326 Op->getFlags()); 4327 4328 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4329 } 4330 4331 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4332 // wider vector type is legal. 4333 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4334 SelectionDAG &DAG) const { 4335 unsigned Opc = Op.getOpcode(); 4336 EVT VT = Op.getValueType(); 4337 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4338 4339 SDValue Lo0, Hi0; 4340 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4341 SDValue Lo1, Hi1; 4342 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4343 4344 SDLoc SL(Op); 4345 4346 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4347 Op->getFlags()); 4348 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4349 Op->getFlags()); 4350 4351 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4352 } 4353 4354 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4355 SelectionDAG &DAG) const { 4356 unsigned Opc = Op.getOpcode(); 4357 EVT VT = Op.getValueType(); 4358 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4359 4360 SDValue Lo0, Hi0; 4361 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4362 SDValue Lo1, Hi1; 4363 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4364 SDValue Lo2, Hi2; 4365 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4366 4367 SDLoc SL(Op); 4368 4369 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4370 Op->getFlags()); 4371 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4372 Op->getFlags()); 4373 4374 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4375 } 4376 4377 4378 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4379 switch (Op.getOpcode()) { 4380 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4381 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4382 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4383 case ISD::LOAD: { 4384 SDValue Result = LowerLOAD(Op, DAG); 4385 assert((!Result.getNode() || 4386 Result.getNode()->getNumValues() == 2) && 4387 "Load should return a value and a chain"); 4388 return Result; 4389 } 4390 4391 case ISD::FSIN: 4392 case ISD::FCOS: 4393 return LowerTrig(Op, DAG); 4394 case ISD::SELECT: return LowerSELECT(Op, DAG); 4395 case ISD::FDIV: return LowerFDIV(Op, DAG); 4396 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4397 case ISD::STORE: return LowerSTORE(Op, DAG); 4398 case ISD::GlobalAddress: { 4399 MachineFunction &MF = DAG.getMachineFunction(); 4400 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4401 return LowerGlobalAddress(MFI, Op, DAG); 4402 } 4403 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4404 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4405 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4406 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4407 case ISD::INSERT_SUBVECTOR: 4408 return lowerINSERT_SUBVECTOR(Op, DAG); 4409 case ISD::INSERT_VECTOR_ELT: 4410 return lowerINSERT_VECTOR_ELT(Op, DAG); 4411 case ISD::EXTRACT_VECTOR_ELT: 4412 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4413 case ISD::VECTOR_SHUFFLE: 4414 return lowerVECTOR_SHUFFLE(Op, DAG); 4415 case ISD::BUILD_VECTOR: 4416 return lowerBUILD_VECTOR(Op, DAG); 4417 case ISD::FP_ROUND: 4418 return lowerFP_ROUND(Op, DAG); 4419 case ISD::TRAP: 4420 return lowerTRAP(Op, DAG); 4421 case ISD::DEBUGTRAP: 4422 return lowerDEBUGTRAP(Op, DAG); 4423 case ISD::FABS: 4424 case ISD::FNEG: 4425 case ISD::FCANONICALIZE: 4426 case ISD::BSWAP: 4427 return splitUnaryVectorOp(Op, DAG); 4428 case ISD::FMINNUM: 4429 case ISD::FMAXNUM: 4430 return lowerFMINNUM_FMAXNUM(Op, DAG); 4431 case ISD::FMA: 4432 return splitTernaryVectorOp(Op, DAG); 4433 case ISD::SHL: 4434 case ISD::SRA: 4435 case ISD::SRL: 4436 case ISD::ADD: 4437 case ISD::SUB: 4438 case ISD::MUL: 4439 case ISD::SMIN: 4440 case ISD::SMAX: 4441 case ISD::UMIN: 4442 case ISD::UMAX: 4443 case ISD::FADD: 4444 case ISD::FMUL: 4445 case ISD::FMINNUM_IEEE: 4446 case ISD::FMAXNUM_IEEE: 4447 return splitBinaryVectorOp(Op, DAG); 4448 case ISD::SMULO: 4449 case ISD::UMULO: 4450 return lowerXMULO(Op, DAG); 4451 case ISD::DYNAMIC_STACKALLOC: 4452 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4453 } 4454 return SDValue(); 4455 } 4456 4457 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4458 const SDLoc &DL, 4459 SelectionDAG &DAG, bool Unpacked) { 4460 if (!LoadVT.isVector()) 4461 return Result; 4462 4463 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4464 // Truncate to v2i16/v4i16. 4465 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4466 4467 // Workaround legalizer not scalarizing truncate after vector op 4468 // legalization byt not creating intermediate vector trunc. 4469 SmallVector<SDValue, 4> Elts; 4470 DAG.ExtractVectorElements(Result, Elts); 4471 for (SDValue &Elt : Elts) 4472 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4473 4474 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4475 4476 // Bitcast to original type (v2f16/v4f16). 4477 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4478 } 4479 4480 // Cast back to the original packed type. 4481 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4482 } 4483 4484 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4485 MemSDNode *M, 4486 SelectionDAG &DAG, 4487 ArrayRef<SDValue> Ops, 4488 bool IsIntrinsic) const { 4489 SDLoc DL(M); 4490 4491 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4492 EVT LoadVT = M->getValueType(0); 4493 4494 EVT EquivLoadVT = LoadVT; 4495 if (Unpacked && LoadVT.isVector()) { 4496 EquivLoadVT = LoadVT.isVector() ? 4497 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4498 LoadVT.getVectorNumElements()) : LoadVT; 4499 } 4500 4501 // Change from v4f16/v2f16 to EquivLoadVT. 4502 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4503 4504 SDValue Load 4505 = DAG.getMemIntrinsicNode( 4506 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4507 VTList, Ops, M->getMemoryVT(), 4508 M->getMemOperand()); 4509 if (!Unpacked) // Just adjusted the opcode. 4510 return Load; 4511 4512 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4513 4514 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4515 } 4516 4517 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4518 SelectionDAG &DAG, 4519 ArrayRef<SDValue> Ops) const { 4520 SDLoc DL(M); 4521 EVT LoadVT = M->getValueType(0); 4522 EVT EltType = LoadVT.getScalarType(); 4523 EVT IntVT = LoadVT.changeTypeToInteger(); 4524 4525 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4526 4527 unsigned Opc = 4528 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4529 4530 if (IsD16) { 4531 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4532 } 4533 4534 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4535 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4536 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4537 4538 if (isTypeLegal(LoadVT)) { 4539 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4540 M->getMemOperand(), DAG); 4541 } 4542 4543 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4544 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4545 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4546 M->getMemOperand(), DAG); 4547 return DAG.getMergeValues( 4548 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4549 DL); 4550 } 4551 4552 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4553 SDNode *N, SelectionDAG &DAG) { 4554 EVT VT = N->getValueType(0); 4555 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4556 unsigned CondCode = CD->getZExtValue(); 4557 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4558 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4559 return DAG.getUNDEF(VT); 4560 4561 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4562 4563 SDValue LHS = N->getOperand(1); 4564 SDValue RHS = N->getOperand(2); 4565 4566 SDLoc DL(N); 4567 4568 EVT CmpVT = LHS.getValueType(); 4569 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4570 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4571 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4572 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4573 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4574 } 4575 4576 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4577 4578 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4579 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4580 4581 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4582 DAG.getCondCode(CCOpcode)); 4583 if (VT.bitsEq(CCVT)) 4584 return SetCC; 4585 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4586 } 4587 4588 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4589 SDNode *N, SelectionDAG &DAG) { 4590 EVT VT = N->getValueType(0); 4591 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4592 4593 unsigned CondCode = CD->getZExtValue(); 4594 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4595 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4596 return DAG.getUNDEF(VT); 4597 } 4598 4599 SDValue Src0 = N->getOperand(1); 4600 SDValue Src1 = N->getOperand(2); 4601 EVT CmpVT = Src0.getValueType(); 4602 SDLoc SL(N); 4603 4604 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4605 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4606 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4607 } 4608 4609 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4610 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4611 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4612 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4613 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4614 Src1, DAG.getCondCode(CCOpcode)); 4615 if (VT.bitsEq(CCVT)) 4616 return SetCC; 4617 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4618 } 4619 4620 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4621 SelectionDAG &DAG) { 4622 EVT VT = N->getValueType(0); 4623 SDValue Src = N->getOperand(1); 4624 SDLoc SL(N); 4625 4626 if (Src.getOpcode() == ISD::SETCC) { 4627 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4628 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4629 Src.getOperand(1), Src.getOperand(2)); 4630 } 4631 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4632 // (ballot 0) -> 0 4633 if (Arg->isNullValue()) 4634 return DAG.getConstant(0, SL, VT); 4635 4636 // (ballot 1) -> EXEC/EXEC_LO 4637 if (Arg->isOne()) { 4638 Register Exec; 4639 if (VT.getScalarSizeInBits() == 32) 4640 Exec = AMDGPU::EXEC_LO; 4641 else if (VT.getScalarSizeInBits() == 64) 4642 Exec = AMDGPU::EXEC; 4643 else 4644 return SDValue(); 4645 4646 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4647 } 4648 } 4649 4650 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4651 // ISD::SETNE) 4652 return DAG.getNode( 4653 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4654 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4655 } 4656 4657 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4658 SmallVectorImpl<SDValue> &Results, 4659 SelectionDAG &DAG) const { 4660 switch (N->getOpcode()) { 4661 case ISD::INSERT_VECTOR_ELT: { 4662 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4663 Results.push_back(Res); 4664 return; 4665 } 4666 case ISD::EXTRACT_VECTOR_ELT: { 4667 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4668 Results.push_back(Res); 4669 return; 4670 } 4671 case ISD::INTRINSIC_WO_CHAIN: { 4672 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4673 switch (IID) { 4674 case Intrinsic::amdgcn_cvt_pkrtz: { 4675 SDValue Src0 = N->getOperand(1); 4676 SDValue Src1 = N->getOperand(2); 4677 SDLoc SL(N); 4678 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4679 Src0, Src1); 4680 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4681 return; 4682 } 4683 case Intrinsic::amdgcn_cvt_pknorm_i16: 4684 case Intrinsic::amdgcn_cvt_pknorm_u16: 4685 case Intrinsic::amdgcn_cvt_pk_i16: 4686 case Intrinsic::amdgcn_cvt_pk_u16: { 4687 SDValue Src0 = N->getOperand(1); 4688 SDValue Src1 = N->getOperand(2); 4689 SDLoc SL(N); 4690 unsigned Opcode; 4691 4692 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4693 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4694 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4695 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4696 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4697 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4698 else 4699 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4700 4701 EVT VT = N->getValueType(0); 4702 if (isTypeLegal(VT)) 4703 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4704 else { 4705 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4706 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4707 } 4708 return; 4709 } 4710 } 4711 break; 4712 } 4713 case ISD::INTRINSIC_W_CHAIN: { 4714 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4715 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4716 // FIXME: Hacky 4717 Results.push_back(Res.getOperand(0)); 4718 Results.push_back(Res.getOperand(1)); 4719 } else { 4720 Results.push_back(Res); 4721 Results.push_back(Res.getValue(1)); 4722 } 4723 return; 4724 } 4725 4726 break; 4727 } 4728 case ISD::SELECT: { 4729 SDLoc SL(N); 4730 EVT VT = N->getValueType(0); 4731 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4732 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4733 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4734 4735 EVT SelectVT = NewVT; 4736 if (NewVT.bitsLT(MVT::i32)) { 4737 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4738 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4739 SelectVT = MVT::i32; 4740 } 4741 4742 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4743 N->getOperand(0), LHS, RHS); 4744 4745 if (NewVT != SelectVT) 4746 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4747 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4748 return; 4749 } 4750 case ISD::FNEG: { 4751 if (N->getValueType(0) != MVT::v2f16) 4752 break; 4753 4754 SDLoc SL(N); 4755 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4756 4757 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4758 BC, 4759 DAG.getConstant(0x80008000, SL, MVT::i32)); 4760 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4761 return; 4762 } 4763 case ISD::FABS: { 4764 if (N->getValueType(0) != MVT::v2f16) 4765 break; 4766 4767 SDLoc SL(N); 4768 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4769 4770 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4771 BC, 4772 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4773 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4774 return; 4775 } 4776 default: 4777 break; 4778 } 4779 } 4780 4781 /// Helper function for LowerBRCOND 4782 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4783 4784 SDNode *Parent = Value.getNode(); 4785 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4786 I != E; ++I) { 4787 4788 if (I.getUse().get() != Value) 4789 continue; 4790 4791 if (I->getOpcode() == Opcode) 4792 return *I; 4793 } 4794 return nullptr; 4795 } 4796 4797 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4798 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4799 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4800 case Intrinsic::amdgcn_if: 4801 return AMDGPUISD::IF; 4802 case Intrinsic::amdgcn_else: 4803 return AMDGPUISD::ELSE; 4804 case Intrinsic::amdgcn_loop: 4805 return AMDGPUISD::LOOP; 4806 case Intrinsic::amdgcn_end_cf: 4807 llvm_unreachable("should not occur"); 4808 default: 4809 return 0; 4810 } 4811 } 4812 4813 // break, if_break, else_break are all only used as inputs to loop, not 4814 // directly as branch conditions. 4815 return 0; 4816 } 4817 4818 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4819 const Triple &TT = getTargetMachine().getTargetTriple(); 4820 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4821 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4822 AMDGPU::shouldEmitConstantsToTextSection(TT); 4823 } 4824 4825 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4826 // FIXME: Either avoid relying on address space here or change the default 4827 // address space for functions to avoid the explicit check. 4828 return (GV->getValueType()->isFunctionTy() || 4829 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4830 !shouldEmitFixup(GV) && 4831 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4832 } 4833 4834 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4835 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4836 } 4837 4838 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4839 if (!GV->hasExternalLinkage()) 4840 return true; 4841 4842 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4843 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4844 } 4845 4846 /// This transforms the control flow intrinsics to get the branch destination as 4847 /// last parameter, also switches branch target with BR if the need arise 4848 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4849 SelectionDAG &DAG) const { 4850 SDLoc DL(BRCOND); 4851 4852 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4853 SDValue Target = BRCOND.getOperand(2); 4854 SDNode *BR = nullptr; 4855 SDNode *SetCC = nullptr; 4856 4857 if (Intr->getOpcode() == ISD::SETCC) { 4858 // As long as we negate the condition everything is fine 4859 SetCC = Intr; 4860 Intr = SetCC->getOperand(0).getNode(); 4861 4862 } else { 4863 // Get the target from BR if we don't negate the condition 4864 BR = findUser(BRCOND, ISD::BR); 4865 assert(BR && "brcond missing unconditional branch user"); 4866 Target = BR->getOperand(1); 4867 } 4868 4869 unsigned CFNode = isCFIntrinsic(Intr); 4870 if (CFNode == 0) { 4871 // This is a uniform branch so we don't need to legalize. 4872 return BRCOND; 4873 } 4874 4875 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4876 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4877 4878 assert(!SetCC || 4879 (SetCC->getConstantOperandVal(1) == 1 && 4880 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4881 ISD::SETNE)); 4882 4883 // operands of the new intrinsic call 4884 SmallVector<SDValue, 4> Ops; 4885 if (HaveChain) 4886 Ops.push_back(BRCOND.getOperand(0)); 4887 4888 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4889 Ops.push_back(Target); 4890 4891 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4892 4893 // build the new intrinsic call 4894 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4895 4896 if (!HaveChain) { 4897 SDValue Ops[] = { 4898 SDValue(Result, 0), 4899 BRCOND.getOperand(0) 4900 }; 4901 4902 Result = DAG.getMergeValues(Ops, DL).getNode(); 4903 } 4904 4905 if (BR) { 4906 // Give the branch instruction our target 4907 SDValue Ops[] = { 4908 BR->getOperand(0), 4909 BRCOND.getOperand(2) 4910 }; 4911 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4912 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4913 } 4914 4915 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4916 4917 // Copy the intrinsic results to registers 4918 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4919 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4920 if (!CopyToReg) 4921 continue; 4922 4923 Chain = DAG.getCopyToReg( 4924 Chain, DL, 4925 CopyToReg->getOperand(1), 4926 SDValue(Result, i - 1), 4927 SDValue()); 4928 4929 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4930 } 4931 4932 // Remove the old intrinsic from the chain 4933 DAG.ReplaceAllUsesOfValueWith( 4934 SDValue(Intr, Intr->getNumValues() - 1), 4935 Intr->getOperand(0)); 4936 4937 return Chain; 4938 } 4939 4940 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4941 SelectionDAG &DAG) const { 4942 MVT VT = Op.getSimpleValueType(); 4943 SDLoc DL(Op); 4944 // Checking the depth 4945 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4946 return DAG.getConstant(0, DL, VT); 4947 4948 MachineFunction &MF = DAG.getMachineFunction(); 4949 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4950 // Check for kernel and shader functions 4951 if (Info->isEntryFunction()) 4952 return DAG.getConstant(0, DL, VT); 4953 4954 MachineFrameInfo &MFI = MF.getFrameInfo(); 4955 // There is a call to @llvm.returnaddress in this function 4956 MFI.setReturnAddressIsTaken(true); 4957 4958 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4959 // Get the return address reg and mark it as an implicit live-in 4960 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4961 4962 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4963 } 4964 4965 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 4966 SDValue Op, 4967 const SDLoc &DL, 4968 EVT VT) const { 4969 return Op.getValueType().bitsLE(VT) ? 4970 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4971 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 4972 DAG.getTargetConstant(0, DL, MVT::i32)); 4973 } 4974 4975 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4976 assert(Op.getValueType() == MVT::f16 && 4977 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4978 4979 SDValue Src = Op.getOperand(0); 4980 EVT SrcVT = Src.getValueType(); 4981 if (SrcVT != MVT::f64) 4982 return Op; 4983 4984 SDLoc DL(Op); 4985 4986 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4987 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4988 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4989 } 4990 4991 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4992 SelectionDAG &DAG) const { 4993 EVT VT = Op.getValueType(); 4994 const MachineFunction &MF = DAG.getMachineFunction(); 4995 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4996 bool IsIEEEMode = Info->getMode().IEEE; 4997 4998 // FIXME: Assert during selection that this is only selected for 4999 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5000 // mode functions, but this happens to be OK since it's only done in cases 5001 // where there is known no sNaN. 5002 if (IsIEEEMode) 5003 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5004 5005 if (VT == MVT::v4f16) 5006 return splitBinaryVectorOp(Op, DAG); 5007 return Op; 5008 } 5009 5010 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5011 EVT VT = Op.getValueType(); 5012 SDLoc SL(Op); 5013 SDValue LHS = Op.getOperand(0); 5014 SDValue RHS = Op.getOperand(1); 5015 bool isSigned = Op.getOpcode() == ISD::SMULO; 5016 5017 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5018 const APInt &C = RHSC->getAPIntValue(); 5019 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5020 if (C.isPowerOf2()) { 5021 // smulo(x, signed_min) is same as umulo(x, signed_min). 5022 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5023 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5024 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5025 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5026 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5027 SL, VT, Result, ShiftAmt), 5028 LHS, ISD::SETNE); 5029 return DAG.getMergeValues({ Result, Overflow }, SL); 5030 } 5031 } 5032 5033 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5034 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5035 SL, VT, LHS, RHS); 5036 5037 SDValue Sign = isSigned 5038 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5039 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5040 : DAG.getConstant(0, SL, VT); 5041 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5042 5043 return DAG.getMergeValues({ Result, Overflow }, SL); 5044 } 5045 5046 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5047 SDLoc SL(Op); 5048 SDValue Chain = Op.getOperand(0); 5049 5050 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5051 !Subtarget->isTrapHandlerEnabled()) 5052 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5053 5054 MachineFunction &MF = DAG.getMachineFunction(); 5055 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5056 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 5057 assert(UserSGPR != AMDGPU::NoRegister); 5058 SDValue QueuePtr = CreateLiveInRegister( 5059 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5060 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5061 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5062 QueuePtr, SDValue()); 5063 SDValue Ops[] = { 5064 ToReg, 5065 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 5066 SGPR01, 5067 ToReg.getValue(1) 5068 }; 5069 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5070 } 5071 5072 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5073 SDLoc SL(Op); 5074 SDValue Chain = Op.getOperand(0); 5075 MachineFunction &MF = DAG.getMachineFunction(); 5076 5077 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5078 !Subtarget->isTrapHandlerEnabled()) { 5079 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5080 "debugtrap handler not supported", 5081 Op.getDebugLoc(), 5082 DS_Warning); 5083 LLVMContext &Ctx = MF.getFunction().getContext(); 5084 Ctx.diagnose(NoTrap); 5085 return Chain; 5086 } 5087 5088 SDValue Ops[] = { 5089 Chain, 5090 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 5091 }; 5092 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5093 } 5094 5095 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5096 SelectionDAG &DAG) const { 5097 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5098 if (Subtarget->hasApertureRegs()) { 5099 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5100 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5101 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5102 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5103 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5104 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5105 unsigned Encoding = 5106 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5107 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5108 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5109 5110 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5111 SDValue ApertureReg = SDValue( 5112 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5113 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5114 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5115 } 5116 5117 MachineFunction &MF = DAG.getMachineFunction(); 5118 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5119 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5120 assert(UserSGPR != AMDGPU::NoRegister); 5121 5122 SDValue QueuePtr = CreateLiveInRegister( 5123 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5124 5125 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5126 // private_segment_aperture_base_hi. 5127 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5128 5129 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 5130 5131 // TODO: Use custom target PseudoSourceValue. 5132 // TODO: We should use the value from the IR intrinsic call, but it might not 5133 // be available and how do we get it? 5134 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5135 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5136 MinAlign(64, StructOffset), 5137 MachineMemOperand::MODereferenceable | 5138 MachineMemOperand::MOInvariant); 5139 } 5140 5141 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5142 SelectionDAG &DAG) const { 5143 SDLoc SL(Op); 5144 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5145 5146 SDValue Src = ASC->getOperand(0); 5147 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5148 5149 const AMDGPUTargetMachine &TM = 5150 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5151 5152 // flat -> local/private 5153 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5154 unsigned DestAS = ASC->getDestAddressSpace(); 5155 5156 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5157 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5158 unsigned NullVal = TM.getNullPointerValue(DestAS); 5159 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5160 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5161 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5162 5163 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5164 NonNull, Ptr, SegmentNullPtr); 5165 } 5166 } 5167 5168 // local/private -> flat 5169 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5170 unsigned SrcAS = ASC->getSrcAddressSpace(); 5171 5172 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5173 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5174 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5175 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5176 5177 SDValue NonNull 5178 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5179 5180 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5181 SDValue CvtPtr 5182 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5183 5184 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5185 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5186 FlatNullPtr); 5187 } 5188 } 5189 5190 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5191 Src.getValueType() == MVT::i64) 5192 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5193 5194 // global <-> flat are no-ops and never emitted. 5195 5196 const MachineFunction &MF = DAG.getMachineFunction(); 5197 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5198 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5199 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5200 5201 return DAG.getUNDEF(ASC->getValueType(0)); 5202 } 5203 5204 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5205 // the small vector and inserting them into the big vector. That is better than 5206 // the default expansion of doing it via a stack slot. Even though the use of 5207 // the stack slot would be optimized away afterwards, the stack slot itself 5208 // remains. 5209 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5210 SelectionDAG &DAG) const { 5211 SDValue Vec = Op.getOperand(0); 5212 SDValue Ins = Op.getOperand(1); 5213 SDValue Idx = Op.getOperand(2); 5214 EVT VecVT = Vec.getValueType(); 5215 EVT InsVT = Ins.getValueType(); 5216 EVT EltVT = VecVT.getVectorElementType(); 5217 unsigned InsNumElts = InsVT.getVectorNumElements(); 5218 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5219 SDLoc SL(Op); 5220 5221 for (unsigned I = 0; I != InsNumElts; ++I) { 5222 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5223 DAG.getConstant(I, SL, MVT::i32)); 5224 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5225 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5226 } 5227 return Vec; 5228 } 5229 5230 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5231 SelectionDAG &DAG) const { 5232 SDValue Vec = Op.getOperand(0); 5233 SDValue InsVal = Op.getOperand(1); 5234 SDValue Idx = Op.getOperand(2); 5235 EVT VecVT = Vec.getValueType(); 5236 EVT EltVT = VecVT.getVectorElementType(); 5237 unsigned VecSize = VecVT.getSizeInBits(); 5238 unsigned EltSize = EltVT.getSizeInBits(); 5239 5240 5241 assert(VecSize <= 64); 5242 5243 unsigned NumElts = VecVT.getVectorNumElements(); 5244 SDLoc SL(Op); 5245 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5246 5247 if (NumElts == 4 && EltSize == 16 && KIdx) { 5248 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5249 5250 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5251 DAG.getConstant(0, SL, MVT::i32)); 5252 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5253 DAG.getConstant(1, SL, MVT::i32)); 5254 5255 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5256 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5257 5258 unsigned Idx = KIdx->getZExtValue(); 5259 bool InsertLo = Idx < 2; 5260 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5261 InsertLo ? LoVec : HiVec, 5262 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5263 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5264 5265 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5266 5267 SDValue Concat = InsertLo ? 5268 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5269 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5270 5271 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5272 } 5273 5274 if (isa<ConstantSDNode>(Idx)) 5275 return SDValue(); 5276 5277 MVT IntVT = MVT::getIntegerVT(VecSize); 5278 5279 // Avoid stack access for dynamic indexing. 5280 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5281 5282 // Create a congruent vector with the target value in each element so that 5283 // the required element can be masked and ORed into the target vector. 5284 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5285 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5286 5287 assert(isPowerOf2_32(EltSize)); 5288 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5289 5290 // Convert vector index to bit-index. 5291 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5292 5293 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5294 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5295 DAG.getConstant(0xffff, SL, IntVT), 5296 ScaledIdx); 5297 5298 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5299 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5300 DAG.getNOT(SL, BFM, IntVT), BCVec); 5301 5302 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5303 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5304 } 5305 5306 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5307 SelectionDAG &DAG) const { 5308 SDLoc SL(Op); 5309 5310 EVT ResultVT = Op.getValueType(); 5311 SDValue Vec = Op.getOperand(0); 5312 SDValue Idx = Op.getOperand(1); 5313 EVT VecVT = Vec.getValueType(); 5314 unsigned VecSize = VecVT.getSizeInBits(); 5315 EVT EltVT = VecVT.getVectorElementType(); 5316 assert(VecSize <= 64); 5317 5318 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5319 5320 // Make sure we do any optimizations that will make it easier to fold 5321 // source modifiers before obscuring it with bit operations. 5322 5323 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5324 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5325 return Combined; 5326 5327 unsigned EltSize = EltVT.getSizeInBits(); 5328 assert(isPowerOf2_32(EltSize)); 5329 5330 MVT IntVT = MVT::getIntegerVT(VecSize); 5331 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5332 5333 // Convert vector index to bit-index (* EltSize) 5334 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5335 5336 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5337 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5338 5339 if (ResultVT == MVT::f16) { 5340 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5341 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5342 } 5343 5344 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5345 } 5346 5347 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5348 assert(Elt % 2 == 0); 5349 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5350 } 5351 5352 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5353 SelectionDAG &DAG) const { 5354 SDLoc SL(Op); 5355 EVT ResultVT = Op.getValueType(); 5356 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5357 5358 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5359 EVT EltVT = PackVT.getVectorElementType(); 5360 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5361 5362 // vector_shuffle <0,1,6,7> lhs, rhs 5363 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5364 // 5365 // vector_shuffle <6,7,2,3> lhs, rhs 5366 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5367 // 5368 // vector_shuffle <6,7,0,1> lhs, rhs 5369 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5370 5371 // Avoid scalarizing when both halves are reading from consecutive elements. 5372 SmallVector<SDValue, 4> Pieces; 5373 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5374 if (elementPairIsContiguous(SVN->getMask(), I)) { 5375 const int Idx = SVN->getMaskElt(I); 5376 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5377 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5378 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5379 PackVT, SVN->getOperand(VecIdx), 5380 DAG.getConstant(EltIdx, SL, MVT::i32)); 5381 Pieces.push_back(SubVec); 5382 } else { 5383 const int Idx0 = SVN->getMaskElt(I); 5384 const int Idx1 = SVN->getMaskElt(I + 1); 5385 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5386 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5387 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5388 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5389 5390 SDValue Vec0 = SVN->getOperand(VecIdx0); 5391 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5392 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5393 5394 SDValue Vec1 = SVN->getOperand(VecIdx1); 5395 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5396 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5397 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5398 } 5399 } 5400 5401 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5402 } 5403 5404 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5405 SelectionDAG &DAG) const { 5406 SDLoc SL(Op); 5407 EVT VT = Op.getValueType(); 5408 5409 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5410 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5411 5412 // Turn into pair of packed build_vectors. 5413 // TODO: Special case for constants that can be materialized with s_mov_b64. 5414 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5415 { Op.getOperand(0), Op.getOperand(1) }); 5416 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5417 { Op.getOperand(2), Op.getOperand(3) }); 5418 5419 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5420 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5421 5422 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5423 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5424 } 5425 5426 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5427 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5428 5429 SDValue Lo = Op.getOperand(0); 5430 SDValue Hi = Op.getOperand(1); 5431 5432 // Avoid adding defined bits with the zero_extend. 5433 if (Hi.isUndef()) { 5434 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5435 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5436 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5437 } 5438 5439 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5440 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5441 5442 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5443 DAG.getConstant(16, SL, MVT::i32)); 5444 if (Lo.isUndef()) 5445 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5446 5447 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5448 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5449 5450 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5451 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5452 } 5453 5454 bool 5455 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5456 // We can fold offsets for anything that doesn't require a GOT relocation. 5457 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5458 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5459 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5460 !shouldEmitGOTReloc(GA->getGlobal()); 5461 } 5462 5463 static SDValue 5464 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5465 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5466 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5467 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5468 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5469 // lowered to the following code sequence: 5470 // 5471 // For constant address space: 5472 // s_getpc_b64 s[0:1] 5473 // s_add_u32 s0, s0, $symbol 5474 // s_addc_u32 s1, s1, 0 5475 // 5476 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5477 // a fixup or relocation is emitted to replace $symbol with a literal 5478 // constant, which is a pc-relative offset from the encoding of the $symbol 5479 // operand to the global variable. 5480 // 5481 // For global address space: 5482 // s_getpc_b64 s[0:1] 5483 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5484 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5485 // 5486 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5487 // fixups or relocations are emitted to replace $symbol@*@lo and 5488 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5489 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5490 // operand to the global variable. 5491 // 5492 // What we want here is an offset from the value returned by s_getpc 5493 // (which is the address of the s_add_u32 instruction) to the global 5494 // variable, but since the encoding of $symbol starts 4 bytes after the start 5495 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5496 // small. This requires us to add 4 to the global variable offset in order to 5497 // compute the correct address. 5498 SDValue PtrLo = 5499 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5500 SDValue PtrHi; 5501 if (GAFlags == SIInstrInfo::MO_NONE) { 5502 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5503 } else { 5504 PtrHi = 5505 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5506 } 5507 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5508 } 5509 5510 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5511 SDValue Op, 5512 SelectionDAG &DAG) const { 5513 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5514 const GlobalValue *GV = GSD->getGlobal(); 5515 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5516 shouldUseLDSConstAddress(GV)) || 5517 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5518 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5519 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5520 5521 SDLoc DL(GSD); 5522 EVT PtrVT = Op.getValueType(); 5523 5524 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5525 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5526 SIInstrInfo::MO_ABS32_LO); 5527 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5528 } 5529 5530 if (shouldEmitFixup(GV)) 5531 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5532 else if (shouldEmitPCReloc(GV)) 5533 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5534 SIInstrInfo::MO_REL32); 5535 5536 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5537 SIInstrInfo::MO_GOTPCREL32); 5538 5539 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5540 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5541 const DataLayout &DataLayout = DAG.getDataLayout(); 5542 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5543 MachinePointerInfo PtrInfo 5544 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5545 5546 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5547 MachineMemOperand::MODereferenceable | 5548 MachineMemOperand::MOInvariant); 5549 } 5550 5551 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5552 const SDLoc &DL, SDValue V) const { 5553 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5554 // the destination register. 5555 // 5556 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5557 // so we will end up with redundant moves to m0. 5558 // 5559 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5560 5561 // A Null SDValue creates a glue result. 5562 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5563 V, Chain); 5564 return SDValue(M0, 0); 5565 } 5566 5567 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5568 SDValue Op, 5569 MVT VT, 5570 unsigned Offset) const { 5571 SDLoc SL(Op); 5572 SDValue Param = lowerKernargMemParameter( 5573 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5574 // The local size values will have the hi 16-bits as zero. 5575 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5576 DAG.getValueType(VT)); 5577 } 5578 5579 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5580 EVT VT) { 5581 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5582 "non-hsa intrinsic with hsa target", 5583 DL.getDebugLoc()); 5584 DAG.getContext()->diagnose(BadIntrin); 5585 return DAG.getUNDEF(VT); 5586 } 5587 5588 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5589 EVT VT) { 5590 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5591 "intrinsic not supported on subtarget", 5592 DL.getDebugLoc()); 5593 DAG.getContext()->diagnose(BadIntrin); 5594 return DAG.getUNDEF(VT); 5595 } 5596 5597 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5598 ArrayRef<SDValue> Elts) { 5599 assert(!Elts.empty()); 5600 MVT Type; 5601 unsigned NumElts; 5602 5603 if (Elts.size() == 1) { 5604 Type = MVT::f32; 5605 NumElts = 1; 5606 } else if (Elts.size() == 2) { 5607 Type = MVT::v2f32; 5608 NumElts = 2; 5609 } else if (Elts.size() == 3) { 5610 Type = MVT::v3f32; 5611 NumElts = 3; 5612 } else if (Elts.size() <= 4) { 5613 Type = MVT::v4f32; 5614 NumElts = 4; 5615 } else if (Elts.size() <= 8) { 5616 Type = MVT::v8f32; 5617 NumElts = 8; 5618 } else { 5619 assert(Elts.size() <= 16); 5620 Type = MVT::v16f32; 5621 NumElts = 16; 5622 } 5623 5624 SmallVector<SDValue, 16> VecElts(NumElts); 5625 for (unsigned i = 0; i < Elts.size(); ++i) { 5626 SDValue Elt = Elts[i]; 5627 if (Elt.getValueType() != MVT::f32) 5628 Elt = DAG.getBitcast(MVT::f32, Elt); 5629 VecElts[i] = Elt; 5630 } 5631 for (unsigned i = Elts.size(); i < NumElts; ++i) 5632 VecElts[i] = DAG.getUNDEF(MVT::f32); 5633 5634 if (NumElts == 1) 5635 return VecElts[0]; 5636 return DAG.getBuildVector(Type, DL, VecElts); 5637 } 5638 5639 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5640 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5641 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5642 5643 uint64_t Value = CachePolicyConst->getZExtValue(); 5644 SDLoc DL(CachePolicy); 5645 if (GLC) { 5646 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5647 Value &= ~(uint64_t)0x1; 5648 } 5649 if (SLC) { 5650 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5651 Value &= ~(uint64_t)0x2; 5652 } 5653 if (DLC) { 5654 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5655 Value &= ~(uint64_t)0x4; 5656 } 5657 5658 return Value == 0; 5659 } 5660 5661 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5662 SDValue Src, int ExtraElts) { 5663 EVT SrcVT = Src.getValueType(); 5664 5665 SmallVector<SDValue, 8> Elts; 5666 5667 if (SrcVT.isVector()) 5668 DAG.ExtractVectorElements(Src, Elts); 5669 else 5670 Elts.push_back(Src); 5671 5672 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5673 while (ExtraElts--) 5674 Elts.push_back(Undef); 5675 5676 return DAG.getBuildVector(CastVT, DL, Elts); 5677 } 5678 5679 // Re-construct the required return value for a image load intrinsic. 5680 // This is more complicated due to the optional use TexFailCtrl which means the required 5681 // return type is an aggregate 5682 static SDValue constructRetValue(SelectionDAG &DAG, 5683 MachineSDNode *Result, 5684 ArrayRef<EVT> ResultTypes, 5685 bool IsTexFail, bool Unpacked, bool IsD16, 5686 int DMaskPop, int NumVDataDwords, 5687 const SDLoc &DL, LLVMContext &Context) { 5688 // Determine the required return type. This is the same regardless of IsTexFail flag 5689 EVT ReqRetVT = ResultTypes[0]; 5690 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5691 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5692 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5693 5694 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5695 DMaskPop : (DMaskPop + 1) / 2; 5696 5697 MVT DataDwordVT = NumDataDwords == 1 ? 5698 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5699 5700 MVT MaskPopVT = MaskPopDwords == 1 ? 5701 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5702 5703 SDValue Data(Result, 0); 5704 SDValue TexFail; 5705 5706 if (IsTexFail) { 5707 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5708 if (MaskPopVT.isVector()) { 5709 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5710 SDValue(Result, 0), ZeroIdx); 5711 } else { 5712 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5713 SDValue(Result, 0), ZeroIdx); 5714 } 5715 5716 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5717 SDValue(Result, 0), 5718 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5719 } 5720 5721 if (DataDwordVT.isVector()) 5722 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5723 NumDataDwords - MaskPopDwords); 5724 5725 if (IsD16) 5726 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5727 5728 if (!ReqRetVT.isVector()) 5729 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5730 5731 Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data); 5732 5733 if (TexFail) 5734 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5735 5736 if (Result->getNumValues() == 1) 5737 return Data; 5738 5739 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5740 } 5741 5742 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5743 SDValue *LWE, bool &IsTexFail) { 5744 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5745 5746 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5747 if (Value) { 5748 IsTexFail = true; 5749 } 5750 5751 SDLoc DL(TexFailCtrlConst); 5752 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5753 Value &= ~(uint64_t)0x1; 5754 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5755 Value &= ~(uint64_t)0x2; 5756 5757 return Value == 0; 5758 } 5759 5760 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5761 MVT PackVectorVT, 5762 SmallVectorImpl<SDValue> &PackedAddrs, 5763 unsigned DimIdx, unsigned EndIdx, 5764 unsigned NumGradients) { 5765 SDLoc DL(Op); 5766 for (unsigned I = DimIdx; I < EndIdx; I++) { 5767 SDValue Addr = Op.getOperand(I); 5768 5769 // Gradients are packed with undef for each coordinate. 5770 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5771 // 1D: undef,dx/dh; undef,dx/dv 5772 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5773 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5774 if (((I + 1) >= EndIdx) || 5775 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5776 I == DimIdx + NumGradients - 1))) { 5777 if (Addr.getValueType() != MVT::i16) 5778 Addr = DAG.getBitcast(MVT::i16, Addr); 5779 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5780 } else { 5781 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5782 I++; 5783 } 5784 Addr = DAG.getBitcast(MVT::f32, Addr); 5785 PackedAddrs.push_back(Addr); 5786 } 5787 } 5788 5789 SDValue SITargetLowering::lowerImage(SDValue Op, 5790 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5791 SelectionDAG &DAG) const { 5792 SDLoc DL(Op); 5793 MachineFunction &MF = DAG.getMachineFunction(); 5794 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5795 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5796 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5797 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5798 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5799 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5800 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5801 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5802 unsigned IntrOpcode = Intr->BaseOpcode; 5803 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5804 5805 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5806 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5807 bool IsD16 = false; 5808 bool IsG16 = false; 5809 bool IsA16 = false; 5810 SDValue VData; 5811 int NumVDataDwords; 5812 bool AdjustRetType = false; 5813 5814 unsigned AddrIdx; // Index of first address argument 5815 unsigned DMask; 5816 unsigned DMaskLanes = 0; 5817 5818 if (BaseOpcode->Atomic) { 5819 VData = Op.getOperand(2); 5820 5821 bool Is64Bit = VData.getValueType() == MVT::i64; 5822 if (BaseOpcode->AtomicX2) { 5823 SDValue VData2 = Op.getOperand(3); 5824 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5825 {VData, VData2}); 5826 if (Is64Bit) 5827 VData = DAG.getBitcast(MVT::v4i32, VData); 5828 5829 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5830 DMask = Is64Bit ? 0xf : 0x3; 5831 NumVDataDwords = Is64Bit ? 4 : 2; 5832 AddrIdx = 4; 5833 } else { 5834 DMask = Is64Bit ? 0x3 : 0x1; 5835 NumVDataDwords = Is64Bit ? 2 : 1; 5836 AddrIdx = 3; 5837 } 5838 } else { 5839 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5840 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5841 DMask = DMaskConst->getZExtValue(); 5842 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5843 5844 if (BaseOpcode->Store) { 5845 VData = Op.getOperand(2); 5846 5847 MVT StoreVT = VData.getSimpleValueType(); 5848 if (StoreVT.getScalarType() == MVT::f16) { 5849 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5850 return Op; // D16 is unsupported for this instruction 5851 5852 IsD16 = true; 5853 VData = handleD16VData(VData, DAG); 5854 } 5855 5856 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5857 } else { 5858 // Work out the num dwords based on the dmask popcount and underlying type 5859 // and whether packing is supported. 5860 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5861 if (LoadVT.getScalarType() == MVT::f16) { 5862 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5863 return Op; // D16 is unsupported for this instruction 5864 5865 IsD16 = true; 5866 } 5867 5868 // Confirm that the return type is large enough for the dmask specified 5869 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5870 (!LoadVT.isVector() && DMaskLanes > 1)) 5871 return Op; 5872 5873 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5874 NumVDataDwords = (DMaskLanes + 1) / 2; 5875 else 5876 NumVDataDwords = DMaskLanes; 5877 5878 AdjustRetType = true; 5879 } 5880 5881 AddrIdx = DMaskIdx + 1; 5882 } 5883 5884 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5885 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5886 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5887 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5888 NumCoords + NumLCM; 5889 unsigned NumMIVAddrs = NumVAddrs; 5890 5891 SmallVector<SDValue, 4> VAddrs; 5892 5893 // Optimize _L to _LZ when _L is zero 5894 if (LZMappingInfo) { 5895 if (auto ConstantLod = 5896 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5897 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5898 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5899 NumMIVAddrs--; // remove 'lod' 5900 } 5901 } 5902 } 5903 5904 // Optimize _mip away, when 'lod' is zero 5905 if (MIPMappingInfo) { 5906 if (auto ConstantLod = 5907 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5908 if (ConstantLod->isNullValue()) { 5909 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5910 NumMIVAddrs--; // remove 'lod' 5911 } 5912 } 5913 } 5914 5915 // Push back extra arguments. 5916 for (unsigned I = 0; I < BaseOpcode->NumExtraArgs; I++) 5917 VAddrs.push_back(Op.getOperand(AddrIdx + I)); 5918 5919 // Check for 16 bit addresses or derivatives and pack if true. 5920 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5921 unsigned CoordIdx = DimIdx + NumGradients; 5922 unsigned CoordsEnd = AddrIdx + NumMIVAddrs; 5923 5924 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5925 MVT VAddrScalarVT = VAddrVT.getScalarType(); 5926 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5927 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 5928 5929 VAddrVT = Op.getOperand(CoordIdx).getSimpleValueType(); 5930 VAddrScalarVT = VAddrVT.getScalarType(); 5931 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 5932 if (IsA16 || IsG16) { 5933 if (IsA16) { 5934 if (!ST->hasA16()) { 5935 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 5936 "support 16 bit addresses\n"); 5937 return Op; 5938 } 5939 if (!IsG16) { 5940 LLVM_DEBUG( 5941 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 5942 "need 16 bit derivatives but got 32 bit derivatives\n"); 5943 return Op; 5944 } 5945 } else if (!ST->hasG16()) { 5946 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 5947 "support 16 bit derivatives\n"); 5948 return Op; 5949 } 5950 5951 if (BaseOpcode->Gradients && !IsA16) { 5952 if (!ST->hasG16()) { 5953 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 5954 "support 16 bit derivatives\n"); 5955 return Op; 5956 } 5957 // Activate g16 5958 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 5959 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 5960 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 5961 } 5962 5963 // Don't compress addresses for G16 5964 const int PackEndIdx = IsA16 ? CoordsEnd : CoordIdx; 5965 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, DimIdx, 5966 PackEndIdx, NumGradients); 5967 5968 if (!IsA16) { 5969 // Add uncompressed address 5970 for (unsigned I = CoordIdx; I < CoordsEnd; I++) 5971 VAddrs.push_back(Op.getOperand(I)); 5972 } 5973 } else { 5974 for (unsigned I = DimIdx; I < CoordsEnd; I++) 5975 VAddrs.push_back(Op.getOperand(I)); 5976 } 5977 5978 // If the register allocator cannot place the address registers contiguously 5979 // without introducing moves, then using the non-sequential address encoding 5980 // is always preferable, since it saves VALU instructions and is usually a 5981 // wash in terms of code size or even better. 5982 // 5983 // However, we currently have no way of hinting to the register allocator that 5984 // MIMG addresses should be placed contiguously when it is possible to do so, 5985 // so force non-NSA for the common 2-address case as a heuristic. 5986 // 5987 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5988 // allocation when possible. 5989 bool UseNSA = 5990 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5991 SDValue VAddr; 5992 if (!UseNSA) 5993 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5994 5995 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5996 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5997 unsigned CtrlIdx; // Index of texfailctrl argument 5998 SDValue Unorm; 5999 if (!BaseOpcode->Sampler) { 6000 Unorm = True; 6001 CtrlIdx = AddrIdx + NumVAddrs + 1; 6002 } else { 6003 auto UnormConst = 6004 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 6005 6006 Unorm = UnormConst->getZExtValue() ? True : False; 6007 CtrlIdx = AddrIdx + NumVAddrs + 3; 6008 } 6009 6010 SDValue TFE; 6011 SDValue LWE; 6012 SDValue TexFail = Op.getOperand(CtrlIdx); 6013 bool IsTexFail = false; 6014 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6015 return Op; 6016 6017 if (IsTexFail) { 6018 if (!DMaskLanes) { 6019 // Expecting to get an error flag since TFC is on - and dmask is 0 6020 // Force dmask to be at least 1 otherwise the instruction will fail 6021 DMask = 0x1; 6022 DMaskLanes = 1; 6023 NumVDataDwords = 1; 6024 } 6025 NumVDataDwords += 1; 6026 AdjustRetType = true; 6027 } 6028 6029 // Has something earlier tagged that the return type needs adjusting 6030 // This happens if the instruction is a load or has set TexFailCtrl flags 6031 if (AdjustRetType) { 6032 // NumVDataDwords reflects the true number of dwords required in the return type 6033 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6034 // This is a no-op load. This can be eliminated 6035 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6036 if (isa<MemSDNode>(Op)) 6037 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6038 return Undef; 6039 } 6040 6041 EVT NewVT = NumVDataDwords > 1 ? 6042 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6043 : MVT::i32; 6044 6045 ResultTypes[0] = NewVT; 6046 if (ResultTypes.size() == 3) { 6047 // Original result was aggregate type used for TexFailCtrl results 6048 // The actual instruction returns as a vector type which has now been 6049 // created. Remove the aggregate result. 6050 ResultTypes.erase(&ResultTypes[1]); 6051 } 6052 } 6053 6054 SDValue GLC; 6055 SDValue SLC; 6056 SDValue DLC; 6057 if (BaseOpcode->Atomic) { 6058 GLC = True; // TODO no-return optimization 6059 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 6060 IsGFX10 ? &DLC : nullptr)) 6061 return Op; 6062 } else { 6063 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 6064 IsGFX10 ? &DLC : nullptr)) 6065 return Op; 6066 } 6067 6068 SmallVector<SDValue, 26> Ops; 6069 if (BaseOpcode->Store || BaseOpcode->Atomic) 6070 Ops.push_back(VData); // vdata 6071 if (UseNSA) { 6072 for (const SDValue &Addr : VAddrs) 6073 Ops.push_back(Addr); 6074 } else { 6075 Ops.push_back(VAddr); 6076 } 6077 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 6078 if (BaseOpcode->Sampler) 6079 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 6080 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6081 if (IsGFX10) 6082 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6083 Ops.push_back(Unorm); 6084 if (IsGFX10) 6085 Ops.push_back(DLC); 6086 Ops.push_back(GLC); 6087 Ops.push_back(SLC); 6088 Ops.push_back(IsA16 && // r128, a16 for gfx9 6089 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6090 if (IsGFX10) 6091 Ops.push_back(IsA16 ? True : False); 6092 Ops.push_back(TFE); 6093 Ops.push_back(LWE); 6094 if (!IsGFX10) 6095 Ops.push_back(DimInfo->DA ? True : False); 6096 if (BaseOpcode->HasD16) 6097 Ops.push_back(IsD16 ? True : False); 6098 if (isa<MemSDNode>(Op)) 6099 Ops.push_back(Op.getOperand(0)); // chain 6100 6101 int NumVAddrDwords = 6102 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6103 int Opcode = -1; 6104 6105 if (IsGFX10) { 6106 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6107 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6108 : AMDGPU::MIMGEncGfx10Default, 6109 NumVDataDwords, NumVAddrDwords); 6110 } else { 6111 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6112 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6113 NumVDataDwords, NumVAddrDwords); 6114 if (Opcode == -1) 6115 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6116 NumVDataDwords, NumVAddrDwords); 6117 } 6118 assert(Opcode != -1); 6119 6120 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6121 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6122 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6123 DAG.setNodeMemRefs(NewNode, {MemRef}); 6124 } 6125 6126 if (BaseOpcode->AtomicX2) { 6127 SmallVector<SDValue, 1> Elt; 6128 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6129 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6130 } else if (!BaseOpcode->Store) { 6131 return constructRetValue(DAG, NewNode, 6132 OrigResultTypes, IsTexFail, 6133 Subtarget->hasUnpackedD16VMem(), IsD16, 6134 DMaskLanes, NumVDataDwords, DL, 6135 *DAG.getContext()); 6136 } 6137 6138 return SDValue(NewNode, 0); 6139 } 6140 6141 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6142 SDValue Offset, SDValue CachePolicy, 6143 SelectionDAG &DAG) const { 6144 MachineFunction &MF = DAG.getMachineFunction(); 6145 6146 const DataLayout &DataLayout = DAG.getDataLayout(); 6147 Align Alignment = 6148 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6149 6150 MachineMemOperand *MMO = MF.getMachineMemOperand( 6151 MachinePointerInfo(), 6152 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6153 MachineMemOperand::MOInvariant, 6154 VT.getStoreSize(), Alignment); 6155 6156 if (!Offset->isDivergent()) { 6157 SDValue Ops[] = { 6158 Rsrc, 6159 Offset, // Offset 6160 CachePolicy 6161 }; 6162 6163 // Widen vec3 load to vec4. 6164 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6165 EVT WidenedVT = 6166 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6167 auto WidenedOp = DAG.getMemIntrinsicNode( 6168 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6169 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6170 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6171 DAG.getVectorIdxConstant(0, DL)); 6172 return Subvector; 6173 } 6174 6175 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6176 DAG.getVTList(VT), Ops, VT, MMO); 6177 } 6178 6179 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6180 // assume that the buffer is unswizzled. 6181 SmallVector<SDValue, 4> Loads; 6182 unsigned NumLoads = 1; 6183 MVT LoadVT = VT.getSimpleVT(); 6184 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6185 assert((LoadVT.getScalarType() == MVT::i32 || 6186 LoadVT.getScalarType() == MVT::f32)); 6187 6188 if (NumElts == 8 || NumElts == 16) { 6189 NumLoads = NumElts / 4; 6190 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6191 } 6192 6193 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6194 SDValue Ops[] = { 6195 DAG.getEntryNode(), // Chain 6196 Rsrc, // rsrc 6197 DAG.getConstant(0, DL, MVT::i32), // vindex 6198 {}, // voffset 6199 {}, // soffset 6200 {}, // offset 6201 CachePolicy, // cachepolicy 6202 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6203 }; 6204 6205 // Use the alignment to ensure that the required offsets will fit into the 6206 // immediate offsets. 6207 setBufferOffsets(Offset, DAG, &Ops[3], 6208 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6209 6210 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6211 for (unsigned i = 0; i < NumLoads; ++i) { 6212 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6213 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6214 LoadVT, MMO, DAG)); 6215 } 6216 6217 if (NumElts == 8 || NumElts == 16) 6218 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6219 6220 return Loads[0]; 6221 } 6222 6223 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6224 SelectionDAG &DAG) const { 6225 MachineFunction &MF = DAG.getMachineFunction(); 6226 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6227 6228 EVT VT = Op.getValueType(); 6229 SDLoc DL(Op); 6230 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6231 6232 // TODO: Should this propagate fast-math-flags? 6233 6234 switch (IntrinsicID) { 6235 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6236 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6237 return emitNonHSAIntrinsicError(DAG, DL, VT); 6238 return getPreloadedValue(DAG, *MFI, VT, 6239 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6240 } 6241 case Intrinsic::amdgcn_dispatch_ptr: 6242 case Intrinsic::amdgcn_queue_ptr: { 6243 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6244 DiagnosticInfoUnsupported BadIntrin( 6245 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6246 DL.getDebugLoc()); 6247 DAG.getContext()->diagnose(BadIntrin); 6248 return DAG.getUNDEF(VT); 6249 } 6250 6251 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6252 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6253 return getPreloadedValue(DAG, *MFI, VT, RegID); 6254 } 6255 case Intrinsic::amdgcn_implicitarg_ptr: { 6256 if (MFI->isEntryFunction()) 6257 return getImplicitArgPtr(DAG, DL); 6258 return getPreloadedValue(DAG, *MFI, VT, 6259 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6260 } 6261 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6262 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6263 // This only makes sense to call in a kernel, so just lower to null. 6264 return DAG.getConstant(0, DL, VT); 6265 } 6266 6267 return getPreloadedValue(DAG, *MFI, VT, 6268 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6269 } 6270 case Intrinsic::amdgcn_dispatch_id: { 6271 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6272 } 6273 case Intrinsic::amdgcn_rcp: 6274 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6275 case Intrinsic::amdgcn_rsq: 6276 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6277 case Intrinsic::amdgcn_rsq_legacy: 6278 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6279 return emitRemovedIntrinsicError(DAG, DL, VT); 6280 return SDValue(); 6281 case Intrinsic::amdgcn_rcp_legacy: 6282 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6283 return emitRemovedIntrinsicError(DAG, DL, VT); 6284 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6285 case Intrinsic::amdgcn_rsq_clamp: { 6286 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6287 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6288 6289 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6290 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6291 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6292 6293 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6294 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6295 DAG.getConstantFP(Max, DL, VT)); 6296 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6297 DAG.getConstantFP(Min, DL, VT)); 6298 } 6299 case Intrinsic::r600_read_ngroups_x: 6300 if (Subtarget->isAmdHsaOS()) 6301 return emitNonHSAIntrinsicError(DAG, DL, VT); 6302 6303 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6304 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6305 false); 6306 case Intrinsic::r600_read_ngroups_y: 6307 if (Subtarget->isAmdHsaOS()) 6308 return emitNonHSAIntrinsicError(DAG, DL, VT); 6309 6310 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6311 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6312 false); 6313 case Intrinsic::r600_read_ngroups_z: 6314 if (Subtarget->isAmdHsaOS()) 6315 return emitNonHSAIntrinsicError(DAG, DL, VT); 6316 6317 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6318 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6319 false); 6320 case Intrinsic::r600_read_global_size_x: 6321 if (Subtarget->isAmdHsaOS()) 6322 return emitNonHSAIntrinsicError(DAG, DL, VT); 6323 6324 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6325 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6326 Align(4), false); 6327 case Intrinsic::r600_read_global_size_y: 6328 if (Subtarget->isAmdHsaOS()) 6329 return emitNonHSAIntrinsicError(DAG, DL, VT); 6330 6331 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6332 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6333 Align(4), false); 6334 case Intrinsic::r600_read_global_size_z: 6335 if (Subtarget->isAmdHsaOS()) 6336 return emitNonHSAIntrinsicError(DAG, DL, VT); 6337 6338 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6339 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6340 Align(4), false); 6341 case Intrinsic::r600_read_local_size_x: 6342 if (Subtarget->isAmdHsaOS()) 6343 return emitNonHSAIntrinsicError(DAG, DL, VT); 6344 6345 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6346 SI::KernelInputOffsets::LOCAL_SIZE_X); 6347 case Intrinsic::r600_read_local_size_y: 6348 if (Subtarget->isAmdHsaOS()) 6349 return emitNonHSAIntrinsicError(DAG, DL, VT); 6350 6351 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6352 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6353 case Intrinsic::r600_read_local_size_z: 6354 if (Subtarget->isAmdHsaOS()) 6355 return emitNonHSAIntrinsicError(DAG, DL, VT); 6356 6357 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6358 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6359 case Intrinsic::amdgcn_workgroup_id_x: 6360 return getPreloadedValue(DAG, *MFI, VT, 6361 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6362 case Intrinsic::amdgcn_workgroup_id_y: 6363 return getPreloadedValue(DAG, *MFI, VT, 6364 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6365 case Intrinsic::amdgcn_workgroup_id_z: 6366 return getPreloadedValue(DAG, *MFI, VT, 6367 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6368 case Intrinsic::amdgcn_workitem_id_x: 6369 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6370 SDLoc(DAG.getEntryNode()), 6371 MFI->getArgInfo().WorkItemIDX); 6372 case Intrinsic::amdgcn_workitem_id_y: 6373 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6374 SDLoc(DAG.getEntryNode()), 6375 MFI->getArgInfo().WorkItemIDY); 6376 case Intrinsic::amdgcn_workitem_id_z: 6377 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6378 SDLoc(DAG.getEntryNode()), 6379 MFI->getArgInfo().WorkItemIDZ); 6380 case Intrinsic::amdgcn_wavefrontsize: 6381 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6382 SDLoc(Op), MVT::i32); 6383 case Intrinsic::amdgcn_s_buffer_load: { 6384 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 6385 SDValue GLC; 6386 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6387 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6388 IsGFX10 ? &DLC : nullptr)) 6389 return Op; 6390 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6391 DAG); 6392 } 6393 case Intrinsic::amdgcn_fdiv_fast: 6394 return lowerFDIV_FAST(Op, DAG); 6395 case Intrinsic::amdgcn_sin: 6396 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6397 6398 case Intrinsic::amdgcn_cos: 6399 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6400 6401 case Intrinsic::amdgcn_mul_u24: 6402 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6403 case Intrinsic::amdgcn_mul_i24: 6404 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6405 6406 case Intrinsic::amdgcn_log_clamp: { 6407 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6408 return SDValue(); 6409 6410 DiagnosticInfoUnsupported BadIntrin( 6411 MF.getFunction(), "intrinsic not supported on subtarget", 6412 DL.getDebugLoc()); 6413 DAG.getContext()->diagnose(BadIntrin); 6414 return DAG.getUNDEF(VT); 6415 } 6416 case Intrinsic::amdgcn_ldexp: 6417 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6418 Op.getOperand(1), Op.getOperand(2)); 6419 6420 case Intrinsic::amdgcn_fract: 6421 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6422 6423 case Intrinsic::amdgcn_class: 6424 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6425 Op.getOperand(1), Op.getOperand(2)); 6426 case Intrinsic::amdgcn_div_fmas: 6427 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6428 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6429 Op.getOperand(4)); 6430 6431 case Intrinsic::amdgcn_div_fixup: 6432 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6433 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6434 6435 case Intrinsic::amdgcn_div_scale: { 6436 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6437 6438 // Translate to the operands expected by the machine instruction. The 6439 // first parameter must be the same as the first instruction. 6440 SDValue Numerator = Op.getOperand(1); 6441 SDValue Denominator = Op.getOperand(2); 6442 6443 // Note this order is opposite of the machine instruction's operations, 6444 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6445 // intrinsic has the numerator as the first operand to match a normal 6446 // division operation. 6447 6448 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6449 6450 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6451 Denominator, Numerator); 6452 } 6453 case Intrinsic::amdgcn_icmp: { 6454 // There is a Pat that handles this variant, so return it as-is. 6455 if (Op.getOperand(1).getValueType() == MVT::i1 && 6456 Op.getConstantOperandVal(2) == 0 && 6457 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6458 return Op; 6459 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6460 } 6461 case Intrinsic::amdgcn_fcmp: { 6462 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6463 } 6464 case Intrinsic::amdgcn_ballot: 6465 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6466 case Intrinsic::amdgcn_fmed3: 6467 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6468 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6469 case Intrinsic::amdgcn_fdot2: 6470 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6471 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6472 Op.getOperand(4)); 6473 case Intrinsic::amdgcn_fmul_legacy: 6474 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6475 Op.getOperand(1), Op.getOperand(2)); 6476 case Intrinsic::amdgcn_sffbh: 6477 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6478 case Intrinsic::amdgcn_sbfe: 6479 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6480 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6481 case Intrinsic::amdgcn_ubfe: 6482 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6483 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6484 case Intrinsic::amdgcn_cvt_pkrtz: 6485 case Intrinsic::amdgcn_cvt_pknorm_i16: 6486 case Intrinsic::amdgcn_cvt_pknorm_u16: 6487 case Intrinsic::amdgcn_cvt_pk_i16: 6488 case Intrinsic::amdgcn_cvt_pk_u16: { 6489 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6490 EVT VT = Op.getValueType(); 6491 unsigned Opcode; 6492 6493 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6494 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6495 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6496 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6497 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6498 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6499 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6500 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6501 else 6502 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6503 6504 if (isTypeLegal(VT)) 6505 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6506 6507 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6508 Op.getOperand(1), Op.getOperand(2)); 6509 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6510 } 6511 case Intrinsic::amdgcn_fmad_ftz: 6512 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6513 Op.getOperand(2), Op.getOperand(3)); 6514 6515 case Intrinsic::amdgcn_if_break: 6516 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6517 Op->getOperand(1), Op->getOperand(2)), 0); 6518 6519 case Intrinsic::amdgcn_groupstaticsize: { 6520 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6521 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6522 return Op; 6523 6524 const Module *M = MF.getFunction().getParent(); 6525 const GlobalValue *GV = 6526 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6527 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6528 SIInstrInfo::MO_ABS32_LO); 6529 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6530 } 6531 case Intrinsic::amdgcn_is_shared: 6532 case Intrinsic::amdgcn_is_private: { 6533 SDLoc SL(Op); 6534 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6535 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6536 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6537 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6538 Op.getOperand(1)); 6539 6540 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6541 DAG.getConstant(1, SL, MVT::i32)); 6542 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6543 } 6544 case Intrinsic::amdgcn_alignbit: 6545 return DAG.getNode(ISD::FSHR, DL, VT, 6546 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6547 case Intrinsic::amdgcn_reloc_constant: { 6548 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6549 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6550 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6551 auto RelocSymbol = cast<GlobalVariable>( 6552 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6553 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6554 SIInstrInfo::MO_ABS32_LO); 6555 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6556 } 6557 default: 6558 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6559 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6560 return lowerImage(Op, ImageDimIntr, DAG); 6561 6562 return Op; 6563 } 6564 } 6565 6566 // This function computes an appropriate offset to pass to 6567 // MachineMemOperand::setOffset() based on the offset inputs to 6568 // an intrinsic. If any of the offsets are non-contstant or 6569 // if VIndex is non-zero then this function returns 0. Otherwise, 6570 // it returns the sum of VOffset, SOffset, and Offset. 6571 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6572 SDValue SOffset, 6573 SDValue Offset, 6574 SDValue VIndex = SDValue()) { 6575 6576 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6577 !isa<ConstantSDNode>(Offset)) 6578 return 0; 6579 6580 if (VIndex) { 6581 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6582 return 0; 6583 } 6584 6585 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6586 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6587 cast<ConstantSDNode>(Offset)->getSExtValue(); 6588 } 6589 6590 static unsigned getDSShaderTypeValue(const MachineFunction &MF) { 6591 switch (MF.getFunction().getCallingConv()) { 6592 case CallingConv::AMDGPU_PS: 6593 return 1; 6594 case CallingConv::AMDGPU_VS: 6595 return 2; 6596 case CallingConv::AMDGPU_GS: 6597 return 3; 6598 case CallingConv::AMDGPU_HS: 6599 case CallingConv::AMDGPU_LS: 6600 case CallingConv::AMDGPU_ES: 6601 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6602 case CallingConv::AMDGPU_CS: 6603 case CallingConv::AMDGPU_KERNEL: 6604 case CallingConv::C: 6605 case CallingConv::Fast: 6606 default: 6607 // Assume other calling conventions are various compute callable functions 6608 return 0; 6609 } 6610 } 6611 6612 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6613 SelectionDAG &DAG) const { 6614 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6615 SDLoc DL(Op); 6616 6617 switch (IntrID) { 6618 case Intrinsic::amdgcn_ds_ordered_add: 6619 case Intrinsic::amdgcn_ds_ordered_swap: { 6620 MemSDNode *M = cast<MemSDNode>(Op); 6621 SDValue Chain = M->getOperand(0); 6622 SDValue M0 = M->getOperand(2); 6623 SDValue Value = M->getOperand(3); 6624 unsigned IndexOperand = M->getConstantOperandVal(7); 6625 unsigned WaveRelease = M->getConstantOperandVal(8); 6626 unsigned WaveDone = M->getConstantOperandVal(9); 6627 6628 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6629 IndexOperand &= ~0x3f; 6630 unsigned CountDw = 0; 6631 6632 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6633 CountDw = (IndexOperand >> 24) & 0xf; 6634 IndexOperand &= ~(0xf << 24); 6635 6636 if (CountDw < 1 || CountDw > 4) { 6637 report_fatal_error( 6638 "ds_ordered_count: dword count must be between 1 and 4"); 6639 } 6640 } 6641 6642 if (IndexOperand) 6643 report_fatal_error("ds_ordered_count: bad index operand"); 6644 6645 if (WaveDone && !WaveRelease) 6646 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6647 6648 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6649 unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction()); 6650 unsigned Offset0 = OrderedCountIndex << 2; 6651 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6652 (Instruction << 4); 6653 6654 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6655 Offset1 |= (CountDw - 1) << 6; 6656 6657 unsigned Offset = Offset0 | (Offset1 << 8); 6658 6659 SDValue Ops[] = { 6660 Chain, 6661 Value, 6662 DAG.getTargetConstant(Offset, DL, MVT::i16), 6663 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6664 }; 6665 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6666 M->getVTList(), Ops, M->getMemoryVT(), 6667 M->getMemOperand()); 6668 } 6669 case Intrinsic::amdgcn_ds_fadd: { 6670 MemSDNode *M = cast<MemSDNode>(Op); 6671 unsigned Opc; 6672 switch (IntrID) { 6673 case Intrinsic::amdgcn_ds_fadd: 6674 Opc = ISD::ATOMIC_LOAD_FADD; 6675 break; 6676 } 6677 6678 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6679 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6680 M->getMemOperand()); 6681 } 6682 case Intrinsic::amdgcn_atomic_inc: 6683 case Intrinsic::amdgcn_atomic_dec: 6684 case Intrinsic::amdgcn_ds_fmin: 6685 case Intrinsic::amdgcn_ds_fmax: { 6686 MemSDNode *M = cast<MemSDNode>(Op); 6687 unsigned Opc; 6688 switch (IntrID) { 6689 case Intrinsic::amdgcn_atomic_inc: 6690 Opc = AMDGPUISD::ATOMIC_INC; 6691 break; 6692 case Intrinsic::amdgcn_atomic_dec: 6693 Opc = AMDGPUISD::ATOMIC_DEC; 6694 break; 6695 case Intrinsic::amdgcn_ds_fmin: 6696 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6697 break; 6698 case Intrinsic::amdgcn_ds_fmax: 6699 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6700 break; 6701 default: 6702 llvm_unreachable("Unknown intrinsic!"); 6703 } 6704 SDValue Ops[] = { 6705 M->getOperand(0), // Chain 6706 M->getOperand(2), // Ptr 6707 M->getOperand(3) // Value 6708 }; 6709 6710 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6711 M->getMemoryVT(), M->getMemOperand()); 6712 } 6713 case Intrinsic::amdgcn_buffer_load: 6714 case Intrinsic::amdgcn_buffer_load_format: { 6715 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6716 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6717 unsigned IdxEn = 1; 6718 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6719 IdxEn = Idx->getZExtValue() != 0; 6720 SDValue Ops[] = { 6721 Op.getOperand(0), // Chain 6722 Op.getOperand(2), // rsrc 6723 Op.getOperand(3), // vindex 6724 SDValue(), // voffset -- will be set by setBufferOffsets 6725 SDValue(), // soffset -- will be set by setBufferOffsets 6726 SDValue(), // offset -- will be set by setBufferOffsets 6727 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6728 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6729 }; 6730 6731 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6732 // We don't know the offset if vindex is non-zero, so clear it. 6733 if (IdxEn) 6734 Offset = 0; 6735 6736 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6737 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6738 6739 EVT VT = Op.getValueType(); 6740 EVT IntVT = VT.changeTypeToInteger(); 6741 auto *M = cast<MemSDNode>(Op); 6742 M->getMemOperand()->setOffset(Offset); 6743 EVT LoadVT = Op.getValueType(); 6744 6745 if (LoadVT.getScalarType() == MVT::f16) 6746 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6747 M, DAG, Ops); 6748 6749 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6750 if (LoadVT.getScalarType() == MVT::i8 || 6751 LoadVT.getScalarType() == MVT::i16) 6752 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6753 6754 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6755 M->getMemOperand(), DAG); 6756 } 6757 case Intrinsic::amdgcn_raw_buffer_load: 6758 case Intrinsic::amdgcn_raw_buffer_load_format: { 6759 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6760 6761 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6762 SDValue Ops[] = { 6763 Op.getOperand(0), // Chain 6764 Op.getOperand(2), // rsrc 6765 DAG.getConstant(0, DL, MVT::i32), // vindex 6766 Offsets.first, // voffset 6767 Op.getOperand(4), // soffset 6768 Offsets.second, // offset 6769 Op.getOperand(5), // cachepolicy, swizzled buffer 6770 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6771 }; 6772 6773 auto *M = cast<MemSDNode>(Op); 6774 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6775 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6776 } 6777 case Intrinsic::amdgcn_struct_buffer_load: 6778 case Intrinsic::amdgcn_struct_buffer_load_format: { 6779 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6780 6781 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6782 SDValue Ops[] = { 6783 Op.getOperand(0), // Chain 6784 Op.getOperand(2), // rsrc 6785 Op.getOperand(3), // vindex 6786 Offsets.first, // voffset 6787 Op.getOperand(5), // soffset 6788 Offsets.second, // offset 6789 Op.getOperand(6), // cachepolicy, swizzled buffer 6790 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6791 }; 6792 6793 auto *M = cast<MemSDNode>(Op); 6794 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6795 Ops[2])); 6796 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6797 } 6798 case Intrinsic::amdgcn_tbuffer_load: { 6799 MemSDNode *M = cast<MemSDNode>(Op); 6800 EVT LoadVT = Op.getValueType(); 6801 6802 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6803 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6804 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6805 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6806 unsigned IdxEn = 1; 6807 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6808 IdxEn = Idx->getZExtValue() != 0; 6809 SDValue Ops[] = { 6810 Op.getOperand(0), // Chain 6811 Op.getOperand(2), // rsrc 6812 Op.getOperand(3), // vindex 6813 Op.getOperand(4), // voffset 6814 Op.getOperand(5), // soffset 6815 Op.getOperand(6), // offset 6816 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6817 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6818 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6819 }; 6820 6821 if (LoadVT.getScalarType() == MVT::f16) 6822 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6823 M, DAG, Ops); 6824 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6825 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6826 DAG); 6827 } 6828 case Intrinsic::amdgcn_raw_tbuffer_load: { 6829 MemSDNode *M = cast<MemSDNode>(Op); 6830 EVT LoadVT = Op.getValueType(); 6831 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6832 6833 SDValue Ops[] = { 6834 Op.getOperand(0), // Chain 6835 Op.getOperand(2), // rsrc 6836 DAG.getConstant(0, DL, MVT::i32), // vindex 6837 Offsets.first, // voffset 6838 Op.getOperand(4), // soffset 6839 Offsets.second, // offset 6840 Op.getOperand(5), // format 6841 Op.getOperand(6), // cachepolicy, swizzled buffer 6842 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6843 }; 6844 6845 if (LoadVT.getScalarType() == MVT::f16) 6846 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6847 M, DAG, Ops); 6848 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6849 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6850 DAG); 6851 } 6852 case Intrinsic::amdgcn_struct_tbuffer_load: { 6853 MemSDNode *M = cast<MemSDNode>(Op); 6854 EVT LoadVT = Op.getValueType(); 6855 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6856 6857 SDValue Ops[] = { 6858 Op.getOperand(0), // Chain 6859 Op.getOperand(2), // rsrc 6860 Op.getOperand(3), // vindex 6861 Offsets.first, // voffset 6862 Op.getOperand(5), // soffset 6863 Offsets.second, // offset 6864 Op.getOperand(6), // format 6865 Op.getOperand(7), // cachepolicy, swizzled buffer 6866 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6867 }; 6868 6869 if (LoadVT.getScalarType() == MVT::f16) 6870 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6871 M, DAG, Ops); 6872 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6873 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6874 DAG); 6875 } 6876 case Intrinsic::amdgcn_buffer_atomic_swap: 6877 case Intrinsic::amdgcn_buffer_atomic_add: 6878 case Intrinsic::amdgcn_buffer_atomic_sub: 6879 case Intrinsic::amdgcn_buffer_atomic_csub: 6880 case Intrinsic::amdgcn_buffer_atomic_smin: 6881 case Intrinsic::amdgcn_buffer_atomic_umin: 6882 case Intrinsic::amdgcn_buffer_atomic_smax: 6883 case Intrinsic::amdgcn_buffer_atomic_umax: 6884 case Intrinsic::amdgcn_buffer_atomic_and: 6885 case Intrinsic::amdgcn_buffer_atomic_or: 6886 case Intrinsic::amdgcn_buffer_atomic_xor: { 6887 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6888 unsigned IdxEn = 1; 6889 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6890 IdxEn = Idx->getZExtValue() != 0; 6891 SDValue Ops[] = { 6892 Op.getOperand(0), // Chain 6893 Op.getOperand(2), // vdata 6894 Op.getOperand(3), // rsrc 6895 Op.getOperand(4), // vindex 6896 SDValue(), // voffset -- will be set by setBufferOffsets 6897 SDValue(), // soffset -- will be set by setBufferOffsets 6898 SDValue(), // offset -- will be set by setBufferOffsets 6899 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6900 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6901 }; 6902 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6903 // We don't know the offset if vindex is non-zero, so clear it. 6904 if (IdxEn) 6905 Offset = 0; 6906 EVT VT = Op.getValueType(); 6907 6908 auto *M = cast<MemSDNode>(Op); 6909 M->getMemOperand()->setOffset(Offset); 6910 unsigned Opcode = 0; 6911 6912 switch (IntrID) { 6913 case Intrinsic::amdgcn_buffer_atomic_swap: 6914 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6915 break; 6916 case Intrinsic::amdgcn_buffer_atomic_add: 6917 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6918 break; 6919 case Intrinsic::amdgcn_buffer_atomic_sub: 6920 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6921 break; 6922 case Intrinsic::amdgcn_buffer_atomic_csub: 6923 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 6924 break; 6925 case Intrinsic::amdgcn_buffer_atomic_smin: 6926 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6927 break; 6928 case Intrinsic::amdgcn_buffer_atomic_umin: 6929 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6930 break; 6931 case Intrinsic::amdgcn_buffer_atomic_smax: 6932 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6933 break; 6934 case Intrinsic::amdgcn_buffer_atomic_umax: 6935 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6936 break; 6937 case Intrinsic::amdgcn_buffer_atomic_and: 6938 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6939 break; 6940 case Intrinsic::amdgcn_buffer_atomic_or: 6941 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6942 break; 6943 case Intrinsic::amdgcn_buffer_atomic_xor: 6944 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6945 break; 6946 default: 6947 llvm_unreachable("unhandled atomic opcode"); 6948 } 6949 6950 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6951 M->getMemOperand()); 6952 } 6953 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6954 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6955 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6956 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6957 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6958 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6959 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6960 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6961 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6962 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6963 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6964 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 6965 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6966 SDValue Ops[] = { 6967 Op.getOperand(0), // Chain 6968 Op.getOperand(2), // vdata 6969 Op.getOperand(3), // rsrc 6970 DAG.getConstant(0, DL, MVT::i32), // vindex 6971 Offsets.first, // voffset 6972 Op.getOperand(5), // soffset 6973 Offsets.second, // offset 6974 Op.getOperand(6), // cachepolicy 6975 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6976 }; 6977 EVT VT = Op.getValueType(); 6978 6979 auto *M = cast<MemSDNode>(Op); 6980 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6981 unsigned Opcode = 0; 6982 6983 switch (IntrID) { 6984 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6985 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6986 break; 6987 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6988 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6989 break; 6990 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6991 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6992 break; 6993 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6994 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6995 break; 6996 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6997 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6998 break; 6999 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7000 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7001 break; 7002 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7003 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7004 break; 7005 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7006 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7007 break; 7008 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7009 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7010 break; 7011 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7012 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7013 break; 7014 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7015 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 7016 break; 7017 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7018 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 7019 break; 7020 default: 7021 llvm_unreachable("unhandled atomic opcode"); 7022 } 7023 7024 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7025 M->getMemOperand()); 7026 } 7027 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7028 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7029 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7030 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7031 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7032 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7033 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7034 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7035 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7036 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7037 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7038 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 7039 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7040 SDValue Ops[] = { 7041 Op.getOperand(0), // Chain 7042 Op.getOperand(2), // vdata 7043 Op.getOperand(3), // rsrc 7044 Op.getOperand(4), // vindex 7045 Offsets.first, // voffset 7046 Op.getOperand(6), // soffset 7047 Offsets.second, // offset 7048 Op.getOperand(7), // cachepolicy 7049 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7050 }; 7051 EVT VT = Op.getValueType(); 7052 7053 auto *M = cast<MemSDNode>(Op); 7054 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7055 Ops[3])); 7056 unsigned Opcode = 0; 7057 7058 switch (IntrID) { 7059 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7060 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7061 break; 7062 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7063 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7064 break; 7065 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7066 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7067 break; 7068 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7069 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7070 break; 7071 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7072 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7073 break; 7074 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7075 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7076 break; 7077 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7078 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7079 break; 7080 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7081 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7082 break; 7083 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7084 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7085 break; 7086 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7087 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7088 break; 7089 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7090 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 7091 break; 7092 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7093 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 7094 break; 7095 default: 7096 llvm_unreachable("unhandled atomic opcode"); 7097 } 7098 7099 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7100 M->getMemOperand()); 7101 } 7102 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7103 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7104 unsigned IdxEn = 1; 7105 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7106 IdxEn = Idx->getZExtValue() != 0; 7107 SDValue Ops[] = { 7108 Op.getOperand(0), // Chain 7109 Op.getOperand(2), // src 7110 Op.getOperand(3), // cmp 7111 Op.getOperand(4), // rsrc 7112 Op.getOperand(5), // vindex 7113 SDValue(), // voffset -- will be set by setBufferOffsets 7114 SDValue(), // soffset -- will be set by setBufferOffsets 7115 SDValue(), // offset -- will be set by setBufferOffsets 7116 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7117 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7118 }; 7119 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7120 // We don't know the offset if vindex is non-zero, so clear it. 7121 if (IdxEn) 7122 Offset = 0; 7123 EVT VT = Op.getValueType(); 7124 auto *M = cast<MemSDNode>(Op); 7125 M->getMemOperand()->setOffset(Offset); 7126 7127 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7128 Op->getVTList(), Ops, VT, M->getMemOperand()); 7129 } 7130 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7131 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7132 SDValue Ops[] = { 7133 Op.getOperand(0), // Chain 7134 Op.getOperand(2), // src 7135 Op.getOperand(3), // cmp 7136 Op.getOperand(4), // rsrc 7137 DAG.getConstant(0, DL, MVT::i32), // vindex 7138 Offsets.first, // voffset 7139 Op.getOperand(6), // soffset 7140 Offsets.second, // offset 7141 Op.getOperand(7), // cachepolicy 7142 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7143 }; 7144 EVT VT = Op.getValueType(); 7145 auto *M = cast<MemSDNode>(Op); 7146 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7147 7148 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7149 Op->getVTList(), Ops, VT, M->getMemOperand()); 7150 } 7151 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7152 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7153 SDValue Ops[] = { 7154 Op.getOperand(0), // Chain 7155 Op.getOperand(2), // src 7156 Op.getOperand(3), // cmp 7157 Op.getOperand(4), // rsrc 7158 Op.getOperand(5), // vindex 7159 Offsets.first, // voffset 7160 Op.getOperand(7), // soffset 7161 Offsets.second, // offset 7162 Op.getOperand(8), // cachepolicy 7163 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7164 }; 7165 EVT VT = Op.getValueType(); 7166 auto *M = cast<MemSDNode>(Op); 7167 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7168 Ops[4])); 7169 7170 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7171 Op->getVTList(), Ops, VT, M->getMemOperand()); 7172 } 7173 case Intrinsic::amdgcn_global_atomic_csub: { 7174 MemSDNode *M = cast<MemSDNode>(Op); 7175 SDValue Ops[] = { 7176 M->getOperand(0), // Chain 7177 M->getOperand(2), // Ptr 7178 M->getOperand(3) // Value 7179 }; 7180 7181 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_LOAD_CSUB, SDLoc(Op), 7182 M->getVTList(), Ops, M->getMemoryVT(), 7183 M->getMemOperand()); 7184 } 7185 7186 default: 7187 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7188 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7189 return lowerImage(Op, ImageDimIntr, DAG); 7190 7191 return SDValue(); 7192 } 7193 } 7194 7195 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7196 // dwordx4 if on SI. 7197 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7198 SDVTList VTList, 7199 ArrayRef<SDValue> Ops, EVT MemVT, 7200 MachineMemOperand *MMO, 7201 SelectionDAG &DAG) const { 7202 EVT VT = VTList.VTs[0]; 7203 EVT WidenedVT = VT; 7204 EVT WidenedMemVT = MemVT; 7205 if (!Subtarget->hasDwordx3LoadStores() && 7206 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7207 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7208 WidenedVT.getVectorElementType(), 4); 7209 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7210 WidenedMemVT.getVectorElementType(), 4); 7211 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7212 } 7213 7214 assert(VTList.NumVTs == 2); 7215 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7216 7217 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7218 WidenedMemVT, MMO); 7219 if (WidenedVT != VT) { 7220 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7221 DAG.getVectorIdxConstant(0, DL)); 7222 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7223 } 7224 return NewOp; 7225 } 7226 7227 SDValue SITargetLowering::handleD16VData(SDValue VData, 7228 SelectionDAG &DAG) const { 7229 EVT StoreVT = VData.getValueType(); 7230 7231 // No change for f16 and legal vector D16 types. 7232 if (!StoreVT.isVector()) 7233 return VData; 7234 7235 SDLoc DL(VData); 7236 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 7237 7238 if (Subtarget->hasUnpackedD16VMem()) { 7239 // We need to unpack the packed data to store. 7240 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7241 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7242 7243 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 7244 StoreVT.getVectorNumElements()); 7245 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7246 return DAG.UnrollVectorOp(ZExt.getNode()); 7247 } 7248 7249 assert(isTypeLegal(StoreVT)); 7250 return VData; 7251 } 7252 7253 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7254 SelectionDAG &DAG) const { 7255 SDLoc DL(Op); 7256 SDValue Chain = Op.getOperand(0); 7257 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7258 MachineFunction &MF = DAG.getMachineFunction(); 7259 7260 switch (IntrinsicID) { 7261 case Intrinsic::amdgcn_exp_compr: { 7262 SDValue Src0 = Op.getOperand(4); 7263 SDValue Src1 = Op.getOperand(5); 7264 // Hack around illegal type on SI by directly selecting it. 7265 if (isTypeLegal(Src0.getValueType())) 7266 return SDValue(); 7267 7268 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7269 SDValue Undef = DAG.getUNDEF(MVT::f32); 7270 const SDValue Ops[] = { 7271 Op.getOperand(2), // tgt 7272 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7273 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7274 Undef, // src2 7275 Undef, // src3 7276 Op.getOperand(7), // vm 7277 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7278 Op.getOperand(3), // en 7279 Op.getOperand(0) // Chain 7280 }; 7281 7282 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7283 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7284 } 7285 case Intrinsic::amdgcn_s_barrier: { 7286 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7287 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7288 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7289 if (WGSize <= ST.getWavefrontSize()) 7290 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7291 Op.getOperand(0)), 0); 7292 } 7293 return SDValue(); 7294 }; 7295 case Intrinsic::amdgcn_tbuffer_store: { 7296 SDValue VData = Op.getOperand(2); 7297 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7298 if (IsD16) 7299 VData = handleD16VData(VData, DAG); 7300 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7301 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7302 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7303 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7304 unsigned IdxEn = 1; 7305 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7306 IdxEn = Idx->getZExtValue() != 0; 7307 SDValue Ops[] = { 7308 Chain, 7309 VData, // vdata 7310 Op.getOperand(3), // rsrc 7311 Op.getOperand(4), // vindex 7312 Op.getOperand(5), // voffset 7313 Op.getOperand(6), // soffset 7314 Op.getOperand(7), // offset 7315 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7316 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7317 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7318 }; 7319 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7320 AMDGPUISD::TBUFFER_STORE_FORMAT; 7321 MemSDNode *M = cast<MemSDNode>(Op); 7322 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7323 M->getMemoryVT(), M->getMemOperand()); 7324 } 7325 7326 case Intrinsic::amdgcn_struct_tbuffer_store: { 7327 SDValue VData = Op.getOperand(2); 7328 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7329 if (IsD16) 7330 VData = handleD16VData(VData, DAG); 7331 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7332 SDValue Ops[] = { 7333 Chain, 7334 VData, // vdata 7335 Op.getOperand(3), // rsrc 7336 Op.getOperand(4), // vindex 7337 Offsets.first, // voffset 7338 Op.getOperand(6), // soffset 7339 Offsets.second, // offset 7340 Op.getOperand(7), // format 7341 Op.getOperand(8), // cachepolicy, swizzled buffer 7342 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7343 }; 7344 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7345 AMDGPUISD::TBUFFER_STORE_FORMAT; 7346 MemSDNode *M = cast<MemSDNode>(Op); 7347 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7348 M->getMemoryVT(), M->getMemOperand()); 7349 } 7350 7351 case Intrinsic::amdgcn_raw_tbuffer_store: { 7352 SDValue VData = Op.getOperand(2); 7353 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7354 if (IsD16) 7355 VData = handleD16VData(VData, DAG); 7356 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7357 SDValue Ops[] = { 7358 Chain, 7359 VData, // vdata 7360 Op.getOperand(3), // rsrc 7361 DAG.getConstant(0, DL, MVT::i32), // vindex 7362 Offsets.first, // voffset 7363 Op.getOperand(5), // soffset 7364 Offsets.second, // offset 7365 Op.getOperand(6), // format 7366 Op.getOperand(7), // cachepolicy, swizzled buffer 7367 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7368 }; 7369 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7370 AMDGPUISD::TBUFFER_STORE_FORMAT; 7371 MemSDNode *M = cast<MemSDNode>(Op); 7372 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7373 M->getMemoryVT(), M->getMemOperand()); 7374 } 7375 7376 case Intrinsic::amdgcn_buffer_store: 7377 case Intrinsic::amdgcn_buffer_store_format: { 7378 SDValue VData = Op.getOperand(2); 7379 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7380 if (IsD16) 7381 VData = handleD16VData(VData, DAG); 7382 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7383 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7384 unsigned IdxEn = 1; 7385 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7386 IdxEn = Idx->getZExtValue() != 0; 7387 SDValue Ops[] = { 7388 Chain, 7389 VData, 7390 Op.getOperand(3), // rsrc 7391 Op.getOperand(4), // vindex 7392 SDValue(), // voffset -- will be set by setBufferOffsets 7393 SDValue(), // soffset -- will be set by setBufferOffsets 7394 SDValue(), // offset -- will be set by setBufferOffsets 7395 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7396 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7397 }; 7398 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7399 // We don't know the offset if vindex is non-zero, so clear it. 7400 if (IdxEn) 7401 Offset = 0; 7402 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7403 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7404 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7405 MemSDNode *M = cast<MemSDNode>(Op); 7406 M->getMemOperand()->setOffset(Offset); 7407 7408 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7409 EVT VDataType = VData.getValueType().getScalarType(); 7410 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7411 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7412 7413 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7414 M->getMemoryVT(), M->getMemOperand()); 7415 } 7416 7417 case Intrinsic::amdgcn_raw_buffer_store: 7418 case Intrinsic::amdgcn_raw_buffer_store_format: { 7419 const bool IsFormat = 7420 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7421 7422 SDValue VData = Op.getOperand(2); 7423 EVT VDataVT = VData.getValueType(); 7424 EVT EltType = VDataVT.getScalarType(); 7425 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7426 if (IsD16) 7427 VData = handleD16VData(VData, DAG); 7428 7429 if (!isTypeLegal(VDataVT)) { 7430 VData = 7431 DAG.getNode(ISD::BITCAST, DL, 7432 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7433 } 7434 7435 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7436 SDValue Ops[] = { 7437 Chain, 7438 VData, 7439 Op.getOperand(3), // rsrc 7440 DAG.getConstant(0, DL, MVT::i32), // vindex 7441 Offsets.first, // voffset 7442 Op.getOperand(5), // soffset 7443 Offsets.second, // offset 7444 Op.getOperand(6), // cachepolicy, swizzled buffer 7445 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7446 }; 7447 unsigned Opc = 7448 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7449 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7450 MemSDNode *M = cast<MemSDNode>(Op); 7451 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7452 7453 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7454 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7455 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7456 7457 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7458 M->getMemoryVT(), M->getMemOperand()); 7459 } 7460 7461 case Intrinsic::amdgcn_struct_buffer_store: 7462 case Intrinsic::amdgcn_struct_buffer_store_format: { 7463 const bool IsFormat = 7464 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7465 7466 SDValue VData = Op.getOperand(2); 7467 EVT VDataVT = VData.getValueType(); 7468 EVT EltType = VDataVT.getScalarType(); 7469 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7470 7471 if (IsD16) 7472 VData = handleD16VData(VData, DAG); 7473 7474 if (!isTypeLegal(VDataVT)) { 7475 VData = 7476 DAG.getNode(ISD::BITCAST, DL, 7477 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7478 } 7479 7480 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7481 SDValue Ops[] = { 7482 Chain, 7483 VData, 7484 Op.getOperand(3), // rsrc 7485 Op.getOperand(4), // vindex 7486 Offsets.first, // voffset 7487 Op.getOperand(6), // soffset 7488 Offsets.second, // offset 7489 Op.getOperand(7), // cachepolicy, swizzled buffer 7490 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7491 }; 7492 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7493 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7494 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7495 MemSDNode *M = cast<MemSDNode>(Op); 7496 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7497 Ops[3])); 7498 7499 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7500 EVT VDataType = VData.getValueType().getScalarType(); 7501 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7502 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7503 7504 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7505 M->getMemoryVT(), M->getMemOperand()); 7506 } 7507 7508 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7509 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7510 unsigned IdxEn = 1; 7511 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7512 IdxEn = Idx->getZExtValue() != 0; 7513 SDValue Ops[] = { 7514 Chain, 7515 Op.getOperand(2), // vdata 7516 Op.getOperand(3), // rsrc 7517 Op.getOperand(4), // vindex 7518 SDValue(), // voffset -- will be set by setBufferOffsets 7519 SDValue(), // soffset -- will be set by setBufferOffsets 7520 SDValue(), // offset -- will be set by setBufferOffsets 7521 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7522 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7523 }; 7524 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7525 // We don't know the offset if vindex is non-zero, so clear it. 7526 if (IdxEn) 7527 Offset = 0; 7528 EVT VT = Op.getOperand(2).getValueType(); 7529 7530 auto *M = cast<MemSDNode>(Op); 7531 M->getMemOperand()->setOffset(Offset); 7532 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 7533 : AMDGPUISD::BUFFER_ATOMIC_FADD; 7534 7535 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7536 M->getMemOperand()); 7537 } 7538 7539 case Intrinsic::amdgcn_global_atomic_fadd: { 7540 SDValue Ops[] = { 7541 Chain, 7542 Op.getOperand(2), // ptr 7543 Op.getOperand(3) // vdata 7544 }; 7545 EVT VT = Op.getOperand(3).getValueType(); 7546 7547 auto *M = cast<MemSDNode>(Op); 7548 if (VT.isVector()) { 7549 return DAG.getMemIntrinsicNode( 7550 AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT, 7551 M->getMemOperand()); 7552 } 7553 7554 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7555 DAG.getVTList(VT, MVT::Other), Ops, 7556 M->getMemOperand()).getValue(1); 7557 } 7558 case Intrinsic::amdgcn_end_cf: 7559 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7560 Op->getOperand(2), Chain), 0); 7561 7562 default: { 7563 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7564 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7565 return lowerImage(Op, ImageDimIntr, DAG); 7566 7567 return Op; 7568 } 7569 } 7570 } 7571 7572 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7573 // offset (the offset that is included in bounds checking and swizzling, to be 7574 // split between the instruction's voffset and immoffset fields) and soffset 7575 // (the offset that is excluded from bounds checking and swizzling, to go in 7576 // the instruction's soffset field). This function takes the first kind of 7577 // offset and figures out how to split it between voffset and immoffset. 7578 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7579 SDValue Offset, SelectionDAG &DAG) const { 7580 SDLoc DL(Offset); 7581 const unsigned MaxImm = 4095; 7582 SDValue N0 = Offset; 7583 ConstantSDNode *C1 = nullptr; 7584 7585 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7586 N0 = SDValue(); 7587 else if (DAG.isBaseWithConstantOffset(N0)) { 7588 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7589 N0 = N0.getOperand(0); 7590 } 7591 7592 if (C1) { 7593 unsigned ImmOffset = C1->getZExtValue(); 7594 // If the immediate value is too big for the immoffset field, put the value 7595 // and -4096 into the immoffset field so that the value that is copied/added 7596 // for the voffset field is a multiple of 4096, and it stands more chance 7597 // of being CSEd with the copy/add for another similar load/store. 7598 // However, do not do that rounding down to a multiple of 4096 if that is a 7599 // negative number, as it appears to be illegal to have a negative offset 7600 // in the vgpr, even if adding the immediate offset makes it positive. 7601 unsigned Overflow = ImmOffset & ~MaxImm; 7602 ImmOffset -= Overflow; 7603 if ((int32_t)Overflow < 0) { 7604 Overflow += ImmOffset; 7605 ImmOffset = 0; 7606 } 7607 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7608 if (Overflow) { 7609 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7610 if (!N0) 7611 N0 = OverflowVal; 7612 else { 7613 SDValue Ops[] = { N0, OverflowVal }; 7614 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7615 } 7616 } 7617 } 7618 if (!N0) 7619 N0 = DAG.getConstant(0, DL, MVT::i32); 7620 if (!C1) 7621 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7622 return {N0, SDValue(C1, 0)}; 7623 } 7624 7625 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7626 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7627 // pointed to by Offsets. 7628 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7629 SelectionDAG &DAG, SDValue *Offsets, 7630 Align Alignment) const { 7631 SDLoc DL(CombinedOffset); 7632 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7633 uint32_t Imm = C->getZExtValue(); 7634 uint32_t SOffset, ImmOffset; 7635 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7636 Alignment)) { 7637 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7638 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7639 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7640 return SOffset + ImmOffset; 7641 } 7642 } 7643 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7644 SDValue N0 = CombinedOffset.getOperand(0); 7645 SDValue N1 = CombinedOffset.getOperand(1); 7646 uint32_t SOffset, ImmOffset; 7647 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7648 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7649 Subtarget, Alignment)) { 7650 Offsets[0] = N0; 7651 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7652 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7653 return 0; 7654 } 7655 } 7656 Offsets[0] = CombinedOffset; 7657 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7658 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7659 return 0; 7660 } 7661 7662 // Handle 8 bit and 16 bit buffer loads 7663 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7664 EVT LoadVT, SDLoc DL, 7665 ArrayRef<SDValue> Ops, 7666 MemSDNode *M) const { 7667 EVT IntVT = LoadVT.changeTypeToInteger(); 7668 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7669 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7670 7671 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7672 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7673 Ops, IntVT, 7674 M->getMemOperand()); 7675 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7676 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7677 7678 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7679 } 7680 7681 // Handle 8 bit and 16 bit buffer stores 7682 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7683 EVT VDataType, SDLoc DL, 7684 SDValue Ops[], 7685 MemSDNode *M) const { 7686 if (VDataType == MVT::f16) 7687 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7688 7689 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7690 Ops[1] = BufferStoreExt; 7691 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7692 AMDGPUISD::BUFFER_STORE_SHORT; 7693 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7694 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7695 M->getMemOperand()); 7696 } 7697 7698 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7699 ISD::LoadExtType ExtType, SDValue Op, 7700 const SDLoc &SL, EVT VT) { 7701 if (VT.bitsLT(Op.getValueType())) 7702 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7703 7704 switch (ExtType) { 7705 case ISD::SEXTLOAD: 7706 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7707 case ISD::ZEXTLOAD: 7708 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7709 case ISD::EXTLOAD: 7710 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7711 case ISD::NON_EXTLOAD: 7712 return Op; 7713 } 7714 7715 llvm_unreachable("invalid ext type"); 7716 } 7717 7718 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7719 SelectionDAG &DAG = DCI.DAG; 7720 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7721 return SDValue(); 7722 7723 // FIXME: Constant loads should all be marked invariant. 7724 unsigned AS = Ld->getAddressSpace(); 7725 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7726 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7727 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7728 return SDValue(); 7729 7730 // Don't do this early, since it may interfere with adjacent load merging for 7731 // illegal types. We can avoid losing alignment information for exotic types 7732 // pre-legalize. 7733 EVT MemVT = Ld->getMemoryVT(); 7734 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7735 MemVT.getSizeInBits() >= 32) 7736 return SDValue(); 7737 7738 SDLoc SL(Ld); 7739 7740 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7741 "unexpected vector extload"); 7742 7743 // TODO: Drop only high part of range. 7744 SDValue Ptr = Ld->getBasePtr(); 7745 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7746 MVT::i32, SL, Ld->getChain(), Ptr, 7747 Ld->getOffset(), 7748 Ld->getPointerInfo(), MVT::i32, 7749 Ld->getAlignment(), 7750 Ld->getMemOperand()->getFlags(), 7751 Ld->getAAInfo(), 7752 nullptr); // Drop ranges 7753 7754 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7755 if (MemVT.isFloatingPoint()) { 7756 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7757 "unexpected fp extload"); 7758 TruncVT = MemVT.changeTypeToInteger(); 7759 } 7760 7761 SDValue Cvt = NewLoad; 7762 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7763 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7764 DAG.getValueType(TruncVT)); 7765 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7766 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7767 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7768 } else { 7769 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7770 } 7771 7772 EVT VT = Ld->getValueType(0); 7773 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7774 7775 DCI.AddToWorklist(Cvt.getNode()); 7776 7777 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7778 // the appropriate extension from the 32-bit load. 7779 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7780 DCI.AddToWorklist(Cvt.getNode()); 7781 7782 // Handle conversion back to floating point if necessary. 7783 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7784 7785 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7786 } 7787 7788 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7789 SDLoc DL(Op); 7790 LoadSDNode *Load = cast<LoadSDNode>(Op); 7791 ISD::LoadExtType ExtType = Load->getExtensionType(); 7792 EVT MemVT = Load->getMemoryVT(); 7793 7794 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7795 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7796 return SDValue(); 7797 7798 // FIXME: Copied from PPC 7799 // First, load into 32 bits, then truncate to 1 bit. 7800 7801 SDValue Chain = Load->getChain(); 7802 SDValue BasePtr = Load->getBasePtr(); 7803 MachineMemOperand *MMO = Load->getMemOperand(); 7804 7805 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7806 7807 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7808 BasePtr, RealMemVT, MMO); 7809 7810 if (!MemVT.isVector()) { 7811 SDValue Ops[] = { 7812 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7813 NewLD.getValue(1) 7814 }; 7815 7816 return DAG.getMergeValues(Ops, DL); 7817 } 7818 7819 SmallVector<SDValue, 3> Elts; 7820 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7821 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7822 DAG.getConstant(I, DL, MVT::i32)); 7823 7824 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7825 } 7826 7827 SDValue Ops[] = { 7828 DAG.getBuildVector(MemVT, DL, Elts), 7829 NewLD.getValue(1) 7830 }; 7831 7832 return DAG.getMergeValues(Ops, DL); 7833 } 7834 7835 if (!MemVT.isVector()) 7836 return SDValue(); 7837 7838 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7839 "Custom lowering for non-i32 vectors hasn't been implemented."); 7840 7841 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7842 MemVT, *Load->getMemOperand())) { 7843 SDValue Ops[2]; 7844 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7845 return DAG.getMergeValues(Ops, DL); 7846 } 7847 7848 unsigned Alignment = Load->getAlignment(); 7849 unsigned AS = Load->getAddressSpace(); 7850 if (Subtarget->hasLDSMisalignedBug() && 7851 AS == AMDGPUAS::FLAT_ADDRESS && 7852 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7853 return SplitVectorLoad(Op, DAG); 7854 } 7855 7856 MachineFunction &MF = DAG.getMachineFunction(); 7857 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7858 // If there is a possibilty that flat instruction access scratch memory 7859 // then we need to use the same legalization rules we use for private. 7860 if (AS == AMDGPUAS::FLAT_ADDRESS && 7861 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7862 AS = MFI->hasFlatScratchInit() ? 7863 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7864 7865 unsigned NumElements = MemVT.getVectorNumElements(); 7866 7867 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7868 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7869 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7870 if (MemVT.isPow2VectorType()) 7871 return SDValue(); 7872 if (NumElements == 3) 7873 return WidenVectorLoad(Op, DAG); 7874 return SplitVectorLoad(Op, DAG); 7875 } 7876 // Non-uniform loads will be selected to MUBUF instructions, so they 7877 // have the same legalization requirements as global and private 7878 // loads. 7879 // 7880 } 7881 7882 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7883 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7884 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7885 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7886 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 7887 Alignment >= 4 && NumElements < 32) { 7888 if (MemVT.isPow2VectorType()) 7889 return SDValue(); 7890 if (NumElements == 3) 7891 return WidenVectorLoad(Op, DAG); 7892 return SplitVectorLoad(Op, DAG); 7893 } 7894 // Non-uniform loads will be selected to MUBUF instructions, so they 7895 // have the same legalization requirements as global and private 7896 // loads. 7897 // 7898 } 7899 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7900 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7901 AS == AMDGPUAS::GLOBAL_ADDRESS || 7902 AS == AMDGPUAS::FLAT_ADDRESS) { 7903 if (NumElements > 4) 7904 return SplitVectorLoad(Op, DAG); 7905 // v3 loads not supported on SI. 7906 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7907 return WidenVectorLoad(Op, DAG); 7908 // v3 and v4 loads are supported for private and global memory. 7909 return SDValue(); 7910 } 7911 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7912 // Depending on the setting of the private_element_size field in the 7913 // resource descriptor, we can only make private accesses up to a certain 7914 // size. 7915 switch (Subtarget->getMaxPrivateElementSize()) { 7916 case 4: { 7917 SDValue Ops[2]; 7918 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7919 return DAG.getMergeValues(Ops, DL); 7920 } 7921 case 8: 7922 if (NumElements > 2) 7923 return SplitVectorLoad(Op, DAG); 7924 return SDValue(); 7925 case 16: 7926 // Same as global/flat 7927 if (NumElements > 4) 7928 return SplitVectorLoad(Op, DAG); 7929 // v3 loads not supported on SI. 7930 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7931 return WidenVectorLoad(Op, DAG); 7932 return SDValue(); 7933 default: 7934 llvm_unreachable("unsupported private_element_size"); 7935 } 7936 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7937 // Use ds_read_b128 if possible. 7938 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7939 MemVT.getStoreSize() == 16) 7940 return SDValue(); 7941 7942 if (NumElements > 2) 7943 return SplitVectorLoad(Op, DAG); 7944 7945 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7946 // address is negative, then the instruction is incorrectly treated as 7947 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7948 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7949 // load later in the SILoadStoreOptimizer. 7950 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7951 NumElements == 2 && MemVT.getStoreSize() == 8 && 7952 Load->getAlignment() < 8) { 7953 return SplitVectorLoad(Op, DAG); 7954 } 7955 } 7956 return SDValue(); 7957 } 7958 7959 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7960 EVT VT = Op.getValueType(); 7961 assert(VT.getSizeInBits() == 64); 7962 7963 SDLoc DL(Op); 7964 SDValue Cond = Op.getOperand(0); 7965 7966 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7967 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7968 7969 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7970 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7971 7972 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7973 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7974 7975 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7976 7977 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7978 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7979 7980 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7981 7982 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7983 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7984 } 7985 7986 // Catch division cases where we can use shortcuts with rcp and rsq 7987 // instructions. 7988 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7989 SelectionDAG &DAG) const { 7990 SDLoc SL(Op); 7991 SDValue LHS = Op.getOperand(0); 7992 SDValue RHS = Op.getOperand(1); 7993 EVT VT = Op.getValueType(); 7994 const SDNodeFlags Flags = Op->getFlags(); 7995 7996 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 7997 Flags.hasApproximateFuncs(); 7998 7999 // Without !fpmath accuracy information, we can't do more because we don't 8000 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8001 if (!AllowInaccurateRcp) 8002 return SDValue(); 8003 8004 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8005 if (CLHS->isExactlyValue(1.0)) { 8006 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8007 // the CI documentation has a worst case error of 1 ulp. 8008 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8009 // use it as long as we aren't trying to use denormals. 8010 // 8011 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8012 8013 // 1.0 / sqrt(x) -> rsq(x) 8014 8015 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8016 // error seems really high at 2^29 ULP. 8017 if (RHS.getOpcode() == ISD::FSQRT) 8018 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8019 8020 // 1.0 / x -> rcp(x) 8021 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8022 } 8023 8024 // Same as for 1.0, but expand the sign out of the constant. 8025 if (CLHS->isExactlyValue(-1.0)) { 8026 // -1.0 / x -> rcp (fneg x) 8027 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8028 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8029 } 8030 } 8031 8032 // Turn into multiply by the reciprocal. 8033 // x / y -> x * (1.0 / y) 8034 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8035 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8036 } 8037 8038 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8039 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8040 SDNodeFlags Flags) { 8041 if (GlueChain->getNumValues() <= 1) { 8042 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8043 } 8044 8045 assert(GlueChain->getNumValues() == 3); 8046 8047 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8048 switch (Opcode) { 8049 default: llvm_unreachable("no chain equivalent for opcode"); 8050 case ISD::FMUL: 8051 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8052 break; 8053 } 8054 8055 return DAG.getNode(Opcode, SL, VTList, 8056 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8057 Flags); 8058 } 8059 8060 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8061 EVT VT, SDValue A, SDValue B, SDValue C, 8062 SDValue GlueChain, SDNodeFlags Flags) { 8063 if (GlueChain->getNumValues() <= 1) { 8064 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8065 } 8066 8067 assert(GlueChain->getNumValues() == 3); 8068 8069 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8070 switch (Opcode) { 8071 default: llvm_unreachable("no chain equivalent for opcode"); 8072 case ISD::FMA: 8073 Opcode = AMDGPUISD::FMA_W_CHAIN; 8074 break; 8075 } 8076 8077 return DAG.getNode(Opcode, SL, VTList, 8078 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8079 Flags); 8080 } 8081 8082 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8083 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8084 return FastLowered; 8085 8086 SDLoc SL(Op); 8087 SDValue Src0 = Op.getOperand(0); 8088 SDValue Src1 = Op.getOperand(1); 8089 8090 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8091 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8092 8093 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8094 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8095 8096 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8097 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8098 8099 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8100 } 8101 8102 // Faster 2.5 ULP division that does not support denormals. 8103 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8104 SDLoc SL(Op); 8105 SDValue LHS = Op.getOperand(1); 8106 SDValue RHS = Op.getOperand(2); 8107 8108 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8109 8110 const APFloat K0Val(BitsToFloat(0x6f800000)); 8111 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8112 8113 const APFloat K1Val(BitsToFloat(0x2f800000)); 8114 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8115 8116 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8117 8118 EVT SetCCVT = 8119 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8120 8121 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8122 8123 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8124 8125 // TODO: Should this propagate fast-math-flags? 8126 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8127 8128 // rcp does not support denormals. 8129 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8130 8131 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8132 8133 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8134 } 8135 8136 // Returns immediate value for setting the F32 denorm mode when using the 8137 // S_DENORM_MODE instruction. 8138 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8139 const SDLoc &SL, const GCNSubtarget *ST) { 8140 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8141 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8142 ? FP_DENORM_FLUSH_NONE 8143 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8144 8145 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8146 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8147 } 8148 8149 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8150 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8151 return FastLowered; 8152 8153 // The selection matcher assumes anything with a chain selecting to a 8154 // mayRaiseFPException machine instruction. Since we're introducing a chain 8155 // here, we need to explicitly report nofpexcept for the regular fdiv 8156 // lowering. 8157 SDNodeFlags Flags = Op->getFlags(); 8158 Flags.setNoFPExcept(true); 8159 8160 SDLoc SL(Op); 8161 SDValue LHS = Op.getOperand(0); 8162 SDValue RHS = Op.getOperand(1); 8163 8164 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8165 8166 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8167 8168 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8169 {RHS, RHS, LHS}, Flags); 8170 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8171 {LHS, RHS, LHS}, Flags); 8172 8173 // Denominator is scaled to not be denormal, so using rcp is ok. 8174 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8175 DenominatorScaled, Flags); 8176 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8177 DenominatorScaled, Flags); 8178 8179 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8180 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8181 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8182 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8183 8184 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8185 8186 if (!HasFP32Denormals) { 8187 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8188 // lowering. The chain dependence is insufficient, and we need glue. We do 8189 // not need the glue variants in a strictfp function. 8190 8191 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8192 8193 SDNode *EnableDenorm; 8194 if (Subtarget->hasDenormModeInst()) { 8195 const SDValue EnableDenormValue = 8196 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8197 8198 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8199 DAG.getEntryNode(), EnableDenormValue).getNode(); 8200 } else { 8201 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8202 SL, MVT::i32); 8203 EnableDenorm = 8204 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8205 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8206 } 8207 8208 SDValue Ops[3] = { 8209 NegDivScale0, 8210 SDValue(EnableDenorm, 0), 8211 SDValue(EnableDenorm, 1) 8212 }; 8213 8214 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8215 } 8216 8217 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8218 ApproxRcp, One, NegDivScale0, Flags); 8219 8220 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8221 ApproxRcp, Fma0, Flags); 8222 8223 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8224 Fma1, Fma1, Flags); 8225 8226 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8227 NumeratorScaled, Mul, Flags); 8228 8229 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8230 Fma2, Fma1, Mul, Fma2, Flags); 8231 8232 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8233 NumeratorScaled, Fma3, Flags); 8234 8235 if (!HasFP32Denormals) { 8236 SDNode *DisableDenorm; 8237 if (Subtarget->hasDenormModeInst()) { 8238 const SDValue DisableDenormValue = 8239 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8240 8241 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8242 Fma4.getValue(1), DisableDenormValue, 8243 Fma4.getValue(2)).getNode(); 8244 } else { 8245 const SDValue DisableDenormValue = 8246 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8247 8248 DisableDenorm = DAG.getMachineNode( 8249 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8250 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8251 } 8252 8253 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8254 SDValue(DisableDenorm, 0), DAG.getRoot()); 8255 DAG.setRoot(OutputChain); 8256 } 8257 8258 SDValue Scale = NumeratorScaled.getValue(1); 8259 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8260 {Fma4, Fma1, Fma3, Scale}, Flags); 8261 8262 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8263 } 8264 8265 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8266 if (DAG.getTarget().Options.UnsafeFPMath) 8267 return lowerFastUnsafeFDIV(Op, DAG); 8268 8269 SDLoc SL(Op); 8270 SDValue X = Op.getOperand(0); 8271 SDValue Y = Op.getOperand(1); 8272 8273 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8274 8275 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8276 8277 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8278 8279 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8280 8281 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8282 8283 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8284 8285 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8286 8287 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8288 8289 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8290 8291 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8292 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8293 8294 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8295 NegDivScale0, Mul, DivScale1); 8296 8297 SDValue Scale; 8298 8299 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8300 // Workaround a hardware bug on SI where the condition output from div_scale 8301 // is not usable. 8302 8303 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8304 8305 // Figure out if the scale to use for div_fmas. 8306 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8307 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8308 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8309 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8310 8311 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8312 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8313 8314 SDValue Scale0Hi 8315 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8316 SDValue Scale1Hi 8317 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8318 8319 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8320 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8321 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8322 } else { 8323 Scale = DivScale1.getValue(1); 8324 } 8325 8326 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8327 Fma4, Fma3, Mul, Scale); 8328 8329 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8330 } 8331 8332 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8333 EVT VT = Op.getValueType(); 8334 8335 if (VT == MVT::f32) 8336 return LowerFDIV32(Op, DAG); 8337 8338 if (VT == MVT::f64) 8339 return LowerFDIV64(Op, DAG); 8340 8341 if (VT == MVT::f16) 8342 return LowerFDIV16(Op, DAG); 8343 8344 llvm_unreachable("Unexpected type for fdiv"); 8345 } 8346 8347 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8348 SDLoc DL(Op); 8349 StoreSDNode *Store = cast<StoreSDNode>(Op); 8350 EVT VT = Store->getMemoryVT(); 8351 8352 if (VT == MVT::i1) { 8353 return DAG.getTruncStore(Store->getChain(), DL, 8354 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8355 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8356 } 8357 8358 assert(VT.isVector() && 8359 Store->getValue().getValueType().getScalarType() == MVT::i32); 8360 8361 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8362 VT, *Store->getMemOperand())) { 8363 return expandUnalignedStore(Store, DAG); 8364 } 8365 8366 unsigned AS = Store->getAddressSpace(); 8367 if (Subtarget->hasLDSMisalignedBug() && 8368 AS == AMDGPUAS::FLAT_ADDRESS && 8369 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8370 return SplitVectorStore(Op, DAG); 8371 } 8372 8373 MachineFunction &MF = DAG.getMachineFunction(); 8374 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8375 // If there is a possibilty that flat instruction access scratch memory 8376 // then we need to use the same legalization rules we use for private. 8377 if (AS == AMDGPUAS::FLAT_ADDRESS && 8378 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8379 AS = MFI->hasFlatScratchInit() ? 8380 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8381 8382 unsigned NumElements = VT.getVectorNumElements(); 8383 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8384 AS == AMDGPUAS::FLAT_ADDRESS) { 8385 if (NumElements > 4) 8386 return SplitVectorStore(Op, DAG); 8387 // v3 stores not supported on SI. 8388 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8389 return SplitVectorStore(Op, DAG); 8390 return SDValue(); 8391 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8392 switch (Subtarget->getMaxPrivateElementSize()) { 8393 case 4: 8394 return scalarizeVectorStore(Store, DAG); 8395 case 8: 8396 if (NumElements > 2) 8397 return SplitVectorStore(Op, DAG); 8398 return SDValue(); 8399 case 16: 8400 if (NumElements > 4 || NumElements == 3) 8401 return SplitVectorStore(Op, DAG); 8402 return SDValue(); 8403 default: 8404 llvm_unreachable("unsupported private_element_size"); 8405 } 8406 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8407 // Use ds_write_b128 if possible. 8408 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 8409 VT.getStoreSize() == 16 && NumElements != 3) 8410 return SDValue(); 8411 8412 if (NumElements > 2) 8413 return SplitVectorStore(Op, DAG); 8414 8415 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8416 // address is negative, then the instruction is incorrectly treated as 8417 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8418 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8419 // store later in the SILoadStoreOptimizer. 8420 if (!Subtarget->hasUsableDSOffset() && 8421 NumElements == 2 && VT.getStoreSize() == 8 && 8422 Store->getAlignment() < 8) { 8423 return SplitVectorStore(Op, DAG); 8424 } 8425 8426 return SDValue(); 8427 } else { 8428 llvm_unreachable("unhandled address space"); 8429 } 8430 } 8431 8432 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8433 SDLoc DL(Op); 8434 EVT VT = Op.getValueType(); 8435 SDValue Arg = Op.getOperand(0); 8436 SDValue TrigVal; 8437 8438 // Propagate fast-math flags so that the multiply we introduce can be folded 8439 // if Arg is already the result of a multiply by constant. 8440 auto Flags = Op->getFlags(); 8441 8442 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8443 8444 if (Subtarget->hasTrigReducedRange()) { 8445 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8446 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8447 } else { 8448 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8449 } 8450 8451 switch (Op.getOpcode()) { 8452 case ISD::FCOS: 8453 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8454 case ISD::FSIN: 8455 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8456 default: 8457 llvm_unreachable("Wrong trig opcode"); 8458 } 8459 } 8460 8461 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8462 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8463 assert(AtomicNode->isCompareAndSwap()); 8464 unsigned AS = AtomicNode->getAddressSpace(); 8465 8466 // No custom lowering required for local address space 8467 if (!isFlatGlobalAddrSpace(AS)) 8468 return Op; 8469 8470 // Non-local address space requires custom lowering for atomic compare 8471 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8472 SDLoc DL(Op); 8473 SDValue ChainIn = Op.getOperand(0); 8474 SDValue Addr = Op.getOperand(1); 8475 SDValue Old = Op.getOperand(2); 8476 SDValue New = Op.getOperand(3); 8477 EVT VT = Op.getValueType(); 8478 MVT SimpleVT = VT.getSimpleVT(); 8479 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8480 8481 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8482 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8483 8484 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8485 Ops, VT, AtomicNode->getMemOperand()); 8486 } 8487 8488 //===----------------------------------------------------------------------===// 8489 // Custom DAG optimizations 8490 //===----------------------------------------------------------------------===// 8491 8492 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8493 DAGCombinerInfo &DCI) const { 8494 EVT VT = N->getValueType(0); 8495 EVT ScalarVT = VT.getScalarType(); 8496 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8497 return SDValue(); 8498 8499 SelectionDAG &DAG = DCI.DAG; 8500 SDLoc DL(N); 8501 8502 SDValue Src = N->getOperand(0); 8503 EVT SrcVT = Src.getValueType(); 8504 8505 // TODO: We could try to match extracting the higher bytes, which would be 8506 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8507 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8508 // about in practice. 8509 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8510 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8511 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8512 DCI.AddToWorklist(Cvt.getNode()); 8513 8514 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8515 if (ScalarVT != MVT::f32) { 8516 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8517 DAG.getTargetConstant(0, DL, MVT::i32)); 8518 } 8519 return Cvt; 8520 } 8521 } 8522 8523 return SDValue(); 8524 } 8525 8526 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8527 8528 // This is a variant of 8529 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8530 // 8531 // The normal DAG combiner will do this, but only if the add has one use since 8532 // that would increase the number of instructions. 8533 // 8534 // This prevents us from seeing a constant offset that can be folded into a 8535 // memory instruction's addressing mode. If we know the resulting add offset of 8536 // a pointer can be folded into an addressing offset, we can replace the pointer 8537 // operand with the add of new constant offset. This eliminates one of the uses, 8538 // and may allow the remaining use to also be simplified. 8539 // 8540 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8541 unsigned AddrSpace, 8542 EVT MemVT, 8543 DAGCombinerInfo &DCI) const { 8544 SDValue N0 = N->getOperand(0); 8545 SDValue N1 = N->getOperand(1); 8546 8547 // We only do this to handle cases where it's profitable when there are 8548 // multiple uses of the add, so defer to the standard combine. 8549 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8550 N0->hasOneUse()) 8551 return SDValue(); 8552 8553 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8554 if (!CN1) 8555 return SDValue(); 8556 8557 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8558 if (!CAdd) 8559 return SDValue(); 8560 8561 // If the resulting offset is too large, we can't fold it into the addressing 8562 // mode offset. 8563 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8564 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8565 8566 AddrMode AM; 8567 AM.HasBaseReg = true; 8568 AM.BaseOffs = Offset.getSExtValue(); 8569 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8570 return SDValue(); 8571 8572 SelectionDAG &DAG = DCI.DAG; 8573 SDLoc SL(N); 8574 EVT VT = N->getValueType(0); 8575 8576 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8577 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 8578 8579 SDNodeFlags Flags; 8580 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8581 (N0.getOpcode() == ISD::OR || 8582 N0->getFlags().hasNoUnsignedWrap())); 8583 8584 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8585 } 8586 8587 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8588 DAGCombinerInfo &DCI) const { 8589 SDValue Ptr = N->getBasePtr(); 8590 SelectionDAG &DAG = DCI.DAG; 8591 SDLoc SL(N); 8592 8593 // TODO: We could also do this for multiplies. 8594 if (Ptr.getOpcode() == ISD::SHL) { 8595 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8596 N->getMemoryVT(), DCI); 8597 if (NewPtr) { 8598 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8599 8600 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8601 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8602 } 8603 } 8604 8605 return SDValue(); 8606 } 8607 8608 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8609 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8610 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8611 (Opc == ISD::XOR && Val == 0); 8612 } 8613 8614 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8615 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8616 // integer combine opportunities since most 64-bit operations are decomposed 8617 // this way. TODO: We won't want this for SALU especially if it is an inline 8618 // immediate. 8619 SDValue SITargetLowering::splitBinaryBitConstantOp( 8620 DAGCombinerInfo &DCI, 8621 const SDLoc &SL, 8622 unsigned Opc, SDValue LHS, 8623 const ConstantSDNode *CRHS) const { 8624 uint64_t Val = CRHS->getZExtValue(); 8625 uint32_t ValLo = Lo_32(Val); 8626 uint32_t ValHi = Hi_32(Val); 8627 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8628 8629 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8630 bitOpWithConstantIsReducible(Opc, ValHi)) || 8631 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8632 // If we need to materialize a 64-bit immediate, it will be split up later 8633 // anyway. Avoid creating the harder to understand 64-bit immediate 8634 // materialization. 8635 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8636 } 8637 8638 return SDValue(); 8639 } 8640 8641 // Returns true if argument is a boolean value which is not serialized into 8642 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8643 static bool isBoolSGPR(SDValue V) { 8644 if (V.getValueType() != MVT::i1) 8645 return false; 8646 switch (V.getOpcode()) { 8647 default: break; 8648 case ISD::SETCC: 8649 case ISD::AND: 8650 case ISD::OR: 8651 case ISD::XOR: 8652 case AMDGPUISD::FP_CLASS: 8653 return true; 8654 } 8655 return false; 8656 } 8657 8658 // If a constant has all zeroes or all ones within each byte return it. 8659 // Otherwise return 0. 8660 static uint32_t getConstantPermuteMask(uint32_t C) { 8661 // 0xff for any zero byte in the mask 8662 uint32_t ZeroByteMask = 0; 8663 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8664 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8665 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8666 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8667 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8668 if ((NonZeroByteMask & C) != NonZeroByteMask) 8669 return 0; // Partial bytes selected. 8670 return C; 8671 } 8672 8673 // Check if a node selects whole bytes from its operand 0 starting at a byte 8674 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8675 // or -1 if not succeeded. 8676 // Note byte select encoding: 8677 // value 0-3 selects corresponding source byte; 8678 // value 0xc selects zero; 8679 // value 0xff selects 0xff. 8680 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8681 assert(V.getValueSizeInBits() == 32); 8682 8683 if (V.getNumOperands() != 2) 8684 return ~0; 8685 8686 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8687 if (!N1) 8688 return ~0; 8689 8690 uint32_t C = N1->getZExtValue(); 8691 8692 switch (V.getOpcode()) { 8693 default: 8694 break; 8695 case ISD::AND: 8696 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8697 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8698 } 8699 break; 8700 8701 case ISD::OR: 8702 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8703 return (0x03020100 & ~ConstMask) | ConstMask; 8704 } 8705 break; 8706 8707 case ISD::SHL: 8708 if (C % 8) 8709 return ~0; 8710 8711 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8712 8713 case ISD::SRL: 8714 if (C % 8) 8715 return ~0; 8716 8717 return uint32_t(0x0c0c0c0c03020100ull >> C); 8718 } 8719 8720 return ~0; 8721 } 8722 8723 SDValue SITargetLowering::performAndCombine(SDNode *N, 8724 DAGCombinerInfo &DCI) const { 8725 if (DCI.isBeforeLegalize()) 8726 return SDValue(); 8727 8728 SelectionDAG &DAG = DCI.DAG; 8729 EVT VT = N->getValueType(0); 8730 SDValue LHS = N->getOperand(0); 8731 SDValue RHS = N->getOperand(1); 8732 8733 8734 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8735 if (VT == MVT::i64 && CRHS) { 8736 if (SDValue Split 8737 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8738 return Split; 8739 } 8740 8741 if (CRHS && VT == MVT::i32) { 8742 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8743 // nb = number of trailing zeroes in mask 8744 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8745 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8746 uint64_t Mask = CRHS->getZExtValue(); 8747 unsigned Bits = countPopulation(Mask); 8748 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8749 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8750 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8751 unsigned Shift = CShift->getZExtValue(); 8752 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8753 unsigned Offset = NB + Shift; 8754 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8755 SDLoc SL(N); 8756 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8757 LHS->getOperand(0), 8758 DAG.getConstant(Offset, SL, MVT::i32), 8759 DAG.getConstant(Bits, SL, MVT::i32)); 8760 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8761 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8762 DAG.getValueType(NarrowVT)); 8763 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8764 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8765 return Shl; 8766 } 8767 } 8768 } 8769 8770 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8771 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8772 isa<ConstantSDNode>(LHS.getOperand(2))) { 8773 uint32_t Sel = getConstantPermuteMask(Mask); 8774 if (!Sel) 8775 return SDValue(); 8776 8777 // Select 0xc for all zero bytes 8778 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8779 SDLoc DL(N); 8780 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8781 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8782 } 8783 } 8784 8785 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8786 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8787 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8788 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8789 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8790 8791 SDValue X = LHS.getOperand(0); 8792 SDValue Y = RHS.getOperand(0); 8793 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8794 return SDValue(); 8795 8796 if (LCC == ISD::SETO) { 8797 if (X != LHS.getOperand(1)) 8798 return SDValue(); 8799 8800 if (RCC == ISD::SETUNE) { 8801 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8802 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8803 return SDValue(); 8804 8805 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8806 SIInstrFlags::N_SUBNORMAL | 8807 SIInstrFlags::N_ZERO | 8808 SIInstrFlags::P_ZERO | 8809 SIInstrFlags::P_SUBNORMAL | 8810 SIInstrFlags::P_NORMAL; 8811 8812 static_assert(((~(SIInstrFlags::S_NAN | 8813 SIInstrFlags::Q_NAN | 8814 SIInstrFlags::N_INFINITY | 8815 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8816 "mask not equal"); 8817 8818 SDLoc DL(N); 8819 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8820 X, DAG.getConstant(Mask, DL, MVT::i32)); 8821 } 8822 } 8823 } 8824 8825 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8826 std::swap(LHS, RHS); 8827 8828 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8829 RHS.hasOneUse()) { 8830 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8831 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8832 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8833 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8834 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8835 (RHS.getOperand(0) == LHS.getOperand(0) && 8836 LHS.getOperand(0) == LHS.getOperand(1))) { 8837 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8838 unsigned NewMask = LCC == ISD::SETO ? 8839 Mask->getZExtValue() & ~OrdMask : 8840 Mask->getZExtValue() & OrdMask; 8841 8842 SDLoc DL(N); 8843 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8844 DAG.getConstant(NewMask, DL, MVT::i32)); 8845 } 8846 } 8847 8848 if (VT == MVT::i32 && 8849 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8850 // and x, (sext cc from i1) => select cc, x, 0 8851 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8852 std::swap(LHS, RHS); 8853 if (isBoolSGPR(RHS.getOperand(0))) 8854 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8855 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8856 } 8857 8858 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8859 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8860 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8861 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8862 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8863 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8864 if (LHSMask != ~0u && RHSMask != ~0u) { 8865 // Canonicalize the expression in an attempt to have fewer unique masks 8866 // and therefore fewer registers used to hold the masks. 8867 if (LHSMask > RHSMask) { 8868 std::swap(LHSMask, RHSMask); 8869 std::swap(LHS, RHS); 8870 } 8871 8872 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8873 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8874 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8875 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8876 8877 // Check of we need to combine values from two sources within a byte. 8878 if (!(LHSUsedLanes & RHSUsedLanes) && 8879 // If we select high and lower word keep it for SDWA. 8880 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8881 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8882 // Each byte in each mask is either selector mask 0-3, or has higher 8883 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8884 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8885 // mask which is not 0xff wins. By anding both masks we have a correct 8886 // result except that 0x0c shall be corrected to give 0x0c only. 8887 uint32_t Mask = LHSMask & RHSMask; 8888 for (unsigned I = 0; I < 32; I += 8) { 8889 uint32_t ByteSel = 0xff << I; 8890 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8891 Mask &= (0x0c << I) & 0xffffffff; 8892 } 8893 8894 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8895 // or 0x0c. 8896 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8897 SDLoc DL(N); 8898 8899 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8900 LHS.getOperand(0), RHS.getOperand(0), 8901 DAG.getConstant(Sel, DL, MVT::i32)); 8902 } 8903 } 8904 } 8905 8906 return SDValue(); 8907 } 8908 8909 SDValue SITargetLowering::performOrCombine(SDNode *N, 8910 DAGCombinerInfo &DCI) const { 8911 SelectionDAG &DAG = DCI.DAG; 8912 SDValue LHS = N->getOperand(0); 8913 SDValue RHS = N->getOperand(1); 8914 8915 EVT VT = N->getValueType(0); 8916 if (VT == MVT::i1) { 8917 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8918 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8919 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8920 SDValue Src = LHS.getOperand(0); 8921 if (Src != RHS.getOperand(0)) 8922 return SDValue(); 8923 8924 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8925 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8926 if (!CLHS || !CRHS) 8927 return SDValue(); 8928 8929 // Only 10 bits are used. 8930 static const uint32_t MaxMask = 0x3ff; 8931 8932 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8933 SDLoc DL(N); 8934 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8935 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8936 } 8937 8938 return SDValue(); 8939 } 8940 8941 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8942 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8943 LHS.getOpcode() == AMDGPUISD::PERM && 8944 isa<ConstantSDNode>(LHS.getOperand(2))) { 8945 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8946 if (!Sel) 8947 return SDValue(); 8948 8949 Sel |= LHS.getConstantOperandVal(2); 8950 SDLoc DL(N); 8951 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8952 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8953 } 8954 8955 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8956 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8957 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8958 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8959 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8960 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8961 if (LHSMask != ~0u && RHSMask != ~0u) { 8962 // Canonicalize the expression in an attempt to have fewer unique masks 8963 // and therefore fewer registers used to hold the masks. 8964 if (LHSMask > RHSMask) { 8965 std::swap(LHSMask, RHSMask); 8966 std::swap(LHS, RHS); 8967 } 8968 8969 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8970 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8971 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8972 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8973 8974 // Check of we need to combine values from two sources within a byte. 8975 if (!(LHSUsedLanes & RHSUsedLanes) && 8976 // If we select high and lower word keep it for SDWA. 8977 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8978 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8979 // Kill zero bytes selected by other mask. Zero value is 0xc. 8980 LHSMask &= ~RHSUsedLanes; 8981 RHSMask &= ~LHSUsedLanes; 8982 // Add 4 to each active LHS lane 8983 LHSMask |= LHSUsedLanes & 0x04040404; 8984 // Combine masks 8985 uint32_t Sel = LHSMask | RHSMask; 8986 SDLoc DL(N); 8987 8988 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8989 LHS.getOperand(0), RHS.getOperand(0), 8990 DAG.getConstant(Sel, DL, MVT::i32)); 8991 } 8992 } 8993 } 8994 8995 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 8996 return SDValue(); 8997 8998 // TODO: This could be a generic combine with a predicate for extracting the 8999 // high half of an integer being free. 9000 9001 // (or i64:x, (zero_extend i32:y)) -> 9002 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9003 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9004 RHS.getOpcode() != ISD::ZERO_EXTEND) 9005 std::swap(LHS, RHS); 9006 9007 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9008 SDValue ExtSrc = RHS.getOperand(0); 9009 EVT SrcVT = ExtSrc.getValueType(); 9010 if (SrcVT == MVT::i32) { 9011 SDLoc SL(N); 9012 SDValue LowLHS, HiBits; 9013 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9014 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9015 9016 DCI.AddToWorklist(LowOr.getNode()); 9017 DCI.AddToWorklist(HiBits.getNode()); 9018 9019 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9020 LowOr, HiBits); 9021 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9022 } 9023 } 9024 9025 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9026 if (CRHS) { 9027 if (SDValue Split 9028 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9029 return Split; 9030 } 9031 9032 return SDValue(); 9033 } 9034 9035 SDValue SITargetLowering::performXorCombine(SDNode *N, 9036 DAGCombinerInfo &DCI) const { 9037 EVT VT = N->getValueType(0); 9038 if (VT != MVT::i64) 9039 return SDValue(); 9040 9041 SDValue LHS = N->getOperand(0); 9042 SDValue RHS = N->getOperand(1); 9043 9044 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9045 if (CRHS) { 9046 if (SDValue Split 9047 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9048 return Split; 9049 } 9050 9051 return SDValue(); 9052 } 9053 9054 // Instructions that will be lowered with a final instruction that zeros the 9055 // high result bits. 9056 // XXX - probably only need to list legal operations. 9057 static bool fp16SrcZerosHighBits(unsigned Opc) { 9058 switch (Opc) { 9059 case ISD::FADD: 9060 case ISD::FSUB: 9061 case ISD::FMUL: 9062 case ISD::FDIV: 9063 case ISD::FREM: 9064 case ISD::FMA: 9065 case ISD::FMAD: 9066 case ISD::FCANONICALIZE: 9067 case ISD::FP_ROUND: 9068 case ISD::UINT_TO_FP: 9069 case ISD::SINT_TO_FP: 9070 case ISD::FABS: 9071 // Fabs is lowered to a bit operation, but it's an and which will clear the 9072 // high bits anyway. 9073 case ISD::FSQRT: 9074 case ISD::FSIN: 9075 case ISD::FCOS: 9076 case ISD::FPOWI: 9077 case ISD::FPOW: 9078 case ISD::FLOG: 9079 case ISD::FLOG2: 9080 case ISD::FLOG10: 9081 case ISD::FEXP: 9082 case ISD::FEXP2: 9083 case ISD::FCEIL: 9084 case ISD::FTRUNC: 9085 case ISD::FRINT: 9086 case ISD::FNEARBYINT: 9087 case ISD::FROUND: 9088 case ISD::FFLOOR: 9089 case ISD::FMINNUM: 9090 case ISD::FMAXNUM: 9091 case AMDGPUISD::FRACT: 9092 case AMDGPUISD::CLAMP: 9093 case AMDGPUISD::COS_HW: 9094 case AMDGPUISD::SIN_HW: 9095 case AMDGPUISD::FMIN3: 9096 case AMDGPUISD::FMAX3: 9097 case AMDGPUISD::FMED3: 9098 case AMDGPUISD::FMAD_FTZ: 9099 case AMDGPUISD::RCP: 9100 case AMDGPUISD::RSQ: 9101 case AMDGPUISD::RCP_IFLAG: 9102 case AMDGPUISD::LDEXP: 9103 return true; 9104 default: 9105 // fcopysign, select and others may be lowered to 32-bit bit operations 9106 // which don't zero the high bits. 9107 return false; 9108 } 9109 } 9110 9111 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9112 DAGCombinerInfo &DCI) const { 9113 if (!Subtarget->has16BitInsts() || 9114 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9115 return SDValue(); 9116 9117 EVT VT = N->getValueType(0); 9118 if (VT != MVT::i32) 9119 return SDValue(); 9120 9121 SDValue Src = N->getOperand(0); 9122 if (Src.getValueType() != MVT::i16) 9123 return SDValue(); 9124 9125 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9126 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9127 if (Src.getOpcode() == ISD::BITCAST) { 9128 SDValue BCSrc = Src.getOperand(0); 9129 if (BCSrc.getValueType() == MVT::f16 && 9130 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9131 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9132 } 9133 9134 return SDValue(); 9135 } 9136 9137 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9138 DAGCombinerInfo &DCI) 9139 const { 9140 SDValue Src = N->getOperand(0); 9141 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9142 9143 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9144 VTSign->getVT() == MVT::i8) || 9145 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9146 VTSign->getVT() == MVT::i16)) && 9147 Src.hasOneUse()) { 9148 auto *M = cast<MemSDNode>(Src); 9149 SDValue Ops[] = { 9150 Src.getOperand(0), // Chain 9151 Src.getOperand(1), // rsrc 9152 Src.getOperand(2), // vindex 9153 Src.getOperand(3), // voffset 9154 Src.getOperand(4), // soffset 9155 Src.getOperand(5), // offset 9156 Src.getOperand(6), 9157 Src.getOperand(7) 9158 }; 9159 // replace with BUFFER_LOAD_BYTE/SHORT 9160 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9161 Src.getOperand(0).getValueType()); 9162 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9163 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9164 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9165 ResList, 9166 Ops, M->getMemoryVT(), 9167 M->getMemOperand()); 9168 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9169 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9170 } 9171 return SDValue(); 9172 } 9173 9174 SDValue SITargetLowering::performClassCombine(SDNode *N, 9175 DAGCombinerInfo &DCI) const { 9176 SelectionDAG &DAG = DCI.DAG; 9177 SDValue Mask = N->getOperand(1); 9178 9179 // fp_class x, 0 -> false 9180 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9181 if (CMask->isNullValue()) 9182 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9183 } 9184 9185 if (N->getOperand(0).isUndef()) 9186 return DAG.getUNDEF(MVT::i1); 9187 9188 return SDValue(); 9189 } 9190 9191 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9192 DAGCombinerInfo &DCI) const { 9193 EVT VT = N->getValueType(0); 9194 SDValue N0 = N->getOperand(0); 9195 9196 if (N0.isUndef()) 9197 return N0; 9198 9199 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9200 N0.getOpcode() == ISD::SINT_TO_FP)) { 9201 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9202 N->getFlags()); 9203 } 9204 9205 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9206 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9207 N0.getOperand(0), N->getFlags()); 9208 } 9209 9210 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9211 } 9212 9213 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9214 unsigned MaxDepth) const { 9215 unsigned Opcode = Op.getOpcode(); 9216 if (Opcode == ISD::FCANONICALIZE) 9217 return true; 9218 9219 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9220 auto F = CFP->getValueAPF(); 9221 if (F.isNaN() && F.isSignaling()) 9222 return false; 9223 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9224 } 9225 9226 // If source is a result of another standard FP operation it is already in 9227 // canonical form. 9228 if (MaxDepth == 0) 9229 return false; 9230 9231 switch (Opcode) { 9232 // These will flush denorms if required. 9233 case ISD::FADD: 9234 case ISD::FSUB: 9235 case ISD::FMUL: 9236 case ISD::FCEIL: 9237 case ISD::FFLOOR: 9238 case ISD::FMA: 9239 case ISD::FMAD: 9240 case ISD::FSQRT: 9241 case ISD::FDIV: 9242 case ISD::FREM: 9243 case ISD::FP_ROUND: 9244 case ISD::FP_EXTEND: 9245 case AMDGPUISD::FMUL_LEGACY: 9246 case AMDGPUISD::FMAD_FTZ: 9247 case AMDGPUISD::RCP: 9248 case AMDGPUISD::RSQ: 9249 case AMDGPUISD::RSQ_CLAMP: 9250 case AMDGPUISD::RCP_LEGACY: 9251 case AMDGPUISD::RCP_IFLAG: 9252 case AMDGPUISD::DIV_SCALE: 9253 case AMDGPUISD::DIV_FMAS: 9254 case AMDGPUISD::DIV_FIXUP: 9255 case AMDGPUISD::FRACT: 9256 case AMDGPUISD::LDEXP: 9257 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9258 case AMDGPUISD::CVT_F32_UBYTE0: 9259 case AMDGPUISD::CVT_F32_UBYTE1: 9260 case AMDGPUISD::CVT_F32_UBYTE2: 9261 case AMDGPUISD::CVT_F32_UBYTE3: 9262 return true; 9263 9264 // It can/will be lowered or combined as a bit operation. 9265 // Need to check their input recursively to handle. 9266 case ISD::FNEG: 9267 case ISD::FABS: 9268 case ISD::FCOPYSIGN: 9269 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9270 9271 case ISD::FSIN: 9272 case ISD::FCOS: 9273 case ISD::FSINCOS: 9274 return Op.getValueType().getScalarType() != MVT::f16; 9275 9276 case ISD::FMINNUM: 9277 case ISD::FMAXNUM: 9278 case ISD::FMINNUM_IEEE: 9279 case ISD::FMAXNUM_IEEE: 9280 case AMDGPUISD::CLAMP: 9281 case AMDGPUISD::FMED3: 9282 case AMDGPUISD::FMAX3: 9283 case AMDGPUISD::FMIN3: { 9284 // FIXME: Shouldn't treat the generic operations different based these. 9285 // However, we aren't really required to flush the result from 9286 // minnum/maxnum.. 9287 9288 // snans will be quieted, so we only need to worry about denormals. 9289 if (Subtarget->supportsMinMaxDenormModes() || 9290 denormalsEnabledForType(DAG, Op.getValueType())) 9291 return true; 9292 9293 // Flushing may be required. 9294 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9295 // targets need to check their input recursively. 9296 9297 // FIXME: Does this apply with clamp? It's implemented with max. 9298 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9299 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9300 return false; 9301 } 9302 9303 return true; 9304 } 9305 case ISD::SELECT: { 9306 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9307 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9308 } 9309 case ISD::BUILD_VECTOR: { 9310 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9311 SDValue SrcOp = Op.getOperand(i); 9312 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9313 return false; 9314 } 9315 9316 return true; 9317 } 9318 case ISD::EXTRACT_VECTOR_ELT: 9319 case ISD::EXTRACT_SUBVECTOR: { 9320 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9321 } 9322 case ISD::INSERT_VECTOR_ELT: { 9323 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9324 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9325 } 9326 case ISD::UNDEF: 9327 // Could be anything. 9328 return false; 9329 9330 case ISD::BITCAST: { 9331 // Hack round the mess we make when legalizing extract_vector_elt 9332 SDValue Src = Op.getOperand(0); 9333 if (Src.getValueType() == MVT::i16 && 9334 Src.getOpcode() == ISD::TRUNCATE) { 9335 SDValue TruncSrc = Src.getOperand(0); 9336 if (TruncSrc.getValueType() == MVT::i32 && 9337 TruncSrc.getOpcode() == ISD::BITCAST && 9338 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9339 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9340 } 9341 } 9342 9343 return false; 9344 } 9345 case ISD::INTRINSIC_WO_CHAIN: { 9346 unsigned IntrinsicID 9347 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9348 // TODO: Handle more intrinsics 9349 switch (IntrinsicID) { 9350 case Intrinsic::amdgcn_cvt_pkrtz: 9351 case Intrinsic::amdgcn_cubeid: 9352 case Intrinsic::amdgcn_frexp_mant: 9353 case Intrinsic::amdgcn_fdot2: 9354 case Intrinsic::amdgcn_rcp: 9355 case Intrinsic::amdgcn_rsq: 9356 case Intrinsic::amdgcn_rsq_clamp: 9357 case Intrinsic::amdgcn_rcp_legacy: 9358 case Intrinsic::amdgcn_rsq_legacy: 9359 case Intrinsic::amdgcn_trig_preop: 9360 return true; 9361 default: 9362 break; 9363 } 9364 9365 LLVM_FALLTHROUGH; 9366 } 9367 default: 9368 return denormalsEnabledForType(DAG, Op.getValueType()) && 9369 DAG.isKnownNeverSNaN(Op); 9370 } 9371 9372 llvm_unreachable("invalid operation"); 9373 } 9374 9375 // Constant fold canonicalize. 9376 SDValue SITargetLowering::getCanonicalConstantFP( 9377 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9378 // Flush denormals to 0 if not enabled. 9379 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9380 return DAG.getConstantFP(0.0, SL, VT); 9381 9382 if (C.isNaN()) { 9383 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9384 if (C.isSignaling()) { 9385 // Quiet a signaling NaN. 9386 // FIXME: Is this supposed to preserve payload bits? 9387 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9388 } 9389 9390 // Make sure it is the canonical NaN bitpattern. 9391 // 9392 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9393 // immediate? 9394 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9395 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9396 } 9397 9398 // Already canonical. 9399 return DAG.getConstantFP(C, SL, VT); 9400 } 9401 9402 static bool vectorEltWillFoldAway(SDValue Op) { 9403 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9404 } 9405 9406 SDValue SITargetLowering::performFCanonicalizeCombine( 9407 SDNode *N, 9408 DAGCombinerInfo &DCI) const { 9409 SelectionDAG &DAG = DCI.DAG; 9410 SDValue N0 = N->getOperand(0); 9411 EVT VT = N->getValueType(0); 9412 9413 // fcanonicalize undef -> qnan 9414 if (N0.isUndef()) { 9415 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9416 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9417 } 9418 9419 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9420 EVT VT = N->getValueType(0); 9421 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9422 } 9423 9424 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9425 // (fcanonicalize k) 9426 // 9427 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9428 9429 // TODO: This could be better with wider vectors that will be split to v2f16, 9430 // and to consider uses since there aren't that many packed operations. 9431 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9432 isTypeLegal(MVT::v2f16)) { 9433 SDLoc SL(N); 9434 SDValue NewElts[2]; 9435 SDValue Lo = N0.getOperand(0); 9436 SDValue Hi = N0.getOperand(1); 9437 EVT EltVT = Lo.getValueType(); 9438 9439 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9440 for (unsigned I = 0; I != 2; ++I) { 9441 SDValue Op = N0.getOperand(I); 9442 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9443 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9444 CFP->getValueAPF()); 9445 } else if (Op.isUndef()) { 9446 // Handled below based on what the other operand is. 9447 NewElts[I] = Op; 9448 } else { 9449 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9450 } 9451 } 9452 9453 // If one half is undef, and one is constant, perfer a splat vector rather 9454 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9455 // cheaper to use and may be free with a packed operation. 9456 if (NewElts[0].isUndef()) { 9457 if (isa<ConstantFPSDNode>(NewElts[1])) 9458 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9459 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9460 } 9461 9462 if (NewElts[1].isUndef()) { 9463 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9464 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9465 } 9466 9467 return DAG.getBuildVector(VT, SL, NewElts); 9468 } 9469 } 9470 9471 unsigned SrcOpc = N0.getOpcode(); 9472 9473 // If it's free to do so, push canonicalizes further up the source, which may 9474 // find a canonical source. 9475 // 9476 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9477 // sNaNs. 9478 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9479 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9480 if (CRHS && N0.hasOneUse()) { 9481 SDLoc SL(N); 9482 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9483 N0.getOperand(0)); 9484 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9485 DCI.AddToWorklist(Canon0.getNode()); 9486 9487 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9488 } 9489 } 9490 9491 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9492 } 9493 9494 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9495 switch (Opc) { 9496 case ISD::FMAXNUM: 9497 case ISD::FMAXNUM_IEEE: 9498 return AMDGPUISD::FMAX3; 9499 case ISD::SMAX: 9500 return AMDGPUISD::SMAX3; 9501 case ISD::UMAX: 9502 return AMDGPUISD::UMAX3; 9503 case ISD::FMINNUM: 9504 case ISD::FMINNUM_IEEE: 9505 return AMDGPUISD::FMIN3; 9506 case ISD::SMIN: 9507 return AMDGPUISD::SMIN3; 9508 case ISD::UMIN: 9509 return AMDGPUISD::UMIN3; 9510 default: 9511 llvm_unreachable("Not a min/max opcode"); 9512 } 9513 } 9514 9515 SDValue SITargetLowering::performIntMed3ImmCombine( 9516 SelectionDAG &DAG, const SDLoc &SL, 9517 SDValue Op0, SDValue Op1, bool Signed) const { 9518 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9519 if (!K1) 9520 return SDValue(); 9521 9522 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9523 if (!K0) 9524 return SDValue(); 9525 9526 if (Signed) { 9527 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9528 return SDValue(); 9529 } else { 9530 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9531 return SDValue(); 9532 } 9533 9534 EVT VT = K0->getValueType(0); 9535 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9536 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9537 return DAG.getNode(Med3Opc, SL, VT, 9538 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9539 } 9540 9541 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9542 MVT NVT = MVT::i32; 9543 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9544 9545 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9546 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9547 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9548 9549 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9550 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9551 } 9552 9553 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9554 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9555 return C; 9556 9557 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9558 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9559 return C; 9560 } 9561 9562 return nullptr; 9563 } 9564 9565 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9566 const SDLoc &SL, 9567 SDValue Op0, 9568 SDValue Op1) const { 9569 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9570 if (!K1) 9571 return SDValue(); 9572 9573 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9574 if (!K0) 9575 return SDValue(); 9576 9577 // Ordered >= (although NaN inputs should have folded away by now). 9578 if (K0->getValueAPF() > K1->getValueAPF()) 9579 return SDValue(); 9580 9581 const MachineFunction &MF = DAG.getMachineFunction(); 9582 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9583 9584 // TODO: Check IEEE bit enabled? 9585 EVT VT = Op0.getValueType(); 9586 if (Info->getMode().DX10Clamp) { 9587 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9588 // hardware fmed3 behavior converting to a min. 9589 // FIXME: Should this be allowing -0.0? 9590 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9591 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9592 } 9593 9594 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9595 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9596 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9597 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9598 // then give the other result, which is different from med3 with a NaN 9599 // input. 9600 SDValue Var = Op0.getOperand(0); 9601 if (!DAG.isKnownNeverSNaN(Var)) 9602 return SDValue(); 9603 9604 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9605 9606 if ((!K0->hasOneUse() || 9607 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9608 (!K1->hasOneUse() || 9609 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9610 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9611 Var, SDValue(K0, 0), SDValue(K1, 0)); 9612 } 9613 } 9614 9615 return SDValue(); 9616 } 9617 9618 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9619 DAGCombinerInfo &DCI) const { 9620 SelectionDAG &DAG = DCI.DAG; 9621 9622 EVT VT = N->getValueType(0); 9623 unsigned Opc = N->getOpcode(); 9624 SDValue Op0 = N->getOperand(0); 9625 SDValue Op1 = N->getOperand(1); 9626 9627 // Only do this if the inner op has one use since this will just increases 9628 // register pressure for no benefit. 9629 9630 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9631 !VT.isVector() && 9632 (VT == MVT::i32 || VT == MVT::f32 || 9633 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9634 // max(max(a, b), c) -> max3(a, b, c) 9635 // min(min(a, b), c) -> min3(a, b, c) 9636 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9637 SDLoc DL(N); 9638 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9639 DL, 9640 N->getValueType(0), 9641 Op0.getOperand(0), 9642 Op0.getOperand(1), 9643 Op1); 9644 } 9645 9646 // Try commuted. 9647 // max(a, max(b, c)) -> max3(a, b, c) 9648 // min(a, min(b, c)) -> min3(a, b, c) 9649 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9650 SDLoc DL(N); 9651 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9652 DL, 9653 N->getValueType(0), 9654 Op0, 9655 Op1.getOperand(0), 9656 Op1.getOperand(1)); 9657 } 9658 } 9659 9660 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9661 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9662 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9663 return Med3; 9664 } 9665 9666 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9667 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9668 return Med3; 9669 } 9670 9671 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9672 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9673 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9674 (Opc == AMDGPUISD::FMIN_LEGACY && 9675 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9676 (VT == MVT::f32 || VT == MVT::f64 || 9677 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9678 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9679 Op0.hasOneUse()) { 9680 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9681 return Res; 9682 } 9683 9684 return SDValue(); 9685 } 9686 9687 static bool isClampZeroToOne(SDValue A, SDValue B) { 9688 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9689 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9690 // FIXME: Should this be allowing -0.0? 9691 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9692 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9693 } 9694 } 9695 9696 return false; 9697 } 9698 9699 // FIXME: Should only worry about snans for version with chain. 9700 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9701 DAGCombinerInfo &DCI) const { 9702 EVT VT = N->getValueType(0); 9703 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9704 // NaNs. With a NaN input, the order of the operands may change the result. 9705 9706 SelectionDAG &DAG = DCI.DAG; 9707 SDLoc SL(N); 9708 9709 SDValue Src0 = N->getOperand(0); 9710 SDValue Src1 = N->getOperand(1); 9711 SDValue Src2 = N->getOperand(2); 9712 9713 if (isClampZeroToOne(Src0, Src1)) { 9714 // const_a, const_b, x -> clamp is safe in all cases including signaling 9715 // nans. 9716 // FIXME: Should this be allowing -0.0? 9717 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9718 } 9719 9720 const MachineFunction &MF = DAG.getMachineFunction(); 9721 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9722 9723 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9724 // handling no dx10-clamp? 9725 if (Info->getMode().DX10Clamp) { 9726 // If NaNs is clamped to 0, we are free to reorder the inputs. 9727 9728 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9729 std::swap(Src0, Src1); 9730 9731 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9732 std::swap(Src1, Src2); 9733 9734 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9735 std::swap(Src0, Src1); 9736 9737 if (isClampZeroToOne(Src1, Src2)) 9738 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9739 } 9740 9741 return SDValue(); 9742 } 9743 9744 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9745 DAGCombinerInfo &DCI) const { 9746 SDValue Src0 = N->getOperand(0); 9747 SDValue Src1 = N->getOperand(1); 9748 if (Src0.isUndef() && Src1.isUndef()) 9749 return DCI.DAG.getUNDEF(N->getValueType(0)); 9750 return SDValue(); 9751 } 9752 9753 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 9754 // expanded into a set of cmp/select instructions. 9755 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 9756 unsigned NumElem, 9757 bool IsDivergentIdx) { 9758 if (UseDivergentRegisterIndexing) 9759 return false; 9760 9761 unsigned VecSize = EltSize * NumElem; 9762 9763 // Sub-dword vectors of size 2 dword or less have better implementation. 9764 if (VecSize <= 64 && EltSize < 32) 9765 return false; 9766 9767 // Always expand the rest of sub-dword instructions, otherwise it will be 9768 // lowered via memory. 9769 if (EltSize < 32) 9770 return true; 9771 9772 // Always do this if var-idx is divergent, otherwise it will become a loop. 9773 if (IsDivergentIdx) 9774 return true; 9775 9776 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 9777 unsigned NumInsts = NumElem /* Number of compares */ + 9778 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 9779 return NumInsts <= 16; 9780 } 9781 9782 static bool shouldExpandVectorDynExt(SDNode *N) { 9783 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 9784 if (isa<ConstantSDNode>(Idx)) 9785 return false; 9786 9787 SDValue Vec = N->getOperand(0); 9788 EVT VecVT = Vec.getValueType(); 9789 EVT EltVT = VecVT.getVectorElementType(); 9790 unsigned EltSize = EltVT.getSizeInBits(); 9791 unsigned NumElem = VecVT.getVectorNumElements(); 9792 9793 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 9794 Idx->isDivergent()); 9795 } 9796 9797 SDValue SITargetLowering::performExtractVectorEltCombine( 9798 SDNode *N, DAGCombinerInfo &DCI) const { 9799 SDValue Vec = N->getOperand(0); 9800 SelectionDAG &DAG = DCI.DAG; 9801 9802 EVT VecVT = Vec.getValueType(); 9803 EVT EltVT = VecVT.getVectorElementType(); 9804 9805 if ((Vec.getOpcode() == ISD::FNEG || 9806 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9807 SDLoc SL(N); 9808 EVT EltVT = N->getValueType(0); 9809 SDValue Idx = N->getOperand(1); 9810 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9811 Vec.getOperand(0), Idx); 9812 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9813 } 9814 9815 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9816 // => 9817 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9818 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9819 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9820 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9821 SDLoc SL(N); 9822 EVT EltVT = N->getValueType(0); 9823 SDValue Idx = N->getOperand(1); 9824 unsigned Opc = Vec.getOpcode(); 9825 9826 switch(Opc) { 9827 default: 9828 break; 9829 // TODO: Support other binary operations. 9830 case ISD::FADD: 9831 case ISD::FSUB: 9832 case ISD::FMUL: 9833 case ISD::ADD: 9834 case ISD::UMIN: 9835 case ISD::UMAX: 9836 case ISD::SMIN: 9837 case ISD::SMAX: 9838 case ISD::FMAXNUM: 9839 case ISD::FMINNUM: 9840 case ISD::FMAXNUM_IEEE: 9841 case ISD::FMINNUM_IEEE: { 9842 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9843 Vec.getOperand(0), Idx); 9844 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9845 Vec.getOperand(1), Idx); 9846 9847 DCI.AddToWorklist(Elt0.getNode()); 9848 DCI.AddToWorklist(Elt1.getNode()); 9849 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9850 } 9851 } 9852 } 9853 9854 unsigned VecSize = VecVT.getSizeInBits(); 9855 unsigned EltSize = EltVT.getSizeInBits(); 9856 9857 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9858 if (::shouldExpandVectorDynExt(N)) { 9859 SDLoc SL(N); 9860 SDValue Idx = N->getOperand(1); 9861 SDValue V; 9862 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9863 SDValue IC = DAG.getVectorIdxConstant(I, SL); 9864 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9865 if (I == 0) 9866 V = Elt; 9867 else 9868 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9869 } 9870 return V; 9871 } 9872 9873 if (!DCI.isBeforeLegalize()) 9874 return SDValue(); 9875 9876 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9877 // elements. This exposes more load reduction opportunities by replacing 9878 // multiple small extract_vector_elements with a single 32-bit extract. 9879 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9880 if (isa<MemSDNode>(Vec) && 9881 EltSize <= 16 && 9882 EltVT.isByteSized() && 9883 VecSize > 32 && 9884 VecSize % 32 == 0 && 9885 Idx) { 9886 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9887 9888 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9889 unsigned EltIdx = BitIndex / 32; 9890 unsigned LeftoverBitIdx = BitIndex % 32; 9891 SDLoc SL(N); 9892 9893 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9894 DCI.AddToWorklist(Cast.getNode()); 9895 9896 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9897 DAG.getConstant(EltIdx, SL, MVT::i32)); 9898 DCI.AddToWorklist(Elt.getNode()); 9899 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9900 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9901 DCI.AddToWorklist(Srl.getNode()); 9902 9903 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9904 DCI.AddToWorklist(Trunc.getNode()); 9905 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9906 } 9907 9908 return SDValue(); 9909 } 9910 9911 SDValue 9912 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9913 DAGCombinerInfo &DCI) const { 9914 SDValue Vec = N->getOperand(0); 9915 SDValue Idx = N->getOperand(2); 9916 EVT VecVT = Vec.getValueType(); 9917 EVT EltVT = VecVT.getVectorElementType(); 9918 9919 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9920 // => BUILD_VECTOR n x select (e, const-idx) 9921 if (!::shouldExpandVectorDynExt(N)) 9922 return SDValue(); 9923 9924 SelectionDAG &DAG = DCI.DAG; 9925 SDLoc SL(N); 9926 SDValue Ins = N->getOperand(1); 9927 EVT IdxVT = Idx.getValueType(); 9928 9929 SmallVector<SDValue, 16> Ops; 9930 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9931 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9932 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9933 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9934 Ops.push_back(V); 9935 } 9936 9937 return DAG.getBuildVector(VecVT, SL, Ops); 9938 } 9939 9940 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9941 const SDNode *N0, 9942 const SDNode *N1) const { 9943 EVT VT = N0->getValueType(0); 9944 9945 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9946 // support denormals ever. 9947 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9948 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9949 getSubtarget()->hasMadF16())) && 9950 isOperationLegal(ISD::FMAD, VT)) 9951 return ISD::FMAD; 9952 9953 const TargetOptions &Options = DAG.getTarget().Options; 9954 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9955 (N0->getFlags().hasAllowContract() && 9956 N1->getFlags().hasAllowContract())) && 9957 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 9958 return ISD::FMA; 9959 } 9960 9961 return 0; 9962 } 9963 9964 // For a reassociatable opcode perform: 9965 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9966 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9967 SelectionDAG &DAG) const { 9968 EVT VT = N->getValueType(0); 9969 if (VT != MVT::i32 && VT != MVT::i64) 9970 return SDValue(); 9971 9972 unsigned Opc = N->getOpcode(); 9973 SDValue Op0 = N->getOperand(0); 9974 SDValue Op1 = N->getOperand(1); 9975 9976 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9977 return SDValue(); 9978 9979 if (Op0->isDivergent()) 9980 std::swap(Op0, Op1); 9981 9982 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9983 return SDValue(); 9984 9985 SDValue Op2 = Op1.getOperand(1); 9986 Op1 = Op1.getOperand(0); 9987 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9988 return SDValue(); 9989 9990 if (Op1->isDivergent()) 9991 std::swap(Op1, Op2); 9992 9993 // If either operand is constant this will conflict with 9994 // DAGCombiner::ReassociateOps(). 9995 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9996 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9997 return SDValue(); 9998 9999 SDLoc SL(N); 10000 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10001 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10002 } 10003 10004 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10005 EVT VT, 10006 SDValue N0, SDValue N1, SDValue N2, 10007 bool Signed) { 10008 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10009 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10010 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10011 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10012 } 10013 10014 SDValue SITargetLowering::performAddCombine(SDNode *N, 10015 DAGCombinerInfo &DCI) const { 10016 SelectionDAG &DAG = DCI.DAG; 10017 EVT VT = N->getValueType(0); 10018 SDLoc SL(N); 10019 SDValue LHS = N->getOperand(0); 10020 SDValue RHS = N->getOperand(1); 10021 10022 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10023 && Subtarget->hasMad64_32() && 10024 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10025 VT.getScalarSizeInBits() <= 64) { 10026 if (LHS.getOpcode() != ISD::MUL) 10027 std::swap(LHS, RHS); 10028 10029 SDValue MulLHS = LHS.getOperand(0); 10030 SDValue MulRHS = LHS.getOperand(1); 10031 SDValue AddRHS = RHS; 10032 10033 // TODO: Maybe restrict if SGPR inputs. 10034 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10035 numBitsUnsigned(MulRHS, DAG) <= 32) { 10036 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10037 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10038 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10039 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10040 } 10041 10042 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10043 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10044 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10045 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10046 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10047 } 10048 10049 return SDValue(); 10050 } 10051 10052 if (SDValue V = reassociateScalarOps(N, DAG)) { 10053 return V; 10054 } 10055 10056 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10057 return SDValue(); 10058 10059 // add x, zext (setcc) => addcarry x, 0, setcc 10060 // add x, sext (setcc) => subcarry x, 0, setcc 10061 unsigned Opc = LHS.getOpcode(); 10062 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10063 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10064 std::swap(RHS, LHS); 10065 10066 Opc = RHS.getOpcode(); 10067 switch (Opc) { 10068 default: break; 10069 case ISD::ZERO_EXTEND: 10070 case ISD::SIGN_EXTEND: 10071 case ISD::ANY_EXTEND: { 10072 auto Cond = RHS.getOperand(0); 10073 // If this won't be a real VOPC output, we would still need to insert an 10074 // extra instruction anyway. 10075 if (!isBoolSGPR(Cond)) 10076 break; 10077 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10078 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10079 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10080 return DAG.getNode(Opc, SL, VTList, Args); 10081 } 10082 case ISD::ADDCARRY: { 10083 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10084 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10085 if (!C || C->getZExtValue() != 0) break; 10086 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10087 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10088 } 10089 } 10090 return SDValue(); 10091 } 10092 10093 SDValue SITargetLowering::performSubCombine(SDNode *N, 10094 DAGCombinerInfo &DCI) const { 10095 SelectionDAG &DAG = DCI.DAG; 10096 EVT VT = N->getValueType(0); 10097 10098 if (VT != MVT::i32) 10099 return SDValue(); 10100 10101 SDLoc SL(N); 10102 SDValue LHS = N->getOperand(0); 10103 SDValue RHS = N->getOperand(1); 10104 10105 // sub x, zext (setcc) => subcarry x, 0, setcc 10106 // sub x, sext (setcc) => addcarry x, 0, setcc 10107 unsigned Opc = RHS.getOpcode(); 10108 switch (Opc) { 10109 default: break; 10110 case ISD::ZERO_EXTEND: 10111 case ISD::SIGN_EXTEND: 10112 case ISD::ANY_EXTEND: { 10113 auto Cond = RHS.getOperand(0); 10114 // If this won't be a real VOPC output, we would still need to insert an 10115 // extra instruction anyway. 10116 if (!isBoolSGPR(Cond)) 10117 break; 10118 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10119 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10120 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10121 return DAG.getNode(Opc, SL, VTList, Args); 10122 } 10123 } 10124 10125 if (LHS.getOpcode() == ISD::SUBCARRY) { 10126 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10127 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10128 if (!C || !C->isNullValue()) 10129 return SDValue(); 10130 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10131 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10132 } 10133 return SDValue(); 10134 } 10135 10136 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10137 DAGCombinerInfo &DCI) const { 10138 10139 if (N->getValueType(0) != MVT::i32) 10140 return SDValue(); 10141 10142 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10143 if (!C || C->getZExtValue() != 0) 10144 return SDValue(); 10145 10146 SelectionDAG &DAG = DCI.DAG; 10147 SDValue LHS = N->getOperand(0); 10148 10149 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10150 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10151 unsigned LHSOpc = LHS.getOpcode(); 10152 unsigned Opc = N->getOpcode(); 10153 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10154 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10155 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10156 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10157 } 10158 return SDValue(); 10159 } 10160 10161 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10162 DAGCombinerInfo &DCI) const { 10163 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10164 return SDValue(); 10165 10166 SelectionDAG &DAG = DCI.DAG; 10167 EVT VT = N->getValueType(0); 10168 10169 SDLoc SL(N); 10170 SDValue LHS = N->getOperand(0); 10171 SDValue RHS = N->getOperand(1); 10172 10173 // These should really be instruction patterns, but writing patterns with 10174 // source modiifiers is a pain. 10175 10176 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10177 if (LHS.getOpcode() == ISD::FADD) { 10178 SDValue A = LHS.getOperand(0); 10179 if (A == LHS.getOperand(1)) { 10180 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10181 if (FusedOp != 0) { 10182 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10183 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10184 } 10185 } 10186 } 10187 10188 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10189 if (RHS.getOpcode() == ISD::FADD) { 10190 SDValue A = RHS.getOperand(0); 10191 if (A == RHS.getOperand(1)) { 10192 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10193 if (FusedOp != 0) { 10194 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10195 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10196 } 10197 } 10198 } 10199 10200 return SDValue(); 10201 } 10202 10203 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10204 DAGCombinerInfo &DCI) const { 10205 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10206 return SDValue(); 10207 10208 SelectionDAG &DAG = DCI.DAG; 10209 SDLoc SL(N); 10210 EVT VT = N->getValueType(0); 10211 assert(!VT.isVector()); 10212 10213 // Try to get the fneg to fold into the source modifier. This undoes generic 10214 // DAG combines and folds them into the mad. 10215 // 10216 // Only do this if we are not trying to support denormals. v_mad_f32 does 10217 // not support denormals ever. 10218 SDValue LHS = N->getOperand(0); 10219 SDValue RHS = N->getOperand(1); 10220 if (LHS.getOpcode() == ISD::FADD) { 10221 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10222 SDValue A = LHS.getOperand(0); 10223 if (A == LHS.getOperand(1)) { 10224 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10225 if (FusedOp != 0){ 10226 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10227 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10228 10229 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10230 } 10231 } 10232 } 10233 10234 if (RHS.getOpcode() == ISD::FADD) { 10235 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10236 10237 SDValue A = RHS.getOperand(0); 10238 if (A == RHS.getOperand(1)) { 10239 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10240 if (FusedOp != 0){ 10241 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10242 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10243 } 10244 } 10245 } 10246 10247 return SDValue(); 10248 } 10249 10250 SDValue SITargetLowering::performFMACombine(SDNode *N, 10251 DAGCombinerInfo &DCI) const { 10252 SelectionDAG &DAG = DCI.DAG; 10253 EVT VT = N->getValueType(0); 10254 SDLoc SL(N); 10255 10256 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 10257 return SDValue(); 10258 10259 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10260 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10261 SDValue Op1 = N->getOperand(0); 10262 SDValue Op2 = N->getOperand(1); 10263 SDValue FMA = N->getOperand(2); 10264 10265 if (FMA.getOpcode() != ISD::FMA || 10266 Op1.getOpcode() != ISD::FP_EXTEND || 10267 Op2.getOpcode() != ISD::FP_EXTEND) 10268 return SDValue(); 10269 10270 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10271 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10272 // is sufficient to allow generaing fdot2. 10273 const TargetOptions &Options = DAG.getTarget().Options; 10274 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10275 (N->getFlags().hasAllowContract() && 10276 FMA->getFlags().hasAllowContract())) { 10277 Op1 = Op1.getOperand(0); 10278 Op2 = Op2.getOperand(0); 10279 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10280 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10281 return SDValue(); 10282 10283 SDValue Vec1 = Op1.getOperand(0); 10284 SDValue Idx1 = Op1.getOperand(1); 10285 SDValue Vec2 = Op2.getOperand(0); 10286 10287 SDValue FMAOp1 = FMA.getOperand(0); 10288 SDValue FMAOp2 = FMA.getOperand(1); 10289 SDValue FMAAcc = FMA.getOperand(2); 10290 10291 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10292 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10293 return SDValue(); 10294 10295 FMAOp1 = FMAOp1.getOperand(0); 10296 FMAOp2 = FMAOp2.getOperand(0); 10297 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10298 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10299 return SDValue(); 10300 10301 SDValue Vec3 = FMAOp1.getOperand(0); 10302 SDValue Vec4 = FMAOp2.getOperand(0); 10303 SDValue Idx2 = FMAOp1.getOperand(1); 10304 10305 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10306 // Idx1 and Idx2 cannot be the same. 10307 Idx1 == Idx2) 10308 return SDValue(); 10309 10310 if (Vec1 == Vec2 || Vec3 == Vec4) 10311 return SDValue(); 10312 10313 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10314 return SDValue(); 10315 10316 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10317 (Vec1 == Vec4 && Vec2 == Vec3)) { 10318 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10319 DAG.getTargetConstant(0, SL, MVT::i1)); 10320 } 10321 } 10322 return SDValue(); 10323 } 10324 10325 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10326 DAGCombinerInfo &DCI) const { 10327 SelectionDAG &DAG = DCI.DAG; 10328 SDLoc SL(N); 10329 10330 SDValue LHS = N->getOperand(0); 10331 SDValue RHS = N->getOperand(1); 10332 EVT VT = LHS.getValueType(); 10333 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10334 10335 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10336 if (!CRHS) { 10337 CRHS = dyn_cast<ConstantSDNode>(LHS); 10338 if (CRHS) { 10339 std::swap(LHS, RHS); 10340 CC = getSetCCSwappedOperands(CC); 10341 } 10342 } 10343 10344 if (CRHS) { 10345 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10346 isBoolSGPR(LHS.getOperand(0))) { 10347 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10348 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10349 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10350 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10351 if ((CRHS->isAllOnesValue() && 10352 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10353 (CRHS->isNullValue() && 10354 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10355 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10356 DAG.getConstant(-1, SL, MVT::i1)); 10357 if ((CRHS->isAllOnesValue() && 10358 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10359 (CRHS->isNullValue() && 10360 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10361 return LHS.getOperand(0); 10362 } 10363 10364 uint64_t CRHSVal = CRHS->getZExtValue(); 10365 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10366 LHS.getOpcode() == ISD::SELECT && 10367 isa<ConstantSDNode>(LHS.getOperand(1)) && 10368 isa<ConstantSDNode>(LHS.getOperand(2)) && 10369 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10370 isBoolSGPR(LHS.getOperand(0))) { 10371 // Given CT != FT: 10372 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10373 // setcc (select cc, CT, CF), CF, ne => cc 10374 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10375 // setcc (select cc, CT, CF), CT, eq => cc 10376 uint64_t CT = LHS.getConstantOperandVal(1); 10377 uint64_t CF = LHS.getConstantOperandVal(2); 10378 10379 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10380 (CT == CRHSVal && CC == ISD::SETNE)) 10381 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10382 DAG.getConstant(-1, SL, MVT::i1)); 10383 if ((CF == CRHSVal && CC == ISD::SETNE) || 10384 (CT == CRHSVal && CC == ISD::SETEQ)) 10385 return LHS.getOperand(0); 10386 } 10387 } 10388 10389 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10390 VT != MVT::f16)) 10391 return SDValue(); 10392 10393 // Match isinf/isfinite pattern 10394 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10395 // (fcmp one (fabs x), inf) -> (fp_class x, 10396 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10397 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10398 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10399 if (!CRHS) 10400 return SDValue(); 10401 10402 const APFloat &APF = CRHS->getValueAPF(); 10403 if (APF.isInfinity() && !APF.isNegative()) { 10404 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10405 SIInstrFlags::N_INFINITY; 10406 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10407 SIInstrFlags::P_ZERO | 10408 SIInstrFlags::N_NORMAL | 10409 SIInstrFlags::P_NORMAL | 10410 SIInstrFlags::N_SUBNORMAL | 10411 SIInstrFlags::P_SUBNORMAL; 10412 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10413 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10414 DAG.getConstant(Mask, SL, MVT::i32)); 10415 } 10416 } 10417 10418 return SDValue(); 10419 } 10420 10421 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10422 DAGCombinerInfo &DCI) const { 10423 SelectionDAG &DAG = DCI.DAG; 10424 SDLoc SL(N); 10425 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10426 10427 SDValue Src = N->getOperand(0); 10428 SDValue Shift = N->getOperand(0); 10429 10430 // TODO: Extend type shouldn't matter (assuming legal types). 10431 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10432 Shift = Shift.getOperand(0); 10433 10434 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10435 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10436 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10437 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10438 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10439 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10440 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10441 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10442 SDLoc(Shift.getOperand(0)), MVT::i32); 10443 10444 unsigned ShiftOffset = 8 * Offset; 10445 if (Shift.getOpcode() == ISD::SHL) 10446 ShiftOffset -= C->getZExtValue(); 10447 else 10448 ShiftOffset += C->getZExtValue(); 10449 10450 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10451 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10452 MVT::f32, Shift); 10453 } 10454 } 10455 } 10456 10457 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10458 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10459 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10460 // We simplified Src. If this node is not dead, visit it again so it is 10461 // folded properly. 10462 if (N->getOpcode() != ISD::DELETED_NODE) 10463 DCI.AddToWorklist(N); 10464 return SDValue(N, 0); 10465 } 10466 10467 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10468 if (SDValue DemandedSrc = 10469 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10470 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10471 10472 return SDValue(); 10473 } 10474 10475 SDValue SITargetLowering::performClampCombine(SDNode *N, 10476 DAGCombinerInfo &DCI) const { 10477 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10478 if (!CSrc) 10479 return SDValue(); 10480 10481 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10482 const APFloat &F = CSrc->getValueAPF(); 10483 APFloat Zero = APFloat::getZero(F.getSemantics()); 10484 if (F < Zero || 10485 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10486 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10487 } 10488 10489 APFloat One(F.getSemantics(), "1.0"); 10490 if (F > One) 10491 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10492 10493 return SDValue(CSrc, 0); 10494 } 10495 10496 10497 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10498 DAGCombinerInfo &DCI) const { 10499 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10500 return SDValue(); 10501 switch (N->getOpcode()) { 10502 default: 10503 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10504 case ISD::ADD: 10505 return performAddCombine(N, DCI); 10506 case ISD::SUB: 10507 return performSubCombine(N, DCI); 10508 case ISD::ADDCARRY: 10509 case ISD::SUBCARRY: 10510 return performAddCarrySubCarryCombine(N, DCI); 10511 case ISD::FADD: 10512 return performFAddCombine(N, DCI); 10513 case ISD::FSUB: 10514 return performFSubCombine(N, DCI); 10515 case ISD::SETCC: 10516 return performSetCCCombine(N, DCI); 10517 case ISD::FMAXNUM: 10518 case ISD::FMINNUM: 10519 case ISD::FMAXNUM_IEEE: 10520 case ISD::FMINNUM_IEEE: 10521 case ISD::SMAX: 10522 case ISD::SMIN: 10523 case ISD::UMAX: 10524 case ISD::UMIN: 10525 case AMDGPUISD::FMIN_LEGACY: 10526 case AMDGPUISD::FMAX_LEGACY: 10527 return performMinMaxCombine(N, DCI); 10528 case ISD::FMA: 10529 return performFMACombine(N, DCI); 10530 case ISD::LOAD: { 10531 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10532 return Widended; 10533 LLVM_FALLTHROUGH; 10534 } 10535 case ISD::STORE: 10536 case ISD::ATOMIC_LOAD: 10537 case ISD::ATOMIC_STORE: 10538 case ISD::ATOMIC_CMP_SWAP: 10539 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 10540 case ISD::ATOMIC_SWAP: 10541 case ISD::ATOMIC_LOAD_ADD: 10542 case ISD::ATOMIC_LOAD_SUB: 10543 case ISD::ATOMIC_LOAD_AND: 10544 case ISD::ATOMIC_LOAD_OR: 10545 case ISD::ATOMIC_LOAD_XOR: 10546 case ISD::ATOMIC_LOAD_NAND: 10547 case ISD::ATOMIC_LOAD_MIN: 10548 case ISD::ATOMIC_LOAD_MAX: 10549 case ISD::ATOMIC_LOAD_UMIN: 10550 case ISD::ATOMIC_LOAD_UMAX: 10551 case ISD::ATOMIC_LOAD_FADD: 10552 case AMDGPUISD::ATOMIC_INC: 10553 case AMDGPUISD::ATOMIC_DEC: 10554 case AMDGPUISD::ATOMIC_LOAD_FMIN: 10555 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 10556 if (DCI.isBeforeLegalize()) 10557 break; 10558 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 10559 case ISD::AND: 10560 return performAndCombine(N, DCI); 10561 case ISD::OR: 10562 return performOrCombine(N, DCI); 10563 case ISD::XOR: 10564 return performXorCombine(N, DCI); 10565 case ISD::ZERO_EXTEND: 10566 return performZeroExtendCombine(N, DCI); 10567 case ISD::SIGN_EXTEND_INREG: 10568 return performSignExtendInRegCombine(N , DCI); 10569 case AMDGPUISD::FP_CLASS: 10570 return performClassCombine(N, DCI); 10571 case ISD::FCANONICALIZE: 10572 return performFCanonicalizeCombine(N, DCI); 10573 case AMDGPUISD::RCP: 10574 return performRcpCombine(N, DCI); 10575 case AMDGPUISD::FRACT: 10576 case AMDGPUISD::RSQ: 10577 case AMDGPUISD::RCP_LEGACY: 10578 case AMDGPUISD::RCP_IFLAG: 10579 case AMDGPUISD::RSQ_CLAMP: 10580 case AMDGPUISD::LDEXP: { 10581 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10582 SDValue Src = N->getOperand(0); 10583 if (Src.isUndef()) 10584 return Src; 10585 break; 10586 } 10587 case ISD::SINT_TO_FP: 10588 case ISD::UINT_TO_FP: 10589 return performUCharToFloatCombine(N, DCI); 10590 case AMDGPUISD::CVT_F32_UBYTE0: 10591 case AMDGPUISD::CVT_F32_UBYTE1: 10592 case AMDGPUISD::CVT_F32_UBYTE2: 10593 case AMDGPUISD::CVT_F32_UBYTE3: 10594 return performCvtF32UByteNCombine(N, DCI); 10595 case AMDGPUISD::FMED3: 10596 return performFMed3Combine(N, DCI); 10597 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10598 return performCvtPkRTZCombine(N, DCI); 10599 case AMDGPUISD::CLAMP: 10600 return performClampCombine(N, DCI); 10601 case ISD::SCALAR_TO_VECTOR: { 10602 SelectionDAG &DAG = DCI.DAG; 10603 EVT VT = N->getValueType(0); 10604 10605 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10606 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10607 SDLoc SL(N); 10608 SDValue Src = N->getOperand(0); 10609 EVT EltVT = Src.getValueType(); 10610 if (EltVT == MVT::f16) 10611 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10612 10613 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10614 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10615 } 10616 10617 break; 10618 } 10619 case ISD::EXTRACT_VECTOR_ELT: 10620 return performExtractVectorEltCombine(N, DCI); 10621 case ISD::INSERT_VECTOR_ELT: 10622 return performInsertVectorEltCombine(N, DCI); 10623 } 10624 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10625 } 10626 10627 /// Helper function for adjustWritemask 10628 static unsigned SubIdx2Lane(unsigned Idx) { 10629 switch (Idx) { 10630 default: return 0; 10631 case AMDGPU::sub0: return 0; 10632 case AMDGPU::sub1: return 1; 10633 case AMDGPU::sub2: return 2; 10634 case AMDGPU::sub3: return 3; 10635 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10636 } 10637 } 10638 10639 /// Adjust the writemask of MIMG instructions 10640 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10641 SelectionDAG &DAG) const { 10642 unsigned Opcode = Node->getMachineOpcode(); 10643 10644 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10645 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10646 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10647 return Node; // not implemented for D16 10648 10649 SDNode *Users[5] = { nullptr }; 10650 unsigned Lane = 0; 10651 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10652 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10653 unsigned NewDmask = 0; 10654 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10655 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10656 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10657 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10658 unsigned TFCLane = 0; 10659 bool HasChain = Node->getNumValues() > 1; 10660 10661 if (OldDmask == 0) { 10662 // These are folded out, but on the chance it happens don't assert. 10663 return Node; 10664 } 10665 10666 unsigned OldBitsSet = countPopulation(OldDmask); 10667 // Work out which is the TFE/LWE lane if that is enabled. 10668 if (UsesTFC) { 10669 TFCLane = OldBitsSet; 10670 } 10671 10672 // Try to figure out the used register components 10673 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10674 I != E; ++I) { 10675 10676 // Don't look at users of the chain. 10677 if (I.getUse().getResNo() != 0) 10678 continue; 10679 10680 // Abort if we can't understand the usage 10681 if (!I->isMachineOpcode() || 10682 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10683 return Node; 10684 10685 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10686 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10687 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10688 // set, etc. 10689 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10690 10691 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10692 if (UsesTFC && Lane == TFCLane) { 10693 Users[Lane] = *I; 10694 } else { 10695 // Set which texture component corresponds to the lane. 10696 unsigned Comp; 10697 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10698 Comp = countTrailingZeros(Dmask); 10699 Dmask &= ~(1 << Comp); 10700 } 10701 10702 // Abort if we have more than one user per component. 10703 if (Users[Lane]) 10704 return Node; 10705 10706 Users[Lane] = *I; 10707 NewDmask |= 1 << Comp; 10708 } 10709 } 10710 10711 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10712 bool NoChannels = !NewDmask; 10713 if (NoChannels) { 10714 if (!UsesTFC) { 10715 // No uses of the result and not using TFC. Then do nothing. 10716 return Node; 10717 } 10718 // If the original dmask has one channel - then nothing to do 10719 if (OldBitsSet == 1) 10720 return Node; 10721 // Use an arbitrary dmask - required for the instruction to work 10722 NewDmask = 1; 10723 } 10724 // Abort if there's no change 10725 if (NewDmask == OldDmask) 10726 return Node; 10727 10728 unsigned BitsSet = countPopulation(NewDmask); 10729 10730 // Check for TFE or LWE - increase the number of channels by one to account 10731 // for the extra return value 10732 // This will need adjustment for D16 if this is also included in 10733 // adjustWriteMask (this function) but at present D16 are excluded. 10734 unsigned NewChannels = BitsSet + UsesTFC; 10735 10736 int NewOpcode = 10737 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10738 assert(NewOpcode != -1 && 10739 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10740 "failed to find equivalent MIMG op"); 10741 10742 // Adjust the writemask in the node 10743 SmallVector<SDValue, 12> Ops; 10744 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10745 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10746 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10747 10748 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10749 10750 MVT ResultVT = NewChannels == 1 ? 10751 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10752 NewChannels == 5 ? 8 : NewChannels); 10753 SDVTList NewVTList = HasChain ? 10754 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10755 10756 10757 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10758 NewVTList, Ops); 10759 10760 if (HasChain) { 10761 // Update chain. 10762 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10763 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10764 } 10765 10766 if (NewChannels == 1) { 10767 assert(Node->hasNUsesOfValue(1, 0)); 10768 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10769 SDLoc(Node), Users[Lane]->getValueType(0), 10770 SDValue(NewNode, 0)); 10771 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10772 return nullptr; 10773 } 10774 10775 // Update the users of the node with the new indices 10776 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10777 SDNode *User = Users[i]; 10778 if (!User) { 10779 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10780 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10781 if (i || !NoChannels) 10782 continue; 10783 } else { 10784 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10785 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10786 } 10787 10788 switch (Idx) { 10789 default: break; 10790 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10791 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10792 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10793 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10794 } 10795 } 10796 10797 DAG.RemoveDeadNode(Node); 10798 return nullptr; 10799 } 10800 10801 static bool isFrameIndexOp(SDValue Op) { 10802 if (Op.getOpcode() == ISD::AssertZext) 10803 Op = Op.getOperand(0); 10804 10805 return isa<FrameIndexSDNode>(Op); 10806 } 10807 10808 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10809 /// with frame index operands. 10810 /// LLVM assumes that inputs are to these instructions are registers. 10811 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10812 SelectionDAG &DAG) const { 10813 if (Node->getOpcode() == ISD::CopyToReg) { 10814 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10815 SDValue SrcVal = Node->getOperand(2); 10816 10817 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10818 // to try understanding copies to physical registers. 10819 if (SrcVal.getValueType() == MVT::i1 && 10820 Register::isPhysicalRegister(DestReg->getReg())) { 10821 SDLoc SL(Node); 10822 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10823 SDValue VReg = DAG.getRegister( 10824 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10825 10826 SDNode *Glued = Node->getGluedNode(); 10827 SDValue ToVReg 10828 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10829 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10830 SDValue ToResultReg 10831 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10832 VReg, ToVReg.getValue(1)); 10833 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10834 DAG.RemoveDeadNode(Node); 10835 return ToResultReg.getNode(); 10836 } 10837 } 10838 10839 SmallVector<SDValue, 8> Ops; 10840 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10841 if (!isFrameIndexOp(Node->getOperand(i))) { 10842 Ops.push_back(Node->getOperand(i)); 10843 continue; 10844 } 10845 10846 SDLoc DL(Node); 10847 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10848 Node->getOperand(i).getValueType(), 10849 Node->getOperand(i)), 0)); 10850 } 10851 10852 return DAG.UpdateNodeOperands(Node, Ops); 10853 } 10854 10855 /// Fold the instructions after selecting them. 10856 /// Returns null if users were already updated. 10857 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10858 SelectionDAG &DAG) const { 10859 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10860 unsigned Opcode = Node->getMachineOpcode(); 10861 10862 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10863 !TII->isGather4(Opcode)) { 10864 return adjustWritemask(Node, DAG); 10865 } 10866 10867 if (Opcode == AMDGPU::INSERT_SUBREG || 10868 Opcode == AMDGPU::REG_SEQUENCE) { 10869 legalizeTargetIndependentNode(Node, DAG); 10870 return Node; 10871 } 10872 10873 switch (Opcode) { 10874 case AMDGPU::V_DIV_SCALE_F32: 10875 case AMDGPU::V_DIV_SCALE_F64: { 10876 // Satisfy the operand register constraint when one of the inputs is 10877 // undefined. Ordinarily each undef value will have its own implicit_def of 10878 // a vreg, so force these to use a single register. 10879 SDValue Src0 = Node->getOperand(0); 10880 SDValue Src1 = Node->getOperand(1); 10881 SDValue Src2 = Node->getOperand(2); 10882 10883 if ((Src0.isMachineOpcode() && 10884 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10885 (Src0 == Src1 || Src0 == Src2)) 10886 break; 10887 10888 MVT VT = Src0.getValueType().getSimpleVT(); 10889 const TargetRegisterClass *RC = 10890 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10891 10892 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10893 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10894 10895 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10896 UndefReg, Src0, SDValue()); 10897 10898 // src0 must be the same register as src1 or src2, even if the value is 10899 // undefined, so make sure we don't violate this constraint. 10900 if (Src0.isMachineOpcode() && 10901 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10902 if (Src1.isMachineOpcode() && 10903 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10904 Src0 = Src1; 10905 else if (Src2.isMachineOpcode() && 10906 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10907 Src0 = Src2; 10908 else { 10909 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10910 Src0 = UndefReg; 10911 Src1 = UndefReg; 10912 } 10913 } else 10914 break; 10915 10916 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10917 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10918 Ops.push_back(Node->getOperand(I)); 10919 10920 Ops.push_back(ImpDef.getValue(1)); 10921 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10922 } 10923 default: 10924 break; 10925 } 10926 10927 return Node; 10928 } 10929 10930 /// Assign the register class depending on the number of 10931 /// bits set in the writemask 10932 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10933 SDNode *Node) const { 10934 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10935 10936 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10937 10938 if (TII->isVOP3(MI.getOpcode())) { 10939 // Make sure constant bus requirements are respected. 10940 TII->legalizeOperandsVOP3(MRI, MI); 10941 10942 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10943 // This saves a chain-copy of registers and better ballance register 10944 // use between vgpr and agpr as agpr tuples tend to be big. 10945 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10946 unsigned Opc = MI.getOpcode(); 10947 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10948 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10949 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10950 if (I == -1) 10951 break; 10952 MachineOperand &Op = MI.getOperand(I); 10953 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10954 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10955 !Register::isVirtualRegister(Op.getReg()) || 10956 !TRI->isAGPR(MRI, Op.getReg())) 10957 continue; 10958 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10959 if (!Src || !Src->isCopy() || 10960 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10961 continue; 10962 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10963 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10964 // All uses of agpr64 and agpr32 can also accept vgpr except for 10965 // v_accvgpr_read, but we do not produce agpr reads during selection, 10966 // so no use checks are needed. 10967 MRI.setRegClass(Op.getReg(), NewRC); 10968 } 10969 } 10970 10971 return; 10972 } 10973 10974 // Replace unused atomics with the no return version. 10975 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10976 if (NoRetAtomicOp != -1) { 10977 if (!Node->hasAnyUseOfValue(0)) { 10978 MI.setDesc(TII->get(NoRetAtomicOp)); 10979 MI.RemoveOperand(0); 10980 return; 10981 } 10982 10983 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10984 // instruction, because the return type of these instructions is a vec2 of 10985 // the memory type, so it can be tied to the input operand. 10986 // This means these instructions always have a use, so we need to add a 10987 // special case to check if the atomic has only one extract_subreg use, 10988 // which itself has no uses. 10989 if ((Node->hasNUsesOfValue(1, 0) && 10990 Node->use_begin()->isMachineOpcode() && 10991 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10992 !Node->use_begin()->hasAnyUseOfValue(0))) { 10993 Register Def = MI.getOperand(0).getReg(); 10994 10995 // Change this into a noret atomic. 10996 MI.setDesc(TII->get(NoRetAtomicOp)); 10997 MI.RemoveOperand(0); 10998 10999 // If we only remove the def operand from the atomic instruction, the 11000 // extract_subreg will be left with a use of a vreg without a def. 11001 // So we need to insert an implicit_def to avoid machine verifier 11002 // errors. 11003 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11004 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11005 } 11006 return; 11007 } 11008 } 11009 11010 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11011 uint64_t Val) { 11012 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11013 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11014 } 11015 11016 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11017 const SDLoc &DL, 11018 SDValue Ptr) const { 11019 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11020 11021 // Build the half of the subregister with the constants before building the 11022 // full 128-bit register. If we are building multiple resource descriptors, 11023 // this will allow CSEing of the 2-component register. 11024 const SDValue Ops0[] = { 11025 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11026 buildSMovImm32(DAG, DL, 0), 11027 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11028 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11029 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11030 }; 11031 11032 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11033 MVT::v2i32, Ops0), 0); 11034 11035 // Combine the constants and the pointer. 11036 const SDValue Ops1[] = { 11037 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11038 Ptr, 11039 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11040 SubRegHi, 11041 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11042 }; 11043 11044 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11045 } 11046 11047 /// Return a resource descriptor with the 'Add TID' bit enabled 11048 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11049 /// of the resource descriptor) to create an offset, which is added to 11050 /// the resource pointer. 11051 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11052 SDValue Ptr, uint32_t RsrcDword1, 11053 uint64_t RsrcDword2And3) const { 11054 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11055 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11056 if (RsrcDword1) { 11057 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11058 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11059 0); 11060 } 11061 11062 SDValue DataLo = buildSMovImm32(DAG, DL, 11063 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11064 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11065 11066 const SDValue Ops[] = { 11067 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11068 PtrLo, 11069 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11070 PtrHi, 11071 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11072 DataLo, 11073 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11074 DataHi, 11075 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11076 }; 11077 11078 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11079 } 11080 11081 //===----------------------------------------------------------------------===// 11082 // SI Inline Assembly Support 11083 //===----------------------------------------------------------------------===// 11084 11085 std::pair<unsigned, const TargetRegisterClass *> 11086 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11087 StringRef Constraint, 11088 MVT VT) const { 11089 const TargetRegisterClass *RC = nullptr; 11090 if (Constraint.size() == 1) { 11091 const unsigned BitWidth = VT.getSizeInBits(); 11092 switch (Constraint[0]) { 11093 default: 11094 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11095 case 's': 11096 case 'r': 11097 switch (BitWidth) { 11098 case 16: 11099 RC = &AMDGPU::SReg_32RegClass; 11100 break; 11101 case 64: 11102 RC = &AMDGPU::SGPR_64RegClass; 11103 break; 11104 default: 11105 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11106 if (!RC) 11107 return std::make_pair(0U, nullptr); 11108 break; 11109 } 11110 break; 11111 case 'v': 11112 switch (BitWidth) { 11113 case 16: 11114 RC = &AMDGPU::VGPR_32RegClass; 11115 break; 11116 default: 11117 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 11118 if (!RC) 11119 return std::make_pair(0U, nullptr); 11120 break; 11121 } 11122 break; 11123 case 'a': 11124 if (!Subtarget->hasMAIInsts()) 11125 break; 11126 switch (BitWidth) { 11127 case 16: 11128 RC = &AMDGPU::AGPR_32RegClass; 11129 break; 11130 default: 11131 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 11132 if (!RC) 11133 return std::make_pair(0U, nullptr); 11134 break; 11135 } 11136 break; 11137 } 11138 // We actually support i128, i16 and f16 as inline parameters 11139 // even if they are not reported as legal 11140 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11141 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11142 return std::make_pair(0U, RC); 11143 } 11144 11145 if (Constraint.size() > 1) { 11146 if (Constraint[1] == 'v') { 11147 RC = &AMDGPU::VGPR_32RegClass; 11148 } else if (Constraint[1] == 's') { 11149 RC = &AMDGPU::SGPR_32RegClass; 11150 } else if (Constraint[1] == 'a') { 11151 RC = &AMDGPU::AGPR_32RegClass; 11152 } 11153 11154 if (RC) { 11155 uint32_t Idx; 11156 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11157 if (!Failed && Idx < RC->getNumRegs()) 11158 return std::make_pair(RC->getRegister(Idx), RC); 11159 } 11160 } 11161 11162 // FIXME: Returns VS_32 for physical SGPR constraints 11163 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11164 } 11165 11166 static bool isImmConstraint(StringRef Constraint) { 11167 if (Constraint.size() == 1) { 11168 switch (Constraint[0]) { 11169 default: break; 11170 case 'I': 11171 case 'J': 11172 case 'A': 11173 case 'B': 11174 case 'C': 11175 return true; 11176 } 11177 } else if (Constraint == "DA" || 11178 Constraint == "DB") { 11179 return true; 11180 } 11181 return false; 11182 } 11183 11184 SITargetLowering::ConstraintType 11185 SITargetLowering::getConstraintType(StringRef Constraint) const { 11186 if (Constraint.size() == 1) { 11187 switch (Constraint[0]) { 11188 default: break; 11189 case 's': 11190 case 'v': 11191 case 'a': 11192 return C_RegisterClass; 11193 } 11194 } 11195 if (isImmConstraint(Constraint)) { 11196 return C_Other; 11197 } 11198 return TargetLowering::getConstraintType(Constraint); 11199 } 11200 11201 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11202 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11203 Val = Val & maskTrailingOnes<uint64_t>(Size); 11204 } 11205 return Val; 11206 } 11207 11208 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11209 std::string &Constraint, 11210 std::vector<SDValue> &Ops, 11211 SelectionDAG &DAG) const { 11212 if (isImmConstraint(Constraint)) { 11213 uint64_t Val; 11214 if (getAsmOperandConstVal(Op, Val) && 11215 checkAsmConstraintVal(Op, Constraint, Val)) { 11216 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11217 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11218 } 11219 } else { 11220 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11221 } 11222 } 11223 11224 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11225 unsigned Size = Op.getScalarValueSizeInBits(); 11226 if (Size > 64) 11227 return false; 11228 11229 if (Size == 16 && !Subtarget->has16BitInsts()) 11230 return false; 11231 11232 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11233 Val = C->getSExtValue(); 11234 return true; 11235 } 11236 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11237 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11238 return true; 11239 } 11240 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11241 if (Size != 16 || Op.getNumOperands() != 2) 11242 return false; 11243 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11244 return false; 11245 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11246 Val = C->getSExtValue(); 11247 return true; 11248 } 11249 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11250 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11251 return true; 11252 } 11253 } 11254 11255 return false; 11256 } 11257 11258 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11259 const std::string &Constraint, 11260 uint64_t Val) const { 11261 if (Constraint.size() == 1) { 11262 switch (Constraint[0]) { 11263 case 'I': 11264 return AMDGPU::isInlinableIntLiteral(Val); 11265 case 'J': 11266 return isInt<16>(Val); 11267 case 'A': 11268 return checkAsmConstraintValA(Op, Val); 11269 case 'B': 11270 return isInt<32>(Val); 11271 case 'C': 11272 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11273 AMDGPU::isInlinableIntLiteral(Val); 11274 default: 11275 break; 11276 } 11277 } else if (Constraint.size() == 2) { 11278 if (Constraint == "DA") { 11279 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11280 int64_t LoBits = static_cast<int32_t>(Val); 11281 return checkAsmConstraintValA(Op, HiBits, 32) && 11282 checkAsmConstraintValA(Op, LoBits, 32); 11283 } 11284 if (Constraint == "DB") { 11285 return true; 11286 } 11287 } 11288 llvm_unreachable("Invalid asm constraint"); 11289 } 11290 11291 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11292 uint64_t Val, 11293 unsigned MaxSize) const { 11294 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11295 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11296 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11297 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11298 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11299 return true; 11300 } 11301 return false; 11302 } 11303 11304 // Figure out which registers should be reserved for stack access. Only after 11305 // the function is legalized do we know all of the non-spill stack objects or if 11306 // calls are present. 11307 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11308 MachineRegisterInfo &MRI = MF.getRegInfo(); 11309 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11310 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11311 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11312 11313 if (Info->isEntryFunction()) { 11314 // Callable functions have fixed registers used for stack access. 11315 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11316 } 11317 11318 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11319 Info->getStackPtrOffsetReg())); 11320 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11321 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11322 11323 // We need to worry about replacing the default register with itself in case 11324 // of MIR testcases missing the MFI. 11325 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11326 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11327 11328 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11329 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11330 11331 Info->limitOccupancy(MF); 11332 11333 if (ST.isWave32() && !MF.empty()) { 11334 // Add VCC_HI def because many instructions marked as imp-use VCC where 11335 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 11336 // having a use of undef. 11337 11338 const SIInstrInfo *TII = ST.getInstrInfo(); 11339 DebugLoc DL; 11340 11341 MachineBasicBlock &MBB = MF.front(); 11342 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 11343 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 11344 11345 for (auto &MBB : MF) { 11346 for (auto &MI : MBB) { 11347 TII->fixImplicitOperands(MI); 11348 } 11349 } 11350 } 11351 11352 TargetLoweringBase::finalizeLowering(MF); 11353 11354 // Allocate a VGPR for future SGPR Spill if 11355 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11356 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11357 if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill && 11358 !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects()) 11359 Info->reserveVGPRforSGPRSpills(MF); 11360 } 11361 11362 void SITargetLowering::computeKnownBitsForFrameIndex( 11363 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11364 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11365 11366 // Set the high bits to zero based on the maximum allowed scratch size per 11367 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11368 // calculation won't overflow, so assume the sign bit is never set. 11369 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11370 } 11371 11372 Align SITargetLowering::computeKnownAlignForTargetInstr( 11373 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11374 unsigned Depth) const { 11375 const MachineInstr *MI = MRI.getVRegDef(R); 11376 switch (MI->getOpcode()) { 11377 case AMDGPU::G_INTRINSIC: 11378 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11379 // FIXME: Can this move to generic code? What about the case where the call 11380 // site specifies a lower alignment? 11381 Intrinsic::ID IID = MI->getIntrinsicID(); 11382 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11383 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11384 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11385 return *RetAlign; 11386 return Align(1); 11387 } 11388 default: 11389 return Align(1); 11390 } 11391 } 11392 11393 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11394 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11395 const Align CacheLineAlign = Align(64); 11396 11397 // Pre-GFX10 target did not benefit from loop alignment 11398 if (!ML || DisableLoopAlignment || 11399 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11400 getSubtarget()->hasInstFwdPrefetchBug()) 11401 return PrefAlign; 11402 11403 // On GFX10 I$ is 4 x 64 bytes cache lines. 11404 // By default prefetcher keeps one cache line behind and reads two ahead. 11405 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11406 // behind and one ahead. 11407 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11408 // If loop fits 64 bytes it always spans no more than two cache lines and 11409 // does not need an alignment. 11410 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11411 // Else if loop is less or equal 192 bytes we need two lines behind. 11412 11413 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11414 const MachineBasicBlock *Header = ML->getHeader(); 11415 if (Header->getAlignment() != PrefAlign) 11416 return Header->getAlignment(); // Already processed. 11417 11418 unsigned LoopSize = 0; 11419 for (const MachineBasicBlock *MBB : ML->blocks()) { 11420 // If inner loop block is aligned assume in average half of the alignment 11421 // size to be added as nops. 11422 if (MBB != Header) 11423 LoopSize += MBB->getAlignment().value() / 2; 11424 11425 for (const MachineInstr &MI : *MBB) { 11426 LoopSize += TII->getInstSizeInBytes(MI); 11427 if (LoopSize > 192) 11428 return PrefAlign; 11429 } 11430 } 11431 11432 if (LoopSize <= 64) 11433 return PrefAlign; 11434 11435 if (LoopSize <= 128) 11436 return CacheLineAlign; 11437 11438 // If any of parent loops is surrounded by prefetch instructions do not 11439 // insert new for inner loop, which would reset parent's settings. 11440 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11441 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11442 auto I = Exit->getFirstNonDebugInstr(); 11443 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11444 return CacheLineAlign; 11445 } 11446 } 11447 11448 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11449 MachineBasicBlock *Exit = ML->getExitBlock(); 11450 11451 if (Pre && Exit) { 11452 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11453 TII->get(AMDGPU::S_INST_PREFETCH)) 11454 .addImm(1); // prefetch 2 lines behind PC 11455 11456 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11457 TII->get(AMDGPU::S_INST_PREFETCH)) 11458 .addImm(2); // prefetch 1 line behind PC 11459 } 11460 11461 return CacheLineAlign; 11462 } 11463 11464 LLVM_ATTRIBUTE_UNUSED 11465 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11466 assert(N->getOpcode() == ISD::CopyFromReg); 11467 do { 11468 // Follow the chain until we find an INLINEASM node. 11469 N = N->getOperand(0).getNode(); 11470 if (N->getOpcode() == ISD::INLINEASM || 11471 N->getOpcode() == ISD::INLINEASM_BR) 11472 return true; 11473 } while (N->getOpcode() == ISD::CopyFromReg); 11474 return false; 11475 } 11476 11477 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 11478 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 11479 { 11480 switch (N->getOpcode()) { 11481 case ISD::CopyFromReg: 11482 { 11483 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11484 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11485 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11486 Register Reg = R->getReg(); 11487 11488 // FIXME: Why does this need to consider isLiveIn? 11489 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11490 return !TRI->isSGPRReg(MRI, Reg); 11491 11492 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11493 return KDA->isDivergent(V); 11494 11495 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11496 return !TRI->isSGPRReg(MRI, Reg); 11497 } 11498 break; 11499 case ISD::LOAD: { 11500 const LoadSDNode *L = cast<LoadSDNode>(N); 11501 unsigned AS = L->getAddressSpace(); 11502 // A flat load may access private memory. 11503 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11504 } break; 11505 case ISD::CALLSEQ_END: 11506 return true; 11507 break; 11508 case ISD::INTRINSIC_WO_CHAIN: 11509 { 11510 11511 } 11512 return AMDGPU::isIntrinsicSourceOfDivergence( 11513 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11514 case ISD::INTRINSIC_W_CHAIN: 11515 return AMDGPU::isIntrinsicSourceOfDivergence( 11516 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11517 } 11518 return false; 11519 } 11520 11521 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11522 EVT VT) const { 11523 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11524 case MVT::f32: 11525 return hasFP32Denormals(DAG.getMachineFunction()); 11526 case MVT::f64: 11527 case MVT::f16: 11528 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11529 default: 11530 return false; 11531 } 11532 } 11533 11534 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11535 const SelectionDAG &DAG, 11536 bool SNaN, 11537 unsigned Depth) const { 11538 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11539 const MachineFunction &MF = DAG.getMachineFunction(); 11540 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11541 11542 if (Info->getMode().DX10Clamp) 11543 return true; // Clamped to 0. 11544 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11545 } 11546 11547 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11548 SNaN, Depth); 11549 } 11550 11551 TargetLowering::AtomicExpansionKind 11552 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11553 switch (RMW->getOperation()) { 11554 case AtomicRMWInst::FAdd: { 11555 Type *Ty = RMW->getType(); 11556 11557 // We don't have a way to support 16-bit atomics now, so just leave them 11558 // as-is. 11559 if (Ty->isHalfTy()) 11560 return AtomicExpansionKind::None; 11561 11562 if (!Ty->isFloatTy()) 11563 return AtomicExpansionKind::CmpXChg; 11564 11565 // TODO: Do have these for flat. Older targets also had them for buffers. 11566 unsigned AS = RMW->getPointerAddressSpace(); 11567 11568 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11569 return RMW->use_empty() ? AtomicExpansionKind::None : 11570 AtomicExpansionKind::CmpXChg; 11571 } 11572 11573 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11574 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11575 } 11576 default: 11577 break; 11578 } 11579 11580 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11581 } 11582 11583 const TargetRegisterClass * 11584 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11585 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11586 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11587 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11588 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11589 : &AMDGPU::SReg_32RegClass; 11590 if (!TRI->isSGPRClass(RC) && !isDivergent) 11591 return TRI->getEquivalentSGPRClass(RC); 11592 else if (TRI->isSGPRClass(RC) && isDivergent) 11593 return TRI->getEquivalentVGPRClass(RC); 11594 11595 return RC; 11596 } 11597 11598 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11599 // uniform values (as produced by the mask results of control flow intrinsics) 11600 // used outside of divergent blocks. The phi users need to also be treated as 11601 // always uniform. 11602 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11603 unsigned WaveSize) { 11604 // FIXME: We asssume we never cast the mask results of a control flow 11605 // intrinsic. 11606 // Early exit if the type won't be consistent as a compile time hack. 11607 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11608 if (!IT || IT->getBitWidth() != WaveSize) 11609 return false; 11610 11611 if (!isa<Instruction>(V)) 11612 return false; 11613 if (!Visited.insert(V).second) 11614 return false; 11615 bool Result = false; 11616 for (auto U : V->users()) { 11617 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11618 if (V == U->getOperand(1)) { 11619 switch (Intrinsic->getIntrinsicID()) { 11620 default: 11621 Result = false; 11622 break; 11623 case Intrinsic::amdgcn_if_break: 11624 case Intrinsic::amdgcn_if: 11625 case Intrinsic::amdgcn_else: 11626 Result = true; 11627 break; 11628 } 11629 } 11630 if (V == U->getOperand(0)) { 11631 switch (Intrinsic->getIntrinsicID()) { 11632 default: 11633 Result = false; 11634 break; 11635 case Intrinsic::amdgcn_end_cf: 11636 case Intrinsic::amdgcn_loop: 11637 Result = true; 11638 break; 11639 } 11640 } 11641 } else { 11642 Result = hasCFUser(U, Visited, WaveSize); 11643 } 11644 if (Result) 11645 break; 11646 } 11647 return Result; 11648 } 11649 11650 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11651 const Value *V) const { 11652 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11653 if (CI->isInlineAsm()) { 11654 // FIXME: This cannot give a correct answer. This should only trigger in 11655 // the case where inline asm returns mixed SGPR and VGPR results, used 11656 // outside the defining block. We don't have a specific result to 11657 // consider, so this assumes if any value is SGPR, the overall register 11658 // also needs to be SGPR. 11659 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11660 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11661 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11662 for (auto &TC : TargetConstraints) { 11663 if (TC.Type == InlineAsm::isOutput) { 11664 ComputeConstraintToUse(TC, SDValue()); 11665 unsigned AssignedReg; 11666 const TargetRegisterClass *RC; 11667 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11668 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11669 if (RC) { 11670 MachineRegisterInfo &MRI = MF.getRegInfo(); 11671 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11672 return true; 11673 else if (SIRI->isSGPRClass(RC)) 11674 return true; 11675 } 11676 } 11677 } 11678 } 11679 } 11680 SmallPtrSet<const Value *, 16> Visited; 11681 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11682 } 11683