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 #if defined(_MSC_VER) || defined(__MINGW32__) 15 // Provide M_PI. 16 #define _USE_MATH_DEFINES 17 #endif 18 19 #include "SIISelLowering.h" 20 #include "AMDGPU.h" 21 #include "AMDGPUSubtarget.h" 22 #include "AMDGPUTargetMachine.h" 23 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 24 #include "SIDefines.h" 25 #include "SIInstrInfo.h" 26 #include "SIMachineFunctionInfo.h" 27 #include "SIRegisterInfo.h" 28 #include "Utils/AMDGPUBaseInfo.h" 29 #include "llvm/ADT/APFloat.h" 30 #include "llvm/ADT/APInt.h" 31 #include "llvm/ADT/ArrayRef.h" 32 #include "llvm/ADT/BitVector.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/ADT/Twine.h" 38 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 39 #include "llvm/CodeGen/Analysis.h" 40 #include "llvm/CodeGen/CallingConvLower.h" 41 #include "llvm/CodeGen/DAGCombine.h" 42 #include "llvm/CodeGen/ISDOpcodes.h" 43 #include "llvm/CodeGen/MachineBasicBlock.h" 44 #include "llvm/CodeGen/MachineFrameInfo.h" 45 #include "llvm/CodeGen/MachineFunction.h" 46 #include "llvm/CodeGen/MachineInstr.h" 47 #include "llvm/CodeGen/MachineInstrBuilder.h" 48 #include "llvm/CodeGen/MachineLoopInfo.h" 49 #include "llvm/CodeGen/MachineMemOperand.h" 50 #include "llvm/CodeGen/MachineModuleInfo.h" 51 #include "llvm/CodeGen/MachineOperand.h" 52 #include "llvm/CodeGen/MachineRegisterInfo.h" 53 #include "llvm/CodeGen/SelectionDAG.h" 54 #include "llvm/CodeGen/SelectionDAGNodes.h" 55 #include "llvm/CodeGen/TargetCallingConv.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/Constants.h" 59 #include "llvm/IR/DataLayout.h" 60 #include "llvm/IR/DebugLoc.h" 61 #include "llvm/IR/DerivedTypes.h" 62 #include "llvm/IR/DiagnosticInfo.h" 63 #include "llvm/IR/Function.h" 64 #include "llvm/IR/GlobalValue.h" 65 #include "llvm/IR/InstrTypes.h" 66 #include "llvm/IR/Instruction.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/IntrinsicInst.h" 69 #include "llvm/IR/Type.h" 70 #include "llvm/Support/Casting.h" 71 #include "llvm/Support/CodeGen.h" 72 #include "llvm/Support/CommandLine.h" 73 #include "llvm/Support/Compiler.h" 74 #include "llvm/Support/ErrorHandling.h" 75 #include "llvm/Support/KnownBits.h" 76 #include "llvm/Support/MachineValueType.h" 77 #include "llvm/Support/MathExtras.h" 78 #include "llvm/Target/TargetOptions.h" 79 #include <cassert> 80 #include <cmath> 81 #include <cstdint> 82 #include <iterator> 83 #include <tuple> 84 #include <utility> 85 #include <vector> 86 87 using namespace llvm; 88 89 #define DEBUG_TYPE "si-lower" 90 91 STATISTIC(NumTailCalls, "Number of tail calls"); 92 93 static cl::opt<bool> DisableLoopAlignment( 94 "amdgpu-disable-loop-alignment", 95 cl::desc("Do not align and prefetch loops"), 96 cl::init(false)); 97 98 static cl::opt<bool> VGPRReserveforSGPRSpill( 99 "amdgpu-reserve-vgpr-for-sgpr-spill", 100 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 101 102 static cl::opt<bool> UseDivergentRegisterIndexing( 103 "amdgpu-use-divergent-register-indexing", 104 cl::Hidden, 105 cl::desc("Use indirect register addressing for divergent indexes"), 106 cl::init(false)); 107 108 static bool hasFP32Denormals(const MachineFunction &MF) { 109 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 110 return Info->getMode().allFP32Denormals(); 111 } 112 113 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 114 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 115 return Info->getMode().allFP64FP16Denormals(); 116 } 117 118 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 119 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 120 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 121 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 122 return AMDGPU::SGPR0 + Reg; 123 } 124 } 125 llvm_unreachable("Cannot allocate sgpr"); 126 } 127 128 SITargetLowering::SITargetLowering(const TargetMachine &TM, 129 const GCNSubtarget &STI) 130 : AMDGPUTargetLowering(TM, STI), 131 Subtarget(&STI) { 132 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 133 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 134 135 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 136 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 137 138 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 139 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 140 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 141 142 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 143 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 144 145 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 146 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 147 148 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 149 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 150 151 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 152 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 153 154 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 155 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 156 157 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 158 addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass); 159 160 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 161 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 162 163 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 164 addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass); 165 166 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 167 addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass); 168 169 if (Subtarget->has16BitInsts()) { 170 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 171 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 172 173 // Unless there are also VOP3P operations, not operations are really legal. 174 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 175 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 176 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 177 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 178 } 179 180 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 181 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 182 183 computeRegisterProperties(Subtarget->getRegisterInfo()); 184 185 // The boolean content concept here is too inflexible. Compares only ever 186 // really produce a 1-bit result. Any copy/extend from these will turn into a 187 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 188 // it's what most targets use. 189 setBooleanContents(ZeroOrOneBooleanContent); 190 setBooleanVectorContents(ZeroOrOneBooleanContent); 191 192 // We need to custom lower vector stores from local memory 193 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 194 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 195 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 196 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 197 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 198 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 199 setOperationAction(ISD::LOAD, MVT::i1, Custom); 200 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 201 202 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 203 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 204 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 205 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 206 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 207 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 208 setOperationAction(ISD::STORE, MVT::i1, Custom); 209 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 210 211 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 212 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 213 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 214 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 215 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 216 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 217 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 218 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 219 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 220 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 221 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 222 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 223 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 224 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 225 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 226 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 227 228 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 229 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 230 231 setOperationAction(ISD::SELECT, MVT::i1, Promote); 232 setOperationAction(ISD::SELECT, MVT::i64, Custom); 233 setOperationAction(ISD::SELECT, MVT::f64, Promote); 234 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 235 236 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 237 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 238 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 239 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 240 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 241 242 setOperationAction(ISD::SETCC, MVT::i1, Promote); 243 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 244 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 245 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 246 247 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 248 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 249 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 250 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 251 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 252 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 253 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 254 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 255 256 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 257 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 258 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 259 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 260 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 261 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 262 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 263 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 264 265 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 266 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 267 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 268 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 269 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 270 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 271 272 setOperationAction(ISD::UADDO, MVT::i32, Legal); 273 setOperationAction(ISD::USUBO, MVT::i32, Legal); 274 275 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 276 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 277 278 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 279 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 280 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 281 282 #if 0 283 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 284 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 285 #endif 286 287 // We only support LOAD/STORE and vector manipulation ops for vectors 288 // with > 4 elements. 289 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 290 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 291 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 292 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 293 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 294 switch (Op) { 295 case ISD::LOAD: 296 case ISD::STORE: 297 case ISD::BUILD_VECTOR: 298 case ISD::BITCAST: 299 case ISD::EXTRACT_VECTOR_ELT: 300 case ISD::INSERT_VECTOR_ELT: 301 case ISD::INSERT_SUBVECTOR: 302 case ISD::EXTRACT_SUBVECTOR: 303 case ISD::SCALAR_TO_VECTOR: 304 break; 305 case ISD::CONCAT_VECTORS: 306 setOperationAction(Op, VT, Custom); 307 break; 308 default: 309 setOperationAction(Op, VT, Expand); 310 break; 311 } 312 } 313 } 314 315 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 316 317 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 318 // is expanded to avoid having two separate loops in case the index is a VGPR. 319 320 // Most operations are naturally 32-bit vector operations. We only support 321 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 322 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 323 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 324 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 325 326 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 327 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 328 329 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 330 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 331 332 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 333 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 334 } 335 336 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 337 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 338 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 339 340 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 341 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 342 343 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 344 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 345 346 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 347 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 348 } 349 350 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 351 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 352 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 353 354 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 355 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 356 357 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 358 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 359 360 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 361 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 362 } 363 364 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 365 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 366 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 367 368 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 369 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 370 371 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 372 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 373 374 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 375 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 376 } 377 378 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 379 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 380 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 381 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 382 383 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 384 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 385 386 // Avoid stack access for these. 387 // TODO: Generalize to more vector types. 388 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 389 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 390 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 391 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 392 393 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 394 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 395 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 396 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 398 399 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 400 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 401 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 402 403 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 404 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 405 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 406 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 407 408 // Deal with vec3 vector operations when widened to vec4. 409 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 410 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 411 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 413 414 // Deal with vec5 vector operations when widened to vec8. 415 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 416 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 417 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 418 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 419 420 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 421 // and output demarshalling 422 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 423 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 424 425 // We can't return success/failure, only the old value, 426 // let LLVM add the comparison 427 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 428 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 429 430 if (Subtarget->hasFlatAddressSpace()) { 431 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 432 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 433 } 434 435 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 436 437 // FIXME: This should be narrowed to i32, but that only happens if i64 is 438 // illegal. 439 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 440 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 441 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 442 443 // On SI this is s_memtime and s_memrealtime on VI. 444 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 445 setOperationAction(ISD::TRAP, MVT::Other, Custom); 446 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 447 448 if (Subtarget->has16BitInsts()) { 449 setOperationAction(ISD::FPOW, MVT::f16, Promote); 450 setOperationAction(ISD::FLOG, MVT::f16, Custom); 451 setOperationAction(ISD::FEXP, MVT::f16, Custom); 452 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 453 } 454 455 // v_mad_f32 does not support denormals. We report it as unconditionally 456 // legal, and the context where it is formed will disallow it when fp32 457 // denormals are enabled. 458 setOperationAction(ISD::FMAD, MVT::f32, Legal); 459 460 if (!Subtarget->hasBFI()) { 461 // fcopysign can be done in a single instruction with BFI. 462 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 463 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 464 } 465 466 if (!Subtarget->hasBCNT(32)) 467 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 468 469 if (!Subtarget->hasBCNT(64)) 470 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 471 472 if (Subtarget->hasFFBH()) 473 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 474 475 if (Subtarget->hasFFBL()) 476 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 477 478 // We only really have 32-bit BFE instructions (and 16-bit on VI). 479 // 480 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 481 // effort to match them now. We want this to be false for i64 cases when the 482 // extraction isn't restricted to the upper or lower half. Ideally we would 483 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 484 // span the midpoint are probably relatively rare, so don't worry about them 485 // for now. 486 if (Subtarget->hasBFE()) 487 setHasExtractBitsInsn(true); 488 489 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 490 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 491 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 492 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 493 494 495 // These are really only legal for ieee_mode functions. We should be avoiding 496 // them for functions that don't have ieee_mode enabled, so just say they are 497 // legal. 498 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 499 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 500 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 501 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 502 503 504 if (Subtarget->haveRoundOpsF64()) { 505 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 506 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 507 setOperationAction(ISD::FRINT, MVT::f64, Legal); 508 } else { 509 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 510 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 511 setOperationAction(ISD::FRINT, MVT::f64, Custom); 512 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 513 } 514 515 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 516 517 setOperationAction(ISD::FSIN, MVT::f32, Custom); 518 setOperationAction(ISD::FCOS, MVT::f32, Custom); 519 setOperationAction(ISD::FDIV, MVT::f32, Custom); 520 setOperationAction(ISD::FDIV, MVT::f64, Custom); 521 522 if (Subtarget->has16BitInsts()) { 523 setOperationAction(ISD::Constant, MVT::i16, Legal); 524 525 setOperationAction(ISD::SMIN, MVT::i16, Legal); 526 setOperationAction(ISD::SMAX, MVT::i16, Legal); 527 528 setOperationAction(ISD::UMIN, MVT::i16, Legal); 529 setOperationAction(ISD::UMAX, MVT::i16, Legal); 530 531 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 532 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 533 534 setOperationAction(ISD::ROTR, MVT::i16, Promote); 535 setOperationAction(ISD::ROTL, MVT::i16, Promote); 536 537 setOperationAction(ISD::SDIV, MVT::i16, Promote); 538 setOperationAction(ISD::UDIV, MVT::i16, Promote); 539 setOperationAction(ISD::SREM, MVT::i16, Promote); 540 setOperationAction(ISD::UREM, MVT::i16, Promote); 541 542 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 543 544 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 545 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 546 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 547 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 548 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 549 550 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 551 552 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 553 554 setOperationAction(ISD::LOAD, MVT::i16, Custom); 555 556 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 557 558 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 559 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 560 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 561 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 562 563 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 564 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 565 566 // F16 - Constant Actions. 567 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 568 569 // F16 - Load/Store Actions. 570 setOperationAction(ISD::LOAD, MVT::f16, Promote); 571 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 572 setOperationAction(ISD::STORE, MVT::f16, Promote); 573 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 574 575 // F16 - VOP1 Actions. 576 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 577 setOperationAction(ISD::FCOS, MVT::f16, Custom); 578 setOperationAction(ISD::FSIN, MVT::f16, Custom); 579 580 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 581 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 582 583 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 584 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 585 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 586 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 587 setOperationAction(ISD::FROUND, MVT::f16, Custom); 588 589 // F16 - VOP2 Actions. 590 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 591 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 592 593 setOperationAction(ISD::FDIV, MVT::f16, Custom); 594 595 // F16 - VOP3 Actions. 596 setOperationAction(ISD::FMA, MVT::f16, Legal); 597 if (STI.hasMadF16()) 598 setOperationAction(ISD::FMAD, MVT::f16, Legal); 599 600 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 601 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 602 switch (Op) { 603 case ISD::LOAD: 604 case ISD::STORE: 605 case ISD::BUILD_VECTOR: 606 case ISD::BITCAST: 607 case ISD::EXTRACT_VECTOR_ELT: 608 case ISD::INSERT_VECTOR_ELT: 609 case ISD::INSERT_SUBVECTOR: 610 case ISD::EXTRACT_SUBVECTOR: 611 case ISD::SCALAR_TO_VECTOR: 612 break; 613 case ISD::CONCAT_VECTORS: 614 setOperationAction(Op, VT, Custom); 615 break; 616 default: 617 setOperationAction(Op, VT, Expand); 618 break; 619 } 620 } 621 } 622 623 // v_perm_b32 can handle either of these. 624 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 625 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 626 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 627 628 // XXX - Do these do anything? Vector constants turn into build_vector. 629 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 630 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 631 632 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 633 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 634 635 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 636 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 637 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 638 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 639 640 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 641 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 642 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 643 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 644 645 setOperationAction(ISD::AND, MVT::v2i16, Promote); 646 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 647 setOperationAction(ISD::OR, MVT::v2i16, Promote); 648 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 649 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 650 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 651 652 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 653 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 654 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 655 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 656 657 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 658 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 659 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 660 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 661 662 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 663 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 664 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 665 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 666 667 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 668 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 669 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 670 671 if (!Subtarget->hasVOP3PInsts()) { 672 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 673 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 674 } 675 676 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 677 // This isn't really legal, but this avoids the legalizer unrolling it (and 678 // allows matching fneg (fabs x) patterns) 679 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 680 681 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 682 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 683 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 684 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 685 686 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 687 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 688 689 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 690 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 691 } 692 693 if (Subtarget->hasVOP3PInsts()) { 694 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 695 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 696 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 697 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 698 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 699 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 700 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 701 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 702 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 703 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 704 705 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 706 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 707 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 708 709 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 710 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 711 712 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 713 714 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 715 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 716 717 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 718 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 719 720 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 721 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 722 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 723 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 724 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 725 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 726 727 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 728 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 729 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 730 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 731 732 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 733 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 734 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 735 736 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 737 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 738 739 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 740 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 741 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 742 743 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 744 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 745 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 746 } 747 748 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 749 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 750 751 if (Subtarget->has16BitInsts()) { 752 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 753 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 754 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 755 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 756 } else { 757 // Legalization hack. 758 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 759 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 760 761 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 762 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 763 } 764 765 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 766 setOperationAction(ISD::SELECT, VT, Custom); 767 } 768 769 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 770 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 771 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 772 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 773 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 774 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 775 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 776 777 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 778 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 779 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 780 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 781 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 782 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 783 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 784 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 785 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 786 787 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 788 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 789 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 790 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 791 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 792 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 793 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 794 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 795 796 setTargetDAGCombine(ISD::ADD); 797 setTargetDAGCombine(ISD::ADDCARRY); 798 setTargetDAGCombine(ISD::SUB); 799 setTargetDAGCombine(ISD::SUBCARRY); 800 setTargetDAGCombine(ISD::FADD); 801 setTargetDAGCombine(ISD::FSUB); 802 setTargetDAGCombine(ISD::FMINNUM); 803 setTargetDAGCombine(ISD::FMAXNUM); 804 setTargetDAGCombine(ISD::FMINNUM_IEEE); 805 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 806 setTargetDAGCombine(ISD::FMA); 807 setTargetDAGCombine(ISD::SMIN); 808 setTargetDAGCombine(ISD::SMAX); 809 setTargetDAGCombine(ISD::UMIN); 810 setTargetDAGCombine(ISD::UMAX); 811 setTargetDAGCombine(ISD::SETCC); 812 setTargetDAGCombine(ISD::AND); 813 setTargetDAGCombine(ISD::OR); 814 setTargetDAGCombine(ISD::XOR); 815 setTargetDAGCombine(ISD::SINT_TO_FP); 816 setTargetDAGCombine(ISD::UINT_TO_FP); 817 setTargetDAGCombine(ISD::FCANONICALIZE); 818 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 819 setTargetDAGCombine(ISD::ZERO_EXTEND); 820 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 821 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 822 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 823 824 // All memory operations. Some folding on the pointer operand is done to help 825 // matching the constant offsets in the addressing modes. 826 setTargetDAGCombine(ISD::LOAD); 827 setTargetDAGCombine(ISD::STORE); 828 setTargetDAGCombine(ISD::ATOMIC_LOAD); 829 setTargetDAGCombine(ISD::ATOMIC_STORE); 830 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 831 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 832 setTargetDAGCombine(ISD::ATOMIC_SWAP); 833 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 834 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 835 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 836 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 837 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 838 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 839 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 840 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 841 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 842 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 843 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 844 845 // FIXME: In other contexts we pretend this is a per-function property. 846 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 847 848 setSchedulingPreference(Sched::RegPressure); 849 } 850 851 const GCNSubtarget *SITargetLowering::getSubtarget() const { 852 return Subtarget; 853 } 854 855 //===----------------------------------------------------------------------===// 856 // TargetLowering queries 857 //===----------------------------------------------------------------------===// 858 859 // v_mad_mix* support a conversion from f16 to f32. 860 // 861 // There is only one special case when denormals are enabled we don't currently, 862 // where this is OK to use. 863 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 864 EVT DestVT, EVT SrcVT) const { 865 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 866 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 867 DestVT.getScalarType() == MVT::f32 && 868 SrcVT.getScalarType() == MVT::f16 && 869 // TODO: This probably only requires no input flushing? 870 !hasFP32Denormals(DAG.getMachineFunction()); 871 } 872 873 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 874 // SI has some legal vector types, but no legal vector operations. Say no 875 // shuffles are legal in order to prefer scalarizing some vector operations. 876 return false; 877 } 878 879 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 880 CallingConv::ID CC, 881 EVT VT) const { 882 if (CC == CallingConv::AMDGPU_KERNEL) 883 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 884 885 if (VT.isVector()) { 886 EVT ScalarVT = VT.getScalarType(); 887 unsigned Size = ScalarVT.getSizeInBits(); 888 if (Size == 32) 889 return ScalarVT.getSimpleVT(); 890 891 if (Size > 32) 892 return MVT::i32; 893 894 if (Size == 16 && Subtarget->has16BitInsts()) 895 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 896 } else if (VT.getSizeInBits() > 32) 897 return MVT::i32; 898 899 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 900 } 901 902 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 903 CallingConv::ID CC, 904 EVT VT) const { 905 if (CC == CallingConv::AMDGPU_KERNEL) 906 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 907 908 if (VT.isVector()) { 909 unsigned NumElts = VT.getVectorNumElements(); 910 EVT ScalarVT = VT.getScalarType(); 911 unsigned Size = ScalarVT.getSizeInBits(); 912 913 if (Size == 32) 914 return NumElts; 915 916 if (Size > 32) 917 return NumElts * ((Size + 31) / 32); 918 919 if (Size == 16 && Subtarget->has16BitInsts()) 920 return (NumElts + 1) / 2; 921 } else if (VT.getSizeInBits() > 32) 922 return (VT.getSizeInBits() + 31) / 32; 923 924 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 925 } 926 927 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 928 LLVMContext &Context, CallingConv::ID CC, 929 EVT VT, EVT &IntermediateVT, 930 unsigned &NumIntermediates, MVT &RegisterVT) const { 931 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 932 unsigned NumElts = VT.getVectorNumElements(); 933 EVT ScalarVT = VT.getScalarType(); 934 unsigned Size = ScalarVT.getSizeInBits(); 935 if (Size == 32) { 936 RegisterVT = ScalarVT.getSimpleVT(); 937 IntermediateVT = RegisterVT; 938 NumIntermediates = NumElts; 939 return NumIntermediates; 940 } 941 942 if (Size > 32) { 943 RegisterVT = MVT::i32; 944 IntermediateVT = RegisterVT; 945 NumIntermediates = NumElts * ((Size + 31) / 32); 946 return NumIntermediates; 947 } 948 949 // FIXME: We should fix the ABI to be the same on targets without 16-bit 950 // support, but unless we can properly handle 3-vectors, it will be still be 951 // inconsistent. 952 if (Size == 16 && Subtarget->has16BitInsts()) { 953 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 954 IntermediateVT = RegisterVT; 955 NumIntermediates = (NumElts + 1) / 2; 956 return NumIntermediates; 957 } 958 } 959 960 return TargetLowering::getVectorTypeBreakdownForCallingConv( 961 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 962 } 963 964 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 965 assert(DMaskLanes != 0); 966 967 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 968 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 969 return EVT::getVectorVT(Ty->getContext(), 970 EVT::getEVT(VT->getElementType()), 971 NumElts); 972 } 973 974 return EVT::getEVT(Ty); 975 } 976 977 // Peek through TFE struct returns to only use the data size. 978 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 979 auto *ST = dyn_cast<StructType>(Ty); 980 if (!ST) 981 return memVTFromImageData(Ty, DMaskLanes); 982 983 // Some intrinsics return an aggregate type - special case to work out the 984 // correct memVT. 985 // 986 // Only limited forms of aggregate type currently expected. 987 if (ST->getNumContainedTypes() != 2 || 988 !ST->getContainedType(1)->isIntegerTy(32)) 989 return EVT(); 990 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 991 } 992 993 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 994 const CallInst &CI, 995 MachineFunction &MF, 996 unsigned IntrID) const { 997 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 998 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 999 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1000 (Intrinsic::ID)IntrID); 1001 if (Attr.hasFnAttribute(Attribute::ReadNone)) 1002 return false; 1003 1004 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1005 1006 if (RsrcIntr->IsImage) { 1007 Info.ptrVal = MFI->getImagePSV( 1008 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1009 CI.getArgOperand(RsrcIntr->RsrcArg)); 1010 Info.align.reset(); 1011 } else { 1012 Info.ptrVal = MFI->getBufferPSV( 1013 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1014 CI.getArgOperand(RsrcIntr->RsrcArg)); 1015 } 1016 1017 Info.flags = MachineMemOperand::MODereferenceable; 1018 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 1019 unsigned DMaskLanes = 4; 1020 1021 if (RsrcIntr->IsImage) { 1022 const AMDGPU::ImageDimIntrinsicInfo *Intr 1023 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1024 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1025 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1026 1027 if (!BaseOpcode->Gather4) { 1028 // If this isn't a gather, we may have excess loaded elements in the 1029 // IR type. Check the dmask for the real number of elements loaded. 1030 unsigned DMask 1031 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1032 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1033 } 1034 1035 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1036 } else 1037 Info.memVT = EVT::getEVT(CI.getType()); 1038 1039 // FIXME: What does alignment mean for an image? 1040 Info.opc = ISD::INTRINSIC_W_CHAIN; 1041 Info.flags |= MachineMemOperand::MOLoad; 1042 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1043 Info.opc = ISD::INTRINSIC_VOID; 1044 1045 Type *DataTy = CI.getArgOperand(0)->getType(); 1046 if (RsrcIntr->IsImage) { 1047 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1048 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1049 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1050 } else 1051 Info.memVT = EVT::getEVT(DataTy); 1052 1053 Info.flags |= MachineMemOperand::MOStore; 1054 } else { 1055 // Atomic 1056 Info.opc = ISD::INTRINSIC_W_CHAIN; 1057 Info.memVT = MVT::getVT(CI.getType()); 1058 Info.flags = MachineMemOperand::MOLoad | 1059 MachineMemOperand::MOStore | 1060 MachineMemOperand::MODereferenceable; 1061 1062 // XXX - Should this be volatile without known ordering? 1063 Info.flags |= MachineMemOperand::MOVolatile; 1064 } 1065 return true; 1066 } 1067 1068 switch (IntrID) { 1069 case Intrinsic::amdgcn_atomic_inc: 1070 case Intrinsic::amdgcn_atomic_dec: 1071 case Intrinsic::amdgcn_ds_ordered_add: 1072 case Intrinsic::amdgcn_ds_ordered_swap: 1073 case Intrinsic::amdgcn_ds_fadd: 1074 case Intrinsic::amdgcn_ds_fmin: 1075 case Intrinsic::amdgcn_ds_fmax: { 1076 Info.opc = ISD::INTRINSIC_W_CHAIN; 1077 Info.memVT = MVT::getVT(CI.getType()); 1078 Info.ptrVal = CI.getOperand(0); 1079 Info.align.reset(); 1080 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1081 1082 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1083 if (!Vol->isZero()) 1084 Info.flags |= MachineMemOperand::MOVolatile; 1085 1086 return true; 1087 } 1088 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1089 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1090 1091 Info.opc = ISD::INTRINSIC_VOID; 1092 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1093 Info.ptrVal = MFI->getBufferPSV( 1094 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1095 CI.getArgOperand(1)); 1096 Info.align.reset(); 1097 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1098 1099 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1100 if (!Vol || !Vol->isZero()) 1101 Info.flags |= MachineMemOperand::MOVolatile; 1102 1103 return true; 1104 } 1105 case Intrinsic::amdgcn_global_atomic_fadd: { 1106 Info.opc = ISD::INTRINSIC_VOID; 1107 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 1108 ->getPointerElementType()); 1109 Info.ptrVal = CI.getOperand(0); 1110 Info.align.reset(); 1111 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1112 1113 return true; 1114 } 1115 case Intrinsic::amdgcn_ds_append: 1116 case Intrinsic::amdgcn_ds_consume: { 1117 Info.opc = ISD::INTRINSIC_W_CHAIN; 1118 Info.memVT = MVT::getVT(CI.getType()); 1119 Info.ptrVal = CI.getOperand(0); 1120 Info.align.reset(); 1121 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1122 1123 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1124 if (!Vol->isZero()) 1125 Info.flags |= MachineMemOperand::MOVolatile; 1126 1127 return true; 1128 } 1129 case Intrinsic::amdgcn_ds_gws_init: 1130 case Intrinsic::amdgcn_ds_gws_barrier: 1131 case Intrinsic::amdgcn_ds_gws_sema_v: 1132 case Intrinsic::amdgcn_ds_gws_sema_br: 1133 case Intrinsic::amdgcn_ds_gws_sema_p: 1134 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1135 Info.opc = ISD::INTRINSIC_VOID; 1136 1137 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1138 Info.ptrVal = 1139 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1140 1141 // This is an abstract access, but we need to specify a type and size. 1142 Info.memVT = MVT::i32; 1143 Info.size = 4; 1144 Info.align = Align(4); 1145 1146 Info.flags = MachineMemOperand::MOStore; 1147 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1148 Info.flags = MachineMemOperand::MOLoad; 1149 return true; 1150 } 1151 default: 1152 return false; 1153 } 1154 } 1155 1156 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1157 SmallVectorImpl<Value*> &Ops, 1158 Type *&AccessTy) const { 1159 switch (II->getIntrinsicID()) { 1160 case Intrinsic::amdgcn_atomic_inc: 1161 case Intrinsic::amdgcn_atomic_dec: 1162 case Intrinsic::amdgcn_ds_ordered_add: 1163 case Intrinsic::amdgcn_ds_ordered_swap: 1164 case Intrinsic::amdgcn_ds_fadd: 1165 case Intrinsic::amdgcn_ds_fmin: 1166 case Intrinsic::amdgcn_ds_fmax: { 1167 Value *Ptr = II->getArgOperand(0); 1168 AccessTy = II->getType(); 1169 Ops.push_back(Ptr); 1170 return true; 1171 } 1172 default: 1173 return false; 1174 } 1175 } 1176 1177 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1178 if (!Subtarget->hasFlatInstOffsets()) { 1179 // Flat instructions do not have offsets, and only have the register 1180 // address. 1181 return AM.BaseOffs == 0 && AM.Scale == 0; 1182 } 1183 1184 return AM.Scale == 0 && 1185 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1186 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1187 /*Signed=*/false)); 1188 } 1189 1190 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1191 if (Subtarget->hasFlatGlobalInsts()) 1192 return AM.Scale == 0 && 1193 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1194 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1195 /*Signed=*/true)); 1196 1197 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1198 // Assume the we will use FLAT for all global memory accesses 1199 // on VI. 1200 // FIXME: This assumption is currently wrong. On VI we still use 1201 // MUBUF instructions for the r + i addressing mode. As currently 1202 // implemented, the MUBUF instructions only work on buffer < 4GB. 1203 // It may be possible to support > 4GB buffers with MUBUF instructions, 1204 // by setting the stride value in the resource descriptor which would 1205 // increase the size limit to (stride * 4GB). However, this is risky, 1206 // because it has never been validated. 1207 return isLegalFlatAddressingMode(AM); 1208 } 1209 1210 return isLegalMUBUFAddressingMode(AM); 1211 } 1212 1213 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1214 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1215 // additionally can do r + r + i with addr64. 32-bit has more addressing 1216 // mode options. Depending on the resource constant, it can also do 1217 // (i64 r0) + (i32 r1) * (i14 i). 1218 // 1219 // Private arrays end up using a scratch buffer most of the time, so also 1220 // assume those use MUBUF instructions. Scratch loads / stores are currently 1221 // implemented as mubuf instructions with offen bit set, so slightly 1222 // different than the normal addr64. 1223 if (!isUInt<12>(AM.BaseOffs)) 1224 return false; 1225 1226 // FIXME: Since we can split immediate into soffset and immediate offset, 1227 // would it make sense to allow any immediate? 1228 1229 switch (AM.Scale) { 1230 case 0: // r + i or just i, depending on HasBaseReg. 1231 return true; 1232 case 1: 1233 return true; // We have r + r or r + i. 1234 case 2: 1235 if (AM.HasBaseReg) { 1236 // Reject 2 * r + r. 1237 return false; 1238 } 1239 1240 // Allow 2 * r as r + r 1241 // Or 2 * r + i is allowed as r + r + i. 1242 return true; 1243 default: // Don't allow n * r 1244 return false; 1245 } 1246 } 1247 1248 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1249 const AddrMode &AM, Type *Ty, 1250 unsigned AS, Instruction *I) const { 1251 // No global is ever allowed as a base. 1252 if (AM.BaseGV) 1253 return false; 1254 1255 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1256 return isLegalGlobalAddressingMode(AM); 1257 1258 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1259 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1260 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1261 // If the offset isn't a multiple of 4, it probably isn't going to be 1262 // correctly aligned. 1263 // FIXME: Can we get the real alignment here? 1264 if (AM.BaseOffs % 4 != 0) 1265 return isLegalMUBUFAddressingMode(AM); 1266 1267 // There are no SMRD extloads, so if we have to do a small type access we 1268 // will use a MUBUF load. 1269 // FIXME?: We also need to do this if unaligned, but we don't know the 1270 // alignment here. 1271 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1272 return isLegalGlobalAddressingMode(AM); 1273 1274 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1275 // SMRD instructions have an 8-bit, dword offset on SI. 1276 if (!isUInt<8>(AM.BaseOffs / 4)) 1277 return false; 1278 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1279 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1280 // in 8-bits, it can use a smaller encoding. 1281 if (!isUInt<32>(AM.BaseOffs / 4)) 1282 return false; 1283 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1284 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1285 if (!isUInt<20>(AM.BaseOffs)) 1286 return false; 1287 } else 1288 llvm_unreachable("unhandled generation"); 1289 1290 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1291 return true; 1292 1293 if (AM.Scale == 1 && AM.HasBaseReg) 1294 return true; 1295 1296 return false; 1297 1298 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1299 return isLegalMUBUFAddressingMode(AM); 1300 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1301 AS == AMDGPUAS::REGION_ADDRESS) { 1302 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1303 // field. 1304 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1305 // an 8-bit dword offset but we don't know the alignment here. 1306 if (!isUInt<16>(AM.BaseOffs)) 1307 return false; 1308 1309 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1310 return true; 1311 1312 if (AM.Scale == 1 && AM.HasBaseReg) 1313 return true; 1314 1315 return false; 1316 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1317 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1318 // For an unknown address space, this usually means that this is for some 1319 // reason being used for pure arithmetic, and not based on some addressing 1320 // computation. We don't have instructions that compute pointers with any 1321 // addressing modes, so treat them as having no offset like flat 1322 // instructions. 1323 return isLegalFlatAddressingMode(AM); 1324 } 1325 1326 // Assume a user alias of global for unknown address spaces. 1327 return isLegalGlobalAddressingMode(AM); 1328 } 1329 1330 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1331 const SelectionDAG &DAG) const { 1332 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1333 return (MemVT.getSizeInBits() <= 4 * 32); 1334 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1335 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1336 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1337 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1338 return (MemVT.getSizeInBits() <= 2 * 32); 1339 } 1340 return true; 1341 } 1342 1343 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1344 unsigned Size, unsigned AddrSpace, unsigned Align, 1345 MachineMemOperand::Flags Flags, bool *IsFast) const { 1346 if (IsFast) 1347 *IsFast = false; 1348 1349 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1350 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1351 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1352 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1353 // with adjacent offsets. 1354 bool AlignedBy4 = (Align % 4 == 0); 1355 if (IsFast) 1356 *IsFast = AlignedBy4; 1357 1358 return AlignedBy4; 1359 } 1360 1361 // FIXME: We have to be conservative here and assume that flat operations 1362 // will access scratch. If we had access to the IR function, then we 1363 // could determine if any private memory was used in the function. 1364 if (!Subtarget->hasUnalignedScratchAccess() && 1365 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1366 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1367 bool AlignedBy4 = Align >= 4; 1368 if (IsFast) 1369 *IsFast = AlignedBy4; 1370 1371 return AlignedBy4; 1372 } 1373 1374 if (Subtarget->hasUnalignedBufferAccess()) { 1375 // If we have an uniform constant load, it still requires using a slow 1376 // buffer instruction if unaligned. 1377 if (IsFast) { 1378 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1379 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1380 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1381 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1382 Align >= 4 : Align != 2; 1383 } 1384 1385 return true; 1386 } 1387 1388 // Smaller than dword value must be aligned. 1389 if (Size < 32) 1390 return false; 1391 1392 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1393 // byte-address are ignored, thus forcing Dword alignment. 1394 // This applies to private, global, and constant memory. 1395 if (IsFast) 1396 *IsFast = true; 1397 1398 return Size >= 32 && Align >= 4; 1399 } 1400 1401 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1402 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1403 bool *IsFast) const { 1404 if (IsFast) 1405 *IsFast = false; 1406 1407 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1408 // which isn't a simple VT. 1409 // Until MVT is extended to handle this, simply check for the size and 1410 // rely on the condition below: allow accesses if the size is a multiple of 4. 1411 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1412 VT.getStoreSize() > 16)) { 1413 return false; 1414 } 1415 1416 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1417 Align, Flags, IsFast); 1418 } 1419 1420 EVT SITargetLowering::getOptimalMemOpType( 1421 const MemOp &Op, const AttributeList &FuncAttributes) const { 1422 // FIXME: Should account for address space here. 1423 1424 // The default fallback uses the private pointer size as a guess for a type to 1425 // use. Make sure we switch these to 64-bit accesses. 1426 1427 if (Op.size() >= 16 && 1428 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1429 return MVT::v4i32; 1430 1431 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1432 return MVT::v2i32; 1433 1434 // Use the default. 1435 return MVT::Other; 1436 } 1437 1438 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1439 unsigned DestAS) const { 1440 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1441 } 1442 1443 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1444 const MemSDNode *MemNode = cast<MemSDNode>(N); 1445 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1446 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1447 return I && I->getMetadata("amdgpu.noclobber"); 1448 } 1449 1450 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1451 unsigned DestAS) const { 1452 // Flat -> private/local is a simple truncate. 1453 // Flat -> global is no-op 1454 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1455 return true; 1456 1457 return isNoopAddrSpaceCast(SrcAS, DestAS); 1458 } 1459 1460 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1461 const MemSDNode *MemNode = cast<MemSDNode>(N); 1462 1463 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1464 } 1465 1466 TargetLoweringBase::LegalizeTypeAction 1467 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1468 int NumElts = VT.getVectorNumElements(); 1469 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1470 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1471 return TargetLoweringBase::getPreferredVectorAction(VT); 1472 } 1473 1474 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1475 Type *Ty) const { 1476 // FIXME: Could be smarter if called for vector constants. 1477 return true; 1478 } 1479 1480 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1481 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1482 switch (Op) { 1483 case ISD::LOAD: 1484 case ISD::STORE: 1485 1486 // These operations are done with 32-bit instructions anyway. 1487 case ISD::AND: 1488 case ISD::OR: 1489 case ISD::XOR: 1490 case ISD::SELECT: 1491 // TODO: Extensions? 1492 return true; 1493 default: 1494 return false; 1495 } 1496 } 1497 1498 // SimplifySetCC uses this function to determine whether or not it should 1499 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1500 if (VT == MVT::i1 && Op == ISD::SETCC) 1501 return false; 1502 1503 return TargetLowering::isTypeDesirableForOp(Op, VT); 1504 } 1505 1506 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1507 const SDLoc &SL, 1508 SDValue Chain, 1509 uint64_t Offset) const { 1510 const DataLayout &DL = DAG.getDataLayout(); 1511 MachineFunction &MF = DAG.getMachineFunction(); 1512 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1513 1514 const ArgDescriptor *InputPtrReg; 1515 const TargetRegisterClass *RC; 1516 1517 std::tie(InputPtrReg, RC) 1518 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1519 1520 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1521 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1522 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1523 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1524 1525 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1526 } 1527 1528 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1529 const SDLoc &SL) const { 1530 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1531 FIRST_IMPLICIT); 1532 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1533 } 1534 1535 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1536 const SDLoc &SL, SDValue Val, 1537 bool Signed, 1538 const ISD::InputArg *Arg) const { 1539 // First, if it is a widened vector, narrow it. 1540 if (VT.isVector() && 1541 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1542 EVT NarrowedVT = 1543 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1544 VT.getVectorNumElements()); 1545 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1546 DAG.getConstant(0, SL, MVT::i32)); 1547 } 1548 1549 // Then convert the vector elements or scalar value. 1550 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1551 VT.bitsLT(MemVT)) { 1552 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1553 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1554 } 1555 1556 if (MemVT.isFloatingPoint()) 1557 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1558 else if (Signed) 1559 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1560 else 1561 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1562 1563 return Val; 1564 } 1565 1566 SDValue SITargetLowering::lowerKernargMemParameter( 1567 SelectionDAG &DAG, EVT VT, EVT MemVT, 1568 const SDLoc &SL, SDValue Chain, 1569 uint64_t Offset, unsigned Align, bool Signed, 1570 const ISD::InputArg *Arg) const { 1571 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1572 1573 // Try to avoid using an extload by loading earlier than the argument address, 1574 // and extracting the relevant bits. The load should hopefully be merged with 1575 // the previous argument. 1576 if (MemVT.getStoreSize() < 4 && Align < 4) { 1577 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1578 int64_t AlignDownOffset = alignDown(Offset, 4); 1579 int64_t OffsetDiff = Offset - AlignDownOffset; 1580 1581 EVT IntVT = MemVT.changeTypeToInteger(); 1582 1583 // TODO: If we passed in the base kernel offset we could have a better 1584 // alignment than 4, but we don't really need it. 1585 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1586 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1587 MachineMemOperand::MODereferenceable | 1588 MachineMemOperand::MOInvariant); 1589 1590 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1591 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1592 1593 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1594 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1595 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1596 1597 1598 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1599 } 1600 1601 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1602 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1603 MachineMemOperand::MODereferenceable | 1604 MachineMemOperand::MOInvariant); 1605 1606 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1607 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1608 } 1609 1610 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1611 const SDLoc &SL, SDValue Chain, 1612 const ISD::InputArg &Arg) const { 1613 MachineFunction &MF = DAG.getMachineFunction(); 1614 MachineFrameInfo &MFI = MF.getFrameInfo(); 1615 1616 if (Arg.Flags.isByVal()) { 1617 unsigned Size = Arg.Flags.getByValSize(); 1618 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1619 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1620 } 1621 1622 unsigned ArgOffset = VA.getLocMemOffset(); 1623 unsigned ArgSize = VA.getValVT().getStoreSize(); 1624 1625 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1626 1627 // Create load nodes to retrieve arguments from the stack. 1628 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1629 SDValue ArgValue; 1630 1631 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1632 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1633 MVT MemVT = VA.getValVT(); 1634 1635 switch (VA.getLocInfo()) { 1636 default: 1637 break; 1638 case CCValAssign::BCvt: 1639 MemVT = VA.getLocVT(); 1640 break; 1641 case CCValAssign::SExt: 1642 ExtType = ISD::SEXTLOAD; 1643 break; 1644 case CCValAssign::ZExt: 1645 ExtType = ISD::ZEXTLOAD; 1646 break; 1647 case CCValAssign::AExt: 1648 ExtType = ISD::EXTLOAD; 1649 break; 1650 } 1651 1652 ArgValue = DAG.getExtLoad( 1653 ExtType, SL, VA.getLocVT(), Chain, FIN, 1654 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1655 MemVT); 1656 return ArgValue; 1657 } 1658 1659 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1660 const SIMachineFunctionInfo &MFI, 1661 EVT VT, 1662 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1663 const ArgDescriptor *Reg; 1664 const TargetRegisterClass *RC; 1665 1666 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1667 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1668 } 1669 1670 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1671 CallingConv::ID CallConv, 1672 ArrayRef<ISD::InputArg> Ins, 1673 BitVector &Skipped, 1674 FunctionType *FType, 1675 SIMachineFunctionInfo *Info) { 1676 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1677 const ISD::InputArg *Arg = &Ins[I]; 1678 1679 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1680 "vector type argument should have been split"); 1681 1682 // First check if it's a PS input addr. 1683 if (CallConv == CallingConv::AMDGPU_PS && 1684 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1685 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1686 1687 // Inconveniently only the first part of the split is marked as isSplit, 1688 // so skip to the end. We only want to increment PSInputNum once for the 1689 // entire split argument. 1690 if (Arg->Flags.isSplit()) { 1691 while (!Arg->Flags.isSplitEnd()) { 1692 assert((!Arg->VT.isVector() || 1693 Arg->VT.getScalarSizeInBits() == 16) && 1694 "unexpected vector split in ps argument type"); 1695 if (!SkipArg) 1696 Splits.push_back(*Arg); 1697 Arg = &Ins[++I]; 1698 } 1699 } 1700 1701 if (SkipArg) { 1702 // We can safely skip PS inputs. 1703 Skipped.set(Arg->getOrigArgIndex()); 1704 ++PSInputNum; 1705 continue; 1706 } 1707 1708 Info->markPSInputAllocated(PSInputNum); 1709 if (Arg->Used) 1710 Info->markPSInputEnabled(PSInputNum); 1711 1712 ++PSInputNum; 1713 } 1714 1715 Splits.push_back(*Arg); 1716 } 1717 } 1718 1719 // Allocate special inputs passed in VGPRs. 1720 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1721 MachineFunction &MF, 1722 const SIRegisterInfo &TRI, 1723 SIMachineFunctionInfo &Info) const { 1724 const LLT S32 = LLT::scalar(32); 1725 MachineRegisterInfo &MRI = MF.getRegInfo(); 1726 1727 if (Info.hasWorkItemIDX()) { 1728 Register Reg = AMDGPU::VGPR0; 1729 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1730 1731 CCInfo.AllocateReg(Reg); 1732 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1733 } 1734 1735 if (Info.hasWorkItemIDY()) { 1736 Register Reg = AMDGPU::VGPR1; 1737 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1738 1739 CCInfo.AllocateReg(Reg); 1740 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1741 } 1742 1743 if (Info.hasWorkItemIDZ()) { 1744 Register Reg = AMDGPU::VGPR2; 1745 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1746 1747 CCInfo.AllocateReg(Reg); 1748 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1749 } 1750 } 1751 1752 // Try to allocate a VGPR at the end of the argument list, or if no argument 1753 // VGPRs are left allocating a stack slot. 1754 // If \p Mask is is given it indicates bitfield position in the register. 1755 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1756 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1757 ArgDescriptor Arg = ArgDescriptor()) { 1758 if (Arg.isSet()) 1759 return ArgDescriptor::createArg(Arg, Mask); 1760 1761 ArrayRef<MCPhysReg> ArgVGPRs 1762 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1763 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1764 if (RegIdx == ArgVGPRs.size()) { 1765 // Spill to stack required. 1766 int64_t Offset = CCInfo.AllocateStack(4, 4); 1767 1768 return ArgDescriptor::createStack(Offset, Mask); 1769 } 1770 1771 unsigned Reg = ArgVGPRs[RegIdx]; 1772 Reg = CCInfo.AllocateReg(Reg); 1773 assert(Reg != AMDGPU::NoRegister); 1774 1775 MachineFunction &MF = CCInfo.getMachineFunction(); 1776 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1777 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1778 return ArgDescriptor::createRegister(Reg, Mask); 1779 } 1780 1781 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1782 const TargetRegisterClass *RC, 1783 unsigned NumArgRegs) { 1784 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1785 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1786 if (RegIdx == ArgSGPRs.size()) 1787 report_fatal_error("ran out of SGPRs for arguments"); 1788 1789 unsigned Reg = ArgSGPRs[RegIdx]; 1790 Reg = CCInfo.AllocateReg(Reg); 1791 assert(Reg != AMDGPU::NoRegister); 1792 1793 MachineFunction &MF = CCInfo.getMachineFunction(); 1794 MF.addLiveIn(Reg, RC); 1795 return ArgDescriptor::createRegister(Reg); 1796 } 1797 1798 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1799 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1800 } 1801 1802 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1803 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1804 } 1805 1806 /// Allocate implicit function VGPR arguments at the end of allocated user 1807 /// arguments. 1808 void SITargetLowering::allocateSpecialInputVGPRs( 1809 CCState &CCInfo, MachineFunction &MF, 1810 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1811 const unsigned Mask = 0x3ff; 1812 ArgDescriptor Arg; 1813 1814 if (Info.hasWorkItemIDX()) { 1815 Arg = allocateVGPR32Input(CCInfo, Mask); 1816 Info.setWorkItemIDX(Arg); 1817 } 1818 1819 if (Info.hasWorkItemIDY()) { 1820 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1821 Info.setWorkItemIDY(Arg); 1822 } 1823 1824 if (Info.hasWorkItemIDZ()) 1825 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1826 } 1827 1828 /// Allocate implicit function VGPR arguments in fixed registers. 1829 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1830 CCState &CCInfo, MachineFunction &MF, 1831 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1832 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1833 if (!Reg) 1834 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1835 1836 const unsigned Mask = 0x3ff; 1837 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1838 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1839 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1840 } 1841 1842 void SITargetLowering::allocateSpecialInputSGPRs( 1843 CCState &CCInfo, 1844 MachineFunction &MF, 1845 const SIRegisterInfo &TRI, 1846 SIMachineFunctionInfo &Info) const { 1847 auto &ArgInfo = Info.getArgInfo(); 1848 1849 // TODO: Unify handling with private memory pointers. 1850 1851 if (Info.hasDispatchPtr()) 1852 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1853 1854 if (Info.hasQueuePtr()) 1855 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1856 1857 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1858 // constant offset from the kernarg segment. 1859 if (Info.hasImplicitArgPtr()) 1860 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1861 1862 if (Info.hasDispatchID()) 1863 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1864 1865 // flat_scratch_init is not applicable for non-kernel functions. 1866 1867 if (Info.hasWorkGroupIDX()) 1868 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1869 1870 if (Info.hasWorkGroupIDY()) 1871 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1872 1873 if (Info.hasWorkGroupIDZ()) 1874 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1875 } 1876 1877 // Allocate special inputs passed in user SGPRs. 1878 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1879 MachineFunction &MF, 1880 const SIRegisterInfo &TRI, 1881 SIMachineFunctionInfo &Info) const { 1882 if (Info.hasImplicitBufferPtr()) { 1883 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1884 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1885 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1886 } 1887 1888 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1889 if (Info.hasPrivateSegmentBuffer()) { 1890 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1891 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1892 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1893 } 1894 1895 if (Info.hasDispatchPtr()) { 1896 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1897 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1898 CCInfo.AllocateReg(DispatchPtrReg); 1899 } 1900 1901 if (Info.hasQueuePtr()) { 1902 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1903 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1904 CCInfo.AllocateReg(QueuePtrReg); 1905 } 1906 1907 if (Info.hasKernargSegmentPtr()) { 1908 MachineRegisterInfo &MRI = MF.getRegInfo(); 1909 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1910 CCInfo.AllocateReg(InputPtrReg); 1911 1912 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1913 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1914 } 1915 1916 if (Info.hasDispatchID()) { 1917 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1918 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1919 CCInfo.AllocateReg(DispatchIDReg); 1920 } 1921 1922 if (Info.hasFlatScratchInit()) { 1923 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1924 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1925 CCInfo.AllocateReg(FlatScratchInitReg); 1926 } 1927 1928 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1929 // these from the dispatch pointer. 1930 } 1931 1932 // Allocate special input registers that are initialized per-wave. 1933 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1934 MachineFunction &MF, 1935 SIMachineFunctionInfo &Info, 1936 CallingConv::ID CallConv, 1937 bool IsShader) const { 1938 if (Info.hasWorkGroupIDX()) { 1939 unsigned Reg = Info.addWorkGroupIDX(); 1940 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1941 CCInfo.AllocateReg(Reg); 1942 } 1943 1944 if (Info.hasWorkGroupIDY()) { 1945 unsigned Reg = Info.addWorkGroupIDY(); 1946 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1947 CCInfo.AllocateReg(Reg); 1948 } 1949 1950 if (Info.hasWorkGroupIDZ()) { 1951 unsigned Reg = Info.addWorkGroupIDZ(); 1952 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1953 CCInfo.AllocateReg(Reg); 1954 } 1955 1956 if (Info.hasWorkGroupInfo()) { 1957 unsigned Reg = Info.addWorkGroupInfo(); 1958 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1959 CCInfo.AllocateReg(Reg); 1960 } 1961 1962 if (Info.hasPrivateSegmentWaveByteOffset()) { 1963 // Scratch wave offset passed in system SGPR. 1964 unsigned PrivateSegmentWaveByteOffsetReg; 1965 1966 if (IsShader) { 1967 PrivateSegmentWaveByteOffsetReg = 1968 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1969 1970 // This is true if the scratch wave byte offset doesn't have a fixed 1971 // location. 1972 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1973 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1974 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1975 } 1976 } else 1977 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1978 1979 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1980 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1981 } 1982 } 1983 1984 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1985 MachineFunction &MF, 1986 const SIRegisterInfo &TRI, 1987 SIMachineFunctionInfo &Info) { 1988 // Now that we've figured out where the scratch register inputs are, see if 1989 // should reserve the arguments and use them directly. 1990 MachineFrameInfo &MFI = MF.getFrameInfo(); 1991 bool HasStackObjects = MFI.hasStackObjects(); 1992 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 1993 1994 // Record that we know we have non-spill stack objects so we don't need to 1995 // check all stack objects later. 1996 if (HasStackObjects) 1997 Info.setHasNonSpillStackObjects(true); 1998 1999 // Everything live out of a block is spilled with fast regalloc, so it's 2000 // almost certain that spilling will be required. 2001 if (TM.getOptLevel() == CodeGenOpt::None) 2002 HasStackObjects = true; 2003 2004 // For now assume stack access is needed in any callee functions, so we need 2005 // the scratch registers to pass in. 2006 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2007 2008 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2009 // If we have stack objects, we unquestionably need the private buffer 2010 // resource. For the Code Object V2 ABI, this will be the first 4 user 2011 // SGPR inputs. We can reserve those and use them directly. 2012 2013 Register PrivateSegmentBufferReg = 2014 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2015 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2016 } else { 2017 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2018 // We tentatively reserve the last registers (skipping the last registers 2019 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2020 // we'll replace these with the ones immediately after those which were 2021 // really allocated. In the prologue copies will be inserted from the 2022 // argument to these reserved registers. 2023 2024 // Without HSA, relocations are used for the scratch pointer and the 2025 // buffer resource setup is always inserted in the prologue. Scratch wave 2026 // offset is still in an input SGPR. 2027 Info.setScratchRSrcReg(ReservedBufferReg); 2028 } 2029 2030 MachineRegisterInfo &MRI = MF.getRegInfo(); 2031 2032 // For entry functions we have to set up the stack pointer if we use it, 2033 // whereas non-entry functions get this "for free". This means there is no 2034 // intrinsic advantage to using S32 over S34 in cases where we do not have 2035 // calls but do need a frame pointer (i.e. if we are requested to have one 2036 // because frame pointer elimination is disabled). To keep things simple we 2037 // only ever use S32 as the call ABI stack pointer, and so using it does not 2038 // imply we need a separate frame pointer. 2039 // 2040 // Try to use s32 as the SP, but move it if it would interfere with input 2041 // arguments. This won't work with calls though. 2042 // 2043 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2044 // registers. 2045 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2046 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2047 } else { 2048 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2049 2050 if (MFI.hasCalls()) 2051 report_fatal_error("call in graphics shader with too many input SGPRs"); 2052 2053 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2054 if (!MRI.isLiveIn(Reg)) { 2055 Info.setStackPtrOffsetReg(Reg); 2056 break; 2057 } 2058 } 2059 2060 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2061 report_fatal_error("failed to find register for SP"); 2062 } 2063 2064 // hasFP should be accurate for entry functions even before the frame is 2065 // finalized, because it does not rely on the known stack size, only 2066 // properties like whether variable sized objects are present. 2067 if (ST.getFrameLowering()->hasFP(MF)) { 2068 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2069 } 2070 } 2071 2072 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2073 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2074 return !Info->isEntryFunction(); 2075 } 2076 2077 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2078 2079 } 2080 2081 void SITargetLowering::insertCopiesSplitCSR( 2082 MachineBasicBlock *Entry, 2083 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2084 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2085 2086 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2087 if (!IStart) 2088 return; 2089 2090 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2091 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2092 MachineBasicBlock::iterator MBBI = Entry->begin(); 2093 for (const MCPhysReg *I = IStart; *I; ++I) { 2094 const TargetRegisterClass *RC = nullptr; 2095 if (AMDGPU::SReg_64RegClass.contains(*I)) 2096 RC = &AMDGPU::SGPR_64RegClass; 2097 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2098 RC = &AMDGPU::SGPR_32RegClass; 2099 else 2100 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2101 2102 Register NewVR = MRI->createVirtualRegister(RC); 2103 // Create copy from CSR to a virtual register. 2104 Entry->addLiveIn(*I); 2105 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2106 .addReg(*I); 2107 2108 // Insert the copy-back instructions right before the terminator. 2109 for (auto *Exit : Exits) 2110 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2111 TII->get(TargetOpcode::COPY), *I) 2112 .addReg(NewVR); 2113 } 2114 } 2115 2116 SDValue SITargetLowering::LowerFormalArguments( 2117 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2118 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2119 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2120 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2121 2122 MachineFunction &MF = DAG.getMachineFunction(); 2123 const Function &Fn = MF.getFunction(); 2124 FunctionType *FType = MF.getFunction().getFunctionType(); 2125 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2126 2127 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2128 DiagnosticInfoUnsupported NoGraphicsHSA( 2129 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2130 DAG.getContext()->diagnose(NoGraphicsHSA); 2131 return DAG.getEntryNode(); 2132 } 2133 2134 SmallVector<ISD::InputArg, 16> Splits; 2135 SmallVector<CCValAssign, 16> ArgLocs; 2136 BitVector Skipped(Ins.size()); 2137 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2138 *DAG.getContext()); 2139 2140 bool IsShader = AMDGPU::isShader(CallConv); 2141 bool IsKernel = AMDGPU::isKernel(CallConv); 2142 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2143 2144 if (IsShader) { 2145 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2146 2147 // At least one interpolation mode must be enabled or else the GPU will 2148 // hang. 2149 // 2150 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2151 // set PSInputAddr, the user wants to enable some bits after the compilation 2152 // based on run-time states. Since we can't know what the final PSInputEna 2153 // will look like, so we shouldn't do anything here and the user should take 2154 // responsibility for the correct programming. 2155 // 2156 // Otherwise, the following restrictions apply: 2157 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2158 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2159 // enabled too. 2160 if (CallConv == CallingConv::AMDGPU_PS) { 2161 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2162 ((Info->getPSInputAddr() & 0xF) == 0 && 2163 Info->isPSInputAllocated(11))) { 2164 CCInfo.AllocateReg(AMDGPU::VGPR0); 2165 CCInfo.AllocateReg(AMDGPU::VGPR1); 2166 Info->markPSInputAllocated(0); 2167 Info->markPSInputEnabled(0); 2168 } 2169 if (Subtarget->isAmdPalOS()) { 2170 // For isAmdPalOS, the user does not enable some bits after compilation 2171 // based on run-time states; the register values being generated here are 2172 // the final ones set in hardware. Therefore we need to apply the 2173 // workaround to PSInputAddr and PSInputEnable together. (The case where 2174 // a bit is set in PSInputAddr but not PSInputEnable is where the 2175 // frontend set up an input arg for a particular interpolation mode, but 2176 // nothing uses that input arg. Really we should have an earlier pass 2177 // that removes such an arg.) 2178 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2179 if ((PsInputBits & 0x7F) == 0 || 2180 ((PsInputBits & 0xF) == 0 && 2181 (PsInputBits >> 11 & 1))) 2182 Info->markPSInputEnabled( 2183 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2184 } 2185 } 2186 2187 assert(!Info->hasDispatchPtr() && 2188 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2189 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2190 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2191 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2192 !Info->hasWorkItemIDZ()); 2193 } else if (IsKernel) { 2194 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2195 } else { 2196 Splits.append(Ins.begin(), Ins.end()); 2197 } 2198 2199 if (IsEntryFunc) { 2200 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2201 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2202 } else { 2203 // For the fixed ABI, pass workitem IDs in the last argument register. 2204 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2205 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2206 } 2207 2208 if (IsKernel) { 2209 analyzeFormalArgumentsCompute(CCInfo, Ins); 2210 } else { 2211 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2212 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2213 } 2214 2215 SmallVector<SDValue, 16> Chains; 2216 2217 // FIXME: This is the minimum kernel argument alignment. We should improve 2218 // this to the maximum alignment of the arguments. 2219 // 2220 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2221 // kern arg offset. 2222 const unsigned KernelArgBaseAlign = 16; 2223 2224 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2225 const ISD::InputArg &Arg = Ins[i]; 2226 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2227 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2228 continue; 2229 } 2230 2231 CCValAssign &VA = ArgLocs[ArgIdx++]; 2232 MVT VT = VA.getLocVT(); 2233 2234 if (IsEntryFunc && VA.isMemLoc()) { 2235 VT = Ins[i].VT; 2236 EVT MemVT = VA.getLocVT(); 2237 2238 const uint64_t Offset = VA.getLocMemOffset(); 2239 unsigned Align = MinAlign(KernelArgBaseAlign, Offset); 2240 2241 SDValue Arg = lowerKernargMemParameter( 2242 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]); 2243 Chains.push_back(Arg.getValue(1)); 2244 2245 auto *ParamTy = 2246 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2247 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2248 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2249 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2250 // On SI local pointers are just offsets into LDS, so they are always 2251 // less than 16-bits. On CI and newer they could potentially be 2252 // real pointers, so we can't guarantee their size. 2253 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2254 DAG.getValueType(MVT::i16)); 2255 } 2256 2257 InVals.push_back(Arg); 2258 continue; 2259 } else if (!IsEntryFunc && VA.isMemLoc()) { 2260 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2261 InVals.push_back(Val); 2262 if (!Arg.Flags.isByVal()) 2263 Chains.push_back(Val.getValue(1)); 2264 continue; 2265 } 2266 2267 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2268 2269 Register Reg = VA.getLocReg(); 2270 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2271 EVT ValVT = VA.getValVT(); 2272 2273 Reg = MF.addLiveIn(Reg, RC); 2274 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2275 2276 if (Arg.Flags.isSRet()) { 2277 // The return object should be reasonably addressable. 2278 2279 // FIXME: This helps when the return is a real sret. If it is a 2280 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2281 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2282 unsigned NumBits 2283 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2284 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2285 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2286 } 2287 2288 // If this is an 8 or 16-bit value, it is really passed promoted 2289 // to 32 bits. Insert an assert[sz]ext to capture this, then 2290 // truncate to the right size. 2291 switch (VA.getLocInfo()) { 2292 case CCValAssign::Full: 2293 break; 2294 case CCValAssign::BCvt: 2295 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2296 break; 2297 case CCValAssign::SExt: 2298 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2299 DAG.getValueType(ValVT)); 2300 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2301 break; 2302 case CCValAssign::ZExt: 2303 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2304 DAG.getValueType(ValVT)); 2305 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2306 break; 2307 case CCValAssign::AExt: 2308 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2309 break; 2310 default: 2311 llvm_unreachable("Unknown loc info!"); 2312 } 2313 2314 InVals.push_back(Val); 2315 } 2316 2317 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2318 // Special inputs come after user arguments. 2319 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2320 } 2321 2322 // Start adding system SGPRs. 2323 if (IsEntryFunc) { 2324 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2325 } else { 2326 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2327 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2328 } 2329 2330 auto &ArgUsageInfo = 2331 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2332 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2333 2334 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2335 Info->setBytesInStackArgArea(StackArgSize); 2336 2337 return Chains.empty() ? Chain : 2338 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2339 } 2340 2341 // TODO: If return values can't fit in registers, we should return as many as 2342 // possible in registers before passing on stack. 2343 bool SITargetLowering::CanLowerReturn( 2344 CallingConv::ID CallConv, 2345 MachineFunction &MF, bool IsVarArg, 2346 const SmallVectorImpl<ISD::OutputArg> &Outs, 2347 LLVMContext &Context) const { 2348 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2349 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2350 // for shaders. Vector types should be explicitly handled by CC. 2351 if (AMDGPU::isEntryFunctionCC(CallConv)) 2352 return true; 2353 2354 SmallVector<CCValAssign, 16> RVLocs; 2355 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2356 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2357 } 2358 2359 SDValue 2360 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2361 bool isVarArg, 2362 const SmallVectorImpl<ISD::OutputArg> &Outs, 2363 const SmallVectorImpl<SDValue> &OutVals, 2364 const SDLoc &DL, SelectionDAG &DAG) const { 2365 MachineFunction &MF = DAG.getMachineFunction(); 2366 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2367 2368 if (AMDGPU::isKernel(CallConv)) { 2369 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2370 OutVals, DL, DAG); 2371 } 2372 2373 bool IsShader = AMDGPU::isShader(CallConv); 2374 2375 Info->setIfReturnsVoid(Outs.empty()); 2376 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2377 2378 // CCValAssign - represent the assignment of the return value to a location. 2379 SmallVector<CCValAssign, 48> RVLocs; 2380 SmallVector<ISD::OutputArg, 48> Splits; 2381 2382 // CCState - Info about the registers and stack slots. 2383 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2384 *DAG.getContext()); 2385 2386 // Analyze outgoing return values. 2387 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2388 2389 SDValue Flag; 2390 SmallVector<SDValue, 48> RetOps; 2391 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2392 2393 // Add return address for callable functions. 2394 if (!Info->isEntryFunction()) { 2395 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2396 SDValue ReturnAddrReg = CreateLiveInRegister( 2397 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2398 2399 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2400 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2401 MVT::i64); 2402 Chain = 2403 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2404 Flag = Chain.getValue(1); 2405 RetOps.push_back(ReturnAddrVirtualReg); 2406 } 2407 2408 // Copy the result values into the output registers. 2409 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2410 ++I, ++RealRVLocIdx) { 2411 CCValAssign &VA = RVLocs[I]; 2412 assert(VA.isRegLoc() && "Can only return in registers!"); 2413 // TODO: Partially return in registers if return values don't fit. 2414 SDValue Arg = OutVals[RealRVLocIdx]; 2415 2416 // Copied from other backends. 2417 switch (VA.getLocInfo()) { 2418 case CCValAssign::Full: 2419 break; 2420 case CCValAssign::BCvt: 2421 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2422 break; 2423 case CCValAssign::SExt: 2424 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2425 break; 2426 case CCValAssign::ZExt: 2427 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2428 break; 2429 case CCValAssign::AExt: 2430 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2431 break; 2432 default: 2433 llvm_unreachable("Unknown loc info!"); 2434 } 2435 2436 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2437 Flag = Chain.getValue(1); 2438 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2439 } 2440 2441 // FIXME: Does sret work properly? 2442 if (!Info->isEntryFunction()) { 2443 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2444 const MCPhysReg *I = 2445 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2446 if (I) { 2447 for (; *I; ++I) { 2448 if (AMDGPU::SReg_64RegClass.contains(*I)) 2449 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2450 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2451 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2452 else 2453 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2454 } 2455 } 2456 } 2457 2458 // Update chain and glue. 2459 RetOps[0] = Chain; 2460 if (Flag.getNode()) 2461 RetOps.push_back(Flag); 2462 2463 unsigned Opc = AMDGPUISD::ENDPGM; 2464 if (!IsWaveEnd) 2465 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2466 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2467 } 2468 2469 SDValue SITargetLowering::LowerCallResult( 2470 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2471 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2472 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2473 SDValue ThisVal) const { 2474 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2475 2476 // Assign locations to each value returned by this call. 2477 SmallVector<CCValAssign, 16> RVLocs; 2478 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2479 *DAG.getContext()); 2480 CCInfo.AnalyzeCallResult(Ins, RetCC); 2481 2482 // Copy all of the result registers out of their specified physreg. 2483 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2484 CCValAssign VA = RVLocs[i]; 2485 SDValue Val; 2486 2487 if (VA.isRegLoc()) { 2488 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2489 Chain = Val.getValue(1); 2490 InFlag = Val.getValue(2); 2491 } else if (VA.isMemLoc()) { 2492 report_fatal_error("TODO: return values in memory"); 2493 } else 2494 llvm_unreachable("unknown argument location type"); 2495 2496 switch (VA.getLocInfo()) { 2497 case CCValAssign::Full: 2498 break; 2499 case CCValAssign::BCvt: 2500 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2501 break; 2502 case CCValAssign::ZExt: 2503 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2504 DAG.getValueType(VA.getValVT())); 2505 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2506 break; 2507 case CCValAssign::SExt: 2508 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2509 DAG.getValueType(VA.getValVT())); 2510 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2511 break; 2512 case CCValAssign::AExt: 2513 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2514 break; 2515 default: 2516 llvm_unreachable("Unknown loc info!"); 2517 } 2518 2519 InVals.push_back(Val); 2520 } 2521 2522 return Chain; 2523 } 2524 2525 // Add code to pass special inputs required depending on used features separate 2526 // from the explicit user arguments present in the IR. 2527 void SITargetLowering::passSpecialInputs( 2528 CallLoweringInfo &CLI, 2529 CCState &CCInfo, 2530 const SIMachineFunctionInfo &Info, 2531 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2532 SmallVectorImpl<SDValue> &MemOpChains, 2533 SDValue Chain) const { 2534 // If we don't have a call site, this was a call inserted by 2535 // legalization. These can never use special inputs. 2536 if (!CLI.CB) 2537 return; 2538 2539 SelectionDAG &DAG = CLI.DAG; 2540 const SDLoc &DL = CLI.DL; 2541 2542 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2543 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2544 2545 const AMDGPUFunctionArgInfo *CalleeArgInfo 2546 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2547 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2548 auto &ArgUsageInfo = 2549 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2550 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2551 } 2552 2553 // TODO: Unify with private memory register handling. This is complicated by 2554 // the fact that at least in kernels, the input argument is not necessarily 2555 // in the same location as the input. 2556 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2557 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2558 AMDGPUFunctionArgInfo::QUEUE_PTR, 2559 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2560 AMDGPUFunctionArgInfo::DISPATCH_ID, 2561 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2562 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2563 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2564 }; 2565 2566 for (auto InputID : InputRegs) { 2567 const ArgDescriptor *OutgoingArg; 2568 const TargetRegisterClass *ArgRC; 2569 2570 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID); 2571 if (!OutgoingArg) 2572 continue; 2573 2574 const ArgDescriptor *IncomingArg; 2575 const TargetRegisterClass *IncomingArgRC; 2576 std::tie(IncomingArg, IncomingArgRC) 2577 = CallerArgInfo.getPreloadedValue(InputID); 2578 assert(IncomingArgRC == ArgRC); 2579 2580 // All special arguments are ints for now. 2581 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2582 SDValue InputReg; 2583 2584 if (IncomingArg) { 2585 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2586 } else { 2587 // The implicit arg ptr is special because it doesn't have a corresponding 2588 // input for kernels, and is computed from the kernarg segment pointer. 2589 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2590 InputReg = getImplicitArgPtr(DAG, DL); 2591 } 2592 2593 if (OutgoingArg->isRegister()) { 2594 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2595 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2596 report_fatal_error("failed to allocate implicit input argument"); 2597 } else { 2598 unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4); 2599 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2600 SpecialArgOffset); 2601 MemOpChains.push_back(ArgStore); 2602 } 2603 } 2604 2605 // Pack workitem IDs into a single register or pass it as is if already 2606 // packed. 2607 const ArgDescriptor *OutgoingArg; 2608 const TargetRegisterClass *ArgRC; 2609 2610 std::tie(OutgoingArg, ArgRC) = 2611 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2612 if (!OutgoingArg) 2613 std::tie(OutgoingArg, ArgRC) = 2614 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2615 if (!OutgoingArg) 2616 std::tie(OutgoingArg, ArgRC) = 2617 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2618 if (!OutgoingArg) 2619 return; 2620 2621 const ArgDescriptor *IncomingArgX 2622 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first; 2623 const ArgDescriptor *IncomingArgY 2624 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first; 2625 const ArgDescriptor *IncomingArgZ 2626 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first; 2627 2628 SDValue InputReg; 2629 SDLoc SL; 2630 2631 // If incoming ids are not packed we need to pack them. 2632 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2633 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2634 2635 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2636 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2637 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2638 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2639 InputReg = InputReg.getNode() ? 2640 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2641 } 2642 2643 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2644 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2645 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2646 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2647 InputReg = InputReg.getNode() ? 2648 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2649 } 2650 2651 if (!InputReg.getNode()) { 2652 // Workitem ids are already packed, any of present incoming arguments 2653 // will carry all required fields. 2654 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2655 IncomingArgX ? *IncomingArgX : 2656 IncomingArgY ? *IncomingArgY : 2657 *IncomingArgZ, ~0u); 2658 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2659 } 2660 2661 if (OutgoingArg->isRegister()) { 2662 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2663 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2664 } else { 2665 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4); 2666 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2667 SpecialArgOffset); 2668 MemOpChains.push_back(ArgStore); 2669 } 2670 } 2671 2672 static bool canGuaranteeTCO(CallingConv::ID CC) { 2673 return CC == CallingConv::Fast; 2674 } 2675 2676 /// Return true if we might ever do TCO for calls with this calling convention. 2677 static bool mayTailCallThisCC(CallingConv::ID CC) { 2678 switch (CC) { 2679 case CallingConv::C: 2680 return true; 2681 default: 2682 return canGuaranteeTCO(CC); 2683 } 2684 } 2685 2686 bool SITargetLowering::isEligibleForTailCallOptimization( 2687 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2688 const SmallVectorImpl<ISD::OutputArg> &Outs, 2689 const SmallVectorImpl<SDValue> &OutVals, 2690 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2691 if (!mayTailCallThisCC(CalleeCC)) 2692 return false; 2693 2694 MachineFunction &MF = DAG.getMachineFunction(); 2695 const Function &CallerF = MF.getFunction(); 2696 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2697 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2698 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2699 2700 // Kernels aren't callable, and don't have a live in return address so it 2701 // doesn't make sense to do a tail call with entry functions. 2702 if (!CallerPreserved) 2703 return false; 2704 2705 bool CCMatch = CallerCC == CalleeCC; 2706 2707 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2708 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2709 return true; 2710 return false; 2711 } 2712 2713 // TODO: Can we handle var args? 2714 if (IsVarArg) 2715 return false; 2716 2717 for (const Argument &Arg : CallerF.args()) { 2718 if (Arg.hasByValAttr()) 2719 return false; 2720 } 2721 2722 LLVMContext &Ctx = *DAG.getContext(); 2723 2724 // Check that the call results are passed in the same way. 2725 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2726 CCAssignFnForCall(CalleeCC, IsVarArg), 2727 CCAssignFnForCall(CallerCC, IsVarArg))) 2728 return false; 2729 2730 // The callee has to preserve all registers the caller needs to preserve. 2731 if (!CCMatch) { 2732 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2733 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2734 return false; 2735 } 2736 2737 // Nothing more to check if the callee is taking no arguments. 2738 if (Outs.empty()) 2739 return true; 2740 2741 SmallVector<CCValAssign, 16> ArgLocs; 2742 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2743 2744 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2745 2746 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2747 // If the stack arguments for this call do not fit into our own save area then 2748 // the call cannot be made tail. 2749 // TODO: Is this really necessary? 2750 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2751 return false; 2752 2753 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2754 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2755 } 2756 2757 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2758 if (!CI->isTailCall()) 2759 return false; 2760 2761 const Function *ParentFn = CI->getParent()->getParent(); 2762 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2763 return false; 2764 return true; 2765 } 2766 2767 // The wave scratch offset register is used as the global base pointer. 2768 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2769 SmallVectorImpl<SDValue> &InVals) const { 2770 SelectionDAG &DAG = CLI.DAG; 2771 const SDLoc &DL = CLI.DL; 2772 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2773 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2774 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2775 SDValue Chain = CLI.Chain; 2776 SDValue Callee = CLI.Callee; 2777 bool &IsTailCall = CLI.IsTailCall; 2778 CallingConv::ID CallConv = CLI.CallConv; 2779 bool IsVarArg = CLI.IsVarArg; 2780 bool IsSibCall = false; 2781 bool IsThisReturn = false; 2782 MachineFunction &MF = DAG.getMachineFunction(); 2783 2784 if (Callee.isUndef() || isNullConstant(Callee)) { 2785 if (!CLI.IsTailCall) { 2786 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2787 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2788 } 2789 2790 return Chain; 2791 } 2792 2793 if (IsVarArg) { 2794 return lowerUnhandledCall(CLI, InVals, 2795 "unsupported call to variadic function "); 2796 } 2797 2798 if (!CLI.CB) 2799 report_fatal_error("unsupported libcall legalization"); 2800 2801 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2802 !CLI.CB->getCalledFunction()) { 2803 return lowerUnhandledCall(CLI, InVals, 2804 "unsupported indirect call to function "); 2805 } 2806 2807 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2808 return lowerUnhandledCall(CLI, InVals, 2809 "unsupported required tail call to function "); 2810 } 2811 2812 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2813 // Note the issue is with the CC of the calling function, not of the call 2814 // itself. 2815 return lowerUnhandledCall(CLI, InVals, 2816 "unsupported call from graphics shader of function "); 2817 } 2818 2819 if (IsTailCall) { 2820 IsTailCall = isEligibleForTailCallOptimization( 2821 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2822 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2823 report_fatal_error("failed to perform tail call elimination on a call " 2824 "site marked musttail"); 2825 } 2826 2827 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2828 2829 // A sibling call is one where we're under the usual C ABI and not planning 2830 // to change that but can still do a tail call: 2831 if (!TailCallOpt && IsTailCall) 2832 IsSibCall = true; 2833 2834 if (IsTailCall) 2835 ++NumTailCalls; 2836 } 2837 2838 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2839 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2840 SmallVector<SDValue, 8> MemOpChains; 2841 2842 // Analyze operands of the call, assigning locations to each operand. 2843 SmallVector<CCValAssign, 16> ArgLocs; 2844 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2845 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2846 2847 if (AMDGPUTargetMachine::EnableFixedFunctionABI) { 2848 // With a fixed ABI, allocate fixed registers before user arguments. 2849 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2850 } 2851 2852 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2853 2854 // Get a count of how many bytes are to be pushed on the stack. 2855 unsigned NumBytes = CCInfo.getNextStackOffset(); 2856 2857 if (IsSibCall) { 2858 // Since we're not changing the ABI to make this a tail call, the memory 2859 // operands are already available in the caller's incoming argument space. 2860 NumBytes = 0; 2861 } 2862 2863 // FPDiff is the byte offset of the call's argument area from the callee's. 2864 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2865 // by this amount for a tail call. In a sibling call it must be 0 because the 2866 // caller will deallocate the entire stack and the callee still expects its 2867 // arguments to begin at SP+0. Completely unused for non-tail calls. 2868 int32_t FPDiff = 0; 2869 MachineFrameInfo &MFI = MF.getFrameInfo(); 2870 2871 // Adjust the stack pointer for the new arguments... 2872 // These operations are automatically eliminated by the prolog/epilog pass 2873 if (!IsSibCall) { 2874 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2875 2876 SmallVector<SDValue, 4> CopyFromChains; 2877 2878 // In the HSA case, this should be an identity copy. 2879 SDValue ScratchRSrcReg 2880 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2881 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2882 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2883 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2884 } 2885 2886 MVT PtrVT = MVT::i32; 2887 2888 // Walk the register/memloc assignments, inserting copies/loads. 2889 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2890 CCValAssign &VA = ArgLocs[i]; 2891 SDValue Arg = OutVals[i]; 2892 2893 // Promote the value if needed. 2894 switch (VA.getLocInfo()) { 2895 case CCValAssign::Full: 2896 break; 2897 case CCValAssign::BCvt: 2898 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2899 break; 2900 case CCValAssign::ZExt: 2901 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2902 break; 2903 case CCValAssign::SExt: 2904 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2905 break; 2906 case CCValAssign::AExt: 2907 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2908 break; 2909 case CCValAssign::FPExt: 2910 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2911 break; 2912 default: 2913 llvm_unreachable("Unknown loc info!"); 2914 } 2915 2916 if (VA.isRegLoc()) { 2917 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2918 } else { 2919 assert(VA.isMemLoc()); 2920 2921 SDValue DstAddr; 2922 MachinePointerInfo DstInfo; 2923 2924 unsigned LocMemOffset = VA.getLocMemOffset(); 2925 int32_t Offset = LocMemOffset; 2926 2927 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2928 MaybeAlign Alignment; 2929 2930 if (IsTailCall) { 2931 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2932 unsigned OpSize = Flags.isByVal() ? 2933 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2934 2935 // FIXME: We can have better than the minimum byval required alignment. 2936 Alignment = 2937 Flags.isByVal() 2938 ? Flags.getNonZeroByValAlign() 2939 : commonAlignment(Subtarget->getStackAlignment(), Offset); 2940 2941 Offset = Offset + FPDiff; 2942 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2943 2944 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2945 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2946 2947 // Make sure any stack arguments overlapping with where we're storing 2948 // are loaded before this eventual operation. Otherwise they'll be 2949 // clobbered. 2950 2951 // FIXME: Why is this really necessary? This seems to just result in a 2952 // lot of code to copy the stack and write them back to the same 2953 // locations, which are supposed to be immutable? 2954 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2955 } else { 2956 DstAddr = PtrOff; 2957 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2958 Alignment = 2959 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 2960 } 2961 2962 if (Outs[i].Flags.isByVal()) { 2963 SDValue SizeNode = 2964 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2965 SDValue Cpy = 2966 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 2967 Outs[i].Flags.getNonZeroByValAlign(), 2968 /*isVol = */ false, /*AlwaysInline = */ true, 2969 /*isTailCall = */ false, DstInfo, 2970 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 2971 2972 MemOpChains.push_back(Cpy); 2973 } else { 2974 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 2975 Alignment ? Alignment->value() : 0); 2976 MemOpChains.push_back(Store); 2977 } 2978 } 2979 } 2980 2981 if (!AMDGPUTargetMachine::EnableFixedFunctionABI) { 2982 // Copy special input registers after user input arguments. 2983 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2984 } 2985 2986 if (!MemOpChains.empty()) 2987 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2988 2989 // Build a sequence of copy-to-reg nodes chained together with token chain 2990 // and flag operands which copy the outgoing args into the appropriate regs. 2991 SDValue InFlag; 2992 for (auto &RegToPass : RegsToPass) { 2993 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2994 RegToPass.second, InFlag); 2995 InFlag = Chain.getValue(1); 2996 } 2997 2998 2999 SDValue PhysReturnAddrReg; 3000 if (IsTailCall) { 3001 // Since the return is being combined with the call, we need to pass on the 3002 // return address. 3003 3004 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3005 SDValue ReturnAddrReg = CreateLiveInRegister( 3006 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3007 3008 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3009 MVT::i64); 3010 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3011 InFlag = Chain.getValue(1); 3012 } 3013 3014 // We don't usually want to end the call-sequence here because we would tidy 3015 // the frame up *after* the call, however in the ABI-changing tail-call case 3016 // we've carefully laid out the parameters so that when sp is reset they'll be 3017 // in the correct location. 3018 if (IsTailCall && !IsSibCall) { 3019 Chain = DAG.getCALLSEQ_END(Chain, 3020 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3021 DAG.getTargetConstant(0, DL, MVT::i32), 3022 InFlag, DL); 3023 InFlag = Chain.getValue(1); 3024 } 3025 3026 std::vector<SDValue> Ops; 3027 Ops.push_back(Chain); 3028 Ops.push_back(Callee); 3029 // Add a redundant copy of the callee global which will not be legalized, as 3030 // we need direct access to the callee later. 3031 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3032 const GlobalValue *GV = GSD->getGlobal(); 3033 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3034 } else { 3035 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3036 } 3037 3038 if (IsTailCall) { 3039 // Each tail call may have to adjust the stack by a different amount, so 3040 // this information must travel along with the operation for eventual 3041 // consumption by emitEpilogue. 3042 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3043 3044 Ops.push_back(PhysReturnAddrReg); 3045 } 3046 3047 // Add argument registers to the end of the list so that they are known live 3048 // into the call. 3049 for (auto &RegToPass : RegsToPass) { 3050 Ops.push_back(DAG.getRegister(RegToPass.first, 3051 RegToPass.second.getValueType())); 3052 } 3053 3054 // Add a register mask operand representing the call-preserved registers. 3055 3056 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3057 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3058 assert(Mask && "Missing call preserved mask for calling convention"); 3059 Ops.push_back(DAG.getRegisterMask(Mask)); 3060 3061 if (InFlag.getNode()) 3062 Ops.push_back(InFlag); 3063 3064 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3065 3066 // If we're doing a tall call, use a TC_RETURN here rather than an 3067 // actual call instruction. 3068 if (IsTailCall) { 3069 MFI.setHasTailCall(); 3070 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3071 } 3072 3073 // Returns a chain and a flag for retval copy to use. 3074 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3075 Chain = Call.getValue(0); 3076 InFlag = Call.getValue(1); 3077 3078 uint64_t CalleePopBytes = NumBytes; 3079 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3080 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3081 InFlag, DL); 3082 if (!Ins.empty()) 3083 InFlag = Chain.getValue(1); 3084 3085 // Handle result values, copying them out of physregs into vregs that we 3086 // return. 3087 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3088 InVals, IsThisReturn, 3089 IsThisReturn ? OutVals[0] : SDValue()); 3090 } 3091 3092 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3093 // except for applying the wave size scale to the increment amount. 3094 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3095 SDValue Op, SelectionDAG &DAG) const { 3096 const MachineFunction &MF = DAG.getMachineFunction(); 3097 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3098 3099 SDLoc dl(Op); 3100 EVT VT = Op.getValueType(); 3101 SDValue Tmp1 = Op; 3102 SDValue Tmp2 = Op.getValue(1); 3103 SDValue Tmp3 = Op.getOperand(2); 3104 SDValue Chain = Tmp1.getOperand(0); 3105 3106 Register SPReg = Info->getStackPtrOffsetReg(); 3107 3108 // Chain the dynamic stack allocation so that it doesn't modify the stack 3109 // pointer when other instructions are using the stack. 3110 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3111 3112 SDValue Size = Tmp2.getOperand(1); 3113 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3114 Chain = SP.getValue(1); 3115 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue(); 3116 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3117 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3118 unsigned Opc = 3119 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3120 ISD::ADD : ISD::SUB; 3121 3122 SDValue ScaledSize = DAG.getNode( 3123 ISD::SHL, dl, VT, Size, 3124 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3125 3126 unsigned StackAlign = TFL->getStackAlignment(); 3127 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3128 if (Align > StackAlign) 3129 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3130 DAG.getConstant(-(uint64_t)Align, dl, VT)); 3131 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3132 Tmp2 = DAG.getCALLSEQ_END( 3133 Chain, DAG.getIntPtrConstant(0, dl, true), 3134 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3135 3136 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3137 } 3138 3139 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3140 SelectionDAG &DAG) const { 3141 // We only handle constant sizes here to allow non-entry block, static sized 3142 // allocas. A truly dynamic value is more difficult to support because we 3143 // don't know if the size value is uniform or not. If the size isn't uniform, 3144 // we would need to do a wave reduction to get the maximum size to know how 3145 // much to increment the uniform stack pointer. 3146 SDValue Size = Op.getOperand(1); 3147 if (isa<ConstantSDNode>(Size)) 3148 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3149 3150 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3151 } 3152 3153 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3154 const MachineFunction &MF) const { 3155 Register Reg = StringSwitch<Register>(RegName) 3156 .Case("m0", AMDGPU::M0) 3157 .Case("exec", AMDGPU::EXEC) 3158 .Case("exec_lo", AMDGPU::EXEC_LO) 3159 .Case("exec_hi", AMDGPU::EXEC_HI) 3160 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3161 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3162 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3163 .Default(Register()); 3164 3165 if (Reg == AMDGPU::NoRegister) { 3166 report_fatal_error(Twine("invalid register name \"" 3167 + StringRef(RegName) + "\".")); 3168 3169 } 3170 3171 if (!Subtarget->hasFlatScrRegister() && 3172 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3173 report_fatal_error(Twine("invalid register \"" 3174 + StringRef(RegName) + "\" for subtarget.")); 3175 } 3176 3177 switch (Reg) { 3178 case AMDGPU::M0: 3179 case AMDGPU::EXEC_LO: 3180 case AMDGPU::EXEC_HI: 3181 case AMDGPU::FLAT_SCR_LO: 3182 case AMDGPU::FLAT_SCR_HI: 3183 if (VT.getSizeInBits() == 32) 3184 return Reg; 3185 break; 3186 case AMDGPU::EXEC: 3187 case AMDGPU::FLAT_SCR: 3188 if (VT.getSizeInBits() == 64) 3189 return Reg; 3190 break; 3191 default: 3192 llvm_unreachable("missing register type checking"); 3193 } 3194 3195 report_fatal_error(Twine("invalid type for register \"" 3196 + StringRef(RegName) + "\".")); 3197 } 3198 3199 // If kill is not the last instruction, split the block so kill is always a 3200 // proper terminator. 3201 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3202 MachineBasicBlock *BB) const { 3203 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3204 3205 MachineBasicBlock::iterator SplitPoint(&MI); 3206 ++SplitPoint; 3207 3208 if (SplitPoint == BB->end()) { 3209 // Don't bother with a new block. 3210 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3211 return BB; 3212 } 3213 3214 MachineFunction *MF = BB->getParent(); 3215 MachineBasicBlock *SplitBB 3216 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3217 3218 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3219 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3220 3221 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3222 BB->addSuccessor(SplitBB); 3223 3224 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3225 return SplitBB; 3226 } 3227 3228 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3229 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3230 // be the first instruction in the remainder block. 3231 // 3232 /// \returns { LoopBody, Remainder } 3233 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3234 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3235 MachineFunction *MF = MBB.getParent(); 3236 MachineBasicBlock::iterator I(&MI); 3237 3238 // To insert the loop we need to split the block. Move everything after this 3239 // point to a new block, and insert a new empty block between the two. 3240 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3241 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3242 MachineFunction::iterator MBBI(MBB); 3243 ++MBBI; 3244 3245 MF->insert(MBBI, LoopBB); 3246 MF->insert(MBBI, RemainderBB); 3247 3248 LoopBB->addSuccessor(LoopBB); 3249 LoopBB->addSuccessor(RemainderBB); 3250 3251 // Move the rest of the block into a new block. 3252 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3253 3254 if (InstInLoop) { 3255 auto Next = std::next(I); 3256 3257 // Move instruction to loop body. 3258 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3259 3260 // Move the rest of the block. 3261 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3262 } else { 3263 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3264 } 3265 3266 MBB.addSuccessor(LoopBB); 3267 3268 return std::make_pair(LoopBB, RemainderBB); 3269 } 3270 3271 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3272 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3273 MachineBasicBlock *MBB = MI.getParent(); 3274 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3275 auto I = MI.getIterator(); 3276 auto E = std::next(I); 3277 3278 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3279 .addImm(0); 3280 3281 MIBundleBuilder Bundler(*MBB, I, E); 3282 finalizeBundle(*MBB, Bundler.begin()); 3283 } 3284 3285 MachineBasicBlock * 3286 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3287 MachineBasicBlock *BB) const { 3288 const DebugLoc &DL = MI.getDebugLoc(); 3289 3290 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3291 3292 MachineBasicBlock *LoopBB; 3293 MachineBasicBlock *RemainderBB; 3294 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3295 3296 // Apparently kill flags are only valid if the def is in the same block? 3297 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3298 Src->setIsKill(false); 3299 3300 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3301 3302 MachineBasicBlock::iterator I = LoopBB->end(); 3303 3304 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3305 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3306 3307 // Clear TRAP_STS.MEM_VIOL 3308 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3309 .addImm(0) 3310 .addImm(EncodedReg); 3311 3312 bundleInstWithWaitcnt(MI); 3313 3314 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3315 3316 // Load and check TRAP_STS.MEM_VIOL 3317 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3318 .addImm(EncodedReg); 3319 3320 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3321 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3322 .addReg(Reg, RegState::Kill) 3323 .addImm(0); 3324 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3325 .addMBB(LoopBB); 3326 3327 return RemainderBB; 3328 } 3329 3330 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3331 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3332 // will only do one iteration. In the worst case, this will loop 64 times. 3333 // 3334 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3335 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3336 const SIInstrInfo *TII, 3337 MachineRegisterInfo &MRI, 3338 MachineBasicBlock &OrigBB, 3339 MachineBasicBlock &LoopBB, 3340 const DebugLoc &DL, 3341 const MachineOperand &IdxReg, 3342 unsigned InitReg, 3343 unsigned ResultReg, 3344 unsigned PhiReg, 3345 unsigned InitSaveExecReg, 3346 int Offset, 3347 bool UseGPRIdxMode, 3348 bool IsIndirectSrc) { 3349 MachineFunction *MF = OrigBB.getParent(); 3350 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3351 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3352 MachineBasicBlock::iterator I = LoopBB.begin(); 3353 3354 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3355 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3356 Register NewExec = MRI.createVirtualRegister(BoolRC); 3357 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3358 Register CondReg = MRI.createVirtualRegister(BoolRC); 3359 3360 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3361 .addReg(InitReg) 3362 .addMBB(&OrigBB) 3363 .addReg(ResultReg) 3364 .addMBB(&LoopBB); 3365 3366 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3367 .addReg(InitSaveExecReg) 3368 .addMBB(&OrigBB) 3369 .addReg(NewExec) 3370 .addMBB(&LoopBB); 3371 3372 // Read the next variant <- also loop target. 3373 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3374 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3375 3376 // Compare the just read M0 value to all possible Idx values. 3377 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3378 .addReg(CurrentIdxReg) 3379 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3380 3381 // Update EXEC, save the original EXEC value to VCC. 3382 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3383 : AMDGPU::S_AND_SAVEEXEC_B64), 3384 NewExec) 3385 .addReg(CondReg, RegState::Kill); 3386 3387 MRI.setSimpleHint(NewExec, CondReg); 3388 3389 if (UseGPRIdxMode) { 3390 unsigned IdxReg; 3391 if (Offset == 0) { 3392 IdxReg = CurrentIdxReg; 3393 } else { 3394 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3395 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3396 .addReg(CurrentIdxReg, RegState::Kill) 3397 .addImm(Offset); 3398 } 3399 unsigned IdxMode = IsIndirectSrc ? 3400 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3401 MachineInstr *SetOn = 3402 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3403 .addReg(IdxReg, RegState::Kill) 3404 .addImm(IdxMode); 3405 SetOn->getOperand(3).setIsUndef(); 3406 } else { 3407 // Move index from VCC into M0 3408 if (Offset == 0) { 3409 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3410 .addReg(CurrentIdxReg, RegState::Kill); 3411 } else { 3412 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3413 .addReg(CurrentIdxReg, RegState::Kill) 3414 .addImm(Offset); 3415 } 3416 } 3417 3418 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3419 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3420 MachineInstr *InsertPt = 3421 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3422 : AMDGPU::S_XOR_B64_term), Exec) 3423 .addReg(Exec) 3424 .addReg(NewExec); 3425 3426 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3427 // s_cbranch_scc0? 3428 3429 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3430 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3431 .addMBB(&LoopBB); 3432 3433 return InsertPt->getIterator(); 3434 } 3435 3436 // This has slightly sub-optimal regalloc when the source vector is killed by 3437 // the read. The register allocator does not understand that the kill is 3438 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3439 // subregister from it, using 1 more VGPR than necessary. This was saved when 3440 // this was expanded after register allocation. 3441 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3442 MachineBasicBlock &MBB, 3443 MachineInstr &MI, 3444 unsigned InitResultReg, 3445 unsigned PhiReg, 3446 int Offset, 3447 bool UseGPRIdxMode, 3448 bool IsIndirectSrc) { 3449 MachineFunction *MF = MBB.getParent(); 3450 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3451 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3452 MachineRegisterInfo &MRI = MF->getRegInfo(); 3453 const DebugLoc &DL = MI.getDebugLoc(); 3454 MachineBasicBlock::iterator I(&MI); 3455 3456 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3457 Register DstReg = MI.getOperand(0).getReg(); 3458 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3459 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3460 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3461 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3462 3463 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3464 3465 // Save the EXEC mask 3466 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3467 .addReg(Exec); 3468 3469 MachineBasicBlock *LoopBB; 3470 MachineBasicBlock *RemainderBB; 3471 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3472 3473 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3474 3475 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3476 InitResultReg, DstReg, PhiReg, TmpExec, 3477 Offset, UseGPRIdxMode, IsIndirectSrc); 3478 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3479 MachineFunction::iterator MBBI(LoopBB); 3480 ++MBBI; 3481 MF->insert(MBBI, LandingPad); 3482 LoopBB->removeSuccessor(RemainderBB); 3483 LandingPad->addSuccessor(RemainderBB); 3484 LoopBB->addSuccessor(LandingPad); 3485 MachineBasicBlock::iterator First = LandingPad->begin(); 3486 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3487 .addReg(SaveExec); 3488 3489 return InsPt; 3490 } 3491 3492 // Returns subreg index, offset 3493 static std::pair<unsigned, int> 3494 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3495 const TargetRegisterClass *SuperRC, 3496 unsigned VecReg, 3497 int Offset) { 3498 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3499 3500 // Skip out of bounds offsets, or else we would end up using an undefined 3501 // register. 3502 if (Offset >= NumElts || Offset < 0) 3503 return std::make_pair(AMDGPU::sub0, Offset); 3504 3505 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3506 } 3507 3508 // Return true if the index is an SGPR and was set. 3509 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3510 MachineRegisterInfo &MRI, 3511 MachineInstr &MI, 3512 int Offset, 3513 bool UseGPRIdxMode, 3514 bool IsIndirectSrc) { 3515 MachineBasicBlock *MBB = MI.getParent(); 3516 const DebugLoc &DL = MI.getDebugLoc(); 3517 MachineBasicBlock::iterator I(&MI); 3518 3519 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3520 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3521 3522 assert(Idx->getReg() != AMDGPU::NoRegister); 3523 3524 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3525 return false; 3526 3527 if (UseGPRIdxMode) { 3528 unsigned IdxMode = IsIndirectSrc ? 3529 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3530 if (Offset == 0) { 3531 MachineInstr *SetOn = 3532 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3533 .add(*Idx) 3534 .addImm(IdxMode); 3535 3536 SetOn->getOperand(3).setIsUndef(); 3537 } else { 3538 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3539 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3540 .add(*Idx) 3541 .addImm(Offset); 3542 MachineInstr *SetOn = 3543 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3544 .addReg(Tmp, RegState::Kill) 3545 .addImm(IdxMode); 3546 3547 SetOn->getOperand(3).setIsUndef(); 3548 } 3549 3550 return true; 3551 } 3552 3553 if (Offset == 0) { 3554 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3555 .add(*Idx); 3556 } else { 3557 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3558 .add(*Idx) 3559 .addImm(Offset); 3560 } 3561 3562 return true; 3563 } 3564 3565 // Control flow needs to be inserted if indexing with a VGPR. 3566 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3567 MachineBasicBlock &MBB, 3568 const GCNSubtarget &ST) { 3569 const SIInstrInfo *TII = ST.getInstrInfo(); 3570 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3571 MachineFunction *MF = MBB.getParent(); 3572 MachineRegisterInfo &MRI = MF->getRegInfo(); 3573 3574 Register Dst = MI.getOperand(0).getReg(); 3575 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3576 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3577 3578 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3579 3580 unsigned SubReg; 3581 std::tie(SubReg, Offset) 3582 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3583 3584 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3585 3586 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3587 MachineBasicBlock::iterator I(&MI); 3588 const DebugLoc &DL = MI.getDebugLoc(); 3589 3590 if (UseGPRIdxMode) { 3591 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3592 // to avoid interfering with other uses, so probably requires a new 3593 // optimization pass. 3594 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3595 .addReg(SrcReg, RegState::Undef, SubReg) 3596 .addReg(SrcReg, RegState::Implicit) 3597 .addReg(AMDGPU::M0, RegState::Implicit); 3598 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3599 } else { 3600 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3601 .addReg(SrcReg, RegState::Undef, SubReg) 3602 .addReg(SrcReg, RegState::Implicit); 3603 } 3604 3605 MI.eraseFromParent(); 3606 3607 return &MBB; 3608 } 3609 3610 const DebugLoc &DL = MI.getDebugLoc(); 3611 MachineBasicBlock::iterator I(&MI); 3612 3613 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3614 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3615 3616 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3617 3618 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3619 Offset, UseGPRIdxMode, true); 3620 MachineBasicBlock *LoopBB = InsPt->getParent(); 3621 3622 if (UseGPRIdxMode) { 3623 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3624 .addReg(SrcReg, RegState::Undef, SubReg) 3625 .addReg(SrcReg, RegState::Implicit) 3626 .addReg(AMDGPU::M0, RegState::Implicit); 3627 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3628 } else { 3629 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3630 .addReg(SrcReg, RegState::Undef, SubReg) 3631 .addReg(SrcReg, RegState::Implicit); 3632 } 3633 3634 MI.eraseFromParent(); 3635 3636 return LoopBB; 3637 } 3638 3639 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3640 MachineBasicBlock &MBB, 3641 const GCNSubtarget &ST) { 3642 const SIInstrInfo *TII = ST.getInstrInfo(); 3643 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3644 MachineFunction *MF = MBB.getParent(); 3645 MachineRegisterInfo &MRI = MF->getRegInfo(); 3646 3647 Register Dst = MI.getOperand(0).getReg(); 3648 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3649 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3650 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3651 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3652 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3653 3654 // This can be an immediate, but will be folded later. 3655 assert(Val->getReg()); 3656 3657 unsigned SubReg; 3658 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3659 SrcVec->getReg(), 3660 Offset); 3661 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3662 3663 if (Idx->getReg() == AMDGPU::NoRegister) { 3664 MachineBasicBlock::iterator I(&MI); 3665 const DebugLoc &DL = MI.getDebugLoc(); 3666 3667 assert(Offset == 0); 3668 3669 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3670 .add(*SrcVec) 3671 .add(*Val) 3672 .addImm(SubReg); 3673 3674 MI.eraseFromParent(); 3675 return &MBB; 3676 } 3677 3678 const MCInstrDesc &MovRelDesc 3679 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3680 3681 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3682 MachineBasicBlock::iterator I(&MI); 3683 const DebugLoc &DL = MI.getDebugLoc(); 3684 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3685 .addReg(SrcVec->getReg()) 3686 .add(*Val) 3687 .addImm(SubReg); 3688 if (UseGPRIdxMode) 3689 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3690 3691 MI.eraseFromParent(); 3692 return &MBB; 3693 } 3694 3695 if (Val->isReg()) 3696 MRI.clearKillFlags(Val->getReg()); 3697 3698 const DebugLoc &DL = MI.getDebugLoc(); 3699 3700 Register PhiReg = MRI.createVirtualRegister(VecRC); 3701 3702 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3703 Offset, UseGPRIdxMode, false); 3704 MachineBasicBlock *LoopBB = InsPt->getParent(); 3705 3706 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3707 .addReg(PhiReg) 3708 .add(*Val) 3709 .addImm(AMDGPU::sub0); 3710 if (UseGPRIdxMode) 3711 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3712 3713 MI.eraseFromParent(); 3714 return LoopBB; 3715 } 3716 3717 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3718 MachineInstr &MI, MachineBasicBlock *BB) const { 3719 3720 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3721 MachineFunction *MF = BB->getParent(); 3722 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3723 3724 if (TII->isMIMG(MI)) { 3725 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 3726 report_fatal_error("missing mem operand from MIMG instruction"); 3727 } 3728 // Add a memoperand for mimg instructions so that they aren't assumed to 3729 // be ordered memory instuctions. 3730 3731 return BB; 3732 } 3733 3734 switch (MI.getOpcode()) { 3735 case AMDGPU::S_UADDO_PSEUDO: 3736 case AMDGPU::S_USUBO_PSEUDO: { 3737 const DebugLoc &DL = MI.getDebugLoc(); 3738 MachineOperand &Dest0 = MI.getOperand(0); 3739 MachineOperand &Dest1 = MI.getOperand(1); 3740 MachineOperand &Src0 = MI.getOperand(2); 3741 MachineOperand &Src1 = MI.getOperand(3); 3742 3743 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3744 ? AMDGPU::S_ADD_I32 3745 : AMDGPU::S_SUB_I32; 3746 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3747 3748 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3749 .addImm(1) 3750 .addImm(0); 3751 3752 MI.eraseFromParent(); 3753 return BB; 3754 } 3755 case AMDGPU::S_ADD_U64_PSEUDO: 3756 case AMDGPU::S_SUB_U64_PSEUDO: { 3757 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3758 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3759 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3760 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3761 const DebugLoc &DL = MI.getDebugLoc(); 3762 3763 MachineOperand &Dest = MI.getOperand(0); 3764 MachineOperand &Src0 = MI.getOperand(1); 3765 MachineOperand &Src1 = MI.getOperand(2); 3766 3767 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3768 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3769 3770 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3771 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3772 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3773 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3774 3775 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3776 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3777 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3778 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3779 3780 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3781 3782 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3783 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3784 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3785 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3786 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3787 .addReg(DestSub0) 3788 .addImm(AMDGPU::sub0) 3789 .addReg(DestSub1) 3790 .addImm(AMDGPU::sub1); 3791 MI.eraseFromParent(); 3792 return BB; 3793 } 3794 case AMDGPU::V_ADD_U64_PSEUDO: 3795 case AMDGPU::V_SUB_U64_PSEUDO: { 3796 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3797 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3798 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3799 const DebugLoc &DL = MI.getDebugLoc(); 3800 3801 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3802 3803 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3804 3805 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3806 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3807 3808 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3809 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3810 3811 MachineOperand &Dest = MI.getOperand(0); 3812 MachineOperand &Src0 = MI.getOperand(1); 3813 MachineOperand &Src1 = MI.getOperand(2); 3814 3815 const TargetRegisterClass *Src0RC = Src0.isReg() 3816 ? MRI.getRegClass(Src0.getReg()) 3817 : &AMDGPU::VReg_64RegClass; 3818 const TargetRegisterClass *Src1RC = Src1.isReg() 3819 ? MRI.getRegClass(Src1.getReg()) 3820 : &AMDGPU::VReg_64RegClass; 3821 3822 const TargetRegisterClass *Src0SubRC = 3823 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3824 const TargetRegisterClass *Src1SubRC = 3825 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3826 3827 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3828 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3829 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3830 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3831 3832 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3833 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3834 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3835 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3836 3837 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64; 3838 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3839 .addReg(CarryReg, RegState::Define) 3840 .add(SrcReg0Sub0) 3841 .add(SrcReg1Sub0) 3842 .addImm(0); // clamp bit 3843 3844 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3845 MachineInstr *HiHalf = 3846 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3847 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3848 .add(SrcReg0Sub1) 3849 .add(SrcReg1Sub1) 3850 .addReg(CarryReg, RegState::Kill) 3851 .addImm(0); // clamp bit 3852 3853 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3854 .addReg(DestSub0) 3855 .addImm(AMDGPU::sub0) 3856 .addReg(DestSub1) 3857 .addImm(AMDGPU::sub1); 3858 TII->legalizeOperands(*LoHalf); 3859 TII->legalizeOperands(*HiHalf); 3860 MI.eraseFromParent(); 3861 return BB; 3862 } 3863 case AMDGPU::S_ADD_CO_PSEUDO: 3864 case AMDGPU::S_SUB_CO_PSEUDO: { 3865 // This pseudo has a chance to be selected 3866 // only from uniform add/subcarry node. All the VGPR operands 3867 // therefore assumed to be splat vectors. 3868 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3869 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3870 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3871 MachineBasicBlock::iterator MII = MI; 3872 const DebugLoc &DL = MI.getDebugLoc(); 3873 MachineOperand &Dest = MI.getOperand(0); 3874 MachineOperand &Src0 = MI.getOperand(2); 3875 MachineOperand &Src1 = MI.getOperand(3); 3876 MachineOperand &Src2 = MI.getOperand(4); 3877 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 3878 ? AMDGPU::S_ADDC_U32 3879 : AMDGPU::S_SUBB_U32; 3880 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 3881 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3882 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 3883 .addReg(Src0.getReg()); 3884 Src0.setReg(RegOp0); 3885 } 3886 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 3887 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3888 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 3889 .addReg(Src1.getReg()); 3890 Src1.setReg(RegOp1); 3891 } 3892 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3893 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 3894 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 3895 .addReg(Src2.getReg()); 3896 Src2.setReg(RegOp2); 3897 } 3898 3899 if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) { 3900 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 3901 .addReg(Src2.getReg()) 3902 .addImm(0); 3903 } else { 3904 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 3905 .addReg(Src2.getReg()) 3906 .addImm(0); 3907 } 3908 3909 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 3910 MI.eraseFromParent(); 3911 return BB; 3912 } 3913 case AMDGPU::SI_INIT_M0: { 3914 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3915 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3916 .add(MI.getOperand(0)); 3917 MI.eraseFromParent(); 3918 return BB; 3919 } 3920 case AMDGPU::SI_INIT_EXEC: 3921 // This should be before all vector instructions. 3922 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3923 AMDGPU::EXEC) 3924 .addImm(MI.getOperand(0).getImm()); 3925 MI.eraseFromParent(); 3926 return BB; 3927 3928 case AMDGPU::SI_INIT_EXEC_LO: 3929 // This should be before all vector instructions. 3930 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3931 AMDGPU::EXEC_LO) 3932 .addImm(MI.getOperand(0).getImm()); 3933 MI.eraseFromParent(); 3934 return BB; 3935 3936 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3937 // Extract the thread count from an SGPR input and set EXEC accordingly. 3938 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3939 // 3940 // S_BFE_U32 count, input, {shift, 7} 3941 // S_BFM_B64 exec, count, 0 3942 // S_CMP_EQ_U32 count, 64 3943 // S_CMOV_B64 exec, -1 3944 MachineInstr *FirstMI = &*BB->begin(); 3945 MachineRegisterInfo &MRI = MF->getRegInfo(); 3946 Register InputReg = MI.getOperand(0).getReg(); 3947 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3948 bool Found = false; 3949 3950 // Move the COPY of the input reg to the beginning, so that we can use it. 3951 for (auto I = BB->begin(); I != &MI; I++) { 3952 if (I->getOpcode() != TargetOpcode::COPY || 3953 I->getOperand(0).getReg() != InputReg) 3954 continue; 3955 3956 if (I == FirstMI) { 3957 FirstMI = &*++BB->begin(); 3958 } else { 3959 I->removeFromParent(); 3960 BB->insert(FirstMI, &*I); 3961 } 3962 Found = true; 3963 break; 3964 } 3965 assert(Found); 3966 (void)Found; 3967 3968 // This should be before all vector instructions. 3969 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3970 bool isWave32 = getSubtarget()->isWave32(); 3971 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3972 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3973 .addReg(InputReg) 3974 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3975 BuildMI(*BB, FirstMI, DebugLoc(), 3976 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3977 Exec) 3978 .addReg(CountReg) 3979 .addImm(0); 3980 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3981 .addReg(CountReg, RegState::Kill) 3982 .addImm(getSubtarget()->getWavefrontSize()); 3983 BuildMI(*BB, FirstMI, DebugLoc(), 3984 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3985 Exec) 3986 .addImm(-1); 3987 MI.eraseFromParent(); 3988 return BB; 3989 } 3990 3991 case AMDGPU::GET_GROUPSTATICSIZE: { 3992 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 3993 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 3994 DebugLoc DL = MI.getDebugLoc(); 3995 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3996 .add(MI.getOperand(0)) 3997 .addImm(MFI->getLDSSize()); 3998 MI.eraseFromParent(); 3999 return BB; 4000 } 4001 case AMDGPU::SI_INDIRECT_SRC_V1: 4002 case AMDGPU::SI_INDIRECT_SRC_V2: 4003 case AMDGPU::SI_INDIRECT_SRC_V4: 4004 case AMDGPU::SI_INDIRECT_SRC_V8: 4005 case AMDGPU::SI_INDIRECT_SRC_V16: 4006 case AMDGPU::SI_INDIRECT_SRC_V32: 4007 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4008 case AMDGPU::SI_INDIRECT_DST_V1: 4009 case AMDGPU::SI_INDIRECT_DST_V2: 4010 case AMDGPU::SI_INDIRECT_DST_V4: 4011 case AMDGPU::SI_INDIRECT_DST_V8: 4012 case AMDGPU::SI_INDIRECT_DST_V16: 4013 case AMDGPU::SI_INDIRECT_DST_V32: 4014 return emitIndirectDst(MI, *BB, *getSubtarget()); 4015 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4016 case AMDGPU::SI_KILL_I1_PSEUDO: 4017 return splitKillBlock(MI, BB); 4018 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4019 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4020 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4021 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4022 4023 Register Dst = MI.getOperand(0).getReg(); 4024 Register Src0 = MI.getOperand(1).getReg(); 4025 Register Src1 = MI.getOperand(2).getReg(); 4026 const DebugLoc &DL = MI.getDebugLoc(); 4027 Register SrcCond = MI.getOperand(3).getReg(); 4028 4029 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4030 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4031 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4032 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4033 4034 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4035 .addReg(SrcCond); 4036 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4037 .addImm(0) 4038 .addReg(Src0, 0, AMDGPU::sub0) 4039 .addImm(0) 4040 .addReg(Src1, 0, AMDGPU::sub0) 4041 .addReg(SrcCondCopy); 4042 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4043 .addImm(0) 4044 .addReg(Src0, 0, AMDGPU::sub1) 4045 .addImm(0) 4046 .addReg(Src1, 0, AMDGPU::sub1) 4047 .addReg(SrcCondCopy); 4048 4049 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4050 .addReg(DstLo) 4051 .addImm(AMDGPU::sub0) 4052 .addReg(DstHi) 4053 .addImm(AMDGPU::sub1); 4054 MI.eraseFromParent(); 4055 return BB; 4056 } 4057 case AMDGPU::SI_BR_UNDEF: { 4058 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4059 const DebugLoc &DL = MI.getDebugLoc(); 4060 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4061 .add(MI.getOperand(0)); 4062 Br->getOperand(1).setIsUndef(true); // read undef SCC 4063 MI.eraseFromParent(); 4064 return BB; 4065 } 4066 case AMDGPU::ADJCALLSTACKUP: 4067 case AMDGPU::ADJCALLSTACKDOWN: { 4068 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4069 MachineInstrBuilder MIB(*MF, &MI); 4070 4071 // Add an implicit use of the frame offset reg to prevent the restore copy 4072 // inserted after the call from being reorderd after stack operations in the 4073 // the caller's frame. 4074 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4075 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 4076 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 4077 return BB; 4078 } 4079 case AMDGPU::SI_CALL_ISEL: { 4080 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4081 const DebugLoc &DL = MI.getDebugLoc(); 4082 4083 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4084 4085 MachineInstrBuilder MIB; 4086 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4087 4088 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4089 MIB.add(MI.getOperand(I)); 4090 4091 MIB.cloneMemRefs(MI); 4092 MI.eraseFromParent(); 4093 return BB; 4094 } 4095 case AMDGPU::V_ADD_I32_e32: 4096 case AMDGPU::V_SUB_I32_e32: 4097 case AMDGPU::V_SUBREV_I32_e32: { 4098 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4099 const DebugLoc &DL = MI.getDebugLoc(); 4100 unsigned Opc = MI.getOpcode(); 4101 4102 bool NeedClampOperand = false; 4103 if (TII->pseudoToMCOpcode(Opc) == -1) { 4104 Opc = AMDGPU::getVOPe64(Opc); 4105 NeedClampOperand = true; 4106 } 4107 4108 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4109 if (TII->isVOP3(*I)) { 4110 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4111 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4112 I.addReg(TRI->getVCC(), RegState::Define); 4113 } 4114 I.add(MI.getOperand(1)) 4115 .add(MI.getOperand(2)); 4116 if (NeedClampOperand) 4117 I.addImm(0); // clamp bit for e64 encoding 4118 4119 TII->legalizeOperands(*I); 4120 4121 MI.eraseFromParent(); 4122 return BB; 4123 } 4124 case AMDGPU::DS_GWS_INIT: 4125 case AMDGPU::DS_GWS_SEMA_V: 4126 case AMDGPU::DS_GWS_SEMA_BR: 4127 case AMDGPU::DS_GWS_SEMA_P: 4128 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4129 case AMDGPU::DS_GWS_BARRIER: 4130 // A s_waitcnt 0 is required to be the instruction immediately following. 4131 if (getSubtarget()->hasGWSAutoReplay()) { 4132 bundleInstWithWaitcnt(MI); 4133 return BB; 4134 } 4135 4136 return emitGWSMemViolTestLoop(MI, BB); 4137 default: 4138 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4139 } 4140 } 4141 4142 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4143 return isTypeLegal(VT.getScalarType()); 4144 } 4145 4146 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4147 // This currently forces unfolding various combinations of fsub into fma with 4148 // free fneg'd operands. As long as we have fast FMA (controlled by 4149 // isFMAFasterThanFMulAndFAdd), we should perform these. 4150 4151 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4152 // most of these combines appear to be cycle neutral but save on instruction 4153 // count / code size. 4154 return true; 4155 } 4156 4157 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4158 EVT VT) const { 4159 if (!VT.isVector()) { 4160 return MVT::i1; 4161 } 4162 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4163 } 4164 4165 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4166 // TODO: Should i16 be used always if legal? For now it would force VALU 4167 // shifts. 4168 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4169 } 4170 4171 // Answering this is somewhat tricky and depends on the specific device which 4172 // have different rates for fma or all f64 operations. 4173 // 4174 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4175 // regardless of which device (although the number of cycles differs between 4176 // devices), so it is always profitable for f64. 4177 // 4178 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4179 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4180 // which we can always do even without fused FP ops since it returns the same 4181 // result as the separate operations and since it is always full 4182 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4183 // however does not support denormals, so we do report fma as faster if we have 4184 // a fast fma device and require denormals. 4185 // 4186 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4187 EVT VT) const { 4188 VT = VT.getScalarType(); 4189 4190 switch (VT.getSimpleVT().SimpleTy) { 4191 case MVT::f32: { 4192 // This is as fast on some subtargets. However, we always have full rate f32 4193 // mad available which returns the same result as the separate operations 4194 // which we should prefer over fma. We can't use this if we want to support 4195 // denormals, so only report this in these cases. 4196 if (hasFP32Denormals(MF)) 4197 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4198 4199 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4200 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4201 } 4202 case MVT::f64: 4203 return true; 4204 case MVT::f16: 4205 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4206 default: 4207 break; 4208 } 4209 4210 return false; 4211 } 4212 4213 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4214 const SDNode *N) const { 4215 // TODO: Check future ftz flag 4216 // v_mad_f32/v_mac_f32 do not support denormals. 4217 EVT VT = N->getValueType(0); 4218 if (VT == MVT::f32) 4219 return !hasFP32Denormals(DAG.getMachineFunction()); 4220 if (VT == MVT::f16) { 4221 return Subtarget->hasMadF16() && 4222 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4223 } 4224 4225 return false; 4226 } 4227 4228 //===----------------------------------------------------------------------===// 4229 // Custom DAG Lowering Operations 4230 //===----------------------------------------------------------------------===// 4231 4232 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4233 // wider vector type is legal. 4234 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4235 SelectionDAG &DAG) const { 4236 unsigned Opc = Op.getOpcode(); 4237 EVT VT = Op.getValueType(); 4238 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4239 4240 SDValue Lo, Hi; 4241 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4242 4243 SDLoc SL(Op); 4244 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4245 Op->getFlags()); 4246 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4247 Op->getFlags()); 4248 4249 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4250 } 4251 4252 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4253 // wider vector type is legal. 4254 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4255 SelectionDAG &DAG) const { 4256 unsigned Opc = Op.getOpcode(); 4257 EVT VT = Op.getValueType(); 4258 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4259 4260 SDValue Lo0, Hi0; 4261 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4262 SDValue Lo1, Hi1; 4263 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4264 4265 SDLoc SL(Op); 4266 4267 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4268 Op->getFlags()); 4269 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4270 Op->getFlags()); 4271 4272 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4273 } 4274 4275 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4276 SelectionDAG &DAG) const { 4277 unsigned Opc = Op.getOpcode(); 4278 EVT VT = Op.getValueType(); 4279 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4280 4281 SDValue Lo0, Hi0; 4282 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4283 SDValue Lo1, Hi1; 4284 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4285 SDValue Lo2, Hi2; 4286 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4287 4288 SDLoc SL(Op); 4289 4290 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4291 Op->getFlags()); 4292 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4293 Op->getFlags()); 4294 4295 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4296 } 4297 4298 4299 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4300 switch (Op.getOpcode()) { 4301 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4302 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4303 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4304 case ISD::LOAD: { 4305 SDValue Result = LowerLOAD(Op, DAG); 4306 assert((!Result.getNode() || 4307 Result.getNode()->getNumValues() == 2) && 4308 "Load should return a value and a chain"); 4309 return Result; 4310 } 4311 4312 case ISD::FSIN: 4313 case ISD::FCOS: 4314 return LowerTrig(Op, DAG); 4315 case ISD::SELECT: return LowerSELECT(Op, DAG); 4316 case ISD::FDIV: return LowerFDIV(Op, DAG); 4317 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4318 case ISD::STORE: return LowerSTORE(Op, DAG); 4319 case ISD::GlobalAddress: { 4320 MachineFunction &MF = DAG.getMachineFunction(); 4321 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4322 return LowerGlobalAddress(MFI, Op, DAG); 4323 } 4324 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4325 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4326 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4327 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4328 case ISD::INSERT_SUBVECTOR: 4329 return lowerINSERT_SUBVECTOR(Op, DAG); 4330 case ISD::INSERT_VECTOR_ELT: 4331 return lowerINSERT_VECTOR_ELT(Op, DAG); 4332 case ISD::EXTRACT_VECTOR_ELT: 4333 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4334 case ISD::VECTOR_SHUFFLE: 4335 return lowerVECTOR_SHUFFLE(Op, DAG); 4336 case ISD::BUILD_VECTOR: 4337 return lowerBUILD_VECTOR(Op, DAG); 4338 case ISD::FP_ROUND: 4339 return lowerFP_ROUND(Op, DAG); 4340 case ISD::TRAP: 4341 return lowerTRAP(Op, DAG); 4342 case ISD::DEBUGTRAP: 4343 return lowerDEBUGTRAP(Op, DAG); 4344 case ISD::FABS: 4345 case ISD::FNEG: 4346 case ISD::FCANONICALIZE: 4347 case ISD::BSWAP: 4348 return splitUnaryVectorOp(Op, DAG); 4349 case ISD::FMINNUM: 4350 case ISD::FMAXNUM: 4351 return lowerFMINNUM_FMAXNUM(Op, DAG); 4352 case ISD::FMA: 4353 return splitTernaryVectorOp(Op, DAG); 4354 case ISD::SHL: 4355 case ISD::SRA: 4356 case ISD::SRL: 4357 case ISD::ADD: 4358 case ISD::SUB: 4359 case ISD::MUL: 4360 case ISD::SMIN: 4361 case ISD::SMAX: 4362 case ISD::UMIN: 4363 case ISD::UMAX: 4364 case ISD::FADD: 4365 case ISD::FMUL: 4366 case ISD::FMINNUM_IEEE: 4367 case ISD::FMAXNUM_IEEE: 4368 return splitBinaryVectorOp(Op, DAG); 4369 case ISD::DYNAMIC_STACKALLOC: 4370 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4371 } 4372 return SDValue(); 4373 } 4374 4375 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4376 const SDLoc &DL, 4377 SelectionDAG &DAG, bool Unpacked) { 4378 if (!LoadVT.isVector()) 4379 return Result; 4380 4381 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4382 // Truncate to v2i16/v4i16. 4383 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4384 4385 // Workaround legalizer not scalarizing truncate after vector op 4386 // legalization byt not creating intermediate vector trunc. 4387 SmallVector<SDValue, 4> Elts; 4388 DAG.ExtractVectorElements(Result, Elts); 4389 for (SDValue &Elt : Elts) 4390 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4391 4392 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4393 4394 // Bitcast to original type (v2f16/v4f16). 4395 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4396 } 4397 4398 // Cast back to the original packed type. 4399 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4400 } 4401 4402 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4403 MemSDNode *M, 4404 SelectionDAG &DAG, 4405 ArrayRef<SDValue> Ops, 4406 bool IsIntrinsic) const { 4407 SDLoc DL(M); 4408 4409 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4410 EVT LoadVT = M->getValueType(0); 4411 4412 EVT EquivLoadVT = LoadVT; 4413 if (Unpacked && LoadVT.isVector()) { 4414 EquivLoadVT = LoadVT.isVector() ? 4415 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4416 LoadVT.getVectorNumElements()) : LoadVT; 4417 } 4418 4419 // Change from v4f16/v2f16 to EquivLoadVT. 4420 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4421 4422 SDValue Load 4423 = DAG.getMemIntrinsicNode( 4424 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4425 VTList, Ops, M->getMemoryVT(), 4426 M->getMemOperand()); 4427 if (!Unpacked) // Just adjusted the opcode. 4428 return Load; 4429 4430 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4431 4432 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4433 } 4434 4435 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4436 SelectionDAG &DAG, 4437 ArrayRef<SDValue> Ops) const { 4438 SDLoc DL(M); 4439 EVT LoadVT = M->getValueType(0); 4440 EVT EltType = LoadVT.getScalarType(); 4441 EVT IntVT = LoadVT.changeTypeToInteger(); 4442 4443 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4444 4445 unsigned Opc = 4446 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4447 4448 if (IsD16) { 4449 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4450 } 4451 4452 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4453 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4454 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4455 4456 if (isTypeLegal(LoadVT)) { 4457 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4458 M->getMemOperand(), DAG); 4459 } 4460 4461 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4462 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4463 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4464 M->getMemOperand(), DAG); 4465 return DAG.getMergeValues( 4466 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4467 DL); 4468 } 4469 4470 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4471 SDNode *N, SelectionDAG &DAG) { 4472 EVT VT = N->getValueType(0); 4473 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4474 int CondCode = CD->getSExtValue(); 4475 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4476 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4477 return DAG.getUNDEF(VT); 4478 4479 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4480 4481 SDValue LHS = N->getOperand(1); 4482 SDValue RHS = N->getOperand(2); 4483 4484 SDLoc DL(N); 4485 4486 EVT CmpVT = LHS.getValueType(); 4487 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4488 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4489 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4490 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4491 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4492 } 4493 4494 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4495 4496 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4497 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4498 4499 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4500 DAG.getCondCode(CCOpcode)); 4501 if (VT.bitsEq(CCVT)) 4502 return SetCC; 4503 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4504 } 4505 4506 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4507 SDNode *N, SelectionDAG &DAG) { 4508 EVT VT = N->getValueType(0); 4509 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4510 4511 int CondCode = CD->getSExtValue(); 4512 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4513 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4514 return DAG.getUNDEF(VT); 4515 } 4516 4517 SDValue Src0 = N->getOperand(1); 4518 SDValue Src1 = N->getOperand(2); 4519 EVT CmpVT = Src0.getValueType(); 4520 SDLoc SL(N); 4521 4522 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4523 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4524 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4525 } 4526 4527 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4528 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4529 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4530 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4531 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4532 Src1, DAG.getCondCode(CCOpcode)); 4533 if (VT.bitsEq(CCVT)) 4534 return SetCC; 4535 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4536 } 4537 4538 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4539 SelectionDAG &DAG) { 4540 EVT VT = N->getValueType(0); 4541 SDValue Src = N->getOperand(1); 4542 SDLoc SL(N); 4543 4544 if (Src.getOpcode() == ISD::SETCC) { 4545 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4546 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4547 Src.getOperand(1), Src.getOperand(2)); 4548 } 4549 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4550 // (ballot 0) -> 0 4551 if (Arg->isNullValue()) 4552 return DAG.getConstant(0, SL, VT); 4553 4554 // (ballot 1) -> EXEC/EXEC_LO 4555 if (Arg->isOne()) { 4556 Register Exec; 4557 if (VT.getScalarSizeInBits() == 32) 4558 Exec = AMDGPU::EXEC_LO; 4559 else if (VT.getScalarSizeInBits() == 64) 4560 Exec = AMDGPU::EXEC; 4561 else 4562 return SDValue(); 4563 4564 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4565 } 4566 } 4567 4568 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4569 // ISD::SETNE) 4570 return DAG.getNode( 4571 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4572 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4573 } 4574 4575 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4576 SmallVectorImpl<SDValue> &Results, 4577 SelectionDAG &DAG) const { 4578 switch (N->getOpcode()) { 4579 case ISD::INSERT_VECTOR_ELT: { 4580 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4581 Results.push_back(Res); 4582 return; 4583 } 4584 case ISD::EXTRACT_VECTOR_ELT: { 4585 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4586 Results.push_back(Res); 4587 return; 4588 } 4589 case ISD::INTRINSIC_WO_CHAIN: { 4590 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4591 switch (IID) { 4592 case Intrinsic::amdgcn_cvt_pkrtz: { 4593 SDValue Src0 = N->getOperand(1); 4594 SDValue Src1 = N->getOperand(2); 4595 SDLoc SL(N); 4596 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4597 Src0, Src1); 4598 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4599 return; 4600 } 4601 case Intrinsic::amdgcn_cvt_pknorm_i16: 4602 case Intrinsic::amdgcn_cvt_pknorm_u16: 4603 case Intrinsic::amdgcn_cvt_pk_i16: 4604 case Intrinsic::amdgcn_cvt_pk_u16: { 4605 SDValue Src0 = N->getOperand(1); 4606 SDValue Src1 = N->getOperand(2); 4607 SDLoc SL(N); 4608 unsigned Opcode; 4609 4610 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4611 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4612 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4613 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4614 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4615 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4616 else 4617 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4618 4619 EVT VT = N->getValueType(0); 4620 if (isTypeLegal(VT)) 4621 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4622 else { 4623 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4624 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4625 } 4626 return; 4627 } 4628 } 4629 break; 4630 } 4631 case ISD::INTRINSIC_W_CHAIN: { 4632 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4633 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4634 // FIXME: Hacky 4635 Results.push_back(Res.getOperand(0)); 4636 Results.push_back(Res.getOperand(1)); 4637 } else { 4638 Results.push_back(Res); 4639 Results.push_back(Res.getValue(1)); 4640 } 4641 return; 4642 } 4643 4644 break; 4645 } 4646 case ISD::SELECT: { 4647 SDLoc SL(N); 4648 EVT VT = N->getValueType(0); 4649 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4650 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4651 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4652 4653 EVT SelectVT = NewVT; 4654 if (NewVT.bitsLT(MVT::i32)) { 4655 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4656 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4657 SelectVT = MVT::i32; 4658 } 4659 4660 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4661 N->getOperand(0), LHS, RHS); 4662 4663 if (NewVT != SelectVT) 4664 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4665 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4666 return; 4667 } 4668 case ISD::FNEG: { 4669 if (N->getValueType(0) != MVT::v2f16) 4670 break; 4671 4672 SDLoc SL(N); 4673 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4674 4675 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4676 BC, 4677 DAG.getConstant(0x80008000, SL, MVT::i32)); 4678 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4679 return; 4680 } 4681 case ISD::FABS: { 4682 if (N->getValueType(0) != MVT::v2f16) 4683 break; 4684 4685 SDLoc SL(N); 4686 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4687 4688 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4689 BC, 4690 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4691 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4692 return; 4693 } 4694 default: 4695 break; 4696 } 4697 } 4698 4699 /// Helper function for LowerBRCOND 4700 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4701 4702 SDNode *Parent = Value.getNode(); 4703 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4704 I != E; ++I) { 4705 4706 if (I.getUse().get() != Value) 4707 continue; 4708 4709 if (I->getOpcode() == Opcode) 4710 return *I; 4711 } 4712 return nullptr; 4713 } 4714 4715 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4716 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4717 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4718 case Intrinsic::amdgcn_if: 4719 return AMDGPUISD::IF; 4720 case Intrinsic::amdgcn_else: 4721 return AMDGPUISD::ELSE; 4722 case Intrinsic::amdgcn_loop: 4723 return AMDGPUISD::LOOP; 4724 case Intrinsic::amdgcn_end_cf: 4725 llvm_unreachable("should not occur"); 4726 default: 4727 return 0; 4728 } 4729 } 4730 4731 // break, if_break, else_break are all only used as inputs to loop, not 4732 // directly as branch conditions. 4733 return 0; 4734 } 4735 4736 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4737 const Triple &TT = getTargetMachine().getTargetTriple(); 4738 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4739 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4740 AMDGPU::shouldEmitConstantsToTextSection(TT); 4741 } 4742 4743 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4744 // FIXME: Either avoid relying on address space here or change the default 4745 // address space for functions to avoid the explicit check. 4746 return (GV->getValueType()->isFunctionTy() || 4747 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4748 !shouldEmitFixup(GV) && 4749 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4750 } 4751 4752 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4753 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4754 } 4755 4756 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4757 if (!GV->hasExternalLinkage()) 4758 return true; 4759 4760 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4761 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4762 } 4763 4764 /// This transforms the control flow intrinsics to get the branch destination as 4765 /// last parameter, also switches branch target with BR if the need arise 4766 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4767 SelectionDAG &DAG) const { 4768 SDLoc DL(BRCOND); 4769 4770 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4771 SDValue Target = BRCOND.getOperand(2); 4772 SDNode *BR = nullptr; 4773 SDNode *SetCC = nullptr; 4774 4775 if (Intr->getOpcode() == ISD::SETCC) { 4776 // As long as we negate the condition everything is fine 4777 SetCC = Intr; 4778 Intr = SetCC->getOperand(0).getNode(); 4779 4780 } else { 4781 // Get the target from BR if we don't negate the condition 4782 BR = findUser(BRCOND, ISD::BR); 4783 assert(BR && "brcond missing unconditional branch user"); 4784 Target = BR->getOperand(1); 4785 } 4786 4787 unsigned CFNode = isCFIntrinsic(Intr); 4788 if (CFNode == 0) { 4789 // This is a uniform branch so we don't need to legalize. 4790 return BRCOND; 4791 } 4792 4793 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4794 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4795 4796 assert(!SetCC || 4797 (SetCC->getConstantOperandVal(1) == 1 && 4798 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4799 ISD::SETNE)); 4800 4801 // operands of the new intrinsic call 4802 SmallVector<SDValue, 4> Ops; 4803 if (HaveChain) 4804 Ops.push_back(BRCOND.getOperand(0)); 4805 4806 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4807 Ops.push_back(Target); 4808 4809 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4810 4811 // build the new intrinsic call 4812 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4813 4814 if (!HaveChain) { 4815 SDValue Ops[] = { 4816 SDValue(Result, 0), 4817 BRCOND.getOperand(0) 4818 }; 4819 4820 Result = DAG.getMergeValues(Ops, DL).getNode(); 4821 } 4822 4823 if (BR) { 4824 // Give the branch instruction our target 4825 SDValue Ops[] = { 4826 BR->getOperand(0), 4827 BRCOND.getOperand(2) 4828 }; 4829 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4830 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4831 } 4832 4833 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4834 4835 // Copy the intrinsic results to registers 4836 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4837 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4838 if (!CopyToReg) 4839 continue; 4840 4841 Chain = DAG.getCopyToReg( 4842 Chain, DL, 4843 CopyToReg->getOperand(1), 4844 SDValue(Result, i - 1), 4845 SDValue()); 4846 4847 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4848 } 4849 4850 // Remove the old intrinsic from the chain 4851 DAG.ReplaceAllUsesOfValueWith( 4852 SDValue(Intr, Intr->getNumValues() - 1), 4853 Intr->getOperand(0)); 4854 4855 return Chain; 4856 } 4857 4858 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4859 SelectionDAG &DAG) const { 4860 MVT VT = Op.getSimpleValueType(); 4861 SDLoc DL(Op); 4862 // Checking the depth 4863 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4864 return DAG.getConstant(0, DL, VT); 4865 4866 MachineFunction &MF = DAG.getMachineFunction(); 4867 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4868 // Check for kernel and shader functions 4869 if (Info->isEntryFunction()) 4870 return DAG.getConstant(0, DL, VT); 4871 4872 MachineFrameInfo &MFI = MF.getFrameInfo(); 4873 // There is a call to @llvm.returnaddress in this function 4874 MFI.setReturnAddressIsTaken(true); 4875 4876 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4877 // Get the return address reg and mark it as an implicit live-in 4878 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4879 4880 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4881 } 4882 4883 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 4884 SDValue Op, 4885 const SDLoc &DL, 4886 EVT VT) const { 4887 return Op.getValueType().bitsLE(VT) ? 4888 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4889 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 4890 DAG.getTargetConstant(0, DL, MVT::i32)); 4891 } 4892 4893 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4894 assert(Op.getValueType() == MVT::f16 && 4895 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4896 4897 SDValue Src = Op.getOperand(0); 4898 EVT SrcVT = Src.getValueType(); 4899 if (SrcVT != MVT::f64) 4900 return Op; 4901 4902 SDLoc DL(Op); 4903 4904 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4905 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4906 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4907 } 4908 4909 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4910 SelectionDAG &DAG) const { 4911 EVT VT = Op.getValueType(); 4912 const MachineFunction &MF = DAG.getMachineFunction(); 4913 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4914 bool IsIEEEMode = Info->getMode().IEEE; 4915 4916 // FIXME: Assert during selection that this is only selected for 4917 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4918 // mode functions, but this happens to be OK since it's only done in cases 4919 // where there is known no sNaN. 4920 if (IsIEEEMode) 4921 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 4922 4923 if (VT == MVT::v4f16) 4924 return splitBinaryVectorOp(Op, DAG); 4925 return Op; 4926 } 4927 4928 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4929 SDLoc SL(Op); 4930 SDValue Chain = Op.getOperand(0); 4931 4932 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4933 !Subtarget->isTrapHandlerEnabled()) 4934 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4935 4936 MachineFunction &MF = DAG.getMachineFunction(); 4937 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4938 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4939 assert(UserSGPR != AMDGPU::NoRegister); 4940 SDValue QueuePtr = CreateLiveInRegister( 4941 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4942 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4943 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4944 QueuePtr, SDValue()); 4945 SDValue Ops[] = { 4946 ToReg, 4947 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 4948 SGPR01, 4949 ToReg.getValue(1) 4950 }; 4951 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4952 } 4953 4954 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 4955 SDLoc SL(Op); 4956 SDValue Chain = Op.getOperand(0); 4957 MachineFunction &MF = DAG.getMachineFunction(); 4958 4959 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4960 !Subtarget->isTrapHandlerEnabled()) { 4961 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4962 "debugtrap handler not supported", 4963 Op.getDebugLoc(), 4964 DS_Warning); 4965 LLVMContext &Ctx = MF.getFunction().getContext(); 4966 Ctx.diagnose(NoTrap); 4967 return Chain; 4968 } 4969 4970 SDValue Ops[] = { 4971 Chain, 4972 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 4973 }; 4974 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4975 } 4976 4977 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4978 SelectionDAG &DAG) const { 4979 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4980 if (Subtarget->hasApertureRegs()) { 4981 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 4982 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4983 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4984 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 4985 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4986 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4987 unsigned Encoding = 4988 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4989 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4990 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4991 4992 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4993 SDValue ApertureReg = SDValue( 4994 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4995 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4996 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4997 } 4998 4999 MachineFunction &MF = DAG.getMachineFunction(); 5000 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5001 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5002 assert(UserSGPR != AMDGPU::NoRegister); 5003 5004 SDValue QueuePtr = CreateLiveInRegister( 5005 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5006 5007 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5008 // private_segment_aperture_base_hi. 5009 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5010 5011 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 5012 5013 // TODO: Use custom target PseudoSourceValue. 5014 // TODO: We should use the value from the IR intrinsic call, but it might not 5015 // be available and how do we get it? 5016 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5017 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5018 MinAlign(64, StructOffset), 5019 MachineMemOperand::MODereferenceable | 5020 MachineMemOperand::MOInvariant); 5021 } 5022 5023 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5024 SelectionDAG &DAG) const { 5025 SDLoc SL(Op); 5026 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5027 5028 SDValue Src = ASC->getOperand(0); 5029 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5030 5031 const AMDGPUTargetMachine &TM = 5032 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5033 5034 // flat -> local/private 5035 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5036 unsigned DestAS = ASC->getDestAddressSpace(); 5037 5038 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5039 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5040 unsigned NullVal = TM.getNullPointerValue(DestAS); 5041 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5042 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5043 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5044 5045 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5046 NonNull, Ptr, SegmentNullPtr); 5047 } 5048 } 5049 5050 // local/private -> flat 5051 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5052 unsigned SrcAS = ASC->getSrcAddressSpace(); 5053 5054 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5055 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5056 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5057 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5058 5059 SDValue NonNull 5060 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5061 5062 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5063 SDValue CvtPtr 5064 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5065 5066 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5067 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5068 FlatNullPtr); 5069 } 5070 } 5071 5072 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5073 Src.getValueType() == MVT::i64) 5074 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5075 5076 // global <-> flat are no-ops and never emitted. 5077 5078 const MachineFunction &MF = DAG.getMachineFunction(); 5079 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5080 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5081 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5082 5083 return DAG.getUNDEF(ASC->getValueType(0)); 5084 } 5085 5086 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5087 // the small vector and inserting them into the big vector. That is better than 5088 // the default expansion of doing it via a stack slot. Even though the use of 5089 // the stack slot would be optimized away afterwards, the stack slot itself 5090 // remains. 5091 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5092 SelectionDAG &DAG) const { 5093 SDValue Vec = Op.getOperand(0); 5094 SDValue Ins = Op.getOperand(1); 5095 SDValue Idx = Op.getOperand(2); 5096 EVT VecVT = Vec.getValueType(); 5097 EVT InsVT = Ins.getValueType(); 5098 EVT EltVT = VecVT.getVectorElementType(); 5099 unsigned InsNumElts = InsVT.getVectorNumElements(); 5100 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5101 SDLoc SL(Op); 5102 5103 for (unsigned I = 0; I != InsNumElts; ++I) { 5104 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5105 DAG.getConstant(I, SL, MVT::i32)); 5106 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5107 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5108 } 5109 return Vec; 5110 } 5111 5112 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5113 SelectionDAG &DAG) const { 5114 SDValue Vec = Op.getOperand(0); 5115 SDValue InsVal = Op.getOperand(1); 5116 SDValue Idx = Op.getOperand(2); 5117 EVT VecVT = Vec.getValueType(); 5118 EVT EltVT = VecVT.getVectorElementType(); 5119 unsigned VecSize = VecVT.getSizeInBits(); 5120 unsigned EltSize = EltVT.getSizeInBits(); 5121 5122 5123 assert(VecSize <= 64); 5124 5125 unsigned NumElts = VecVT.getVectorNumElements(); 5126 SDLoc SL(Op); 5127 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5128 5129 if (NumElts == 4 && EltSize == 16 && KIdx) { 5130 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5131 5132 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5133 DAG.getConstant(0, SL, MVT::i32)); 5134 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5135 DAG.getConstant(1, SL, MVT::i32)); 5136 5137 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5138 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5139 5140 unsigned Idx = KIdx->getZExtValue(); 5141 bool InsertLo = Idx < 2; 5142 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5143 InsertLo ? LoVec : HiVec, 5144 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5145 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5146 5147 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5148 5149 SDValue Concat = InsertLo ? 5150 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5151 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5152 5153 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5154 } 5155 5156 if (isa<ConstantSDNode>(Idx)) 5157 return SDValue(); 5158 5159 MVT IntVT = MVT::getIntegerVT(VecSize); 5160 5161 // Avoid stack access for dynamic indexing. 5162 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5163 5164 // Create a congruent vector with the target value in each element so that 5165 // the required element can be masked and ORed into the target vector. 5166 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5167 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5168 5169 assert(isPowerOf2_32(EltSize)); 5170 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5171 5172 // Convert vector index to bit-index. 5173 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5174 5175 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5176 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5177 DAG.getConstant(0xffff, SL, IntVT), 5178 ScaledIdx); 5179 5180 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5181 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5182 DAG.getNOT(SL, BFM, IntVT), BCVec); 5183 5184 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5185 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5186 } 5187 5188 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5189 SelectionDAG &DAG) const { 5190 SDLoc SL(Op); 5191 5192 EVT ResultVT = Op.getValueType(); 5193 SDValue Vec = Op.getOperand(0); 5194 SDValue Idx = Op.getOperand(1); 5195 EVT VecVT = Vec.getValueType(); 5196 unsigned VecSize = VecVT.getSizeInBits(); 5197 EVT EltVT = VecVT.getVectorElementType(); 5198 assert(VecSize <= 64); 5199 5200 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5201 5202 // Make sure we do any optimizations that will make it easier to fold 5203 // source modifiers before obscuring it with bit operations. 5204 5205 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5206 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5207 return Combined; 5208 5209 unsigned EltSize = EltVT.getSizeInBits(); 5210 assert(isPowerOf2_32(EltSize)); 5211 5212 MVT IntVT = MVT::getIntegerVT(VecSize); 5213 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5214 5215 // Convert vector index to bit-index (* EltSize) 5216 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5217 5218 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5219 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5220 5221 if (ResultVT == MVT::f16) { 5222 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5223 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5224 } 5225 5226 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5227 } 5228 5229 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5230 assert(Elt % 2 == 0); 5231 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5232 } 5233 5234 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5235 SelectionDAG &DAG) const { 5236 SDLoc SL(Op); 5237 EVT ResultVT = Op.getValueType(); 5238 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5239 5240 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5241 EVT EltVT = PackVT.getVectorElementType(); 5242 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5243 5244 // vector_shuffle <0,1,6,7> lhs, rhs 5245 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5246 // 5247 // vector_shuffle <6,7,2,3> lhs, rhs 5248 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5249 // 5250 // vector_shuffle <6,7,0,1> lhs, rhs 5251 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5252 5253 // Avoid scalarizing when both halves are reading from consecutive elements. 5254 SmallVector<SDValue, 4> Pieces; 5255 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5256 if (elementPairIsContiguous(SVN->getMask(), I)) { 5257 const int Idx = SVN->getMaskElt(I); 5258 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5259 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5260 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5261 PackVT, SVN->getOperand(VecIdx), 5262 DAG.getConstant(EltIdx, SL, MVT::i32)); 5263 Pieces.push_back(SubVec); 5264 } else { 5265 const int Idx0 = SVN->getMaskElt(I); 5266 const int Idx1 = SVN->getMaskElt(I + 1); 5267 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5268 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5269 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5270 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5271 5272 SDValue Vec0 = SVN->getOperand(VecIdx0); 5273 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5274 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5275 5276 SDValue Vec1 = SVN->getOperand(VecIdx1); 5277 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5278 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5279 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5280 } 5281 } 5282 5283 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5284 } 5285 5286 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5287 SelectionDAG &DAG) const { 5288 SDLoc SL(Op); 5289 EVT VT = Op.getValueType(); 5290 5291 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5292 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5293 5294 // Turn into pair of packed build_vectors. 5295 // TODO: Special case for constants that can be materialized with s_mov_b64. 5296 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5297 { Op.getOperand(0), Op.getOperand(1) }); 5298 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5299 { Op.getOperand(2), Op.getOperand(3) }); 5300 5301 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5302 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5303 5304 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5305 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5306 } 5307 5308 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5309 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5310 5311 SDValue Lo = Op.getOperand(0); 5312 SDValue Hi = Op.getOperand(1); 5313 5314 // Avoid adding defined bits with the zero_extend. 5315 if (Hi.isUndef()) { 5316 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5317 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5318 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5319 } 5320 5321 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5322 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5323 5324 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5325 DAG.getConstant(16, SL, MVT::i32)); 5326 if (Lo.isUndef()) 5327 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5328 5329 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5330 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5331 5332 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5333 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5334 } 5335 5336 bool 5337 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5338 // We can fold offsets for anything that doesn't require a GOT relocation. 5339 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5340 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5341 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5342 !shouldEmitGOTReloc(GA->getGlobal()); 5343 } 5344 5345 static SDValue 5346 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5347 const SDLoc &DL, unsigned Offset, EVT PtrVT, 5348 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5349 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5350 // lowered to the following code sequence: 5351 // 5352 // For constant address space: 5353 // s_getpc_b64 s[0:1] 5354 // s_add_u32 s0, s0, $symbol 5355 // s_addc_u32 s1, s1, 0 5356 // 5357 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5358 // a fixup or relocation is emitted to replace $symbol with a literal 5359 // constant, which is a pc-relative offset from the encoding of the $symbol 5360 // operand to the global variable. 5361 // 5362 // For global address space: 5363 // s_getpc_b64 s[0:1] 5364 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5365 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5366 // 5367 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5368 // fixups or relocations are emitted to replace $symbol@*@lo and 5369 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5370 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5371 // operand to the global variable. 5372 // 5373 // What we want here is an offset from the value returned by s_getpc 5374 // (which is the address of the s_add_u32 instruction) to the global 5375 // variable, but since the encoding of $symbol starts 4 bytes after the start 5376 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5377 // small. This requires us to add 4 to the global variable offset in order to 5378 // compute the correct address. 5379 SDValue PtrLo = 5380 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5381 SDValue PtrHi; 5382 if (GAFlags == SIInstrInfo::MO_NONE) { 5383 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5384 } else { 5385 PtrHi = 5386 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5387 } 5388 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5389 } 5390 5391 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5392 SDValue Op, 5393 SelectionDAG &DAG) const { 5394 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5395 const GlobalValue *GV = GSD->getGlobal(); 5396 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5397 shouldUseLDSConstAddress(GV)) || 5398 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5399 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5400 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5401 5402 SDLoc DL(GSD); 5403 EVT PtrVT = Op.getValueType(); 5404 5405 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5406 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5407 SIInstrInfo::MO_ABS32_LO); 5408 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5409 } 5410 5411 if (shouldEmitFixup(GV)) 5412 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5413 else if (shouldEmitPCReloc(GV)) 5414 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5415 SIInstrInfo::MO_REL32); 5416 5417 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5418 SIInstrInfo::MO_GOTPCREL32); 5419 5420 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5421 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5422 const DataLayout &DataLayout = DAG.getDataLayout(); 5423 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 5424 MachinePointerInfo PtrInfo 5425 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5426 5427 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 5428 MachineMemOperand::MODereferenceable | 5429 MachineMemOperand::MOInvariant); 5430 } 5431 5432 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5433 const SDLoc &DL, SDValue V) const { 5434 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5435 // the destination register. 5436 // 5437 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5438 // so we will end up with redundant moves to m0. 5439 // 5440 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5441 5442 // A Null SDValue creates a glue result. 5443 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5444 V, Chain); 5445 return SDValue(M0, 0); 5446 } 5447 5448 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5449 SDValue Op, 5450 MVT VT, 5451 unsigned Offset) const { 5452 SDLoc SL(Op); 5453 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 5454 DAG.getEntryNode(), Offset, 4, false); 5455 // The local size values will have the hi 16-bits as zero. 5456 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5457 DAG.getValueType(VT)); 5458 } 5459 5460 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5461 EVT VT) { 5462 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5463 "non-hsa intrinsic with hsa target", 5464 DL.getDebugLoc()); 5465 DAG.getContext()->diagnose(BadIntrin); 5466 return DAG.getUNDEF(VT); 5467 } 5468 5469 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5470 EVT VT) { 5471 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5472 "intrinsic not supported on subtarget", 5473 DL.getDebugLoc()); 5474 DAG.getContext()->diagnose(BadIntrin); 5475 return DAG.getUNDEF(VT); 5476 } 5477 5478 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5479 ArrayRef<SDValue> Elts) { 5480 assert(!Elts.empty()); 5481 MVT Type; 5482 unsigned NumElts; 5483 5484 if (Elts.size() == 1) { 5485 Type = MVT::f32; 5486 NumElts = 1; 5487 } else if (Elts.size() == 2) { 5488 Type = MVT::v2f32; 5489 NumElts = 2; 5490 } else if (Elts.size() == 3) { 5491 Type = MVT::v3f32; 5492 NumElts = 3; 5493 } else if (Elts.size() <= 4) { 5494 Type = MVT::v4f32; 5495 NumElts = 4; 5496 } else if (Elts.size() <= 8) { 5497 Type = MVT::v8f32; 5498 NumElts = 8; 5499 } else { 5500 assert(Elts.size() <= 16); 5501 Type = MVT::v16f32; 5502 NumElts = 16; 5503 } 5504 5505 SmallVector<SDValue, 16> VecElts(NumElts); 5506 for (unsigned i = 0; i < Elts.size(); ++i) { 5507 SDValue Elt = Elts[i]; 5508 if (Elt.getValueType() != MVT::f32) 5509 Elt = DAG.getBitcast(MVT::f32, Elt); 5510 VecElts[i] = Elt; 5511 } 5512 for (unsigned i = Elts.size(); i < NumElts; ++i) 5513 VecElts[i] = DAG.getUNDEF(MVT::f32); 5514 5515 if (NumElts == 1) 5516 return VecElts[0]; 5517 return DAG.getBuildVector(Type, DL, VecElts); 5518 } 5519 5520 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5521 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5522 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5523 5524 uint64_t Value = CachePolicyConst->getZExtValue(); 5525 SDLoc DL(CachePolicy); 5526 if (GLC) { 5527 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5528 Value &= ~(uint64_t)0x1; 5529 } 5530 if (SLC) { 5531 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5532 Value &= ~(uint64_t)0x2; 5533 } 5534 if (DLC) { 5535 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5536 Value &= ~(uint64_t)0x4; 5537 } 5538 5539 return Value == 0; 5540 } 5541 5542 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5543 SDValue Src, int ExtraElts) { 5544 EVT SrcVT = Src.getValueType(); 5545 5546 SmallVector<SDValue, 8> Elts; 5547 5548 if (SrcVT.isVector()) 5549 DAG.ExtractVectorElements(Src, Elts); 5550 else 5551 Elts.push_back(Src); 5552 5553 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5554 while (ExtraElts--) 5555 Elts.push_back(Undef); 5556 5557 return DAG.getBuildVector(CastVT, DL, Elts); 5558 } 5559 5560 // Re-construct the required return value for a image load intrinsic. 5561 // This is more complicated due to the optional use TexFailCtrl which means the required 5562 // return type is an aggregate 5563 static SDValue constructRetValue(SelectionDAG &DAG, 5564 MachineSDNode *Result, 5565 ArrayRef<EVT> ResultTypes, 5566 bool IsTexFail, bool Unpacked, bool IsD16, 5567 int DMaskPop, int NumVDataDwords, 5568 const SDLoc &DL, LLVMContext &Context) { 5569 // Determine the required return type. This is the same regardless of IsTexFail flag 5570 EVT ReqRetVT = ResultTypes[0]; 5571 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5572 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5573 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5574 5575 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5576 DMaskPop : (DMaskPop + 1) / 2; 5577 5578 MVT DataDwordVT = NumDataDwords == 1 ? 5579 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5580 5581 MVT MaskPopVT = MaskPopDwords == 1 ? 5582 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5583 5584 SDValue Data(Result, 0); 5585 SDValue TexFail; 5586 5587 if (IsTexFail) { 5588 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5589 if (MaskPopVT.isVector()) { 5590 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5591 SDValue(Result, 0), ZeroIdx); 5592 } else { 5593 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5594 SDValue(Result, 0), ZeroIdx); 5595 } 5596 5597 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5598 SDValue(Result, 0), 5599 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5600 } 5601 5602 if (DataDwordVT.isVector()) 5603 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5604 NumDataDwords - MaskPopDwords); 5605 5606 if (IsD16) 5607 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5608 5609 if (!ReqRetVT.isVector()) 5610 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5611 5612 Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data); 5613 5614 if (TexFail) 5615 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5616 5617 if (Result->getNumValues() == 1) 5618 return Data; 5619 5620 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5621 } 5622 5623 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5624 SDValue *LWE, bool &IsTexFail) { 5625 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5626 5627 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5628 if (Value) { 5629 IsTexFail = true; 5630 } 5631 5632 SDLoc DL(TexFailCtrlConst); 5633 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5634 Value &= ~(uint64_t)0x1; 5635 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5636 Value &= ~(uint64_t)0x2; 5637 5638 return Value == 0; 5639 } 5640 5641 SDValue SITargetLowering::lowerImage(SDValue Op, 5642 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5643 SelectionDAG &DAG) const { 5644 SDLoc DL(Op); 5645 MachineFunction &MF = DAG.getMachineFunction(); 5646 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5647 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5648 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5649 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5650 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5651 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5652 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5653 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5654 unsigned IntrOpcode = Intr->BaseOpcode; 5655 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5656 5657 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5658 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5659 bool IsD16 = false; 5660 bool IsA16 = false; 5661 SDValue VData; 5662 int NumVDataDwords; 5663 bool AdjustRetType = false; 5664 5665 unsigned AddrIdx; // Index of first address argument 5666 unsigned DMask; 5667 unsigned DMaskLanes = 0; 5668 5669 if (BaseOpcode->Atomic) { 5670 VData = Op.getOperand(2); 5671 5672 bool Is64Bit = VData.getValueType() == MVT::i64; 5673 if (BaseOpcode->AtomicX2) { 5674 SDValue VData2 = Op.getOperand(3); 5675 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5676 {VData, VData2}); 5677 if (Is64Bit) 5678 VData = DAG.getBitcast(MVT::v4i32, VData); 5679 5680 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5681 DMask = Is64Bit ? 0xf : 0x3; 5682 NumVDataDwords = Is64Bit ? 4 : 2; 5683 AddrIdx = 4; 5684 } else { 5685 DMask = Is64Bit ? 0x3 : 0x1; 5686 NumVDataDwords = Is64Bit ? 2 : 1; 5687 AddrIdx = 3; 5688 } 5689 } else { 5690 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5691 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5692 DMask = DMaskConst->getZExtValue(); 5693 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5694 5695 if (BaseOpcode->Store) { 5696 VData = Op.getOperand(2); 5697 5698 MVT StoreVT = VData.getSimpleValueType(); 5699 if (StoreVT.getScalarType() == MVT::f16) { 5700 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5701 return Op; // D16 is unsupported for this instruction 5702 5703 IsD16 = true; 5704 VData = handleD16VData(VData, DAG); 5705 } 5706 5707 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5708 } else { 5709 // Work out the num dwords based on the dmask popcount and underlying type 5710 // and whether packing is supported. 5711 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5712 if (LoadVT.getScalarType() == MVT::f16) { 5713 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5714 return Op; // D16 is unsupported for this instruction 5715 5716 IsD16 = true; 5717 } 5718 5719 // Confirm that the return type is large enough for the dmask specified 5720 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5721 (!LoadVT.isVector() && DMaskLanes > 1)) 5722 return Op; 5723 5724 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5725 NumVDataDwords = (DMaskLanes + 1) / 2; 5726 else 5727 NumVDataDwords = DMaskLanes; 5728 5729 AdjustRetType = true; 5730 } 5731 5732 AddrIdx = DMaskIdx + 1; 5733 } 5734 5735 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5736 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5737 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5738 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5739 NumCoords + NumLCM; 5740 unsigned NumMIVAddrs = NumVAddrs; 5741 5742 SmallVector<SDValue, 4> VAddrs; 5743 5744 // Optimize _L to _LZ when _L is zero 5745 if (LZMappingInfo) { 5746 if (auto ConstantLod = 5747 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5748 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5749 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5750 NumMIVAddrs--; // remove 'lod' 5751 } 5752 } 5753 } 5754 5755 // Optimize _mip away, when 'lod' is zero 5756 if (MIPMappingInfo) { 5757 if (auto ConstantLod = 5758 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5759 if (ConstantLod->isNullValue()) { 5760 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5761 NumMIVAddrs--; // remove 'lod' 5762 } 5763 } 5764 } 5765 5766 // Check for 16 bit addresses and pack if true. 5767 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5768 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5769 const MVT VAddrScalarVT = VAddrVT.getScalarType(); 5770 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) { 5771 // Illegal to use a16 images 5772 if (!ST->hasFeature(AMDGPU::FeatureR128A16) && !ST->hasFeature(AMDGPU::FeatureGFX10A16)) 5773 return Op; 5774 5775 IsA16 = true; 5776 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5777 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) { 5778 SDValue AddrLo; 5779 // Push back extra arguments. 5780 if (i < DimIdx) { 5781 AddrLo = Op.getOperand(i); 5782 } else { 5783 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, 5784 // in 1D, derivatives dx/dh and dx/dv are packed with undef. 5785 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) || 5786 ((NumGradients / 2) % 2 == 1 && 5787 (i == DimIdx + (NumGradients / 2) - 1 || 5788 i == DimIdx + NumGradients - 1))) { 5789 AddrLo = Op.getOperand(i); 5790 if (AddrLo.getValueType() != MVT::i16) 5791 AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i)); 5792 AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo); 5793 } else { 5794 AddrLo = DAG.getBuildVector(VectorVT, DL, 5795 {Op.getOperand(i), Op.getOperand(i + 1)}); 5796 i++; 5797 } 5798 AddrLo = DAG.getBitcast(MVT::f32, AddrLo); 5799 } 5800 VAddrs.push_back(AddrLo); 5801 } 5802 } else { 5803 for (unsigned i = 0; i < NumMIVAddrs; ++i) 5804 VAddrs.push_back(Op.getOperand(AddrIdx + i)); 5805 } 5806 5807 // If the register allocator cannot place the address registers contiguously 5808 // without introducing moves, then using the non-sequential address encoding 5809 // is always preferable, since it saves VALU instructions and is usually a 5810 // wash in terms of code size or even better. 5811 // 5812 // However, we currently have no way of hinting to the register allocator that 5813 // MIMG addresses should be placed contiguously when it is possible to do so, 5814 // so force non-NSA for the common 2-address case as a heuristic. 5815 // 5816 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5817 // allocation when possible. 5818 bool UseNSA = 5819 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5820 SDValue VAddr; 5821 if (!UseNSA) 5822 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5823 5824 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5825 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5826 unsigned CtrlIdx; // Index of texfailctrl argument 5827 SDValue Unorm; 5828 if (!BaseOpcode->Sampler) { 5829 Unorm = True; 5830 CtrlIdx = AddrIdx + NumVAddrs + 1; 5831 } else { 5832 auto UnormConst = 5833 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 5834 5835 Unorm = UnormConst->getZExtValue() ? True : False; 5836 CtrlIdx = AddrIdx + NumVAddrs + 3; 5837 } 5838 5839 SDValue TFE; 5840 SDValue LWE; 5841 SDValue TexFail = Op.getOperand(CtrlIdx); 5842 bool IsTexFail = false; 5843 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 5844 return Op; 5845 5846 if (IsTexFail) { 5847 if (!DMaskLanes) { 5848 // Expecting to get an error flag since TFC is on - and dmask is 0 5849 // Force dmask to be at least 1 otherwise the instruction will fail 5850 DMask = 0x1; 5851 DMaskLanes = 1; 5852 NumVDataDwords = 1; 5853 } 5854 NumVDataDwords += 1; 5855 AdjustRetType = true; 5856 } 5857 5858 // Has something earlier tagged that the return type needs adjusting 5859 // This happens if the instruction is a load or has set TexFailCtrl flags 5860 if (AdjustRetType) { 5861 // NumVDataDwords reflects the true number of dwords required in the return type 5862 if (DMaskLanes == 0 && !BaseOpcode->Store) { 5863 // This is a no-op load. This can be eliminated 5864 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 5865 if (isa<MemSDNode>(Op)) 5866 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 5867 return Undef; 5868 } 5869 5870 EVT NewVT = NumVDataDwords > 1 ? 5871 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 5872 : MVT::i32; 5873 5874 ResultTypes[0] = NewVT; 5875 if (ResultTypes.size() == 3) { 5876 // Original result was aggregate type used for TexFailCtrl results 5877 // The actual instruction returns as a vector type which has now been 5878 // created. Remove the aggregate result. 5879 ResultTypes.erase(&ResultTypes[1]); 5880 } 5881 } 5882 5883 SDValue GLC; 5884 SDValue SLC; 5885 SDValue DLC; 5886 if (BaseOpcode->Atomic) { 5887 GLC = True; // TODO no-return optimization 5888 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 5889 IsGFX10 ? &DLC : nullptr)) 5890 return Op; 5891 } else { 5892 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 5893 IsGFX10 ? &DLC : nullptr)) 5894 return Op; 5895 } 5896 5897 SmallVector<SDValue, 26> Ops; 5898 if (BaseOpcode->Store || BaseOpcode->Atomic) 5899 Ops.push_back(VData); // vdata 5900 if (UseNSA) { 5901 for (const SDValue &Addr : VAddrs) 5902 Ops.push_back(Addr); 5903 } else { 5904 Ops.push_back(VAddr); 5905 } 5906 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 5907 if (BaseOpcode->Sampler) 5908 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 5909 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 5910 if (IsGFX10) 5911 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 5912 Ops.push_back(Unorm); 5913 if (IsGFX10) 5914 Ops.push_back(DLC); 5915 Ops.push_back(GLC); 5916 Ops.push_back(SLC); 5917 Ops.push_back(IsA16 && // r128, a16 for gfx9 5918 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 5919 if (IsGFX10) 5920 Ops.push_back(IsA16 ? True : False); 5921 Ops.push_back(TFE); 5922 Ops.push_back(LWE); 5923 if (!IsGFX10) 5924 Ops.push_back(DimInfo->DA ? True : False); 5925 if (BaseOpcode->HasD16) 5926 Ops.push_back(IsD16 ? True : False); 5927 if (isa<MemSDNode>(Op)) 5928 Ops.push_back(Op.getOperand(0)); // chain 5929 5930 int NumVAddrDwords = 5931 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 5932 int Opcode = -1; 5933 5934 if (IsGFX10) { 5935 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 5936 UseNSA ? AMDGPU::MIMGEncGfx10NSA 5937 : AMDGPU::MIMGEncGfx10Default, 5938 NumVDataDwords, NumVAddrDwords); 5939 } else { 5940 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5941 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 5942 NumVDataDwords, NumVAddrDwords); 5943 if (Opcode == -1) 5944 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 5945 NumVDataDwords, NumVAddrDwords); 5946 } 5947 assert(Opcode != -1); 5948 5949 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 5950 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 5951 MachineMemOperand *MemRef = MemOp->getMemOperand(); 5952 DAG.setNodeMemRefs(NewNode, {MemRef}); 5953 } 5954 5955 if (BaseOpcode->AtomicX2) { 5956 SmallVector<SDValue, 1> Elt; 5957 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 5958 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 5959 } else if (!BaseOpcode->Store) { 5960 return constructRetValue(DAG, NewNode, 5961 OrigResultTypes, IsTexFail, 5962 Subtarget->hasUnpackedD16VMem(), IsD16, 5963 DMaskLanes, NumVDataDwords, DL, 5964 *DAG.getContext()); 5965 } 5966 5967 return SDValue(NewNode, 0); 5968 } 5969 5970 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 5971 SDValue Offset, SDValue CachePolicy, 5972 SelectionDAG &DAG) const { 5973 MachineFunction &MF = DAG.getMachineFunction(); 5974 5975 const DataLayout &DataLayout = DAG.getDataLayout(); 5976 Align Alignment = 5977 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 5978 5979 MachineMemOperand *MMO = MF.getMachineMemOperand( 5980 MachinePointerInfo(), 5981 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 5982 MachineMemOperand::MOInvariant, 5983 VT.getStoreSize(), Alignment); 5984 5985 if (!Offset->isDivergent()) { 5986 SDValue Ops[] = { 5987 Rsrc, 5988 Offset, // Offset 5989 CachePolicy 5990 }; 5991 5992 // Widen vec3 load to vec4. 5993 if (VT.isVector() && VT.getVectorNumElements() == 3) { 5994 EVT WidenedVT = 5995 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 5996 auto WidenedOp = DAG.getMemIntrinsicNode( 5997 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 5998 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 5999 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6000 DAG.getVectorIdxConstant(0, DL)); 6001 return Subvector; 6002 } 6003 6004 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6005 DAG.getVTList(VT), Ops, VT, MMO); 6006 } 6007 6008 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6009 // assume that the buffer is unswizzled. 6010 SmallVector<SDValue, 4> Loads; 6011 unsigned NumLoads = 1; 6012 MVT LoadVT = VT.getSimpleVT(); 6013 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6014 assert((LoadVT.getScalarType() == MVT::i32 || 6015 LoadVT.getScalarType() == MVT::f32)); 6016 6017 if (NumElts == 8 || NumElts == 16) { 6018 NumLoads = NumElts / 4; 6019 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6020 } 6021 6022 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6023 SDValue Ops[] = { 6024 DAG.getEntryNode(), // Chain 6025 Rsrc, // rsrc 6026 DAG.getConstant(0, DL, MVT::i32), // vindex 6027 {}, // voffset 6028 {}, // soffset 6029 {}, // offset 6030 CachePolicy, // cachepolicy 6031 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6032 }; 6033 6034 // Use the alignment to ensure that the required offsets will fit into the 6035 // immediate offsets. 6036 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 6037 6038 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6039 for (unsigned i = 0; i < NumLoads; ++i) { 6040 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6041 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6042 LoadVT, MMO, DAG)); 6043 } 6044 6045 if (NumElts == 8 || NumElts == 16) 6046 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6047 6048 return Loads[0]; 6049 } 6050 6051 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6052 SelectionDAG &DAG) const { 6053 MachineFunction &MF = DAG.getMachineFunction(); 6054 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6055 6056 EVT VT = Op.getValueType(); 6057 SDLoc DL(Op); 6058 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6059 6060 // TODO: Should this propagate fast-math-flags? 6061 6062 switch (IntrinsicID) { 6063 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6064 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6065 return emitNonHSAIntrinsicError(DAG, DL, VT); 6066 return getPreloadedValue(DAG, *MFI, VT, 6067 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6068 } 6069 case Intrinsic::amdgcn_dispatch_ptr: 6070 case Intrinsic::amdgcn_queue_ptr: { 6071 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6072 DiagnosticInfoUnsupported BadIntrin( 6073 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6074 DL.getDebugLoc()); 6075 DAG.getContext()->diagnose(BadIntrin); 6076 return DAG.getUNDEF(VT); 6077 } 6078 6079 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6080 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6081 return getPreloadedValue(DAG, *MFI, VT, RegID); 6082 } 6083 case Intrinsic::amdgcn_implicitarg_ptr: { 6084 if (MFI->isEntryFunction()) 6085 return getImplicitArgPtr(DAG, DL); 6086 return getPreloadedValue(DAG, *MFI, VT, 6087 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6088 } 6089 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6090 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6091 // This only makes sense to call in a kernel, so just lower to null. 6092 return DAG.getConstant(0, DL, VT); 6093 } 6094 6095 return getPreloadedValue(DAG, *MFI, VT, 6096 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6097 } 6098 case Intrinsic::amdgcn_dispatch_id: { 6099 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6100 } 6101 case Intrinsic::amdgcn_rcp: 6102 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6103 case Intrinsic::amdgcn_rsq: 6104 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6105 case Intrinsic::amdgcn_rsq_legacy: 6106 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6107 return emitRemovedIntrinsicError(DAG, DL, VT); 6108 return SDValue(); 6109 case Intrinsic::amdgcn_rcp_legacy: 6110 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6111 return emitRemovedIntrinsicError(DAG, DL, VT); 6112 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6113 case Intrinsic::amdgcn_rsq_clamp: { 6114 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6115 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6116 6117 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6118 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6119 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6120 6121 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6122 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6123 DAG.getConstantFP(Max, DL, VT)); 6124 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6125 DAG.getConstantFP(Min, DL, VT)); 6126 } 6127 case Intrinsic::r600_read_ngroups_x: 6128 if (Subtarget->isAmdHsaOS()) 6129 return emitNonHSAIntrinsicError(DAG, DL, VT); 6130 6131 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6132 SI::KernelInputOffsets::NGROUPS_X, 4, false); 6133 case Intrinsic::r600_read_ngroups_y: 6134 if (Subtarget->isAmdHsaOS()) 6135 return emitNonHSAIntrinsicError(DAG, DL, VT); 6136 6137 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6138 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 6139 case Intrinsic::r600_read_ngroups_z: 6140 if (Subtarget->isAmdHsaOS()) 6141 return emitNonHSAIntrinsicError(DAG, DL, VT); 6142 6143 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6144 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 6145 case Intrinsic::r600_read_global_size_x: 6146 if (Subtarget->isAmdHsaOS()) 6147 return emitNonHSAIntrinsicError(DAG, DL, VT); 6148 6149 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6150 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 6151 case Intrinsic::r600_read_global_size_y: 6152 if (Subtarget->isAmdHsaOS()) 6153 return emitNonHSAIntrinsicError(DAG, DL, VT); 6154 6155 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6156 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 6157 case Intrinsic::r600_read_global_size_z: 6158 if (Subtarget->isAmdHsaOS()) 6159 return emitNonHSAIntrinsicError(DAG, DL, VT); 6160 6161 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6162 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 6163 case Intrinsic::r600_read_local_size_x: 6164 if (Subtarget->isAmdHsaOS()) 6165 return emitNonHSAIntrinsicError(DAG, DL, VT); 6166 6167 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6168 SI::KernelInputOffsets::LOCAL_SIZE_X); 6169 case Intrinsic::r600_read_local_size_y: 6170 if (Subtarget->isAmdHsaOS()) 6171 return emitNonHSAIntrinsicError(DAG, DL, VT); 6172 6173 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6174 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6175 case Intrinsic::r600_read_local_size_z: 6176 if (Subtarget->isAmdHsaOS()) 6177 return emitNonHSAIntrinsicError(DAG, DL, VT); 6178 6179 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6180 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6181 case Intrinsic::amdgcn_workgroup_id_x: 6182 return getPreloadedValue(DAG, *MFI, VT, 6183 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6184 case Intrinsic::amdgcn_workgroup_id_y: 6185 return getPreloadedValue(DAG, *MFI, VT, 6186 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6187 case Intrinsic::amdgcn_workgroup_id_z: 6188 return getPreloadedValue(DAG, *MFI, VT, 6189 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6190 case Intrinsic::amdgcn_workitem_id_x: 6191 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6192 SDLoc(DAG.getEntryNode()), 6193 MFI->getArgInfo().WorkItemIDX); 6194 case Intrinsic::amdgcn_workitem_id_y: 6195 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6196 SDLoc(DAG.getEntryNode()), 6197 MFI->getArgInfo().WorkItemIDY); 6198 case Intrinsic::amdgcn_workitem_id_z: 6199 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6200 SDLoc(DAG.getEntryNode()), 6201 MFI->getArgInfo().WorkItemIDZ); 6202 case Intrinsic::amdgcn_wavefrontsize: 6203 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6204 SDLoc(Op), MVT::i32); 6205 case Intrinsic::amdgcn_s_buffer_load: { 6206 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 6207 SDValue GLC; 6208 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6209 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6210 IsGFX10 ? &DLC : nullptr)) 6211 return Op; 6212 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6213 DAG); 6214 } 6215 case Intrinsic::amdgcn_fdiv_fast: 6216 return lowerFDIV_FAST(Op, DAG); 6217 case Intrinsic::amdgcn_sin: 6218 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6219 6220 case Intrinsic::amdgcn_cos: 6221 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6222 6223 case Intrinsic::amdgcn_mul_u24: 6224 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6225 case Intrinsic::amdgcn_mul_i24: 6226 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6227 6228 case Intrinsic::amdgcn_log_clamp: { 6229 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6230 return SDValue(); 6231 6232 DiagnosticInfoUnsupported BadIntrin( 6233 MF.getFunction(), "intrinsic not supported on subtarget", 6234 DL.getDebugLoc()); 6235 DAG.getContext()->diagnose(BadIntrin); 6236 return DAG.getUNDEF(VT); 6237 } 6238 case Intrinsic::amdgcn_ldexp: 6239 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6240 Op.getOperand(1), Op.getOperand(2)); 6241 6242 case Intrinsic::amdgcn_fract: 6243 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6244 6245 case Intrinsic::amdgcn_class: 6246 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6247 Op.getOperand(1), Op.getOperand(2)); 6248 case Intrinsic::amdgcn_div_fmas: 6249 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6250 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6251 Op.getOperand(4)); 6252 6253 case Intrinsic::amdgcn_div_fixup: 6254 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6255 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6256 6257 case Intrinsic::amdgcn_trig_preop: 6258 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 6259 Op.getOperand(1), Op.getOperand(2)); 6260 case Intrinsic::amdgcn_div_scale: { 6261 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6262 6263 // Translate to the operands expected by the machine instruction. The 6264 // first parameter must be the same as the first instruction. 6265 SDValue Numerator = Op.getOperand(1); 6266 SDValue Denominator = Op.getOperand(2); 6267 6268 // Note this order is opposite of the machine instruction's operations, 6269 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6270 // intrinsic has the numerator as the first operand to match a normal 6271 // division operation. 6272 6273 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6274 6275 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6276 Denominator, Numerator); 6277 } 6278 case Intrinsic::amdgcn_icmp: { 6279 // There is a Pat that handles this variant, so return it as-is. 6280 if (Op.getOperand(1).getValueType() == MVT::i1 && 6281 Op.getConstantOperandVal(2) == 0 && 6282 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6283 return Op; 6284 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6285 } 6286 case Intrinsic::amdgcn_fcmp: { 6287 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6288 } 6289 case Intrinsic::amdgcn_ballot: 6290 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6291 case Intrinsic::amdgcn_fmed3: 6292 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6293 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6294 case Intrinsic::amdgcn_fdot2: 6295 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6296 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6297 Op.getOperand(4)); 6298 case Intrinsic::amdgcn_fmul_legacy: 6299 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6300 Op.getOperand(1), Op.getOperand(2)); 6301 case Intrinsic::amdgcn_sffbh: 6302 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6303 case Intrinsic::amdgcn_sbfe: 6304 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6305 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6306 case Intrinsic::amdgcn_ubfe: 6307 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6308 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6309 case Intrinsic::amdgcn_cvt_pkrtz: 6310 case Intrinsic::amdgcn_cvt_pknorm_i16: 6311 case Intrinsic::amdgcn_cvt_pknorm_u16: 6312 case Intrinsic::amdgcn_cvt_pk_i16: 6313 case Intrinsic::amdgcn_cvt_pk_u16: { 6314 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6315 EVT VT = Op.getValueType(); 6316 unsigned Opcode; 6317 6318 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6319 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6320 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6321 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6322 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6323 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6324 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6325 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6326 else 6327 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6328 6329 if (isTypeLegal(VT)) 6330 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6331 6332 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6333 Op.getOperand(1), Op.getOperand(2)); 6334 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6335 } 6336 case Intrinsic::amdgcn_fmad_ftz: 6337 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6338 Op.getOperand(2), Op.getOperand(3)); 6339 6340 case Intrinsic::amdgcn_if_break: 6341 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6342 Op->getOperand(1), Op->getOperand(2)), 0); 6343 6344 case Intrinsic::amdgcn_groupstaticsize: { 6345 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6346 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6347 return Op; 6348 6349 const Module *M = MF.getFunction().getParent(); 6350 const GlobalValue *GV = 6351 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6352 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6353 SIInstrInfo::MO_ABS32_LO); 6354 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6355 } 6356 case Intrinsic::amdgcn_is_shared: 6357 case Intrinsic::amdgcn_is_private: { 6358 SDLoc SL(Op); 6359 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6360 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6361 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6362 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6363 Op.getOperand(1)); 6364 6365 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6366 DAG.getConstant(1, SL, MVT::i32)); 6367 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6368 } 6369 case Intrinsic::amdgcn_alignbit: 6370 return DAG.getNode(ISD::FSHR, DL, VT, 6371 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6372 case Intrinsic::amdgcn_reloc_constant: { 6373 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6374 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6375 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6376 auto RelocSymbol = cast<GlobalVariable>( 6377 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6378 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6379 SIInstrInfo::MO_ABS32_LO); 6380 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6381 } 6382 default: 6383 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6384 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6385 return lowerImage(Op, ImageDimIntr, DAG); 6386 6387 return Op; 6388 } 6389 } 6390 6391 // This function computes an appropriate offset to pass to 6392 // MachineMemOperand::setOffset() based on the offset inputs to 6393 // an intrinsic. If any of the offsets are non-contstant or 6394 // if VIndex is non-zero then this function returns 0. Otherwise, 6395 // it returns the sum of VOffset, SOffset, and Offset. 6396 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6397 SDValue SOffset, 6398 SDValue Offset, 6399 SDValue VIndex = SDValue()) { 6400 6401 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6402 !isa<ConstantSDNode>(Offset)) 6403 return 0; 6404 6405 if (VIndex) { 6406 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6407 return 0; 6408 } 6409 6410 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6411 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6412 cast<ConstantSDNode>(Offset)->getSExtValue(); 6413 } 6414 6415 static unsigned getDSShaderTypeValue(const MachineFunction &MF) { 6416 switch (MF.getFunction().getCallingConv()) { 6417 case CallingConv::AMDGPU_PS: 6418 return 1; 6419 case CallingConv::AMDGPU_VS: 6420 return 2; 6421 case CallingConv::AMDGPU_GS: 6422 return 3; 6423 case CallingConv::AMDGPU_HS: 6424 case CallingConv::AMDGPU_LS: 6425 case CallingConv::AMDGPU_ES: 6426 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6427 case CallingConv::AMDGPU_CS: 6428 case CallingConv::AMDGPU_KERNEL: 6429 case CallingConv::C: 6430 case CallingConv::Fast: 6431 default: 6432 // Assume other calling conventions are various compute callable functions 6433 return 0; 6434 } 6435 } 6436 6437 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6438 SelectionDAG &DAG) const { 6439 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6440 SDLoc DL(Op); 6441 6442 switch (IntrID) { 6443 case Intrinsic::amdgcn_ds_ordered_add: 6444 case Intrinsic::amdgcn_ds_ordered_swap: { 6445 MemSDNode *M = cast<MemSDNode>(Op); 6446 SDValue Chain = M->getOperand(0); 6447 SDValue M0 = M->getOperand(2); 6448 SDValue Value = M->getOperand(3); 6449 unsigned IndexOperand = M->getConstantOperandVal(7); 6450 unsigned WaveRelease = M->getConstantOperandVal(8); 6451 unsigned WaveDone = M->getConstantOperandVal(9); 6452 6453 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6454 IndexOperand &= ~0x3f; 6455 unsigned CountDw = 0; 6456 6457 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6458 CountDw = (IndexOperand >> 24) & 0xf; 6459 IndexOperand &= ~(0xf << 24); 6460 6461 if (CountDw < 1 || CountDw > 4) { 6462 report_fatal_error( 6463 "ds_ordered_count: dword count must be between 1 and 4"); 6464 } 6465 } 6466 6467 if (IndexOperand) 6468 report_fatal_error("ds_ordered_count: bad index operand"); 6469 6470 if (WaveDone && !WaveRelease) 6471 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6472 6473 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6474 unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction()); 6475 unsigned Offset0 = OrderedCountIndex << 2; 6476 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6477 (Instruction << 4); 6478 6479 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6480 Offset1 |= (CountDw - 1) << 6; 6481 6482 unsigned Offset = Offset0 | (Offset1 << 8); 6483 6484 SDValue Ops[] = { 6485 Chain, 6486 Value, 6487 DAG.getTargetConstant(Offset, DL, MVT::i16), 6488 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6489 }; 6490 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6491 M->getVTList(), Ops, M->getMemoryVT(), 6492 M->getMemOperand()); 6493 } 6494 case Intrinsic::amdgcn_ds_fadd: { 6495 MemSDNode *M = cast<MemSDNode>(Op); 6496 unsigned Opc; 6497 switch (IntrID) { 6498 case Intrinsic::amdgcn_ds_fadd: 6499 Opc = ISD::ATOMIC_LOAD_FADD; 6500 break; 6501 } 6502 6503 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6504 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6505 M->getMemOperand()); 6506 } 6507 case Intrinsic::amdgcn_atomic_inc: 6508 case Intrinsic::amdgcn_atomic_dec: 6509 case Intrinsic::amdgcn_ds_fmin: 6510 case Intrinsic::amdgcn_ds_fmax: { 6511 MemSDNode *M = cast<MemSDNode>(Op); 6512 unsigned Opc; 6513 switch (IntrID) { 6514 case Intrinsic::amdgcn_atomic_inc: 6515 Opc = AMDGPUISD::ATOMIC_INC; 6516 break; 6517 case Intrinsic::amdgcn_atomic_dec: 6518 Opc = AMDGPUISD::ATOMIC_DEC; 6519 break; 6520 case Intrinsic::amdgcn_ds_fmin: 6521 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6522 break; 6523 case Intrinsic::amdgcn_ds_fmax: 6524 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6525 break; 6526 default: 6527 llvm_unreachable("Unknown intrinsic!"); 6528 } 6529 SDValue Ops[] = { 6530 M->getOperand(0), // Chain 6531 M->getOperand(2), // Ptr 6532 M->getOperand(3) // Value 6533 }; 6534 6535 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6536 M->getMemoryVT(), M->getMemOperand()); 6537 } 6538 case Intrinsic::amdgcn_buffer_load: 6539 case Intrinsic::amdgcn_buffer_load_format: { 6540 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6541 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6542 unsigned IdxEn = 1; 6543 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6544 IdxEn = Idx->getZExtValue() != 0; 6545 SDValue Ops[] = { 6546 Op.getOperand(0), // Chain 6547 Op.getOperand(2), // rsrc 6548 Op.getOperand(3), // vindex 6549 SDValue(), // voffset -- will be set by setBufferOffsets 6550 SDValue(), // soffset -- will be set by setBufferOffsets 6551 SDValue(), // offset -- will be set by setBufferOffsets 6552 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6553 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6554 }; 6555 6556 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6557 // We don't know the offset if vindex is non-zero, so clear it. 6558 if (IdxEn) 6559 Offset = 0; 6560 6561 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6562 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6563 6564 EVT VT = Op.getValueType(); 6565 EVT IntVT = VT.changeTypeToInteger(); 6566 auto *M = cast<MemSDNode>(Op); 6567 M->getMemOperand()->setOffset(Offset); 6568 EVT LoadVT = Op.getValueType(); 6569 6570 if (LoadVT.getScalarType() == MVT::f16) 6571 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6572 M, DAG, Ops); 6573 6574 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6575 if (LoadVT.getScalarType() == MVT::i8 || 6576 LoadVT.getScalarType() == MVT::i16) 6577 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6578 6579 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6580 M->getMemOperand(), DAG); 6581 } 6582 case Intrinsic::amdgcn_raw_buffer_load: 6583 case Intrinsic::amdgcn_raw_buffer_load_format: { 6584 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6585 6586 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6587 SDValue Ops[] = { 6588 Op.getOperand(0), // Chain 6589 Op.getOperand(2), // rsrc 6590 DAG.getConstant(0, DL, MVT::i32), // vindex 6591 Offsets.first, // voffset 6592 Op.getOperand(4), // soffset 6593 Offsets.second, // offset 6594 Op.getOperand(5), // cachepolicy, swizzled buffer 6595 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6596 }; 6597 6598 auto *M = cast<MemSDNode>(Op); 6599 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6600 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6601 } 6602 case Intrinsic::amdgcn_struct_buffer_load: 6603 case Intrinsic::amdgcn_struct_buffer_load_format: { 6604 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6605 6606 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6607 SDValue Ops[] = { 6608 Op.getOperand(0), // Chain 6609 Op.getOperand(2), // rsrc 6610 Op.getOperand(3), // vindex 6611 Offsets.first, // voffset 6612 Op.getOperand(5), // soffset 6613 Offsets.second, // offset 6614 Op.getOperand(6), // cachepolicy, swizzled buffer 6615 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6616 }; 6617 6618 auto *M = cast<MemSDNode>(Op); 6619 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6620 Ops[2])); 6621 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6622 } 6623 case Intrinsic::amdgcn_tbuffer_load: { 6624 MemSDNode *M = cast<MemSDNode>(Op); 6625 EVT LoadVT = Op.getValueType(); 6626 6627 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6628 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6629 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6630 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6631 unsigned IdxEn = 1; 6632 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6633 IdxEn = Idx->getZExtValue() != 0; 6634 SDValue Ops[] = { 6635 Op.getOperand(0), // Chain 6636 Op.getOperand(2), // rsrc 6637 Op.getOperand(3), // vindex 6638 Op.getOperand(4), // voffset 6639 Op.getOperand(5), // soffset 6640 Op.getOperand(6), // offset 6641 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6642 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6643 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6644 }; 6645 6646 if (LoadVT.getScalarType() == MVT::f16) 6647 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6648 M, DAG, Ops); 6649 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6650 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6651 DAG); 6652 } 6653 case Intrinsic::amdgcn_raw_tbuffer_load: { 6654 MemSDNode *M = cast<MemSDNode>(Op); 6655 EVT LoadVT = Op.getValueType(); 6656 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6657 6658 SDValue Ops[] = { 6659 Op.getOperand(0), // Chain 6660 Op.getOperand(2), // rsrc 6661 DAG.getConstant(0, DL, MVT::i32), // vindex 6662 Offsets.first, // voffset 6663 Op.getOperand(4), // soffset 6664 Offsets.second, // offset 6665 Op.getOperand(5), // format 6666 Op.getOperand(6), // cachepolicy, swizzled buffer 6667 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6668 }; 6669 6670 if (LoadVT.getScalarType() == MVT::f16) 6671 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6672 M, DAG, Ops); 6673 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6674 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6675 DAG); 6676 } 6677 case Intrinsic::amdgcn_struct_tbuffer_load: { 6678 MemSDNode *M = cast<MemSDNode>(Op); 6679 EVT LoadVT = Op.getValueType(); 6680 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6681 6682 SDValue Ops[] = { 6683 Op.getOperand(0), // Chain 6684 Op.getOperand(2), // rsrc 6685 Op.getOperand(3), // vindex 6686 Offsets.first, // voffset 6687 Op.getOperand(5), // soffset 6688 Offsets.second, // offset 6689 Op.getOperand(6), // format 6690 Op.getOperand(7), // cachepolicy, swizzled buffer 6691 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6692 }; 6693 6694 if (LoadVT.getScalarType() == MVT::f16) 6695 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6696 M, DAG, Ops); 6697 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6698 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6699 DAG); 6700 } 6701 case Intrinsic::amdgcn_buffer_atomic_swap: 6702 case Intrinsic::amdgcn_buffer_atomic_add: 6703 case Intrinsic::amdgcn_buffer_atomic_sub: 6704 case Intrinsic::amdgcn_buffer_atomic_smin: 6705 case Intrinsic::amdgcn_buffer_atomic_umin: 6706 case Intrinsic::amdgcn_buffer_atomic_smax: 6707 case Intrinsic::amdgcn_buffer_atomic_umax: 6708 case Intrinsic::amdgcn_buffer_atomic_and: 6709 case Intrinsic::amdgcn_buffer_atomic_or: 6710 case Intrinsic::amdgcn_buffer_atomic_xor: { 6711 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6712 unsigned IdxEn = 1; 6713 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6714 IdxEn = Idx->getZExtValue() != 0; 6715 SDValue Ops[] = { 6716 Op.getOperand(0), // Chain 6717 Op.getOperand(2), // vdata 6718 Op.getOperand(3), // rsrc 6719 Op.getOperand(4), // vindex 6720 SDValue(), // voffset -- will be set by setBufferOffsets 6721 SDValue(), // soffset -- will be set by setBufferOffsets 6722 SDValue(), // offset -- will be set by setBufferOffsets 6723 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6724 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6725 }; 6726 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6727 // We don't know the offset if vindex is non-zero, so clear it. 6728 if (IdxEn) 6729 Offset = 0; 6730 EVT VT = Op.getValueType(); 6731 6732 auto *M = cast<MemSDNode>(Op); 6733 M->getMemOperand()->setOffset(Offset); 6734 unsigned Opcode = 0; 6735 6736 switch (IntrID) { 6737 case Intrinsic::amdgcn_buffer_atomic_swap: 6738 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6739 break; 6740 case Intrinsic::amdgcn_buffer_atomic_add: 6741 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6742 break; 6743 case Intrinsic::amdgcn_buffer_atomic_sub: 6744 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6745 break; 6746 case Intrinsic::amdgcn_buffer_atomic_smin: 6747 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6748 break; 6749 case Intrinsic::amdgcn_buffer_atomic_umin: 6750 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6751 break; 6752 case Intrinsic::amdgcn_buffer_atomic_smax: 6753 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6754 break; 6755 case Intrinsic::amdgcn_buffer_atomic_umax: 6756 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6757 break; 6758 case Intrinsic::amdgcn_buffer_atomic_and: 6759 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6760 break; 6761 case Intrinsic::amdgcn_buffer_atomic_or: 6762 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6763 break; 6764 case Intrinsic::amdgcn_buffer_atomic_xor: 6765 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6766 break; 6767 default: 6768 llvm_unreachable("unhandled atomic opcode"); 6769 } 6770 6771 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6772 M->getMemOperand()); 6773 } 6774 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6775 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6776 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6777 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6778 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6779 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6780 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6781 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6782 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6783 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6784 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6785 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 6786 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6787 SDValue Ops[] = { 6788 Op.getOperand(0), // Chain 6789 Op.getOperand(2), // vdata 6790 Op.getOperand(3), // rsrc 6791 DAG.getConstant(0, DL, MVT::i32), // vindex 6792 Offsets.first, // voffset 6793 Op.getOperand(5), // soffset 6794 Offsets.second, // offset 6795 Op.getOperand(6), // cachepolicy 6796 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6797 }; 6798 EVT VT = Op.getValueType(); 6799 6800 auto *M = cast<MemSDNode>(Op); 6801 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6802 unsigned Opcode = 0; 6803 6804 switch (IntrID) { 6805 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6806 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6807 break; 6808 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6809 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6810 break; 6811 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6812 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6813 break; 6814 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6815 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6816 break; 6817 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6818 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6819 break; 6820 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6821 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6822 break; 6823 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6824 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6825 break; 6826 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6827 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6828 break; 6829 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6830 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6831 break; 6832 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6833 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6834 break; 6835 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6836 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6837 break; 6838 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 6839 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6840 break; 6841 default: 6842 llvm_unreachable("unhandled atomic opcode"); 6843 } 6844 6845 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6846 M->getMemOperand()); 6847 } 6848 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6849 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6850 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6851 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6852 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6853 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6854 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6855 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6856 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6857 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6858 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6859 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 6860 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6861 SDValue Ops[] = { 6862 Op.getOperand(0), // Chain 6863 Op.getOperand(2), // vdata 6864 Op.getOperand(3), // rsrc 6865 Op.getOperand(4), // vindex 6866 Offsets.first, // voffset 6867 Op.getOperand(6), // soffset 6868 Offsets.second, // offset 6869 Op.getOperand(7), // cachepolicy 6870 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6871 }; 6872 EVT VT = Op.getValueType(); 6873 6874 auto *M = cast<MemSDNode>(Op); 6875 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6876 Ops[3])); 6877 unsigned Opcode = 0; 6878 6879 switch (IntrID) { 6880 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6881 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6882 break; 6883 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6884 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6885 break; 6886 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6887 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6888 break; 6889 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6890 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6891 break; 6892 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6893 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6894 break; 6895 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6896 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6897 break; 6898 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6899 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6900 break; 6901 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6902 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6903 break; 6904 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6905 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6906 break; 6907 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6908 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6909 break; 6910 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6911 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6912 break; 6913 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 6914 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6915 break; 6916 default: 6917 llvm_unreachable("unhandled atomic opcode"); 6918 } 6919 6920 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6921 M->getMemOperand()); 6922 } 6923 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 6924 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6925 unsigned IdxEn = 1; 6926 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 6927 IdxEn = Idx->getZExtValue() != 0; 6928 SDValue Ops[] = { 6929 Op.getOperand(0), // Chain 6930 Op.getOperand(2), // src 6931 Op.getOperand(3), // cmp 6932 Op.getOperand(4), // rsrc 6933 Op.getOperand(5), // vindex 6934 SDValue(), // voffset -- will be set by setBufferOffsets 6935 SDValue(), // soffset -- will be set by setBufferOffsets 6936 SDValue(), // offset -- will be set by setBufferOffsets 6937 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6938 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6939 }; 6940 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 6941 // We don't know the offset if vindex is non-zero, so clear it. 6942 if (IdxEn) 6943 Offset = 0; 6944 EVT VT = Op.getValueType(); 6945 auto *M = cast<MemSDNode>(Op); 6946 M->getMemOperand()->setOffset(Offset); 6947 6948 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6949 Op->getVTList(), Ops, VT, M->getMemOperand()); 6950 } 6951 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 6952 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6953 SDValue Ops[] = { 6954 Op.getOperand(0), // Chain 6955 Op.getOperand(2), // src 6956 Op.getOperand(3), // cmp 6957 Op.getOperand(4), // rsrc 6958 DAG.getConstant(0, DL, MVT::i32), // vindex 6959 Offsets.first, // voffset 6960 Op.getOperand(6), // soffset 6961 Offsets.second, // offset 6962 Op.getOperand(7), // cachepolicy 6963 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6964 }; 6965 EVT VT = Op.getValueType(); 6966 auto *M = cast<MemSDNode>(Op); 6967 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 6968 6969 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6970 Op->getVTList(), Ops, VT, M->getMemOperand()); 6971 } 6972 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 6973 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 6974 SDValue Ops[] = { 6975 Op.getOperand(0), // Chain 6976 Op.getOperand(2), // src 6977 Op.getOperand(3), // cmp 6978 Op.getOperand(4), // rsrc 6979 Op.getOperand(5), // vindex 6980 Offsets.first, // voffset 6981 Op.getOperand(7), // soffset 6982 Offsets.second, // offset 6983 Op.getOperand(8), // cachepolicy 6984 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6985 }; 6986 EVT VT = Op.getValueType(); 6987 auto *M = cast<MemSDNode>(Op); 6988 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 6989 Ops[4])); 6990 6991 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6992 Op->getVTList(), Ops, VT, M->getMemOperand()); 6993 } 6994 6995 default: 6996 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6997 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 6998 return lowerImage(Op, ImageDimIntr, DAG); 6999 7000 return SDValue(); 7001 } 7002 } 7003 7004 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7005 // dwordx4 if on SI. 7006 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7007 SDVTList VTList, 7008 ArrayRef<SDValue> Ops, EVT MemVT, 7009 MachineMemOperand *MMO, 7010 SelectionDAG &DAG) const { 7011 EVT VT = VTList.VTs[0]; 7012 EVT WidenedVT = VT; 7013 EVT WidenedMemVT = MemVT; 7014 if (!Subtarget->hasDwordx3LoadStores() && 7015 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7016 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7017 WidenedVT.getVectorElementType(), 4); 7018 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7019 WidenedMemVT.getVectorElementType(), 4); 7020 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7021 } 7022 7023 assert(VTList.NumVTs == 2); 7024 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7025 7026 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7027 WidenedMemVT, MMO); 7028 if (WidenedVT != VT) { 7029 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7030 DAG.getVectorIdxConstant(0, DL)); 7031 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7032 } 7033 return NewOp; 7034 } 7035 7036 SDValue SITargetLowering::handleD16VData(SDValue VData, 7037 SelectionDAG &DAG) const { 7038 EVT StoreVT = VData.getValueType(); 7039 7040 // No change for f16 and legal vector D16 types. 7041 if (!StoreVT.isVector()) 7042 return VData; 7043 7044 SDLoc DL(VData); 7045 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 7046 7047 if (Subtarget->hasUnpackedD16VMem()) { 7048 // We need to unpack the packed data to store. 7049 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7050 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7051 7052 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 7053 StoreVT.getVectorNumElements()); 7054 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7055 return DAG.UnrollVectorOp(ZExt.getNode()); 7056 } 7057 7058 assert(isTypeLegal(StoreVT)); 7059 return VData; 7060 } 7061 7062 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7063 SelectionDAG &DAG) const { 7064 SDLoc DL(Op); 7065 SDValue Chain = Op.getOperand(0); 7066 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7067 MachineFunction &MF = DAG.getMachineFunction(); 7068 7069 switch (IntrinsicID) { 7070 case Intrinsic::amdgcn_exp_compr: { 7071 SDValue Src0 = Op.getOperand(4); 7072 SDValue Src1 = Op.getOperand(5); 7073 // Hack around illegal type on SI by directly selecting it. 7074 if (isTypeLegal(Src0.getValueType())) 7075 return SDValue(); 7076 7077 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7078 SDValue Undef = DAG.getUNDEF(MVT::f32); 7079 const SDValue Ops[] = { 7080 Op.getOperand(2), // tgt 7081 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7082 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7083 Undef, // src2 7084 Undef, // src3 7085 Op.getOperand(7), // vm 7086 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7087 Op.getOperand(3), // en 7088 Op.getOperand(0) // Chain 7089 }; 7090 7091 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7092 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7093 } 7094 case Intrinsic::amdgcn_s_barrier: { 7095 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7096 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7097 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7098 if (WGSize <= ST.getWavefrontSize()) 7099 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7100 Op.getOperand(0)), 0); 7101 } 7102 return SDValue(); 7103 }; 7104 case Intrinsic::amdgcn_tbuffer_store: { 7105 SDValue VData = Op.getOperand(2); 7106 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7107 if (IsD16) 7108 VData = handleD16VData(VData, DAG); 7109 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7110 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7111 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7112 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7113 unsigned IdxEn = 1; 7114 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7115 IdxEn = Idx->getZExtValue() != 0; 7116 SDValue Ops[] = { 7117 Chain, 7118 VData, // vdata 7119 Op.getOperand(3), // rsrc 7120 Op.getOperand(4), // vindex 7121 Op.getOperand(5), // voffset 7122 Op.getOperand(6), // soffset 7123 Op.getOperand(7), // offset 7124 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7125 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7126 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7127 }; 7128 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7129 AMDGPUISD::TBUFFER_STORE_FORMAT; 7130 MemSDNode *M = cast<MemSDNode>(Op); 7131 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7132 M->getMemoryVT(), M->getMemOperand()); 7133 } 7134 7135 case Intrinsic::amdgcn_struct_tbuffer_store: { 7136 SDValue VData = Op.getOperand(2); 7137 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7138 if (IsD16) 7139 VData = handleD16VData(VData, DAG); 7140 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7141 SDValue Ops[] = { 7142 Chain, 7143 VData, // vdata 7144 Op.getOperand(3), // rsrc 7145 Op.getOperand(4), // vindex 7146 Offsets.first, // voffset 7147 Op.getOperand(6), // soffset 7148 Offsets.second, // offset 7149 Op.getOperand(7), // format 7150 Op.getOperand(8), // cachepolicy, swizzled buffer 7151 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7152 }; 7153 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7154 AMDGPUISD::TBUFFER_STORE_FORMAT; 7155 MemSDNode *M = cast<MemSDNode>(Op); 7156 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7157 M->getMemoryVT(), M->getMemOperand()); 7158 } 7159 7160 case Intrinsic::amdgcn_raw_tbuffer_store: { 7161 SDValue VData = Op.getOperand(2); 7162 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7163 if (IsD16) 7164 VData = handleD16VData(VData, DAG); 7165 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7166 SDValue Ops[] = { 7167 Chain, 7168 VData, // vdata 7169 Op.getOperand(3), // rsrc 7170 DAG.getConstant(0, DL, MVT::i32), // vindex 7171 Offsets.first, // voffset 7172 Op.getOperand(5), // soffset 7173 Offsets.second, // offset 7174 Op.getOperand(6), // format 7175 Op.getOperand(7), // cachepolicy, swizzled buffer 7176 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7177 }; 7178 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7179 AMDGPUISD::TBUFFER_STORE_FORMAT; 7180 MemSDNode *M = cast<MemSDNode>(Op); 7181 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7182 M->getMemoryVT(), M->getMemOperand()); 7183 } 7184 7185 case Intrinsic::amdgcn_buffer_store: 7186 case Intrinsic::amdgcn_buffer_store_format: { 7187 SDValue VData = Op.getOperand(2); 7188 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7189 if (IsD16) 7190 VData = handleD16VData(VData, DAG); 7191 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7192 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7193 unsigned IdxEn = 1; 7194 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7195 IdxEn = Idx->getZExtValue() != 0; 7196 SDValue Ops[] = { 7197 Chain, 7198 VData, 7199 Op.getOperand(3), // rsrc 7200 Op.getOperand(4), // vindex 7201 SDValue(), // voffset -- will be set by setBufferOffsets 7202 SDValue(), // soffset -- will be set by setBufferOffsets 7203 SDValue(), // offset -- will be set by setBufferOffsets 7204 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7205 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7206 }; 7207 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7208 // We don't know the offset if vindex is non-zero, so clear it. 7209 if (IdxEn) 7210 Offset = 0; 7211 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7212 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7213 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7214 MemSDNode *M = cast<MemSDNode>(Op); 7215 M->getMemOperand()->setOffset(Offset); 7216 7217 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7218 EVT VDataType = VData.getValueType().getScalarType(); 7219 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7220 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7221 7222 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7223 M->getMemoryVT(), M->getMemOperand()); 7224 } 7225 7226 case Intrinsic::amdgcn_raw_buffer_store: 7227 case Intrinsic::amdgcn_raw_buffer_store_format: { 7228 const bool IsFormat = 7229 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7230 7231 SDValue VData = Op.getOperand(2); 7232 EVT VDataVT = VData.getValueType(); 7233 EVT EltType = VDataVT.getScalarType(); 7234 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7235 if (IsD16) 7236 VData = handleD16VData(VData, DAG); 7237 7238 if (!isTypeLegal(VDataVT)) { 7239 VData = 7240 DAG.getNode(ISD::BITCAST, DL, 7241 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7242 } 7243 7244 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7245 SDValue Ops[] = { 7246 Chain, 7247 VData, 7248 Op.getOperand(3), // rsrc 7249 DAG.getConstant(0, DL, MVT::i32), // vindex 7250 Offsets.first, // voffset 7251 Op.getOperand(5), // soffset 7252 Offsets.second, // offset 7253 Op.getOperand(6), // cachepolicy, swizzled buffer 7254 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7255 }; 7256 unsigned Opc = 7257 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7258 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7259 MemSDNode *M = cast<MemSDNode>(Op); 7260 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7261 7262 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7263 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7264 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7265 7266 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7267 M->getMemoryVT(), M->getMemOperand()); 7268 } 7269 7270 case Intrinsic::amdgcn_struct_buffer_store: 7271 case Intrinsic::amdgcn_struct_buffer_store_format: { 7272 const bool IsFormat = 7273 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7274 7275 SDValue VData = Op.getOperand(2); 7276 EVT VDataVT = VData.getValueType(); 7277 EVT EltType = VDataVT.getScalarType(); 7278 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7279 7280 if (IsD16) 7281 VData = handleD16VData(VData, DAG); 7282 7283 if (!isTypeLegal(VDataVT)) { 7284 VData = 7285 DAG.getNode(ISD::BITCAST, DL, 7286 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7287 } 7288 7289 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7290 SDValue Ops[] = { 7291 Chain, 7292 VData, 7293 Op.getOperand(3), // rsrc 7294 Op.getOperand(4), // vindex 7295 Offsets.first, // voffset 7296 Op.getOperand(6), // soffset 7297 Offsets.second, // offset 7298 Op.getOperand(7), // cachepolicy, swizzled buffer 7299 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7300 }; 7301 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7302 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7303 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7304 MemSDNode *M = cast<MemSDNode>(Op); 7305 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7306 Ops[3])); 7307 7308 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7309 EVT VDataType = VData.getValueType().getScalarType(); 7310 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7311 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7312 7313 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7314 M->getMemoryVT(), M->getMemOperand()); 7315 } 7316 7317 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7318 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7319 unsigned IdxEn = 1; 7320 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7321 IdxEn = Idx->getZExtValue() != 0; 7322 SDValue Ops[] = { 7323 Chain, 7324 Op.getOperand(2), // vdata 7325 Op.getOperand(3), // rsrc 7326 Op.getOperand(4), // vindex 7327 SDValue(), // voffset -- will be set by setBufferOffsets 7328 SDValue(), // soffset -- will be set by setBufferOffsets 7329 SDValue(), // offset -- will be set by setBufferOffsets 7330 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7331 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7332 }; 7333 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7334 // We don't know the offset if vindex is non-zero, so clear it. 7335 if (IdxEn) 7336 Offset = 0; 7337 EVT VT = Op.getOperand(2).getValueType(); 7338 7339 auto *M = cast<MemSDNode>(Op); 7340 M->getMemOperand()->setOffset(Offset); 7341 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 7342 : AMDGPUISD::BUFFER_ATOMIC_FADD; 7343 7344 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7345 M->getMemOperand()); 7346 } 7347 7348 case Intrinsic::amdgcn_global_atomic_fadd: { 7349 SDValue Ops[] = { 7350 Chain, 7351 Op.getOperand(2), // ptr 7352 Op.getOperand(3) // vdata 7353 }; 7354 EVT VT = Op.getOperand(3).getValueType(); 7355 7356 auto *M = cast<MemSDNode>(Op); 7357 if (VT.isVector()) { 7358 return DAG.getMemIntrinsicNode( 7359 AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT, 7360 M->getMemOperand()); 7361 } 7362 7363 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7364 DAG.getVTList(VT, MVT::Other), Ops, 7365 M->getMemOperand()).getValue(1); 7366 } 7367 case Intrinsic::amdgcn_end_cf: 7368 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7369 Op->getOperand(2), Chain), 0); 7370 7371 default: { 7372 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7373 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7374 return lowerImage(Op, ImageDimIntr, DAG); 7375 7376 return Op; 7377 } 7378 } 7379 } 7380 7381 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7382 // offset (the offset that is included in bounds checking and swizzling, to be 7383 // split between the instruction's voffset and immoffset fields) and soffset 7384 // (the offset that is excluded from bounds checking and swizzling, to go in 7385 // the instruction's soffset field). This function takes the first kind of 7386 // offset and figures out how to split it between voffset and immoffset. 7387 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7388 SDValue Offset, SelectionDAG &DAG) const { 7389 SDLoc DL(Offset); 7390 const unsigned MaxImm = 4095; 7391 SDValue N0 = Offset; 7392 ConstantSDNode *C1 = nullptr; 7393 7394 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7395 N0 = SDValue(); 7396 else if (DAG.isBaseWithConstantOffset(N0)) { 7397 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7398 N0 = N0.getOperand(0); 7399 } 7400 7401 if (C1) { 7402 unsigned ImmOffset = C1->getZExtValue(); 7403 // If the immediate value is too big for the immoffset field, put the value 7404 // and -4096 into the immoffset field so that the value that is copied/added 7405 // for the voffset field is a multiple of 4096, and it stands more chance 7406 // of being CSEd with the copy/add for another similar load/store. 7407 // However, do not do that rounding down to a multiple of 4096 if that is a 7408 // negative number, as it appears to be illegal to have a negative offset 7409 // in the vgpr, even if adding the immediate offset makes it positive. 7410 unsigned Overflow = ImmOffset & ~MaxImm; 7411 ImmOffset -= Overflow; 7412 if ((int32_t)Overflow < 0) { 7413 Overflow += ImmOffset; 7414 ImmOffset = 0; 7415 } 7416 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7417 if (Overflow) { 7418 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7419 if (!N0) 7420 N0 = OverflowVal; 7421 else { 7422 SDValue Ops[] = { N0, OverflowVal }; 7423 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7424 } 7425 } 7426 } 7427 if (!N0) 7428 N0 = DAG.getConstant(0, DL, MVT::i32); 7429 if (!C1) 7430 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7431 return {N0, SDValue(C1, 0)}; 7432 } 7433 7434 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7435 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7436 // pointed to by Offsets. 7437 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7438 SelectionDAG &DAG, SDValue *Offsets, 7439 unsigned Align) const { 7440 SDLoc DL(CombinedOffset); 7441 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7442 uint32_t Imm = C->getZExtValue(); 7443 uint32_t SOffset, ImmOffset; 7444 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 7445 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7446 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7447 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7448 return SOffset + ImmOffset; 7449 } 7450 } 7451 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7452 SDValue N0 = CombinedOffset.getOperand(0); 7453 SDValue N1 = CombinedOffset.getOperand(1); 7454 uint32_t SOffset, ImmOffset; 7455 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7456 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7457 Subtarget, Align)) { 7458 Offsets[0] = N0; 7459 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7460 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7461 return 0; 7462 } 7463 } 7464 Offsets[0] = CombinedOffset; 7465 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7466 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7467 return 0; 7468 } 7469 7470 // Handle 8 bit and 16 bit buffer loads 7471 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7472 EVT LoadVT, SDLoc DL, 7473 ArrayRef<SDValue> Ops, 7474 MemSDNode *M) const { 7475 EVT IntVT = LoadVT.changeTypeToInteger(); 7476 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7477 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7478 7479 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7480 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7481 Ops, IntVT, 7482 M->getMemOperand()); 7483 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7484 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7485 7486 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7487 } 7488 7489 // Handle 8 bit and 16 bit buffer stores 7490 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7491 EVT VDataType, SDLoc DL, 7492 SDValue Ops[], 7493 MemSDNode *M) const { 7494 if (VDataType == MVT::f16) 7495 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7496 7497 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7498 Ops[1] = BufferStoreExt; 7499 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7500 AMDGPUISD::BUFFER_STORE_SHORT; 7501 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7502 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7503 M->getMemOperand()); 7504 } 7505 7506 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7507 ISD::LoadExtType ExtType, SDValue Op, 7508 const SDLoc &SL, EVT VT) { 7509 if (VT.bitsLT(Op.getValueType())) 7510 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7511 7512 switch (ExtType) { 7513 case ISD::SEXTLOAD: 7514 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7515 case ISD::ZEXTLOAD: 7516 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7517 case ISD::EXTLOAD: 7518 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7519 case ISD::NON_EXTLOAD: 7520 return Op; 7521 } 7522 7523 llvm_unreachable("invalid ext type"); 7524 } 7525 7526 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7527 SelectionDAG &DAG = DCI.DAG; 7528 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7529 return SDValue(); 7530 7531 // FIXME: Constant loads should all be marked invariant. 7532 unsigned AS = Ld->getAddressSpace(); 7533 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7534 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7535 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7536 return SDValue(); 7537 7538 // Don't do this early, since it may interfere with adjacent load merging for 7539 // illegal types. We can avoid losing alignment information for exotic types 7540 // pre-legalize. 7541 EVT MemVT = Ld->getMemoryVT(); 7542 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7543 MemVT.getSizeInBits() >= 32) 7544 return SDValue(); 7545 7546 SDLoc SL(Ld); 7547 7548 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7549 "unexpected vector extload"); 7550 7551 // TODO: Drop only high part of range. 7552 SDValue Ptr = Ld->getBasePtr(); 7553 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7554 MVT::i32, SL, Ld->getChain(), Ptr, 7555 Ld->getOffset(), 7556 Ld->getPointerInfo(), MVT::i32, 7557 Ld->getAlignment(), 7558 Ld->getMemOperand()->getFlags(), 7559 Ld->getAAInfo(), 7560 nullptr); // Drop ranges 7561 7562 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7563 if (MemVT.isFloatingPoint()) { 7564 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7565 "unexpected fp extload"); 7566 TruncVT = MemVT.changeTypeToInteger(); 7567 } 7568 7569 SDValue Cvt = NewLoad; 7570 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7571 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7572 DAG.getValueType(TruncVT)); 7573 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7574 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7575 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7576 } else { 7577 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7578 } 7579 7580 EVT VT = Ld->getValueType(0); 7581 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7582 7583 DCI.AddToWorklist(Cvt.getNode()); 7584 7585 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7586 // the appropriate extension from the 32-bit load. 7587 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7588 DCI.AddToWorklist(Cvt.getNode()); 7589 7590 // Handle conversion back to floating point if necessary. 7591 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7592 7593 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7594 } 7595 7596 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7597 SDLoc DL(Op); 7598 LoadSDNode *Load = cast<LoadSDNode>(Op); 7599 ISD::LoadExtType ExtType = Load->getExtensionType(); 7600 EVT MemVT = Load->getMemoryVT(); 7601 7602 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7603 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7604 return SDValue(); 7605 7606 // FIXME: Copied from PPC 7607 // First, load into 32 bits, then truncate to 1 bit. 7608 7609 SDValue Chain = Load->getChain(); 7610 SDValue BasePtr = Load->getBasePtr(); 7611 MachineMemOperand *MMO = Load->getMemOperand(); 7612 7613 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7614 7615 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7616 BasePtr, RealMemVT, MMO); 7617 7618 if (!MemVT.isVector()) { 7619 SDValue Ops[] = { 7620 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7621 NewLD.getValue(1) 7622 }; 7623 7624 return DAG.getMergeValues(Ops, DL); 7625 } 7626 7627 SmallVector<SDValue, 3> Elts; 7628 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7629 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7630 DAG.getConstant(I, DL, MVT::i32)); 7631 7632 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7633 } 7634 7635 SDValue Ops[] = { 7636 DAG.getBuildVector(MemVT, DL, Elts), 7637 NewLD.getValue(1) 7638 }; 7639 7640 return DAG.getMergeValues(Ops, DL); 7641 } 7642 7643 if (!MemVT.isVector()) 7644 return SDValue(); 7645 7646 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7647 "Custom lowering for non-i32 vectors hasn't been implemented."); 7648 7649 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7650 MemVT, *Load->getMemOperand())) { 7651 SDValue Ops[2]; 7652 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7653 return DAG.getMergeValues(Ops, DL); 7654 } 7655 7656 unsigned Alignment = Load->getAlignment(); 7657 unsigned AS = Load->getAddressSpace(); 7658 if (Subtarget->hasLDSMisalignedBug() && 7659 AS == AMDGPUAS::FLAT_ADDRESS && 7660 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7661 return SplitVectorLoad(Op, DAG); 7662 } 7663 7664 MachineFunction &MF = DAG.getMachineFunction(); 7665 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7666 // If there is a possibilty that flat instruction access scratch memory 7667 // then we need to use the same legalization rules we use for private. 7668 if (AS == AMDGPUAS::FLAT_ADDRESS && 7669 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7670 AS = MFI->hasFlatScratchInit() ? 7671 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7672 7673 unsigned NumElements = MemVT.getVectorNumElements(); 7674 7675 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7676 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7677 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7678 if (MemVT.isPow2VectorType()) 7679 return SDValue(); 7680 if (NumElements == 3) 7681 return WidenVectorLoad(Op, DAG); 7682 return SplitVectorLoad(Op, DAG); 7683 } 7684 // Non-uniform loads will be selected to MUBUF instructions, so they 7685 // have the same legalization requirements as global and private 7686 // loads. 7687 // 7688 } 7689 7690 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7691 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7692 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7693 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7694 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 7695 Alignment >= 4 && NumElements < 32) { 7696 if (MemVT.isPow2VectorType()) 7697 return SDValue(); 7698 if (NumElements == 3) 7699 return WidenVectorLoad(Op, DAG); 7700 return SplitVectorLoad(Op, DAG); 7701 } 7702 // Non-uniform loads will be selected to MUBUF instructions, so they 7703 // have the same legalization requirements as global and private 7704 // loads. 7705 // 7706 } 7707 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7708 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7709 AS == AMDGPUAS::GLOBAL_ADDRESS || 7710 AS == AMDGPUAS::FLAT_ADDRESS) { 7711 if (NumElements > 4) 7712 return SplitVectorLoad(Op, DAG); 7713 // v3 loads not supported on SI. 7714 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7715 return WidenVectorLoad(Op, DAG); 7716 // v3 and v4 loads are supported for private and global memory. 7717 return SDValue(); 7718 } 7719 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7720 // Depending on the setting of the private_element_size field in the 7721 // resource descriptor, we can only make private accesses up to a certain 7722 // size. 7723 switch (Subtarget->getMaxPrivateElementSize()) { 7724 case 4: { 7725 SDValue Ops[2]; 7726 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7727 return DAG.getMergeValues(Ops, DL); 7728 } 7729 case 8: 7730 if (NumElements > 2) 7731 return SplitVectorLoad(Op, DAG); 7732 return SDValue(); 7733 case 16: 7734 // Same as global/flat 7735 if (NumElements > 4) 7736 return SplitVectorLoad(Op, DAG); 7737 // v3 loads not supported on SI. 7738 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7739 return WidenVectorLoad(Op, DAG); 7740 return SDValue(); 7741 default: 7742 llvm_unreachable("unsupported private_element_size"); 7743 } 7744 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7745 // Use ds_read_b128 if possible. 7746 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7747 MemVT.getStoreSize() == 16) 7748 return SDValue(); 7749 7750 if (NumElements > 2) 7751 return SplitVectorLoad(Op, DAG); 7752 7753 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7754 // address is negative, then the instruction is incorrectly treated as 7755 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7756 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7757 // load later in the SILoadStoreOptimizer. 7758 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7759 NumElements == 2 && MemVT.getStoreSize() == 8 && 7760 Load->getAlignment() < 8) { 7761 return SplitVectorLoad(Op, DAG); 7762 } 7763 } 7764 return SDValue(); 7765 } 7766 7767 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7768 EVT VT = Op.getValueType(); 7769 assert(VT.getSizeInBits() == 64); 7770 7771 SDLoc DL(Op); 7772 SDValue Cond = Op.getOperand(0); 7773 7774 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7775 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7776 7777 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7778 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7779 7780 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7781 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7782 7783 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7784 7785 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7786 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7787 7788 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7789 7790 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7791 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7792 } 7793 7794 // Catch division cases where we can use shortcuts with rcp and rsq 7795 // instructions. 7796 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7797 SelectionDAG &DAG) const { 7798 SDLoc SL(Op); 7799 SDValue LHS = Op.getOperand(0); 7800 SDValue RHS = Op.getOperand(1); 7801 EVT VT = Op.getValueType(); 7802 const SDNodeFlags Flags = Op->getFlags(); 7803 7804 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 7805 Flags.hasApproximateFuncs(); 7806 7807 // Without !fpmath accuracy information, we can't do more because we don't 7808 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 7809 if (!AllowInaccurateRcp) 7810 return SDValue(); 7811 7812 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7813 if (CLHS->isExactlyValue(1.0)) { 7814 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7815 // the CI documentation has a worst case error of 1 ulp. 7816 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7817 // use it as long as we aren't trying to use denormals. 7818 // 7819 // v_rcp_f16 and v_rsq_f16 DO support denormals. 7820 7821 // 1.0 / sqrt(x) -> rsq(x) 7822 7823 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 7824 // error seems really high at 2^29 ULP. 7825 if (RHS.getOpcode() == ISD::FSQRT) 7826 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 7827 7828 // 1.0 / x -> rcp(x) 7829 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7830 } 7831 7832 // Same as for 1.0, but expand the sign out of the constant. 7833 if (CLHS->isExactlyValue(-1.0)) { 7834 // -1.0 / x -> rcp (fneg x) 7835 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7836 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 7837 } 7838 } 7839 7840 // Turn into multiply by the reciprocal. 7841 // x / y -> x * (1.0 / y) 7842 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7843 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 7844 } 7845 7846 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7847 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 7848 if (GlueChain->getNumValues() <= 1) { 7849 return DAG.getNode(Opcode, SL, VT, A, B); 7850 } 7851 7852 assert(GlueChain->getNumValues() == 3); 7853 7854 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7855 switch (Opcode) { 7856 default: llvm_unreachable("no chain equivalent for opcode"); 7857 case ISD::FMUL: 7858 Opcode = AMDGPUISD::FMUL_W_CHAIN; 7859 break; 7860 } 7861 7862 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 7863 GlueChain.getValue(2)); 7864 } 7865 7866 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7867 EVT VT, SDValue A, SDValue B, SDValue C, 7868 SDValue GlueChain) { 7869 if (GlueChain->getNumValues() <= 1) { 7870 return DAG.getNode(Opcode, SL, VT, A, B, C); 7871 } 7872 7873 assert(GlueChain->getNumValues() == 3); 7874 7875 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7876 switch (Opcode) { 7877 default: llvm_unreachable("no chain equivalent for opcode"); 7878 case ISD::FMA: 7879 Opcode = AMDGPUISD::FMA_W_CHAIN; 7880 break; 7881 } 7882 7883 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 7884 GlueChain.getValue(2)); 7885 } 7886 7887 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 7888 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7889 return FastLowered; 7890 7891 SDLoc SL(Op); 7892 SDValue Src0 = Op.getOperand(0); 7893 SDValue Src1 = Op.getOperand(1); 7894 7895 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 7896 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 7897 7898 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 7899 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 7900 7901 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 7902 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 7903 7904 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 7905 } 7906 7907 // Faster 2.5 ULP division that does not support denormals. 7908 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 7909 SDLoc SL(Op); 7910 SDValue LHS = Op.getOperand(1); 7911 SDValue RHS = Op.getOperand(2); 7912 7913 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 7914 7915 const APFloat K0Val(BitsToFloat(0x6f800000)); 7916 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 7917 7918 const APFloat K1Val(BitsToFloat(0x2f800000)); 7919 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 7920 7921 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7922 7923 EVT SetCCVT = 7924 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 7925 7926 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 7927 7928 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 7929 7930 // TODO: Should this propagate fast-math-flags? 7931 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 7932 7933 // rcp does not support denormals. 7934 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 7935 7936 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 7937 7938 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 7939 } 7940 7941 // Returns immediate value for setting the F32 denorm mode when using the 7942 // S_DENORM_MODE instruction. 7943 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 7944 const SDLoc &SL, const GCNSubtarget *ST) { 7945 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 7946 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 7947 ? FP_DENORM_FLUSH_NONE 7948 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 7949 7950 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 7951 return DAG.getTargetConstant(Mode, SL, MVT::i32); 7952 } 7953 7954 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 7955 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7956 return FastLowered; 7957 7958 SDLoc SL(Op); 7959 SDValue LHS = Op.getOperand(0); 7960 SDValue RHS = Op.getOperand(1); 7961 7962 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7963 7964 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 7965 7966 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7967 RHS, RHS, LHS); 7968 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7969 LHS, RHS, LHS); 7970 7971 // Denominator is scaled to not be denormal, so using rcp is ok. 7972 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 7973 DenominatorScaled); 7974 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 7975 DenominatorScaled); 7976 7977 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 7978 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 7979 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 7980 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 7981 7982 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 7983 7984 if (!HasFP32Denormals) { 7985 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 7986 7987 SDNode *EnableDenorm; 7988 if (Subtarget->hasDenormModeInst()) { 7989 const SDValue EnableDenormValue = 7990 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 7991 7992 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 7993 DAG.getEntryNode(), EnableDenormValue).getNode(); 7994 } else { 7995 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 7996 SL, MVT::i32); 7997 EnableDenorm = 7998 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 7999 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8000 } 8001 8002 SDValue Ops[3] = { 8003 NegDivScale0, 8004 SDValue(EnableDenorm, 0), 8005 SDValue(EnableDenorm, 1) 8006 }; 8007 8008 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8009 } 8010 8011 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8012 ApproxRcp, One, NegDivScale0); 8013 8014 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8015 ApproxRcp, Fma0); 8016 8017 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8018 Fma1, Fma1); 8019 8020 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8021 NumeratorScaled, Mul); 8022 8023 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 8024 8025 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8026 NumeratorScaled, Fma3); 8027 8028 if (!HasFP32Denormals) { 8029 SDNode *DisableDenorm; 8030 if (Subtarget->hasDenormModeInst()) { 8031 const SDValue DisableDenormValue = 8032 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8033 8034 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8035 Fma4.getValue(1), DisableDenormValue, 8036 Fma4.getValue(2)).getNode(); 8037 } else { 8038 const SDValue DisableDenormValue = 8039 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8040 8041 DisableDenorm = DAG.getMachineNode( 8042 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8043 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8044 } 8045 8046 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8047 SDValue(DisableDenorm, 0), DAG.getRoot()); 8048 DAG.setRoot(OutputChain); 8049 } 8050 8051 SDValue Scale = NumeratorScaled.getValue(1); 8052 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8053 Fma4, Fma1, Fma3, Scale); 8054 8055 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 8056 } 8057 8058 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8059 if (DAG.getTarget().Options.UnsafeFPMath) 8060 return lowerFastUnsafeFDIV(Op, DAG); 8061 8062 SDLoc SL(Op); 8063 SDValue X = Op.getOperand(0); 8064 SDValue Y = Op.getOperand(1); 8065 8066 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8067 8068 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8069 8070 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8071 8072 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8073 8074 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8075 8076 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8077 8078 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8079 8080 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8081 8082 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8083 8084 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8085 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8086 8087 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8088 NegDivScale0, Mul, DivScale1); 8089 8090 SDValue Scale; 8091 8092 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8093 // Workaround a hardware bug on SI where the condition output from div_scale 8094 // is not usable. 8095 8096 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8097 8098 // Figure out if the scale to use for div_fmas. 8099 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8100 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8101 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8102 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8103 8104 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8105 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8106 8107 SDValue Scale0Hi 8108 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8109 SDValue Scale1Hi 8110 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8111 8112 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8113 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8114 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8115 } else { 8116 Scale = DivScale1.getValue(1); 8117 } 8118 8119 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8120 Fma4, Fma3, Mul, Scale); 8121 8122 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8123 } 8124 8125 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8126 EVT VT = Op.getValueType(); 8127 8128 if (VT == MVT::f32) 8129 return LowerFDIV32(Op, DAG); 8130 8131 if (VT == MVT::f64) 8132 return LowerFDIV64(Op, DAG); 8133 8134 if (VT == MVT::f16) 8135 return LowerFDIV16(Op, DAG); 8136 8137 llvm_unreachable("Unexpected type for fdiv"); 8138 } 8139 8140 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8141 SDLoc DL(Op); 8142 StoreSDNode *Store = cast<StoreSDNode>(Op); 8143 EVT VT = Store->getMemoryVT(); 8144 8145 if (VT == MVT::i1) { 8146 return DAG.getTruncStore(Store->getChain(), DL, 8147 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8148 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8149 } 8150 8151 assert(VT.isVector() && 8152 Store->getValue().getValueType().getScalarType() == MVT::i32); 8153 8154 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8155 VT, *Store->getMemOperand())) { 8156 return expandUnalignedStore(Store, DAG); 8157 } 8158 8159 unsigned AS = Store->getAddressSpace(); 8160 if (Subtarget->hasLDSMisalignedBug() && 8161 AS == AMDGPUAS::FLAT_ADDRESS && 8162 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8163 return SplitVectorStore(Op, DAG); 8164 } 8165 8166 MachineFunction &MF = DAG.getMachineFunction(); 8167 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8168 // If there is a possibilty that flat instruction access scratch memory 8169 // then we need to use the same legalization rules we use for private. 8170 if (AS == AMDGPUAS::FLAT_ADDRESS && 8171 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8172 AS = MFI->hasFlatScratchInit() ? 8173 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8174 8175 unsigned NumElements = VT.getVectorNumElements(); 8176 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8177 AS == AMDGPUAS::FLAT_ADDRESS) { 8178 if (NumElements > 4) 8179 return SplitVectorStore(Op, DAG); 8180 // v3 stores not supported on SI. 8181 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8182 return SplitVectorStore(Op, DAG); 8183 return SDValue(); 8184 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8185 switch (Subtarget->getMaxPrivateElementSize()) { 8186 case 4: 8187 return scalarizeVectorStore(Store, DAG); 8188 case 8: 8189 if (NumElements > 2) 8190 return SplitVectorStore(Op, DAG); 8191 return SDValue(); 8192 case 16: 8193 if (NumElements > 4 || NumElements == 3) 8194 return SplitVectorStore(Op, DAG); 8195 return SDValue(); 8196 default: 8197 llvm_unreachable("unsupported private_element_size"); 8198 } 8199 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8200 // Use ds_write_b128 if possible. 8201 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 8202 VT.getStoreSize() == 16 && NumElements != 3) 8203 return SDValue(); 8204 8205 if (NumElements > 2) 8206 return SplitVectorStore(Op, DAG); 8207 8208 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8209 // address is negative, then the instruction is incorrectly treated as 8210 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8211 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8212 // store later in the SILoadStoreOptimizer. 8213 if (!Subtarget->hasUsableDSOffset() && 8214 NumElements == 2 && VT.getStoreSize() == 8 && 8215 Store->getAlignment() < 8) { 8216 return SplitVectorStore(Op, DAG); 8217 } 8218 8219 return SDValue(); 8220 } else { 8221 llvm_unreachable("unhandled address space"); 8222 } 8223 } 8224 8225 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8226 SDLoc DL(Op); 8227 EVT VT = Op.getValueType(); 8228 SDValue Arg = Op.getOperand(0); 8229 SDValue TrigVal; 8230 8231 // TODO: Should this propagate fast-math-flags? 8232 8233 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT); 8234 8235 if (Subtarget->hasTrigReducedRange()) { 8236 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 8237 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal); 8238 } else { 8239 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 8240 } 8241 8242 switch (Op.getOpcode()) { 8243 case ISD::FCOS: 8244 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal); 8245 case ISD::FSIN: 8246 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal); 8247 default: 8248 llvm_unreachable("Wrong trig opcode"); 8249 } 8250 } 8251 8252 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8253 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8254 assert(AtomicNode->isCompareAndSwap()); 8255 unsigned AS = AtomicNode->getAddressSpace(); 8256 8257 // No custom lowering required for local address space 8258 if (!isFlatGlobalAddrSpace(AS)) 8259 return Op; 8260 8261 // Non-local address space requires custom lowering for atomic compare 8262 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8263 SDLoc DL(Op); 8264 SDValue ChainIn = Op.getOperand(0); 8265 SDValue Addr = Op.getOperand(1); 8266 SDValue Old = Op.getOperand(2); 8267 SDValue New = Op.getOperand(3); 8268 EVT VT = Op.getValueType(); 8269 MVT SimpleVT = VT.getSimpleVT(); 8270 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8271 8272 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8273 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8274 8275 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8276 Ops, VT, AtomicNode->getMemOperand()); 8277 } 8278 8279 //===----------------------------------------------------------------------===// 8280 // Custom DAG optimizations 8281 //===----------------------------------------------------------------------===// 8282 8283 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8284 DAGCombinerInfo &DCI) const { 8285 EVT VT = N->getValueType(0); 8286 EVT ScalarVT = VT.getScalarType(); 8287 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8288 return SDValue(); 8289 8290 SelectionDAG &DAG = DCI.DAG; 8291 SDLoc DL(N); 8292 8293 SDValue Src = N->getOperand(0); 8294 EVT SrcVT = Src.getValueType(); 8295 8296 // TODO: We could try to match extracting the higher bytes, which would be 8297 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8298 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8299 // about in practice. 8300 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8301 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8302 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8303 DCI.AddToWorklist(Cvt.getNode()); 8304 8305 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8306 if (ScalarVT != MVT::f32) { 8307 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8308 DAG.getTargetConstant(0, DL, MVT::i32)); 8309 } 8310 return Cvt; 8311 } 8312 } 8313 8314 return SDValue(); 8315 } 8316 8317 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8318 8319 // This is a variant of 8320 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8321 // 8322 // The normal DAG combiner will do this, but only if the add has one use since 8323 // that would increase the number of instructions. 8324 // 8325 // This prevents us from seeing a constant offset that can be folded into a 8326 // memory instruction's addressing mode. If we know the resulting add offset of 8327 // a pointer can be folded into an addressing offset, we can replace the pointer 8328 // operand with the add of new constant offset. This eliminates one of the uses, 8329 // and may allow the remaining use to also be simplified. 8330 // 8331 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8332 unsigned AddrSpace, 8333 EVT MemVT, 8334 DAGCombinerInfo &DCI) const { 8335 SDValue N0 = N->getOperand(0); 8336 SDValue N1 = N->getOperand(1); 8337 8338 // We only do this to handle cases where it's profitable when there are 8339 // multiple uses of the add, so defer to the standard combine. 8340 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8341 N0->hasOneUse()) 8342 return SDValue(); 8343 8344 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8345 if (!CN1) 8346 return SDValue(); 8347 8348 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8349 if (!CAdd) 8350 return SDValue(); 8351 8352 // If the resulting offset is too large, we can't fold it into the addressing 8353 // mode offset. 8354 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8355 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8356 8357 AddrMode AM; 8358 AM.HasBaseReg = true; 8359 AM.BaseOffs = Offset.getSExtValue(); 8360 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8361 return SDValue(); 8362 8363 SelectionDAG &DAG = DCI.DAG; 8364 SDLoc SL(N); 8365 EVT VT = N->getValueType(0); 8366 8367 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8368 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 8369 8370 SDNodeFlags Flags; 8371 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8372 (N0.getOpcode() == ISD::OR || 8373 N0->getFlags().hasNoUnsignedWrap())); 8374 8375 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8376 } 8377 8378 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8379 DAGCombinerInfo &DCI) const { 8380 SDValue Ptr = N->getBasePtr(); 8381 SelectionDAG &DAG = DCI.DAG; 8382 SDLoc SL(N); 8383 8384 // TODO: We could also do this for multiplies. 8385 if (Ptr.getOpcode() == ISD::SHL) { 8386 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8387 N->getMemoryVT(), DCI); 8388 if (NewPtr) { 8389 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8390 8391 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8392 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8393 } 8394 } 8395 8396 return SDValue(); 8397 } 8398 8399 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8400 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8401 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8402 (Opc == ISD::XOR && Val == 0); 8403 } 8404 8405 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8406 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8407 // integer combine opportunities since most 64-bit operations are decomposed 8408 // this way. TODO: We won't want this for SALU especially if it is an inline 8409 // immediate. 8410 SDValue SITargetLowering::splitBinaryBitConstantOp( 8411 DAGCombinerInfo &DCI, 8412 const SDLoc &SL, 8413 unsigned Opc, SDValue LHS, 8414 const ConstantSDNode *CRHS) const { 8415 uint64_t Val = CRHS->getZExtValue(); 8416 uint32_t ValLo = Lo_32(Val); 8417 uint32_t ValHi = Hi_32(Val); 8418 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8419 8420 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8421 bitOpWithConstantIsReducible(Opc, ValHi)) || 8422 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8423 // If we need to materialize a 64-bit immediate, it will be split up later 8424 // anyway. Avoid creating the harder to understand 64-bit immediate 8425 // materialization. 8426 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8427 } 8428 8429 return SDValue(); 8430 } 8431 8432 // Returns true if argument is a boolean value which is not serialized into 8433 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8434 static bool isBoolSGPR(SDValue V) { 8435 if (V.getValueType() != MVT::i1) 8436 return false; 8437 switch (V.getOpcode()) { 8438 default: break; 8439 case ISD::SETCC: 8440 case ISD::AND: 8441 case ISD::OR: 8442 case ISD::XOR: 8443 case AMDGPUISD::FP_CLASS: 8444 return true; 8445 } 8446 return false; 8447 } 8448 8449 // If a constant has all zeroes or all ones within each byte return it. 8450 // Otherwise return 0. 8451 static uint32_t getConstantPermuteMask(uint32_t C) { 8452 // 0xff for any zero byte in the mask 8453 uint32_t ZeroByteMask = 0; 8454 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8455 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8456 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8457 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8458 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8459 if ((NonZeroByteMask & C) != NonZeroByteMask) 8460 return 0; // Partial bytes selected. 8461 return C; 8462 } 8463 8464 // Check if a node selects whole bytes from its operand 0 starting at a byte 8465 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8466 // or -1 if not succeeded. 8467 // Note byte select encoding: 8468 // value 0-3 selects corresponding source byte; 8469 // value 0xc selects zero; 8470 // value 0xff selects 0xff. 8471 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8472 assert(V.getValueSizeInBits() == 32); 8473 8474 if (V.getNumOperands() != 2) 8475 return ~0; 8476 8477 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8478 if (!N1) 8479 return ~0; 8480 8481 uint32_t C = N1->getZExtValue(); 8482 8483 switch (V.getOpcode()) { 8484 default: 8485 break; 8486 case ISD::AND: 8487 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8488 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8489 } 8490 break; 8491 8492 case ISD::OR: 8493 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8494 return (0x03020100 & ~ConstMask) | ConstMask; 8495 } 8496 break; 8497 8498 case ISD::SHL: 8499 if (C % 8) 8500 return ~0; 8501 8502 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8503 8504 case ISD::SRL: 8505 if (C % 8) 8506 return ~0; 8507 8508 return uint32_t(0x0c0c0c0c03020100ull >> C); 8509 } 8510 8511 return ~0; 8512 } 8513 8514 SDValue SITargetLowering::performAndCombine(SDNode *N, 8515 DAGCombinerInfo &DCI) const { 8516 if (DCI.isBeforeLegalize()) 8517 return SDValue(); 8518 8519 SelectionDAG &DAG = DCI.DAG; 8520 EVT VT = N->getValueType(0); 8521 SDValue LHS = N->getOperand(0); 8522 SDValue RHS = N->getOperand(1); 8523 8524 8525 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8526 if (VT == MVT::i64 && CRHS) { 8527 if (SDValue Split 8528 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8529 return Split; 8530 } 8531 8532 if (CRHS && VT == MVT::i32) { 8533 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8534 // nb = number of trailing zeroes in mask 8535 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8536 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8537 uint64_t Mask = CRHS->getZExtValue(); 8538 unsigned Bits = countPopulation(Mask); 8539 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8540 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8541 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8542 unsigned Shift = CShift->getZExtValue(); 8543 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8544 unsigned Offset = NB + Shift; 8545 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8546 SDLoc SL(N); 8547 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8548 LHS->getOperand(0), 8549 DAG.getConstant(Offset, SL, MVT::i32), 8550 DAG.getConstant(Bits, SL, MVT::i32)); 8551 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8552 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8553 DAG.getValueType(NarrowVT)); 8554 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8555 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8556 return Shl; 8557 } 8558 } 8559 } 8560 8561 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8562 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8563 isa<ConstantSDNode>(LHS.getOperand(2))) { 8564 uint32_t Sel = getConstantPermuteMask(Mask); 8565 if (!Sel) 8566 return SDValue(); 8567 8568 // Select 0xc for all zero bytes 8569 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8570 SDLoc DL(N); 8571 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8572 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8573 } 8574 } 8575 8576 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8577 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8578 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8579 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8580 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8581 8582 SDValue X = LHS.getOperand(0); 8583 SDValue Y = RHS.getOperand(0); 8584 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8585 return SDValue(); 8586 8587 if (LCC == ISD::SETO) { 8588 if (X != LHS.getOperand(1)) 8589 return SDValue(); 8590 8591 if (RCC == ISD::SETUNE) { 8592 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8593 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8594 return SDValue(); 8595 8596 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8597 SIInstrFlags::N_SUBNORMAL | 8598 SIInstrFlags::N_ZERO | 8599 SIInstrFlags::P_ZERO | 8600 SIInstrFlags::P_SUBNORMAL | 8601 SIInstrFlags::P_NORMAL; 8602 8603 static_assert(((~(SIInstrFlags::S_NAN | 8604 SIInstrFlags::Q_NAN | 8605 SIInstrFlags::N_INFINITY | 8606 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8607 "mask not equal"); 8608 8609 SDLoc DL(N); 8610 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8611 X, DAG.getConstant(Mask, DL, MVT::i32)); 8612 } 8613 } 8614 } 8615 8616 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8617 std::swap(LHS, RHS); 8618 8619 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8620 RHS.hasOneUse()) { 8621 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8622 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8623 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8624 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8625 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8626 (RHS.getOperand(0) == LHS.getOperand(0) && 8627 LHS.getOperand(0) == LHS.getOperand(1))) { 8628 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8629 unsigned NewMask = LCC == ISD::SETO ? 8630 Mask->getZExtValue() & ~OrdMask : 8631 Mask->getZExtValue() & OrdMask; 8632 8633 SDLoc DL(N); 8634 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8635 DAG.getConstant(NewMask, DL, MVT::i32)); 8636 } 8637 } 8638 8639 if (VT == MVT::i32 && 8640 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8641 // and x, (sext cc from i1) => select cc, x, 0 8642 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8643 std::swap(LHS, RHS); 8644 if (isBoolSGPR(RHS.getOperand(0))) 8645 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8646 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8647 } 8648 8649 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8650 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8651 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8652 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8653 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8654 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8655 if (LHSMask != ~0u && RHSMask != ~0u) { 8656 // Canonicalize the expression in an attempt to have fewer unique masks 8657 // and therefore fewer registers used to hold the masks. 8658 if (LHSMask > RHSMask) { 8659 std::swap(LHSMask, RHSMask); 8660 std::swap(LHS, RHS); 8661 } 8662 8663 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8664 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8665 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8666 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8667 8668 // Check of we need to combine values from two sources within a byte. 8669 if (!(LHSUsedLanes & RHSUsedLanes) && 8670 // If we select high and lower word keep it for SDWA. 8671 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8672 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8673 // Each byte in each mask is either selector mask 0-3, or has higher 8674 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8675 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8676 // mask which is not 0xff wins. By anding both masks we have a correct 8677 // result except that 0x0c shall be corrected to give 0x0c only. 8678 uint32_t Mask = LHSMask & RHSMask; 8679 for (unsigned I = 0; I < 32; I += 8) { 8680 uint32_t ByteSel = 0xff << I; 8681 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8682 Mask &= (0x0c << I) & 0xffffffff; 8683 } 8684 8685 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8686 // or 0x0c. 8687 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8688 SDLoc DL(N); 8689 8690 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8691 LHS.getOperand(0), RHS.getOperand(0), 8692 DAG.getConstant(Sel, DL, MVT::i32)); 8693 } 8694 } 8695 } 8696 8697 return SDValue(); 8698 } 8699 8700 SDValue SITargetLowering::performOrCombine(SDNode *N, 8701 DAGCombinerInfo &DCI) const { 8702 SelectionDAG &DAG = DCI.DAG; 8703 SDValue LHS = N->getOperand(0); 8704 SDValue RHS = N->getOperand(1); 8705 8706 EVT VT = N->getValueType(0); 8707 if (VT == MVT::i1) { 8708 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8709 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8710 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8711 SDValue Src = LHS.getOperand(0); 8712 if (Src != RHS.getOperand(0)) 8713 return SDValue(); 8714 8715 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8716 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8717 if (!CLHS || !CRHS) 8718 return SDValue(); 8719 8720 // Only 10 bits are used. 8721 static const uint32_t MaxMask = 0x3ff; 8722 8723 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8724 SDLoc DL(N); 8725 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8726 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8727 } 8728 8729 return SDValue(); 8730 } 8731 8732 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8733 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8734 LHS.getOpcode() == AMDGPUISD::PERM && 8735 isa<ConstantSDNode>(LHS.getOperand(2))) { 8736 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8737 if (!Sel) 8738 return SDValue(); 8739 8740 Sel |= LHS.getConstantOperandVal(2); 8741 SDLoc DL(N); 8742 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8743 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8744 } 8745 8746 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8747 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8748 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8749 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8750 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8751 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8752 if (LHSMask != ~0u && RHSMask != ~0u) { 8753 // Canonicalize the expression in an attempt to have fewer unique masks 8754 // and therefore fewer registers used to hold the masks. 8755 if (LHSMask > RHSMask) { 8756 std::swap(LHSMask, RHSMask); 8757 std::swap(LHS, RHS); 8758 } 8759 8760 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8761 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8762 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8763 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8764 8765 // Check of we need to combine values from two sources within a byte. 8766 if (!(LHSUsedLanes & RHSUsedLanes) && 8767 // If we select high and lower word keep it for SDWA. 8768 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8769 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8770 // Kill zero bytes selected by other mask. Zero value is 0xc. 8771 LHSMask &= ~RHSUsedLanes; 8772 RHSMask &= ~LHSUsedLanes; 8773 // Add 4 to each active LHS lane 8774 LHSMask |= LHSUsedLanes & 0x04040404; 8775 // Combine masks 8776 uint32_t Sel = LHSMask | RHSMask; 8777 SDLoc DL(N); 8778 8779 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8780 LHS.getOperand(0), RHS.getOperand(0), 8781 DAG.getConstant(Sel, DL, MVT::i32)); 8782 } 8783 } 8784 } 8785 8786 if (VT != MVT::i64) 8787 return SDValue(); 8788 8789 // TODO: This could be a generic combine with a predicate for extracting the 8790 // high half of an integer being free. 8791 8792 // (or i64:x, (zero_extend i32:y)) -> 8793 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8794 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8795 RHS.getOpcode() != ISD::ZERO_EXTEND) 8796 std::swap(LHS, RHS); 8797 8798 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8799 SDValue ExtSrc = RHS.getOperand(0); 8800 EVT SrcVT = ExtSrc.getValueType(); 8801 if (SrcVT == MVT::i32) { 8802 SDLoc SL(N); 8803 SDValue LowLHS, HiBits; 8804 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 8805 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 8806 8807 DCI.AddToWorklist(LowOr.getNode()); 8808 DCI.AddToWorklist(HiBits.getNode()); 8809 8810 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 8811 LowOr, HiBits); 8812 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 8813 } 8814 } 8815 8816 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8817 if (CRHS) { 8818 if (SDValue Split 8819 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 8820 return Split; 8821 } 8822 8823 return SDValue(); 8824 } 8825 8826 SDValue SITargetLowering::performXorCombine(SDNode *N, 8827 DAGCombinerInfo &DCI) const { 8828 EVT VT = N->getValueType(0); 8829 if (VT != MVT::i64) 8830 return SDValue(); 8831 8832 SDValue LHS = N->getOperand(0); 8833 SDValue RHS = N->getOperand(1); 8834 8835 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8836 if (CRHS) { 8837 if (SDValue Split 8838 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 8839 return Split; 8840 } 8841 8842 return SDValue(); 8843 } 8844 8845 // Instructions that will be lowered with a final instruction that zeros the 8846 // high result bits. 8847 // XXX - probably only need to list legal operations. 8848 static bool fp16SrcZerosHighBits(unsigned Opc) { 8849 switch (Opc) { 8850 case ISD::FADD: 8851 case ISD::FSUB: 8852 case ISD::FMUL: 8853 case ISD::FDIV: 8854 case ISD::FREM: 8855 case ISD::FMA: 8856 case ISD::FMAD: 8857 case ISD::FCANONICALIZE: 8858 case ISD::FP_ROUND: 8859 case ISD::UINT_TO_FP: 8860 case ISD::SINT_TO_FP: 8861 case ISD::FABS: 8862 // Fabs is lowered to a bit operation, but it's an and which will clear the 8863 // high bits anyway. 8864 case ISD::FSQRT: 8865 case ISD::FSIN: 8866 case ISD::FCOS: 8867 case ISD::FPOWI: 8868 case ISD::FPOW: 8869 case ISD::FLOG: 8870 case ISD::FLOG2: 8871 case ISD::FLOG10: 8872 case ISD::FEXP: 8873 case ISD::FEXP2: 8874 case ISD::FCEIL: 8875 case ISD::FTRUNC: 8876 case ISD::FRINT: 8877 case ISD::FNEARBYINT: 8878 case ISD::FROUND: 8879 case ISD::FFLOOR: 8880 case ISD::FMINNUM: 8881 case ISD::FMAXNUM: 8882 case AMDGPUISD::FRACT: 8883 case AMDGPUISD::CLAMP: 8884 case AMDGPUISD::COS_HW: 8885 case AMDGPUISD::SIN_HW: 8886 case AMDGPUISD::FMIN3: 8887 case AMDGPUISD::FMAX3: 8888 case AMDGPUISD::FMED3: 8889 case AMDGPUISD::FMAD_FTZ: 8890 case AMDGPUISD::RCP: 8891 case AMDGPUISD::RSQ: 8892 case AMDGPUISD::RCP_IFLAG: 8893 case AMDGPUISD::LDEXP: 8894 return true; 8895 default: 8896 // fcopysign, select and others may be lowered to 32-bit bit operations 8897 // which don't zero the high bits. 8898 return false; 8899 } 8900 } 8901 8902 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 8903 DAGCombinerInfo &DCI) const { 8904 if (!Subtarget->has16BitInsts() || 8905 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8906 return SDValue(); 8907 8908 EVT VT = N->getValueType(0); 8909 if (VT != MVT::i32) 8910 return SDValue(); 8911 8912 SDValue Src = N->getOperand(0); 8913 if (Src.getValueType() != MVT::i16) 8914 return SDValue(); 8915 8916 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 8917 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 8918 if (Src.getOpcode() == ISD::BITCAST) { 8919 SDValue BCSrc = Src.getOperand(0); 8920 if (BCSrc.getValueType() == MVT::f16 && 8921 fp16SrcZerosHighBits(BCSrc.getOpcode())) 8922 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 8923 } 8924 8925 return SDValue(); 8926 } 8927 8928 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 8929 DAGCombinerInfo &DCI) 8930 const { 8931 SDValue Src = N->getOperand(0); 8932 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 8933 8934 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 8935 VTSign->getVT() == MVT::i8) || 8936 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 8937 VTSign->getVT() == MVT::i16)) && 8938 Src.hasOneUse()) { 8939 auto *M = cast<MemSDNode>(Src); 8940 SDValue Ops[] = { 8941 Src.getOperand(0), // Chain 8942 Src.getOperand(1), // rsrc 8943 Src.getOperand(2), // vindex 8944 Src.getOperand(3), // voffset 8945 Src.getOperand(4), // soffset 8946 Src.getOperand(5), // offset 8947 Src.getOperand(6), 8948 Src.getOperand(7) 8949 }; 8950 // replace with BUFFER_LOAD_BYTE/SHORT 8951 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 8952 Src.getOperand(0).getValueType()); 8953 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 8954 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 8955 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 8956 ResList, 8957 Ops, M->getMemoryVT(), 8958 M->getMemOperand()); 8959 return DCI.DAG.getMergeValues({BufferLoadSignExt, 8960 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 8961 } 8962 return SDValue(); 8963 } 8964 8965 SDValue SITargetLowering::performClassCombine(SDNode *N, 8966 DAGCombinerInfo &DCI) const { 8967 SelectionDAG &DAG = DCI.DAG; 8968 SDValue Mask = N->getOperand(1); 8969 8970 // fp_class x, 0 -> false 8971 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 8972 if (CMask->isNullValue()) 8973 return DAG.getConstant(0, SDLoc(N), MVT::i1); 8974 } 8975 8976 if (N->getOperand(0).isUndef()) 8977 return DAG.getUNDEF(MVT::i1); 8978 8979 return SDValue(); 8980 } 8981 8982 SDValue SITargetLowering::performRcpCombine(SDNode *N, 8983 DAGCombinerInfo &DCI) const { 8984 EVT VT = N->getValueType(0); 8985 SDValue N0 = N->getOperand(0); 8986 8987 if (N0.isUndef()) 8988 return N0; 8989 8990 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 8991 N0.getOpcode() == ISD::SINT_TO_FP)) { 8992 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 8993 N->getFlags()); 8994 } 8995 8996 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 8997 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 8998 N0.getOperand(0), N->getFlags()); 8999 } 9000 9001 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9002 } 9003 9004 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9005 unsigned MaxDepth) const { 9006 unsigned Opcode = Op.getOpcode(); 9007 if (Opcode == ISD::FCANONICALIZE) 9008 return true; 9009 9010 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9011 auto F = CFP->getValueAPF(); 9012 if (F.isNaN() && F.isSignaling()) 9013 return false; 9014 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9015 } 9016 9017 // If source is a result of another standard FP operation it is already in 9018 // canonical form. 9019 if (MaxDepth == 0) 9020 return false; 9021 9022 switch (Opcode) { 9023 // These will flush denorms if required. 9024 case ISD::FADD: 9025 case ISD::FSUB: 9026 case ISD::FMUL: 9027 case ISD::FCEIL: 9028 case ISD::FFLOOR: 9029 case ISD::FMA: 9030 case ISD::FMAD: 9031 case ISD::FSQRT: 9032 case ISD::FDIV: 9033 case ISD::FREM: 9034 case ISD::FP_ROUND: 9035 case ISD::FP_EXTEND: 9036 case AMDGPUISD::FMUL_LEGACY: 9037 case AMDGPUISD::FMAD_FTZ: 9038 case AMDGPUISD::RCP: 9039 case AMDGPUISD::RSQ: 9040 case AMDGPUISD::RSQ_CLAMP: 9041 case AMDGPUISD::RCP_LEGACY: 9042 case AMDGPUISD::RCP_IFLAG: 9043 case AMDGPUISD::TRIG_PREOP: 9044 case AMDGPUISD::DIV_SCALE: 9045 case AMDGPUISD::DIV_FMAS: 9046 case AMDGPUISD::DIV_FIXUP: 9047 case AMDGPUISD::FRACT: 9048 case AMDGPUISD::LDEXP: 9049 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9050 case AMDGPUISD::CVT_F32_UBYTE0: 9051 case AMDGPUISD::CVT_F32_UBYTE1: 9052 case AMDGPUISD::CVT_F32_UBYTE2: 9053 case AMDGPUISD::CVT_F32_UBYTE3: 9054 return true; 9055 9056 // It can/will be lowered or combined as a bit operation. 9057 // Need to check their input recursively to handle. 9058 case ISD::FNEG: 9059 case ISD::FABS: 9060 case ISD::FCOPYSIGN: 9061 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9062 9063 case ISD::FSIN: 9064 case ISD::FCOS: 9065 case ISD::FSINCOS: 9066 return Op.getValueType().getScalarType() != MVT::f16; 9067 9068 case ISD::FMINNUM: 9069 case ISD::FMAXNUM: 9070 case ISD::FMINNUM_IEEE: 9071 case ISD::FMAXNUM_IEEE: 9072 case AMDGPUISD::CLAMP: 9073 case AMDGPUISD::FMED3: 9074 case AMDGPUISD::FMAX3: 9075 case AMDGPUISD::FMIN3: { 9076 // FIXME: Shouldn't treat the generic operations different based these. 9077 // However, we aren't really required to flush the result from 9078 // minnum/maxnum.. 9079 9080 // snans will be quieted, so we only need to worry about denormals. 9081 if (Subtarget->supportsMinMaxDenormModes() || 9082 denormalsEnabledForType(DAG, Op.getValueType())) 9083 return true; 9084 9085 // Flushing may be required. 9086 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9087 // targets need to check their input recursively. 9088 9089 // FIXME: Does this apply with clamp? It's implemented with max. 9090 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9091 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9092 return false; 9093 } 9094 9095 return true; 9096 } 9097 case ISD::SELECT: { 9098 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9099 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9100 } 9101 case ISD::BUILD_VECTOR: { 9102 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9103 SDValue SrcOp = Op.getOperand(i); 9104 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9105 return false; 9106 } 9107 9108 return true; 9109 } 9110 case ISD::EXTRACT_VECTOR_ELT: 9111 case ISD::EXTRACT_SUBVECTOR: { 9112 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9113 } 9114 case ISD::INSERT_VECTOR_ELT: { 9115 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9116 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9117 } 9118 case ISD::UNDEF: 9119 // Could be anything. 9120 return false; 9121 9122 case ISD::BITCAST: { 9123 // Hack round the mess we make when legalizing extract_vector_elt 9124 SDValue Src = Op.getOperand(0); 9125 if (Src.getValueType() == MVT::i16 && 9126 Src.getOpcode() == ISD::TRUNCATE) { 9127 SDValue TruncSrc = Src.getOperand(0); 9128 if (TruncSrc.getValueType() == MVT::i32 && 9129 TruncSrc.getOpcode() == ISD::BITCAST && 9130 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9131 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9132 } 9133 } 9134 9135 return false; 9136 } 9137 case ISD::INTRINSIC_WO_CHAIN: { 9138 unsigned IntrinsicID 9139 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9140 // TODO: Handle more intrinsics 9141 switch (IntrinsicID) { 9142 case Intrinsic::amdgcn_cvt_pkrtz: 9143 case Intrinsic::amdgcn_cubeid: 9144 case Intrinsic::amdgcn_frexp_mant: 9145 case Intrinsic::amdgcn_fdot2: 9146 case Intrinsic::amdgcn_rcp: 9147 case Intrinsic::amdgcn_rsq: 9148 case Intrinsic::amdgcn_rsq_clamp: 9149 case Intrinsic::amdgcn_rcp_legacy: 9150 case Intrinsic::amdgcn_rsq_legacy: 9151 return true; 9152 default: 9153 break; 9154 } 9155 9156 LLVM_FALLTHROUGH; 9157 } 9158 default: 9159 return denormalsEnabledForType(DAG, Op.getValueType()) && 9160 DAG.isKnownNeverSNaN(Op); 9161 } 9162 9163 llvm_unreachable("invalid operation"); 9164 } 9165 9166 // Constant fold canonicalize. 9167 SDValue SITargetLowering::getCanonicalConstantFP( 9168 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9169 // Flush denormals to 0 if not enabled. 9170 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9171 return DAG.getConstantFP(0.0, SL, VT); 9172 9173 if (C.isNaN()) { 9174 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9175 if (C.isSignaling()) { 9176 // Quiet a signaling NaN. 9177 // FIXME: Is this supposed to preserve payload bits? 9178 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9179 } 9180 9181 // Make sure it is the canonical NaN bitpattern. 9182 // 9183 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9184 // immediate? 9185 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9186 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9187 } 9188 9189 // Already canonical. 9190 return DAG.getConstantFP(C, SL, VT); 9191 } 9192 9193 static bool vectorEltWillFoldAway(SDValue Op) { 9194 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9195 } 9196 9197 SDValue SITargetLowering::performFCanonicalizeCombine( 9198 SDNode *N, 9199 DAGCombinerInfo &DCI) const { 9200 SelectionDAG &DAG = DCI.DAG; 9201 SDValue N0 = N->getOperand(0); 9202 EVT VT = N->getValueType(0); 9203 9204 // fcanonicalize undef -> qnan 9205 if (N0.isUndef()) { 9206 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9207 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9208 } 9209 9210 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9211 EVT VT = N->getValueType(0); 9212 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9213 } 9214 9215 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9216 // (fcanonicalize k) 9217 // 9218 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9219 9220 // TODO: This could be better with wider vectors that will be split to v2f16, 9221 // and to consider uses since there aren't that many packed operations. 9222 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9223 isTypeLegal(MVT::v2f16)) { 9224 SDLoc SL(N); 9225 SDValue NewElts[2]; 9226 SDValue Lo = N0.getOperand(0); 9227 SDValue Hi = N0.getOperand(1); 9228 EVT EltVT = Lo.getValueType(); 9229 9230 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9231 for (unsigned I = 0; I != 2; ++I) { 9232 SDValue Op = N0.getOperand(I); 9233 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9234 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9235 CFP->getValueAPF()); 9236 } else if (Op.isUndef()) { 9237 // Handled below based on what the other operand is. 9238 NewElts[I] = Op; 9239 } else { 9240 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9241 } 9242 } 9243 9244 // If one half is undef, and one is constant, perfer a splat vector rather 9245 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9246 // cheaper to use and may be free with a packed operation. 9247 if (NewElts[0].isUndef()) { 9248 if (isa<ConstantFPSDNode>(NewElts[1])) 9249 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9250 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9251 } 9252 9253 if (NewElts[1].isUndef()) { 9254 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9255 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9256 } 9257 9258 return DAG.getBuildVector(VT, SL, NewElts); 9259 } 9260 } 9261 9262 unsigned SrcOpc = N0.getOpcode(); 9263 9264 // If it's free to do so, push canonicalizes further up the source, which may 9265 // find a canonical source. 9266 // 9267 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9268 // sNaNs. 9269 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9270 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9271 if (CRHS && N0.hasOneUse()) { 9272 SDLoc SL(N); 9273 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9274 N0.getOperand(0)); 9275 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9276 DCI.AddToWorklist(Canon0.getNode()); 9277 9278 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9279 } 9280 } 9281 9282 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9283 } 9284 9285 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9286 switch (Opc) { 9287 case ISD::FMAXNUM: 9288 case ISD::FMAXNUM_IEEE: 9289 return AMDGPUISD::FMAX3; 9290 case ISD::SMAX: 9291 return AMDGPUISD::SMAX3; 9292 case ISD::UMAX: 9293 return AMDGPUISD::UMAX3; 9294 case ISD::FMINNUM: 9295 case ISD::FMINNUM_IEEE: 9296 return AMDGPUISD::FMIN3; 9297 case ISD::SMIN: 9298 return AMDGPUISD::SMIN3; 9299 case ISD::UMIN: 9300 return AMDGPUISD::UMIN3; 9301 default: 9302 llvm_unreachable("Not a min/max opcode"); 9303 } 9304 } 9305 9306 SDValue SITargetLowering::performIntMed3ImmCombine( 9307 SelectionDAG &DAG, const SDLoc &SL, 9308 SDValue Op0, SDValue Op1, bool Signed) const { 9309 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9310 if (!K1) 9311 return SDValue(); 9312 9313 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9314 if (!K0) 9315 return SDValue(); 9316 9317 if (Signed) { 9318 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9319 return SDValue(); 9320 } else { 9321 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9322 return SDValue(); 9323 } 9324 9325 EVT VT = K0->getValueType(0); 9326 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9327 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9328 return DAG.getNode(Med3Opc, SL, VT, 9329 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9330 } 9331 9332 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9333 MVT NVT = MVT::i32; 9334 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9335 9336 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9337 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9338 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9339 9340 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9341 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9342 } 9343 9344 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9345 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9346 return C; 9347 9348 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9349 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9350 return C; 9351 } 9352 9353 return nullptr; 9354 } 9355 9356 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9357 const SDLoc &SL, 9358 SDValue Op0, 9359 SDValue Op1) const { 9360 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9361 if (!K1) 9362 return SDValue(); 9363 9364 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9365 if (!K0) 9366 return SDValue(); 9367 9368 // Ordered >= (although NaN inputs should have folded away by now). 9369 if (K0->getValueAPF() > K1->getValueAPF()) 9370 return SDValue(); 9371 9372 const MachineFunction &MF = DAG.getMachineFunction(); 9373 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9374 9375 // TODO: Check IEEE bit enabled? 9376 EVT VT = Op0.getValueType(); 9377 if (Info->getMode().DX10Clamp) { 9378 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9379 // hardware fmed3 behavior converting to a min. 9380 // FIXME: Should this be allowing -0.0? 9381 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9382 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9383 } 9384 9385 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9386 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9387 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9388 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9389 // then give the other result, which is different from med3 with a NaN 9390 // input. 9391 SDValue Var = Op0.getOperand(0); 9392 if (!DAG.isKnownNeverSNaN(Var)) 9393 return SDValue(); 9394 9395 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9396 9397 if ((!K0->hasOneUse() || 9398 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9399 (!K1->hasOneUse() || 9400 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9401 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9402 Var, SDValue(K0, 0), SDValue(K1, 0)); 9403 } 9404 } 9405 9406 return SDValue(); 9407 } 9408 9409 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9410 DAGCombinerInfo &DCI) const { 9411 SelectionDAG &DAG = DCI.DAG; 9412 9413 EVT VT = N->getValueType(0); 9414 unsigned Opc = N->getOpcode(); 9415 SDValue Op0 = N->getOperand(0); 9416 SDValue Op1 = N->getOperand(1); 9417 9418 // Only do this if the inner op has one use since this will just increases 9419 // register pressure for no benefit. 9420 9421 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9422 !VT.isVector() && 9423 (VT == MVT::i32 || VT == MVT::f32 || 9424 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9425 // max(max(a, b), c) -> max3(a, b, c) 9426 // min(min(a, b), c) -> min3(a, b, c) 9427 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9428 SDLoc DL(N); 9429 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9430 DL, 9431 N->getValueType(0), 9432 Op0.getOperand(0), 9433 Op0.getOperand(1), 9434 Op1); 9435 } 9436 9437 // Try commuted. 9438 // max(a, max(b, c)) -> max3(a, b, c) 9439 // min(a, min(b, c)) -> min3(a, b, c) 9440 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9441 SDLoc DL(N); 9442 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9443 DL, 9444 N->getValueType(0), 9445 Op0, 9446 Op1.getOperand(0), 9447 Op1.getOperand(1)); 9448 } 9449 } 9450 9451 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9452 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9453 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9454 return Med3; 9455 } 9456 9457 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9458 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9459 return Med3; 9460 } 9461 9462 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9463 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9464 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9465 (Opc == AMDGPUISD::FMIN_LEGACY && 9466 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9467 (VT == MVT::f32 || VT == MVT::f64 || 9468 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9469 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9470 Op0.hasOneUse()) { 9471 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9472 return Res; 9473 } 9474 9475 return SDValue(); 9476 } 9477 9478 static bool isClampZeroToOne(SDValue A, SDValue B) { 9479 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9480 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9481 // FIXME: Should this be allowing -0.0? 9482 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9483 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9484 } 9485 } 9486 9487 return false; 9488 } 9489 9490 // FIXME: Should only worry about snans for version with chain. 9491 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9492 DAGCombinerInfo &DCI) const { 9493 EVT VT = N->getValueType(0); 9494 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9495 // NaNs. With a NaN input, the order of the operands may change the result. 9496 9497 SelectionDAG &DAG = DCI.DAG; 9498 SDLoc SL(N); 9499 9500 SDValue Src0 = N->getOperand(0); 9501 SDValue Src1 = N->getOperand(1); 9502 SDValue Src2 = N->getOperand(2); 9503 9504 if (isClampZeroToOne(Src0, Src1)) { 9505 // const_a, const_b, x -> clamp is safe in all cases including signaling 9506 // nans. 9507 // FIXME: Should this be allowing -0.0? 9508 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9509 } 9510 9511 const MachineFunction &MF = DAG.getMachineFunction(); 9512 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9513 9514 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9515 // handling no dx10-clamp? 9516 if (Info->getMode().DX10Clamp) { 9517 // If NaNs is clamped to 0, we are free to reorder the inputs. 9518 9519 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9520 std::swap(Src0, Src1); 9521 9522 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9523 std::swap(Src1, Src2); 9524 9525 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9526 std::swap(Src0, Src1); 9527 9528 if (isClampZeroToOne(Src1, Src2)) 9529 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9530 } 9531 9532 return SDValue(); 9533 } 9534 9535 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9536 DAGCombinerInfo &DCI) const { 9537 SDValue Src0 = N->getOperand(0); 9538 SDValue Src1 = N->getOperand(1); 9539 if (Src0.isUndef() && Src1.isUndef()) 9540 return DCI.DAG.getUNDEF(N->getValueType(0)); 9541 return SDValue(); 9542 } 9543 9544 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 9545 // expanded into a set of cmp/select instructions. 9546 static bool shouldExpandVectorDynExt(SDNode *N) { 9547 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 9548 if (UseDivergentRegisterIndexing || isa<ConstantSDNode>(Idx)) 9549 return false; 9550 9551 SDValue Vec = N->getOperand(0); 9552 EVT VecVT = Vec.getValueType(); 9553 EVT EltVT = VecVT.getVectorElementType(); 9554 unsigned VecSize = VecVT.getSizeInBits(); 9555 unsigned EltSize = EltVT.getSizeInBits(); 9556 unsigned NumElem = VecVT.getVectorNumElements(); 9557 9558 // Sub-dword vectors of size 2 dword or less have better implementation. 9559 if (VecSize <= 64 && EltSize < 32) 9560 return false; 9561 9562 // Always expand the rest of sub-dword instructions, otherwise it will be 9563 // lowered via memory. 9564 if (EltSize < 32) 9565 return true; 9566 9567 // Always do this if var-idx is divergent, otherwise it will become a loop. 9568 if (Idx->isDivergent()) 9569 return true; 9570 9571 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 9572 unsigned NumInsts = NumElem /* Number of compares */ + 9573 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 9574 return NumInsts <= 16; 9575 } 9576 9577 SDValue SITargetLowering::performExtractVectorEltCombine( 9578 SDNode *N, DAGCombinerInfo &DCI) const { 9579 SDValue Vec = N->getOperand(0); 9580 SelectionDAG &DAG = DCI.DAG; 9581 9582 EVT VecVT = Vec.getValueType(); 9583 EVT EltVT = VecVT.getVectorElementType(); 9584 9585 if ((Vec.getOpcode() == ISD::FNEG || 9586 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9587 SDLoc SL(N); 9588 EVT EltVT = N->getValueType(0); 9589 SDValue Idx = N->getOperand(1); 9590 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9591 Vec.getOperand(0), Idx); 9592 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9593 } 9594 9595 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9596 // => 9597 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9598 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9599 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9600 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9601 SDLoc SL(N); 9602 EVT EltVT = N->getValueType(0); 9603 SDValue Idx = N->getOperand(1); 9604 unsigned Opc = Vec.getOpcode(); 9605 9606 switch(Opc) { 9607 default: 9608 break; 9609 // TODO: Support other binary operations. 9610 case ISD::FADD: 9611 case ISD::FSUB: 9612 case ISD::FMUL: 9613 case ISD::ADD: 9614 case ISD::UMIN: 9615 case ISD::UMAX: 9616 case ISD::SMIN: 9617 case ISD::SMAX: 9618 case ISD::FMAXNUM: 9619 case ISD::FMINNUM: 9620 case ISD::FMAXNUM_IEEE: 9621 case ISD::FMINNUM_IEEE: { 9622 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9623 Vec.getOperand(0), Idx); 9624 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9625 Vec.getOperand(1), Idx); 9626 9627 DCI.AddToWorklist(Elt0.getNode()); 9628 DCI.AddToWorklist(Elt1.getNode()); 9629 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9630 } 9631 } 9632 } 9633 9634 unsigned VecSize = VecVT.getSizeInBits(); 9635 unsigned EltSize = EltVT.getSizeInBits(); 9636 9637 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9638 if (shouldExpandVectorDynExt(N)) { 9639 SDLoc SL(N); 9640 SDValue Idx = N->getOperand(1); 9641 SDValue V; 9642 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9643 SDValue IC = DAG.getVectorIdxConstant(I, SL); 9644 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9645 if (I == 0) 9646 V = Elt; 9647 else 9648 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9649 } 9650 return V; 9651 } 9652 9653 if (!DCI.isBeforeLegalize()) 9654 return SDValue(); 9655 9656 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9657 // elements. This exposes more load reduction opportunities by replacing 9658 // multiple small extract_vector_elements with a single 32-bit extract. 9659 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9660 if (isa<MemSDNode>(Vec) && 9661 EltSize <= 16 && 9662 EltVT.isByteSized() && 9663 VecSize > 32 && 9664 VecSize % 32 == 0 && 9665 Idx) { 9666 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9667 9668 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9669 unsigned EltIdx = BitIndex / 32; 9670 unsigned LeftoverBitIdx = BitIndex % 32; 9671 SDLoc SL(N); 9672 9673 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9674 DCI.AddToWorklist(Cast.getNode()); 9675 9676 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9677 DAG.getConstant(EltIdx, SL, MVT::i32)); 9678 DCI.AddToWorklist(Elt.getNode()); 9679 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9680 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9681 DCI.AddToWorklist(Srl.getNode()); 9682 9683 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9684 DCI.AddToWorklist(Trunc.getNode()); 9685 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9686 } 9687 9688 return SDValue(); 9689 } 9690 9691 SDValue 9692 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9693 DAGCombinerInfo &DCI) const { 9694 SDValue Vec = N->getOperand(0); 9695 SDValue Idx = N->getOperand(2); 9696 EVT VecVT = Vec.getValueType(); 9697 EVT EltVT = VecVT.getVectorElementType(); 9698 9699 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9700 // => BUILD_VECTOR n x select (e, const-idx) 9701 if (!shouldExpandVectorDynExt(N)) 9702 return SDValue(); 9703 9704 SelectionDAG &DAG = DCI.DAG; 9705 SDLoc SL(N); 9706 SDValue Ins = N->getOperand(1); 9707 EVT IdxVT = Idx.getValueType(); 9708 9709 SmallVector<SDValue, 16> Ops; 9710 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9711 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9712 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9713 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9714 Ops.push_back(V); 9715 } 9716 9717 return DAG.getBuildVector(VecVT, SL, Ops); 9718 } 9719 9720 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9721 const SDNode *N0, 9722 const SDNode *N1) const { 9723 EVT VT = N0->getValueType(0); 9724 9725 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9726 // support denormals ever. 9727 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9728 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9729 getSubtarget()->hasMadF16())) && 9730 isOperationLegal(ISD::FMAD, VT)) 9731 return ISD::FMAD; 9732 9733 const TargetOptions &Options = DAG.getTarget().Options; 9734 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9735 (N0->getFlags().hasAllowContract() && 9736 N1->getFlags().hasAllowContract())) && 9737 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 9738 return ISD::FMA; 9739 } 9740 9741 return 0; 9742 } 9743 9744 // For a reassociatable opcode perform: 9745 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9746 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9747 SelectionDAG &DAG) const { 9748 EVT VT = N->getValueType(0); 9749 if (VT != MVT::i32 && VT != MVT::i64) 9750 return SDValue(); 9751 9752 unsigned Opc = N->getOpcode(); 9753 SDValue Op0 = N->getOperand(0); 9754 SDValue Op1 = N->getOperand(1); 9755 9756 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9757 return SDValue(); 9758 9759 if (Op0->isDivergent()) 9760 std::swap(Op0, Op1); 9761 9762 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9763 return SDValue(); 9764 9765 SDValue Op2 = Op1.getOperand(1); 9766 Op1 = Op1.getOperand(0); 9767 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9768 return SDValue(); 9769 9770 if (Op1->isDivergent()) 9771 std::swap(Op1, Op2); 9772 9773 // If either operand is constant this will conflict with 9774 // DAGCombiner::ReassociateOps(). 9775 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9776 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9777 return SDValue(); 9778 9779 SDLoc SL(N); 9780 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9781 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9782 } 9783 9784 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9785 EVT VT, 9786 SDValue N0, SDValue N1, SDValue N2, 9787 bool Signed) { 9788 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9789 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9790 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 9791 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 9792 } 9793 9794 SDValue SITargetLowering::performAddCombine(SDNode *N, 9795 DAGCombinerInfo &DCI) const { 9796 SelectionDAG &DAG = DCI.DAG; 9797 EVT VT = N->getValueType(0); 9798 SDLoc SL(N); 9799 SDValue LHS = N->getOperand(0); 9800 SDValue RHS = N->getOperand(1); 9801 9802 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 9803 && Subtarget->hasMad64_32() && 9804 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 9805 VT.getScalarSizeInBits() <= 64) { 9806 if (LHS.getOpcode() != ISD::MUL) 9807 std::swap(LHS, RHS); 9808 9809 SDValue MulLHS = LHS.getOperand(0); 9810 SDValue MulRHS = LHS.getOperand(1); 9811 SDValue AddRHS = RHS; 9812 9813 // TODO: Maybe restrict if SGPR inputs. 9814 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 9815 numBitsUnsigned(MulRHS, DAG) <= 32) { 9816 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 9817 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 9818 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 9819 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 9820 } 9821 9822 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 9823 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 9824 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 9825 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 9826 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 9827 } 9828 9829 return SDValue(); 9830 } 9831 9832 if (SDValue V = reassociateScalarOps(N, DAG)) { 9833 return V; 9834 } 9835 9836 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 9837 return SDValue(); 9838 9839 // add x, zext (setcc) => addcarry x, 0, setcc 9840 // add x, sext (setcc) => subcarry x, 0, setcc 9841 unsigned Opc = LHS.getOpcode(); 9842 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9843 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 9844 std::swap(RHS, LHS); 9845 9846 Opc = RHS.getOpcode(); 9847 switch (Opc) { 9848 default: break; 9849 case ISD::ZERO_EXTEND: 9850 case ISD::SIGN_EXTEND: 9851 case ISD::ANY_EXTEND: { 9852 auto Cond = RHS.getOperand(0); 9853 // If this won't be a real VOPC output, we would still need to insert an 9854 // extra instruction anyway. 9855 if (!isBoolSGPR(Cond)) 9856 break; 9857 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9858 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9859 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9860 return DAG.getNode(Opc, SL, VTList, Args); 9861 } 9862 case ISD::ADDCARRY: { 9863 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 9864 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9865 if (!C || C->getZExtValue() != 0) break; 9866 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 9867 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 9868 } 9869 } 9870 return SDValue(); 9871 } 9872 9873 SDValue SITargetLowering::performSubCombine(SDNode *N, 9874 DAGCombinerInfo &DCI) const { 9875 SelectionDAG &DAG = DCI.DAG; 9876 EVT VT = N->getValueType(0); 9877 9878 if (VT != MVT::i32) 9879 return SDValue(); 9880 9881 SDLoc SL(N); 9882 SDValue LHS = N->getOperand(0); 9883 SDValue RHS = N->getOperand(1); 9884 9885 // sub x, zext (setcc) => subcarry x, 0, setcc 9886 // sub x, sext (setcc) => addcarry x, 0, setcc 9887 unsigned Opc = RHS.getOpcode(); 9888 switch (Opc) { 9889 default: break; 9890 case ISD::ZERO_EXTEND: 9891 case ISD::SIGN_EXTEND: 9892 case ISD::ANY_EXTEND: { 9893 auto Cond = RHS.getOperand(0); 9894 // If this won't be a real VOPC output, we would still need to insert an 9895 // extra instruction anyway. 9896 if (!isBoolSGPR(Cond)) 9897 break; 9898 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9899 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9900 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 9901 return DAG.getNode(Opc, SL, VTList, Args); 9902 } 9903 } 9904 9905 if (LHS.getOpcode() == ISD::SUBCARRY) { 9906 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 9907 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9908 if (!C || !C->isNullValue()) 9909 return SDValue(); 9910 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 9911 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 9912 } 9913 return SDValue(); 9914 } 9915 9916 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 9917 DAGCombinerInfo &DCI) const { 9918 9919 if (N->getValueType(0) != MVT::i32) 9920 return SDValue(); 9921 9922 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9923 if (!C || C->getZExtValue() != 0) 9924 return SDValue(); 9925 9926 SelectionDAG &DAG = DCI.DAG; 9927 SDValue LHS = N->getOperand(0); 9928 9929 // addcarry (add x, y), 0, cc => addcarry x, y, cc 9930 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 9931 unsigned LHSOpc = LHS.getOpcode(); 9932 unsigned Opc = N->getOpcode(); 9933 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 9934 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 9935 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 9936 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 9937 } 9938 return SDValue(); 9939 } 9940 9941 SDValue SITargetLowering::performFAddCombine(SDNode *N, 9942 DAGCombinerInfo &DCI) const { 9943 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9944 return SDValue(); 9945 9946 SelectionDAG &DAG = DCI.DAG; 9947 EVT VT = N->getValueType(0); 9948 9949 SDLoc SL(N); 9950 SDValue LHS = N->getOperand(0); 9951 SDValue RHS = N->getOperand(1); 9952 9953 // These should really be instruction patterns, but writing patterns with 9954 // source modiifiers is a pain. 9955 9956 // fadd (fadd (a, a), b) -> mad 2.0, a, b 9957 if (LHS.getOpcode() == ISD::FADD) { 9958 SDValue A = LHS.getOperand(0); 9959 if (A == LHS.getOperand(1)) { 9960 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9961 if (FusedOp != 0) { 9962 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9963 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 9964 } 9965 } 9966 } 9967 9968 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 9969 if (RHS.getOpcode() == ISD::FADD) { 9970 SDValue A = RHS.getOperand(0); 9971 if (A == RHS.getOperand(1)) { 9972 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9973 if (FusedOp != 0) { 9974 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9975 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 9976 } 9977 } 9978 } 9979 9980 return SDValue(); 9981 } 9982 9983 SDValue SITargetLowering::performFSubCombine(SDNode *N, 9984 DAGCombinerInfo &DCI) const { 9985 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9986 return SDValue(); 9987 9988 SelectionDAG &DAG = DCI.DAG; 9989 SDLoc SL(N); 9990 EVT VT = N->getValueType(0); 9991 assert(!VT.isVector()); 9992 9993 // Try to get the fneg to fold into the source modifier. This undoes generic 9994 // DAG combines and folds them into the mad. 9995 // 9996 // Only do this if we are not trying to support denormals. v_mad_f32 does 9997 // not support denormals ever. 9998 SDValue LHS = N->getOperand(0); 9999 SDValue RHS = N->getOperand(1); 10000 if (LHS.getOpcode() == ISD::FADD) { 10001 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10002 SDValue A = LHS.getOperand(0); 10003 if (A == LHS.getOperand(1)) { 10004 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10005 if (FusedOp != 0){ 10006 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10007 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10008 10009 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10010 } 10011 } 10012 } 10013 10014 if (RHS.getOpcode() == ISD::FADD) { 10015 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10016 10017 SDValue A = RHS.getOperand(0); 10018 if (A == RHS.getOperand(1)) { 10019 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10020 if (FusedOp != 0){ 10021 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10022 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10023 } 10024 } 10025 } 10026 10027 return SDValue(); 10028 } 10029 10030 SDValue SITargetLowering::performFMACombine(SDNode *N, 10031 DAGCombinerInfo &DCI) const { 10032 SelectionDAG &DAG = DCI.DAG; 10033 EVT VT = N->getValueType(0); 10034 SDLoc SL(N); 10035 10036 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 10037 return SDValue(); 10038 10039 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10040 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10041 SDValue Op1 = N->getOperand(0); 10042 SDValue Op2 = N->getOperand(1); 10043 SDValue FMA = N->getOperand(2); 10044 10045 if (FMA.getOpcode() != ISD::FMA || 10046 Op1.getOpcode() != ISD::FP_EXTEND || 10047 Op2.getOpcode() != ISD::FP_EXTEND) 10048 return SDValue(); 10049 10050 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10051 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10052 // is sufficient to allow generaing fdot2. 10053 const TargetOptions &Options = DAG.getTarget().Options; 10054 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10055 (N->getFlags().hasAllowContract() && 10056 FMA->getFlags().hasAllowContract())) { 10057 Op1 = Op1.getOperand(0); 10058 Op2 = Op2.getOperand(0); 10059 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10060 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10061 return SDValue(); 10062 10063 SDValue Vec1 = Op1.getOperand(0); 10064 SDValue Idx1 = Op1.getOperand(1); 10065 SDValue Vec2 = Op2.getOperand(0); 10066 10067 SDValue FMAOp1 = FMA.getOperand(0); 10068 SDValue FMAOp2 = FMA.getOperand(1); 10069 SDValue FMAAcc = FMA.getOperand(2); 10070 10071 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10072 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10073 return SDValue(); 10074 10075 FMAOp1 = FMAOp1.getOperand(0); 10076 FMAOp2 = FMAOp2.getOperand(0); 10077 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10078 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10079 return SDValue(); 10080 10081 SDValue Vec3 = FMAOp1.getOperand(0); 10082 SDValue Vec4 = FMAOp2.getOperand(0); 10083 SDValue Idx2 = FMAOp1.getOperand(1); 10084 10085 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10086 // Idx1 and Idx2 cannot be the same. 10087 Idx1 == Idx2) 10088 return SDValue(); 10089 10090 if (Vec1 == Vec2 || Vec3 == Vec4) 10091 return SDValue(); 10092 10093 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10094 return SDValue(); 10095 10096 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10097 (Vec1 == Vec4 && Vec2 == Vec3)) { 10098 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10099 DAG.getTargetConstant(0, SL, MVT::i1)); 10100 } 10101 } 10102 return SDValue(); 10103 } 10104 10105 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10106 DAGCombinerInfo &DCI) const { 10107 SelectionDAG &DAG = DCI.DAG; 10108 SDLoc SL(N); 10109 10110 SDValue LHS = N->getOperand(0); 10111 SDValue RHS = N->getOperand(1); 10112 EVT VT = LHS.getValueType(); 10113 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10114 10115 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10116 if (!CRHS) { 10117 CRHS = dyn_cast<ConstantSDNode>(LHS); 10118 if (CRHS) { 10119 std::swap(LHS, RHS); 10120 CC = getSetCCSwappedOperands(CC); 10121 } 10122 } 10123 10124 if (CRHS) { 10125 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10126 isBoolSGPR(LHS.getOperand(0))) { 10127 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10128 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10129 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10130 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10131 if ((CRHS->isAllOnesValue() && 10132 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10133 (CRHS->isNullValue() && 10134 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10135 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10136 DAG.getConstant(-1, SL, MVT::i1)); 10137 if ((CRHS->isAllOnesValue() && 10138 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10139 (CRHS->isNullValue() && 10140 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10141 return LHS.getOperand(0); 10142 } 10143 10144 uint64_t CRHSVal = CRHS->getZExtValue(); 10145 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10146 LHS.getOpcode() == ISD::SELECT && 10147 isa<ConstantSDNode>(LHS.getOperand(1)) && 10148 isa<ConstantSDNode>(LHS.getOperand(2)) && 10149 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10150 isBoolSGPR(LHS.getOperand(0))) { 10151 // Given CT != FT: 10152 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10153 // setcc (select cc, CT, CF), CF, ne => cc 10154 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10155 // setcc (select cc, CT, CF), CT, eq => cc 10156 uint64_t CT = LHS.getConstantOperandVal(1); 10157 uint64_t CF = LHS.getConstantOperandVal(2); 10158 10159 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10160 (CT == CRHSVal && CC == ISD::SETNE)) 10161 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10162 DAG.getConstant(-1, SL, MVT::i1)); 10163 if ((CF == CRHSVal && CC == ISD::SETNE) || 10164 (CT == CRHSVal && CC == ISD::SETEQ)) 10165 return LHS.getOperand(0); 10166 } 10167 } 10168 10169 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10170 VT != MVT::f16)) 10171 return SDValue(); 10172 10173 // Match isinf/isfinite pattern 10174 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10175 // (fcmp one (fabs x), inf) -> (fp_class x, 10176 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10177 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10178 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10179 if (!CRHS) 10180 return SDValue(); 10181 10182 const APFloat &APF = CRHS->getValueAPF(); 10183 if (APF.isInfinity() && !APF.isNegative()) { 10184 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10185 SIInstrFlags::N_INFINITY; 10186 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10187 SIInstrFlags::P_ZERO | 10188 SIInstrFlags::N_NORMAL | 10189 SIInstrFlags::P_NORMAL | 10190 SIInstrFlags::N_SUBNORMAL | 10191 SIInstrFlags::P_SUBNORMAL; 10192 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10193 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10194 DAG.getConstant(Mask, SL, MVT::i32)); 10195 } 10196 } 10197 10198 return SDValue(); 10199 } 10200 10201 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10202 DAGCombinerInfo &DCI) const { 10203 SelectionDAG &DAG = DCI.DAG; 10204 SDLoc SL(N); 10205 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10206 10207 SDValue Src = N->getOperand(0); 10208 SDValue Shift = N->getOperand(0); 10209 10210 // TODO: Extend type shouldn't matter (assuming legal types). 10211 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10212 Shift = Shift.getOperand(0); 10213 10214 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10215 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10216 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10217 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10218 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10219 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10220 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10221 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10222 SDLoc(Shift.getOperand(0)), MVT::i32); 10223 10224 unsigned ShiftOffset = 8 * Offset; 10225 if (Shift.getOpcode() == ISD::SHL) 10226 ShiftOffset -= C->getZExtValue(); 10227 else 10228 ShiftOffset += C->getZExtValue(); 10229 10230 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10231 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10232 MVT::f32, Shift); 10233 } 10234 } 10235 } 10236 10237 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10238 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10239 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10240 // We simplified Src. If this node is not dead, visit it again so it is 10241 // folded properly. 10242 if (N->getOpcode() != ISD::DELETED_NODE) 10243 DCI.AddToWorklist(N); 10244 return SDValue(N, 0); 10245 } 10246 10247 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10248 if (SDValue DemandedSrc = 10249 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10250 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10251 10252 return SDValue(); 10253 } 10254 10255 SDValue SITargetLowering::performClampCombine(SDNode *N, 10256 DAGCombinerInfo &DCI) const { 10257 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10258 if (!CSrc) 10259 return SDValue(); 10260 10261 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10262 const APFloat &F = CSrc->getValueAPF(); 10263 APFloat Zero = APFloat::getZero(F.getSemantics()); 10264 if (F < Zero || 10265 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10266 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10267 } 10268 10269 APFloat One(F.getSemantics(), "1.0"); 10270 if (F > One) 10271 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10272 10273 return SDValue(CSrc, 0); 10274 } 10275 10276 10277 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10278 DAGCombinerInfo &DCI) const { 10279 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10280 return SDValue(); 10281 switch (N->getOpcode()) { 10282 default: 10283 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10284 case ISD::ADD: 10285 return performAddCombine(N, DCI); 10286 case ISD::SUB: 10287 return performSubCombine(N, DCI); 10288 case ISD::ADDCARRY: 10289 case ISD::SUBCARRY: 10290 return performAddCarrySubCarryCombine(N, DCI); 10291 case ISD::FADD: 10292 return performFAddCombine(N, DCI); 10293 case ISD::FSUB: 10294 return performFSubCombine(N, DCI); 10295 case ISD::SETCC: 10296 return performSetCCCombine(N, DCI); 10297 case ISD::FMAXNUM: 10298 case ISD::FMINNUM: 10299 case ISD::FMAXNUM_IEEE: 10300 case ISD::FMINNUM_IEEE: 10301 case ISD::SMAX: 10302 case ISD::SMIN: 10303 case ISD::UMAX: 10304 case ISD::UMIN: 10305 case AMDGPUISD::FMIN_LEGACY: 10306 case AMDGPUISD::FMAX_LEGACY: 10307 return performMinMaxCombine(N, DCI); 10308 case ISD::FMA: 10309 return performFMACombine(N, DCI); 10310 case ISD::LOAD: { 10311 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10312 return Widended; 10313 LLVM_FALLTHROUGH; 10314 } 10315 case ISD::STORE: 10316 case ISD::ATOMIC_LOAD: 10317 case ISD::ATOMIC_STORE: 10318 case ISD::ATOMIC_CMP_SWAP: 10319 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 10320 case ISD::ATOMIC_SWAP: 10321 case ISD::ATOMIC_LOAD_ADD: 10322 case ISD::ATOMIC_LOAD_SUB: 10323 case ISD::ATOMIC_LOAD_AND: 10324 case ISD::ATOMIC_LOAD_OR: 10325 case ISD::ATOMIC_LOAD_XOR: 10326 case ISD::ATOMIC_LOAD_NAND: 10327 case ISD::ATOMIC_LOAD_MIN: 10328 case ISD::ATOMIC_LOAD_MAX: 10329 case ISD::ATOMIC_LOAD_UMIN: 10330 case ISD::ATOMIC_LOAD_UMAX: 10331 case ISD::ATOMIC_LOAD_FADD: 10332 case AMDGPUISD::ATOMIC_INC: 10333 case AMDGPUISD::ATOMIC_DEC: 10334 case AMDGPUISD::ATOMIC_LOAD_FMIN: 10335 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 10336 if (DCI.isBeforeLegalize()) 10337 break; 10338 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 10339 case ISD::AND: 10340 return performAndCombine(N, DCI); 10341 case ISD::OR: 10342 return performOrCombine(N, DCI); 10343 case ISD::XOR: 10344 return performXorCombine(N, DCI); 10345 case ISD::ZERO_EXTEND: 10346 return performZeroExtendCombine(N, DCI); 10347 case ISD::SIGN_EXTEND_INREG: 10348 return performSignExtendInRegCombine(N , DCI); 10349 case AMDGPUISD::FP_CLASS: 10350 return performClassCombine(N, DCI); 10351 case ISD::FCANONICALIZE: 10352 return performFCanonicalizeCombine(N, DCI); 10353 case AMDGPUISD::RCP: 10354 return performRcpCombine(N, DCI); 10355 case AMDGPUISD::FRACT: 10356 case AMDGPUISD::RSQ: 10357 case AMDGPUISD::RCP_LEGACY: 10358 case AMDGPUISD::RCP_IFLAG: 10359 case AMDGPUISD::RSQ_CLAMP: 10360 case AMDGPUISD::LDEXP: { 10361 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10362 SDValue Src = N->getOperand(0); 10363 if (Src.isUndef()) 10364 return Src; 10365 break; 10366 } 10367 case ISD::SINT_TO_FP: 10368 case ISD::UINT_TO_FP: 10369 return performUCharToFloatCombine(N, DCI); 10370 case AMDGPUISD::CVT_F32_UBYTE0: 10371 case AMDGPUISD::CVT_F32_UBYTE1: 10372 case AMDGPUISD::CVT_F32_UBYTE2: 10373 case AMDGPUISD::CVT_F32_UBYTE3: 10374 return performCvtF32UByteNCombine(N, DCI); 10375 case AMDGPUISD::FMED3: 10376 return performFMed3Combine(N, DCI); 10377 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10378 return performCvtPkRTZCombine(N, DCI); 10379 case AMDGPUISD::CLAMP: 10380 return performClampCombine(N, DCI); 10381 case ISD::SCALAR_TO_VECTOR: { 10382 SelectionDAG &DAG = DCI.DAG; 10383 EVT VT = N->getValueType(0); 10384 10385 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10386 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10387 SDLoc SL(N); 10388 SDValue Src = N->getOperand(0); 10389 EVT EltVT = Src.getValueType(); 10390 if (EltVT == MVT::f16) 10391 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10392 10393 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10394 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10395 } 10396 10397 break; 10398 } 10399 case ISD::EXTRACT_VECTOR_ELT: 10400 return performExtractVectorEltCombine(N, DCI); 10401 case ISD::INSERT_VECTOR_ELT: 10402 return performInsertVectorEltCombine(N, DCI); 10403 } 10404 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10405 } 10406 10407 /// Helper function for adjustWritemask 10408 static unsigned SubIdx2Lane(unsigned Idx) { 10409 switch (Idx) { 10410 default: return 0; 10411 case AMDGPU::sub0: return 0; 10412 case AMDGPU::sub1: return 1; 10413 case AMDGPU::sub2: return 2; 10414 case AMDGPU::sub3: return 3; 10415 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10416 } 10417 } 10418 10419 /// Adjust the writemask of MIMG instructions 10420 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10421 SelectionDAG &DAG) const { 10422 unsigned Opcode = Node->getMachineOpcode(); 10423 10424 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10425 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10426 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10427 return Node; // not implemented for D16 10428 10429 SDNode *Users[5] = { nullptr }; 10430 unsigned Lane = 0; 10431 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10432 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10433 unsigned NewDmask = 0; 10434 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10435 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10436 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10437 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10438 unsigned TFCLane = 0; 10439 bool HasChain = Node->getNumValues() > 1; 10440 10441 if (OldDmask == 0) { 10442 // These are folded out, but on the chance it happens don't assert. 10443 return Node; 10444 } 10445 10446 unsigned OldBitsSet = countPopulation(OldDmask); 10447 // Work out which is the TFE/LWE lane if that is enabled. 10448 if (UsesTFC) { 10449 TFCLane = OldBitsSet; 10450 } 10451 10452 // Try to figure out the used register components 10453 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10454 I != E; ++I) { 10455 10456 // Don't look at users of the chain. 10457 if (I.getUse().getResNo() != 0) 10458 continue; 10459 10460 // Abort if we can't understand the usage 10461 if (!I->isMachineOpcode() || 10462 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10463 return Node; 10464 10465 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10466 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10467 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10468 // set, etc. 10469 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10470 10471 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10472 if (UsesTFC && Lane == TFCLane) { 10473 Users[Lane] = *I; 10474 } else { 10475 // Set which texture component corresponds to the lane. 10476 unsigned Comp; 10477 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10478 Comp = countTrailingZeros(Dmask); 10479 Dmask &= ~(1 << Comp); 10480 } 10481 10482 // Abort if we have more than one user per component. 10483 if (Users[Lane]) 10484 return Node; 10485 10486 Users[Lane] = *I; 10487 NewDmask |= 1 << Comp; 10488 } 10489 } 10490 10491 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10492 bool NoChannels = !NewDmask; 10493 if (NoChannels) { 10494 if (!UsesTFC) { 10495 // No uses of the result and not using TFC. Then do nothing. 10496 return Node; 10497 } 10498 // If the original dmask has one channel - then nothing to do 10499 if (OldBitsSet == 1) 10500 return Node; 10501 // Use an arbitrary dmask - required for the instruction to work 10502 NewDmask = 1; 10503 } 10504 // Abort if there's no change 10505 if (NewDmask == OldDmask) 10506 return Node; 10507 10508 unsigned BitsSet = countPopulation(NewDmask); 10509 10510 // Check for TFE or LWE - increase the number of channels by one to account 10511 // for the extra return value 10512 // This will need adjustment for D16 if this is also included in 10513 // adjustWriteMask (this function) but at present D16 are excluded. 10514 unsigned NewChannels = BitsSet + UsesTFC; 10515 10516 int NewOpcode = 10517 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10518 assert(NewOpcode != -1 && 10519 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10520 "failed to find equivalent MIMG op"); 10521 10522 // Adjust the writemask in the node 10523 SmallVector<SDValue, 12> Ops; 10524 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10525 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10526 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10527 10528 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10529 10530 MVT ResultVT = NewChannels == 1 ? 10531 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10532 NewChannels == 5 ? 8 : NewChannels); 10533 SDVTList NewVTList = HasChain ? 10534 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10535 10536 10537 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10538 NewVTList, Ops); 10539 10540 if (HasChain) { 10541 // Update chain. 10542 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10543 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10544 } 10545 10546 if (NewChannels == 1) { 10547 assert(Node->hasNUsesOfValue(1, 0)); 10548 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10549 SDLoc(Node), Users[Lane]->getValueType(0), 10550 SDValue(NewNode, 0)); 10551 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10552 return nullptr; 10553 } 10554 10555 // Update the users of the node with the new indices 10556 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10557 SDNode *User = Users[i]; 10558 if (!User) { 10559 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10560 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10561 if (i || !NoChannels) 10562 continue; 10563 } else { 10564 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10565 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10566 } 10567 10568 switch (Idx) { 10569 default: break; 10570 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10571 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10572 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10573 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10574 } 10575 } 10576 10577 DAG.RemoveDeadNode(Node); 10578 return nullptr; 10579 } 10580 10581 static bool isFrameIndexOp(SDValue Op) { 10582 if (Op.getOpcode() == ISD::AssertZext) 10583 Op = Op.getOperand(0); 10584 10585 return isa<FrameIndexSDNode>(Op); 10586 } 10587 10588 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10589 /// with frame index operands. 10590 /// LLVM assumes that inputs are to these instructions are registers. 10591 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10592 SelectionDAG &DAG) const { 10593 if (Node->getOpcode() == ISD::CopyToReg) { 10594 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10595 SDValue SrcVal = Node->getOperand(2); 10596 10597 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10598 // to try understanding copies to physical registers. 10599 if (SrcVal.getValueType() == MVT::i1 && 10600 Register::isPhysicalRegister(DestReg->getReg())) { 10601 SDLoc SL(Node); 10602 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10603 SDValue VReg = DAG.getRegister( 10604 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10605 10606 SDNode *Glued = Node->getGluedNode(); 10607 SDValue ToVReg 10608 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10609 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10610 SDValue ToResultReg 10611 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10612 VReg, ToVReg.getValue(1)); 10613 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10614 DAG.RemoveDeadNode(Node); 10615 return ToResultReg.getNode(); 10616 } 10617 } 10618 10619 SmallVector<SDValue, 8> Ops; 10620 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10621 if (!isFrameIndexOp(Node->getOperand(i))) { 10622 Ops.push_back(Node->getOperand(i)); 10623 continue; 10624 } 10625 10626 SDLoc DL(Node); 10627 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10628 Node->getOperand(i).getValueType(), 10629 Node->getOperand(i)), 0)); 10630 } 10631 10632 return DAG.UpdateNodeOperands(Node, Ops); 10633 } 10634 10635 /// Fold the instructions after selecting them. 10636 /// Returns null if users were already updated. 10637 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10638 SelectionDAG &DAG) const { 10639 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10640 unsigned Opcode = Node->getMachineOpcode(); 10641 10642 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10643 !TII->isGather4(Opcode)) { 10644 return adjustWritemask(Node, DAG); 10645 } 10646 10647 if (Opcode == AMDGPU::INSERT_SUBREG || 10648 Opcode == AMDGPU::REG_SEQUENCE) { 10649 legalizeTargetIndependentNode(Node, DAG); 10650 return Node; 10651 } 10652 10653 switch (Opcode) { 10654 case AMDGPU::V_DIV_SCALE_F32: 10655 case AMDGPU::V_DIV_SCALE_F64: { 10656 // Satisfy the operand register constraint when one of the inputs is 10657 // undefined. Ordinarily each undef value will have its own implicit_def of 10658 // a vreg, so force these to use a single register. 10659 SDValue Src0 = Node->getOperand(0); 10660 SDValue Src1 = Node->getOperand(1); 10661 SDValue Src2 = Node->getOperand(2); 10662 10663 if ((Src0.isMachineOpcode() && 10664 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10665 (Src0 == Src1 || Src0 == Src2)) 10666 break; 10667 10668 MVT VT = Src0.getValueType().getSimpleVT(); 10669 const TargetRegisterClass *RC = 10670 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10671 10672 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10673 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10674 10675 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10676 UndefReg, Src0, SDValue()); 10677 10678 // src0 must be the same register as src1 or src2, even if the value is 10679 // undefined, so make sure we don't violate this constraint. 10680 if (Src0.isMachineOpcode() && 10681 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10682 if (Src1.isMachineOpcode() && 10683 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10684 Src0 = Src1; 10685 else if (Src2.isMachineOpcode() && 10686 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10687 Src0 = Src2; 10688 else { 10689 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10690 Src0 = UndefReg; 10691 Src1 = UndefReg; 10692 } 10693 } else 10694 break; 10695 10696 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10697 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10698 Ops.push_back(Node->getOperand(I)); 10699 10700 Ops.push_back(ImpDef.getValue(1)); 10701 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10702 } 10703 default: 10704 break; 10705 } 10706 10707 return Node; 10708 } 10709 10710 /// Assign the register class depending on the number of 10711 /// bits set in the writemask 10712 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10713 SDNode *Node) const { 10714 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10715 10716 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10717 10718 if (TII->isVOP3(MI.getOpcode())) { 10719 // Make sure constant bus requirements are respected. 10720 TII->legalizeOperandsVOP3(MRI, MI); 10721 10722 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10723 // This saves a chain-copy of registers and better ballance register 10724 // use between vgpr and agpr as agpr tuples tend to be big. 10725 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10726 unsigned Opc = MI.getOpcode(); 10727 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10728 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10729 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10730 if (I == -1) 10731 break; 10732 MachineOperand &Op = MI.getOperand(I); 10733 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10734 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10735 !Register::isVirtualRegister(Op.getReg()) || 10736 !TRI->isAGPR(MRI, Op.getReg())) 10737 continue; 10738 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10739 if (!Src || !Src->isCopy() || 10740 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10741 continue; 10742 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10743 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10744 // All uses of agpr64 and agpr32 can also accept vgpr except for 10745 // v_accvgpr_read, but we do not produce agpr reads during selection, 10746 // so no use checks are needed. 10747 MRI.setRegClass(Op.getReg(), NewRC); 10748 } 10749 } 10750 10751 return; 10752 } 10753 10754 // Replace unused atomics with the no return version. 10755 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10756 if (NoRetAtomicOp != -1) { 10757 if (!Node->hasAnyUseOfValue(0)) { 10758 MI.setDesc(TII->get(NoRetAtomicOp)); 10759 MI.RemoveOperand(0); 10760 return; 10761 } 10762 10763 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10764 // instruction, because the return type of these instructions is a vec2 of 10765 // the memory type, so it can be tied to the input operand. 10766 // This means these instructions always have a use, so we need to add a 10767 // special case to check if the atomic has only one extract_subreg use, 10768 // which itself has no uses. 10769 if ((Node->hasNUsesOfValue(1, 0) && 10770 Node->use_begin()->isMachineOpcode() && 10771 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10772 !Node->use_begin()->hasAnyUseOfValue(0))) { 10773 Register Def = MI.getOperand(0).getReg(); 10774 10775 // Change this into a noret atomic. 10776 MI.setDesc(TII->get(NoRetAtomicOp)); 10777 MI.RemoveOperand(0); 10778 10779 // If we only remove the def operand from the atomic instruction, the 10780 // extract_subreg will be left with a use of a vreg without a def. 10781 // So we need to insert an implicit_def to avoid machine verifier 10782 // errors. 10783 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10784 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10785 } 10786 return; 10787 } 10788 } 10789 10790 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 10791 uint64_t Val) { 10792 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 10793 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 10794 } 10795 10796 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 10797 const SDLoc &DL, 10798 SDValue Ptr) const { 10799 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10800 10801 // Build the half of the subregister with the constants before building the 10802 // full 128-bit register. If we are building multiple resource descriptors, 10803 // this will allow CSEing of the 2-component register. 10804 const SDValue Ops0[] = { 10805 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 10806 buildSMovImm32(DAG, DL, 0), 10807 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10808 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 10809 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 10810 }; 10811 10812 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 10813 MVT::v2i32, Ops0), 0); 10814 10815 // Combine the constants and the pointer. 10816 const SDValue Ops1[] = { 10817 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10818 Ptr, 10819 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 10820 SubRegHi, 10821 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 10822 }; 10823 10824 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 10825 } 10826 10827 /// Return a resource descriptor with the 'Add TID' bit enabled 10828 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 10829 /// of the resource descriptor) to create an offset, which is added to 10830 /// the resource pointer. 10831 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 10832 SDValue Ptr, uint32_t RsrcDword1, 10833 uint64_t RsrcDword2And3) const { 10834 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 10835 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 10836 if (RsrcDword1) { 10837 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 10838 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 10839 0); 10840 } 10841 10842 SDValue DataLo = buildSMovImm32(DAG, DL, 10843 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 10844 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 10845 10846 const SDValue Ops[] = { 10847 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10848 PtrLo, 10849 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10850 PtrHi, 10851 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 10852 DataLo, 10853 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 10854 DataHi, 10855 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 10856 }; 10857 10858 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 10859 } 10860 10861 //===----------------------------------------------------------------------===// 10862 // SI Inline Assembly Support 10863 //===----------------------------------------------------------------------===// 10864 10865 std::pair<unsigned, const TargetRegisterClass *> 10866 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10867 StringRef Constraint, 10868 MVT VT) const { 10869 const TargetRegisterClass *RC = nullptr; 10870 if (Constraint.size() == 1) { 10871 const unsigned BitWidth = VT.getSizeInBits(); 10872 switch (Constraint[0]) { 10873 default: 10874 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10875 case 's': 10876 case 'r': 10877 switch (BitWidth) { 10878 case 16: 10879 RC = &AMDGPU::SReg_32RegClass; 10880 break; 10881 case 64: 10882 RC = &AMDGPU::SGPR_64RegClass; 10883 break; 10884 default: 10885 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 10886 if (!RC) 10887 return std::make_pair(0U, nullptr); 10888 break; 10889 } 10890 break; 10891 case 'v': 10892 switch (BitWidth) { 10893 case 16: 10894 RC = &AMDGPU::VGPR_32RegClass; 10895 break; 10896 default: 10897 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 10898 if (!RC) 10899 return std::make_pair(0U, nullptr); 10900 break; 10901 } 10902 break; 10903 case 'a': 10904 if (!Subtarget->hasMAIInsts()) 10905 break; 10906 switch (BitWidth) { 10907 case 16: 10908 RC = &AMDGPU::AGPR_32RegClass; 10909 break; 10910 default: 10911 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 10912 if (!RC) 10913 return std::make_pair(0U, nullptr); 10914 break; 10915 } 10916 break; 10917 } 10918 // We actually support i128, i16 and f16 as inline parameters 10919 // even if they are not reported as legal 10920 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 10921 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 10922 return std::make_pair(0U, RC); 10923 } 10924 10925 if (Constraint.size() > 1) { 10926 if (Constraint[1] == 'v') { 10927 RC = &AMDGPU::VGPR_32RegClass; 10928 } else if (Constraint[1] == 's') { 10929 RC = &AMDGPU::SGPR_32RegClass; 10930 } else if (Constraint[1] == 'a') { 10931 RC = &AMDGPU::AGPR_32RegClass; 10932 } 10933 10934 if (RC) { 10935 uint32_t Idx; 10936 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 10937 if (!Failed && Idx < RC->getNumRegs()) 10938 return std::make_pair(RC->getRegister(Idx), RC); 10939 } 10940 } 10941 10942 // FIXME: Returns VS_32 for physical SGPR constraints 10943 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10944 } 10945 10946 SITargetLowering::ConstraintType 10947 SITargetLowering::getConstraintType(StringRef Constraint) const { 10948 if (Constraint.size() == 1) { 10949 switch (Constraint[0]) { 10950 default: break; 10951 case 's': 10952 case 'v': 10953 case 'a': 10954 return C_RegisterClass; 10955 case 'A': 10956 return C_Other; 10957 } 10958 } 10959 return TargetLowering::getConstraintType(Constraint); 10960 } 10961 10962 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 10963 std::string &Constraint, 10964 std::vector<SDValue> &Ops, 10965 SelectionDAG &DAG) const { 10966 if (Constraint.length() == 1 && Constraint[0] == 'A') { 10967 LowerAsmOperandForConstraintA(Op, Ops, DAG); 10968 } else { 10969 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 10970 } 10971 } 10972 10973 void SITargetLowering::LowerAsmOperandForConstraintA(SDValue Op, 10974 std::vector<SDValue> &Ops, 10975 SelectionDAG &DAG) const { 10976 unsigned Size = Op.getScalarValueSizeInBits(); 10977 if (Size > 64) 10978 return; 10979 10980 uint64_t Val; 10981 bool IsConst = false; 10982 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 10983 Val = C->getSExtValue(); 10984 IsConst = true; 10985 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 10986 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 10987 IsConst = true; 10988 } else if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 10989 if (Size != 16 || Op.getNumOperands() != 2) 10990 return; 10991 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 10992 return; 10993 if (ConstantSDNode *C = V->getConstantSplatNode()) { 10994 Val = C->getSExtValue(); 10995 IsConst = true; 10996 } else if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 10997 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 10998 IsConst = true; 10999 } 11000 } 11001 11002 if (IsConst) { 11003 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11004 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11005 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11006 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11007 // Clear unused bits of fp constants 11008 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11009 unsigned UnusedBits = 64 - Size; 11010 Val = (Val << UnusedBits) >> UnusedBits; 11011 } 11012 auto Res = DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64); 11013 Ops.push_back(Res); 11014 } 11015 } 11016 } 11017 11018 // Figure out which registers should be reserved for stack access. Only after 11019 // the function is legalized do we know all of the non-spill stack objects or if 11020 // calls are present. 11021 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11022 MachineRegisterInfo &MRI = MF.getRegInfo(); 11023 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11024 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11025 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11026 11027 if (Info->isEntryFunction()) { 11028 // Callable functions have fixed registers used for stack access. 11029 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11030 } 11031 11032 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11033 Info->getStackPtrOffsetReg())); 11034 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11035 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11036 11037 // We need to worry about replacing the default register with itself in case 11038 // of MIR testcases missing the MFI. 11039 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11040 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11041 11042 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11043 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11044 11045 Info->limitOccupancy(MF); 11046 11047 if (ST.isWave32() && !MF.empty()) { 11048 // Add VCC_HI def because many instructions marked as imp-use VCC where 11049 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 11050 // having a use of undef. 11051 11052 const SIInstrInfo *TII = ST.getInstrInfo(); 11053 DebugLoc DL; 11054 11055 MachineBasicBlock &MBB = MF.front(); 11056 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 11057 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 11058 11059 for (auto &MBB : MF) { 11060 for (auto &MI : MBB) { 11061 TII->fixImplicitOperands(MI); 11062 } 11063 } 11064 } 11065 11066 TargetLoweringBase::finalizeLowering(MF); 11067 11068 // Allocate a VGPR for future SGPR Spill if 11069 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11070 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11071 if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill && 11072 !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects()) 11073 Info->reserveVGPRforSGPRSpills(MF); 11074 } 11075 11076 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 11077 KnownBits &Known, 11078 const APInt &DemandedElts, 11079 const SelectionDAG &DAG, 11080 unsigned Depth) const { 11081 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 11082 DAG, Depth); 11083 11084 // Set the high bits to zero based on the maximum allowed scratch size per 11085 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11086 // calculation won't overflow, so assume the sign bit is never set. 11087 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11088 } 11089 11090 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11091 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11092 const Align CacheLineAlign = Align(64); 11093 11094 // Pre-GFX10 target did not benefit from loop alignment 11095 if (!ML || DisableLoopAlignment || 11096 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11097 getSubtarget()->hasInstFwdPrefetchBug()) 11098 return PrefAlign; 11099 11100 // On GFX10 I$ is 4 x 64 bytes cache lines. 11101 // By default prefetcher keeps one cache line behind and reads two ahead. 11102 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11103 // behind and one ahead. 11104 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11105 // If loop fits 64 bytes it always spans no more than two cache lines and 11106 // does not need an alignment. 11107 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11108 // Else if loop is less or equal 192 bytes we need two lines behind. 11109 11110 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11111 const MachineBasicBlock *Header = ML->getHeader(); 11112 if (Header->getAlignment() != PrefAlign) 11113 return Header->getAlignment(); // Already processed. 11114 11115 unsigned LoopSize = 0; 11116 for (const MachineBasicBlock *MBB : ML->blocks()) { 11117 // If inner loop block is aligned assume in average half of the alignment 11118 // size to be added as nops. 11119 if (MBB != Header) 11120 LoopSize += MBB->getAlignment().value() / 2; 11121 11122 for (const MachineInstr &MI : *MBB) { 11123 LoopSize += TII->getInstSizeInBytes(MI); 11124 if (LoopSize > 192) 11125 return PrefAlign; 11126 } 11127 } 11128 11129 if (LoopSize <= 64) 11130 return PrefAlign; 11131 11132 if (LoopSize <= 128) 11133 return CacheLineAlign; 11134 11135 // If any of parent loops is surrounded by prefetch instructions do not 11136 // insert new for inner loop, which would reset parent's settings. 11137 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11138 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11139 auto I = Exit->getFirstNonDebugInstr(); 11140 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11141 return CacheLineAlign; 11142 } 11143 } 11144 11145 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11146 MachineBasicBlock *Exit = ML->getExitBlock(); 11147 11148 if (Pre && Exit) { 11149 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11150 TII->get(AMDGPU::S_INST_PREFETCH)) 11151 .addImm(1); // prefetch 2 lines behind PC 11152 11153 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11154 TII->get(AMDGPU::S_INST_PREFETCH)) 11155 .addImm(2); // prefetch 1 line behind PC 11156 } 11157 11158 return CacheLineAlign; 11159 } 11160 11161 LLVM_ATTRIBUTE_UNUSED 11162 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11163 assert(N->getOpcode() == ISD::CopyFromReg); 11164 do { 11165 // Follow the chain until we find an INLINEASM node. 11166 N = N->getOperand(0).getNode(); 11167 if (N->getOpcode() == ISD::INLINEASM || 11168 N->getOpcode() == ISD::INLINEASM_BR) 11169 return true; 11170 } while (N->getOpcode() == ISD::CopyFromReg); 11171 return false; 11172 } 11173 11174 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 11175 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 11176 { 11177 switch (N->getOpcode()) { 11178 case ISD::CopyFromReg: 11179 { 11180 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11181 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11182 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11183 Register Reg = R->getReg(); 11184 11185 // FIXME: Why does this need to consider isLiveIn? 11186 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11187 return !TRI->isSGPRReg(MRI, Reg); 11188 11189 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11190 return KDA->isDivergent(V); 11191 11192 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11193 return !TRI->isSGPRReg(MRI, Reg); 11194 } 11195 break; 11196 case ISD::LOAD: { 11197 const LoadSDNode *L = cast<LoadSDNode>(N); 11198 unsigned AS = L->getAddressSpace(); 11199 // A flat load may access private memory. 11200 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11201 } break; 11202 case ISD::CALLSEQ_END: 11203 return true; 11204 break; 11205 case ISD::INTRINSIC_WO_CHAIN: 11206 { 11207 11208 } 11209 return AMDGPU::isIntrinsicSourceOfDivergence( 11210 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11211 case ISD::INTRINSIC_W_CHAIN: 11212 return AMDGPU::isIntrinsicSourceOfDivergence( 11213 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11214 } 11215 return false; 11216 } 11217 11218 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11219 EVT VT) const { 11220 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11221 case MVT::f32: 11222 return hasFP32Denormals(DAG.getMachineFunction()); 11223 case MVT::f64: 11224 case MVT::f16: 11225 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11226 default: 11227 return false; 11228 } 11229 } 11230 11231 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11232 const SelectionDAG &DAG, 11233 bool SNaN, 11234 unsigned Depth) const { 11235 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11236 const MachineFunction &MF = DAG.getMachineFunction(); 11237 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11238 11239 if (Info->getMode().DX10Clamp) 11240 return true; // Clamped to 0. 11241 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11242 } 11243 11244 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11245 SNaN, Depth); 11246 } 11247 11248 TargetLowering::AtomicExpansionKind 11249 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11250 switch (RMW->getOperation()) { 11251 case AtomicRMWInst::FAdd: { 11252 Type *Ty = RMW->getType(); 11253 11254 // We don't have a way to support 16-bit atomics now, so just leave them 11255 // as-is. 11256 if (Ty->isHalfTy()) 11257 return AtomicExpansionKind::None; 11258 11259 if (!Ty->isFloatTy()) 11260 return AtomicExpansionKind::CmpXChg; 11261 11262 // TODO: Do have these for flat. Older targets also had them for buffers. 11263 unsigned AS = RMW->getPointerAddressSpace(); 11264 11265 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11266 return RMW->use_empty() ? AtomicExpansionKind::None : 11267 AtomicExpansionKind::CmpXChg; 11268 } 11269 11270 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11271 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11272 } 11273 default: 11274 break; 11275 } 11276 11277 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11278 } 11279 11280 const TargetRegisterClass * 11281 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11282 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11283 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11284 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11285 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11286 : &AMDGPU::SReg_32RegClass; 11287 if (!TRI->isSGPRClass(RC) && !isDivergent) 11288 return TRI->getEquivalentSGPRClass(RC); 11289 else if (TRI->isSGPRClass(RC) && isDivergent) 11290 return TRI->getEquivalentVGPRClass(RC); 11291 11292 return RC; 11293 } 11294 11295 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11296 // uniform values (as produced by the mask results of control flow intrinsics) 11297 // used outside of divergent blocks. The phi users need to also be treated as 11298 // always uniform. 11299 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11300 unsigned WaveSize) { 11301 // FIXME: We asssume we never cast the mask results of a control flow 11302 // intrinsic. 11303 // Early exit if the type won't be consistent as a compile time hack. 11304 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11305 if (!IT || IT->getBitWidth() != WaveSize) 11306 return false; 11307 11308 if (!isa<Instruction>(V)) 11309 return false; 11310 if (!Visited.insert(V).second) 11311 return false; 11312 bool Result = false; 11313 for (auto U : V->users()) { 11314 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11315 if (V == U->getOperand(1)) { 11316 switch (Intrinsic->getIntrinsicID()) { 11317 default: 11318 Result = false; 11319 break; 11320 case Intrinsic::amdgcn_if_break: 11321 case Intrinsic::amdgcn_if: 11322 case Intrinsic::amdgcn_else: 11323 Result = true; 11324 break; 11325 } 11326 } 11327 if (V == U->getOperand(0)) { 11328 switch (Intrinsic->getIntrinsicID()) { 11329 default: 11330 Result = false; 11331 break; 11332 case Intrinsic::amdgcn_end_cf: 11333 case Intrinsic::amdgcn_loop: 11334 Result = true; 11335 break; 11336 } 11337 } 11338 } else { 11339 Result = hasCFUser(U, Visited, WaveSize); 11340 } 11341 if (Result) 11342 break; 11343 } 11344 return Result; 11345 } 11346 11347 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11348 const Value *V) const { 11349 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11350 if (CI->isInlineAsm()) { 11351 // FIXME: This cannot give a correct answer. This should only trigger in 11352 // the case where inline asm returns mixed SGPR and VGPR results, used 11353 // outside the defining block. We don't have a specific result to 11354 // consider, so this assumes if any value is SGPR, the overall register 11355 // also needs to be SGPR. 11356 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11357 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11358 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11359 for (auto &TC : TargetConstraints) { 11360 if (TC.Type == InlineAsm::isOutput) { 11361 ComputeConstraintToUse(TC, SDValue()); 11362 unsigned AssignedReg; 11363 const TargetRegisterClass *RC; 11364 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11365 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11366 if (RC) { 11367 MachineRegisterInfo &MRI = MF.getRegInfo(); 11368 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11369 return true; 11370 else if (SIRI->isSGPRClass(RC)) 11371 return true; 11372 } 11373 } 11374 } 11375 } 11376 } 11377 SmallPtrSet<const Value *, 16> Visited; 11378 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11379 } 11380