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::FPOWI, MVT::f16, Promote); 453 setOperationAction(ISD::FLOG, MVT::f16, Custom); 454 setOperationAction(ISD::FEXP, MVT::f16, Custom); 455 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 456 } 457 458 if (Subtarget->hasMadMacF32Insts()) 459 setOperationAction(ISD::FMAD, MVT::f32, Legal); 460 461 if (!Subtarget->hasBFI()) { 462 // fcopysign can be done in a single instruction with BFI. 463 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 464 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 465 } 466 467 if (!Subtarget->hasBCNT(32)) 468 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 469 470 if (!Subtarget->hasBCNT(64)) 471 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 472 473 if (Subtarget->hasFFBH()) 474 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 475 476 if (Subtarget->hasFFBL()) 477 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 478 479 // We only really have 32-bit BFE instructions (and 16-bit on VI). 480 // 481 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 482 // effort to match them now. We want this to be false for i64 cases when the 483 // extraction isn't restricted to the upper or lower half. Ideally we would 484 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 485 // span the midpoint are probably relatively rare, so don't worry about them 486 // for now. 487 if (Subtarget->hasBFE()) 488 setHasExtractBitsInsn(true); 489 490 // Clamp modifier on add/sub 491 if (Subtarget->hasIntClamp()) { 492 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 493 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 494 } 495 496 if (Subtarget->hasAddNoCarry()) { 497 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 498 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 499 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 500 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 501 } 502 503 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 504 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 505 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 506 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 507 508 509 // These are really only legal for ieee_mode functions. We should be avoiding 510 // them for functions that don't have ieee_mode enabled, so just say they are 511 // legal. 512 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 513 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 514 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 515 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 516 517 518 if (Subtarget->haveRoundOpsF64()) { 519 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 520 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 521 setOperationAction(ISD::FRINT, MVT::f64, Legal); 522 } else { 523 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 524 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 525 setOperationAction(ISD::FRINT, MVT::f64, Custom); 526 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 527 } 528 529 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 530 531 setOperationAction(ISD::FSIN, MVT::f32, Custom); 532 setOperationAction(ISD::FCOS, MVT::f32, Custom); 533 setOperationAction(ISD::FDIV, MVT::f32, Custom); 534 setOperationAction(ISD::FDIV, MVT::f64, Custom); 535 536 if (Subtarget->has16BitInsts()) { 537 setOperationAction(ISD::Constant, MVT::i16, Legal); 538 539 setOperationAction(ISD::SMIN, MVT::i16, Legal); 540 setOperationAction(ISD::SMAX, MVT::i16, Legal); 541 542 setOperationAction(ISD::UMIN, MVT::i16, Legal); 543 setOperationAction(ISD::UMAX, MVT::i16, Legal); 544 545 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 546 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 547 548 setOperationAction(ISD::ROTR, MVT::i16, Promote); 549 setOperationAction(ISD::ROTL, MVT::i16, Promote); 550 551 setOperationAction(ISD::SDIV, MVT::i16, Promote); 552 setOperationAction(ISD::UDIV, MVT::i16, Promote); 553 setOperationAction(ISD::SREM, MVT::i16, Promote); 554 setOperationAction(ISD::UREM, MVT::i16, Promote); 555 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 556 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 557 558 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 559 560 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 561 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 562 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 563 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 564 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 565 566 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 567 568 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 569 570 setOperationAction(ISD::LOAD, MVT::i16, Custom); 571 572 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 573 574 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 575 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 576 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 577 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 578 579 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 580 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 581 582 // F16 - Constant Actions. 583 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 584 585 // F16 - Load/Store Actions. 586 setOperationAction(ISD::LOAD, MVT::f16, Promote); 587 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 588 setOperationAction(ISD::STORE, MVT::f16, Promote); 589 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 590 591 // F16 - VOP1 Actions. 592 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 593 setOperationAction(ISD::FCOS, MVT::f16, Custom); 594 setOperationAction(ISD::FSIN, MVT::f16, Custom); 595 596 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 597 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 598 599 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 600 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 601 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 602 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 603 setOperationAction(ISD::FROUND, MVT::f16, Custom); 604 605 // F16 - VOP2 Actions. 606 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 607 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 608 609 setOperationAction(ISD::FDIV, MVT::f16, Custom); 610 611 // F16 - VOP3 Actions. 612 setOperationAction(ISD::FMA, MVT::f16, Legal); 613 if (STI.hasMadF16()) 614 setOperationAction(ISD::FMAD, MVT::f16, Legal); 615 616 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 617 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 618 switch (Op) { 619 case ISD::LOAD: 620 case ISD::STORE: 621 case ISD::BUILD_VECTOR: 622 case ISD::BITCAST: 623 case ISD::EXTRACT_VECTOR_ELT: 624 case ISD::INSERT_VECTOR_ELT: 625 case ISD::INSERT_SUBVECTOR: 626 case ISD::EXTRACT_SUBVECTOR: 627 case ISD::SCALAR_TO_VECTOR: 628 break; 629 case ISD::CONCAT_VECTORS: 630 setOperationAction(Op, VT, Custom); 631 break; 632 default: 633 setOperationAction(Op, VT, Expand); 634 break; 635 } 636 } 637 } 638 639 // v_perm_b32 can handle either of these. 640 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 641 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 642 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 643 644 // XXX - Do these do anything? Vector constants turn into build_vector. 645 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 646 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 647 648 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 649 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 650 651 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 652 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 653 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 654 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 655 656 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 657 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 658 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 659 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 660 661 setOperationAction(ISD::AND, MVT::v2i16, Promote); 662 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 663 setOperationAction(ISD::OR, MVT::v2i16, Promote); 664 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 665 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 666 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 667 668 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 669 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 670 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 671 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 672 673 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 674 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 675 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 676 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 677 678 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 679 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 680 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 681 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 682 683 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 684 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 685 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 686 687 if (!Subtarget->hasVOP3PInsts()) { 688 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 689 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 690 } 691 692 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 693 // This isn't really legal, but this avoids the legalizer unrolling it (and 694 // allows matching fneg (fabs x) patterns) 695 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 696 697 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 698 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 699 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 700 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 701 702 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 703 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 704 705 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 706 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 707 } 708 709 if (Subtarget->hasVOP3PInsts()) { 710 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 711 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 712 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 713 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 714 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 715 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 716 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 717 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 718 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 719 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 720 721 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 722 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 723 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 724 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 725 726 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 727 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 728 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 729 730 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 731 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 732 733 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 734 735 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 736 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 737 738 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 739 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 740 741 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 742 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 743 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 744 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 745 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 746 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 747 748 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 749 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 750 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 751 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 752 753 setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom); 754 setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom); 755 setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom); 756 setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom); 757 758 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 759 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 760 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 761 762 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 763 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 764 765 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 766 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 767 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 768 769 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 770 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 771 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 772 } 773 774 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 775 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 776 777 if (Subtarget->has16BitInsts()) { 778 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 779 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 780 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 781 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 782 } else { 783 // Legalization hack. 784 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 785 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 786 787 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 788 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 789 } 790 791 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 792 setOperationAction(ISD::SELECT, VT, Custom); 793 } 794 795 setOperationAction(ISD::SMULO, MVT::i64, Custom); 796 setOperationAction(ISD::UMULO, MVT::i64, Custom); 797 798 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 799 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 800 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 801 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 802 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 803 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 804 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 805 806 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 807 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 808 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 809 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 810 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 811 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 812 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 813 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 814 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 815 816 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 817 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 818 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 819 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 820 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 821 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 822 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 823 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 824 825 setTargetDAGCombine(ISD::ADD); 826 setTargetDAGCombine(ISD::ADDCARRY); 827 setTargetDAGCombine(ISD::SUB); 828 setTargetDAGCombine(ISD::SUBCARRY); 829 setTargetDAGCombine(ISD::FADD); 830 setTargetDAGCombine(ISD::FSUB); 831 setTargetDAGCombine(ISD::FMINNUM); 832 setTargetDAGCombine(ISD::FMAXNUM); 833 setTargetDAGCombine(ISD::FMINNUM_IEEE); 834 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 835 setTargetDAGCombine(ISD::FMA); 836 setTargetDAGCombine(ISD::SMIN); 837 setTargetDAGCombine(ISD::SMAX); 838 setTargetDAGCombine(ISD::UMIN); 839 setTargetDAGCombine(ISD::UMAX); 840 setTargetDAGCombine(ISD::SETCC); 841 setTargetDAGCombine(ISD::AND); 842 setTargetDAGCombine(ISD::OR); 843 setTargetDAGCombine(ISD::XOR); 844 setTargetDAGCombine(ISD::SINT_TO_FP); 845 setTargetDAGCombine(ISD::UINT_TO_FP); 846 setTargetDAGCombine(ISD::FCANONICALIZE); 847 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 848 setTargetDAGCombine(ISD::ZERO_EXTEND); 849 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 850 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 851 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 852 853 // All memory operations. Some folding on the pointer operand is done to help 854 // matching the constant offsets in the addressing modes. 855 setTargetDAGCombine(ISD::LOAD); 856 setTargetDAGCombine(ISD::STORE); 857 setTargetDAGCombine(ISD::ATOMIC_LOAD); 858 setTargetDAGCombine(ISD::ATOMIC_STORE); 859 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 860 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 861 setTargetDAGCombine(ISD::ATOMIC_SWAP); 862 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 863 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 864 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 865 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 866 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 867 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 868 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 869 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 870 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 871 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 872 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 873 setTargetDAGCombine(ISD::INTRINSIC_VOID); 874 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 875 876 // FIXME: In other contexts we pretend this is a per-function property. 877 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 878 879 setSchedulingPreference(Sched::RegPressure); 880 } 881 882 const GCNSubtarget *SITargetLowering::getSubtarget() const { 883 return Subtarget; 884 } 885 886 //===----------------------------------------------------------------------===// 887 // TargetLowering queries 888 //===----------------------------------------------------------------------===// 889 890 // v_mad_mix* support a conversion from f16 to f32. 891 // 892 // There is only one special case when denormals are enabled we don't currently, 893 // where this is OK to use. 894 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 895 EVT DestVT, EVT SrcVT) const { 896 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 897 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 898 DestVT.getScalarType() == MVT::f32 && 899 SrcVT.getScalarType() == MVT::f16 && 900 // TODO: This probably only requires no input flushing? 901 !hasFP32Denormals(DAG.getMachineFunction()); 902 } 903 904 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 905 // SI has some legal vector types, but no legal vector operations. Say no 906 // shuffles are legal in order to prefer scalarizing some vector operations. 907 return false; 908 } 909 910 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 911 CallingConv::ID CC, 912 EVT VT) const { 913 if (CC == CallingConv::AMDGPU_KERNEL) 914 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 915 916 if (VT.isVector()) { 917 EVT ScalarVT = VT.getScalarType(); 918 unsigned Size = ScalarVT.getSizeInBits(); 919 if (Size == 32) 920 return ScalarVT.getSimpleVT(); 921 922 if (Size > 32) 923 return MVT::i32; 924 925 if (Size == 16 && Subtarget->has16BitInsts()) 926 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 927 } else if (VT.getSizeInBits() > 32) 928 return MVT::i32; 929 930 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 931 } 932 933 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 934 CallingConv::ID CC, 935 EVT VT) const { 936 if (CC == CallingConv::AMDGPU_KERNEL) 937 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 938 939 if (VT.isVector()) { 940 unsigned NumElts = VT.getVectorNumElements(); 941 EVT ScalarVT = VT.getScalarType(); 942 unsigned Size = ScalarVT.getSizeInBits(); 943 944 if (Size == 32) 945 return NumElts; 946 947 if (Size > 32) 948 return NumElts * ((Size + 31) / 32); 949 950 if (Size == 16 && Subtarget->has16BitInsts()) 951 return (NumElts + 1) / 2; 952 } else if (VT.getSizeInBits() > 32) 953 return (VT.getSizeInBits() + 31) / 32; 954 955 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 956 } 957 958 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 959 LLVMContext &Context, CallingConv::ID CC, 960 EVT VT, EVT &IntermediateVT, 961 unsigned &NumIntermediates, MVT &RegisterVT) const { 962 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 963 unsigned NumElts = VT.getVectorNumElements(); 964 EVT ScalarVT = VT.getScalarType(); 965 unsigned Size = ScalarVT.getSizeInBits(); 966 if (Size == 32) { 967 RegisterVT = ScalarVT.getSimpleVT(); 968 IntermediateVT = RegisterVT; 969 NumIntermediates = NumElts; 970 return NumIntermediates; 971 } 972 973 if (Size > 32) { 974 RegisterVT = MVT::i32; 975 IntermediateVT = RegisterVT; 976 NumIntermediates = NumElts * ((Size + 31) / 32); 977 return NumIntermediates; 978 } 979 980 // FIXME: We should fix the ABI to be the same on targets without 16-bit 981 // support, but unless we can properly handle 3-vectors, it will be still be 982 // inconsistent. 983 if (Size == 16 && Subtarget->has16BitInsts()) { 984 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 985 IntermediateVT = RegisterVT; 986 NumIntermediates = (NumElts + 1) / 2; 987 return NumIntermediates; 988 } 989 } 990 991 return TargetLowering::getVectorTypeBreakdownForCallingConv( 992 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 993 } 994 995 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 996 assert(DMaskLanes != 0); 997 998 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 999 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1000 return EVT::getVectorVT(Ty->getContext(), 1001 EVT::getEVT(VT->getElementType()), 1002 NumElts); 1003 } 1004 1005 return EVT::getEVT(Ty); 1006 } 1007 1008 // Peek through TFE struct returns to only use the data size. 1009 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1010 auto *ST = dyn_cast<StructType>(Ty); 1011 if (!ST) 1012 return memVTFromImageData(Ty, DMaskLanes); 1013 1014 // Some intrinsics return an aggregate type - special case to work out the 1015 // correct memVT. 1016 // 1017 // Only limited forms of aggregate type currently expected. 1018 if (ST->getNumContainedTypes() != 2 || 1019 !ST->getContainedType(1)->isIntegerTy(32)) 1020 return EVT(); 1021 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1022 } 1023 1024 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1025 const CallInst &CI, 1026 MachineFunction &MF, 1027 unsigned IntrID) const { 1028 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1029 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1030 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1031 (Intrinsic::ID)IntrID); 1032 if (Attr.hasFnAttribute(Attribute::ReadNone)) 1033 return false; 1034 1035 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1036 1037 if (RsrcIntr->IsImage) { 1038 Info.ptrVal = MFI->getImagePSV( 1039 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1040 CI.getArgOperand(RsrcIntr->RsrcArg)); 1041 Info.align.reset(); 1042 } else { 1043 Info.ptrVal = MFI->getBufferPSV( 1044 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1045 CI.getArgOperand(RsrcIntr->RsrcArg)); 1046 } 1047 1048 Info.flags = MachineMemOperand::MODereferenceable; 1049 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 1050 unsigned DMaskLanes = 4; 1051 1052 if (RsrcIntr->IsImage) { 1053 const AMDGPU::ImageDimIntrinsicInfo *Intr 1054 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1055 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1056 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1057 1058 if (!BaseOpcode->Gather4) { 1059 // If this isn't a gather, we may have excess loaded elements in the 1060 // IR type. Check the dmask for the real number of elements loaded. 1061 unsigned DMask 1062 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1063 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1064 } 1065 1066 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1067 } else 1068 Info.memVT = EVT::getEVT(CI.getType()); 1069 1070 // FIXME: What does alignment mean for an image? 1071 Info.opc = ISD::INTRINSIC_W_CHAIN; 1072 Info.flags |= MachineMemOperand::MOLoad; 1073 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1074 Info.opc = ISD::INTRINSIC_VOID; 1075 1076 Type *DataTy = CI.getArgOperand(0)->getType(); 1077 if (RsrcIntr->IsImage) { 1078 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1079 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1080 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1081 } else 1082 Info.memVT = EVT::getEVT(DataTy); 1083 1084 Info.flags |= MachineMemOperand::MOStore; 1085 } else { 1086 // Atomic 1087 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1088 ISD::INTRINSIC_W_CHAIN; 1089 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1090 Info.flags = MachineMemOperand::MOLoad | 1091 MachineMemOperand::MOStore | 1092 MachineMemOperand::MODereferenceable; 1093 1094 // XXX - Should this be volatile without known ordering? 1095 Info.flags |= MachineMemOperand::MOVolatile; 1096 } 1097 return true; 1098 } 1099 1100 switch (IntrID) { 1101 case Intrinsic::amdgcn_atomic_inc: 1102 case Intrinsic::amdgcn_atomic_dec: 1103 case Intrinsic::amdgcn_ds_ordered_add: 1104 case Intrinsic::amdgcn_ds_ordered_swap: 1105 case Intrinsic::amdgcn_ds_fadd: 1106 case Intrinsic::amdgcn_ds_fmin: 1107 case Intrinsic::amdgcn_ds_fmax: { 1108 Info.opc = ISD::INTRINSIC_W_CHAIN; 1109 Info.memVT = MVT::getVT(CI.getType()); 1110 Info.ptrVal = CI.getOperand(0); 1111 Info.align.reset(); 1112 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1113 1114 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1115 if (!Vol->isZero()) 1116 Info.flags |= MachineMemOperand::MOVolatile; 1117 1118 return true; 1119 } 1120 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1121 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1122 1123 Info.opc = ISD::INTRINSIC_VOID; 1124 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1125 Info.ptrVal = MFI->getBufferPSV( 1126 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1127 CI.getArgOperand(1)); 1128 Info.align.reset(); 1129 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1130 1131 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1132 if (!Vol || !Vol->isZero()) 1133 Info.flags |= MachineMemOperand::MOVolatile; 1134 1135 return true; 1136 } 1137 case Intrinsic::amdgcn_global_atomic_fadd: { 1138 Info.opc = ISD::INTRINSIC_VOID; 1139 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 1140 ->getPointerElementType()); 1141 Info.ptrVal = CI.getOperand(0); 1142 Info.align.reset(); 1143 1144 // FIXME: Should report an atomic ordering here. 1145 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1146 1147 return true; 1148 } 1149 case Intrinsic::amdgcn_ds_append: 1150 case Intrinsic::amdgcn_ds_consume: { 1151 Info.opc = ISD::INTRINSIC_W_CHAIN; 1152 Info.memVT = MVT::getVT(CI.getType()); 1153 Info.ptrVal = CI.getOperand(0); 1154 Info.align.reset(); 1155 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1156 1157 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1158 if (!Vol->isZero()) 1159 Info.flags |= MachineMemOperand::MOVolatile; 1160 1161 return true; 1162 } 1163 case Intrinsic::amdgcn_global_atomic_csub: { 1164 Info.opc = ISD::INTRINSIC_W_CHAIN; 1165 Info.memVT = MVT::getVT(CI.getType()); 1166 Info.ptrVal = CI.getOperand(0); 1167 Info.align.reset(); 1168 Info.flags = MachineMemOperand::MOLoad | 1169 MachineMemOperand::MOStore | 1170 MachineMemOperand::MOVolatile; 1171 return true; 1172 } 1173 case Intrinsic::amdgcn_ds_gws_init: 1174 case Intrinsic::amdgcn_ds_gws_barrier: 1175 case Intrinsic::amdgcn_ds_gws_sema_v: 1176 case Intrinsic::amdgcn_ds_gws_sema_br: 1177 case Intrinsic::amdgcn_ds_gws_sema_p: 1178 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1179 Info.opc = ISD::INTRINSIC_VOID; 1180 1181 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1182 Info.ptrVal = 1183 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1184 1185 // This is an abstract access, but we need to specify a type and size. 1186 Info.memVT = MVT::i32; 1187 Info.size = 4; 1188 Info.align = Align(4); 1189 1190 Info.flags = MachineMemOperand::MOStore; 1191 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1192 Info.flags = MachineMemOperand::MOLoad; 1193 return true; 1194 } 1195 default: 1196 return false; 1197 } 1198 } 1199 1200 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1201 SmallVectorImpl<Value*> &Ops, 1202 Type *&AccessTy) const { 1203 switch (II->getIntrinsicID()) { 1204 case Intrinsic::amdgcn_atomic_inc: 1205 case Intrinsic::amdgcn_atomic_dec: 1206 case Intrinsic::amdgcn_ds_ordered_add: 1207 case Intrinsic::amdgcn_ds_ordered_swap: 1208 case Intrinsic::amdgcn_ds_append: 1209 case Intrinsic::amdgcn_ds_consume: 1210 case Intrinsic::amdgcn_ds_fadd: 1211 case Intrinsic::amdgcn_ds_fmin: 1212 case Intrinsic::amdgcn_ds_fmax: 1213 case Intrinsic::amdgcn_global_atomic_fadd: 1214 case Intrinsic::amdgcn_global_atomic_csub: { 1215 Value *Ptr = II->getArgOperand(0); 1216 AccessTy = II->getType(); 1217 Ops.push_back(Ptr); 1218 return true; 1219 } 1220 default: 1221 return false; 1222 } 1223 } 1224 1225 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1226 if (!Subtarget->hasFlatInstOffsets()) { 1227 // Flat instructions do not have offsets, and only have the register 1228 // address. 1229 return AM.BaseOffs == 0 && AM.Scale == 0; 1230 } 1231 1232 return AM.Scale == 0 && 1233 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1234 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1235 /*Signed=*/false)); 1236 } 1237 1238 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1239 if (Subtarget->hasFlatGlobalInsts()) 1240 return AM.Scale == 0 && 1241 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1242 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1243 /*Signed=*/true)); 1244 1245 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1246 // Assume the we will use FLAT for all global memory accesses 1247 // on VI. 1248 // FIXME: This assumption is currently wrong. On VI we still use 1249 // MUBUF instructions for the r + i addressing mode. As currently 1250 // implemented, the MUBUF instructions only work on buffer < 4GB. 1251 // It may be possible to support > 4GB buffers with MUBUF instructions, 1252 // by setting the stride value in the resource descriptor which would 1253 // increase the size limit to (stride * 4GB). However, this is risky, 1254 // because it has never been validated. 1255 return isLegalFlatAddressingMode(AM); 1256 } 1257 1258 return isLegalMUBUFAddressingMode(AM); 1259 } 1260 1261 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1262 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1263 // additionally can do r + r + i with addr64. 32-bit has more addressing 1264 // mode options. Depending on the resource constant, it can also do 1265 // (i64 r0) + (i32 r1) * (i14 i). 1266 // 1267 // Private arrays end up using a scratch buffer most of the time, so also 1268 // assume those use MUBUF instructions. Scratch loads / stores are currently 1269 // implemented as mubuf instructions with offen bit set, so slightly 1270 // different than the normal addr64. 1271 if (!isUInt<12>(AM.BaseOffs)) 1272 return false; 1273 1274 // FIXME: Since we can split immediate into soffset and immediate offset, 1275 // would it make sense to allow any immediate? 1276 1277 switch (AM.Scale) { 1278 case 0: // r + i or just i, depending on HasBaseReg. 1279 return true; 1280 case 1: 1281 return true; // We have r + r or r + i. 1282 case 2: 1283 if (AM.HasBaseReg) { 1284 // Reject 2 * r + r. 1285 return false; 1286 } 1287 1288 // Allow 2 * r as r + r 1289 // Or 2 * r + i is allowed as r + r + i. 1290 return true; 1291 default: // Don't allow n * r 1292 return false; 1293 } 1294 } 1295 1296 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1297 const AddrMode &AM, Type *Ty, 1298 unsigned AS, Instruction *I) const { 1299 // No global is ever allowed as a base. 1300 if (AM.BaseGV) 1301 return false; 1302 1303 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1304 return isLegalGlobalAddressingMode(AM); 1305 1306 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1307 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1308 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1309 // If the offset isn't a multiple of 4, it probably isn't going to be 1310 // correctly aligned. 1311 // FIXME: Can we get the real alignment here? 1312 if (AM.BaseOffs % 4 != 0) 1313 return isLegalMUBUFAddressingMode(AM); 1314 1315 // There are no SMRD extloads, so if we have to do a small type access we 1316 // will use a MUBUF load. 1317 // FIXME?: We also need to do this if unaligned, but we don't know the 1318 // alignment here. 1319 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1320 return isLegalGlobalAddressingMode(AM); 1321 1322 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1323 // SMRD instructions have an 8-bit, dword offset on SI. 1324 if (!isUInt<8>(AM.BaseOffs / 4)) 1325 return false; 1326 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1327 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1328 // in 8-bits, it can use a smaller encoding. 1329 if (!isUInt<32>(AM.BaseOffs / 4)) 1330 return false; 1331 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1332 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1333 if (!isUInt<20>(AM.BaseOffs)) 1334 return false; 1335 } else 1336 llvm_unreachable("unhandled generation"); 1337 1338 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1339 return true; 1340 1341 if (AM.Scale == 1 && AM.HasBaseReg) 1342 return true; 1343 1344 return false; 1345 1346 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1347 return isLegalMUBUFAddressingMode(AM); 1348 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1349 AS == AMDGPUAS::REGION_ADDRESS) { 1350 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1351 // field. 1352 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1353 // an 8-bit dword offset but we don't know the alignment here. 1354 if (!isUInt<16>(AM.BaseOffs)) 1355 return false; 1356 1357 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1358 return true; 1359 1360 if (AM.Scale == 1 && AM.HasBaseReg) 1361 return true; 1362 1363 return false; 1364 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1365 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1366 // For an unknown address space, this usually means that this is for some 1367 // reason being used for pure arithmetic, and not based on some addressing 1368 // computation. We don't have instructions that compute pointers with any 1369 // addressing modes, so treat them as having no offset like flat 1370 // instructions. 1371 return isLegalFlatAddressingMode(AM); 1372 } 1373 1374 // Assume a user alias of global for unknown address spaces. 1375 return isLegalGlobalAddressingMode(AM); 1376 } 1377 1378 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1379 const SelectionDAG &DAG) const { 1380 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1381 return (MemVT.getSizeInBits() <= 4 * 32); 1382 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1383 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1384 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1385 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1386 return (MemVT.getSizeInBits() <= 2 * 32); 1387 } 1388 return true; 1389 } 1390 1391 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1392 unsigned Size, unsigned AddrSpace, Align Alignment, 1393 MachineMemOperand::Flags Flags, bool *IsFast) const { 1394 if (IsFast) 1395 *IsFast = false; 1396 1397 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1398 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1399 // Check if alignment requirements for ds_read/write instructions are 1400 // disabled. 1401 if (Subtarget->hasUnalignedDSAccessEnabled()) { 1402 if (IsFast) 1403 *IsFast = true; 1404 return true; 1405 } 1406 1407 if (Size == 64) { 1408 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1409 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1410 // with adjacent offsets. 1411 bool AlignedBy4 = Alignment >= Align(4); 1412 if (IsFast) 1413 *IsFast = AlignedBy4; 1414 1415 return AlignedBy4; 1416 } 1417 if (Size == 96) { 1418 // ds_read/write_b96 require 16-byte alignment on gfx8 and older. 1419 bool Aligned = 1420 Alignment >= Align(Subtarget->hasUnalignedDSAccess() ? 4 : 16); 1421 if (IsFast) 1422 *IsFast = Aligned; 1423 1424 return Aligned; 1425 } 1426 if (Size == 128) { 1427 // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we 1428 // can do a 8 byte aligned, 16 byte access in a single operation using 1429 // ds_read2/write2_b64. 1430 bool Aligned = 1431 Alignment >= Align(Subtarget->hasUnalignedDSAccess() ? 4 : 8); 1432 if (IsFast) 1433 *IsFast = Aligned; 1434 1435 return Aligned; 1436 } 1437 } 1438 1439 // FIXME: We have to be conservative here and assume that flat operations 1440 // will access scratch. If we had access to the IR function, then we 1441 // could determine if any private memory was used in the function. 1442 if (!Subtarget->hasUnalignedScratchAccess() && 1443 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1444 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1445 bool AlignedBy4 = Alignment >= Align(4); 1446 if (IsFast) 1447 *IsFast = AlignedBy4; 1448 1449 return AlignedBy4; 1450 } 1451 1452 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1453 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1454 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1455 // If we have an uniform constant load, it still requires using a slow 1456 // buffer instruction if unaligned. 1457 if (IsFast) { 1458 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1459 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1460 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1461 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1462 Alignment >= Align(4) : Alignment != Align(2); 1463 } 1464 1465 return true; 1466 } 1467 1468 // Smaller than dword value must be aligned. 1469 if (Size < 32) 1470 return false; 1471 1472 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1473 // byte-address are ignored, thus forcing Dword alignment. 1474 // This applies to private, global, and constant memory. 1475 if (IsFast) 1476 *IsFast = true; 1477 1478 return Size >= 32 && Alignment >= Align(4); 1479 } 1480 1481 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1482 EVT VT, unsigned AddrSpace, unsigned Alignment, 1483 MachineMemOperand::Flags Flags, bool *IsFast) const { 1484 if (IsFast) 1485 *IsFast = false; 1486 1487 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1488 // which isn't a simple VT. 1489 // Until MVT is extended to handle this, simply check for the size and 1490 // rely on the condition below: allow accesses if the size is a multiple of 4. 1491 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1492 VT.getStoreSize() > 16)) { 1493 return false; 1494 } 1495 1496 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1497 Align(Alignment), Flags, IsFast); 1498 } 1499 1500 EVT SITargetLowering::getOptimalMemOpType( 1501 const MemOp &Op, const AttributeList &FuncAttributes) const { 1502 // FIXME: Should account for address space here. 1503 1504 // The default fallback uses the private pointer size as a guess for a type to 1505 // use. Make sure we switch these to 64-bit accesses. 1506 1507 if (Op.size() >= 16 && 1508 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1509 return MVT::v4i32; 1510 1511 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1512 return MVT::v2i32; 1513 1514 // Use the default. 1515 return MVT::Other; 1516 } 1517 1518 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1519 const MemSDNode *MemNode = cast<MemSDNode>(N); 1520 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1521 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1522 return I && I->getMetadata("amdgpu.noclobber"); 1523 } 1524 1525 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1526 unsigned DestAS) const { 1527 // Flat -> private/local is a simple truncate. 1528 // Flat -> global is no-op 1529 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1530 return true; 1531 1532 const GCNTargetMachine &TM = 1533 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1534 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1535 } 1536 1537 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1538 const MemSDNode *MemNode = cast<MemSDNode>(N); 1539 1540 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1541 } 1542 1543 TargetLoweringBase::LegalizeTypeAction 1544 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1545 int NumElts = VT.getVectorNumElements(); 1546 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1547 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1548 return TargetLoweringBase::getPreferredVectorAction(VT); 1549 } 1550 1551 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1552 Type *Ty) const { 1553 // FIXME: Could be smarter if called for vector constants. 1554 return true; 1555 } 1556 1557 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1558 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1559 switch (Op) { 1560 case ISD::LOAD: 1561 case ISD::STORE: 1562 1563 // These operations are done with 32-bit instructions anyway. 1564 case ISD::AND: 1565 case ISD::OR: 1566 case ISD::XOR: 1567 case ISD::SELECT: 1568 // TODO: Extensions? 1569 return true; 1570 default: 1571 return false; 1572 } 1573 } 1574 1575 // SimplifySetCC uses this function to determine whether or not it should 1576 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1577 if (VT == MVT::i1 && Op == ISD::SETCC) 1578 return false; 1579 1580 return TargetLowering::isTypeDesirableForOp(Op, VT); 1581 } 1582 1583 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1584 const SDLoc &SL, 1585 SDValue Chain, 1586 uint64_t Offset) const { 1587 const DataLayout &DL = DAG.getDataLayout(); 1588 MachineFunction &MF = DAG.getMachineFunction(); 1589 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1590 1591 const ArgDescriptor *InputPtrReg; 1592 const TargetRegisterClass *RC; 1593 LLT ArgTy; 1594 1595 std::tie(InputPtrReg, RC, ArgTy) = 1596 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1597 1598 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1599 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1600 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1601 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1602 1603 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1604 } 1605 1606 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1607 const SDLoc &SL) const { 1608 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1609 FIRST_IMPLICIT); 1610 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1611 } 1612 1613 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1614 const SDLoc &SL, SDValue Val, 1615 bool Signed, 1616 const ISD::InputArg *Arg) const { 1617 // First, if it is a widened vector, narrow it. 1618 if (VT.isVector() && 1619 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1620 EVT NarrowedVT = 1621 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1622 VT.getVectorNumElements()); 1623 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1624 DAG.getConstant(0, SL, MVT::i32)); 1625 } 1626 1627 // Then convert the vector elements or scalar value. 1628 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1629 VT.bitsLT(MemVT)) { 1630 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1631 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1632 } 1633 1634 if (MemVT.isFloatingPoint()) 1635 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1636 else if (Signed) 1637 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1638 else 1639 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1640 1641 return Val; 1642 } 1643 1644 SDValue SITargetLowering::lowerKernargMemParameter( 1645 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1646 uint64_t Offset, Align Alignment, bool Signed, 1647 const ISD::InputArg *Arg) const { 1648 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1649 1650 // Try to avoid using an extload by loading earlier than the argument address, 1651 // and extracting the relevant bits. The load should hopefully be merged with 1652 // the previous argument. 1653 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1654 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1655 int64_t AlignDownOffset = alignDown(Offset, 4); 1656 int64_t OffsetDiff = Offset - AlignDownOffset; 1657 1658 EVT IntVT = MemVT.changeTypeToInteger(); 1659 1660 // TODO: If we passed in the base kernel offset we could have a better 1661 // alignment than 4, but we don't really need it. 1662 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1663 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1664 MachineMemOperand::MODereferenceable | 1665 MachineMemOperand::MOInvariant); 1666 1667 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1668 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1669 1670 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1671 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1672 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1673 1674 1675 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1676 } 1677 1678 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1679 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1680 MachineMemOperand::MODereferenceable | 1681 MachineMemOperand::MOInvariant); 1682 1683 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1684 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1685 } 1686 1687 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1688 const SDLoc &SL, SDValue Chain, 1689 const ISD::InputArg &Arg) const { 1690 MachineFunction &MF = DAG.getMachineFunction(); 1691 MachineFrameInfo &MFI = MF.getFrameInfo(); 1692 1693 if (Arg.Flags.isByVal()) { 1694 unsigned Size = Arg.Flags.getByValSize(); 1695 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1696 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1697 } 1698 1699 unsigned ArgOffset = VA.getLocMemOffset(); 1700 unsigned ArgSize = VA.getValVT().getStoreSize(); 1701 1702 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1703 1704 // Create load nodes to retrieve arguments from the stack. 1705 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1706 SDValue ArgValue; 1707 1708 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1709 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1710 MVT MemVT = VA.getValVT(); 1711 1712 switch (VA.getLocInfo()) { 1713 default: 1714 break; 1715 case CCValAssign::BCvt: 1716 MemVT = VA.getLocVT(); 1717 break; 1718 case CCValAssign::SExt: 1719 ExtType = ISD::SEXTLOAD; 1720 break; 1721 case CCValAssign::ZExt: 1722 ExtType = ISD::ZEXTLOAD; 1723 break; 1724 case CCValAssign::AExt: 1725 ExtType = ISD::EXTLOAD; 1726 break; 1727 } 1728 1729 ArgValue = DAG.getExtLoad( 1730 ExtType, SL, VA.getLocVT(), Chain, FIN, 1731 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1732 MemVT); 1733 return ArgValue; 1734 } 1735 1736 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1737 const SIMachineFunctionInfo &MFI, 1738 EVT VT, 1739 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1740 const ArgDescriptor *Reg; 1741 const TargetRegisterClass *RC; 1742 LLT Ty; 1743 1744 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1745 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1746 } 1747 1748 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1749 CallingConv::ID CallConv, 1750 ArrayRef<ISD::InputArg> Ins, 1751 BitVector &Skipped, 1752 FunctionType *FType, 1753 SIMachineFunctionInfo *Info) { 1754 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1755 const ISD::InputArg *Arg = &Ins[I]; 1756 1757 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1758 "vector type argument should have been split"); 1759 1760 // First check if it's a PS input addr. 1761 if (CallConv == CallingConv::AMDGPU_PS && 1762 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1763 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1764 1765 // Inconveniently only the first part of the split is marked as isSplit, 1766 // so skip to the end. We only want to increment PSInputNum once for the 1767 // entire split argument. 1768 if (Arg->Flags.isSplit()) { 1769 while (!Arg->Flags.isSplitEnd()) { 1770 assert((!Arg->VT.isVector() || 1771 Arg->VT.getScalarSizeInBits() == 16) && 1772 "unexpected vector split in ps argument type"); 1773 if (!SkipArg) 1774 Splits.push_back(*Arg); 1775 Arg = &Ins[++I]; 1776 } 1777 } 1778 1779 if (SkipArg) { 1780 // We can safely skip PS inputs. 1781 Skipped.set(Arg->getOrigArgIndex()); 1782 ++PSInputNum; 1783 continue; 1784 } 1785 1786 Info->markPSInputAllocated(PSInputNum); 1787 if (Arg->Used) 1788 Info->markPSInputEnabled(PSInputNum); 1789 1790 ++PSInputNum; 1791 } 1792 1793 Splits.push_back(*Arg); 1794 } 1795 } 1796 1797 // Allocate special inputs passed in VGPRs. 1798 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1799 MachineFunction &MF, 1800 const SIRegisterInfo &TRI, 1801 SIMachineFunctionInfo &Info) const { 1802 const LLT S32 = LLT::scalar(32); 1803 MachineRegisterInfo &MRI = MF.getRegInfo(); 1804 1805 if (Info.hasWorkItemIDX()) { 1806 Register Reg = AMDGPU::VGPR0; 1807 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1808 1809 CCInfo.AllocateReg(Reg); 1810 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1811 } 1812 1813 if (Info.hasWorkItemIDY()) { 1814 Register Reg = AMDGPU::VGPR1; 1815 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1816 1817 CCInfo.AllocateReg(Reg); 1818 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1819 } 1820 1821 if (Info.hasWorkItemIDZ()) { 1822 Register Reg = AMDGPU::VGPR2; 1823 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1824 1825 CCInfo.AllocateReg(Reg); 1826 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1827 } 1828 } 1829 1830 // Try to allocate a VGPR at the end of the argument list, or if no argument 1831 // VGPRs are left allocating a stack slot. 1832 // If \p Mask is is given it indicates bitfield position in the register. 1833 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1834 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1835 ArgDescriptor Arg = ArgDescriptor()) { 1836 if (Arg.isSet()) 1837 return ArgDescriptor::createArg(Arg, Mask); 1838 1839 ArrayRef<MCPhysReg> ArgVGPRs 1840 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1841 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1842 if (RegIdx == ArgVGPRs.size()) { 1843 // Spill to stack required. 1844 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1845 1846 return ArgDescriptor::createStack(Offset, Mask); 1847 } 1848 1849 unsigned Reg = ArgVGPRs[RegIdx]; 1850 Reg = CCInfo.AllocateReg(Reg); 1851 assert(Reg != AMDGPU::NoRegister); 1852 1853 MachineFunction &MF = CCInfo.getMachineFunction(); 1854 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1855 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1856 return ArgDescriptor::createRegister(Reg, Mask); 1857 } 1858 1859 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1860 const TargetRegisterClass *RC, 1861 unsigned NumArgRegs) { 1862 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1863 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1864 if (RegIdx == ArgSGPRs.size()) 1865 report_fatal_error("ran out of SGPRs for arguments"); 1866 1867 unsigned Reg = ArgSGPRs[RegIdx]; 1868 Reg = CCInfo.AllocateReg(Reg); 1869 assert(Reg != AMDGPU::NoRegister); 1870 1871 MachineFunction &MF = CCInfo.getMachineFunction(); 1872 MF.addLiveIn(Reg, RC); 1873 return ArgDescriptor::createRegister(Reg); 1874 } 1875 1876 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1877 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1878 } 1879 1880 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1881 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1882 } 1883 1884 /// Allocate implicit function VGPR arguments at the end of allocated user 1885 /// arguments. 1886 void SITargetLowering::allocateSpecialInputVGPRs( 1887 CCState &CCInfo, MachineFunction &MF, 1888 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1889 const unsigned Mask = 0x3ff; 1890 ArgDescriptor Arg; 1891 1892 if (Info.hasWorkItemIDX()) { 1893 Arg = allocateVGPR32Input(CCInfo, Mask); 1894 Info.setWorkItemIDX(Arg); 1895 } 1896 1897 if (Info.hasWorkItemIDY()) { 1898 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1899 Info.setWorkItemIDY(Arg); 1900 } 1901 1902 if (Info.hasWorkItemIDZ()) 1903 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1904 } 1905 1906 /// Allocate implicit function VGPR arguments in fixed registers. 1907 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1908 CCState &CCInfo, MachineFunction &MF, 1909 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1910 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1911 if (!Reg) 1912 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1913 1914 const unsigned Mask = 0x3ff; 1915 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1916 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1917 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1918 } 1919 1920 void SITargetLowering::allocateSpecialInputSGPRs( 1921 CCState &CCInfo, 1922 MachineFunction &MF, 1923 const SIRegisterInfo &TRI, 1924 SIMachineFunctionInfo &Info) const { 1925 auto &ArgInfo = Info.getArgInfo(); 1926 1927 // TODO: Unify handling with private memory pointers. 1928 1929 if (Info.hasDispatchPtr()) 1930 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1931 1932 if (Info.hasQueuePtr()) 1933 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1934 1935 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1936 // constant offset from the kernarg segment. 1937 if (Info.hasImplicitArgPtr()) 1938 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1939 1940 if (Info.hasDispatchID()) 1941 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1942 1943 // flat_scratch_init is not applicable for non-kernel functions. 1944 1945 if (Info.hasWorkGroupIDX()) 1946 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1947 1948 if (Info.hasWorkGroupIDY()) 1949 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1950 1951 if (Info.hasWorkGroupIDZ()) 1952 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1953 } 1954 1955 // Allocate special inputs passed in user SGPRs. 1956 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1957 MachineFunction &MF, 1958 const SIRegisterInfo &TRI, 1959 SIMachineFunctionInfo &Info) const { 1960 if (Info.hasImplicitBufferPtr()) { 1961 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1962 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1963 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1964 } 1965 1966 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1967 if (Info.hasPrivateSegmentBuffer()) { 1968 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1969 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1970 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1971 } 1972 1973 if (Info.hasDispatchPtr()) { 1974 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 1975 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1976 CCInfo.AllocateReg(DispatchPtrReg); 1977 } 1978 1979 if (Info.hasQueuePtr()) { 1980 Register QueuePtrReg = Info.addQueuePtr(TRI); 1981 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1982 CCInfo.AllocateReg(QueuePtrReg); 1983 } 1984 1985 if (Info.hasKernargSegmentPtr()) { 1986 MachineRegisterInfo &MRI = MF.getRegInfo(); 1987 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1988 CCInfo.AllocateReg(InputPtrReg); 1989 1990 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1991 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1992 } 1993 1994 if (Info.hasDispatchID()) { 1995 Register DispatchIDReg = Info.addDispatchID(TRI); 1996 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1997 CCInfo.AllocateReg(DispatchIDReg); 1998 } 1999 2000 if (Info.hasFlatScratchInit()) { 2001 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2002 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2003 CCInfo.AllocateReg(FlatScratchInitReg); 2004 } 2005 2006 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2007 // these from the dispatch pointer. 2008 } 2009 2010 // Allocate special input registers that are initialized per-wave. 2011 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2012 MachineFunction &MF, 2013 SIMachineFunctionInfo &Info, 2014 CallingConv::ID CallConv, 2015 bool IsShader) const { 2016 if (Info.hasWorkGroupIDX()) { 2017 Register Reg = Info.addWorkGroupIDX(); 2018 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2019 CCInfo.AllocateReg(Reg); 2020 } 2021 2022 if (Info.hasWorkGroupIDY()) { 2023 Register Reg = Info.addWorkGroupIDY(); 2024 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2025 CCInfo.AllocateReg(Reg); 2026 } 2027 2028 if (Info.hasWorkGroupIDZ()) { 2029 Register Reg = Info.addWorkGroupIDZ(); 2030 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2031 CCInfo.AllocateReg(Reg); 2032 } 2033 2034 if (Info.hasWorkGroupInfo()) { 2035 Register Reg = Info.addWorkGroupInfo(); 2036 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2037 CCInfo.AllocateReg(Reg); 2038 } 2039 2040 if (Info.hasPrivateSegmentWaveByteOffset()) { 2041 // Scratch wave offset passed in system SGPR. 2042 unsigned PrivateSegmentWaveByteOffsetReg; 2043 2044 if (IsShader) { 2045 PrivateSegmentWaveByteOffsetReg = 2046 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2047 2048 // This is true if the scratch wave byte offset doesn't have a fixed 2049 // location. 2050 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2051 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2052 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2053 } 2054 } else 2055 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2056 2057 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2058 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2059 } 2060 } 2061 2062 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2063 MachineFunction &MF, 2064 const SIRegisterInfo &TRI, 2065 SIMachineFunctionInfo &Info) { 2066 // Now that we've figured out where the scratch register inputs are, see if 2067 // should reserve the arguments and use them directly. 2068 MachineFrameInfo &MFI = MF.getFrameInfo(); 2069 bool HasStackObjects = MFI.hasStackObjects(); 2070 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2071 2072 // Record that we know we have non-spill stack objects so we don't need to 2073 // check all stack objects later. 2074 if (HasStackObjects) 2075 Info.setHasNonSpillStackObjects(true); 2076 2077 // Everything live out of a block is spilled with fast regalloc, so it's 2078 // almost certain that spilling will be required. 2079 if (TM.getOptLevel() == CodeGenOpt::None) 2080 HasStackObjects = true; 2081 2082 // For now assume stack access is needed in any callee functions, so we need 2083 // the scratch registers to pass in. 2084 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2085 2086 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2087 // If we have stack objects, we unquestionably need the private buffer 2088 // resource. For the Code Object V2 ABI, this will be the first 4 user 2089 // SGPR inputs. We can reserve those and use them directly. 2090 2091 Register PrivateSegmentBufferReg = 2092 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2093 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2094 } else { 2095 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2096 // We tentatively reserve the last registers (skipping the last registers 2097 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2098 // we'll replace these with the ones immediately after those which were 2099 // really allocated. In the prologue copies will be inserted from the 2100 // argument to these reserved registers. 2101 2102 // Without HSA, relocations are used for the scratch pointer and the 2103 // buffer resource setup is always inserted in the prologue. Scratch wave 2104 // offset is still in an input SGPR. 2105 Info.setScratchRSrcReg(ReservedBufferReg); 2106 } 2107 2108 MachineRegisterInfo &MRI = MF.getRegInfo(); 2109 2110 // For entry functions we have to set up the stack pointer if we use it, 2111 // whereas non-entry functions get this "for free". This means there is no 2112 // intrinsic advantage to using S32 over S34 in cases where we do not have 2113 // calls but do need a frame pointer (i.e. if we are requested to have one 2114 // because frame pointer elimination is disabled). To keep things simple we 2115 // only ever use S32 as the call ABI stack pointer, and so using it does not 2116 // imply we need a separate frame pointer. 2117 // 2118 // Try to use s32 as the SP, but move it if it would interfere with input 2119 // arguments. This won't work with calls though. 2120 // 2121 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2122 // registers. 2123 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2124 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2125 } else { 2126 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2127 2128 if (MFI.hasCalls()) 2129 report_fatal_error("call in graphics shader with too many input SGPRs"); 2130 2131 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2132 if (!MRI.isLiveIn(Reg)) { 2133 Info.setStackPtrOffsetReg(Reg); 2134 break; 2135 } 2136 } 2137 2138 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2139 report_fatal_error("failed to find register for SP"); 2140 } 2141 2142 // hasFP should be accurate for entry functions even before the frame is 2143 // finalized, because it does not rely on the known stack size, only 2144 // properties like whether variable sized objects are present. 2145 if (ST.getFrameLowering()->hasFP(MF)) { 2146 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2147 } 2148 } 2149 2150 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2151 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2152 return !Info->isEntryFunction(); 2153 } 2154 2155 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2156 2157 } 2158 2159 void SITargetLowering::insertCopiesSplitCSR( 2160 MachineBasicBlock *Entry, 2161 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2162 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2163 2164 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2165 if (!IStart) 2166 return; 2167 2168 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2169 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2170 MachineBasicBlock::iterator MBBI = Entry->begin(); 2171 for (const MCPhysReg *I = IStart; *I; ++I) { 2172 const TargetRegisterClass *RC = nullptr; 2173 if (AMDGPU::SReg_64RegClass.contains(*I)) 2174 RC = &AMDGPU::SGPR_64RegClass; 2175 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2176 RC = &AMDGPU::SGPR_32RegClass; 2177 else 2178 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2179 2180 Register NewVR = MRI->createVirtualRegister(RC); 2181 // Create copy from CSR to a virtual register. 2182 Entry->addLiveIn(*I); 2183 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2184 .addReg(*I); 2185 2186 // Insert the copy-back instructions right before the terminator. 2187 for (auto *Exit : Exits) 2188 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2189 TII->get(TargetOpcode::COPY), *I) 2190 .addReg(NewVR); 2191 } 2192 } 2193 2194 SDValue SITargetLowering::LowerFormalArguments( 2195 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2196 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2197 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2198 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2199 2200 MachineFunction &MF = DAG.getMachineFunction(); 2201 const Function &Fn = MF.getFunction(); 2202 FunctionType *FType = MF.getFunction().getFunctionType(); 2203 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2204 2205 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2206 DiagnosticInfoUnsupported NoGraphicsHSA( 2207 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2208 DAG.getContext()->diagnose(NoGraphicsHSA); 2209 return DAG.getEntryNode(); 2210 } 2211 2212 SmallVector<ISD::InputArg, 16> Splits; 2213 SmallVector<CCValAssign, 16> ArgLocs; 2214 BitVector Skipped(Ins.size()); 2215 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2216 *DAG.getContext()); 2217 2218 bool IsShader = AMDGPU::isShader(CallConv); 2219 bool IsKernel = AMDGPU::isKernel(CallConv); 2220 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2221 2222 if (IsShader) { 2223 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2224 2225 // At least one interpolation mode must be enabled or else the GPU will 2226 // hang. 2227 // 2228 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2229 // set PSInputAddr, the user wants to enable some bits after the compilation 2230 // based on run-time states. Since we can't know what the final PSInputEna 2231 // will look like, so we shouldn't do anything here and the user should take 2232 // responsibility for the correct programming. 2233 // 2234 // Otherwise, the following restrictions apply: 2235 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2236 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2237 // enabled too. 2238 if (CallConv == CallingConv::AMDGPU_PS) { 2239 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2240 ((Info->getPSInputAddr() & 0xF) == 0 && 2241 Info->isPSInputAllocated(11))) { 2242 CCInfo.AllocateReg(AMDGPU::VGPR0); 2243 CCInfo.AllocateReg(AMDGPU::VGPR1); 2244 Info->markPSInputAllocated(0); 2245 Info->markPSInputEnabled(0); 2246 } 2247 if (Subtarget->isAmdPalOS()) { 2248 // For isAmdPalOS, the user does not enable some bits after compilation 2249 // based on run-time states; the register values being generated here are 2250 // the final ones set in hardware. Therefore we need to apply the 2251 // workaround to PSInputAddr and PSInputEnable together. (The case where 2252 // a bit is set in PSInputAddr but not PSInputEnable is where the 2253 // frontend set up an input arg for a particular interpolation mode, but 2254 // nothing uses that input arg. Really we should have an earlier pass 2255 // that removes such an arg.) 2256 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2257 if ((PsInputBits & 0x7F) == 0 || 2258 ((PsInputBits & 0xF) == 0 && 2259 (PsInputBits >> 11 & 1))) 2260 Info->markPSInputEnabled( 2261 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2262 } 2263 } 2264 2265 assert(!Info->hasDispatchPtr() && 2266 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2267 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2268 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2269 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2270 !Info->hasWorkItemIDZ()); 2271 } else if (IsKernel) { 2272 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2273 } else { 2274 Splits.append(Ins.begin(), Ins.end()); 2275 } 2276 2277 if (IsEntryFunc) { 2278 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2279 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2280 } else { 2281 // For the fixed ABI, pass workitem IDs in the last argument register. 2282 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2283 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2284 } 2285 2286 if (IsKernel) { 2287 analyzeFormalArgumentsCompute(CCInfo, Ins); 2288 } else { 2289 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2290 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2291 } 2292 2293 SmallVector<SDValue, 16> Chains; 2294 2295 // FIXME: This is the minimum kernel argument alignment. We should improve 2296 // this to the maximum alignment of the arguments. 2297 // 2298 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2299 // kern arg offset. 2300 const Align KernelArgBaseAlign = Align(16); 2301 2302 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2303 const ISD::InputArg &Arg = Ins[i]; 2304 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2305 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2306 continue; 2307 } 2308 2309 CCValAssign &VA = ArgLocs[ArgIdx++]; 2310 MVT VT = VA.getLocVT(); 2311 2312 if (IsEntryFunc && VA.isMemLoc()) { 2313 VT = Ins[i].VT; 2314 EVT MemVT = VA.getLocVT(); 2315 2316 const uint64_t Offset = VA.getLocMemOffset(); 2317 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2318 2319 if (Arg.Flags.isByRef()) { 2320 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2321 2322 const GCNTargetMachine &TM = 2323 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2324 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2325 Arg.Flags.getPointerAddrSpace())) { 2326 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2327 Arg.Flags.getPointerAddrSpace()); 2328 } 2329 2330 InVals.push_back(Ptr); 2331 continue; 2332 } 2333 2334 SDValue Arg = lowerKernargMemParameter( 2335 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2336 Chains.push_back(Arg.getValue(1)); 2337 2338 auto *ParamTy = 2339 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2340 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2341 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2342 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2343 // On SI local pointers are just offsets into LDS, so they are always 2344 // less than 16-bits. On CI and newer they could potentially be 2345 // real pointers, so we can't guarantee their size. 2346 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2347 DAG.getValueType(MVT::i16)); 2348 } 2349 2350 InVals.push_back(Arg); 2351 continue; 2352 } else if (!IsEntryFunc && VA.isMemLoc()) { 2353 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2354 InVals.push_back(Val); 2355 if (!Arg.Flags.isByVal()) 2356 Chains.push_back(Val.getValue(1)); 2357 continue; 2358 } 2359 2360 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2361 2362 Register Reg = VA.getLocReg(); 2363 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2364 EVT ValVT = VA.getValVT(); 2365 2366 Reg = MF.addLiveIn(Reg, RC); 2367 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2368 2369 if (Arg.Flags.isSRet()) { 2370 // The return object should be reasonably addressable. 2371 2372 // FIXME: This helps when the return is a real sret. If it is a 2373 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2374 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2375 unsigned NumBits 2376 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2377 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2378 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2379 } 2380 2381 // If this is an 8 or 16-bit value, it is really passed promoted 2382 // to 32 bits. Insert an assert[sz]ext to capture this, then 2383 // truncate to the right size. 2384 switch (VA.getLocInfo()) { 2385 case CCValAssign::Full: 2386 break; 2387 case CCValAssign::BCvt: 2388 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2389 break; 2390 case CCValAssign::SExt: 2391 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2392 DAG.getValueType(ValVT)); 2393 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2394 break; 2395 case CCValAssign::ZExt: 2396 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2397 DAG.getValueType(ValVT)); 2398 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2399 break; 2400 case CCValAssign::AExt: 2401 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2402 break; 2403 default: 2404 llvm_unreachable("Unknown loc info!"); 2405 } 2406 2407 InVals.push_back(Val); 2408 } 2409 2410 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2411 // Special inputs come after user arguments. 2412 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2413 } 2414 2415 // Start adding system SGPRs. 2416 if (IsEntryFunc) { 2417 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2418 } else { 2419 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2420 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2421 } 2422 2423 auto &ArgUsageInfo = 2424 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2425 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2426 2427 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2428 Info->setBytesInStackArgArea(StackArgSize); 2429 2430 return Chains.empty() ? Chain : 2431 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2432 } 2433 2434 // TODO: If return values can't fit in registers, we should return as many as 2435 // possible in registers before passing on stack. 2436 bool SITargetLowering::CanLowerReturn( 2437 CallingConv::ID CallConv, 2438 MachineFunction &MF, bool IsVarArg, 2439 const SmallVectorImpl<ISD::OutputArg> &Outs, 2440 LLVMContext &Context) const { 2441 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2442 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2443 // for shaders. Vector types should be explicitly handled by CC. 2444 if (AMDGPU::isEntryFunctionCC(CallConv)) 2445 return true; 2446 2447 SmallVector<CCValAssign, 16> RVLocs; 2448 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2449 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2450 } 2451 2452 SDValue 2453 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2454 bool isVarArg, 2455 const SmallVectorImpl<ISD::OutputArg> &Outs, 2456 const SmallVectorImpl<SDValue> &OutVals, 2457 const SDLoc &DL, SelectionDAG &DAG) const { 2458 MachineFunction &MF = DAG.getMachineFunction(); 2459 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2460 2461 if (AMDGPU::isKernel(CallConv)) { 2462 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2463 OutVals, DL, DAG); 2464 } 2465 2466 bool IsShader = AMDGPU::isShader(CallConv); 2467 2468 Info->setIfReturnsVoid(Outs.empty()); 2469 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2470 2471 // CCValAssign - represent the assignment of the return value to a location. 2472 SmallVector<CCValAssign, 48> RVLocs; 2473 SmallVector<ISD::OutputArg, 48> Splits; 2474 2475 // CCState - Info about the registers and stack slots. 2476 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2477 *DAG.getContext()); 2478 2479 // Analyze outgoing return values. 2480 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2481 2482 SDValue Flag; 2483 SmallVector<SDValue, 48> RetOps; 2484 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2485 2486 // Add return address for callable functions. 2487 if (!Info->isEntryFunction()) { 2488 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2489 SDValue ReturnAddrReg = CreateLiveInRegister( 2490 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2491 2492 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2493 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2494 MVT::i64); 2495 Chain = 2496 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2497 Flag = Chain.getValue(1); 2498 RetOps.push_back(ReturnAddrVirtualReg); 2499 } 2500 2501 // Copy the result values into the output registers. 2502 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2503 ++I, ++RealRVLocIdx) { 2504 CCValAssign &VA = RVLocs[I]; 2505 assert(VA.isRegLoc() && "Can only return in registers!"); 2506 // TODO: Partially return in registers if return values don't fit. 2507 SDValue Arg = OutVals[RealRVLocIdx]; 2508 2509 // Copied from other backends. 2510 switch (VA.getLocInfo()) { 2511 case CCValAssign::Full: 2512 break; 2513 case CCValAssign::BCvt: 2514 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2515 break; 2516 case CCValAssign::SExt: 2517 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2518 break; 2519 case CCValAssign::ZExt: 2520 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2521 break; 2522 case CCValAssign::AExt: 2523 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2524 break; 2525 default: 2526 llvm_unreachable("Unknown loc info!"); 2527 } 2528 2529 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2530 Flag = Chain.getValue(1); 2531 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2532 } 2533 2534 // FIXME: Does sret work properly? 2535 if (!Info->isEntryFunction()) { 2536 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2537 const MCPhysReg *I = 2538 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2539 if (I) { 2540 for (; *I; ++I) { 2541 if (AMDGPU::SReg_64RegClass.contains(*I)) 2542 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2543 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2544 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2545 else 2546 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2547 } 2548 } 2549 } 2550 2551 // Update chain and glue. 2552 RetOps[0] = Chain; 2553 if (Flag.getNode()) 2554 RetOps.push_back(Flag); 2555 2556 unsigned Opc = AMDGPUISD::ENDPGM; 2557 if (!IsWaveEnd) 2558 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2559 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2560 } 2561 2562 SDValue SITargetLowering::LowerCallResult( 2563 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2564 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2565 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2566 SDValue ThisVal) const { 2567 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2568 2569 // Assign locations to each value returned by this call. 2570 SmallVector<CCValAssign, 16> RVLocs; 2571 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2572 *DAG.getContext()); 2573 CCInfo.AnalyzeCallResult(Ins, RetCC); 2574 2575 // Copy all of the result registers out of their specified physreg. 2576 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2577 CCValAssign VA = RVLocs[i]; 2578 SDValue Val; 2579 2580 if (VA.isRegLoc()) { 2581 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2582 Chain = Val.getValue(1); 2583 InFlag = Val.getValue(2); 2584 } else if (VA.isMemLoc()) { 2585 report_fatal_error("TODO: return values in memory"); 2586 } else 2587 llvm_unreachable("unknown argument location type"); 2588 2589 switch (VA.getLocInfo()) { 2590 case CCValAssign::Full: 2591 break; 2592 case CCValAssign::BCvt: 2593 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2594 break; 2595 case CCValAssign::ZExt: 2596 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2597 DAG.getValueType(VA.getValVT())); 2598 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2599 break; 2600 case CCValAssign::SExt: 2601 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2602 DAG.getValueType(VA.getValVT())); 2603 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2604 break; 2605 case CCValAssign::AExt: 2606 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2607 break; 2608 default: 2609 llvm_unreachable("Unknown loc info!"); 2610 } 2611 2612 InVals.push_back(Val); 2613 } 2614 2615 return Chain; 2616 } 2617 2618 // Add code to pass special inputs required depending on used features separate 2619 // from the explicit user arguments present in the IR. 2620 void SITargetLowering::passSpecialInputs( 2621 CallLoweringInfo &CLI, 2622 CCState &CCInfo, 2623 const SIMachineFunctionInfo &Info, 2624 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2625 SmallVectorImpl<SDValue> &MemOpChains, 2626 SDValue Chain) const { 2627 // If we don't have a call site, this was a call inserted by 2628 // legalization. These can never use special inputs. 2629 if (!CLI.CB) 2630 return; 2631 2632 SelectionDAG &DAG = CLI.DAG; 2633 const SDLoc &DL = CLI.DL; 2634 2635 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2636 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2637 2638 const AMDGPUFunctionArgInfo *CalleeArgInfo 2639 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2640 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2641 auto &ArgUsageInfo = 2642 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2643 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2644 } 2645 2646 // TODO: Unify with private memory register handling. This is complicated by 2647 // the fact that at least in kernels, the input argument is not necessarily 2648 // in the same location as the input. 2649 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2650 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2651 AMDGPUFunctionArgInfo::QUEUE_PTR, 2652 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2653 AMDGPUFunctionArgInfo::DISPATCH_ID, 2654 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2655 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2656 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2657 }; 2658 2659 for (auto InputID : InputRegs) { 2660 const ArgDescriptor *OutgoingArg; 2661 const TargetRegisterClass *ArgRC; 2662 LLT ArgTy; 2663 2664 std::tie(OutgoingArg, ArgRC, ArgTy) = 2665 CalleeArgInfo->getPreloadedValue(InputID); 2666 if (!OutgoingArg) 2667 continue; 2668 2669 const ArgDescriptor *IncomingArg; 2670 const TargetRegisterClass *IncomingArgRC; 2671 LLT Ty; 2672 std::tie(IncomingArg, IncomingArgRC, Ty) = 2673 CallerArgInfo.getPreloadedValue(InputID); 2674 assert(IncomingArgRC == ArgRC); 2675 2676 // All special arguments are ints for now. 2677 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2678 SDValue InputReg; 2679 2680 if (IncomingArg) { 2681 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2682 } else { 2683 // The implicit arg ptr is special because it doesn't have a corresponding 2684 // input for kernels, and is computed from the kernarg segment pointer. 2685 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2686 InputReg = getImplicitArgPtr(DAG, DL); 2687 } 2688 2689 if (OutgoingArg->isRegister()) { 2690 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2691 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2692 report_fatal_error("failed to allocate implicit input argument"); 2693 } else { 2694 unsigned SpecialArgOffset = 2695 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2696 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2697 SpecialArgOffset); 2698 MemOpChains.push_back(ArgStore); 2699 } 2700 } 2701 2702 // Pack workitem IDs into a single register or pass it as is if already 2703 // packed. 2704 const ArgDescriptor *OutgoingArg; 2705 const TargetRegisterClass *ArgRC; 2706 LLT Ty; 2707 2708 std::tie(OutgoingArg, ArgRC, Ty) = 2709 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2710 if (!OutgoingArg) 2711 std::tie(OutgoingArg, ArgRC, Ty) = 2712 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2713 if (!OutgoingArg) 2714 std::tie(OutgoingArg, ArgRC, Ty) = 2715 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2716 if (!OutgoingArg) 2717 return; 2718 2719 const ArgDescriptor *IncomingArgX = std::get<0>( 2720 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2721 const ArgDescriptor *IncomingArgY = std::get<0>( 2722 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2723 const ArgDescriptor *IncomingArgZ = std::get<0>( 2724 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2725 2726 SDValue InputReg; 2727 SDLoc SL; 2728 2729 // If incoming ids are not packed we need to pack them. 2730 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2731 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2732 2733 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2734 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2735 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2736 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2737 InputReg = InputReg.getNode() ? 2738 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2739 } 2740 2741 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2742 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2743 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2744 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2745 InputReg = InputReg.getNode() ? 2746 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2747 } 2748 2749 if (!InputReg.getNode()) { 2750 // Workitem ids are already packed, any of present incoming arguments 2751 // will carry all required fields. 2752 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2753 IncomingArgX ? *IncomingArgX : 2754 IncomingArgY ? *IncomingArgY : 2755 *IncomingArgZ, ~0u); 2756 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2757 } 2758 2759 if (OutgoingArg->isRegister()) { 2760 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2761 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2762 } else { 2763 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2764 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2765 SpecialArgOffset); 2766 MemOpChains.push_back(ArgStore); 2767 } 2768 } 2769 2770 static bool canGuaranteeTCO(CallingConv::ID CC) { 2771 return CC == CallingConv::Fast; 2772 } 2773 2774 /// Return true if we might ever do TCO for calls with this calling convention. 2775 static bool mayTailCallThisCC(CallingConv::ID CC) { 2776 switch (CC) { 2777 case CallingConv::C: 2778 return true; 2779 default: 2780 return canGuaranteeTCO(CC); 2781 } 2782 } 2783 2784 bool SITargetLowering::isEligibleForTailCallOptimization( 2785 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2786 const SmallVectorImpl<ISD::OutputArg> &Outs, 2787 const SmallVectorImpl<SDValue> &OutVals, 2788 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2789 if (!mayTailCallThisCC(CalleeCC)) 2790 return false; 2791 2792 MachineFunction &MF = DAG.getMachineFunction(); 2793 const Function &CallerF = MF.getFunction(); 2794 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2795 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2796 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2797 2798 // Kernels aren't callable, and don't have a live in return address so it 2799 // doesn't make sense to do a tail call with entry functions. 2800 if (!CallerPreserved) 2801 return false; 2802 2803 bool CCMatch = CallerCC == CalleeCC; 2804 2805 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2806 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2807 return true; 2808 return false; 2809 } 2810 2811 // TODO: Can we handle var args? 2812 if (IsVarArg) 2813 return false; 2814 2815 for (const Argument &Arg : CallerF.args()) { 2816 if (Arg.hasByValAttr()) 2817 return false; 2818 } 2819 2820 LLVMContext &Ctx = *DAG.getContext(); 2821 2822 // Check that the call results are passed in the same way. 2823 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2824 CCAssignFnForCall(CalleeCC, IsVarArg), 2825 CCAssignFnForCall(CallerCC, IsVarArg))) 2826 return false; 2827 2828 // The callee has to preserve all registers the caller needs to preserve. 2829 if (!CCMatch) { 2830 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2831 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2832 return false; 2833 } 2834 2835 // Nothing more to check if the callee is taking no arguments. 2836 if (Outs.empty()) 2837 return true; 2838 2839 SmallVector<CCValAssign, 16> ArgLocs; 2840 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2841 2842 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2843 2844 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2845 // If the stack arguments for this call do not fit into our own save area then 2846 // the call cannot be made tail. 2847 // TODO: Is this really necessary? 2848 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2849 return false; 2850 2851 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2852 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2853 } 2854 2855 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2856 if (!CI->isTailCall()) 2857 return false; 2858 2859 const Function *ParentFn = CI->getParent()->getParent(); 2860 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2861 return false; 2862 return true; 2863 } 2864 2865 // The wave scratch offset register is used as the global base pointer. 2866 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2867 SmallVectorImpl<SDValue> &InVals) const { 2868 SelectionDAG &DAG = CLI.DAG; 2869 const SDLoc &DL = CLI.DL; 2870 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2871 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2872 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2873 SDValue Chain = CLI.Chain; 2874 SDValue Callee = CLI.Callee; 2875 bool &IsTailCall = CLI.IsTailCall; 2876 CallingConv::ID CallConv = CLI.CallConv; 2877 bool IsVarArg = CLI.IsVarArg; 2878 bool IsSibCall = false; 2879 bool IsThisReturn = false; 2880 MachineFunction &MF = DAG.getMachineFunction(); 2881 2882 if (Callee.isUndef() || isNullConstant(Callee)) { 2883 if (!CLI.IsTailCall) { 2884 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2885 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2886 } 2887 2888 return Chain; 2889 } 2890 2891 if (IsVarArg) { 2892 return lowerUnhandledCall(CLI, InVals, 2893 "unsupported call to variadic function "); 2894 } 2895 2896 if (!CLI.CB) 2897 report_fatal_error("unsupported libcall legalization"); 2898 2899 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2900 !CLI.CB->getCalledFunction()) { 2901 return lowerUnhandledCall(CLI, InVals, 2902 "unsupported indirect call to function "); 2903 } 2904 2905 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2906 return lowerUnhandledCall(CLI, InVals, 2907 "unsupported required tail call to function "); 2908 } 2909 2910 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2911 // Note the issue is with the CC of the calling function, not of the call 2912 // itself. 2913 return lowerUnhandledCall(CLI, InVals, 2914 "unsupported call from graphics shader of function "); 2915 } 2916 2917 if (IsTailCall) { 2918 IsTailCall = isEligibleForTailCallOptimization( 2919 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2920 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2921 report_fatal_error("failed to perform tail call elimination on a call " 2922 "site marked musttail"); 2923 } 2924 2925 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2926 2927 // A sibling call is one where we're under the usual C ABI and not planning 2928 // to change that but can still do a tail call: 2929 if (!TailCallOpt && IsTailCall) 2930 IsSibCall = true; 2931 2932 if (IsTailCall) 2933 ++NumTailCalls; 2934 } 2935 2936 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2937 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2938 SmallVector<SDValue, 8> MemOpChains; 2939 2940 // Analyze operands of the call, assigning locations to each operand. 2941 SmallVector<CCValAssign, 16> ArgLocs; 2942 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2943 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2944 2945 if (AMDGPUTargetMachine::EnableFixedFunctionABI) { 2946 // With a fixed ABI, allocate fixed registers before user arguments. 2947 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2948 } 2949 2950 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2951 2952 // Get a count of how many bytes are to be pushed on the stack. 2953 unsigned NumBytes = CCInfo.getNextStackOffset(); 2954 2955 if (IsSibCall) { 2956 // Since we're not changing the ABI to make this a tail call, the memory 2957 // operands are already available in the caller's incoming argument space. 2958 NumBytes = 0; 2959 } 2960 2961 // FPDiff is the byte offset of the call's argument area from the callee's. 2962 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2963 // by this amount for a tail call. In a sibling call it must be 0 because the 2964 // caller will deallocate the entire stack and the callee still expects its 2965 // arguments to begin at SP+0. Completely unused for non-tail calls. 2966 int32_t FPDiff = 0; 2967 MachineFrameInfo &MFI = MF.getFrameInfo(); 2968 2969 // Adjust the stack pointer for the new arguments... 2970 // These operations are automatically eliminated by the prolog/epilog pass 2971 if (!IsSibCall) { 2972 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2973 2974 SmallVector<SDValue, 4> CopyFromChains; 2975 2976 // In the HSA case, this should be an identity copy. 2977 SDValue ScratchRSrcReg 2978 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2979 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2980 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2981 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2982 } 2983 2984 MVT PtrVT = MVT::i32; 2985 2986 // Walk the register/memloc assignments, inserting copies/loads. 2987 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2988 CCValAssign &VA = ArgLocs[i]; 2989 SDValue Arg = OutVals[i]; 2990 2991 // Promote the value if needed. 2992 switch (VA.getLocInfo()) { 2993 case CCValAssign::Full: 2994 break; 2995 case CCValAssign::BCvt: 2996 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2997 break; 2998 case CCValAssign::ZExt: 2999 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3000 break; 3001 case CCValAssign::SExt: 3002 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3003 break; 3004 case CCValAssign::AExt: 3005 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3006 break; 3007 case CCValAssign::FPExt: 3008 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3009 break; 3010 default: 3011 llvm_unreachable("Unknown loc info!"); 3012 } 3013 3014 if (VA.isRegLoc()) { 3015 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3016 } else { 3017 assert(VA.isMemLoc()); 3018 3019 SDValue DstAddr; 3020 MachinePointerInfo DstInfo; 3021 3022 unsigned LocMemOffset = VA.getLocMemOffset(); 3023 int32_t Offset = LocMemOffset; 3024 3025 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3026 MaybeAlign Alignment; 3027 3028 if (IsTailCall) { 3029 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3030 unsigned OpSize = Flags.isByVal() ? 3031 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3032 3033 // FIXME: We can have better than the minimum byval required alignment. 3034 Alignment = 3035 Flags.isByVal() 3036 ? Flags.getNonZeroByValAlign() 3037 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3038 3039 Offset = Offset + FPDiff; 3040 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3041 3042 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3043 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3044 3045 // Make sure any stack arguments overlapping with where we're storing 3046 // are loaded before this eventual operation. Otherwise they'll be 3047 // clobbered. 3048 3049 // FIXME: Why is this really necessary? This seems to just result in a 3050 // lot of code to copy the stack and write them back to the same 3051 // locations, which are supposed to be immutable? 3052 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3053 } else { 3054 DstAddr = PtrOff; 3055 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3056 Alignment = 3057 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3058 } 3059 3060 if (Outs[i].Flags.isByVal()) { 3061 SDValue SizeNode = 3062 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3063 SDValue Cpy = 3064 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3065 Outs[i].Flags.getNonZeroByValAlign(), 3066 /*isVol = */ false, /*AlwaysInline = */ true, 3067 /*isTailCall = */ false, DstInfo, 3068 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3069 3070 MemOpChains.push_back(Cpy); 3071 } else { 3072 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 3073 Alignment ? Alignment->value() : 0); 3074 MemOpChains.push_back(Store); 3075 } 3076 } 3077 } 3078 3079 if (!AMDGPUTargetMachine::EnableFixedFunctionABI) { 3080 // Copy special input registers after user input arguments. 3081 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3082 } 3083 3084 if (!MemOpChains.empty()) 3085 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3086 3087 // Build a sequence of copy-to-reg nodes chained together with token chain 3088 // and flag operands which copy the outgoing args into the appropriate regs. 3089 SDValue InFlag; 3090 for (auto &RegToPass : RegsToPass) { 3091 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3092 RegToPass.second, InFlag); 3093 InFlag = Chain.getValue(1); 3094 } 3095 3096 3097 SDValue PhysReturnAddrReg; 3098 if (IsTailCall) { 3099 // Since the return is being combined with the call, we need to pass on the 3100 // return address. 3101 3102 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3103 SDValue ReturnAddrReg = CreateLiveInRegister( 3104 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3105 3106 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3107 MVT::i64); 3108 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3109 InFlag = Chain.getValue(1); 3110 } 3111 3112 // We don't usually want to end the call-sequence here because we would tidy 3113 // the frame up *after* the call, however in the ABI-changing tail-call case 3114 // we've carefully laid out the parameters so that when sp is reset they'll be 3115 // in the correct location. 3116 if (IsTailCall && !IsSibCall) { 3117 Chain = DAG.getCALLSEQ_END(Chain, 3118 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3119 DAG.getTargetConstant(0, DL, MVT::i32), 3120 InFlag, DL); 3121 InFlag = Chain.getValue(1); 3122 } 3123 3124 std::vector<SDValue> Ops; 3125 Ops.push_back(Chain); 3126 Ops.push_back(Callee); 3127 // Add a redundant copy of the callee global which will not be legalized, as 3128 // we need direct access to the callee later. 3129 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3130 const GlobalValue *GV = GSD->getGlobal(); 3131 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3132 } else { 3133 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3134 } 3135 3136 if (IsTailCall) { 3137 // Each tail call may have to adjust the stack by a different amount, so 3138 // this information must travel along with the operation for eventual 3139 // consumption by emitEpilogue. 3140 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3141 3142 Ops.push_back(PhysReturnAddrReg); 3143 } 3144 3145 // Add argument registers to the end of the list so that they are known live 3146 // into the call. 3147 for (auto &RegToPass : RegsToPass) { 3148 Ops.push_back(DAG.getRegister(RegToPass.first, 3149 RegToPass.second.getValueType())); 3150 } 3151 3152 // Add a register mask operand representing the call-preserved registers. 3153 3154 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3155 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3156 assert(Mask && "Missing call preserved mask for calling convention"); 3157 Ops.push_back(DAG.getRegisterMask(Mask)); 3158 3159 if (InFlag.getNode()) 3160 Ops.push_back(InFlag); 3161 3162 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3163 3164 // If we're doing a tall call, use a TC_RETURN here rather than an 3165 // actual call instruction. 3166 if (IsTailCall) { 3167 MFI.setHasTailCall(); 3168 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3169 } 3170 3171 // Returns a chain and a flag for retval copy to use. 3172 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3173 Chain = Call.getValue(0); 3174 InFlag = Call.getValue(1); 3175 3176 uint64_t CalleePopBytes = NumBytes; 3177 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3178 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3179 InFlag, DL); 3180 if (!Ins.empty()) 3181 InFlag = Chain.getValue(1); 3182 3183 // Handle result values, copying them out of physregs into vregs that we 3184 // return. 3185 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3186 InVals, IsThisReturn, 3187 IsThisReturn ? OutVals[0] : SDValue()); 3188 } 3189 3190 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3191 // except for applying the wave size scale to the increment amount. 3192 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3193 SDValue Op, SelectionDAG &DAG) const { 3194 const MachineFunction &MF = DAG.getMachineFunction(); 3195 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3196 3197 SDLoc dl(Op); 3198 EVT VT = Op.getValueType(); 3199 SDValue Tmp1 = Op; 3200 SDValue Tmp2 = Op.getValue(1); 3201 SDValue Tmp3 = Op.getOperand(2); 3202 SDValue Chain = Tmp1.getOperand(0); 3203 3204 Register SPReg = Info->getStackPtrOffsetReg(); 3205 3206 // Chain the dynamic stack allocation so that it doesn't modify the stack 3207 // pointer when other instructions are using the stack. 3208 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3209 3210 SDValue Size = Tmp2.getOperand(1); 3211 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3212 Chain = SP.getValue(1); 3213 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3214 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3215 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3216 unsigned Opc = 3217 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3218 ISD::ADD : ISD::SUB; 3219 3220 SDValue ScaledSize = DAG.getNode( 3221 ISD::SHL, dl, VT, Size, 3222 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3223 3224 Align StackAlign = TFL->getStackAlign(); 3225 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3226 if (Alignment && *Alignment > StackAlign) { 3227 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3228 DAG.getConstant(-(uint64_t)Alignment->value() 3229 << ST.getWavefrontSizeLog2(), 3230 dl, VT)); 3231 } 3232 3233 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3234 Tmp2 = DAG.getCALLSEQ_END( 3235 Chain, DAG.getIntPtrConstant(0, dl, true), 3236 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3237 3238 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3239 } 3240 3241 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3242 SelectionDAG &DAG) const { 3243 // We only handle constant sizes here to allow non-entry block, static sized 3244 // allocas. A truly dynamic value is more difficult to support because we 3245 // don't know if the size value is uniform or not. If the size isn't uniform, 3246 // we would need to do a wave reduction to get the maximum size to know how 3247 // much to increment the uniform stack pointer. 3248 SDValue Size = Op.getOperand(1); 3249 if (isa<ConstantSDNode>(Size)) 3250 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3251 3252 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3253 } 3254 3255 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3256 const MachineFunction &MF) const { 3257 Register Reg = StringSwitch<Register>(RegName) 3258 .Case("m0", AMDGPU::M0) 3259 .Case("exec", AMDGPU::EXEC) 3260 .Case("exec_lo", AMDGPU::EXEC_LO) 3261 .Case("exec_hi", AMDGPU::EXEC_HI) 3262 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3263 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3264 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3265 .Default(Register()); 3266 3267 if (Reg == AMDGPU::NoRegister) { 3268 report_fatal_error(Twine("invalid register name \"" 3269 + StringRef(RegName) + "\".")); 3270 3271 } 3272 3273 if (!Subtarget->hasFlatScrRegister() && 3274 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3275 report_fatal_error(Twine("invalid register \"" 3276 + StringRef(RegName) + "\" for subtarget.")); 3277 } 3278 3279 switch (Reg) { 3280 case AMDGPU::M0: 3281 case AMDGPU::EXEC_LO: 3282 case AMDGPU::EXEC_HI: 3283 case AMDGPU::FLAT_SCR_LO: 3284 case AMDGPU::FLAT_SCR_HI: 3285 if (VT.getSizeInBits() == 32) 3286 return Reg; 3287 break; 3288 case AMDGPU::EXEC: 3289 case AMDGPU::FLAT_SCR: 3290 if (VT.getSizeInBits() == 64) 3291 return Reg; 3292 break; 3293 default: 3294 llvm_unreachable("missing register type checking"); 3295 } 3296 3297 report_fatal_error(Twine("invalid type for register \"" 3298 + StringRef(RegName) + "\".")); 3299 } 3300 3301 // If kill is not the last instruction, split the block so kill is always a 3302 // proper terminator. 3303 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3304 MachineBasicBlock *BB) const { 3305 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3306 3307 MachineBasicBlock::iterator SplitPoint(&MI); 3308 ++SplitPoint; 3309 3310 if (SplitPoint == BB->end()) { 3311 // Don't bother with a new block. 3312 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3313 return BB; 3314 } 3315 3316 MachineFunction *MF = BB->getParent(); 3317 MachineBasicBlock *SplitBB 3318 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3319 3320 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3321 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3322 3323 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3324 BB->addSuccessor(SplitBB); 3325 3326 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3327 return SplitBB; 3328 } 3329 3330 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3331 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3332 // be the first instruction in the remainder block. 3333 // 3334 /// \returns { LoopBody, Remainder } 3335 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3336 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3337 MachineFunction *MF = MBB.getParent(); 3338 MachineBasicBlock::iterator I(&MI); 3339 3340 // To insert the loop we need to split the block. Move everything after this 3341 // point to a new block, and insert a new empty block between the two. 3342 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3343 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3344 MachineFunction::iterator MBBI(MBB); 3345 ++MBBI; 3346 3347 MF->insert(MBBI, LoopBB); 3348 MF->insert(MBBI, RemainderBB); 3349 3350 LoopBB->addSuccessor(LoopBB); 3351 LoopBB->addSuccessor(RemainderBB); 3352 3353 // Move the rest of the block into a new block. 3354 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3355 3356 if (InstInLoop) { 3357 auto Next = std::next(I); 3358 3359 // Move instruction to loop body. 3360 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3361 3362 // Move the rest of the block. 3363 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3364 } else { 3365 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3366 } 3367 3368 MBB.addSuccessor(LoopBB); 3369 3370 return std::make_pair(LoopBB, RemainderBB); 3371 } 3372 3373 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3374 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3375 MachineBasicBlock *MBB = MI.getParent(); 3376 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3377 auto I = MI.getIterator(); 3378 auto E = std::next(I); 3379 3380 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3381 .addImm(0); 3382 3383 MIBundleBuilder Bundler(*MBB, I, E); 3384 finalizeBundle(*MBB, Bundler.begin()); 3385 } 3386 3387 MachineBasicBlock * 3388 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3389 MachineBasicBlock *BB) const { 3390 const DebugLoc &DL = MI.getDebugLoc(); 3391 3392 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3393 3394 MachineBasicBlock *LoopBB; 3395 MachineBasicBlock *RemainderBB; 3396 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3397 3398 // Apparently kill flags are only valid if the def is in the same block? 3399 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3400 Src->setIsKill(false); 3401 3402 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3403 3404 MachineBasicBlock::iterator I = LoopBB->end(); 3405 3406 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3407 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3408 3409 // Clear TRAP_STS.MEM_VIOL 3410 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3411 .addImm(0) 3412 .addImm(EncodedReg); 3413 3414 bundleInstWithWaitcnt(MI); 3415 3416 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3417 3418 // Load and check TRAP_STS.MEM_VIOL 3419 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3420 .addImm(EncodedReg); 3421 3422 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3423 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3424 .addReg(Reg, RegState::Kill) 3425 .addImm(0); 3426 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3427 .addMBB(LoopBB); 3428 3429 return RemainderBB; 3430 } 3431 3432 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3433 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3434 // will only do one iteration. In the worst case, this will loop 64 times. 3435 // 3436 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3437 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3438 const SIInstrInfo *TII, 3439 MachineRegisterInfo &MRI, 3440 MachineBasicBlock &OrigBB, 3441 MachineBasicBlock &LoopBB, 3442 const DebugLoc &DL, 3443 const MachineOperand &IdxReg, 3444 unsigned InitReg, 3445 unsigned ResultReg, 3446 unsigned PhiReg, 3447 unsigned InitSaveExecReg, 3448 int Offset, 3449 bool UseGPRIdxMode, 3450 bool IsIndirectSrc) { 3451 MachineFunction *MF = OrigBB.getParent(); 3452 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3453 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3454 MachineBasicBlock::iterator I = LoopBB.begin(); 3455 3456 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3457 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3458 Register NewExec = MRI.createVirtualRegister(BoolRC); 3459 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3460 Register CondReg = MRI.createVirtualRegister(BoolRC); 3461 3462 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3463 .addReg(InitReg) 3464 .addMBB(&OrigBB) 3465 .addReg(ResultReg) 3466 .addMBB(&LoopBB); 3467 3468 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3469 .addReg(InitSaveExecReg) 3470 .addMBB(&OrigBB) 3471 .addReg(NewExec) 3472 .addMBB(&LoopBB); 3473 3474 // Read the next variant <- also loop target. 3475 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3476 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3477 3478 // Compare the just read M0 value to all possible Idx values. 3479 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3480 .addReg(CurrentIdxReg) 3481 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3482 3483 // Update EXEC, save the original EXEC value to VCC. 3484 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3485 : AMDGPU::S_AND_SAVEEXEC_B64), 3486 NewExec) 3487 .addReg(CondReg, RegState::Kill); 3488 3489 MRI.setSimpleHint(NewExec, CondReg); 3490 3491 if (UseGPRIdxMode) { 3492 unsigned IdxReg; 3493 if (Offset == 0) { 3494 IdxReg = CurrentIdxReg; 3495 } else { 3496 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3497 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3498 .addReg(CurrentIdxReg, RegState::Kill) 3499 .addImm(Offset); 3500 } 3501 unsigned IdxMode = IsIndirectSrc ? 3502 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3503 MachineInstr *SetOn = 3504 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3505 .addReg(IdxReg, RegState::Kill) 3506 .addImm(IdxMode); 3507 SetOn->getOperand(3).setIsUndef(); 3508 } else { 3509 // Move index from VCC into M0 3510 if (Offset == 0) { 3511 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3512 .addReg(CurrentIdxReg, RegState::Kill); 3513 } else { 3514 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3515 .addReg(CurrentIdxReg, RegState::Kill) 3516 .addImm(Offset); 3517 } 3518 } 3519 3520 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3521 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3522 MachineInstr *InsertPt = 3523 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3524 : AMDGPU::S_XOR_B64_term), Exec) 3525 .addReg(Exec) 3526 .addReg(NewExec); 3527 3528 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3529 // s_cbranch_scc0? 3530 3531 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3532 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3533 .addMBB(&LoopBB); 3534 3535 return InsertPt->getIterator(); 3536 } 3537 3538 // This has slightly sub-optimal regalloc when the source vector is killed by 3539 // the read. The register allocator does not understand that the kill is 3540 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3541 // subregister from it, using 1 more VGPR than necessary. This was saved when 3542 // this was expanded after register allocation. 3543 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3544 MachineBasicBlock &MBB, 3545 MachineInstr &MI, 3546 unsigned InitResultReg, 3547 unsigned PhiReg, 3548 int Offset, 3549 bool UseGPRIdxMode, 3550 bool IsIndirectSrc) { 3551 MachineFunction *MF = MBB.getParent(); 3552 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3553 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3554 MachineRegisterInfo &MRI = MF->getRegInfo(); 3555 const DebugLoc &DL = MI.getDebugLoc(); 3556 MachineBasicBlock::iterator I(&MI); 3557 3558 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3559 Register DstReg = MI.getOperand(0).getReg(); 3560 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3561 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3562 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3563 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3564 3565 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3566 3567 // Save the EXEC mask 3568 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3569 .addReg(Exec); 3570 3571 MachineBasicBlock *LoopBB; 3572 MachineBasicBlock *RemainderBB; 3573 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3574 3575 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3576 3577 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3578 InitResultReg, DstReg, PhiReg, TmpExec, 3579 Offset, UseGPRIdxMode, IsIndirectSrc); 3580 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3581 MachineFunction::iterator MBBI(LoopBB); 3582 ++MBBI; 3583 MF->insert(MBBI, LandingPad); 3584 LoopBB->removeSuccessor(RemainderBB); 3585 LandingPad->addSuccessor(RemainderBB); 3586 LoopBB->addSuccessor(LandingPad); 3587 MachineBasicBlock::iterator First = LandingPad->begin(); 3588 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3589 .addReg(SaveExec); 3590 3591 return InsPt; 3592 } 3593 3594 // Returns subreg index, offset 3595 static std::pair<unsigned, int> 3596 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3597 const TargetRegisterClass *SuperRC, 3598 unsigned VecReg, 3599 int Offset) { 3600 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3601 3602 // Skip out of bounds offsets, or else we would end up using an undefined 3603 // register. 3604 if (Offset >= NumElts || Offset < 0) 3605 return std::make_pair(AMDGPU::sub0, Offset); 3606 3607 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3608 } 3609 3610 // Return true if the index is an SGPR and was set. 3611 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3612 MachineRegisterInfo &MRI, 3613 MachineInstr &MI, 3614 int Offset, 3615 bool UseGPRIdxMode, 3616 bool IsIndirectSrc) { 3617 MachineBasicBlock *MBB = MI.getParent(); 3618 const DebugLoc &DL = MI.getDebugLoc(); 3619 MachineBasicBlock::iterator I(&MI); 3620 3621 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3622 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3623 3624 assert(Idx->getReg() != AMDGPU::NoRegister); 3625 3626 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3627 return false; 3628 3629 if (UseGPRIdxMode) { 3630 unsigned IdxMode = IsIndirectSrc ? 3631 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3632 if (Offset == 0) { 3633 MachineInstr *SetOn = 3634 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3635 .add(*Idx) 3636 .addImm(IdxMode); 3637 3638 SetOn->getOperand(3).setIsUndef(); 3639 } else { 3640 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3641 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3642 .add(*Idx) 3643 .addImm(Offset); 3644 MachineInstr *SetOn = 3645 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3646 .addReg(Tmp, RegState::Kill) 3647 .addImm(IdxMode); 3648 3649 SetOn->getOperand(3).setIsUndef(); 3650 } 3651 3652 return true; 3653 } 3654 3655 if (Offset == 0) { 3656 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3657 .add(*Idx); 3658 } else { 3659 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3660 .add(*Idx) 3661 .addImm(Offset); 3662 } 3663 3664 return true; 3665 } 3666 3667 // Control flow needs to be inserted if indexing with a VGPR. 3668 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3669 MachineBasicBlock &MBB, 3670 const GCNSubtarget &ST) { 3671 const SIInstrInfo *TII = ST.getInstrInfo(); 3672 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3673 MachineFunction *MF = MBB.getParent(); 3674 MachineRegisterInfo &MRI = MF->getRegInfo(); 3675 3676 Register Dst = MI.getOperand(0).getReg(); 3677 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3678 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3679 3680 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3681 3682 unsigned SubReg; 3683 std::tie(SubReg, Offset) 3684 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3685 3686 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3687 3688 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3689 MachineBasicBlock::iterator I(&MI); 3690 const DebugLoc &DL = MI.getDebugLoc(); 3691 3692 if (UseGPRIdxMode) { 3693 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3694 // to avoid interfering with other uses, so probably requires a new 3695 // optimization pass. 3696 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3697 .addReg(SrcReg, 0, SubReg) 3698 .addReg(SrcReg, RegState::Implicit) 3699 .addReg(AMDGPU::M0, RegState::Implicit); 3700 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3701 } else { 3702 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3703 .addReg(SrcReg, 0, SubReg) 3704 .addReg(SrcReg, RegState::Implicit); 3705 } 3706 3707 MI.eraseFromParent(); 3708 3709 return &MBB; 3710 } 3711 3712 const DebugLoc &DL = MI.getDebugLoc(); 3713 MachineBasicBlock::iterator I(&MI); 3714 3715 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3716 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3717 3718 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3719 3720 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3721 Offset, UseGPRIdxMode, true); 3722 MachineBasicBlock *LoopBB = InsPt->getParent(); 3723 3724 if (UseGPRIdxMode) { 3725 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3726 .addReg(SrcReg, 0, SubReg) 3727 .addReg(SrcReg, RegState::Implicit) 3728 .addReg(AMDGPU::M0, RegState::Implicit); 3729 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3730 } else { 3731 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3732 .addReg(SrcReg, 0, SubReg) 3733 .addReg(SrcReg, RegState::Implicit); 3734 } 3735 3736 MI.eraseFromParent(); 3737 3738 return LoopBB; 3739 } 3740 3741 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3742 MachineBasicBlock &MBB, 3743 const GCNSubtarget &ST) { 3744 const SIInstrInfo *TII = ST.getInstrInfo(); 3745 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3746 MachineFunction *MF = MBB.getParent(); 3747 MachineRegisterInfo &MRI = MF->getRegInfo(); 3748 3749 Register Dst = MI.getOperand(0).getReg(); 3750 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3751 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3752 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3753 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3754 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3755 3756 // This can be an immediate, but will be folded later. 3757 assert(Val->getReg()); 3758 3759 unsigned SubReg; 3760 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3761 SrcVec->getReg(), 3762 Offset); 3763 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3764 3765 if (Idx->getReg() == AMDGPU::NoRegister) { 3766 MachineBasicBlock::iterator I(&MI); 3767 const DebugLoc &DL = MI.getDebugLoc(); 3768 3769 assert(Offset == 0); 3770 3771 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3772 .add(*SrcVec) 3773 .add(*Val) 3774 .addImm(SubReg); 3775 3776 MI.eraseFromParent(); 3777 return &MBB; 3778 } 3779 3780 const MCInstrDesc &MovRelDesc 3781 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3782 3783 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3784 MachineBasicBlock::iterator I(&MI); 3785 const DebugLoc &DL = MI.getDebugLoc(); 3786 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3787 .addReg(SrcVec->getReg()) 3788 .add(*Val) 3789 .addImm(SubReg); 3790 if (UseGPRIdxMode) 3791 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3792 3793 MI.eraseFromParent(); 3794 return &MBB; 3795 } 3796 3797 if (Val->isReg()) 3798 MRI.clearKillFlags(Val->getReg()); 3799 3800 const DebugLoc &DL = MI.getDebugLoc(); 3801 3802 Register PhiReg = MRI.createVirtualRegister(VecRC); 3803 3804 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3805 Offset, UseGPRIdxMode, false); 3806 MachineBasicBlock *LoopBB = InsPt->getParent(); 3807 3808 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3809 .addReg(PhiReg) 3810 .add(*Val) 3811 .addImm(AMDGPU::sub0); 3812 if (UseGPRIdxMode) 3813 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3814 3815 MI.eraseFromParent(); 3816 return LoopBB; 3817 } 3818 3819 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3820 MachineInstr &MI, MachineBasicBlock *BB) const { 3821 3822 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3823 MachineFunction *MF = BB->getParent(); 3824 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3825 3826 switch (MI.getOpcode()) { 3827 case AMDGPU::S_UADDO_PSEUDO: 3828 case AMDGPU::S_USUBO_PSEUDO: { 3829 const DebugLoc &DL = MI.getDebugLoc(); 3830 MachineOperand &Dest0 = MI.getOperand(0); 3831 MachineOperand &Dest1 = MI.getOperand(1); 3832 MachineOperand &Src0 = MI.getOperand(2); 3833 MachineOperand &Src1 = MI.getOperand(3); 3834 3835 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3836 ? AMDGPU::S_ADD_I32 3837 : AMDGPU::S_SUB_I32; 3838 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3839 3840 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3841 .addImm(1) 3842 .addImm(0); 3843 3844 MI.eraseFromParent(); 3845 return BB; 3846 } 3847 case AMDGPU::S_ADD_U64_PSEUDO: 3848 case AMDGPU::S_SUB_U64_PSEUDO: { 3849 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3850 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3851 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3852 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3853 const DebugLoc &DL = MI.getDebugLoc(); 3854 3855 MachineOperand &Dest = MI.getOperand(0); 3856 MachineOperand &Src0 = MI.getOperand(1); 3857 MachineOperand &Src1 = MI.getOperand(2); 3858 3859 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3860 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3861 3862 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3863 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3864 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3865 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3866 3867 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3868 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3869 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3870 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3871 3872 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3873 3874 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3875 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3876 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3877 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3878 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3879 .addReg(DestSub0) 3880 .addImm(AMDGPU::sub0) 3881 .addReg(DestSub1) 3882 .addImm(AMDGPU::sub1); 3883 MI.eraseFromParent(); 3884 return BB; 3885 } 3886 case AMDGPU::V_ADD_U64_PSEUDO: 3887 case AMDGPU::V_SUB_U64_PSEUDO: { 3888 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3889 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3890 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3891 const DebugLoc &DL = MI.getDebugLoc(); 3892 3893 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3894 3895 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3896 3897 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3898 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3899 3900 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3901 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3902 3903 MachineOperand &Dest = MI.getOperand(0); 3904 MachineOperand &Src0 = MI.getOperand(1); 3905 MachineOperand &Src1 = MI.getOperand(2); 3906 3907 const TargetRegisterClass *Src0RC = Src0.isReg() 3908 ? MRI.getRegClass(Src0.getReg()) 3909 : &AMDGPU::VReg_64RegClass; 3910 const TargetRegisterClass *Src1RC = Src1.isReg() 3911 ? MRI.getRegClass(Src1.getReg()) 3912 : &AMDGPU::VReg_64RegClass; 3913 3914 const TargetRegisterClass *Src0SubRC = 3915 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3916 const TargetRegisterClass *Src1SubRC = 3917 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3918 3919 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3920 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3921 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3922 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3923 3924 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3925 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3926 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3927 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3928 3929 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 3930 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3931 .addReg(CarryReg, RegState::Define) 3932 .add(SrcReg0Sub0) 3933 .add(SrcReg1Sub0) 3934 .addImm(0); // clamp bit 3935 3936 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3937 MachineInstr *HiHalf = 3938 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3939 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3940 .add(SrcReg0Sub1) 3941 .add(SrcReg1Sub1) 3942 .addReg(CarryReg, RegState::Kill) 3943 .addImm(0); // clamp bit 3944 3945 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3946 .addReg(DestSub0) 3947 .addImm(AMDGPU::sub0) 3948 .addReg(DestSub1) 3949 .addImm(AMDGPU::sub1); 3950 TII->legalizeOperands(*LoHalf); 3951 TII->legalizeOperands(*HiHalf); 3952 MI.eraseFromParent(); 3953 return BB; 3954 } 3955 case AMDGPU::S_ADD_CO_PSEUDO: 3956 case AMDGPU::S_SUB_CO_PSEUDO: { 3957 // This pseudo has a chance to be selected 3958 // only from uniform add/subcarry node. All the VGPR operands 3959 // therefore assumed to be splat vectors. 3960 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3961 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3962 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3963 MachineBasicBlock::iterator MII = MI; 3964 const DebugLoc &DL = MI.getDebugLoc(); 3965 MachineOperand &Dest = MI.getOperand(0); 3966 MachineOperand &CarryDest = MI.getOperand(1); 3967 MachineOperand &Src0 = MI.getOperand(2); 3968 MachineOperand &Src1 = MI.getOperand(3); 3969 MachineOperand &Src2 = MI.getOperand(4); 3970 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 3971 ? AMDGPU::S_ADDC_U32 3972 : AMDGPU::S_SUBB_U32; 3973 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 3974 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3975 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 3976 .addReg(Src0.getReg()); 3977 Src0.setReg(RegOp0); 3978 } 3979 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 3980 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3981 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 3982 .addReg(Src1.getReg()); 3983 Src1.setReg(RegOp1); 3984 } 3985 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3986 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 3987 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 3988 .addReg(Src2.getReg()); 3989 Src2.setReg(RegOp2); 3990 } 3991 3992 if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) { 3993 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 3994 .addReg(Src2.getReg()) 3995 .addImm(0); 3996 } else { 3997 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 3998 .addReg(Src2.getReg()) 3999 .addImm(0); 4000 } 4001 4002 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4003 4004 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 4005 .addReg(AMDGPU::SCC); 4006 MI.eraseFromParent(); 4007 return BB; 4008 } 4009 case AMDGPU::SI_INIT_M0: { 4010 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4011 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4012 .add(MI.getOperand(0)); 4013 MI.eraseFromParent(); 4014 return BB; 4015 } 4016 case AMDGPU::SI_INIT_EXEC: 4017 // This should be before all vector instructions. 4018 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 4019 AMDGPU::EXEC) 4020 .addImm(MI.getOperand(0).getImm()); 4021 MI.eraseFromParent(); 4022 return BB; 4023 4024 case AMDGPU::SI_INIT_EXEC_LO: 4025 // This should be before all vector instructions. 4026 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 4027 AMDGPU::EXEC_LO) 4028 .addImm(MI.getOperand(0).getImm()); 4029 MI.eraseFromParent(); 4030 return BB; 4031 4032 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 4033 // Extract the thread count from an SGPR input and set EXEC accordingly. 4034 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 4035 // 4036 // S_BFE_U32 count, input, {shift, 7} 4037 // S_BFM_B64 exec, count, 0 4038 // S_CMP_EQ_U32 count, 64 4039 // S_CMOV_B64 exec, -1 4040 MachineInstr *FirstMI = &*BB->begin(); 4041 MachineRegisterInfo &MRI = MF->getRegInfo(); 4042 Register InputReg = MI.getOperand(0).getReg(); 4043 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 4044 bool Found = false; 4045 4046 // Move the COPY of the input reg to the beginning, so that we can use it. 4047 for (auto I = BB->begin(); I != &MI; I++) { 4048 if (I->getOpcode() != TargetOpcode::COPY || 4049 I->getOperand(0).getReg() != InputReg) 4050 continue; 4051 4052 if (I == FirstMI) { 4053 FirstMI = &*++BB->begin(); 4054 } else { 4055 I->removeFromParent(); 4056 BB->insert(FirstMI, &*I); 4057 } 4058 Found = true; 4059 break; 4060 } 4061 assert(Found); 4062 (void)Found; 4063 4064 // This should be before all vector instructions. 4065 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 4066 bool isWave32 = getSubtarget()->isWave32(); 4067 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 4068 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 4069 .addReg(InputReg) 4070 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 4071 BuildMI(*BB, FirstMI, DebugLoc(), 4072 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 4073 Exec) 4074 .addReg(CountReg) 4075 .addImm(0); 4076 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 4077 .addReg(CountReg, RegState::Kill) 4078 .addImm(getSubtarget()->getWavefrontSize()); 4079 BuildMI(*BB, FirstMI, DebugLoc(), 4080 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 4081 Exec) 4082 .addImm(-1); 4083 MI.eraseFromParent(); 4084 return BB; 4085 } 4086 4087 case AMDGPU::GET_GROUPSTATICSIZE: { 4088 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4089 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4090 DebugLoc DL = MI.getDebugLoc(); 4091 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4092 .add(MI.getOperand(0)) 4093 .addImm(MFI->getLDSSize()); 4094 MI.eraseFromParent(); 4095 return BB; 4096 } 4097 case AMDGPU::SI_INDIRECT_SRC_V1: 4098 case AMDGPU::SI_INDIRECT_SRC_V2: 4099 case AMDGPU::SI_INDIRECT_SRC_V4: 4100 case AMDGPU::SI_INDIRECT_SRC_V8: 4101 case AMDGPU::SI_INDIRECT_SRC_V16: 4102 case AMDGPU::SI_INDIRECT_SRC_V32: 4103 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4104 case AMDGPU::SI_INDIRECT_DST_V1: 4105 case AMDGPU::SI_INDIRECT_DST_V2: 4106 case AMDGPU::SI_INDIRECT_DST_V4: 4107 case AMDGPU::SI_INDIRECT_DST_V8: 4108 case AMDGPU::SI_INDIRECT_DST_V16: 4109 case AMDGPU::SI_INDIRECT_DST_V32: 4110 return emitIndirectDst(MI, *BB, *getSubtarget()); 4111 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4112 case AMDGPU::SI_KILL_I1_PSEUDO: 4113 return splitKillBlock(MI, BB); 4114 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4115 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4116 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4117 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4118 4119 Register Dst = MI.getOperand(0).getReg(); 4120 Register Src0 = MI.getOperand(1).getReg(); 4121 Register Src1 = MI.getOperand(2).getReg(); 4122 const DebugLoc &DL = MI.getDebugLoc(); 4123 Register SrcCond = MI.getOperand(3).getReg(); 4124 4125 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4126 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4127 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4128 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4129 4130 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4131 .addReg(SrcCond); 4132 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4133 .addImm(0) 4134 .addReg(Src0, 0, AMDGPU::sub0) 4135 .addImm(0) 4136 .addReg(Src1, 0, AMDGPU::sub0) 4137 .addReg(SrcCondCopy); 4138 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4139 .addImm(0) 4140 .addReg(Src0, 0, AMDGPU::sub1) 4141 .addImm(0) 4142 .addReg(Src1, 0, AMDGPU::sub1) 4143 .addReg(SrcCondCopy); 4144 4145 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4146 .addReg(DstLo) 4147 .addImm(AMDGPU::sub0) 4148 .addReg(DstHi) 4149 .addImm(AMDGPU::sub1); 4150 MI.eraseFromParent(); 4151 return BB; 4152 } 4153 case AMDGPU::SI_BR_UNDEF: { 4154 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4155 const DebugLoc &DL = MI.getDebugLoc(); 4156 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4157 .add(MI.getOperand(0)); 4158 Br->getOperand(1).setIsUndef(true); // read undef SCC 4159 MI.eraseFromParent(); 4160 return BB; 4161 } 4162 case AMDGPU::ADJCALLSTACKUP: 4163 case AMDGPU::ADJCALLSTACKDOWN: { 4164 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4165 MachineInstrBuilder MIB(*MF, &MI); 4166 4167 // Add an implicit use of the frame offset reg to prevent the restore copy 4168 // inserted after the call from being reorderd after stack operations in the 4169 // the caller's frame. 4170 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4171 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 4172 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 4173 return BB; 4174 } 4175 case AMDGPU::SI_CALL_ISEL: { 4176 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4177 const DebugLoc &DL = MI.getDebugLoc(); 4178 4179 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4180 4181 MachineInstrBuilder MIB; 4182 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4183 4184 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4185 MIB.add(MI.getOperand(I)); 4186 4187 MIB.cloneMemRefs(MI); 4188 MI.eraseFromParent(); 4189 return BB; 4190 } 4191 case AMDGPU::V_ADD_CO_U32_e32: 4192 case AMDGPU::V_SUB_CO_U32_e32: 4193 case AMDGPU::V_SUBREV_CO_U32_e32: { 4194 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4195 const DebugLoc &DL = MI.getDebugLoc(); 4196 unsigned Opc = MI.getOpcode(); 4197 4198 bool NeedClampOperand = false; 4199 if (TII->pseudoToMCOpcode(Opc) == -1) { 4200 Opc = AMDGPU::getVOPe64(Opc); 4201 NeedClampOperand = true; 4202 } 4203 4204 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4205 if (TII->isVOP3(*I)) { 4206 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4207 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4208 I.addReg(TRI->getVCC(), RegState::Define); 4209 } 4210 I.add(MI.getOperand(1)) 4211 .add(MI.getOperand(2)); 4212 if (NeedClampOperand) 4213 I.addImm(0); // clamp bit for e64 encoding 4214 4215 TII->legalizeOperands(*I); 4216 4217 MI.eraseFromParent(); 4218 return BB; 4219 } 4220 case AMDGPU::DS_GWS_INIT: 4221 case AMDGPU::DS_GWS_SEMA_V: 4222 case AMDGPU::DS_GWS_SEMA_BR: 4223 case AMDGPU::DS_GWS_SEMA_P: 4224 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4225 case AMDGPU::DS_GWS_BARRIER: 4226 // A s_waitcnt 0 is required to be the instruction immediately following. 4227 if (getSubtarget()->hasGWSAutoReplay()) { 4228 bundleInstWithWaitcnt(MI); 4229 return BB; 4230 } 4231 4232 return emitGWSMemViolTestLoop(MI, BB); 4233 case AMDGPU::S_SETREG_B32: { 4234 if (!getSubtarget()->hasDenormModeInst()) 4235 return BB; 4236 4237 // Try to optimize cases that only set the denormal mode or rounding mode. 4238 // 4239 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4240 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4241 // instead. 4242 // 4243 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4244 // allow you to have a no side effect instruction in the output of a 4245 // sideeffecting pattern. 4246 4247 // TODO: Should also emit a no side effects pseudo if only FP bits are 4248 // touched, even if not all of them or to a variable. 4249 unsigned ID, Offset, Width; 4250 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4251 if (ID != AMDGPU::Hwreg::ID_MODE) 4252 return BB; 4253 4254 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4255 const unsigned SetMask = WidthMask << Offset; 4256 unsigned SetDenormOp = 0; 4257 unsigned SetRoundOp = 0; 4258 4259 // The dedicated instructions can only set the whole denorm or round mode at 4260 // once, not a subset of bits in either. 4261 if (Width == 8 && (SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4262 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) { 4263 // If this fully sets both the round and denorm mode, emit the two 4264 // dedicated instructions for these. 4265 assert(Offset == 0); 4266 SetRoundOp = AMDGPU::S_ROUND_MODE; 4267 SetDenormOp = AMDGPU::S_DENORM_MODE; 4268 } else if (Width == 4) { 4269 if ((SetMask & AMDGPU::Hwreg::FP_ROUND_MASK) == SetMask) { 4270 SetRoundOp = AMDGPU::S_ROUND_MODE; 4271 assert(Offset == 0); 4272 } else if ((SetMask & AMDGPU::Hwreg::FP_DENORM_MASK) == SetMask) { 4273 SetDenormOp = AMDGPU::S_DENORM_MODE; 4274 assert(Offset == 4); 4275 } 4276 } 4277 4278 if (SetRoundOp || SetDenormOp) { 4279 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4280 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4281 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4282 unsigned ImmVal = Def->getOperand(1).getImm(); 4283 if (SetRoundOp) { 4284 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4285 .addImm(ImmVal & 0xf); 4286 4287 // If we also have the denorm mode, get just the denorm mode bits. 4288 ImmVal >>= 4; 4289 } 4290 4291 if (SetDenormOp) { 4292 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4293 .addImm(ImmVal & 0xf); 4294 } 4295 4296 MI.eraseFromParent(); 4297 } 4298 } 4299 4300 return BB; 4301 } 4302 default: 4303 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4304 } 4305 } 4306 4307 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4308 return isTypeLegal(VT.getScalarType()); 4309 } 4310 4311 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4312 // This currently forces unfolding various combinations of fsub into fma with 4313 // free fneg'd operands. As long as we have fast FMA (controlled by 4314 // isFMAFasterThanFMulAndFAdd), we should perform these. 4315 4316 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4317 // most of these combines appear to be cycle neutral but save on instruction 4318 // count / code size. 4319 return true; 4320 } 4321 4322 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4323 EVT VT) const { 4324 if (!VT.isVector()) { 4325 return MVT::i1; 4326 } 4327 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4328 } 4329 4330 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4331 // TODO: Should i16 be used always if legal? For now it would force VALU 4332 // shifts. 4333 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4334 } 4335 4336 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4337 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4338 ? Ty.changeElementSize(16) 4339 : Ty.changeElementSize(32); 4340 } 4341 4342 // Answering this is somewhat tricky and depends on the specific device which 4343 // have different rates for fma or all f64 operations. 4344 // 4345 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4346 // regardless of which device (although the number of cycles differs between 4347 // devices), so it is always profitable for f64. 4348 // 4349 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4350 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4351 // which we can always do even without fused FP ops since it returns the same 4352 // result as the separate operations and since it is always full 4353 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4354 // however does not support denormals, so we do report fma as faster if we have 4355 // a fast fma device and require denormals. 4356 // 4357 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4358 EVT VT) const { 4359 VT = VT.getScalarType(); 4360 4361 switch (VT.getSimpleVT().SimpleTy) { 4362 case MVT::f32: { 4363 // If mad is not available this depends only on if f32 fma is full rate. 4364 if (!Subtarget->hasMadMacF32Insts()) 4365 return Subtarget->hasFastFMAF32(); 4366 4367 // Otherwise f32 mad is always full rate and returns the same result as 4368 // the separate operations so should be preferred over fma. 4369 // However does not support denomals. 4370 if (hasFP32Denormals(MF)) 4371 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4372 4373 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4374 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4375 } 4376 case MVT::f64: 4377 return true; 4378 case MVT::f16: 4379 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4380 default: 4381 break; 4382 } 4383 4384 return false; 4385 } 4386 4387 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4388 const SDNode *N) const { 4389 // TODO: Check future ftz flag 4390 // v_mad_f32/v_mac_f32 do not support denormals. 4391 EVT VT = N->getValueType(0); 4392 if (VT == MVT::f32) 4393 return Subtarget->hasMadMacF32Insts() && 4394 !hasFP32Denormals(DAG.getMachineFunction()); 4395 if (VT == MVT::f16) { 4396 return Subtarget->hasMadF16() && 4397 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4398 } 4399 4400 return false; 4401 } 4402 4403 //===----------------------------------------------------------------------===// 4404 // Custom DAG Lowering Operations 4405 //===----------------------------------------------------------------------===// 4406 4407 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4408 // wider vector type is legal. 4409 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4410 SelectionDAG &DAG) const { 4411 unsigned Opc = Op.getOpcode(); 4412 EVT VT = Op.getValueType(); 4413 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4414 4415 SDValue Lo, Hi; 4416 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4417 4418 SDLoc SL(Op); 4419 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4420 Op->getFlags()); 4421 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4422 Op->getFlags()); 4423 4424 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4425 } 4426 4427 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4428 // wider vector type is legal. 4429 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4430 SelectionDAG &DAG) const { 4431 unsigned Opc = Op.getOpcode(); 4432 EVT VT = Op.getValueType(); 4433 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4434 4435 SDValue Lo0, Hi0; 4436 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4437 SDValue Lo1, Hi1; 4438 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4439 4440 SDLoc SL(Op); 4441 4442 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4443 Op->getFlags()); 4444 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4445 Op->getFlags()); 4446 4447 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4448 } 4449 4450 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4451 SelectionDAG &DAG) const { 4452 unsigned Opc = Op.getOpcode(); 4453 EVT VT = Op.getValueType(); 4454 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4455 4456 SDValue Lo0, Hi0; 4457 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4458 SDValue Lo1, Hi1; 4459 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4460 SDValue Lo2, Hi2; 4461 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4462 4463 SDLoc SL(Op); 4464 4465 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4466 Op->getFlags()); 4467 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4468 Op->getFlags()); 4469 4470 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4471 } 4472 4473 4474 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4475 switch (Op.getOpcode()) { 4476 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4477 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4478 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4479 case ISD::LOAD: { 4480 SDValue Result = LowerLOAD(Op, DAG); 4481 assert((!Result.getNode() || 4482 Result.getNode()->getNumValues() == 2) && 4483 "Load should return a value and a chain"); 4484 return Result; 4485 } 4486 4487 case ISD::FSIN: 4488 case ISD::FCOS: 4489 return LowerTrig(Op, DAG); 4490 case ISD::SELECT: return LowerSELECT(Op, DAG); 4491 case ISD::FDIV: return LowerFDIV(Op, DAG); 4492 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4493 case ISD::STORE: return LowerSTORE(Op, DAG); 4494 case ISD::GlobalAddress: { 4495 MachineFunction &MF = DAG.getMachineFunction(); 4496 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4497 return LowerGlobalAddress(MFI, Op, DAG); 4498 } 4499 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4500 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4501 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4502 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4503 case ISD::INSERT_SUBVECTOR: 4504 return lowerINSERT_SUBVECTOR(Op, DAG); 4505 case ISD::INSERT_VECTOR_ELT: 4506 return lowerINSERT_VECTOR_ELT(Op, DAG); 4507 case ISD::EXTRACT_VECTOR_ELT: 4508 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4509 case ISD::VECTOR_SHUFFLE: 4510 return lowerVECTOR_SHUFFLE(Op, DAG); 4511 case ISD::BUILD_VECTOR: 4512 return lowerBUILD_VECTOR(Op, DAG); 4513 case ISD::FP_ROUND: 4514 return lowerFP_ROUND(Op, DAG); 4515 case ISD::TRAP: 4516 return lowerTRAP(Op, DAG); 4517 case ISD::DEBUGTRAP: 4518 return lowerDEBUGTRAP(Op, DAG); 4519 case ISD::FABS: 4520 case ISD::FNEG: 4521 case ISD::FCANONICALIZE: 4522 case ISD::BSWAP: 4523 return splitUnaryVectorOp(Op, DAG); 4524 case ISD::FMINNUM: 4525 case ISD::FMAXNUM: 4526 return lowerFMINNUM_FMAXNUM(Op, DAG); 4527 case ISD::FMA: 4528 return splitTernaryVectorOp(Op, DAG); 4529 case ISD::SHL: 4530 case ISD::SRA: 4531 case ISD::SRL: 4532 case ISD::ADD: 4533 case ISD::SUB: 4534 case ISD::MUL: 4535 case ISD::SMIN: 4536 case ISD::SMAX: 4537 case ISD::UMIN: 4538 case ISD::UMAX: 4539 case ISD::FADD: 4540 case ISD::FMUL: 4541 case ISD::FMINNUM_IEEE: 4542 case ISD::FMAXNUM_IEEE: 4543 case ISD::UADDSAT: 4544 case ISD::USUBSAT: 4545 case ISD::SADDSAT: 4546 case ISD::SSUBSAT: 4547 return splitBinaryVectorOp(Op, DAG); 4548 case ISD::SMULO: 4549 case ISD::UMULO: 4550 return lowerXMULO(Op, DAG); 4551 case ISD::DYNAMIC_STACKALLOC: 4552 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4553 } 4554 return SDValue(); 4555 } 4556 4557 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4558 const SDLoc &DL, 4559 SelectionDAG &DAG, bool Unpacked) { 4560 if (!LoadVT.isVector()) 4561 return Result; 4562 4563 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4564 // Truncate to v2i16/v4i16. 4565 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4566 4567 // Workaround legalizer not scalarizing truncate after vector op 4568 // legalization but not creating intermediate vector trunc. 4569 SmallVector<SDValue, 4> Elts; 4570 DAG.ExtractVectorElements(Result, Elts); 4571 for (SDValue &Elt : Elts) 4572 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4573 4574 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4575 4576 // Bitcast to original type (v2f16/v4f16). 4577 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4578 } 4579 4580 // Cast back to the original packed type. 4581 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4582 } 4583 4584 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4585 MemSDNode *M, 4586 SelectionDAG &DAG, 4587 ArrayRef<SDValue> Ops, 4588 bool IsIntrinsic) const { 4589 SDLoc DL(M); 4590 4591 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4592 EVT LoadVT = M->getValueType(0); 4593 4594 EVT EquivLoadVT = LoadVT; 4595 if (Unpacked && LoadVT.isVector()) { 4596 EquivLoadVT = LoadVT.isVector() ? 4597 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4598 LoadVT.getVectorNumElements()) : LoadVT; 4599 } 4600 4601 // Change from v4f16/v2f16 to EquivLoadVT. 4602 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4603 4604 SDValue Load 4605 = DAG.getMemIntrinsicNode( 4606 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4607 VTList, Ops, M->getMemoryVT(), 4608 M->getMemOperand()); 4609 if (!Unpacked) // Just adjusted the opcode. 4610 return Load; 4611 4612 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4613 4614 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4615 } 4616 4617 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4618 SelectionDAG &DAG, 4619 ArrayRef<SDValue> Ops) const { 4620 SDLoc DL(M); 4621 EVT LoadVT = M->getValueType(0); 4622 EVT EltType = LoadVT.getScalarType(); 4623 EVT IntVT = LoadVT.changeTypeToInteger(); 4624 4625 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4626 4627 unsigned Opc = 4628 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4629 4630 if (IsD16) { 4631 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4632 } 4633 4634 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4635 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4636 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4637 4638 if (isTypeLegal(LoadVT)) { 4639 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4640 M->getMemOperand(), DAG); 4641 } 4642 4643 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4644 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4645 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4646 M->getMemOperand(), DAG); 4647 return DAG.getMergeValues( 4648 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4649 DL); 4650 } 4651 4652 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4653 SDNode *N, SelectionDAG &DAG) { 4654 EVT VT = N->getValueType(0); 4655 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4656 unsigned CondCode = CD->getZExtValue(); 4657 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4658 return DAG.getUNDEF(VT); 4659 4660 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4661 4662 SDValue LHS = N->getOperand(1); 4663 SDValue RHS = N->getOperand(2); 4664 4665 SDLoc DL(N); 4666 4667 EVT CmpVT = LHS.getValueType(); 4668 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4669 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4670 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4671 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4672 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4673 } 4674 4675 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4676 4677 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4678 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4679 4680 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4681 DAG.getCondCode(CCOpcode)); 4682 if (VT.bitsEq(CCVT)) 4683 return SetCC; 4684 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4685 } 4686 4687 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4688 SDNode *N, SelectionDAG &DAG) { 4689 EVT VT = N->getValueType(0); 4690 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4691 4692 unsigned CondCode = CD->getZExtValue(); 4693 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4694 return DAG.getUNDEF(VT); 4695 4696 SDValue Src0 = N->getOperand(1); 4697 SDValue Src1 = N->getOperand(2); 4698 EVT CmpVT = Src0.getValueType(); 4699 SDLoc SL(N); 4700 4701 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4702 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4703 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4704 } 4705 4706 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4707 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4708 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4709 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4710 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4711 Src1, DAG.getCondCode(CCOpcode)); 4712 if (VT.bitsEq(CCVT)) 4713 return SetCC; 4714 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4715 } 4716 4717 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4718 SelectionDAG &DAG) { 4719 EVT VT = N->getValueType(0); 4720 SDValue Src = N->getOperand(1); 4721 SDLoc SL(N); 4722 4723 if (Src.getOpcode() == ISD::SETCC) { 4724 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4725 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4726 Src.getOperand(1), Src.getOperand(2)); 4727 } 4728 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4729 // (ballot 0) -> 0 4730 if (Arg->isNullValue()) 4731 return DAG.getConstant(0, SL, VT); 4732 4733 // (ballot 1) -> EXEC/EXEC_LO 4734 if (Arg->isOne()) { 4735 Register Exec; 4736 if (VT.getScalarSizeInBits() == 32) 4737 Exec = AMDGPU::EXEC_LO; 4738 else if (VT.getScalarSizeInBits() == 64) 4739 Exec = AMDGPU::EXEC; 4740 else 4741 return SDValue(); 4742 4743 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4744 } 4745 } 4746 4747 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4748 // ISD::SETNE) 4749 return DAG.getNode( 4750 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4751 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4752 } 4753 4754 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4755 SmallVectorImpl<SDValue> &Results, 4756 SelectionDAG &DAG) const { 4757 switch (N->getOpcode()) { 4758 case ISD::INSERT_VECTOR_ELT: { 4759 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4760 Results.push_back(Res); 4761 return; 4762 } 4763 case ISD::EXTRACT_VECTOR_ELT: { 4764 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4765 Results.push_back(Res); 4766 return; 4767 } 4768 case ISD::INTRINSIC_WO_CHAIN: { 4769 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4770 switch (IID) { 4771 case Intrinsic::amdgcn_cvt_pkrtz: { 4772 SDValue Src0 = N->getOperand(1); 4773 SDValue Src1 = N->getOperand(2); 4774 SDLoc SL(N); 4775 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4776 Src0, Src1); 4777 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4778 return; 4779 } 4780 case Intrinsic::amdgcn_cvt_pknorm_i16: 4781 case Intrinsic::amdgcn_cvt_pknorm_u16: 4782 case Intrinsic::amdgcn_cvt_pk_i16: 4783 case Intrinsic::amdgcn_cvt_pk_u16: { 4784 SDValue Src0 = N->getOperand(1); 4785 SDValue Src1 = N->getOperand(2); 4786 SDLoc SL(N); 4787 unsigned Opcode; 4788 4789 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4790 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4791 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4792 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4793 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4794 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4795 else 4796 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4797 4798 EVT VT = N->getValueType(0); 4799 if (isTypeLegal(VT)) 4800 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4801 else { 4802 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4803 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4804 } 4805 return; 4806 } 4807 } 4808 break; 4809 } 4810 case ISD::INTRINSIC_W_CHAIN: { 4811 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4812 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4813 // FIXME: Hacky 4814 Results.push_back(Res.getOperand(0)); 4815 Results.push_back(Res.getOperand(1)); 4816 } else { 4817 Results.push_back(Res); 4818 Results.push_back(Res.getValue(1)); 4819 } 4820 return; 4821 } 4822 4823 break; 4824 } 4825 case ISD::SELECT: { 4826 SDLoc SL(N); 4827 EVT VT = N->getValueType(0); 4828 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4829 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4830 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4831 4832 EVT SelectVT = NewVT; 4833 if (NewVT.bitsLT(MVT::i32)) { 4834 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4835 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4836 SelectVT = MVT::i32; 4837 } 4838 4839 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4840 N->getOperand(0), LHS, RHS); 4841 4842 if (NewVT != SelectVT) 4843 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4844 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4845 return; 4846 } 4847 case ISD::FNEG: { 4848 if (N->getValueType(0) != MVT::v2f16) 4849 break; 4850 4851 SDLoc SL(N); 4852 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4853 4854 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4855 BC, 4856 DAG.getConstant(0x80008000, SL, MVT::i32)); 4857 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4858 return; 4859 } 4860 case ISD::FABS: { 4861 if (N->getValueType(0) != MVT::v2f16) 4862 break; 4863 4864 SDLoc SL(N); 4865 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4866 4867 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4868 BC, 4869 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4870 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4871 return; 4872 } 4873 default: 4874 break; 4875 } 4876 } 4877 4878 /// Helper function for LowerBRCOND 4879 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4880 4881 SDNode *Parent = Value.getNode(); 4882 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4883 I != E; ++I) { 4884 4885 if (I.getUse().get() != Value) 4886 continue; 4887 4888 if (I->getOpcode() == Opcode) 4889 return *I; 4890 } 4891 return nullptr; 4892 } 4893 4894 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4895 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4896 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4897 case Intrinsic::amdgcn_if: 4898 return AMDGPUISD::IF; 4899 case Intrinsic::amdgcn_else: 4900 return AMDGPUISD::ELSE; 4901 case Intrinsic::amdgcn_loop: 4902 return AMDGPUISD::LOOP; 4903 case Intrinsic::amdgcn_end_cf: 4904 llvm_unreachable("should not occur"); 4905 default: 4906 return 0; 4907 } 4908 } 4909 4910 // break, if_break, else_break are all only used as inputs to loop, not 4911 // directly as branch conditions. 4912 return 0; 4913 } 4914 4915 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4916 const Triple &TT = getTargetMachine().getTargetTriple(); 4917 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4918 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4919 AMDGPU::shouldEmitConstantsToTextSection(TT); 4920 } 4921 4922 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4923 // FIXME: Either avoid relying on address space here or change the default 4924 // address space for functions to avoid the explicit check. 4925 return (GV->getValueType()->isFunctionTy() || 4926 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4927 !shouldEmitFixup(GV) && 4928 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4929 } 4930 4931 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4932 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4933 } 4934 4935 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4936 if (!GV->hasExternalLinkage()) 4937 return true; 4938 4939 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4940 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4941 } 4942 4943 /// This transforms the control flow intrinsics to get the branch destination as 4944 /// last parameter, also switches branch target with BR if the need arise 4945 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4946 SelectionDAG &DAG) const { 4947 SDLoc DL(BRCOND); 4948 4949 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4950 SDValue Target = BRCOND.getOperand(2); 4951 SDNode *BR = nullptr; 4952 SDNode *SetCC = nullptr; 4953 4954 if (Intr->getOpcode() == ISD::SETCC) { 4955 // As long as we negate the condition everything is fine 4956 SetCC = Intr; 4957 Intr = SetCC->getOperand(0).getNode(); 4958 4959 } else { 4960 // Get the target from BR if we don't negate the condition 4961 BR = findUser(BRCOND, ISD::BR); 4962 assert(BR && "brcond missing unconditional branch user"); 4963 Target = BR->getOperand(1); 4964 } 4965 4966 unsigned CFNode = isCFIntrinsic(Intr); 4967 if (CFNode == 0) { 4968 // This is a uniform branch so we don't need to legalize. 4969 return BRCOND; 4970 } 4971 4972 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4973 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4974 4975 assert(!SetCC || 4976 (SetCC->getConstantOperandVal(1) == 1 && 4977 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4978 ISD::SETNE)); 4979 4980 // operands of the new intrinsic call 4981 SmallVector<SDValue, 4> Ops; 4982 if (HaveChain) 4983 Ops.push_back(BRCOND.getOperand(0)); 4984 4985 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4986 Ops.push_back(Target); 4987 4988 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4989 4990 // build the new intrinsic call 4991 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4992 4993 if (!HaveChain) { 4994 SDValue Ops[] = { 4995 SDValue(Result, 0), 4996 BRCOND.getOperand(0) 4997 }; 4998 4999 Result = DAG.getMergeValues(Ops, DL).getNode(); 5000 } 5001 5002 if (BR) { 5003 // Give the branch instruction our target 5004 SDValue Ops[] = { 5005 BR->getOperand(0), 5006 BRCOND.getOperand(2) 5007 }; 5008 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5009 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5010 } 5011 5012 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5013 5014 // Copy the intrinsic results to registers 5015 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5016 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5017 if (!CopyToReg) 5018 continue; 5019 5020 Chain = DAG.getCopyToReg( 5021 Chain, DL, 5022 CopyToReg->getOperand(1), 5023 SDValue(Result, i - 1), 5024 SDValue()); 5025 5026 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5027 } 5028 5029 // Remove the old intrinsic from the chain 5030 DAG.ReplaceAllUsesOfValueWith( 5031 SDValue(Intr, Intr->getNumValues() - 1), 5032 Intr->getOperand(0)); 5033 5034 return Chain; 5035 } 5036 5037 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5038 SelectionDAG &DAG) const { 5039 MVT VT = Op.getSimpleValueType(); 5040 SDLoc DL(Op); 5041 // Checking the depth 5042 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5043 return DAG.getConstant(0, DL, VT); 5044 5045 MachineFunction &MF = DAG.getMachineFunction(); 5046 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5047 // Check for kernel and shader functions 5048 if (Info->isEntryFunction()) 5049 return DAG.getConstant(0, DL, VT); 5050 5051 MachineFrameInfo &MFI = MF.getFrameInfo(); 5052 // There is a call to @llvm.returnaddress in this function 5053 MFI.setReturnAddressIsTaken(true); 5054 5055 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5056 // Get the return address reg and mark it as an implicit live-in 5057 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5058 5059 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5060 } 5061 5062 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5063 SDValue Op, 5064 const SDLoc &DL, 5065 EVT VT) const { 5066 return Op.getValueType().bitsLE(VT) ? 5067 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5068 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5069 DAG.getTargetConstant(0, DL, MVT::i32)); 5070 } 5071 5072 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5073 assert(Op.getValueType() == MVT::f16 && 5074 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5075 5076 SDValue Src = Op.getOperand(0); 5077 EVT SrcVT = Src.getValueType(); 5078 if (SrcVT != MVT::f64) 5079 return Op; 5080 5081 SDLoc DL(Op); 5082 5083 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5084 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5085 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5086 } 5087 5088 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5089 SelectionDAG &DAG) const { 5090 EVT VT = Op.getValueType(); 5091 const MachineFunction &MF = DAG.getMachineFunction(); 5092 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5093 bool IsIEEEMode = Info->getMode().IEEE; 5094 5095 // FIXME: Assert during selection that this is only selected for 5096 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5097 // mode functions, but this happens to be OK since it's only done in cases 5098 // where there is known no sNaN. 5099 if (IsIEEEMode) 5100 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5101 5102 if (VT == MVT::v4f16) 5103 return splitBinaryVectorOp(Op, DAG); 5104 return Op; 5105 } 5106 5107 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5108 EVT VT = Op.getValueType(); 5109 SDLoc SL(Op); 5110 SDValue LHS = Op.getOperand(0); 5111 SDValue RHS = Op.getOperand(1); 5112 bool isSigned = Op.getOpcode() == ISD::SMULO; 5113 5114 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5115 const APInt &C = RHSC->getAPIntValue(); 5116 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5117 if (C.isPowerOf2()) { 5118 // smulo(x, signed_min) is same as umulo(x, signed_min). 5119 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5120 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5121 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5122 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5123 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5124 SL, VT, Result, ShiftAmt), 5125 LHS, ISD::SETNE); 5126 return DAG.getMergeValues({ Result, Overflow }, SL); 5127 } 5128 } 5129 5130 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5131 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5132 SL, VT, LHS, RHS); 5133 5134 SDValue Sign = isSigned 5135 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5136 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5137 : DAG.getConstant(0, SL, VT); 5138 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5139 5140 return DAG.getMergeValues({ Result, Overflow }, SL); 5141 } 5142 5143 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5144 SDLoc SL(Op); 5145 SDValue Chain = Op.getOperand(0); 5146 5147 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5148 !Subtarget->isTrapHandlerEnabled()) 5149 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5150 5151 MachineFunction &MF = DAG.getMachineFunction(); 5152 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5153 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5154 assert(UserSGPR != AMDGPU::NoRegister); 5155 SDValue QueuePtr = CreateLiveInRegister( 5156 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5157 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5158 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5159 QueuePtr, SDValue()); 5160 SDValue Ops[] = { 5161 ToReg, 5162 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 5163 SGPR01, 5164 ToReg.getValue(1) 5165 }; 5166 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5167 } 5168 5169 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5170 SDLoc SL(Op); 5171 SDValue Chain = Op.getOperand(0); 5172 MachineFunction &MF = DAG.getMachineFunction(); 5173 5174 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5175 !Subtarget->isTrapHandlerEnabled()) { 5176 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5177 "debugtrap handler not supported", 5178 Op.getDebugLoc(), 5179 DS_Warning); 5180 LLVMContext &Ctx = MF.getFunction().getContext(); 5181 Ctx.diagnose(NoTrap); 5182 return Chain; 5183 } 5184 5185 SDValue Ops[] = { 5186 Chain, 5187 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 5188 }; 5189 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5190 } 5191 5192 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5193 SelectionDAG &DAG) const { 5194 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5195 if (Subtarget->hasApertureRegs()) { 5196 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5197 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5198 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5199 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5200 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5201 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5202 unsigned Encoding = 5203 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5204 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5205 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5206 5207 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5208 SDValue ApertureReg = SDValue( 5209 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5210 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5211 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5212 } 5213 5214 MachineFunction &MF = DAG.getMachineFunction(); 5215 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5216 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5217 assert(UserSGPR != AMDGPU::NoRegister); 5218 5219 SDValue QueuePtr = CreateLiveInRegister( 5220 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5221 5222 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5223 // private_segment_aperture_base_hi. 5224 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5225 5226 SDValue Ptr = 5227 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5228 5229 // TODO: Use custom target PseudoSourceValue. 5230 // TODO: We should use the value from the IR intrinsic call, but it might not 5231 // be available and how do we get it? 5232 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5233 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5234 MinAlign(64, StructOffset), 5235 MachineMemOperand::MODereferenceable | 5236 MachineMemOperand::MOInvariant); 5237 } 5238 5239 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5240 SelectionDAG &DAG) const { 5241 SDLoc SL(Op); 5242 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5243 5244 SDValue Src = ASC->getOperand(0); 5245 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5246 5247 const AMDGPUTargetMachine &TM = 5248 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5249 5250 // flat -> local/private 5251 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5252 unsigned DestAS = ASC->getDestAddressSpace(); 5253 5254 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5255 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5256 unsigned NullVal = TM.getNullPointerValue(DestAS); 5257 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5258 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5259 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5260 5261 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5262 NonNull, Ptr, SegmentNullPtr); 5263 } 5264 } 5265 5266 // local/private -> flat 5267 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5268 unsigned SrcAS = ASC->getSrcAddressSpace(); 5269 5270 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5271 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5272 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5273 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5274 5275 SDValue NonNull 5276 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5277 5278 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5279 SDValue CvtPtr 5280 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5281 5282 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5283 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5284 FlatNullPtr); 5285 } 5286 } 5287 5288 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5289 Src.getValueType() == MVT::i64) 5290 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5291 5292 // global <-> flat are no-ops and never emitted. 5293 5294 const MachineFunction &MF = DAG.getMachineFunction(); 5295 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5296 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5297 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5298 5299 return DAG.getUNDEF(ASC->getValueType(0)); 5300 } 5301 5302 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5303 // the small vector and inserting them into the big vector. That is better than 5304 // the default expansion of doing it via a stack slot. Even though the use of 5305 // the stack slot would be optimized away afterwards, the stack slot itself 5306 // remains. 5307 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5308 SelectionDAG &DAG) const { 5309 SDValue Vec = Op.getOperand(0); 5310 SDValue Ins = Op.getOperand(1); 5311 SDValue Idx = Op.getOperand(2); 5312 EVT VecVT = Vec.getValueType(); 5313 EVT InsVT = Ins.getValueType(); 5314 EVT EltVT = VecVT.getVectorElementType(); 5315 unsigned InsNumElts = InsVT.getVectorNumElements(); 5316 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5317 SDLoc SL(Op); 5318 5319 for (unsigned I = 0; I != InsNumElts; ++I) { 5320 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5321 DAG.getConstant(I, SL, MVT::i32)); 5322 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5323 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5324 } 5325 return Vec; 5326 } 5327 5328 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5329 SelectionDAG &DAG) const { 5330 SDValue Vec = Op.getOperand(0); 5331 SDValue InsVal = Op.getOperand(1); 5332 SDValue Idx = Op.getOperand(2); 5333 EVT VecVT = Vec.getValueType(); 5334 EVT EltVT = VecVT.getVectorElementType(); 5335 unsigned VecSize = VecVT.getSizeInBits(); 5336 unsigned EltSize = EltVT.getSizeInBits(); 5337 5338 5339 assert(VecSize <= 64); 5340 5341 unsigned NumElts = VecVT.getVectorNumElements(); 5342 SDLoc SL(Op); 5343 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5344 5345 if (NumElts == 4 && EltSize == 16 && KIdx) { 5346 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5347 5348 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5349 DAG.getConstant(0, SL, MVT::i32)); 5350 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5351 DAG.getConstant(1, SL, MVT::i32)); 5352 5353 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5354 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5355 5356 unsigned Idx = KIdx->getZExtValue(); 5357 bool InsertLo = Idx < 2; 5358 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5359 InsertLo ? LoVec : HiVec, 5360 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5361 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5362 5363 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5364 5365 SDValue Concat = InsertLo ? 5366 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5367 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5368 5369 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5370 } 5371 5372 if (isa<ConstantSDNode>(Idx)) 5373 return SDValue(); 5374 5375 MVT IntVT = MVT::getIntegerVT(VecSize); 5376 5377 // Avoid stack access for dynamic indexing. 5378 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5379 5380 // Create a congruent vector with the target value in each element so that 5381 // the required element can be masked and ORed into the target vector. 5382 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5383 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5384 5385 assert(isPowerOf2_32(EltSize)); 5386 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5387 5388 // Convert vector index to bit-index. 5389 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5390 5391 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5392 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5393 DAG.getConstant(0xffff, SL, IntVT), 5394 ScaledIdx); 5395 5396 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5397 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5398 DAG.getNOT(SL, BFM, IntVT), BCVec); 5399 5400 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5401 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5402 } 5403 5404 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5405 SelectionDAG &DAG) const { 5406 SDLoc SL(Op); 5407 5408 EVT ResultVT = Op.getValueType(); 5409 SDValue Vec = Op.getOperand(0); 5410 SDValue Idx = Op.getOperand(1); 5411 EVT VecVT = Vec.getValueType(); 5412 unsigned VecSize = VecVT.getSizeInBits(); 5413 EVT EltVT = VecVT.getVectorElementType(); 5414 assert(VecSize <= 64); 5415 5416 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5417 5418 // Make sure we do any optimizations that will make it easier to fold 5419 // source modifiers before obscuring it with bit operations. 5420 5421 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5422 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5423 return Combined; 5424 5425 unsigned EltSize = EltVT.getSizeInBits(); 5426 assert(isPowerOf2_32(EltSize)); 5427 5428 MVT IntVT = MVT::getIntegerVT(VecSize); 5429 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5430 5431 // Convert vector index to bit-index (* EltSize) 5432 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5433 5434 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5435 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5436 5437 if (ResultVT == MVT::f16) { 5438 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5439 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5440 } 5441 5442 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5443 } 5444 5445 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5446 assert(Elt % 2 == 0); 5447 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5448 } 5449 5450 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5451 SelectionDAG &DAG) const { 5452 SDLoc SL(Op); 5453 EVT ResultVT = Op.getValueType(); 5454 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5455 5456 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5457 EVT EltVT = PackVT.getVectorElementType(); 5458 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5459 5460 // vector_shuffle <0,1,6,7> lhs, rhs 5461 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5462 // 5463 // vector_shuffle <6,7,2,3> lhs, rhs 5464 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5465 // 5466 // vector_shuffle <6,7,0,1> lhs, rhs 5467 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5468 5469 // Avoid scalarizing when both halves are reading from consecutive elements. 5470 SmallVector<SDValue, 4> Pieces; 5471 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5472 if (elementPairIsContiguous(SVN->getMask(), I)) { 5473 const int Idx = SVN->getMaskElt(I); 5474 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5475 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5476 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5477 PackVT, SVN->getOperand(VecIdx), 5478 DAG.getConstant(EltIdx, SL, MVT::i32)); 5479 Pieces.push_back(SubVec); 5480 } else { 5481 const int Idx0 = SVN->getMaskElt(I); 5482 const int Idx1 = SVN->getMaskElt(I + 1); 5483 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5484 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5485 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5486 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5487 5488 SDValue Vec0 = SVN->getOperand(VecIdx0); 5489 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5490 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5491 5492 SDValue Vec1 = SVN->getOperand(VecIdx1); 5493 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5494 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5495 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5496 } 5497 } 5498 5499 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5500 } 5501 5502 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5503 SelectionDAG &DAG) const { 5504 SDLoc SL(Op); 5505 EVT VT = Op.getValueType(); 5506 5507 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5508 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5509 5510 // Turn into pair of packed build_vectors. 5511 // TODO: Special case for constants that can be materialized with s_mov_b64. 5512 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5513 { Op.getOperand(0), Op.getOperand(1) }); 5514 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5515 { Op.getOperand(2), Op.getOperand(3) }); 5516 5517 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5518 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5519 5520 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5521 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5522 } 5523 5524 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5525 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5526 5527 SDValue Lo = Op.getOperand(0); 5528 SDValue Hi = Op.getOperand(1); 5529 5530 // Avoid adding defined bits with the zero_extend. 5531 if (Hi.isUndef()) { 5532 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5533 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5534 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5535 } 5536 5537 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5538 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5539 5540 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5541 DAG.getConstant(16, SL, MVT::i32)); 5542 if (Lo.isUndef()) 5543 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5544 5545 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5546 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5547 5548 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5549 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5550 } 5551 5552 bool 5553 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5554 // We can fold offsets for anything that doesn't require a GOT relocation. 5555 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5556 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5557 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5558 !shouldEmitGOTReloc(GA->getGlobal()); 5559 } 5560 5561 static SDValue 5562 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5563 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5564 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5565 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5566 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5567 // lowered to the following code sequence: 5568 // 5569 // For constant address space: 5570 // s_getpc_b64 s[0:1] 5571 // s_add_u32 s0, s0, $symbol 5572 // s_addc_u32 s1, s1, 0 5573 // 5574 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5575 // a fixup or relocation is emitted to replace $symbol with a literal 5576 // constant, which is a pc-relative offset from the encoding of the $symbol 5577 // operand to the global variable. 5578 // 5579 // For global address space: 5580 // s_getpc_b64 s[0:1] 5581 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5582 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5583 // 5584 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5585 // fixups or relocations are emitted to replace $symbol@*@lo and 5586 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5587 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5588 // operand to the global variable. 5589 // 5590 // What we want here is an offset from the value returned by s_getpc 5591 // (which is the address of the s_add_u32 instruction) to the global 5592 // variable, but since the encoding of $symbol starts 4 bytes after the start 5593 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5594 // small. This requires us to add 4 to the global variable offset in order to 5595 // compute the correct address. 5596 SDValue PtrLo = 5597 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5598 SDValue PtrHi; 5599 if (GAFlags == SIInstrInfo::MO_NONE) { 5600 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5601 } else { 5602 PtrHi = 5603 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5604 } 5605 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5606 } 5607 5608 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5609 SDValue Op, 5610 SelectionDAG &DAG) const { 5611 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5612 SDLoc DL(GSD); 5613 EVT PtrVT = Op.getValueType(); 5614 5615 const GlobalValue *GV = GSD->getGlobal(); 5616 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5617 shouldUseLDSConstAddress(GV)) || 5618 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5619 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5620 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5621 GV->hasExternalLinkage()) { 5622 Type *Ty = GV->getValueType(); 5623 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5624 // zero-sized type in other languages to declare the dynamic shared 5625 // memory which size is not known at the compile time. They will be 5626 // allocated by the runtime and placed directly after the static 5627 // allocated ones. They all share the same offset. 5628 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5629 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5630 // Adjust alignment for that dynamic shared memory array. 5631 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5632 return SDValue( 5633 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5634 } 5635 } 5636 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5637 } 5638 5639 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5640 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5641 SIInstrInfo::MO_ABS32_LO); 5642 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5643 } 5644 5645 if (shouldEmitFixup(GV)) 5646 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5647 else if (shouldEmitPCReloc(GV)) 5648 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5649 SIInstrInfo::MO_REL32); 5650 5651 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5652 SIInstrInfo::MO_GOTPCREL32); 5653 5654 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5655 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5656 const DataLayout &DataLayout = DAG.getDataLayout(); 5657 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5658 MachinePointerInfo PtrInfo 5659 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5660 5661 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5662 MachineMemOperand::MODereferenceable | 5663 MachineMemOperand::MOInvariant); 5664 } 5665 5666 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5667 const SDLoc &DL, SDValue V) const { 5668 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5669 // the destination register. 5670 // 5671 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5672 // so we will end up with redundant moves to m0. 5673 // 5674 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5675 5676 // A Null SDValue creates a glue result. 5677 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5678 V, Chain); 5679 return SDValue(M0, 0); 5680 } 5681 5682 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5683 SDValue Op, 5684 MVT VT, 5685 unsigned Offset) const { 5686 SDLoc SL(Op); 5687 SDValue Param = lowerKernargMemParameter( 5688 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5689 // The local size values will have the hi 16-bits as zero. 5690 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5691 DAG.getValueType(VT)); 5692 } 5693 5694 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5695 EVT VT) { 5696 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5697 "non-hsa intrinsic with hsa target", 5698 DL.getDebugLoc()); 5699 DAG.getContext()->diagnose(BadIntrin); 5700 return DAG.getUNDEF(VT); 5701 } 5702 5703 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5704 EVT VT) { 5705 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5706 "intrinsic not supported on subtarget", 5707 DL.getDebugLoc()); 5708 DAG.getContext()->diagnose(BadIntrin); 5709 return DAG.getUNDEF(VT); 5710 } 5711 5712 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5713 ArrayRef<SDValue> Elts) { 5714 assert(!Elts.empty()); 5715 MVT Type; 5716 unsigned NumElts; 5717 5718 if (Elts.size() == 1) { 5719 Type = MVT::f32; 5720 NumElts = 1; 5721 } else if (Elts.size() == 2) { 5722 Type = MVT::v2f32; 5723 NumElts = 2; 5724 } else if (Elts.size() == 3) { 5725 Type = MVT::v3f32; 5726 NumElts = 3; 5727 } else if (Elts.size() <= 4) { 5728 Type = MVT::v4f32; 5729 NumElts = 4; 5730 } else if (Elts.size() <= 8) { 5731 Type = MVT::v8f32; 5732 NumElts = 8; 5733 } else { 5734 assert(Elts.size() <= 16); 5735 Type = MVT::v16f32; 5736 NumElts = 16; 5737 } 5738 5739 SmallVector<SDValue, 16> VecElts(NumElts); 5740 for (unsigned i = 0; i < Elts.size(); ++i) { 5741 SDValue Elt = Elts[i]; 5742 if (Elt.getValueType() != MVT::f32) 5743 Elt = DAG.getBitcast(MVT::f32, Elt); 5744 VecElts[i] = Elt; 5745 } 5746 for (unsigned i = Elts.size(); i < NumElts; ++i) 5747 VecElts[i] = DAG.getUNDEF(MVT::f32); 5748 5749 if (NumElts == 1) 5750 return VecElts[0]; 5751 return DAG.getBuildVector(Type, DL, VecElts); 5752 } 5753 5754 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5755 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5756 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5757 5758 uint64_t Value = CachePolicyConst->getZExtValue(); 5759 SDLoc DL(CachePolicy); 5760 if (GLC) { 5761 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5762 Value &= ~(uint64_t)0x1; 5763 } 5764 if (SLC) { 5765 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5766 Value &= ~(uint64_t)0x2; 5767 } 5768 if (DLC) { 5769 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5770 Value &= ~(uint64_t)0x4; 5771 } 5772 5773 return Value == 0; 5774 } 5775 5776 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5777 SDValue Src, int ExtraElts) { 5778 EVT SrcVT = Src.getValueType(); 5779 5780 SmallVector<SDValue, 8> Elts; 5781 5782 if (SrcVT.isVector()) 5783 DAG.ExtractVectorElements(Src, Elts); 5784 else 5785 Elts.push_back(Src); 5786 5787 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5788 while (ExtraElts--) 5789 Elts.push_back(Undef); 5790 5791 return DAG.getBuildVector(CastVT, DL, Elts); 5792 } 5793 5794 // Re-construct the required return value for a image load intrinsic. 5795 // This is more complicated due to the optional use TexFailCtrl which means the required 5796 // return type is an aggregate 5797 static SDValue constructRetValue(SelectionDAG &DAG, 5798 MachineSDNode *Result, 5799 ArrayRef<EVT> ResultTypes, 5800 bool IsTexFail, bool Unpacked, bool IsD16, 5801 int DMaskPop, int NumVDataDwords, 5802 const SDLoc &DL, LLVMContext &Context) { 5803 // Determine the required return type. This is the same regardless of IsTexFail flag 5804 EVT ReqRetVT = ResultTypes[0]; 5805 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5806 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5807 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5808 5809 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5810 DMaskPop : (DMaskPop + 1) / 2; 5811 5812 MVT DataDwordVT = NumDataDwords == 1 ? 5813 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5814 5815 MVT MaskPopVT = MaskPopDwords == 1 ? 5816 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5817 5818 SDValue Data(Result, 0); 5819 SDValue TexFail; 5820 5821 if (IsTexFail) { 5822 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5823 if (MaskPopVT.isVector()) { 5824 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5825 SDValue(Result, 0), ZeroIdx); 5826 } else { 5827 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5828 SDValue(Result, 0), ZeroIdx); 5829 } 5830 5831 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5832 SDValue(Result, 0), 5833 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5834 } 5835 5836 if (DataDwordVT.isVector()) 5837 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5838 NumDataDwords - MaskPopDwords); 5839 5840 if (IsD16) 5841 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5842 5843 if (!ReqRetVT.isVector()) 5844 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5845 5846 Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data); 5847 5848 if (TexFail) 5849 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5850 5851 if (Result->getNumValues() == 1) 5852 return Data; 5853 5854 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5855 } 5856 5857 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5858 SDValue *LWE, bool &IsTexFail) { 5859 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5860 5861 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5862 if (Value) { 5863 IsTexFail = true; 5864 } 5865 5866 SDLoc DL(TexFailCtrlConst); 5867 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5868 Value &= ~(uint64_t)0x1; 5869 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5870 Value &= ~(uint64_t)0x2; 5871 5872 return Value == 0; 5873 } 5874 5875 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5876 MVT PackVectorVT, 5877 SmallVectorImpl<SDValue> &PackedAddrs, 5878 unsigned DimIdx, unsigned EndIdx, 5879 unsigned NumGradients) { 5880 SDLoc DL(Op); 5881 for (unsigned I = DimIdx; I < EndIdx; I++) { 5882 SDValue Addr = Op.getOperand(I); 5883 5884 // Gradients are packed with undef for each coordinate. 5885 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5886 // 1D: undef,dx/dh; undef,dx/dv 5887 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5888 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5889 if (((I + 1) >= EndIdx) || 5890 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5891 I == DimIdx + NumGradients - 1))) { 5892 if (Addr.getValueType() != MVT::i16) 5893 Addr = DAG.getBitcast(MVT::i16, Addr); 5894 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5895 } else { 5896 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5897 I++; 5898 } 5899 Addr = DAG.getBitcast(MVT::f32, Addr); 5900 PackedAddrs.push_back(Addr); 5901 } 5902 } 5903 5904 SDValue SITargetLowering::lowerImage(SDValue Op, 5905 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5906 SelectionDAG &DAG) const { 5907 SDLoc DL(Op); 5908 MachineFunction &MF = DAG.getMachineFunction(); 5909 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5910 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5911 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5912 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5913 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5914 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5915 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5916 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5917 unsigned IntrOpcode = Intr->BaseOpcode; 5918 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5919 5920 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5921 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5922 bool IsD16 = false; 5923 bool IsG16 = false; 5924 bool IsA16 = false; 5925 SDValue VData; 5926 int NumVDataDwords; 5927 bool AdjustRetType = false; 5928 5929 unsigned AddrIdx; // Index of first address argument 5930 unsigned DMask; 5931 unsigned DMaskLanes = 0; 5932 5933 if (BaseOpcode->Atomic) { 5934 VData = Op.getOperand(2); 5935 5936 bool Is64Bit = VData.getValueType() == MVT::i64; 5937 if (BaseOpcode->AtomicX2) { 5938 SDValue VData2 = Op.getOperand(3); 5939 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5940 {VData, VData2}); 5941 if (Is64Bit) 5942 VData = DAG.getBitcast(MVT::v4i32, VData); 5943 5944 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5945 DMask = Is64Bit ? 0xf : 0x3; 5946 NumVDataDwords = Is64Bit ? 4 : 2; 5947 AddrIdx = 4; 5948 } else { 5949 DMask = Is64Bit ? 0x3 : 0x1; 5950 NumVDataDwords = Is64Bit ? 2 : 1; 5951 AddrIdx = 3; 5952 } 5953 } else { 5954 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5955 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5956 DMask = DMaskConst->getZExtValue(); 5957 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5958 5959 if (BaseOpcode->Store) { 5960 VData = Op.getOperand(2); 5961 5962 MVT StoreVT = VData.getSimpleValueType(); 5963 if (StoreVT.getScalarType() == MVT::f16) { 5964 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5965 return Op; // D16 is unsupported for this instruction 5966 5967 IsD16 = true; 5968 VData = handleD16VData(VData, DAG); 5969 } 5970 5971 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5972 } else { 5973 // Work out the num dwords based on the dmask popcount and underlying type 5974 // and whether packing is supported. 5975 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5976 if (LoadVT.getScalarType() == MVT::f16) { 5977 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5978 return Op; // D16 is unsupported for this instruction 5979 5980 IsD16 = true; 5981 } 5982 5983 // Confirm that the return type is large enough for the dmask specified 5984 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5985 (!LoadVT.isVector() && DMaskLanes > 1)) 5986 return Op; 5987 5988 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5989 NumVDataDwords = (DMaskLanes + 1) / 2; 5990 else 5991 NumVDataDwords = DMaskLanes; 5992 5993 AdjustRetType = true; 5994 } 5995 5996 AddrIdx = DMaskIdx + 1; 5997 } 5998 5999 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 6000 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 6001 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 6002 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 6003 NumCoords + NumLCM; 6004 unsigned NumMIVAddrs = NumVAddrs; 6005 6006 SmallVector<SDValue, 4> VAddrs; 6007 6008 // Optimize _L to _LZ when _L is zero 6009 if (LZMappingInfo) { 6010 if (auto ConstantLod = 6011 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 6012 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6013 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6014 NumMIVAddrs--; // remove 'lod' 6015 } 6016 } 6017 } 6018 6019 // Optimize _mip away, when 'lod' is zero 6020 if (MIPMappingInfo) { 6021 if (auto ConstantLod = 6022 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 6023 if (ConstantLod->isNullValue()) { 6024 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6025 NumMIVAddrs--; // remove 'lod' 6026 } 6027 } 6028 } 6029 6030 // Push back extra arguments. 6031 for (unsigned I = 0; I < BaseOpcode->NumExtraArgs; I++) 6032 VAddrs.push_back(Op.getOperand(AddrIdx + I)); 6033 6034 // Check for 16 bit addresses or derivatives and pack if true. 6035 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 6036 unsigned CoordIdx = DimIdx + NumGradients; 6037 unsigned CoordsEnd = AddrIdx + NumMIVAddrs; 6038 6039 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 6040 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6041 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6042 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6043 6044 VAddrVT = Op.getOperand(CoordIdx).getSimpleValueType(); 6045 VAddrScalarVT = VAddrVT.getScalarType(); 6046 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6047 if (IsA16 || IsG16) { 6048 if (IsA16) { 6049 if (!ST->hasA16()) { 6050 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6051 "support 16 bit addresses\n"); 6052 return Op; 6053 } 6054 if (!IsG16) { 6055 LLVM_DEBUG( 6056 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6057 "need 16 bit derivatives but got 32 bit derivatives\n"); 6058 return Op; 6059 } 6060 } else if (!ST->hasG16()) { 6061 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6062 "support 16 bit derivatives\n"); 6063 return Op; 6064 } 6065 6066 if (BaseOpcode->Gradients && !IsA16) { 6067 if (!ST->hasG16()) { 6068 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6069 "support 16 bit derivatives\n"); 6070 return Op; 6071 } 6072 // Activate g16 6073 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6074 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6075 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6076 } 6077 6078 // Don't compress addresses for G16 6079 const int PackEndIdx = IsA16 ? CoordsEnd : CoordIdx; 6080 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, DimIdx, 6081 PackEndIdx, NumGradients); 6082 6083 if (!IsA16) { 6084 // Add uncompressed address 6085 for (unsigned I = CoordIdx; I < CoordsEnd; I++) 6086 VAddrs.push_back(Op.getOperand(I)); 6087 } 6088 } else { 6089 for (unsigned I = DimIdx; I < CoordsEnd; I++) 6090 VAddrs.push_back(Op.getOperand(I)); 6091 } 6092 6093 // If the register allocator cannot place the address registers contiguously 6094 // without introducing moves, then using the non-sequential address encoding 6095 // is always preferable, since it saves VALU instructions and is usually a 6096 // wash in terms of code size or even better. 6097 // 6098 // However, we currently have no way of hinting to the register allocator that 6099 // MIMG addresses should be placed contiguously when it is possible to do so, 6100 // so force non-NSA for the common 2-address case as a heuristic. 6101 // 6102 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6103 // allocation when possible. 6104 bool UseNSA = 6105 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 6106 SDValue VAddr; 6107 if (!UseNSA) 6108 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6109 6110 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6111 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6112 unsigned CtrlIdx; // Index of texfailctrl argument 6113 SDValue Unorm; 6114 if (!BaseOpcode->Sampler) { 6115 Unorm = True; 6116 CtrlIdx = AddrIdx + NumVAddrs + 1; 6117 } else { 6118 auto UnormConst = 6119 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 6120 6121 Unorm = UnormConst->getZExtValue() ? True : False; 6122 CtrlIdx = AddrIdx + NumVAddrs + 3; 6123 } 6124 6125 SDValue TFE; 6126 SDValue LWE; 6127 SDValue TexFail = Op.getOperand(CtrlIdx); 6128 bool IsTexFail = false; 6129 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6130 return Op; 6131 6132 if (IsTexFail) { 6133 if (!DMaskLanes) { 6134 // Expecting to get an error flag since TFC is on - and dmask is 0 6135 // Force dmask to be at least 1 otherwise the instruction will fail 6136 DMask = 0x1; 6137 DMaskLanes = 1; 6138 NumVDataDwords = 1; 6139 } 6140 NumVDataDwords += 1; 6141 AdjustRetType = true; 6142 } 6143 6144 // Has something earlier tagged that the return type needs adjusting 6145 // This happens if the instruction is a load or has set TexFailCtrl flags 6146 if (AdjustRetType) { 6147 // NumVDataDwords reflects the true number of dwords required in the return type 6148 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6149 // This is a no-op load. This can be eliminated 6150 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6151 if (isa<MemSDNode>(Op)) 6152 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6153 return Undef; 6154 } 6155 6156 EVT NewVT = NumVDataDwords > 1 ? 6157 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6158 : MVT::i32; 6159 6160 ResultTypes[0] = NewVT; 6161 if (ResultTypes.size() == 3) { 6162 // Original result was aggregate type used for TexFailCtrl results 6163 // The actual instruction returns as a vector type which has now been 6164 // created. Remove the aggregate result. 6165 ResultTypes.erase(&ResultTypes[1]); 6166 } 6167 } 6168 6169 SDValue GLC; 6170 SDValue SLC; 6171 SDValue DLC; 6172 if (BaseOpcode->Atomic) { 6173 GLC = True; // TODO no-return optimization 6174 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 6175 IsGFX10 ? &DLC : nullptr)) 6176 return Op; 6177 } else { 6178 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 6179 IsGFX10 ? &DLC : nullptr)) 6180 return Op; 6181 } 6182 6183 SmallVector<SDValue, 26> Ops; 6184 if (BaseOpcode->Store || BaseOpcode->Atomic) 6185 Ops.push_back(VData); // vdata 6186 if (UseNSA) { 6187 for (const SDValue &Addr : VAddrs) 6188 Ops.push_back(Addr); 6189 } else { 6190 Ops.push_back(VAddr); 6191 } 6192 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 6193 if (BaseOpcode->Sampler) 6194 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 6195 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6196 if (IsGFX10) 6197 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6198 Ops.push_back(Unorm); 6199 if (IsGFX10) 6200 Ops.push_back(DLC); 6201 Ops.push_back(GLC); 6202 Ops.push_back(SLC); 6203 Ops.push_back(IsA16 && // r128, a16 for gfx9 6204 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6205 if (IsGFX10) 6206 Ops.push_back(IsA16 ? True : False); 6207 Ops.push_back(TFE); 6208 Ops.push_back(LWE); 6209 if (!IsGFX10) 6210 Ops.push_back(DimInfo->DA ? True : False); 6211 if (BaseOpcode->HasD16) 6212 Ops.push_back(IsD16 ? True : False); 6213 if (isa<MemSDNode>(Op)) 6214 Ops.push_back(Op.getOperand(0)); // chain 6215 6216 int NumVAddrDwords = 6217 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6218 int Opcode = -1; 6219 6220 if (IsGFX10) { 6221 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6222 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6223 : AMDGPU::MIMGEncGfx10Default, 6224 NumVDataDwords, NumVAddrDwords); 6225 } else { 6226 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6227 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6228 NumVDataDwords, NumVAddrDwords); 6229 if (Opcode == -1) 6230 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6231 NumVDataDwords, NumVAddrDwords); 6232 } 6233 assert(Opcode != -1); 6234 6235 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6236 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6237 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6238 DAG.setNodeMemRefs(NewNode, {MemRef}); 6239 } 6240 6241 if (BaseOpcode->AtomicX2) { 6242 SmallVector<SDValue, 1> Elt; 6243 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6244 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6245 } else if (!BaseOpcode->Store) { 6246 return constructRetValue(DAG, NewNode, 6247 OrigResultTypes, IsTexFail, 6248 Subtarget->hasUnpackedD16VMem(), IsD16, 6249 DMaskLanes, NumVDataDwords, DL, 6250 *DAG.getContext()); 6251 } 6252 6253 return SDValue(NewNode, 0); 6254 } 6255 6256 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6257 SDValue Offset, SDValue CachePolicy, 6258 SelectionDAG &DAG) const { 6259 MachineFunction &MF = DAG.getMachineFunction(); 6260 6261 const DataLayout &DataLayout = DAG.getDataLayout(); 6262 Align Alignment = 6263 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6264 6265 MachineMemOperand *MMO = MF.getMachineMemOperand( 6266 MachinePointerInfo(), 6267 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6268 MachineMemOperand::MOInvariant, 6269 VT.getStoreSize(), Alignment); 6270 6271 if (!Offset->isDivergent()) { 6272 SDValue Ops[] = { 6273 Rsrc, 6274 Offset, // Offset 6275 CachePolicy 6276 }; 6277 6278 // Widen vec3 load to vec4. 6279 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6280 EVT WidenedVT = 6281 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6282 auto WidenedOp = DAG.getMemIntrinsicNode( 6283 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6284 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6285 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6286 DAG.getVectorIdxConstant(0, DL)); 6287 return Subvector; 6288 } 6289 6290 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6291 DAG.getVTList(VT), Ops, VT, MMO); 6292 } 6293 6294 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6295 // assume that the buffer is unswizzled. 6296 SmallVector<SDValue, 4> Loads; 6297 unsigned NumLoads = 1; 6298 MVT LoadVT = VT.getSimpleVT(); 6299 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6300 assert((LoadVT.getScalarType() == MVT::i32 || 6301 LoadVT.getScalarType() == MVT::f32)); 6302 6303 if (NumElts == 8 || NumElts == 16) { 6304 NumLoads = NumElts / 4; 6305 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6306 } 6307 6308 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6309 SDValue Ops[] = { 6310 DAG.getEntryNode(), // Chain 6311 Rsrc, // rsrc 6312 DAG.getConstant(0, DL, MVT::i32), // vindex 6313 {}, // voffset 6314 {}, // soffset 6315 {}, // offset 6316 CachePolicy, // cachepolicy 6317 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6318 }; 6319 6320 // Use the alignment to ensure that the required offsets will fit into the 6321 // immediate offsets. 6322 setBufferOffsets(Offset, DAG, &Ops[3], 6323 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6324 6325 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6326 for (unsigned i = 0; i < NumLoads; ++i) { 6327 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6328 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6329 LoadVT, MMO, DAG)); 6330 } 6331 6332 if (NumElts == 8 || NumElts == 16) 6333 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6334 6335 return Loads[0]; 6336 } 6337 6338 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6339 SelectionDAG &DAG) const { 6340 MachineFunction &MF = DAG.getMachineFunction(); 6341 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6342 6343 EVT VT = Op.getValueType(); 6344 SDLoc DL(Op); 6345 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6346 6347 // TODO: Should this propagate fast-math-flags? 6348 6349 switch (IntrinsicID) { 6350 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6351 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6352 return emitNonHSAIntrinsicError(DAG, DL, VT); 6353 return getPreloadedValue(DAG, *MFI, VT, 6354 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6355 } 6356 case Intrinsic::amdgcn_dispatch_ptr: 6357 case Intrinsic::amdgcn_queue_ptr: { 6358 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6359 DiagnosticInfoUnsupported BadIntrin( 6360 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6361 DL.getDebugLoc()); 6362 DAG.getContext()->diagnose(BadIntrin); 6363 return DAG.getUNDEF(VT); 6364 } 6365 6366 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6367 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6368 return getPreloadedValue(DAG, *MFI, VT, RegID); 6369 } 6370 case Intrinsic::amdgcn_implicitarg_ptr: { 6371 if (MFI->isEntryFunction()) 6372 return getImplicitArgPtr(DAG, DL); 6373 return getPreloadedValue(DAG, *MFI, VT, 6374 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6375 } 6376 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6377 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6378 // This only makes sense to call in a kernel, so just lower to null. 6379 return DAG.getConstant(0, DL, VT); 6380 } 6381 6382 return getPreloadedValue(DAG, *MFI, VT, 6383 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6384 } 6385 case Intrinsic::amdgcn_dispatch_id: { 6386 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6387 } 6388 case Intrinsic::amdgcn_rcp: 6389 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6390 case Intrinsic::amdgcn_rsq: 6391 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6392 case Intrinsic::amdgcn_rsq_legacy: 6393 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6394 return emitRemovedIntrinsicError(DAG, DL, VT); 6395 return SDValue(); 6396 case Intrinsic::amdgcn_rcp_legacy: 6397 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6398 return emitRemovedIntrinsicError(DAG, DL, VT); 6399 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6400 case Intrinsic::amdgcn_rsq_clamp: { 6401 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6402 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6403 6404 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6405 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6406 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6407 6408 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6409 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6410 DAG.getConstantFP(Max, DL, VT)); 6411 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6412 DAG.getConstantFP(Min, DL, VT)); 6413 } 6414 case Intrinsic::r600_read_ngroups_x: 6415 if (Subtarget->isAmdHsaOS()) 6416 return emitNonHSAIntrinsicError(DAG, DL, VT); 6417 6418 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6419 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6420 false); 6421 case Intrinsic::r600_read_ngroups_y: 6422 if (Subtarget->isAmdHsaOS()) 6423 return emitNonHSAIntrinsicError(DAG, DL, VT); 6424 6425 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6426 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6427 false); 6428 case Intrinsic::r600_read_ngroups_z: 6429 if (Subtarget->isAmdHsaOS()) 6430 return emitNonHSAIntrinsicError(DAG, DL, VT); 6431 6432 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6433 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6434 false); 6435 case Intrinsic::r600_read_global_size_x: 6436 if (Subtarget->isAmdHsaOS()) 6437 return emitNonHSAIntrinsicError(DAG, DL, VT); 6438 6439 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6440 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6441 Align(4), false); 6442 case Intrinsic::r600_read_global_size_y: 6443 if (Subtarget->isAmdHsaOS()) 6444 return emitNonHSAIntrinsicError(DAG, DL, VT); 6445 6446 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6447 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6448 Align(4), false); 6449 case Intrinsic::r600_read_global_size_z: 6450 if (Subtarget->isAmdHsaOS()) 6451 return emitNonHSAIntrinsicError(DAG, DL, VT); 6452 6453 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6454 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6455 Align(4), false); 6456 case Intrinsic::r600_read_local_size_x: 6457 if (Subtarget->isAmdHsaOS()) 6458 return emitNonHSAIntrinsicError(DAG, DL, VT); 6459 6460 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6461 SI::KernelInputOffsets::LOCAL_SIZE_X); 6462 case Intrinsic::r600_read_local_size_y: 6463 if (Subtarget->isAmdHsaOS()) 6464 return emitNonHSAIntrinsicError(DAG, DL, VT); 6465 6466 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6467 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6468 case Intrinsic::r600_read_local_size_z: 6469 if (Subtarget->isAmdHsaOS()) 6470 return emitNonHSAIntrinsicError(DAG, DL, VT); 6471 6472 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6473 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6474 case Intrinsic::amdgcn_workgroup_id_x: 6475 return getPreloadedValue(DAG, *MFI, VT, 6476 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6477 case Intrinsic::amdgcn_workgroup_id_y: 6478 return getPreloadedValue(DAG, *MFI, VT, 6479 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6480 case Intrinsic::amdgcn_workgroup_id_z: 6481 return getPreloadedValue(DAG, *MFI, VT, 6482 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6483 case Intrinsic::amdgcn_workitem_id_x: 6484 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6485 SDLoc(DAG.getEntryNode()), 6486 MFI->getArgInfo().WorkItemIDX); 6487 case Intrinsic::amdgcn_workitem_id_y: 6488 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6489 SDLoc(DAG.getEntryNode()), 6490 MFI->getArgInfo().WorkItemIDY); 6491 case Intrinsic::amdgcn_workitem_id_z: 6492 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6493 SDLoc(DAG.getEntryNode()), 6494 MFI->getArgInfo().WorkItemIDZ); 6495 case Intrinsic::amdgcn_wavefrontsize: 6496 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6497 SDLoc(Op), MVT::i32); 6498 case Intrinsic::amdgcn_s_buffer_load: { 6499 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 6500 SDValue GLC; 6501 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6502 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6503 IsGFX10 ? &DLC : nullptr)) 6504 return Op; 6505 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6506 DAG); 6507 } 6508 case Intrinsic::amdgcn_fdiv_fast: 6509 return lowerFDIV_FAST(Op, DAG); 6510 case Intrinsic::amdgcn_sin: 6511 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6512 6513 case Intrinsic::amdgcn_cos: 6514 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6515 6516 case Intrinsic::amdgcn_mul_u24: 6517 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6518 case Intrinsic::amdgcn_mul_i24: 6519 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6520 6521 case Intrinsic::amdgcn_log_clamp: { 6522 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6523 return SDValue(); 6524 6525 DiagnosticInfoUnsupported BadIntrin( 6526 MF.getFunction(), "intrinsic not supported on subtarget", 6527 DL.getDebugLoc()); 6528 DAG.getContext()->diagnose(BadIntrin); 6529 return DAG.getUNDEF(VT); 6530 } 6531 case Intrinsic::amdgcn_ldexp: 6532 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6533 Op.getOperand(1), Op.getOperand(2)); 6534 6535 case Intrinsic::amdgcn_fract: 6536 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6537 6538 case Intrinsic::amdgcn_class: 6539 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6540 Op.getOperand(1), Op.getOperand(2)); 6541 case Intrinsic::amdgcn_div_fmas: 6542 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6543 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6544 Op.getOperand(4)); 6545 6546 case Intrinsic::amdgcn_div_fixup: 6547 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6548 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6549 6550 case Intrinsic::amdgcn_div_scale: { 6551 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6552 6553 // Translate to the operands expected by the machine instruction. The 6554 // first parameter must be the same as the first instruction. 6555 SDValue Numerator = Op.getOperand(1); 6556 SDValue Denominator = Op.getOperand(2); 6557 6558 // Note this order is opposite of the machine instruction's operations, 6559 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6560 // intrinsic has the numerator as the first operand to match a normal 6561 // division operation. 6562 6563 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6564 6565 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6566 Denominator, Numerator); 6567 } 6568 case Intrinsic::amdgcn_icmp: { 6569 // There is a Pat that handles this variant, so return it as-is. 6570 if (Op.getOperand(1).getValueType() == MVT::i1 && 6571 Op.getConstantOperandVal(2) == 0 && 6572 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6573 return Op; 6574 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6575 } 6576 case Intrinsic::amdgcn_fcmp: { 6577 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6578 } 6579 case Intrinsic::amdgcn_ballot: 6580 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6581 case Intrinsic::amdgcn_fmed3: 6582 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6583 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6584 case Intrinsic::amdgcn_fdot2: 6585 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6586 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6587 Op.getOperand(4)); 6588 case Intrinsic::amdgcn_fmul_legacy: 6589 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6590 Op.getOperand(1), Op.getOperand(2)); 6591 case Intrinsic::amdgcn_sffbh: 6592 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6593 case Intrinsic::amdgcn_sbfe: 6594 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6595 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6596 case Intrinsic::amdgcn_ubfe: 6597 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6598 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6599 case Intrinsic::amdgcn_cvt_pkrtz: 6600 case Intrinsic::amdgcn_cvt_pknorm_i16: 6601 case Intrinsic::amdgcn_cvt_pknorm_u16: 6602 case Intrinsic::amdgcn_cvt_pk_i16: 6603 case Intrinsic::amdgcn_cvt_pk_u16: { 6604 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6605 EVT VT = Op.getValueType(); 6606 unsigned Opcode; 6607 6608 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6609 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6610 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6611 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6612 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6613 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6614 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6615 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6616 else 6617 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6618 6619 if (isTypeLegal(VT)) 6620 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6621 6622 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6623 Op.getOperand(1), Op.getOperand(2)); 6624 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6625 } 6626 case Intrinsic::amdgcn_fmad_ftz: 6627 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6628 Op.getOperand(2), Op.getOperand(3)); 6629 6630 case Intrinsic::amdgcn_if_break: 6631 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6632 Op->getOperand(1), Op->getOperand(2)), 0); 6633 6634 case Intrinsic::amdgcn_groupstaticsize: { 6635 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6636 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6637 return Op; 6638 6639 const Module *M = MF.getFunction().getParent(); 6640 const GlobalValue *GV = 6641 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6642 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6643 SIInstrInfo::MO_ABS32_LO); 6644 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6645 } 6646 case Intrinsic::amdgcn_is_shared: 6647 case Intrinsic::amdgcn_is_private: { 6648 SDLoc SL(Op); 6649 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6650 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6651 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6652 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6653 Op.getOperand(1)); 6654 6655 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6656 DAG.getConstant(1, SL, MVT::i32)); 6657 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6658 } 6659 case Intrinsic::amdgcn_alignbit: 6660 return DAG.getNode(ISD::FSHR, DL, VT, 6661 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6662 case Intrinsic::amdgcn_reloc_constant: { 6663 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6664 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6665 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6666 auto RelocSymbol = cast<GlobalVariable>( 6667 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6668 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6669 SIInstrInfo::MO_ABS32_LO); 6670 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6671 } 6672 default: 6673 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6674 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6675 return lowerImage(Op, ImageDimIntr, DAG); 6676 6677 return Op; 6678 } 6679 } 6680 6681 // This function computes an appropriate offset to pass to 6682 // MachineMemOperand::setOffset() based on the offset inputs to 6683 // an intrinsic. If any of the offsets are non-contstant or 6684 // if VIndex is non-zero then this function returns 0. Otherwise, 6685 // it returns the sum of VOffset, SOffset, and Offset. 6686 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6687 SDValue SOffset, 6688 SDValue Offset, 6689 SDValue VIndex = SDValue()) { 6690 6691 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6692 !isa<ConstantSDNode>(Offset)) 6693 return 0; 6694 6695 if (VIndex) { 6696 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6697 return 0; 6698 } 6699 6700 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6701 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6702 cast<ConstantSDNode>(Offset)->getSExtValue(); 6703 } 6704 6705 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6706 SelectionDAG &DAG, 6707 unsigned NewOpcode) const { 6708 SDLoc DL(Op); 6709 6710 SDValue VData = Op.getOperand(2); 6711 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6712 SDValue Ops[] = { 6713 Op.getOperand(0), // Chain 6714 VData, // vdata 6715 Op.getOperand(3), // rsrc 6716 DAG.getConstant(0, DL, MVT::i32), // vindex 6717 Offsets.first, // voffset 6718 Op.getOperand(5), // soffset 6719 Offsets.second, // offset 6720 Op.getOperand(6), // cachepolicy 6721 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6722 }; 6723 6724 auto *M = cast<MemSDNode>(Op); 6725 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6726 6727 EVT MemVT = VData.getValueType(); 6728 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6729 M->getMemOperand()); 6730 } 6731 6732 SDValue 6733 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6734 unsigned NewOpcode) const { 6735 SDLoc DL(Op); 6736 6737 SDValue VData = Op.getOperand(2); 6738 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6739 SDValue Ops[] = { 6740 Op.getOperand(0), // Chain 6741 VData, // vdata 6742 Op.getOperand(3), // rsrc 6743 Op.getOperand(4), // vindex 6744 Offsets.first, // voffset 6745 Op.getOperand(6), // soffset 6746 Offsets.second, // offset 6747 Op.getOperand(7), // cachepolicy 6748 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6749 }; 6750 6751 auto *M = cast<MemSDNode>(Op); 6752 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6753 Ops[3])); 6754 6755 EVT MemVT = VData.getValueType(); 6756 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6757 M->getMemOperand()); 6758 } 6759 6760 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6761 SelectionDAG &DAG) const { 6762 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6763 SDLoc DL(Op); 6764 6765 switch (IntrID) { 6766 case Intrinsic::amdgcn_ds_ordered_add: 6767 case Intrinsic::amdgcn_ds_ordered_swap: { 6768 MemSDNode *M = cast<MemSDNode>(Op); 6769 SDValue Chain = M->getOperand(0); 6770 SDValue M0 = M->getOperand(2); 6771 SDValue Value = M->getOperand(3); 6772 unsigned IndexOperand = M->getConstantOperandVal(7); 6773 unsigned WaveRelease = M->getConstantOperandVal(8); 6774 unsigned WaveDone = M->getConstantOperandVal(9); 6775 6776 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6777 IndexOperand &= ~0x3f; 6778 unsigned CountDw = 0; 6779 6780 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6781 CountDw = (IndexOperand >> 24) & 0xf; 6782 IndexOperand &= ~(0xf << 24); 6783 6784 if (CountDw < 1 || CountDw > 4) { 6785 report_fatal_error( 6786 "ds_ordered_count: dword count must be between 1 and 4"); 6787 } 6788 } 6789 6790 if (IndexOperand) 6791 report_fatal_error("ds_ordered_count: bad index operand"); 6792 6793 if (WaveDone && !WaveRelease) 6794 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6795 6796 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6797 unsigned ShaderType = 6798 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6799 unsigned Offset0 = OrderedCountIndex << 2; 6800 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6801 (Instruction << 4); 6802 6803 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6804 Offset1 |= (CountDw - 1) << 6; 6805 6806 unsigned Offset = Offset0 | (Offset1 << 8); 6807 6808 SDValue Ops[] = { 6809 Chain, 6810 Value, 6811 DAG.getTargetConstant(Offset, DL, MVT::i16), 6812 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6813 }; 6814 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6815 M->getVTList(), Ops, M->getMemoryVT(), 6816 M->getMemOperand()); 6817 } 6818 case Intrinsic::amdgcn_ds_fadd: { 6819 MemSDNode *M = cast<MemSDNode>(Op); 6820 unsigned Opc; 6821 switch (IntrID) { 6822 case Intrinsic::amdgcn_ds_fadd: 6823 Opc = ISD::ATOMIC_LOAD_FADD; 6824 break; 6825 } 6826 6827 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6828 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6829 M->getMemOperand()); 6830 } 6831 case Intrinsic::amdgcn_atomic_inc: 6832 case Intrinsic::amdgcn_atomic_dec: 6833 case Intrinsic::amdgcn_ds_fmin: 6834 case Intrinsic::amdgcn_ds_fmax: { 6835 MemSDNode *M = cast<MemSDNode>(Op); 6836 unsigned Opc; 6837 switch (IntrID) { 6838 case Intrinsic::amdgcn_atomic_inc: 6839 Opc = AMDGPUISD::ATOMIC_INC; 6840 break; 6841 case Intrinsic::amdgcn_atomic_dec: 6842 Opc = AMDGPUISD::ATOMIC_DEC; 6843 break; 6844 case Intrinsic::amdgcn_ds_fmin: 6845 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6846 break; 6847 case Intrinsic::amdgcn_ds_fmax: 6848 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6849 break; 6850 default: 6851 llvm_unreachable("Unknown intrinsic!"); 6852 } 6853 SDValue Ops[] = { 6854 M->getOperand(0), // Chain 6855 M->getOperand(2), // Ptr 6856 M->getOperand(3) // Value 6857 }; 6858 6859 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6860 M->getMemoryVT(), M->getMemOperand()); 6861 } 6862 case Intrinsic::amdgcn_buffer_load: 6863 case Intrinsic::amdgcn_buffer_load_format: { 6864 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6865 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6866 unsigned IdxEn = 1; 6867 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6868 IdxEn = Idx->getZExtValue() != 0; 6869 SDValue Ops[] = { 6870 Op.getOperand(0), // Chain 6871 Op.getOperand(2), // rsrc 6872 Op.getOperand(3), // vindex 6873 SDValue(), // voffset -- will be set by setBufferOffsets 6874 SDValue(), // soffset -- will be set by setBufferOffsets 6875 SDValue(), // offset -- will be set by setBufferOffsets 6876 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6877 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6878 }; 6879 6880 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6881 // We don't know the offset if vindex is non-zero, so clear it. 6882 if (IdxEn) 6883 Offset = 0; 6884 6885 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6886 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6887 6888 EVT VT = Op.getValueType(); 6889 EVT IntVT = VT.changeTypeToInteger(); 6890 auto *M = cast<MemSDNode>(Op); 6891 M->getMemOperand()->setOffset(Offset); 6892 EVT LoadVT = Op.getValueType(); 6893 6894 if (LoadVT.getScalarType() == MVT::f16) 6895 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6896 M, DAG, Ops); 6897 6898 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6899 if (LoadVT.getScalarType() == MVT::i8 || 6900 LoadVT.getScalarType() == MVT::i16) 6901 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6902 6903 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6904 M->getMemOperand(), DAG); 6905 } 6906 case Intrinsic::amdgcn_raw_buffer_load: 6907 case Intrinsic::amdgcn_raw_buffer_load_format: { 6908 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6909 6910 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6911 SDValue Ops[] = { 6912 Op.getOperand(0), // Chain 6913 Op.getOperand(2), // rsrc 6914 DAG.getConstant(0, DL, MVT::i32), // vindex 6915 Offsets.first, // voffset 6916 Op.getOperand(4), // soffset 6917 Offsets.second, // offset 6918 Op.getOperand(5), // cachepolicy, swizzled buffer 6919 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6920 }; 6921 6922 auto *M = cast<MemSDNode>(Op); 6923 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6924 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6925 } 6926 case Intrinsic::amdgcn_struct_buffer_load: 6927 case Intrinsic::amdgcn_struct_buffer_load_format: { 6928 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6929 6930 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6931 SDValue Ops[] = { 6932 Op.getOperand(0), // Chain 6933 Op.getOperand(2), // rsrc 6934 Op.getOperand(3), // vindex 6935 Offsets.first, // voffset 6936 Op.getOperand(5), // soffset 6937 Offsets.second, // offset 6938 Op.getOperand(6), // cachepolicy, swizzled buffer 6939 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6940 }; 6941 6942 auto *M = cast<MemSDNode>(Op); 6943 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6944 Ops[2])); 6945 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6946 } 6947 case Intrinsic::amdgcn_tbuffer_load: { 6948 MemSDNode *M = cast<MemSDNode>(Op); 6949 EVT LoadVT = Op.getValueType(); 6950 6951 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6952 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6953 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6954 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6955 unsigned IdxEn = 1; 6956 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6957 IdxEn = Idx->getZExtValue() != 0; 6958 SDValue Ops[] = { 6959 Op.getOperand(0), // Chain 6960 Op.getOperand(2), // rsrc 6961 Op.getOperand(3), // vindex 6962 Op.getOperand(4), // voffset 6963 Op.getOperand(5), // soffset 6964 Op.getOperand(6), // offset 6965 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6966 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6967 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6968 }; 6969 6970 if (LoadVT.getScalarType() == MVT::f16) 6971 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6972 M, DAG, Ops); 6973 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6974 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6975 DAG); 6976 } 6977 case Intrinsic::amdgcn_raw_tbuffer_load: { 6978 MemSDNode *M = cast<MemSDNode>(Op); 6979 EVT LoadVT = Op.getValueType(); 6980 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6981 6982 SDValue Ops[] = { 6983 Op.getOperand(0), // Chain 6984 Op.getOperand(2), // rsrc 6985 DAG.getConstant(0, DL, MVT::i32), // vindex 6986 Offsets.first, // voffset 6987 Op.getOperand(4), // soffset 6988 Offsets.second, // offset 6989 Op.getOperand(5), // format 6990 Op.getOperand(6), // cachepolicy, swizzled buffer 6991 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6992 }; 6993 6994 if (LoadVT.getScalarType() == MVT::f16) 6995 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6996 M, DAG, Ops); 6997 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6998 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6999 DAG); 7000 } 7001 case Intrinsic::amdgcn_struct_tbuffer_load: { 7002 MemSDNode *M = cast<MemSDNode>(Op); 7003 EVT LoadVT = Op.getValueType(); 7004 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7005 7006 SDValue Ops[] = { 7007 Op.getOperand(0), // Chain 7008 Op.getOperand(2), // rsrc 7009 Op.getOperand(3), // vindex 7010 Offsets.first, // voffset 7011 Op.getOperand(5), // soffset 7012 Offsets.second, // offset 7013 Op.getOperand(6), // format 7014 Op.getOperand(7), // cachepolicy, swizzled buffer 7015 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7016 }; 7017 7018 if (LoadVT.getScalarType() == MVT::f16) 7019 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7020 M, DAG, Ops); 7021 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7022 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7023 DAG); 7024 } 7025 case Intrinsic::amdgcn_buffer_atomic_swap: 7026 case Intrinsic::amdgcn_buffer_atomic_add: 7027 case Intrinsic::amdgcn_buffer_atomic_sub: 7028 case Intrinsic::amdgcn_buffer_atomic_csub: 7029 case Intrinsic::amdgcn_buffer_atomic_smin: 7030 case Intrinsic::amdgcn_buffer_atomic_umin: 7031 case Intrinsic::amdgcn_buffer_atomic_smax: 7032 case Intrinsic::amdgcn_buffer_atomic_umax: 7033 case Intrinsic::amdgcn_buffer_atomic_and: 7034 case Intrinsic::amdgcn_buffer_atomic_or: 7035 case Intrinsic::amdgcn_buffer_atomic_xor: { 7036 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7037 unsigned IdxEn = 1; 7038 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7039 IdxEn = Idx->getZExtValue() != 0; 7040 SDValue Ops[] = { 7041 Op.getOperand(0), // Chain 7042 Op.getOperand(2), // vdata 7043 Op.getOperand(3), // rsrc 7044 Op.getOperand(4), // vindex 7045 SDValue(), // voffset -- will be set by setBufferOffsets 7046 SDValue(), // soffset -- will be set by setBufferOffsets 7047 SDValue(), // offset -- will be set by setBufferOffsets 7048 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7049 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7050 }; 7051 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7052 // We don't know the offset if vindex is non-zero, so clear it. 7053 if (IdxEn) 7054 Offset = 0; 7055 EVT VT = Op.getValueType(); 7056 7057 auto *M = cast<MemSDNode>(Op); 7058 M->getMemOperand()->setOffset(Offset); 7059 unsigned Opcode = 0; 7060 7061 switch (IntrID) { 7062 case Intrinsic::amdgcn_buffer_atomic_swap: 7063 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7064 break; 7065 case Intrinsic::amdgcn_buffer_atomic_add: 7066 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7067 break; 7068 case Intrinsic::amdgcn_buffer_atomic_sub: 7069 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7070 break; 7071 case Intrinsic::amdgcn_buffer_atomic_csub: 7072 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7073 break; 7074 case Intrinsic::amdgcn_buffer_atomic_smin: 7075 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7076 break; 7077 case Intrinsic::amdgcn_buffer_atomic_umin: 7078 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7079 break; 7080 case Intrinsic::amdgcn_buffer_atomic_smax: 7081 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7082 break; 7083 case Intrinsic::amdgcn_buffer_atomic_umax: 7084 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7085 break; 7086 case Intrinsic::amdgcn_buffer_atomic_and: 7087 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7088 break; 7089 case Intrinsic::amdgcn_buffer_atomic_or: 7090 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7091 break; 7092 case Intrinsic::amdgcn_buffer_atomic_xor: 7093 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 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_raw_buffer_atomic_swap: 7103 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7104 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7105 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7106 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7107 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7108 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7109 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7110 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7111 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7112 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7113 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7114 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7115 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7116 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7117 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7118 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7119 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7120 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7121 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7122 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7123 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7124 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7125 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7126 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7127 return lowerStructBufferAtomicIntrin(Op, DAG, 7128 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7129 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7130 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7131 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7132 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7133 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7134 return lowerStructBufferAtomicIntrin(Op, DAG, 7135 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7136 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7137 return lowerStructBufferAtomicIntrin(Op, DAG, 7138 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7139 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7140 return lowerStructBufferAtomicIntrin(Op, DAG, 7141 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7142 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7143 return lowerStructBufferAtomicIntrin(Op, DAG, 7144 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7145 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7146 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7147 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7148 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7149 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7150 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7151 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7152 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7153 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7154 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7155 7156 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7157 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7158 unsigned IdxEn = 1; 7159 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7160 IdxEn = Idx->getZExtValue() != 0; 7161 SDValue Ops[] = { 7162 Op.getOperand(0), // Chain 7163 Op.getOperand(2), // src 7164 Op.getOperand(3), // cmp 7165 Op.getOperand(4), // rsrc 7166 Op.getOperand(5), // vindex 7167 SDValue(), // voffset -- will be set by setBufferOffsets 7168 SDValue(), // soffset -- will be set by setBufferOffsets 7169 SDValue(), // offset -- will be set by setBufferOffsets 7170 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7171 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7172 }; 7173 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7174 // We don't know the offset if vindex is non-zero, so clear it. 7175 if (IdxEn) 7176 Offset = 0; 7177 EVT VT = Op.getValueType(); 7178 auto *M = cast<MemSDNode>(Op); 7179 M->getMemOperand()->setOffset(Offset); 7180 7181 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7182 Op->getVTList(), Ops, VT, M->getMemOperand()); 7183 } 7184 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7185 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7186 SDValue Ops[] = { 7187 Op.getOperand(0), // Chain 7188 Op.getOperand(2), // src 7189 Op.getOperand(3), // cmp 7190 Op.getOperand(4), // rsrc 7191 DAG.getConstant(0, DL, MVT::i32), // vindex 7192 Offsets.first, // voffset 7193 Op.getOperand(6), // soffset 7194 Offsets.second, // offset 7195 Op.getOperand(7), // cachepolicy 7196 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7197 }; 7198 EVT VT = Op.getValueType(); 7199 auto *M = cast<MemSDNode>(Op); 7200 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7201 7202 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7203 Op->getVTList(), Ops, VT, M->getMemOperand()); 7204 } 7205 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7206 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7207 SDValue Ops[] = { 7208 Op.getOperand(0), // Chain 7209 Op.getOperand(2), // src 7210 Op.getOperand(3), // cmp 7211 Op.getOperand(4), // rsrc 7212 Op.getOperand(5), // vindex 7213 Offsets.first, // voffset 7214 Op.getOperand(7), // soffset 7215 Offsets.second, // offset 7216 Op.getOperand(8), // cachepolicy 7217 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7218 }; 7219 EVT VT = Op.getValueType(); 7220 auto *M = cast<MemSDNode>(Op); 7221 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7222 Ops[4])); 7223 7224 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7225 Op->getVTList(), Ops, VT, M->getMemOperand()); 7226 } 7227 default: 7228 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7229 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7230 return lowerImage(Op, ImageDimIntr, DAG); 7231 7232 return SDValue(); 7233 } 7234 } 7235 7236 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7237 // dwordx4 if on SI. 7238 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7239 SDVTList VTList, 7240 ArrayRef<SDValue> Ops, EVT MemVT, 7241 MachineMemOperand *MMO, 7242 SelectionDAG &DAG) const { 7243 EVT VT = VTList.VTs[0]; 7244 EVT WidenedVT = VT; 7245 EVT WidenedMemVT = MemVT; 7246 if (!Subtarget->hasDwordx3LoadStores() && 7247 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7248 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7249 WidenedVT.getVectorElementType(), 4); 7250 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7251 WidenedMemVT.getVectorElementType(), 4); 7252 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7253 } 7254 7255 assert(VTList.NumVTs == 2); 7256 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7257 7258 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7259 WidenedMemVT, MMO); 7260 if (WidenedVT != VT) { 7261 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7262 DAG.getVectorIdxConstant(0, DL)); 7263 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7264 } 7265 return NewOp; 7266 } 7267 7268 SDValue SITargetLowering::handleD16VData(SDValue VData, 7269 SelectionDAG &DAG) const { 7270 EVT StoreVT = VData.getValueType(); 7271 7272 // No change for f16 and legal vector D16 types. 7273 if (!StoreVT.isVector()) 7274 return VData; 7275 7276 SDLoc DL(VData); 7277 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 7278 7279 if (Subtarget->hasUnpackedD16VMem()) { 7280 // We need to unpack the packed data to store. 7281 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7282 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7283 7284 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 7285 StoreVT.getVectorNumElements()); 7286 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7287 return DAG.UnrollVectorOp(ZExt.getNode()); 7288 } 7289 7290 assert(isTypeLegal(StoreVT)); 7291 return VData; 7292 } 7293 7294 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7295 SelectionDAG &DAG) const { 7296 SDLoc DL(Op); 7297 SDValue Chain = Op.getOperand(0); 7298 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7299 MachineFunction &MF = DAG.getMachineFunction(); 7300 7301 switch (IntrinsicID) { 7302 case Intrinsic::amdgcn_exp_compr: { 7303 SDValue Src0 = Op.getOperand(4); 7304 SDValue Src1 = Op.getOperand(5); 7305 // Hack around illegal type on SI by directly selecting it. 7306 if (isTypeLegal(Src0.getValueType())) 7307 return SDValue(); 7308 7309 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7310 SDValue Undef = DAG.getUNDEF(MVT::f32); 7311 const SDValue Ops[] = { 7312 Op.getOperand(2), // tgt 7313 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7314 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7315 Undef, // src2 7316 Undef, // src3 7317 Op.getOperand(7), // vm 7318 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7319 Op.getOperand(3), // en 7320 Op.getOperand(0) // Chain 7321 }; 7322 7323 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7324 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7325 } 7326 case Intrinsic::amdgcn_s_barrier: { 7327 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7328 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7329 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7330 if (WGSize <= ST.getWavefrontSize()) 7331 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7332 Op.getOperand(0)), 0); 7333 } 7334 return SDValue(); 7335 }; 7336 case Intrinsic::amdgcn_tbuffer_store: { 7337 SDValue VData = Op.getOperand(2); 7338 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7339 if (IsD16) 7340 VData = handleD16VData(VData, DAG); 7341 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7342 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7343 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7344 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7345 unsigned IdxEn = 1; 7346 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7347 IdxEn = Idx->getZExtValue() != 0; 7348 SDValue Ops[] = { 7349 Chain, 7350 VData, // vdata 7351 Op.getOperand(3), // rsrc 7352 Op.getOperand(4), // vindex 7353 Op.getOperand(5), // voffset 7354 Op.getOperand(6), // soffset 7355 Op.getOperand(7), // offset 7356 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7357 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7358 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7359 }; 7360 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7361 AMDGPUISD::TBUFFER_STORE_FORMAT; 7362 MemSDNode *M = cast<MemSDNode>(Op); 7363 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7364 M->getMemoryVT(), M->getMemOperand()); 7365 } 7366 7367 case Intrinsic::amdgcn_struct_tbuffer_store: { 7368 SDValue VData = Op.getOperand(2); 7369 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7370 if (IsD16) 7371 VData = handleD16VData(VData, DAG); 7372 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7373 SDValue Ops[] = { 7374 Chain, 7375 VData, // vdata 7376 Op.getOperand(3), // rsrc 7377 Op.getOperand(4), // vindex 7378 Offsets.first, // voffset 7379 Op.getOperand(6), // soffset 7380 Offsets.second, // offset 7381 Op.getOperand(7), // format 7382 Op.getOperand(8), // cachepolicy, swizzled buffer 7383 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7384 }; 7385 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7386 AMDGPUISD::TBUFFER_STORE_FORMAT; 7387 MemSDNode *M = cast<MemSDNode>(Op); 7388 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7389 M->getMemoryVT(), M->getMemOperand()); 7390 } 7391 7392 case Intrinsic::amdgcn_raw_tbuffer_store: { 7393 SDValue VData = Op.getOperand(2); 7394 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7395 if (IsD16) 7396 VData = handleD16VData(VData, DAG); 7397 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7398 SDValue Ops[] = { 7399 Chain, 7400 VData, // vdata 7401 Op.getOperand(3), // rsrc 7402 DAG.getConstant(0, DL, MVT::i32), // vindex 7403 Offsets.first, // voffset 7404 Op.getOperand(5), // soffset 7405 Offsets.second, // offset 7406 Op.getOperand(6), // format 7407 Op.getOperand(7), // cachepolicy, swizzled buffer 7408 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7409 }; 7410 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7411 AMDGPUISD::TBUFFER_STORE_FORMAT; 7412 MemSDNode *M = cast<MemSDNode>(Op); 7413 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7414 M->getMemoryVT(), M->getMemOperand()); 7415 } 7416 7417 case Intrinsic::amdgcn_buffer_store: 7418 case Intrinsic::amdgcn_buffer_store_format: { 7419 SDValue VData = Op.getOperand(2); 7420 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7421 if (IsD16) 7422 VData = handleD16VData(VData, DAG); 7423 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7424 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7425 unsigned IdxEn = 1; 7426 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7427 IdxEn = Idx->getZExtValue() != 0; 7428 SDValue Ops[] = { 7429 Chain, 7430 VData, 7431 Op.getOperand(3), // rsrc 7432 Op.getOperand(4), // vindex 7433 SDValue(), // voffset -- will be set by setBufferOffsets 7434 SDValue(), // soffset -- will be set by setBufferOffsets 7435 SDValue(), // offset -- will be set by setBufferOffsets 7436 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7437 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7438 }; 7439 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7440 // We don't know the offset if vindex is non-zero, so clear it. 7441 if (IdxEn) 7442 Offset = 0; 7443 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7444 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7445 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7446 MemSDNode *M = cast<MemSDNode>(Op); 7447 M->getMemOperand()->setOffset(Offset); 7448 7449 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7450 EVT VDataType = VData.getValueType().getScalarType(); 7451 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7452 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7453 7454 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7455 M->getMemoryVT(), M->getMemOperand()); 7456 } 7457 7458 case Intrinsic::amdgcn_raw_buffer_store: 7459 case Intrinsic::amdgcn_raw_buffer_store_format: { 7460 const bool IsFormat = 7461 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7462 7463 SDValue VData = Op.getOperand(2); 7464 EVT VDataVT = VData.getValueType(); 7465 EVT EltType = VDataVT.getScalarType(); 7466 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7467 if (IsD16) 7468 VData = handleD16VData(VData, DAG); 7469 7470 if (!isTypeLegal(VDataVT)) { 7471 VData = 7472 DAG.getNode(ISD::BITCAST, DL, 7473 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7474 } 7475 7476 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7477 SDValue Ops[] = { 7478 Chain, 7479 VData, 7480 Op.getOperand(3), // rsrc 7481 DAG.getConstant(0, DL, MVT::i32), // vindex 7482 Offsets.first, // voffset 7483 Op.getOperand(5), // soffset 7484 Offsets.second, // offset 7485 Op.getOperand(6), // cachepolicy, swizzled buffer 7486 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7487 }; 7488 unsigned Opc = 7489 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7490 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7491 MemSDNode *M = cast<MemSDNode>(Op); 7492 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7493 7494 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7495 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7496 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7497 7498 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7499 M->getMemoryVT(), M->getMemOperand()); 7500 } 7501 7502 case Intrinsic::amdgcn_struct_buffer_store: 7503 case Intrinsic::amdgcn_struct_buffer_store_format: { 7504 const bool IsFormat = 7505 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7506 7507 SDValue VData = Op.getOperand(2); 7508 EVT VDataVT = VData.getValueType(); 7509 EVT EltType = VDataVT.getScalarType(); 7510 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7511 7512 if (IsD16) 7513 VData = handleD16VData(VData, DAG); 7514 7515 if (!isTypeLegal(VDataVT)) { 7516 VData = 7517 DAG.getNode(ISD::BITCAST, DL, 7518 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7519 } 7520 7521 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7522 SDValue Ops[] = { 7523 Chain, 7524 VData, 7525 Op.getOperand(3), // rsrc 7526 Op.getOperand(4), // vindex 7527 Offsets.first, // voffset 7528 Op.getOperand(6), // soffset 7529 Offsets.second, // offset 7530 Op.getOperand(7), // cachepolicy, swizzled buffer 7531 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7532 }; 7533 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7534 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7535 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7536 MemSDNode *M = cast<MemSDNode>(Op); 7537 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7538 Ops[3])); 7539 7540 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7541 EVT VDataType = VData.getValueType().getScalarType(); 7542 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7543 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7544 7545 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7546 M->getMemoryVT(), M->getMemOperand()); 7547 } 7548 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7549 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7550 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7551 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7552 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7553 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7554 unsigned IdxEn = 1; 7555 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7556 IdxEn = Idx->getZExtValue() != 0; 7557 SDValue Ops[] = { 7558 Chain, 7559 Op.getOperand(2), // vdata 7560 Op.getOperand(3), // rsrc 7561 Op.getOperand(4), // vindex 7562 SDValue(), // voffset -- will be set by setBufferOffsets 7563 SDValue(), // soffset -- will be set by setBufferOffsets 7564 SDValue(), // offset -- will be set by setBufferOffsets 7565 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7566 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7567 }; 7568 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7569 // We don't know the offset if vindex is non-zero, so clear it. 7570 if (IdxEn) 7571 Offset = 0; 7572 EVT VT = Op.getOperand(2).getValueType(); 7573 7574 auto *M = cast<MemSDNode>(Op); 7575 M->getMemOperand()->setOffset(Offset); 7576 7577 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_FADD, DL, 7578 Op->getVTList(), Ops, VT, 7579 M->getMemOperand()); 7580 } 7581 case Intrinsic::amdgcn_end_cf: 7582 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7583 Op->getOperand(2), Chain), 0); 7584 7585 default: { 7586 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7587 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7588 return lowerImage(Op, ImageDimIntr, DAG); 7589 7590 return Op; 7591 } 7592 } 7593 } 7594 7595 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7596 // offset (the offset that is included in bounds checking and swizzling, to be 7597 // split between the instruction's voffset and immoffset fields) and soffset 7598 // (the offset that is excluded from bounds checking and swizzling, to go in 7599 // the instruction's soffset field). This function takes the first kind of 7600 // offset and figures out how to split it between voffset and immoffset. 7601 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7602 SDValue Offset, SelectionDAG &DAG) const { 7603 SDLoc DL(Offset); 7604 const unsigned MaxImm = 4095; 7605 SDValue N0 = Offset; 7606 ConstantSDNode *C1 = nullptr; 7607 7608 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7609 N0 = SDValue(); 7610 else if (DAG.isBaseWithConstantOffset(N0)) { 7611 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7612 N0 = N0.getOperand(0); 7613 } 7614 7615 if (C1) { 7616 unsigned ImmOffset = C1->getZExtValue(); 7617 // If the immediate value is too big for the immoffset field, put the value 7618 // and -4096 into the immoffset field so that the value that is copied/added 7619 // for the voffset field is a multiple of 4096, and it stands more chance 7620 // of being CSEd with the copy/add for another similar load/store. 7621 // However, do not do that rounding down to a multiple of 4096 if that is a 7622 // negative number, as it appears to be illegal to have a negative offset 7623 // in the vgpr, even if adding the immediate offset makes it positive. 7624 unsigned Overflow = ImmOffset & ~MaxImm; 7625 ImmOffset -= Overflow; 7626 if ((int32_t)Overflow < 0) { 7627 Overflow += ImmOffset; 7628 ImmOffset = 0; 7629 } 7630 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7631 if (Overflow) { 7632 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7633 if (!N0) 7634 N0 = OverflowVal; 7635 else { 7636 SDValue Ops[] = { N0, OverflowVal }; 7637 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7638 } 7639 } 7640 } 7641 if (!N0) 7642 N0 = DAG.getConstant(0, DL, MVT::i32); 7643 if (!C1) 7644 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7645 return {N0, SDValue(C1, 0)}; 7646 } 7647 7648 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7649 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7650 // pointed to by Offsets. 7651 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7652 SelectionDAG &DAG, SDValue *Offsets, 7653 Align Alignment) const { 7654 SDLoc DL(CombinedOffset); 7655 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7656 uint32_t Imm = C->getZExtValue(); 7657 uint32_t SOffset, ImmOffset; 7658 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7659 Alignment)) { 7660 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7661 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7662 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7663 return SOffset + ImmOffset; 7664 } 7665 } 7666 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7667 SDValue N0 = CombinedOffset.getOperand(0); 7668 SDValue N1 = CombinedOffset.getOperand(1); 7669 uint32_t SOffset, ImmOffset; 7670 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7671 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7672 Subtarget, Alignment)) { 7673 Offsets[0] = N0; 7674 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7675 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7676 return 0; 7677 } 7678 } 7679 Offsets[0] = CombinedOffset; 7680 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7681 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7682 return 0; 7683 } 7684 7685 // Handle 8 bit and 16 bit buffer loads 7686 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7687 EVT LoadVT, SDLoc DL, 7688 ArrayRef<SDValue> Ops, 7689 MemSDNode *M) const { 7690 EVT IntVT = LoadVT.changeTypeToInteger(); 7691 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7692 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7693 7694 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7695 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7696 Ops, IntVT, 7697 M->getMemOperand()); 7698 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7699 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7700 7701 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7702 } 7703 7704 // Handle 8 bit and 16 bit buffer stores 7705 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7706 EVT VDataType, SDLoc DL, 7707 SDValue Ops[], 7708 MemSDNode *M) const { 7709 if (VDataType == MVT::f16) 7710 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7711 7712 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7713 Ops[1] = BufferStoreExt; 7714 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7715 AMDGPUISD::BUFFER_STORE_SHORT; 7716 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7717 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7718 M->getMemOperand()); 7719 } 7720 7721 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7722 ISD::LoadExtType ExtType, SDValue Op, 7723 const SDLoc &SL, EVT VT) { 7724 if (VT.bitsLT(Op.getValueType())) 7725 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7726 7727 switch (ExtType) { 7728 case ISD::SEXTLOAD: 7729 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7730 case ISD::ZEXTLOAD: 7731 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7732 case ISD::EXTLOAD: 7733 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7734 case ISD::NON_EXTLOAD: 7735 return Op; 7736 } 7737 7738 llvm_unreachable("invalid ext type"); 7739 } 7740 7741 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7742 SelectionDAG &DAG = DCI.DAG; 7743 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7744 return SDValue(); 7745 7746 // FIXME: Constant loads should all be marked invariant. 7747 unsigned AS = Ld->getAddressSpace(); 7748 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7749 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7750 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7751 return SDValue(); 7752 7753 // Don't do this early, since it may interfere with adjacent load merging for 7754 // illegal types. We can avoid losing alignment information for exotic types 7755 // pre-legalize. 7756 EVT MemVT = Ld->getMemoryVT(); 7757 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7758 MemVT.getSizeInBits() >= 32) 7759 return SDValue(); 7760 7761 SDLoc SL(Ld); 7762 7763 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7764 "unexpected vector extload"); 7765 7766 // TODO: Drop only high part of range. 7767 SDValue Ptr = Ld->getBasePtr(); 7768 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7769 MVT::i32, SL, Ld->getChain(), Ptr, 7770 Ld->getOffset(), 7771 Ld->getPointerInfo(), MVT::i32, 7772 Ld->getAlignment(), 7773 Ld->getMemOperand()->getFlags(), 7774 Ld->getAAInfo(), 7775 nullptr); // Drop ranges 7776 7777 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7778 if (MemVT.isFloatingPoint()) { 7779 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7780 "unexpected fp extload"); 7781 TruncVT = MemVT.changeTypeToInteger(); 7782 } 7783 7784 SDValue Cvt = NewLoad; 7785 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7786 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7787 DAG.getValueType(TruncVT)); 7788 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7789 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7790 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7791 } else { 7792 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7793 } 7794 7795 EVT VT = Ld->getValueType(0); 7796 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7797 7798 DCI.AddToWorklist(Cvt.getNode()); 7799 7800 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7801 // the appropriate extension from the 32-bit load. 7802 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7803 DCI.AddToWorklist(Cvt.getNode()); 7804 7805 // Handle conversion back to floating point if necessary. 7806 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7807 7808 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7809 } 7810 7811 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7812 SDLoc DL(Op); 7813 LoadSDNode *Load = cast<LoadSDNode>(Op); 7814 ISD::LoadExtType ExtType = Load->getExtensionType(); 7815 EVT MemVT = Load->getMemoryVT(); 7816 7817 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7818 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7819 return SDValue(); 7820 7821 // FIXME: Copied from PPC 7822 // First, load into 32 bits, then truncate to 1 bit. 7823 7824 SDValue Chain = Load->getChain(); 7825 SDValue BasePtr = Load->getBasePtr(); 7826 MachineMemOperand *MMO = Load->getMemOperand(); 7827 7828 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7829 7830 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7831 BasePtr, RealMemVT, MMO); 7832 7833 if (!MemVT.isVector()) { 7834 SDValue Ops[] = { 7835 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7836 NewLD.getValue(1) 7837 }; 7838 7839 return DAG.getMergeValues(Ops, DL); 7840 } 7841 7842 SmallVector<SDValue, 3> Elts; 7843 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7844 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7845 DAG.getConstant(I, DL, MVT::i32)); 7846 7847 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7848 } 7849 7850 SDValue Ops[] = { 7851 DAG.getBuildVector(MemVT, DL, Elts), 7852 NewLD.getValue(1) 7853 }; 7854 7855 return DAG.getMergeValues(Ops, DL); 7856 } 7857 7858 if (!MemVT.isVector()) 7859 return SDValue(); 7860 7861 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7862 "Custom lowering for non-i32 vectors hasn't been implemented."); 7863 7864 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7865 MemVT, *Load->getMemOperand())) { 7866 SDValue Ops[2]; 7867 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7868 return DAG.getMergeValues(Ops, DL); 7869 } 7870 7871 unsigned Alignment = Load->getAlignment(); 7872 unsigned AS = Load->getAddressSpace(); 7873 if (Subtarget->hasLDSMisalignedBug() && 7874 AS == AMDGPUAS::FLAT_ADDRESS && 7875 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7876 return SplitVectorLoad(Op, DAG); 7877 } 7878 7879 MachineFunction &MF = DAG.getMachineFunction(); 7880 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7881 // If there is a possibilty that flat instruction access scratch memory 7882 // then we need to use the same legalization rules we use for private. 7883 if (AS == AMDGPUAS::FLAT_ADDRESS && 7884 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7885 AS = MFI->hasFlatScratchInit() ? 7886 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7887 7888 unsigned NumElements = MemVT.getVectorNumElements(); 7889 7890 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7891 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7892 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7893 if (MemVT.isPow2VectorType()) 7894 return SDValue(); 7895 if (NumElements == 3) 7896 return WidenVectorLoad(Op, DAG); 7897 return SplitVectorLoad(Op, DAG); 7898 } 7899 // Non-uniform loads will be selected to MUBUF instructions, so they 7900 // have the same legalization requirements as global and private 7901 // loads. 7902 // 7903 } 7904 7905 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7906 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7907 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7908 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7909 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 7910 Alignment >= 4 && NumElements < 32) { 7911 if (MemVT.isPow2VectorType()) 7912 return SDValue(); 7913 if (NumElements == 3) 7914 return WidenVectorLoad(Op, DAG); 7915 return SplitVectorLoad(Op, DAG); 7916 } 7917 // Non-uniform loads will be selected to MUBUF instructions, so they 7918 // have the same legalization requirements as global and private 7919 // loads. 7920 // 7921 } 7922 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7923 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7924 AS == AMDGPUAS::GLOBAL_ADDRESS || 7925 AS == AMDGPUAS::FLAT_ADDRESS) { 7926 if (NumElements > 4) 7927 return SplitVectorLoad(Op, DAG); 7928 // v3 loads not supported on SI. 7929 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7930 return WidenVectorLoad(Op, DAG); 7931 // v3 and v4 loads are supported for private and global memory. 7932 return SDValue(); 7933 } 7934 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7935 // Depending on the setting of the private_element_size field in the 7936 // resource descriptor, we can only make private accesses up to a certain 7937 // size. 7938 switch (Subtarget->getMaxPrivateElementSize()) { 7939 case 4: { 7940 SDValue Ops[2]; 7941 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7942 return DAG.getMergeValues(Ops, DL); 7943 } 7944 case 8: 7945 if (NumElements > 2) 7946 return SplitVectorLoad(Op, DAG); 7947 return SDValue(); 7948 case 16: 7949 // Same as global/flat 7950 if (NumElements > 4) 7951 return SplitVectorLoad(Op, DAG); 7952 // v3 loads not supported on SI. 7953 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7954 return WidenVectorLoad(Op, DAG); 7955 return SDValue(); 7956 default: 7957 llvm_unreachable("unsupported private_element_size"); 7958 } 7959 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7960 // Use ds_read_b128 or ds_read_b96 when possible. 7961 if (Subtarget->hasDS96AndDS128() && 7962 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 7963 MemVT.getStoreSize() == 12) && 7964 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 7965 Load->getAlign())) 7966 return SDValue(); 7967 7968 if (NumElements > 2) 7969 return SplitVectorLoad(Op, DAG); 7970 7971 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7972 // address is negative, then the instruction is incorrectly treated as 7973 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7974 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7975 // load later in the SILoadStoreOptimizer. 7976 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7977 NumElements == 2 && MemVT.getStoreSize() == 8 && 7978 Load->getAlignment() < 8) { 7979 return SplitVectorLoad(Op, DAG); 7980 } 7981 } 7982 return SDValue(); 7983 } 7984 7985 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7986 EVT VT = Op.getValueType(); 7987 assert(VT.getSizeInBits() == 64); 7988 7989 SDLoc DL(Op); 7990 SDValue Cond = Op.getOperand(0); 7991 7992 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7993 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7994 7995 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7996 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7997 7998 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7999 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8000 8001 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8002 8003 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8004 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8005 8006 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8007 8008 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8009 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8010 } 8011 8012 // Catch division cases where we can use shortcuts with rcp and rsq 8013 // instructions. 8014 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8015 SelectionDAG &DAG) const { 8016 SDLoc SL(Op); 8017 SDValue LHS = Op.getOperand(0); 8018 SDValue RHS = Op.getOperand(1); 8019 EVT VT = Op.getValueType(); 8020 const SDNodeFlags Flags = Op->getFlags(); 8021 8022 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 8023 Flags.hasApproximateFuncs(); 8024 8025 // Without !fpmath accuracy information, we can't do more because we don't 8026 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8027 if (!AllowInaccurateRcp) 8028 return SDValue(); 8029 8030 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8031 if (CLHS->isExactlyValue(1.0)) { 8032 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8033 // the CI documentation has a worst case error of 1 ulp. 8034 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8035 // use it as long as we aren't trying to use denormals. 8036 // 8037 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8038 8039 // 1.0 / sqrt(x) -> rsq(x) 8040 8041 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8042 // error seems really high at 2^29 ULP. 8043 if (RHS.getOpcode() == ISD::FSQRT) 8044 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8045 8046 // 1.0 / x -> rcp(x) 8047 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8048 } 8049 8050 // Same as for 1.0, but expand the sign out of the constant. 8051 if (CLHS->isExactlyValue(-1.0)) { 8052 // -1.0 / x -> rcp (fneg x) 8053 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8054 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8055 } 8056 } 8057 8058 // Turn into multiply by the reciprocal. 8059 // x / y -> x * (1.0 / y) 8060 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8061 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8062 } 8063 8064 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8065 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8066 SDNodeFlags Flags) { 8067 if (GlueChain->getNumValues() <= 1) { 8068 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8069 } 8070 8071 assert(GlueChain->getNumValues() == 3); 8072 8073 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8074 switch (Opcode) { 8075 default: llvm_unreachable("no chain equivalent for opcode"); 8076 case ISD::FMUL: 8077 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8078 break; 8079 } 8080 8081 return DAG.getNode(Opcode, SL, VTList, 8082 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8083 Flags); 8084 } 8085 8086 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8087 EVT VT, SDValue A, SDValue B, SDValue C, 8088 SDValue GlueChain, SDNodeFlags Flags) { 8089 if (GlueChain->getNumValues() <= 1) { 8090 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8091 } 8092 8093 assert(GlueChain->getNumValues() == 3); 8094 8095 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8096 switch (Opcode) { 8097 default: llvm_unreachable("no chain equivalent for opcode"); 8098 case ISD::FMA: 8099 Opcode = AMDGPUISD::FMA_W_CHAIN; 8100 break; 8101 } 8102 8103 return DAG.getNode(Opcode, SL, VTList, 8104 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8105 Flags); 8106 } 8107 8108 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8109 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8110 return FastLowered; 8111 8112 SDLoc SL(Op); 8113 SDValue Src0 = Op.getOperand(0); 8114 SDValue Src1 = Op.getOperand(1); 8115 8116 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8117 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8118 8119 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8120 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8121 8122 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8123 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8124 8125 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8126 } 8127 8128 // Faster 2.5 ULP division that does not support denormals. 8129 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8130 SDLoc SL(Op); 8131 SDValue LHS = Op.getOperand(1); 8132 SDValue RHS = Op.getOperand(2); 8133 8134 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8135 8136 const APFloat K0Val(BitsToFloat(0x6f800000)); 8137 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8138 8139 const APFloat K1Val(BitsToFloat(0x2f800000)); 8140 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8141 8142 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8143 8144 EVT SetCCVT = 8145 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8146 8147 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8148 8149 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8150 8151 // TODO: Should this propagate fast-math-flags? 8152 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8153 8154 // rcp does not support denormals. 8155 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8156 8157 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8158 8159 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8160 } 8161 8162 // Returns immediate value for setting the F32 denorm mode when using the 8163 // S_DENORM_MODE instruction. 8164 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8165 const SDLoc &SL, const GCNSubtarget *ST) { 8166 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8167 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8168 ? FP_DENORM_FLUSH_NONE 8169 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8170 8171 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8172 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8173 } 8174 8175 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8176 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8177 return FastLowered; 8178 8179 // The selection matcher assumes anything with a chain selecting to a 8180 // mayRaiseFPException machine instruction. Since we're introducing a chain 8181 // here, we need to explicitly report nofpexcept for the regular fdiv 8182 // lowering. 8183 SDNodeFlags Flags = Op->getFlags(); 8184 Flags.setNoFPExcept(true); 8185 8186 SDLoc SL(Op); 8187 SDValue LHS = Op.getOperand(0); 8188 SDValue RHS = Op.getOperand(1); 8189 8190 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8191 8192 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8193 8194 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8195 {RHS, RHS, LHS}, Flags); 8196 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8197 {LHS, RHS, LHS}, Flags); 8198 8199 // Denominator is scaled to not be denormal, so using rcp is ok. 8200 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8201 DenominatorScaled, Flags); 8202 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8203 DenominatorScaled, Flags); 8204 8205 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8206 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8207 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8208 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8209 8210 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8211 8212 if (!HasFP32Denormals) { 8213 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8214 // lowering. The chain dependence is insufficient, and we need glue. We do 8215 // not need the glue variants in a strictfp function. 8216 8217 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8218 8219 SDNode *EnableDenorm; 8220 if (Subtarget->hasDenormModeInst()) { 8221 const SDValue EnableDenormValue = 8222 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8223 8224 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8225 DAG.getEntryNode(), EnableDenormValue).getNode(); 8226 } else { 8227 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8228 SL, MVT::i32); 8229 EnableDenorm = 8230 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8231 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8232 } 8233 8234 SDValue Ops[3] = { 8235 NegDivScale0, 8236 SDValue(EnableDenorm, 0), 8237 SDValue(EnableDenorm, 1) 8238 }; 8239 8240 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8241 } 8242 8243 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8244 ApproxRcp, One, NegDivScale0, Flags); 8245 8246 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8247 ApproxRcp, Fma0, Flags); 8248 8249 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8250 Fma1, Fma1, Flags); 8251 8252 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8253 NumeratorScaled, Mul, Flags); 8254 8255 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8256 Fma2, Fma1, Mul, Fma2, Flags); 8257 8258 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8259 NumeratorScaled, Fma3, Flags); 8260 8261 if (!HasFP32Denormals) { 8262 SDNode *DisableDenorm; 8263 if (Subtarget->hasDenormModeInst()) { 8264 const SDValue DisableDenormValue = 8265 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8266 8267 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8268 Fma4.getValue(1), DisableDenormValue, 8269 Fma4.getValue(2)).getNode(); 8270 } else { 8271 const SDValue DisableDenormValue = 8272 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8273 8274 DisableDenorm = DAG.getMachineNode( 8275 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8276 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8277 } 8278 8279 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8280 SDValue(DisableDenorm, 0), DAG.getRoot()); 8281 DAG.setRoot(OutputChain); 8282 } 8283 8284 SDValue Scale = NumeratorScaled.getValue(1); 8285 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8286 {Fma4, Fma1, Fma3, Scale}, Flags); 8287 8288 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8289 } 8290 8291 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8292 if (DAG.getTarget().Options.UnsafeFPMath) 8293 return lowerFastUnsafeFDIV(Op, DAG); 8294 8295 SDLoc SL(Op); 8296 SDValue X = Op.getOperand(0); 8297 SDValue Y = Op.getOperand(1); 8298 8299 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8300 8301 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8302 8303 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8304 8305 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8306 8307 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8308 8309 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8310 8311 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8312 8313 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8314 8315 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8316 8317 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8318 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8319 8320 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8321 NegDivScale0, Mul, DivScale1); 8322 8323 SDValue Scale; 8324 8325 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8326 // Workaround a hardware bug on SI where the condition output from div_scale 8327 // is not usable. 8328 8329 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8330 8331 // Figure out if the scale to use for div_fmas. 8332 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8333 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8334 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8335 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8336 8337 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8338 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8339 8340 SDValue Scale0Hi 8341 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8342 SDValue Scale1Hi 8343 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8344 8345 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8346 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8347 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8348 } else { 8349 Scale = DivScale1.getValue(1); 8350 } 8351 8352 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8353 Fma4, Fma3, Mul, Scale); 8354 8355 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8356 } 8357 8358 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8359 EVT VT = Op.getValueType(); 8360 8361 if (VT == MVT::f32) 8362 return LowerFDIV32(Op, DAG); 8363 8364 if (VT == MVT::f64) 8365 return LowerFDIV64(Op, DAG); 8366 8367 if (VT == MVT::f16) 8368 return LowerFDIV16(Op, DAG); 8369 8370 llvm_unreachable("Unexpected type for fdiv"); 8371 } 8372 8373 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8374 SDLoc DL(Op); 8375 StoreSDNode *Store = cast<StoreSDNode>(Op); 8376 EVT VT = Store->getMemoryVT(); 8377 8378 if (VT == MVT::i1) { 8379 return DAG.getTruncStore(Store->getChain(), DL, 8380 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8381 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8382 } 8383 8384 assert(VT.isVector() && 8385 Store->getValue().getValueType().getScalarType() == MVT::i32); 8386 8387 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8388 VT, *Store->getMemOperand())) { 8389 return expandUnalignedStore(Store, DAG); 8390 } 8391 8392 unsigned AS = Store->getAddressSpace(); 8393 if (Subtarget->hasLDSMisalignedBug() && 8394 AS == AMDGPUAS::FLAT_ADDRESS && 8395 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8396 return SplitVectorStore(Op, DAG); 8397 } 8398 8399 MachineFunction &MF = DAG.getMachineFunction(); 8400 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8401 // If there is a possibilty that flat instruction access scratch memory 8402 // then we need to use the same legalization rules we use for private. 8403 if (AS == AMDGPUAS::FLAT_ADDRESS && 8404 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8405 AS = MFI->hasFlatScratchInit() ? 8406 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8407 8408 unsigned NumElements = VT.getVectorNumElements(); 8409 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8410 AS == AMDGPUAS::FLAT_ADDRESS) { 8411 if (NumElements > 4) 8412 return SplitVectorStore(Op, DAG); 8413 // v3 stores not supported on SI. 8414 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8415 return SplitVectorStore(Op, DAG); 8416 return SDValue(); 8417 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8418 switch (Subtarget->getMaxPrivateElementSize()) { 8419 case 4: 8420 return scalarizeVectorStore(Store, DAG); 8421 case 8: 8422 if (NumElements > 2) 8423 return SplitVectorStore(Op, DAG); 8424 return SDValue(); 8425 case 16: 8426 if (NumElements > 4 || NumElements == 3) 8427 return SplitVectorStore(Op, DAG); 8428 return SDValue(); 8429 default: 8430 llvm_unreachable("unsupported private_element_size"); 8431 } 8432 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8433 // Use ds_write_b128 or ds_write_b96 when possible. 8434 if (Subtarget->hasDS96AndDS128() && 8435 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8436 (VT.getStoreSize() == 12)) && 8437 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8438 Store->getAlign())) 8439 return SDValue(); 8440 8441 if (NumElements > 2) 8442 return SplitVectorStore(Op, DAG); 8443 8444 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8445 // address is negative, then the instruction is incorrectly treated as 8446 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8447 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8448 // store later in the SILoadStoreOptimizer. 8449 if (!Subtarget->hasUsableDSOffset() && 8450 NumElements == 2 && VT.getStoreSize() == 8 && 8451 Store->getAlignment() < 8) { 8452 return SplitVectorStore(Op, DAG); 8453 } 8454 8455 return SDValue(); 8456 } else { 8457 llvm_unreachable("unhandled address space"); 8458 } 8459 } 8460 8461 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8462 SDLoc DL(Op); 8463 EVT VT = Op.getValueType(); 8464 SDValue Arg = Op.getOperand(0); 8465 SDValue TrigVal; 8466 8467 // Propagate fast-math flags so that the multiply we introduce can be folded 8468 // if Arg is already the result of a multiply by constant. 8469 auto Flags = Op->getFlags(); 8470 8471 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8472 8473 if (Subtarget->hasTrigReducedRange()) { 8474 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8475 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8476 } else { 8477 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8478 } 8479 8480 switch (Op.getOpcode()) { 8481 case ISD::FCOS: 8482 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8483 case ISD::FSIN: 8484 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8485 default: 8486 llvm_unreachable("Wrong trig opcode"); 8487 } 8488 } 8489 8490 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8491 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8492 assert(AtomicNode->isCompareAndSwap()); 8493 unsigned AS = AtomicNode->getAddressSpace(); 8494 8495 // No custom lowering required for local address space 8496 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8497 return Op; 8498 8499 // Non-local address space requires custom lowering for atomic compare 8500 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8501 SDLoc DL(Op); 8502 SDValue ChainIn = Op.getOperand(0); 8503 SDValue Addr = Op.getOperand(1); 8504 SDValue Old = Op.getOperand(2); 8505 SDValue New = Op.getOperand(3); 8506 EVT VT = Op.getValueType(); 8507 MVT SimpleVT = VT.getSimpleVT(); 8508 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8509 8510 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8511 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8512 8513 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8514 Ops, VT, AtomicNode->getMemOperand()); 8515 } 8516 8517 //===----------------------------------------------------------------------===// 8518 // Custom DAG optimizations 8519 //===----------------------------------------------------------------------===// 8520 8521 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8522 DAGCombinerInfo &DCI) const { 8523 EVT VT = N->getValueType(0); 8524 EVT ScalarVT = VT.getScalarType(); 8525 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8526 return SDValue(); 8527 8528 SelectionDAG &DAG = DCI.DAG; 8529 SDLoc DL(N); 8530 8531 SDValue Src = N->getOperand(0); 8532 EVT SrcVT = Src.getValueType(); 8533 8534 // TODO: We could try to match extracting the higher bytes, which would be 8535 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8536 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8537 // about in practice. 8538 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8539 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8540 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8541 DCI.AddToWorklist(Cvt.getNode()); 8542 8543 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8544 if (ScalarVT != MVT::f32) { 8545 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8546 DAG.getTargetConstant(0, DL, MVT::i32)); 8547 } 8548 return Cvt; 8549 } 8550 } 8551 8552 return SDValue(); 8553 } 8554 8555 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8556 8557 // This is a variant of 8558 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8559 // 8560 // The normal DAG combiner will do this, but only if the add has one use since 8561 // that would increase the number of instructions. 8562 // 8563 // This prevents us from seeing a constant offset that can be folded into a 8564 // memory instruction's addressing mode. If we know the resulting add offset of 8565 // a pointer can be folded into an addressing offset, we can replace the pointer 8566 // operand with the add of new constant offset. This eliminates one of the uses, 8567 // and may allow the remaining use to also be simplified. 8568 // 8569 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8570 unsigned AddrSpace, 8571 EVT MemVT, 8572 DAGCombinerInfo &DCI) const { 8573 SDValue N0 = N->getOperand(0); 8574 SDValue N1 = N->getOperand(1); 8575 8576 // We only do this to handle cases where it's profitable when there are 8577 // multiple uses of the add, so defer to the standard combine. 8578 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8579 N0->hasOneUse()) 8580 return SDValue(); 8581 8582 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8583 if (!CN1) 8584 return SDValue(); 8585 8586 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8587 if (!CAdd) 8588 return SDValue(); 8589 8590 // If the resulting offset is too large, we can't fold it into the addressing 8591 // mode offset. 8592 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8593 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8594 8595 AddrMode AM; 8596 AM.HasBaseReg = true; 8597 AM.BaseOffs = Offset.getSExtValue(); 8598 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8599 return SDValue(); 8600 8601 SelectionDAG &DAG = DCI.DAG; 8602 SDLoc SL(N); 8603 EVT VT = N->getValueType(0); 8604 8605 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8606 SDValue COffset = DAG.getConstant(Offset, SL, VT); 8607 8608 SDNodeFlags Flags; 8609 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8610 (N0.getOpcode() == ISD::OR || 8611 N0->getFlags().hasNoUnsignedWrap())); 8612 8613 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8614 } 8615 8616 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 8617 /// by the chain and intrinsic ID. Theoretically we would also need to check the 8618 /// specific intrinsic, but they all place the pointer operand first. 8619 static unsigned getBasePtrIndex(const MemSDNode *N) { 8620 switch (N->getOpcode()) { 8621 case ISD::STORE: 8622 case ISD::INTRINSIC_W_CHAIN: 8623 case ISD::INTRINSIC_VOID: 8624 return 2; 8625 default: 8626 return 1; 8627 } 8628 } 8629 8630 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8631 DAGCombinerInfo &DCI) const { 8632 SelectionDAG &DAG = DCI.DAG; 8633 SDLoc SL(N); 8634 8635 unsigned PtrIdx = getBasePtrIndex(N); 8636 SDValue Ptr = N->getOperand(PtrIdx); 8637 8638 // TODO: We could also do this for multiplies. 8639 if (Ptr.getOpcode() == ISD::SHL) { 8640 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8641 N->getMemoryVT(), DCI); 8642 if (NewPtr) { 8643 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8644 8645 NewOps[PtrIdx] = NewPtr; 8646 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8647 } 8648 } 8649 8650 return SDValue(); 8651 } 8652 8653 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8654 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8655 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8656 (Opc == ISD::XOR && Val == 0); 8657 } 8658 8659 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8660 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8661 // integer combine opportunities since most 64-bit operations are decomposed 8662 // this way. TODO: We won't want this for SALU especially if it is an inline 8663 // immediate. 8664 SDValue SITargetLowering::splitBinaryBitConstantOp( 8665 DAGCombinerInfo &DCI, 8666 const SDLoc &SL, 8667 unsigned Opc, SDValue LHS, 8668 const ConstantSDNode *CRHS) const { 8669 uint64_t Val = CRHS->getZExtValue(); 8670 uint32_t ValLo = Lo_32(Val); 8671 uint32_t ValHi = Hi_32(Val); 8672 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8673 8674 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8675 bitOpWithConstantIsReducible(Opc, ValHi)) || 8676 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8677 // If we need to materialize a 64-bit immediate, it will be split up later 8678 // anyway. Avoid creating the harder to understand 64-bit immediate 8679 // materialization. 8680 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8681 } 8682 8683 return SDValue(); 8684 } 8685 8686 // Returns true if argument is a boolean value which is not serialized into 8687 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8688 static bool isBoolSGPR(SDValue V) { 8689 if (V.getValueType() != MVT::i1) 8690 return false; 8691 switch (V.getOpcode()) { 8692 default: break; 8693 case ISD::SETCC: 8694 case ISD::AND: 8695 case ISD::OR: 8696 case ISD::XOR: 8697 case AMDGPUISD::FP_CLASS: 8698 return true; 8699 } 8700 return false; 8701 } 8702 8703 // If a constant has all zeroes or all ones within each byte return it. 8704 // Otherwise return 0. 8705 static uint32_t getConstantPermuteMask(uint32_t C) { 8706 // 0xff for any zero byte in the mask 8707 uint32_t ZeroByteMask = 0; 8708 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8709 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8710 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8711 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8712 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8713 if ((NonZeroByteMask & C) != NonZeroByteMask) 8714 return 0; // Partial bytes selected. 8715 return C; 8716 } 8717 8718 // Check if a node selects whole bytes from its operand 0 starting at a byte 8719 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8720 // or -1 if not succeeded. 8721 // Note byte select encoding: 8722 // value 0-3 selects corresponding source byte; 8723 // value 0xc selects zero; 8724 // value 0xff selects 0xff. 8725 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8726 assert(V.getValueSizeInBits() == 32); 8727 8728 if (V.getNumOperands() != 2) 8729 return ~0; 8730 8731 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8732 if (!N1) 8733 return ~0; 8734 8735 uint32_t C = N1->getZExtValue(); 8736 8737 switch (V.getOpcode()) { 8738 default: 8739 break; 8740 case ISD::AND: 8741 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8742 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8743 } 8744 break; 8745 8746 case ISD::OR: 8747 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8748 return (0x03020100 & ~ConstMask) | ConstMask; 8749 } 8750 break; 8751 8752 case ISD::SHL: 8753 if (C % 8) 8754 return ~0; 8755 8756 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8757 8758 case ISD::SRL: 8759 if (C % 8) 8760 return ~0; 8761 8762 return uint32_t(0x0c0c0c0c03020100ull >> C); 8763 } 8764 8765 return ~0; 8766 } 8767 8768 SDValue SITargetLowering::performAndCombine(SDNode *N, 8769 DAGCombinerInfo &DCI) const { 8770 if (DCI.isBeforeLegalize()) 8771 return SDValue(); 8772 8773 SelectionDAG &DAG = DCI.DAG; 8774 EVT VT = N->getValueType(0); 8775 SDValue LHS = N->getOperand(0); 8776 SDValue RHS = N->getOperand(1); 8777 8778 8779 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8780 if (VT == MVT::i64 && CRHS) { 8781 if (SDValue Split 8782 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8783 return Split; 8784 } 8785 8786 if (CRHS && VT == MVT::i32) { 8787 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8788 // nb = number of trailing zeroes in mask 8789 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8790 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8791 uint64_t Mask = CRHS->getZExtValue(); 8792 unsigned Bits = countPopulation(Mask); 8793 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8794 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8795 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8796 unsigned Shift = CShift->getZExtValue(); 8797 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8798 unsigned Offset = NB + Shift; 8799 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8800 SDLoc SL(N); 8801 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8802 LHS->getOperand(0), 8803 DAG.getConstant(Offset, SL, MVT::i32), 8804 DAG.getConstant(Bits, SL, MVT::i32)); 8805 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8806 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8807 DAG.getValueType(NarrowVT)); 8808 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8809 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8810 return Shl; 8811 } 8812 } 8813 } 8814 8815 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8816 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8817 isa<ConstantSDNode>(LHS.getOperand(2))) { 8818 uint32_t Sel = getConstantPermuteMask(Mask); 8819 if (!Sel) 8820 return SDValue(); 8821 8822 // Select 0xc for all zero bytes 8823 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8824 SDLoc DL(N); 8825 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8826 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8827 } 8828 } 8829 8830 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8831 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8832 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8833 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8834 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8835 8836 SDValue X = LHS.getOperand(0); 8837 SDValue Y = RHS.getOperand(0); 8838 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8839 return SDValue(); 8840 8841 if (LCC == ISD::SETO) { 8842 if (X != LHS.getOperand(1)) 8843 return SDValue(); 8844 8845 if (RCC == ISD::SETUNE) { 8846 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8847 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8848 return SDValue(); 8849 8850 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8851 SIInstrFlags::N_SUBNORMAL | 8852 SIInstrFlags::N_ZERO | 8853 SIInstrFlags::P_ZERO | 8854 SIInstrFlags::P_SUBNORMAL | 8855 SIInstrFlags::P_NORMAL; 8856 8857 static_assert(((~(SIInstrFlags::S_NAN | 8858 SIInstrFlags::Q_NAN | 8859 SIInstrFlags::N_INFINITY | 8860 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8861 "mask not equal"); 8862 8863 SDLoc DL(N); 8864 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8865 X, DAG.getConstant(Mask, DL, MVT::i32)); 8866 } 8867 } 8868 } 8869 8870 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8871 std::swap(LHS, RHS); 8872 8873 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8874 RHS.hasOneUse()) { 8875 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8876 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8877 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8878 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8879 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8880 (RHS.getOperand(0) == LHS.getOperand(0) && 8881 LHS.getOperand(0) == LHS.getOperand(1))) { 8882 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8883 unsigned NewMask = LCC == ISD::SETO ? 8884 Mask->getZExtValue() & ~OrdMask : 8885 Mask->getZExtValue() & OrdMask; 8886 8887 SDLoc DL(N); 8888 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8889 DAG.getConstant(NewMask, DL, MVT::i32)); 8890 } 8891 } 8892 8893 if (VT == MVT::i32 && 8894 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8895 // and x, (sext cc from i1) => select cc, x, 0 8896 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8897 std::swap(LHS, RHS); 8898 if (isBoolSGPR(RHS.getOperand(0))) 8899 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8900 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8901 } 8902 8903 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8904 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8905 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8906 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8907 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8908 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8909 if (LHSMask != ~0u && RHSMask != ~0u) { 8910 // Canonicalize the expression in an attempt to have fewer unique masks 8911 // and therefore fewer registers used to hold the masks. 8912 if (LHSMask > RHSMask) { 8913 std::swap(LHSMask, RHSMask); 8914 std::swap(LHS, RHS); 8915 } 8916 8917 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8918 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8919 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8920 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8921 8922 // Check of we need to combine values from two sources within a byte. 8923 if (!(LHSUsedLanes & RHSUsedLanes) && 8924 // If we select high and lower word keep it for SDWA. 8925 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8926 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8927 // Each byte in each mask is either selector mask 0-3, or has higher 8928 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8929 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8930 // mask which is not 0xff wins. By anding both masks we have a correct 8931 // result except that 0x0c shall be corrected to give 0x0c only. 8932 uint32_t Mask = LHSMask & RHSMask; 8933 for (unsigned I = 0; I < 32; I += 8) { 8934 uint32_t ByteSel = 0xff << I; 8935 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8936 Mask &= (0x0c << I) & 0xffffffff; 8937 } 8938 8939 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8940 // or 0x0c. 8941 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8942 SDLoc DL(N); 8943 8944 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8945 LHS.getOperand(0), RHS.getOperand(0), 8946 DAG.getConstant(Sel, DL, MVT::i32)); 8947 } 8948 } 8949 } 8950 8951 return SDValue(); 8952 } 8953 8954 SDValue SITargetLowering::performOrCombine(SDNode *N, 8955 DAGCombinerInfo &DCI) const { 8956 SelectionDAG &DAG = DCI.DAG; 8957 SDValue LHS = N->getOperand(0); 8958 SDValue RHS = N->getOperand(1); 8959 8960 EVT VT = N->getValueType(0); 8961 if (VT == MVT::i1) { 8962 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8963 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8964 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8965 SDValue Src = LHS.getOperand(0); 8966 if (Src != RHS.getOperand(0)) 8967 return SDValue(); 8968 8969 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8970 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8971 if (!CLHS || !CRHS) 8972 return SDValue(); 8973 8974 // Only 10 bits are used. 8975 static const uint32_t MaxMask = 0x3ff; 8976 8977 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8978 SDLoc DL(N); 8979 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8980 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8981 } 8982 8983 return SDValue(); 8984 } 8985 8986 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8987 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8988 LHS.getOpcode() == AMDGPUISD::PERM && 8989 isa<ConstantSDNode>(LHS.getOperand(2))) { 8990 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8991 if (!Sel) 8992 return SDValue(); 8993 8994 Sel |= LHS.getConstantOperandVal(2); 8995 SDLoc DL(N); 8996 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8997 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8998 } 8999 9000 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9001 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9002 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9003 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 9004 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9005 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9006 if (LHSMask != ~0u && RHSMask != ~0u) { 9007 // Canonicalize the expression in an attempt to have fewer unique masks 9008 // and therefore fewer registers used to hold the masks. 9009 if (LHSMask > RHSMask) { 9010 std::swap(LHSMask, RHSMask); 9011 std::swap(LHS, RHS); 9012 } 9013 9014 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9015 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9016 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9017 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9018 9019 // Check of we need to combine values from two sources within a byte. 9020 if (!(LHSUsedLanes & RHSUsedLanes) && 9021 // If we select high and lower word keep it for SDWA. 9022 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9023 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9024 // Kill zero bytes selected by other mask. Zero value is 0xc. 9025 LHSMask &= ~RHSUsedLanes; 9026 RHSMask &= ~LHSUsedLanes; 9027 // Add 4 to each active LHS lane 9028 LHSMask |= LHSUsedLanes & 0x04040404; 9029 // Combine masks 9030 uint32_t Sel = LHSMask | RHSMask; 9031 SDLoc DL(N); 9032 9033 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9034 LHS.getOperand(0), RHS.getOperand(0), 9035 DAG.getConstant(Sel, DL, MVT::i32)); 9036 } 9037 } 9038 } 9039 9040 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9041 return SDValue(); 9042 9043 // TODO: This could be a generic combine with a predicate for extracting the 9044 // high half of an integer being free. 9045 9046 // (or i64:x, (zero_extend i32:y)) -> 9047 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9048 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9049 RHS.getOpcode() != ISD::ZERO_EXTEND) 9050 std::swap(LHS, RHS); 9051 9052 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9053 SDValue ExtSrc = RHS.getOperand(0); 9054 EVT SrcVT = ExtSrc.getValueType(); 9055 if (SrcVT == MVT::i32) { 9056 SDLoc SL(N); 9057 SDValue LowLHS, HiBits; 9058 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9059 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9060 9061 DCI.AddToWorklist(LowOr.getNode()); 9062 DCI.AddToWorklist(HiBits.getNode()); 9063 9064 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9065 LowOr, HiBits); 9066 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9067 } 9068 } 9069 9070 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9071 if (CRHS) { 9072 if (SDValue Split 9073 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9074 return Split; 9075 } 9076 9077 return SDValue(); 9078 } 9079 9080 SDValue SITargetLowering::performXorCombine(SDNode *N, 9081 DAGCombinerInfo &DCI) const { 9082 EVT VT = N->getValueType(0); 9083 if (VT != MVT::i64) 9084 return SDValue(); 9085 9086 SDValue LHS = N->getOperand(0); 9087 SDValue RHS = N->getOperand(1); 9088 9089 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9090 if (CRHS) { 9091 if (SDValue Split 9092 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9093 return Split; 9094 } 9095 9096 return SDValue(); 9097 } 9098 9099 // Instructions that will be lowered with a final instruction that zeros the 9100 // high result bits. 9101 // XXX - probably only need to list legal operations. 9102 static bool fp16SrcZerosHighBits(unsigned Opc) { 9103 switch (Opc) { 9104 case ISD::FADD: 9105 case ISD::FSUB: 9106 case ISD::FMUL: 9107 case ISD::FDIV: 9108 case ISD::FREM: 9109 case ISD::FMA: 9110 case ISD::FMAD: 9111 case ISD::FCANONICALIZE: 9112 case ISD::FP_ROUND: 9113 case ISD::UINT_TO_FP: 9114 case ISD::SINT_TO_FP: 9115 case ISD::FABS: 9116 // Fabs is lowered to a bit operation, but it's an and which will clear the 9117 // high bits anyway. 9118 case ISD::FSQRT: 9119 case ISD::FSIN: 9120 case ISD::FCOS: 9121 case ISD::FPOWI: 9122 case ISD::FPOW: 9123 case ISD::FLOG: 9124 case ISD::FLOG2: 9125 case ISD::FLOG10: 9126 case ISD::FEXP: 9127 case ISD::FEXP2: 9128 case ISD::FCEIL: 9129 case ISD::FTRUNC: 9130 case ISD::FRINT: 9131 case ISD::FNEARBYINT: 9132 case ISD::FROUND: 9133 case ISD::FFLOOR: 9134 case ISD::FMINNUM: 9135 case ISD::FMAXNUM: 9136 case AMDGPUISD::FRACT: 9137 case AMDGPUISD::CLAMP: 9138 case AMDGPUISD::COS_HW: 9139 case AMDGPUISD::SIN_HW: 9140 case AMDGPUISD::FMIN3: 9141 case AMDGPUISD::FMAX3: 9142 case AMDGPUISD::FMED3: 9143 case AMDGPUISD::FMAD_FTZ: 9144 case AMDGPUISD::RCP: 9145 case AMDGPUISD::RSQ: 9146 case AMDGPUISD::RCP_IFLAG: 9147 case AMDGPUISD::LDEXP: 9148 return true; 9149 default: 9150 // fcopysign, select and others may be lowered to 32-bit bit operations 9151 // which don't zero the high bits. 9152 return false; 9153 } 9154 } 9155 9156 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9157 DAGCombinerInfo &DCI) const { 9158 if (!Subtarget->has16BitInsts() || 9159 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9160 return SDValue(); 9161 9162 EVT VT = N->getValueType(0); 9163 if (VT != MVT::i32) 9164 return SDValue(); 9165 9166 SDValue Src = N->getOperand(0); 9167 if (Src.getValueType() != MVT::i16) 9168 return SDValue(); 9169 9170 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9171 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9172 if (Src.getOpcode() == ISD::BITCAST) { 9173 SDValue BCSrc = Src.getOperand(0); 9174 if (BCSrc.getValueType() == MVT::f16 && 9175 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9176 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9177 } 9178 9179 return SDValue(); 9180 } 9181 9182 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9183 DAGCombinerInfo &DCI) 9184 const { 9185 SDValue Src = N->getOperand(0); 9186 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9187 9188 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9189 VTSign->getVT() == MVT::i8) || 9190 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9191 VTSign->getVT() == MVT::i16)) && 9192 Src.hasOneUse()) { 9193 auto *M = cast<MemSDNode>(Src); 9194 SDValue Ops[] = { 9195 Src.getOperand(0), // Chain 9196 Src.getOperand(1), // rsrc 9197 Src.getOperand(2), // vindex 9198 Src.getOperand(3), // voffset 9199 Src.getOperand(4), // soffset 9200 Src.getOperand(5), // offset 9201 Src.getOperand(6), 9202 Src.getOperand(7) 9203 }; 9204 // replace with BUFFER_LOAD_BYTE/SHORT 9205 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9206 Src.getOperand(0).getValueType()); 9207 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9208 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9209 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9210 ResList, 9211 Ops, M->getMemoryVT(), 9212 M->getMemOperand()); 9213 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9214 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9215 } 9216 return SDValue(); 9217 } 9218 9219 SDValue SITargetLowering::performClassCombine(SDNode *N, 9220 DAGCombinerInfo &DCI) const { 9221 SelectionDAG &DAG = DCI.DAG; 9222 SDValue Mask = N->getOperand(1); 9223 9224 // fp_class x, 0 -> false 9225 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9226 if (CMask->isNullValue()) 9227 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9228 } 9229 9230 if (N->getOperand(0).isUndef()) 9231 return DAG.getUNDEF(MVT::i1); 9232 9233 return SDValue(); 9234 } 9235 9236 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9237 DAGCombinerInfo &DCI) const { 9238 EVT VT = N->getValueType(0); 9239 SDValue N0 = N->getOperand(0); 9240 9241 if (N0.isUndef()) 9242 return N0; 9243 9244 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9245 N0.getOpcode() == ISD::SINT_TO_FP)) { 9246 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9247 N->getFlags()); 9248 } 9249 9250 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9251 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9252 N0.getOperand(0), N->getFlags()); 9253 } 9254 9255 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9256 } 9257 9258 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9259 unsigned MaxDepth) const { 9260 unsigned Opcode = Op.getOpcode(); 9261 if (Opcode == ISD::FCANONICALIZE) 9262 return true; 9263 9264 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9265 auto F = CFP->getValueAPF(); 9266 if (F.isNaN() && F.isSignaling()) 9267 return false; 9268 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9269 } 9270 9271 // If source is a result of another standard FP operation it is already in 9272 // canonical form. 9273 if (MaxDepth == 0) 9274 return false; 9275 9276 switch (Opcode) { 9277 // These will flush denorms if required. 9278 case ISD::FADD: 9279 case ISD::FSUB: 9280 case ISD::FMUL: 9281 case ISD::FCEIL: 9282 case ISD::FFLOOR: 9283 case ISD::FMA: 9284 case ISD::FMAD: 9285 case ISD::FSQRT: 9286 case ISD::FDIV: 9287 case ISD::FREM: 9288 case ISD::FP_ROUND: 9289 case ISD::FP_EXTEND: 9290 case AMDGPUISD::FMUL_LEGACY: 9291 case AMDGPUISD::FMAD_FTZ: 9292 case AMDGPUISD::RCP: 9293 case AMDGPUISD::RSQ: 9294 case AMDGPUISD::RSQ_CLAMP: 9295 case AMDGPUISD::RCP_LEGACY: 9296 case AMDGPUISD::RCP_IFLAG: 9297 case AMDGPUISD::DIV_SCALE: 9298 case AMDGPUISD::DIV_FMAS: 9299 case AMDGPUISD::DIV_FIXUP: 9300 case AMDGPUISD::FRACT: 9301 case AMDGPUISD::LDEXP: 9302 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9303 case AMDGPUISD::CVT_F32_UBYTE0: 9304 case AMDGPUISD::CVT_F32_UBYTE1: 9305 case AMDGPUISD::CVT_F32_UBYTE2: 9306 case AMDGPUISD::CVT_F32_UBYTE3: 9307 return true; 9308 9309 // It can/will be lowered or combined as a bit operation. 9310 // Need to check their input recursively to handle. 9311 case ISD::FNEG: 9312 case ISD::FABS: 9313 case ISD::FCOPYSIGN: 9314 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9315 9316 case ISD::FSIN: 9317 case ISD::FCOS: 9318 case ISD::FSINCOS: 9319 return Op.getValueType().getScalarType() != MVT::f16; 9320 9321 case ISD::FMINNUM: 9322 case ISD::FMAXNUM: 9323 case ISD::FMINNUM_IEEE: 9324 case ISD::FMAXNUM_IEEE: 9325 case AMDGPUISD::CLAMP: 9326 case AMDGPUISD::FMED3: 9327 case AMDGPUISD::FMAX3: 9328 case AMDGPUISD::FMIN3: { 9329 // FIXME: Shouldn't treat the generic operations different based these. 9330 // However, we aren't really required to flush the result from 9331 // minnum/maxnum.. 9332 9333 // snans will be quieted, so we only need to worry about denormals. 9334 if (Subtarget->supportsMinMaxDenormModes() || 9335 denormalsEnabledForType(DAG, Op.getValueType())) 9336 return true; 9337 9338 // Flushing may be required. 9339 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9340 // targets need to check their input recursively. 9341 9342 // FIXME: Does this apply with clamp? It's implemented with max. 9343 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9344 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9345 return false; 9346 } 9347 9348 return true; 9349 } 9350 case ISD::SELECT: { 9351 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9352 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9353 } 9354 case ISD::BUILD_VECTOR: { 9355 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9356 SDValue SrcOp = Op.getOperand(i); 9357 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9358 return false; 9359 } 9360 9361 return true; 9362 } 9363 case ISD::EXTRACT_VECTOR_ELT: 9364 case ISD::EXTRACT_SUBVECTOR: { 9365 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9366 } 9367 case ISD::INSERT_VECTOR_ELT: { 9368 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9369 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9370 } 9371 case ISD::UNDEF: 9372 // Could be anything. 9373 return false; 9374 9375 case ISD::BITCAST: { 9376 // Hack round the mess we make when legalizing extract_vector_elt 9377 SDValue Src = Op.getOperand(0); 9378 if (Src.getValueType() == MVT::i16 && 9379 Src.getOpcode() == ISD::TRUNCATE) { 9380 SDValue TruncSrc = Src.getOperand(0); 9381 if (TruncSrc.getValueType() == MVT::i32 && 9382 TruncSrc.getOpcode() == ISD::BITCAST && 9383 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9384 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9385 } 9386 } 9387 9388 return false; 9389 } 9390 case ISD::INTRINSIC_WO_CHAIN: { 9391 unsigned IntrinsicID 9392 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9393 // TODO: Handle more intrinsics 9394 switch (IntrinsicID) { 9395 case Intrinsic::amdgcn_cvt_pkrtz: 9396 case Intrinsic::amdgcn_cubeid: 9397 case Intrinsic::amdgcn_frexp_mant: 9398 case Intrinsic::amdgcn_fdot2: 9399 case Intrinsic::amdgcn_rcp: 9400 case Intrinsic::amdgcn_rsq: 9401 case Intrinsic::amdgcn_rsq_clamp: 9402 case Intrinsic::amdgcn_rcp_legacy: 9403 case Intrinsic::amdgcn_rsq_legacy: 9404 case Intrinsic::amdgcn_trig_preop: 9405 return true; 9406 default: 9407 break; 9408 } 9409 9410 LLVM_FALLTHROUGH; 9411 } 9412 default: 9413 return denormalsEnabledForType(DAG, Op.getValueType()) && 9414 DAG.isKnownNeverSNaN(Op); 9415 } 9416 9417 llvm_unreachable("invalid operation"); 9418 } 9419 9420 // Constant fold canonicalize. 9421 SDValue SITargetLowering::getCanonicalConstantFP( 9422 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9423 // Flush denormals to 0 if not enabled. 9424 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9425 return DAG.getConstantFP(0.0, SL, VT); 9426 9427 if (C.isNaN()) { 9428 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9429 if (C.isSignaling()) { 9430 // Quiet a signaling NaN. 9431 // FIXME: Is this supposed to preserve payload bits? 9432 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9433 } 9434 9435 // Make sure it is the canonical NaN bitpattern. 9436 // 9437 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9438 // immediate? 9439 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9440 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9441 } 9442 9443 // Already canonical. 9444 return DAG.getConstantFP(C, SL, VT); 9445 } 9446 9447 static bool vectorEltWillFoldAway(SDValue Op) { 9448 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9449 } 9450 9451 SDValue SITargetLowering::performFCanonicalizeCombine( 9452 SDNode *N, 9453 DAGCombinerInfo &DCI) const { 9454 SelectionDAG &DAG = DCI.DAG; 9455 SDValue N0 = N->getOperand(0); 9456 EVT VT = N->getValueType(0); 9457 9458 // fcanonicalize undef -> qnan 9459 if (N0.isUndef()) { 9460 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9461 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9462 } 9463 9464 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9465 EVT VT = N->getValueType(0); 9466 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9467 } 9468 9469 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9470 // (fcanonicalize k) 9471 // 9472 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9473 9474 // TODO: This could be better with wider vectors that will be split to v2f16, 9475 // and to consider uses since there aren't that many packed operations. 9476 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9477 isTypeLegal(MVT::v2f16)) { 9478 SDLoc SL(N); 9479 SDValue NewElts[2]; 9480 SDValue Lo = N0.getOperand(0); 9481 SDValue Hi = N0.getOperand(1); 9482 EVT EltVT = Lo.getValueType(); 9483 9484 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9485 for (unsigned I = 0; I != 2; ++I) { 9486 SDValue Op = N0.getOperand(I); 9487 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9488 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9489 CFP->getValueAPF()); 9490 } else if (Op.isUndef()) { 9491 // Handled below based on what the other operand is. 9492 NewElts[I] = Op; 9493 } else { 9494 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9495 } 9496 } 9497 9498 // If one half is undef, and one is constant, perfer a splat vector rather 9499 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9500 // cheaper to use and may be free with a packed operation. 9501 if (NewElts[0].isUndef()) { 9502 if (isa<ConstantFPSDNode>(NewElts[1])) 9503 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9504 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9505 } 9506 9507 if (NewElts[1].isUndef()) { 9508 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9509 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9510 } 9511 9512 return DAG.getBuildVector(VT, SL, NewElts); 9513 } 9514 } 9515 9516 unsigned SrcOpc = N0.getOpcode(); 9517 9518 // If it's free to do so, push canonicalizes further up the source, which may 9519 // find a canonical source. 9520 // 9521 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9522 // sNaNs. 9523 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9524 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9525 if (CRHS && N0.hasOneUse()) { 9526 SDLoc SL(N); 9527 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9528 N0.getOperand(0)); 9529 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9530 DCI.AddToWorklist(Canon0.getNode()); 9531 9532 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9533 } 9534 } 9535 9536 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9537 } 9538 9539 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9540 switch (Opc) { 9541 case ISD::FMAXNUM: 9542 case ISD::FMAXNUM_IEEE: 9543 return AMDGPUISD::FMAX3; 9544 case ISD::SMAX: 9545 return AMDGPUISD::SMAX3; 9546 case ISD::UMAX: 9547 return AMDGPUISD::UMAX3; 9548 case ISD::FMINNUM: 9549 case ISD::FMINNUM_IEEE: 9550 return AMDGPUISD::FMIN3; 9551 case ISD::SMIN: 9552 return AMDGPUISD::SMIN3; 9553 case ISD::UMIN: 9554 return AMDGPUISD::UMIN3; 9555 default: 9556 llvm_unreachable("Not a min/max opcode"); 9557 } 9558 } 9559 9560 SDValue SITargetLowering::performIntMed3ImmCombine( 9561 SelectionDAG &DAG, const SDLoc &SL, 9562 SDValue Op0, SDValue Op1, bool Signed) const { 9563 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9564 if (!K1) 9565 return SDValue(); 9566 9567 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9568 if (!K0) 9569 return SDValue(); 9570 9571 if (Signed) { 9572 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9573 return SDValue(); 9574 } else { 9575 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9576 return SDValue(); 9577 } 9578 9579 EVT VT = K0->getValueType(0); 9580 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9581 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9582 return DAG.getNode(Med3Opc, SL, VT, 9583 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9584 } 9585 9586 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9587 MVT NVT = MVT::i32; 9588 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9589 9590 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9591 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9592 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9593 9594 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9595 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9596 } 9597 9598 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9599 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9600 return C; 9601 9602 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9603 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9604 return C; 9605 } 9606 9607 return nullptr; 9608 } 9609 9610 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9611 const SDLoc &SL, 9612 SDValue Op0, 9613 SDValue Op1) const { 9614 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9615 if (!K1) 9616 return SDValue(); 9617 9618 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9619 if (!K0) 9620 return SDValue(); 9621 9622 // Ordered >= (although NaN inputs should have folded away by now). 9623 if (K0->getValueAPF() > K1->getValueAPF()) 9624 return SDValue(); 9625 9626 const MachineFunction &MF = DAG.getMachineFunction(); 9627 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9628 9629 // TODO: Check IEEE bit enabled? 9630 EVT VT = Op0.getValueType(); 9631 if (Info->getMode().DX10Clamp) { 9632 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9633 // hardware fmed3 behavior converting to a min. 9634 // FIXME: Should this be allowing -0.0? 9635 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9636 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9637 } 9638 9639 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9640 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9641 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9642 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9643 // then give the other result, which is different from med3 with a NaN 9644 // input. 9645 SDValue Var = Op0.getOperand(0); 9646 if (!DAG.isKnownNeverSNaN(Var)) 9647 return SDValue(); 9648 9649 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9650 9651 if ((!K0->hasOneUse() || 9652 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9653 (!K1->hasOneUse() || 9654 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9655 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9656 Var, SDValue(K0, 0), SDValue(K1, 0)); 9657 } 9658 } 9659 9660 return SDValue(); 9661 } 9662 9663 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9664 DAGCombinerInfo &DCI) const { 9665 SelectionDAG &DAG = DCI.DAG; 9666 9667 EVT VT = N->getValueType(0); 9668 unsigned Opc = N->getOpcode(); 9669 SDValue Op0 = N->getOperand(0); 9670 SDValue Op1 = N->getOperand(1); 9671 9672 // Only do this if the inner op has one use since this will just increases 9673 // register pressure for no benefit. 9674 9675 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9676 !VT.isVector() && 9677 (VT == MVT::i32 || VT == MVT::f32 || 9678 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9679 // max(max(a, b), c) -> max3(a, b, c) 9680 // min(min(a, b), c) -> min3(a, b, c) 9681 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9682 SDLoc DL(N); 9683 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9684 DL, 9685 N->getValueType(0), 9686 Op0.getOperand(0), 9687 Op0.getOperand(1), 9688 Op1); 9689 } 9690 9691 // Try commuted. 9692 // max(a, max(b, c)) -> max3(a, b, c) 9693 // min(a, min(b, c)) -> min3(a, b, c) 9694 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9695 SDLoc DL(N); 9696 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9697 DL, 9698 N->getValueType(0), 9699 Op0, 9700 Op1.getOperand(0), 9701 Op1.getOperand(1)); 9702 } 9703 } 9704 9705 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9706 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9707 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9708 return Med3; 9709 } 9710 9711 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9712 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9713 return Med3; 9714 } 9715 9716 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9717 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9718 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9719 (Opc == AMDGPUISD::FMIN_LEGACY && 9720 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9721 (VT == MVT::f32 || VT == MVT::f64 || 9722 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9723 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9724 Op0.hasOneUse()) { 9725 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9726 return Res; 9727 } 9728 9729 return SDValue(); 9730 } 9731 9732 static bool isClampZeroToOne(SDValue A, SDValue B) { 9733 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9734 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9735 // FIXME: Should this be allowing -0.0? 9736 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9737 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9738 } 9739 } 9740 9741 return false; 9742 } 9743 9744 // FIXME: Should only worry about snans for version with chain. 9745 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9746 DAGCombinerInfo &DCI) const { 9747 EVT VT = N->getValueType(0); 9748 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9749 // NaNs. With a NaN input, the order of the operands may change the result. 9750 9751 SelectionDAG &DAG = DCI.DAG; 9752 SDLoc SL(N); 9753 9754 SDValue Src0 = N->getOperand(0); 9755 SDValue Src1 = N->getOperand(1); 9756 SDValue Src2 = N->getOperand(2); 9757 9758 if (isClampZeroToOne(Src0, Src1)) { 9759 // const_a, const_b, x -> clamp is safe in all cases including signaling 9760 // nans. 9761 // FIXME: Should this be allowing -0.0? 9762 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9763 } 9764 9765 const MachineFunction &MF = DAG.getMachineFunction(); 9766 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9767 9768 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9769 // handling no dx10-clamp? 9770 if (Info->getMode().DX10Clamp) { 9771 // If NaNs is clamped to 0, we are free to reorder the inputs. 9772 9773 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9774 std::swap(Src0, Src1); 9775 9776 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9777 std::swap(Src1, Src2); 9778 9779 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9780 std::swap(Src0, Src1); 9781 9782 if (isClampZeroToOne(Src1, Src2)) 9783 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9784 } 9785 9786 return SDValue(); 9787 } 9788 9789 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9790 DAGCombinerInfo &DCI) const { 9791 SDValue Src0 = N->getOperand(0); 9792 SDValue Src1 = N->getOperand(1); 9793 if (Src0.isUndef() && Src1.isUndef()) 9794 return DCI.DAG.getUNDEF(N->getValueType(0)); 9795 return SDValue(); 9796 } 9797 9798 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 9799 // expanded into a set of cmp/select instructions. 9800 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 9801 unsigned NumElem, 9802 bool IsDivergentIdx) { 9803 if (UseDivergentRegisterIndexing) 9804 return false; 9805 9806 unsigned VecSize = EltSize * NumElem; 9807 9808 // Sub-dword vectors of size 2 dword or less have better implementation. 9809 if (VecSize <= 64 && EltSize < 32) 9810 return false; 9811 9812 // Always expand the rest of sub-dword instructions, otherwise it will be 9813 // lowered via memory. 9814 if (EltSize < 32) 9815 return true; 9816 9817 // Always do this if var-idx is divergent, otherwise it will become a loop. 9818 if (IsDivergentIdx) 9819 return true; 9820 9821 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 9822 unsigned NumInsts = NumElem /* Number of compares */ + 9823 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 9824 return NumInsts <= 16; 9825 } 9826 9827 static bool shouldExpandVectorDynExt(SDNode *N) { 9828 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 9829 if (isa<ConstantSDNode>(Idx)) 9830 return false; 9831 9832 SDValue Vec = N->getOperand(0); 9833 EVT VecVT = Vec.getValueType(); 9834 EVT EltVT = VecVT.getVectorElementType(); 9835 unsigned EltSize = EltVT.getSizeInBits(); 9836 unsigned NumElem = VecVT.getVectorNumElements(); 9837 9838 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 9839 Idx->isDivergent()); 9840 } 9841 9842 SDValue SITargetLowering::performExtractVectorEltCombine( 9843 SDNode *N, DAGCombinerInfo &DCI) const { 9844 SDValue Vec = N->getOperand(0); 9845 SelectionDAG &DAG = DCI.DAG; 9846 9847 EVT VecVT = Vec.getValueType(); 9848 EVT EltVT = VecVT.getVectorElementType(); 9849 9850 if ((Vec.getOpcode() == ISD::FNEG || 9851 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9852 SDLoc SL(N); 9853 EVT EltVT = N->getValueType(0); 9854 SDValue Idx = N->getOperand(1); 9855 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9856 Vec.getOperand(0), Idx); 9857 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9858 } 9859 9860 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9861 // => 9862 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9863 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9864 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9865 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9866 SDLoc SL(N); 9867 EVT EltVT = N->getValueType(0); 9868 SDValue Idx = N->getOperand(1); 9869 unsigned Opc = Vec.getOpcode(); 9870 9871 switch(Opc) { 9872 default: 9873 break; 9874 // TODO: Support other binary operations. 9875 case ISD::FADD: 9876 case ISD::FSUB: 9877 case ISD::FMUL: 9878 case ISD::ADD: 9879 case ISD::UMIN: 9880 case ISD::UMAX: 9881 case ISD::SMIN: 9882 case ISD::SMAX: 9883 case ISD::FMAXNUM: 9884 case ISD::FMINNUM: 9885 case ISD::FMAXNUM_IEEE: 9886 case ISD::FMINNUM_IEEE: { 9887 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9888 Vec.getOperand(0), Idx); 9889 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9890 Vec.getOperand(1), Idx); 9891 9892 DCI.AddToWorklist(Elt0.getNode()); 9893 DCI.AddToWorklist(Elt1.getNode()); 9894 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9895 } 9896 } 9897 } 9898 9899 unsigned VecSize = VecVT.getSizeInBits(); 9900 unsigned EltSize = EltVT.getSizeInBits(); 9901 9902 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9903 if (::shouldExpandVectorDynExt(N)) { 9904 SDLoc SL(N); 9905 SDValue Idx = N->getOperand(1); 9906 SDValue V; 9907 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9908 SDValue IC = DAG.getVectorIdxConstant(I, SL); 9909 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9910 if (I == 0) 9911 V = Elt; 9912 else 9913 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9914 } 9915 return V; 9916 } 9917 9918 if (!DCI.isBeforeLegalize()) 9919 return SDValue(); 9920 9921 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9922 // elements. This exposes more load reduction opportunities by replacing 9923 // multiple small extract_vector_elements with a single 32-bit extract. 9924 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9925 if (isa<MemSDNode>(Vec) && 9926 EltSize <= 16 && 9927 EltVT.isByteSized() && 9928 VecSize > 32 && 9929 VecSize % 32 == 0 && 9930 Idx) { 9931 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9932 9933 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9934 unsigned EltIdx = BitIndex / 32; 9935 unsigned LeftoverBitIdx = BitIndex % 32; 9936 SDLoc SL(N); 9937 9938 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9939 DCI.AddToWorklist(Cast.getNode()); 9940 9941 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9942 DAG.getConstant(EltIdx, SL, MVT::i32)); 9943 DCI.AddToWorklist(Elt.getNode()); 9944 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9945 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9946 DCI.AddToWorklist(Srl.getNode()); 9947 9948 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9949 DCI.AddToWorklist(Trunc.getNode()); 9950 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9951 } 9952 9953 return SDValue(); 9954 } 9955 9956 SDValue 9957 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9958 DAGCombinerInfo &DCI) const { 9959 SDValue Vec = N->getOperand(0); 9960 SDValue Idx = N->getOperand(2); 9961 EVT VecVT = Vec.getValueType(); 9962 EVT EltVT = VecVT.getVectorElementType(); 9963 9964 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9965 // => BUILD_VECTOR n x select (e, const-idx) 9966 if (!::shouldExpandVectorDynExt(N)) 9967 return SDValue(); 9968 9969 SelectionDAG &DAG = DCI.DAG; 9970 SDLoc SL(N); 9971 SDValue Ins = N->getOperand(1); 9972 EVT IdxVT = Idx.getValueType(); 9973 9974 SmallVector<SDValue, 16> Ops; 9975 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9976 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9977 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9978 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9979 Ops.push_back(V); 9980 } 9981 9982 return DAG.getBuildVector(VecVT, SL, Ops); 9983 } 9984 9985 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9986 const SDNode *N0, 9987 const SDNode *N1) const { 9988 EVT VT = N0->getValueType(0); 9989 9990 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9991 // support denormals ever. 9992 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9993 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9994 getSubtarget()->hasMadF16())) && 9995 isOperationLegal(ISD::FMAD, VT)) 9996 return ISD::FMAD; 9997 9998 const TargetOptions &Options = DAG.getTarget().Options; 9999 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10000 (N0->getFlags().hasAllowContract() && 10001 N1->getFlags().hasAllowContract())) && 10002 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10003 return ISD::FMA; 10004 } 10005 10006 return 0; 10007 } 10008 10009 // For a reassociatable opcode perform: 10010 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10011 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10012 SelectionDAG &DAG) const { 10013 EVT VT = N->getValueType(0); 10014 if (VT != MVT::i32 && VT != MVT::i64) 10015 return SDValue(); 10016 10017 unsigned Opc = N->getOpcode(); 10018 SDValue Op0 = N->getOperand(0); 10019 SDValue Op1 = N->getOperand(1); 10020 10021 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10022 return SDValue(); 10023 10024 if (Op0->isDivergent()) 10025 std::swap(Op0, Op1); 10026 10027 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10028 return SDValue(); 10029 10030 SDValue Op2 = Op1.getOperand(1); 10031 Op1 = Op1.getOperand(0); 10032 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10033 return SDValue(); 10034 10035 if (Op1->isDivergent()) 10036 std::swap(Op1, Op2); 10037 10038 // If either operand is constant this will conflict with 10039 // DAGCombiner::ReassociateOps(). 10040 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10041 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10042 return SDValue(); 10043 10044 SDLoc SL(N); 10045 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10046 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10047 } 10048 10049 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10050 EVT VT, 10051 SDValue N0, SDValue N1, SDValue N2, 10052 bool Signed) { 10053 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10054 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10055 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10056 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10057 } 10058 10059 SDValue SITargetLowering::performAddCombine(SDNode *N, 10060 DAGCombinerInfo &DCI) const { 10061 SelectionDAG &DAG = DCI.DAG; 10062 EVT VT = N->getValueType(0); 10063 SDLoc SL(N); 10064 SDValue LHS = N->getOperand(0); 10065 SDValue RHS = N->getOperand(1); 10066 10067 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10068 && Subtarget->hasMad64_32() && 10069 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10070 VT.getScalarSizeInBits() <= 64) { 10071 if (LHS.getOpcode() != ISD::MUL) 10072 std::swap(LHS, RHS); 10073 10074 SDValue MulLHS = LHS.getOperand(0); 10075 SDValue MulRHS = LHS.getOperand(1); 10076 SDValue AddRHS = RHS; 10077 10078 // TODO: Maybe restrict if SGPR inputs. 10079 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10080 numBitsUnsigned(MulRHS, DAG) <= 32) { 10081 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10082 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10083 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10084 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10085 } 10086 10087 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10088 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10089 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10090 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10091 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10092 } 10093 10094 return SDValue(); 10095 } 10096 10097 if (SDValue V = reassociateScalarOps(N, DAG)) { 10098 return V; 10099 } 10100 10101 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10102 return SDValue(); 10103 10104 // add x, zext (setcc) => addcarry x, 0, setcc 10105 // add x, sext (setcc) => subcarry x, 0, setcc 10106 unsigned Opc = LHS.getOpcode(); 10107 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10108 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10109 std::swap(RHS, LHS); 10110 10111 Opc = RHS.getOpcode(); 10112 switch (Opc) { 10113 default: break; 10114 case ISD::ZERO_EXTEND: 10115 case ISD::SIGN_EXTEND: 10116 case ISD::ANY_EXTEND: { 10117 auto Cond = RHS.getOperand(0); 10118 // If this won't be a real VOPC output, we would still need to insert an 10119 // extra instruction anyway. 10120 if (!isBoolSGPR(Cond)) 10121 break; 10122 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10123 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10124 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10125 return DAG.getNode(Opc, SL, VTList, Args); 10126 } 10127 case ISD::ADDCARRY: { 10128 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10129 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10130 if (!C || C->getZExtValue() != 0) break; 10131 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10132 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10133 } 10134 } 10135 return SDValue(); 10136 } 10137 10138 SDValue SITargetLowering::performSubCombine(SDNode *N, 10139 DAGCombinerInfo &DCI) const { 10140 SelectionDAG &DAG = DCI.DAG; 10141 EVT VT = N->getValueType(0); 10142 10143 if (VT != MVT::i32) 10144 return SDValue(); 10145 10146 SDLoc SL(N); 10147 SDValue LHS = N->getOperand(0); 10148 SDValue RHS = N->getOperand(1); 10149 10150 // sub x, zext (setcc) => subcarry x, 0, setcc 10151 // sub x, sext (setcc) => addcarry x, 0, setcc 10152 unsigned Opc = RHS.getOpcode(); 10153 switch (Opc) { 10154 default: break; 10155 case ISD::ZERO_EXTEND: 10156 case ISD::SIGN_EXTEND: 10157 case ISD::ANY_EXTEND: { 10158 auto Cond = RHS.getOperand(0); 10159 // If this won't be a real VOPC output, we would still need to insert an 10160 // extra instruction anyway. 10161 if (!isBoolSGPR(Cond)) 10162 break; 10163 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10164 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10165 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10166 return DAG.getNode(Opc, SL, VTList, Args); 10167 } 10168 } 10169 10170 if (LHS.getOpcode() == ISD::SUBCARRY) { 10171 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10172 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10173 if (!C || !C->isNullValue()) 10174 return SDValue(); 10175 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10176 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10177 } 10178 return SDValue(); 10179 } 10180 10181 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10182 DAGCombinerInfo &DCI) const { 10183 10184 if (N->getValueType(0) != MVT::i32) 10185 return SDValue(); 10186 10187 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10188 if (!C || C->getZExtValue() != 0) 10189 return SDValue(); 10190 10191 SelectionDAG &DAG = DCI.DAG; 10192 SDValue LHS = N->getOperand(0); 10193 10194 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10195 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10196 unsigned LHSOpc = LHS.getOpcode(); 10197 unsigned Opc = N->getOpcode(); 10198 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10199 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10200 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10201 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10202 } 10203 return SDValue(); 10204 } 10205 10206 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10207 DAGCombinerInfo &DCI) const { 10208 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10209 return SDValue(); 10210 10211 SelectionDAG &DAG = DCI.DAG; 10212 EVT VT = N->getValueType(0); 10213 10214 SDLoc SL(N); 10215 SDValue LHS = N->getOperand(0); 10216 SDValue RHS = N->getOperand(1); 10217 10218 // These should really be instruction patterns, but writing patterns with 10219 // source modiifiers is a pain. 10220 10221 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10222 if (LHS.getOpcode() == ISD::FADD) { 10223 SDValue A = LHS.getOperand(0); 10224 if (A == LHS.getOperand(1)) { 10225 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10226 if (FusedOp != 0) { 10227 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10228 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10229 } 10230 } 10231 } 10232 10233 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10234 if (RHS.getOpcode() == ISD::FADD) { 10235 SDValue A = RHS.getOperand(0); 10236 if (A == RHS.getOperand(1)) { 10237 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10238 if (FusedOp != 0) { 10239 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10240 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10241 } 10242 } 10243 } 10244 10245 return SDValue(); 10246 } 10247 10248 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10249 DAGCombinerInfo &DCI) const { 10250 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10251 return SDValue(); 10252 10253 SelectionDAG &DAG = DCI.DAG; 10254 SDLoc SL(N); 10255 EVT VT = N->getValueType(0); 10256 assert(!VT.isVector()); 10257 10258 // Try to get the fneg to fold into the source modifier. This undoes generic 10259 // DAG combines and folds them into the mad. 10260 // 10261 // Only do this if we are not trying to support denormals. v_mad_f32 does 10262 // not support denormals ever. 10263 SDValue LHS = N->getOperand(0); 10264 SDValue RHS = N->getOperand(1); 10265 if (LHS.getOpcode() == ISD::FADD) { 10266 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10267 SDValue A = LHS.getOperand(0); 10268 if (A == LHS.getOperand(1)) { 10269 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10270 if (FusedOp != 0){ 10271 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10272 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10273 10274 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10275 } 10276 } 10277 } 10278 10279 if (RHS.getOpcode() == ISD::FADD) { 10280 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10281 10282 SDValue A = RHS.getOperand(0); 10283 if (A == RHS.getOperand(1)) { 10284 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10285 if (FusedOp != 0){ 10286 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10287 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10288 } 10289 } 10290 } 10291 10292 return SDValue(); 10293 } 10294 10295 SDValue SITargetLowering::performFMACombine(SDNode *N, 10296 DAGCombinerInfo &DCI) const { 10297 SelectionDAG &DAG = DCI.DAG; 10298 EVT VT = N->getValueType(0); 10299 SDLoc SL(N); 10300 10301 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 10302 return SDValue(); 10303 10304 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10305 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10306 SDValue Op1 = N->getOperand(0); 10307 SDValue Op2 = N->getOperand(1); 10308 SDValue FMA = N->getOperand(2); 10309 10310 if (FMA.getOpcode() != ISD::FMA || 10311 Op1.getOpcode() != ISD::FP_EXTEND || 10312 Op2.getOpcode() != ISD::FP_EXTEND) 10313 return SDValue(); 10314 10315 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10316 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10317 // is sufficient to allow generaing fdot2. 10318 const TargetOptions &Options = DAG.getTarget().Options; 10319 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10320 (N->getFlags().hasAllowContract() && 10321 FMA->getFlags().hasAllowContract())) { 10322 Op1 = Op1.getOperand(0); 10323 Op2 = Op2.getOperand(0); 10324 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10325 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10326 return SDValue(); 10327 10328 SDValue Vec1 = Op1.getOperand(0); 10329 SDValue Idx1 = Op1.getOperand(1); 10330 SDValue Vec2 = Op2.getOperand(0); 10331 10332 SDValue FMAOp1 = FMA.getOperand(0); 10333 SDValue FMAOp2 = FMA.getOperand(1); 10334 SDValue FMAAcc = FMA.getOperand(2); 10335 10336 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10337 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10338 return SDValue(); 10339 10340 FMAOp1 = FMAOp1.getOperand(0); 10341 FMAOp2 = FMAOp2.getOperand(0); 10342 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10343 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10344 return SDValue(); 10345 10346 SDValue Vec3 = FMAOp1.getOperand(0); 10347 SDValue Vec4 = FMAOp2.getOperand(0); 10348 SDValue Idx2 = FMAOp1.getOperand(1); 10349 10350 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10351 // Idx1 and Idx2 cannot be the same. 10352 Idx1 == Idx2) 10353 return SDValue(); 10354 10355 if (Vec1 == Vec2 || Vec3 == Vec4) 10356 return SDValue(); 10357 10358 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10359 return SDValue(); 10360 10361 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10362 (Vec1 == Vec4 && Vec2 == Vec3)) { 10363 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10364 DAG.getTargetConstant(0, SL, MVT::i1)); 10365 } 10366 } 10367 return SDValue(); 10368 } 10369 10370 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10371 DAGCombinerInfo &DCI) const { 10372 SelectionDAG &DAG = DCI.DAG; 10373 SDLoc SL(N); 10374 10375 SDValue LHS = N->getOperand(0); 10376 SDValue RHS = N->getOperand(1); 10377 EVT VT = LHS.getValueType(); 10378 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10379 10380 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10381 if (!CRHS) { 10382 CRHS = dyn_cast<ConstantSDNode>(LHS); 10383 if (CRHS) { 10384 std::swap(LHS, RHS); 10385 CC = getSetCCSwappedOperands(CC); 10386 } 10387 } 10388 10389 if (CRHS) { 10390 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10391 isBoolSGPR(LHS.getOperand(0))) { 10392 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10393 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10394 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10395 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10396 if ((CRHS->isAllOnesValue() && 10397 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10398 (CRHS->isNullValue() && 10399 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10400 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10401 DAG.getConstant(-1, SL, MVT::i1)); 10402 if ((CRHS->isAllOnesValue() && 10403 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10404 (CRHS->isNullValue() && 10405 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10406 return LHS.getOperand(0); 10407 } 10408 10409 uint64_t CRHSVal = CRHS->getZExtValue(); 10410 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10411 LHS.getOpcode() == ISD::SELECT && 10412 isa<ConstantSDNode>(LHS.getOperand(1)) && 10413 isa<ConstantSDNode>(LHS.getOperand(2)) && 10414 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10415 isBoolSGPR(LHS.getOperand(0))) { 10416 // Given CT != FT: 10417 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10418 // setcc (select cc, CT, CF), CF, ne => cc 10419 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10420 // setcc (select cc, CT, CF), CT, eq => cc 10421 uint64_t CT = LHS.getConstantOperandVal(1); 10422 uint64_t CF = LHS.getConstantOperandVal(2); 10423 10424 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10425 (CT == CRHSVal && CC == ISD::SETNE)) 10426 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10427 DAG.getConstant(-1, SL, MVT::i1)); 10428 if ((CF == CRHSVal && CC == ISD::SETNE) || 10429 (CT == CRHSVal && CC == ISD::SETEQ)) 10430 return LHS.getOperand(0); 10431 } 10432 } 10433 10434 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10435 VT != MVT::f16)) 10436 return SDValue(); 10437 10438 // Match isinf/isfinite pattern 10439 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10440 // (fcmp one (fabs x), inf) -> (fp_class x, 10441 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10442 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10443 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10444 if (!CRHS) 10445 return SDValue(); 10446 10447 const APFloat &APF = CRHS->getValueAPF(); 10448 if (APF.isInfinity() && !APF.isNegative()) { 10449 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10450 SIInstrFlags::N_INFINITY; 10451 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10452 SIInstrFlags::P_ZERO | 10453 SIInstrFlags::N_NORMAL | 10454 SIInstrFlags::P_NORMAL | 10455 SIInstrFlags::N_SUBNORMAL | 10456 SIInstrFlags::P_SUBNORMAL; 10457 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10458 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10459 DAG.getConstant(Mask, SL, MVT::i32)); 10460 } 10461 } 10462 10463 return SDValue(); 10464 } 10465 10466 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10467 DAGCombinerInfo &DCI) const { 10468 SelectionDAG &DAG = DCI.DAG; 10469 SDLoc SL(N); 10470 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10471 10472 SDValue Src = N->getOperand(0); 10473 SDValue Shift = N->getOperand(0); 10474 10475 // TODO: Extend type shouldn't matter (assuming legal types). 10476 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10477 Shift = Shift.getOperand(0); 10478 10479 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10480 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10481 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10482 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10483 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10484 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10485 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10486 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10487 SDLoc(Shift.getOperand(0)), MVT::i32); 10488 10489 unsigned ShiftOffset = 8 * Offset; 10490 if (Shift.getOpcode() == ISD::SHL) 10491 ShiftOffset -= C->getZExtValue(); 10492 else 10493 ShiftOffset += C->getZExtValue(); 10494 10495 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10496 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10497 MVT::f32, Shift); 10498 } 10499 } 10500 } 10501 10502 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10503 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10504 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10505 // We simplified Src. If this node is not dead, visit it again so it is 10506 // folded properly. 10507 if (N->getOpcode() != ISD::DELETED_NODE) 10508 DCI.AddToWorklist(N); 10509 return SDValue(N, 0); 10510 } 10511 10512 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10513 if (SDValue DemandedSrc = 10514 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10515 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10516 10517 return SDValue(); 10518 } 10519 10520 SDValue SITargetLowering::performClampCombine(SDNode *N, 10521 DAGCombinerInfo &DCI) const { 10522 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10523 if (!CSrc) 10524 return SDValue(); 10525 10526 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10527 const APFloat &F = CSrc->getValueAPF(); 10528 APFloat Zero = APFloat::getZero(F.getSemantics()); 10529 if (F < Zero || 10530 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10531 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10532 } 10533 10534 APFloat One(F.getSemantics(), "1.0"); 10535 if (F > One) 10536 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10537 10538 return SDValue(CSrc, 0); 10539 } 10540 10541 10542 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10543 DAGCombinerInfo &DCI) const { 10544 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10545 return SDValue(); 10546 switch (N->getOpcode()) { 10547 case ISD::ADD: 10548 return performAddCombine(N, DCI); 10549 case ISD::SUB: 10550 return performSubCombine(N, DCI); 10551 case ISD::ADDCARRY: 10552 case ISD::SUBCARRY: 10553 return performAddCarrySubCarryCombine(N, DCI); 10554 case ISD::FADD: 10555 return performFAddCombine(N, DCI); 10556 case ISD::FSUB: 10557 return performFSubCombine(N, DCI); 10558 case ISD::SETCC: 10559 return performSetCCCombine(N, DCI); 10560 case ISD::FMAXNUM: 10561 case ISD::FMINNUM: 10562 case ISD::FMAXNUM_IEEE: 10563 case ISD::FMINNUM_IEEE: 10564 case ISD::SMAX: 10565 case ISD::SMIN: 10566 case ISD::UMAX: 10567 case ISD::UMIN: 10568 case AMDGPUISD::FMIN_LEGACY: 10569 case AMDGPUISD::FMAX_LEGACY: 10570 return performMinMaxCombine(N, DCI); 10571 case ISD::FMA: 10572 return performFMACombine(N, DCI); 10573 case ISD::AND: 10574 return performAndCombine(N, DCI); 10575 case ISD::OR: 10576 return performOrCombine(N, DCI); 10577 case ISD::XOR: 10578 return performXorCombine(N, DCI); 10579 case ISD::ZERO_EXTEND: 10580 return performZeroExtendCombine(N, DCI); 10581 case ISD::SIGN_EXTEND_INREG: 10582 return performSignExtendInRegCombine(N , DCI); 10583 case AMDGPUISD::FP_CLASS: 10584 return performClassCombine(N, DCI); 10585 case ISD::FCANONICALIZE: 10586 return performFCanonicalizeCombine(N, DCI); 10587 case AMDGPUISD::RCP: 10588 return performRcpCombine(N, DCI); 10589 case AMDGPUISD::FRACT: 10590 case AMDGPUISD::RSQ: 10591 case AMDGPUISD::RCP_LEGACY: 10592 case AMDGPUISD::RCP_IFLAG: 10593 case AMDGPUISD::RSQ_CLAMP: 10594 case AMDGPUISD::LDEXP: { 10595 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10596 SDValue Src = N->getOperand(0); 10597 if (Src.isUndef()) 10598 return Src; 10599 break; 10600 } 10601 case ISD::SINT_TO_FP: 10602 case ISD::UINT_TO_FP: 10603 return performUCharToFloatCombine(N, DCI); 10604 case AMDGPUISD::CVT_F32_UBYTE0: 10605 case AMDGPUISD::CVT_F32_UBYTE1: 10606 case AMDGPUISD::CVT_F32_UBYTE2: 10607 case AMDGPUISD::CVT_F32_UBYTE3: 10608 return performCvtF32UByteNCombine(N, DCI); 10609 case AMDGPUISD::FMED3: 10610 return performFMed3Combine(N, DCI); 10611 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10612 return performCvtPkRTZCombine(N, DCI); 10613 case AMDGPUISD::CLAMP: 10614 return performClampCombine(N, DCI); 10615 case ISD::SCALAR_TO_VECTOR: { 10616 SelectionDAG &DAG = DCI.DAG; 10617 EVT VT = N->getValueType(0); 10618 10619 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10620 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10621 SDLoc SL(N); 10622 SDValue Src = N->getOperand(0); 10623 EVT EltVT = Src.getValueType(); 10624 if (EltVT == MVT::f16) 10625 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10626 10627 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10628 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10629 } 10630 10631 break; 10632 } 10633 case ISD::EXTRACT_VECTOR_ELT: 10634 return performExtractVectorEltCombine(N, DCI); 10635 case ISD::INSERT_VECTOR_ELT: 10636 return performInsertVectorEltCombine(N, DCI); 10637 case ISD::LOAD: { 10638 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10639 return Widended; 10640 LLVM_FALLTHROUGH; 10641 } 10642 default: { 10643 if (!DCI.isBeforeLegalize()) { 10644 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 10645 return performMemSDNodeCombine(MemNode, DCI); 10646 } 10647 10648 break; 10649 } 10650 } 10651 10652 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10653 } 10654 10655 /// Helper function for adjustWritemask 10656 static unsigned SubIdx2Lane(unsigned Idx) { 10657 switch (Idx) { 10658 default: return 0; 10659 case AMDGPU::sub0: return 0; 10660 case AMDGPU::sub1: return 1; 10661 case AMDGPU::sub2: return 2; 10662 case AMDGPU::sub3: return 3; 10663 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10664 } 10665 } 10666 10667 /// Adjust the writemask of MIMG instructions 10668 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10669 SelectionDAG &DAG) const { 10670 unsigned Opcode = Node->getMachineOpcode(); 10671 10672 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10673 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10674 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10675 return Node; // not implemented for D16 10676 10677 SDNode *Users[5] = { nullptr }; 10678 unsigned Lane = 0; 10679 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10680 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10681 unsigned NewDmask = 0; 10682 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10683 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10684 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10685 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10686 unsigned TFCLane = 0; 10687 bool HasChain = Node->getNumValues() > 1; 10688 10689 if (OldDmask == 0) { 10690 // These are folded out, but on the chance it happens don't assert. 10691 return Node; 10692 } 10693 10694 unsigned OldBitsSet = countPopulation(OldDmask); 10695 // Work out which is the TFE/LWE lane if that is enabled. 10696 if (UsesTFC) { 10697 TFCLane = OldBitsSet; 10698 } 10699 10700 // Try to figure out the used register components 10701 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10702 I != E; ++I) { 10703 10704 // Don't look at users of the chain. 10705 if (I.getUse().getResNo() != 0) 10706 continue; 10707 10708 // Abort if we can't understand the usage 10709 if (!I->isMachineOpcode() || 10710 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10711 return Node; 10712 10713 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10714 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10715 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10716 // set, etc. 10717 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10718 10719 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10720 if (UsesTFC && Lane == TFCLane) { 10721 Users[Lane] = *I; 10722 } else { 10723 // Set which texture component corresponds to the lane. 10724 unsigned Comp; 10725 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10726 Comp = countTrailingZeros(Dmask); 10727 Dmask &= ~(1 << Comp); 10728 } 10729 10730 // Abort if we have more than one user per component. 10731 if (Users[Lane]) 10732 return Node; 10733 10734 Users[Lane] = *I; 10735 NewDmask |= 1 << Comp; 10736 } 10737 } 10738 10739 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10740 bool NoChannels = !NewDmask; 10741 if (NoChannels) { 10742 if (!UsesTFC) { 10743 // No uses of the result and not using TFC. Then do nothing. 10744 return Node; 10745 } 10746 // If the original dmask has one channel - then nothing to do 10747 if (OldBitsSet == 1) 10748 return Node; 10749 // Use an arbitrary dmask - required for the instruction to work 10750 NewDmask = 1; 10751 } 10752 // Abort if there's no change 10753 if (NewDmask == OldDmask) 10754 return Node; 10755 10756 unsigned BitsSet = countPopulation(NewDmask); 10757 10758 // Check for TFE or LWE - increase the number of channels by one to account 10759 // for the extra return value 10760 // This will need adjustment for D16 if this is also included in 10761 // adjustWriteMask (this function) but at present D16 are excluded. 10762 unsigned NewChannels = BitsSet + UsesTFC; 10763 10764 int NewOpcode = 10765 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10766 assert(NewOpcode != -1 && 10767 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10768 "failed to find equivalent MIMG op"); 10769 10770 // Adjust the writemask in the node 10771 SmallVector<SDValue, 12> Ops; 10772 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10773 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10774 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10775 10776 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10777 10778 MVT ResultVT = NewChannels == 1 ? 10779 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10780 NewChannels == 5 ? 8 : NewChannels); 10781 SDVTList NewVTList = HasChain ? 10782 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10783 10784 10785 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10786 NewVTList, Ops); 10787 10788 if (HasChain) { 10789 // Update chain. 10790 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10791 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10792 } 10793 10794 if (NewChannels == 1) { 10795 assert(Node->hasNUsesOfValue(1, 0)); 10796 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10797 SDLoc(Node), Users[Lane]->getValueType(0), 10798 SDValue(NewNode, 0)); 10799 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10800 return nullptr; 10801 } 10802 10803 // Update the users of the node with the new indices 10804 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10805 SDNode *User = Users[i]; 10806 if (!User) { 10807 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10808 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10809 if (i || !NoChannels) 10810 continue; 10811 } else { 10812 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10813 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10814 } 10815 10816 switch (Idx) { 10817 default: break; 10818 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10819 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10820 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10821 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10822 } 10823 } 10824 10825 DAG.RemoveDeadNode(Node); 10826 return nullptr; 10827 } 10828 10829 static bool isFrameIndexOp(SDValue Op) { 10830 if (Op.getOpcode() == ISD::AssertZext) 10831 Op = Op.getOperand(0); 10832 10833 return isa<FrameIndexSDNode>(Op); 10834 } 10835 10836 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10837 /// with frame index operands. 10838 /// LLVM assumes that inputs are to these instructions are registers. 10839 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10840 SelectionDAG &DAG) const { 10841 if (Node->getOpcode() == ISD::CopyToReg) { 10842 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10843 SDValue SrcVal = Node->getOperand(2); 10844 10845 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10846 // to try understanding copies to physical registers. 10847 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 10848 SDLoc SL(Node); 10849 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10850 SDValue VReg = DAG.getRegister( 10851 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10852 10853 SDNode *Glued = Node->getGluedNode(); 10854 SDValue ToVReg 10855 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10856 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10857 SDValue ToResultReg 10858 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10859 VReg, ToVReg.getValue(1)); 10860 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10861 DAG.RemoveDeadNode(Node); 10862 return ToResultReg.getNode(); 10863 } 10864 } 10865 10866 SmallVector<SDValue, 8> Ops; 10867 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10868 if (!isFrameIndexOp(Node->getOperand(i))) { 10869 Ops.push_back(Node->getOperand(i)); 10870 continue; 10871 } 10872 10873 SDLoc DL(Node); 10874 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10875 Node->getOperand(i).getValueType(), 10876 Node->getOperand(i)), 0)); 10877 } 10878 10879 return DAG.UpdateNodeOperands(Node, Ops); 10880 } 10881 10882 /// Fold the instructions after selecting them. 10883 /// Returns null if users were already updated. 10884 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10885 SelectionDAG &DAG) const { 10886 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10887 unsigned Opcode = Node->getMachineOpcode(); 10888 10889 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10890 !TII->isGather4(Opcode)) { 10891 return adjustWritemask(Node, DAG); 10892 } 10893 10894 if (Opcode == AMDGPU::INSERT_SUBREG || 10895 Opcode == AMDGPU::REG_SEQUENCE) { 10896 legalizeTargetIndependentNode(Node, DAG); 10897 return Node; 10898 } 10899 10900 switch (Opcode) { 10901 case AMDGPU::V_DIV_SCALE_F32: 10902 case AMDGPU::V_DIV_SCALE_F64: { 10903 // Satisfy the operand register constraint when one of the inputs is 10904 // undefined. Ordinarily each undef value will have its own implicit_def of 10905 // a vreg, so force these to use a single register. 10906 SDValue Src0 = Node->getOperand(0); 10907 SDValue Src1 = Node->getOperand(1); 10908 SDValue Src2 = Node->getOperand(2); 10909 10910 if ((Src0.isMachineOpcode() && 10911 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10912 (Src0 == Src1 || Src0 == Src2)) 10913 break; 10914 10915 MVT VT = Src0.getValueType().getSimpleVT(); 10916 const TargetRegisterClass *RC = 10917 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10918 10919 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10920 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10921 10922 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10923 UndefReg, Src0, SDValue()); 10924 10925 // src0 must be the same register as src1 or src2, even if the value is 10926 // undefined, so make sure we don't violate this constraint. 10927 if (Src0.isMachineOpcode() && 10928 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10929 if (Src1.isMachineOpcode() && 10930 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10931 Src0 = Src1; 10932 else if (Src2.isMachineOpcode() && 10933 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10934 Src0 = Src2; 10935 else { 10936 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10937 Src0 = UndefReg; 10938 Src1 = UndefReg; 10939 } 10940 } else 10941 break; 10942 10943 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10944 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10945 Ops.push_back(Node->getOperand(I)); 10946 10947 Ops.push_back(ImpDef.getValue(1)); 10948 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10949 } 10950 default: 10951 break; 10952 } 10953 10954 return Node; 10955 } 10956 10957 /// Assign the register class depending on the number of 10958 /// bits set in the writemask 10959 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10960 SDNode *Node) const { 10961 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10962 10963 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10964 10965 if (TII->isVOP3(MI.getOpcode())) { 10966 // Make sure constant bus requirements are respected. 10967 TII->legalizeOperandsVOP3(MRI, MI); 10968 10969 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10970 // This saves a chain-copy of registers and better ballance register 10971 // use between vgpr and agpr as agpr tuples tend to be big. 10972 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10973 unsigned Opc = MI.getOpcode(); 10974 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10975 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10976 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10977 if (I == -1) 10978 break; 10979 MachineOperand &Op = MI.getOperand(I); 10980 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10981 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10982 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 10983 continue; 10984 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10985 if (!Src || !Src->isCopy() || 10986 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10987 continue; 10988 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10989 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10990 // All uses of agpr64 and agpr32 can also accept vgpr except for 10991 // v_accvgpr_read, but we do not produce agpr reads during selection, 10992 // so no use checks are needed. 10993 MRI.setRegClass(Op.getReg(), NewRC); 10994 } 10995 } 10996 10997 return; 10998 } 10999 11000 // Replace unused atomics with the no return version. 11001 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11002 if (NoRetAtomicOp != -1) { 11003 if (!Node->hasAnyUseOfValue(0)) { 11004 MI.setDesc(TII->get(NoRetAtomicOp)); 11005 MI.RemoveOperand(0); 11006 return; 11007 } 11008 11009 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11010 // instruction, because the return type of these instructions is a vec2 of 11011 // the memory type, so it can be tied to the input operand. 11012 // This means these instructions always have a use, so we need to add a 11013 // special case to check if the atomic has only one extract_subreg use, 11014 // which itself has no uses. 11015 if ((Node->hasNUsesOfValue(1, 0) && 11016 Node->use_begin()->isMachineOpcode() && 11017 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11018 !Node->use_begin()->hasAnyUseOfValue(0))) { 11019 Register Def = MI.getOperand(0).getReg(); 11020 11021 // Change this into a noret atomic. 11022 MI.setDesc(TII->get(NoRetAtomicOp)); 11023 MI.RemoveOperand(0); 11024 11025 // If we only remove the def operand from the atomic instruction, the 11026 // extract_subreg will be left with a use of a vreg without a def. 11027 // So we need to insert an implicit_def to avoid machine verifier 11028 // errors. 11029 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11030 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11031 } 11032 return; 11033 } 11034 } 11035 11036 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11037 uint64_t Val) { 11038 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11039 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11040 } 11041 11042 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11043 const SDLoc &DL, 11044 SDValue Ptr) const { 11045 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11046 11047 // Build the half of the subregister with the constants before building the 11048 // full 128-bit register. If we are building multiple resource descriptors, 11049 // this will allow CSEing of the 2-component register. 11050 const SDValue Ops0[] = { 11051 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11052 buildSMovImm32(DAG, DL, 0), 11053 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11054 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11055 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11056 }; 11057 11058 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11059 MVT::v2i32, Ops0), 0); 11060 11061 // Combine the constants and the pointer. 11062 const SDValue Ops1[] = { 11063 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11064 Ptr, 11065 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11066 SubRegHi, 11067 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11068 }; 11069 11070 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11071 } 11072 11073 /// Return a resource descriptor with the 'Add TID' bit enabled 11074 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11075 /// of the resource descriptor) to create an offset, which is added to 11076 /// the resource pointer. 11077 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11078 SDValue Ptr, uint32_t RsrcDword1, 11079 uint64_t RsrcDword2And3) const { 11080 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11081 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11082 if (RsrcDword1) { 11083 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11084 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11085 0); 11086 } 11087 11088 SDValue DataLo = buildSMovImm32(DAG, DL, 11089 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11090 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11091 11092 const SDValue Ops[] = { 11093 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11094 PtrLo, 11095 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11096 PtrHi, 11097 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11098 DataLo, 11099 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11100 DataHi, 11101 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11102 }; 11103 11104 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11105 } 11106 11107 //===----------------------------------------------------------------------===// 11108 // SI Inline Assembly Support 11109 //===----------------------------------------------------------------------===// 11110 11111 std::pair<unsigned, const TargetRegisterClass *> 11112 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11113 StringRef Constraint, 11114 MVT VT) const { 11115 const TargetRegisterClass *RC = nullptr; 11116 if (Constraint.size() == 1) { 11117 const unsigned BitWidth = VT.getSizeInBits(); 11118 switch (Constraint[0]) { 11119 default: 11120 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11121 case 's': 11122 case 'r': 11123 switch (BitWidth) { 11124 case 16: 11125 RC = &AMDGPU::SReg_32RegClass; 11126 break; 11127 case 64: 11128 RC = &AMDGPU::SGPR_64RegClass; 11129 break; 11130 default: 11131 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11132 if (!RC) 11133 return std::make_pair(0U, nullptr); 11134 break; 11135 } 11136 break; 11137 case 'v': 11138 switch (BitWidth) { 11139 case 16: 11140 RC = &AMDGPU::VGPR_32RegClass; 11141 break; 11142 default: 11143 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 11144 if (!RC) 11145 return std::make_pair(0U, nullptr); 11146 break; 11147 } 11148 break; 11149 case 'a': 11150 if (!Subtarget->hasMAIInsts()) 11151 break; 11152 switch (BitWidth) { 11153 case 16: 11154 RC = &AMDGPU::AGPR_32RegClass; 11155 break; 11156 default: 11157 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 11158 if (!RC) 11159 return std::make_pair(0U, nullptr); 11160 break; 11161 } 11162 break; 11163 } 11164 // We actually support i128, i16 and f16 as inline parameters 11165 // even if they are not reported as legal 11166 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11167 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11168 return std::make_pair(0U, RC); 11169 } 11170 11171 if (Constraint.size() > 1) { 11172 if (Constraint[1] == 'v') { 11173 RC = &AMDGPU::VGPR_32RegClass; 11174 } else if (Constraint[1] == 's') { 11175 RC = &AMDGPU::SGPR_32RegClass; 11176 } else if (Constraint[1] == 'a') { 11177 RC = &AMDGPU::AGPR_32RegClass; 11178 } 11179 11180 if (RC) { 11181 uint32_t Idx; 11182 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11183 if (!Failed && Idx < RC->getNumRegs()) 11184 return std::make_pair(RC->getRegister(Idx), RC); 11185 } 11186 } 11187 11188 // FIXME: Returns VS_32 for physical SGPR constraints 11189 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11190 } 11191 11192 static bool isImmConstraint(StringRef Constraint) { 11193 if (Constraint.size() == 1) { 11194 switch (Constraint[0]) { 11195 default: break; 11196 case 'I': 11197 case 'J': 11198 case 'A': 11199 case 'B': 11200 case 'C': 11201 return true; 11202 } 11203 } else if (Constraint == "DA" || 11204 Constraint == "DB") { 11205 return true; 11206 } 11207 return false; 11208 } 11209 11210 SITargetLowering::ConstraintType 11211 SITargetLowering::getConstraintType(StringRef Constraint) const { 11212 if (Constraint.size() == 1) { 11213 switch (Constraint[0]) { 11214 default: break; 11215 case 's': 11216 case 'v': 11217 case 'a': 11218 return C_RegisterClass; 11219 } 11220 } 11221 if (isImmConstraint(Constraint)) { 11222 return C_Other; 11223 } 11224 return TargetLowering::getConstraintType(Constraint); 11225 } 11226 11227 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11228 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11229 Val = Val & maskTrailingOnes<uint64_t>(Size); 11230 } 11231 return Val; 11232 } 11233 11234 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11235 std::string &Constraint, 11236 std::vector<SDValue> &Ops, 11237 SelectionDAG &DAG) const { 11238 if (isImmConstraint(Constraint)) { 11239 uint64_t Val; 11240 if (getAsmOperandConstVal(Op, Val) && 11241 checkAsmConstraintVal(Op, Constraint, Val)) { 11242 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11243 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11244 } 11245 } else { 11246 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11247 } 11248 } 11249 11250 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11251 unsigned Size = Op.getScalarValueSizeInBits(); 11252 if (Size > 64) 11253 return false; 11254 11255 if (Size == 16 && !Subtarget->has16BitInsts()) 11256 return false; 11257 11258 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11259 Val = C->getSExtValue(); 11260 return true; 11261 } 11262 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11263 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11264 return true; 11265 } 11266 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11267 if (Size != 16 || Op.getNumOperands() != 2) 11268 return false; 11269 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11270 return false; 11271 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11272 Val = C->getSExtValue(); 11273 return true; 11274 } 11275 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11276 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11277 return true; 11278 } 11279 } 11280 11281 return false; 11282 } 11283 11284 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11285 const std::string &Constraint, 11286 uint64_t Val) const { 11287 if (Constraint.size() == 1) { 11288 switch (Constraint[0]) { 11289 case 'I': 11290 return AMDGPU::isInlinableIntLiteral(Val); 11291 case 'J': 11292 return isInt<16>(Val); 11293 case 'A': 11294 return checkAsmConstraintValA(Op, Val); 11295 case 'B': 11296 return isInt<32>(Val); 11297 case 'C': 11298 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11299 AMDGPU::isInlinableIntLiteral(Val); 11300 default: 11301 break; 11302 } 11303 } else if (Constraint.size() == 2) { 11304 if (Constraint == "DA") { 11305 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11306 int64_t LoBits = static_cast<int32_t>(Val); 11307 return checkAsmConstraintValA(Op, HiBits, 32) && 11308 checkAsmConstraintValA(Op, LoBits, 32); 11309 } 11310 if (Constraint == "DB") { 11311 return true; 11312 } 11313 } 11314 llvm_unreachable("Invalid asm constraint"); 11315 } 11316 11317 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11318 uint64_t Val, 11319 unsigned MaxSize) const { 11320 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11321 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11322 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11323 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11324 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11325 return true; 11326 } 11327 return false; 11328 } 11329 11330 // Figure out which registers should be reserved for stack access. Only after 11331 // the function is legalized do we know all of the non-spill stack objects or if 11332 // calls are present. 11333 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11334 MachineRegisterInfo &MRI = MF.getRegInfo(); 11335 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11336 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11337 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11338 11339 if (Info->isEntryFunction()) { 11340 // Callable functions have fixed registers used for stack access. 11341 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11342 } 11343 11344 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11345 Info->getStackPtrOffsetReg())); 11346 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11347 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11348 11349 // We need to worry about replacing the default register with itself in case 11350 // of MIR testcases missing the MFI. 11351 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11352 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11353 11354 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11355 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11356 11357 Info->limitOccupancy(MF); 11358 11359 if (ST.isWave32() && !MF.empty()) { 11360 // Add VCC_HI def because many instructions marked as imp-use VCC where 11361 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 11362 // having a use of undef. 11363 11364 const SIInstrInfo *TII = ST.getInstrInfo(); 11365 DebugLoc DL; 11366 11367 MachineBasicBlock &MBB = MF.front(); 11368 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 11369 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 11370 11371 for (auto &MBB : MF) { 11372 for (auto &MI : MBB) { 11373 TII->fixImplicitOperands(MI); 11374 } 11375 } 11376 } 11377 11378 TargetLoweringBase::finalizeLowering(MF); 11379 11380 // Allocate a VGPR for future SGPR Spill if 11381 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11382 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11383 if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill && 11384 !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects()) 11385 Info->reserveVGPRforSGPRSpills(MF); 11386 } 11387 11388 void SITargetLowering::computeKnownBitsForFrameIndex( 11389 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11390 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11391 11392 // Set the high bits to zero based on the maximum allowed scratch size per 11393 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11394 // calculation won't overflow, so assume the sign bit is never set. 11395 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11396 } 11397 11398 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11399 KnownBits &Known, unsigned Dim) { 11400 unsigned MaxValue = 11401 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11402 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11403 } 11404 11405 void SITargetLowering::computeKnownBitsForTargetInstr( 11406 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11407 const MachineRegisterInfo &MRI, unsigned Depth) const { 11408 const MachineInstr *MI = MRI.getVRegDef(R); 11409 switch (MI->getOpcode()) { 11410 case AMDGPU::G_INTRINSIC: { 11411 switch (MI->getIntrinsicID()) 11412 case Intrinsic::amdgcn_workitem_id_x: 11413 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11414 break; 11415 case Intrinsic::amdgcn_workitem_id_y: 11416 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11417 break; 11418 case Intrinsic::amdgcn_workitem_id_z: 11419 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11420 break; 11421 case Intrinsic::amdgcn_mbcnt_lo: 11422 case Intrinsic::amdgcn_mbcnt_hi: { 11423 // These return at most the wavefront size - 1. 11424 unsigned Size = MRI.getType(R).getSizeInBits(); 11425 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11426 break; 11427 } 11428 default: 11429 break; 11430 } 11431 } 11432 } 11433 11434 Align SITargetLowering::computeKnownAlignForTargetInstr( 11435 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11436 unsigned Depth) const { 11437 const MachineInstr *MI = MRI.getVRegDef(R); 11438 switch (MI->getOpcode()) { 11439 case AMDGPU::G_INTRINSIC: 11440 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11441 // FIXME: Can this move to generic code? What about the case where the call 11442 // site specifies a lower alignment? 11443 Intrinsic::ID IID = MI->getIntrinsicID(); 11444 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11445 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11446 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11447 return *RetAlign; 11448 return Align(1); 11449 } 11450 default: 11451 return Align(1); 11452 } 11453 } 11454 11455 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11456 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11457 const Align CacheLineAlign = Align(64); 11458 11459 // Pre-GFX10 target did not benefit from loop alignment 11460 if (!ML || DisableLoopAlignment || 11461 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11462 getSubtarget()->hasInstFwdPrefetchBug()) 11463 return PrefAlign; 11464 11465 // On GFX10 I$ is 4 x 64 bytes cache lines. 11466 // By default prefetcher keeps one cache line behind and reads two ahead. 11467 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11468 // behind and one ahead. 11469 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11470 // If loop fits 64 bytes it always spans no more than two cache lines and 11471 // does not need an alignment. 11472 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11473 // Else if loop is less or equal 192 bytes we need two lines behind. 11474 11475 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11476 const MachineBasicBlock *Header = ML->getHeader(); 11477 if (Header->getAlignment() != PrefAlign) 11478 return Header->getAlignment(); // Already processed. 11479 11480 unsigned LoopSize = 0; 11481 for (const MachineBasicBlock *MBB : ML->blocks()) { 11482 // If inner loop block is aligned assume in average half of the alignment 11483 // size to be added as nops. 11484 if (MBB != Header) 11485 LoopSize += MBB->getAlignment().value() / 2; 11486 11487 for (const MachineInstr &MI : *MBB) { 11488 LoopSize += TII->getInstSizeInBytes(MI); 11489 if (LoopSize > 192) 11490 return PrefAlign; 11491 } 11492 } 11493 11494 if (LoopSize <= 64) 11495 return PrefAlign; 11496 11497 if (LoopSize <= 128) 11498 return CacheLineAlign; 11499 11500 // If any of parent loops is surrounded by prefetch instructions do not 11501 // insert new for inner loop, which would reset parent's settings. 11502 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11503 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11504 auto I = Exit->getFirstNonDebugInstr(); 11505 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11506 return CacheLineAlign; 11507 } 11508 } 11509 11510 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11511 MachineBasicBlock *Exit = ML->getExitBlock(); 11512 11513 if (Pre && Exit) { 11514 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11515 TII->get(AMDGPU::S_INST_PREFETCH)) 11516 .addImm(1); // prefetch 2 lines behind PC 11517 11518 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11519 TII->get(AMDGPU::S_INST_PREFETCH)) 11520 .addImm(2); // prefetch 1 line behind PC 11521 } 11522 11523 return CacheLineAlign; 11524 } 11525 11526 LLVM_ATTRIBUTE_UNUSED 11527 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11528 assert(N->getOpcode() == ISD::CopyFromReg); 11529 do { 11530 // Follow the chain until we find an INLINEASM node. 11531 N = N->getOperand(0).getNode(); 11532 if (N->getOpcode() == ISD::INLINEASM || 11533 N->getOpcode() == ISD::INLINEASM_BR) 11534 return true; 11535 } while (N->getOpcode() == ISD::CopyFromReg); 11536 return false; 11537 } 11538 11539 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 11540 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 11541 { 11542 switch (N->getOpcode()) { 11543 case ISD::CopyFromReg: 11544 { 11545 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11546 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11547 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11548 Register Reg = R->getReg(); 11549 11550 // FIXME: Why does this need to consider isLiveIn? 11551 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11552 return !TRI->isSGPRReg(MRI, Reg); 11553 11554 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11555 return KDA->isDivergent(V); 11556 11557 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11558 return !TRI->isSGPRReg(MRI, Reg); 11559 } 11560 break; 11561 case ISD::LOAD: { 11562 const LoadSDNode *L = cast<LoadSDNode>(N); 11563 unsigned AS = L->getAddressSpace(); 11564 // A flat load may access private memory. 11565 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11566 } break; 11567 case ISD::CALLSEQ_END: 11568 return true; 11569 break; 11570 case ISD::INTRINSIC_WO_CHAIN: 11571 { 11572 11573 } 11574 return AMDGPU::isIntrinsicSourceOfDivergence( 11575 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11576 case ISD::INTRINSIC_W_CHAIN: 11577 return AMDGPU::isIntrinsicSourceOfDivergence( 11578 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11579 } 11580 return false; 11581 } 11582 11583 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11584 EVT VT) const { 11585 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11586 case MVT::f32: 11587 return hasFP32Denormals(DAG.getMachineFunction()); 11588 case MVT::f64: 11589 case MVT::f16: 11590 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11591 default: 11592 return false; 11593 } 11594 } 11595 11596 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11597 const SelectionDAG &DAG, 11598 bool SNaN, 11599 unsigned Depth) const { 11600 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11601 const MachineFunction &MF = DAG.getMachineFunction(); 11602 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11603 11604 if (Info->getMode().DX10Clamp) 11605 return true; // Clamped to 0. 11606 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11607 } 11608 11609 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11610 SNaN, Depth); 11611 } 11612 11613 TargetLowering::AtomicExpansionKind 11614 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11615 switch (RMW->getOperation()) { 11616 case AtomicRMWInst::FAdd: { 11617 Type *Ty = RMW->getType(); 11618 11619 // We don't have a way to support 16-bit atomics now, so just leave them 11620 // as-is. 11621 if (Ty->isHalfTy()) 11622 return AtomicExpansionKind::None; 11623 11624 if (!Ty->isFloatTy()) 11625 return AtomicExpansionKind::CmpXChg; 11626 11627 // TODO: Do have these for flat. Older targets also had them for buffers. 11628 unsigned AS = RMW->getPointerAddressSpace(); 11629 11630 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11631 return RMW->use_empty() ? AtomicExpansionKind::None : 11632 AtomicExpansionKind::CmpXChg; 11633 } 11634 11635 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11636 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11637 } 11638 default: 11639 break; 11640 } 11641 11642 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11643 } 11644 11645 const TargetRegisterClass * 11646 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11647 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11648 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11649 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11650 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11651 : &AMDGPU::SReg_32RegClass; 11652 if (!TRI->isSGPRClass(RC) && !isDivergent) 11653 return TRI->getEquivalentSGPRClass(RC); 11654 else if (TRI->isSGPRClass(RC) && isDivergent) 11655 return TRI->getEquivalentVGPRClass(RC); 11656 11657 return RC; 11658 } 11659 11660 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11661 // uniform values (as produced by the mask results of control flow intrinsics) 11662 // used outside of divergent blocks. The phi users need to also be treated as 11663 // always uniform. 11664 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11665 unsigned WaveSize) { 11666 // FIXME: We asssume we never cast the mask results of a control flow 11667 // intrinsic. 11668 // Early exit if the type won't be consistent as a compile time hack. 11669 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11670 if (!IT || IT->getBitWidth() != WaveSize) 11671 return false; 11672 11673 if (!isa<Instruction>(V)) 11674 return false; 11675 if (!Visited.insert(V).second) 11676 return false; 11677 bool Result = false; 11678 for (auto U : V->users()) { 11679 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11680 if (V == U->getOperand(1)) { 11681 switch (Intrinsic->getIntrinsicID()) { 11682 default: 11683 Result = false; 11684 break; 11685 case Intrinsic::amdgcn_if_break: 11686 case Intrinsic::amdgcn_if: 11687 case Intrinsic::amdgcn_else: 11688 Result = true; 11689 break; 11690 } 11691 } 11692 if (V == U->getOperand(0)) { 11693 switch (Intrinsic->getIntrinsicID()) { 11694 default: 11695 Result = false; 11696 break; 11697 case Intrinsic::amdgcn_end_cf: 11698 case Intrinsic::amdgcn_loop: 11699 Result = true; 11700 break; 11701 } 11702 } 11703 } else { 11704 Result = hasCFUser(U, Visited, WaveSize); 11705 } 11706 if (Result) 11707 break; 11708 } 11709 return Result; 11710 } 11711 11712 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11713 const Value *V) const { 11714 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11715 if (CI->isInlineAsm()) { 11716 // FIXME: This cannot give a correct answer. This should only trigger in 11717 // the case where inline asm returns mixed SGPR and VGPR results, used 11718 // outside the defining block. We don't have a specific result to 11719 // consider, so this assumes if any value is SGPR, the overall register 11720 // also needs to be SGPR. 11721 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11722 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11723 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11724 for (auto &TC : TargetConstraints) { 11725 if (TC.Type == InlineAsm::isOutput) { 11726 ComputeConstraintToUse(TC, SDValue()); 11727 unsigned AssignedReg; 11728 const TargetRegisterClass *RC; 11729 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11730 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11731 if (RC) { 11732 MachineRegisterInfo &MRI = MF.getRegInfo(); 11733 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11734 return true; 11735 else if (SIRI->isSGPRClass(RC)) 11736 return true; 11737 } 11738 } 11739 } 11740 } 11741 } 11742 SmallPtrSet<const Value *, 16> Visited; 11743 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11744 } 11745 11746 std::pair<int, MVT> 11747 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 11748 Type *Ty) const { 11749 auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 11750 auto Size = DL.getTypeSizeInBits(Ty); 11751 // Maximum load or store can handle 8 dwords for scalar and 4 for 11752 // vector ALU. Let's assume anything above 8 dwords is expensive 11753 // even if legal. 11754 if (Size <= 256) 11755 return Cost; 11756 11757 Cost.first = (Size + 255) / 256; 11758 return Cost; 11759 } 11760